code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
############################################################################
# Copyright (c) 2010 Robotnik Automation, SLL #
# Makefile for standard Robotnik component #
############################################################################
BUILD = ./build/
BINDIR = ./bin/
SRC = ./src/
LIB = ./lib/
#LIBS = -L$(LIB) -lpthread -lremotelog -lcurses -lrt
INC = ./include/SerialDevice
CPP = g++
CCFLAGS = -Wall -c -g3 -I$(INC)
# -g3 -Wno-deprecated -Wall
OBJECTS = \
$(BUILD)SerialDevice.o \
default: $(BINDIR)$(EXE)
all: $(BINDIR)$(EXE)
$(BUILD)SerialDevice.o : $(SRC)SerialDevice.cc
$(CPP) $(CCFLAGS) -o $(BUILD)SerialDevice.o $(SRC)SerialDevice.cc
#$(BINDIR)$(EXE) : $(OBJECTS)
# $(CPP) -I$(INC) -o $(BINDIR)$(EXE) $(OBJECTS) $(LIBS)
clean:
rm -fv $(BUILD)*.o
rm -fv $(BINDIR)$(EXE)
| clearpathrobotics/s3000_laser | external/SerialDevice/Makefile | Makefile | gpl-3.0 | 845 |
#ifndef MANTID_CURVEFITTING_SEQDOMAIN_H_
#define MANTID_CURVEFITTING_SEQDOMAIN_H_
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidCurveFitting/DllConfig.h"
#include "MantidAPI/FunctionDomain.h"
#include "MantidAPI/FunctionValues.h"
#include "MantidAPI/IDomainCreator.h"
#include "MantidCurveFitting/CostFunctions/CostFuncLeastSquares.h"
#include "MantidCurveFitting/CostFunctions/CostFuncRwp.h"
#include <stdexcept>
#include <vector>
#include <algorithm>
namespace Mantid {
namespace CurveFitting {
/** An implementation of CompositeDomain.
@author Roman Tolchenov, Tessella plc
@date 15/11/2011
Copyright © 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge
National Laboratory & European Spallation Source
This file is part of Mantid.
Mantid 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.
Mantid 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/>.
File change history is stored at: <https://github.com/mantidproject/mantid>.
Code Documentation is available at: <http://doxygen.mantidproject.org>
*/
class MANTID_CURVEFITTING_DLL SeqDomain : public API::FunctionDomain {
public:
SeqDomain() : API::FunctionDomain(), m_currentIndex(0) {}
/// Return the number of points in the domain
size_t size() const override;
/// Return the number of parts in the domain
virtual size_t getNDomains() const;
/// Create and return i-th domain and i-th values, (i-1)th domain is released.
virtual void getDomainAndValues(size_t i, API::FunctionDomain_sptr &domain,
API::FunctionValues_sptr &values) const;
/// Add new domain creator
void addCreator(API::IDomainCreator_sptr creator);
/// Calculate the value of a least squares cost function
virtual void
leastSquaresVal(const CostFunctions::CostFuncLeastSquares &leastSquares);
/// Calculate the value, first and second derivatives of a least squares cost
/// function
virtual void leastSquaresValDerivHessian(
const CostFunctions::CostFuncLeastSquares &leastSquares, bool evalDeriv,
bool evalHessian);
/// Calculate the value of a Rwp cost function
void rwpVal(const CostFunctions::CostFuncRwp &rwp);
/// Calculate the value, first and second derivatives of a RWP cost function
void rwpValDerivHessian(const CostFunctions::CostFuncRwp &rwp, bool evalDeriv,
bool evalHessian);
/// Create an instance of SeqDomain in one of two forms: either SeqDomain for
/// sequential domain creation
/// or ParDomain for parallel calculations
static SeqDomain *create(API::IDomainCreator::DomainType type);
protected:
/// Current index
mutable size_t m_currentIndex;
/// Currently active domain.
mutable std::vector<API::FunctionDomain_sptr> m_domain;
/// Currently active values.
mutable std::vector<API::FunctionValues_sptr> m_values;
/// Domain creators.
std::vector<boost::shared_ptr<API::IDomainCreator>> m_creators;
};
} // namespace CurveFitting
} // namespace Mantid
#endif /*MANTID_CURVEFITTING_SEQDOMAIN_H_*/
| dymkowsk/mantid | Framework/CurveFitting/inc/MantidCurveFitting/SeqDomain.h | C | gpl-3.0 | 3,677 |
/* XGGState - Implements graphic state drawing for Xlib
Copyright (C) 1995 Free Software Foundation, Inc.
Written by: Adam Fedor <fedor@boulder.colorado.edu>
Date: Nov 1995
This file is part of the GNU Objective C User Interface Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; see the file COPYING.LIB.
If not, see <http://www.gnu.org/licenses/> or write to the
Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef _XGGState_h_INCLUDE
#define _XGGState_h_INCLUDE
#include <Foundation/NSArray.h>
#include <Foundation/NSObject.h>
#include "gsc/GSGState.h"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "x11/XGServer.h"
#ifdef HAVE_XFT
#define id xwindowsid
#include <X11/Xft/Xft.h>
#undef id
#endif
@class NSBezierPath;
@class NSFont;
@interface XGGState : GSGState
{
@public
void *context;
void *windevice;
XGDrawMechanism drawMechanism;
GC xgcntxt;
GC agcntxt;
XGCValues gcv;
Drawable draw;
Drawable alpha_buffer;
Region clipregion;
#ifdef HAVE_XFT
XftDraw *xft_draw;
XftDraw *xft_alpha_draw;
XftColor xft_color;
#endif
BOOL drawingAlpha;
BOOL sharedGC; /* Do we own the GC or share it? */
}
- (void) setWindowDevice: (void *)device;
- (void) setGraphicContext: (GC)xGraphicContext;
- (void) setGCValues: (XGCValues)values withMask: (int)mask;
- (void) setClipMask;
- (Region) xClipRegion;
- (BOOL) hasDrawable;
- (BOOL) hasGraphicContext;
- (void *) windevice;
- (Drawable) drawable;
- (GC) graphicContext;
- (NSRect) clipRect;
#ifdef HAVE_XFT
- (XftDraw *)xftDrawForDrawable: (Drawable)d;
- (XftColor)xftColor;
#endif
- (XPoint) viewPointToX: (NSPoint)aPoint;
- (XRectangle) viewRectToX: (NSRect)aRect;
- (XPoint) windowPointToX: (NSPoint)aPoint;
- (XRectangle) windowRectToX: (NSRect)aRect;
@end
@interface XGGState (Ops)
- (NSDictionary *) GSReadRect: (NSRect)rect;
@end
#endif /* _XGGState_h_INCLUDE */
| gnustep/back | Headers/xlib/XGGState.h | C | gpl-3.0 | 2,536 |
#!/usr/bin/env python3
#
# Copyright (C) 2018-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo 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.
#
# ESPResSo 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/>.
import os
if not os.environ.get('CI_COMMIT_REF_NAME', '').startswith('PR-'):
print("Not a pull request. Exiting now.")
exit(0)
import subprocess
import gh_post
SIZELIMIT = 10000
TOKEN_ESPRESSO_CI = 'style.patch'
# Delete obsolete posts
gh_post.delete_comments_by_token(TOKEN_ESPRESSO_CI)
MESSAGE = '''Your pull request does not meet our code formatting \
rules. {header}, please do one of the following:
- You can download a patch with my suggested changes \
[here]({url}/artifacts/raw/style.patch), inspect it and make \
changes manually.
- You can directly apply it to your repository by running \
`curl {url}/artifacts/raw/style.patch | git apply -`.
- You can run `maintainer/CI/fix_style.sh` to automatically fix your coding \
style. This is the same command that I have executed to generate the patch \
above, but it requires certain tools to be installed on your computer.
You can run `gitlab-runner exec docker style` afterwards to check if your \
changes worked out properly.
Please note that there are often multiple ways to correctly format code. \
As I am just a robot, I sometimes fail to identify the most aesthetically \
pleasing way. So please look over my suggested changes and adapt them \
where the style does not make sense.\
'''
# If the working directory is not clean, post a new comment
if subprocess.call(["git", "diff-index", "--quiet", "HEAD", "--"]) != 0:
patch = subprocess.check_output(['git', '--no-pager', 'diff'])
if len(patch) <= SIZELIMIT:
comment = 'Specifically, I suggest you make the following changes:'
comment += '\n```diff\n'
comment += patch.decode('utf-8').replace('`', r'\`').strip()
comment += '\n```\n'
comment += 'To apply these changes'
else:
comment = 'To fix this'
comment = MESSAGE.format(header=comment, url=gh_post.CI_JOB_URL)
if patch:
assert TOKEN_ESPRESSO_CI in comment
gh_post.post_message(comment)
| espressomd/espresso | maintainer/gh_post_style_patch.py | Python | gpl-3.0 | 2,704 |
/*
Drawpile - a collaborative drawing program.
Copyright (C) 2014-2019 Calle Laakkonen
Drawpile 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.
Drawpile 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 Drawpile. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "stats.h"
#include "../libshared/record/reader.h"
#include "../libshared/record/writer.h"
#include "../libclient/canvas/aclfilter.h"
#include <QCoreApplication>
#include <QStringList>
#include <QScopedPointer>
#include <QRegularExpression>
#include <QCommandLineParser>
#include <QTextStream>
#include <QFile>
using namespace recording;
void printVersion()
{
printf("dprectool " DRAWPILE_VERSION "\n");
printf("Protocol version: %s\n", qPrintable(protocol::ProtocolVersion::current().asString()));
printf("Qt version: %s (compiled against %s)\n", qVersion(), QT_VERSION_STR);
}
bool convertRecording(const QString &inputfilename, const QString &outputfilename, const QString &outputFormat, bool doAclFiltering)
{
// Open input file
Reader reader(inputfilename);
Compatibility compat = reader.open();
switch(compat) {
case INCOMPATIBLE:
fprintf(
stderr,
"This recording is incompatible (format version %s). It was made with Drawpile version %s.\n",
qPrintable(reader.formatVersion().asString()),
qPrintable(reader.writerVersion())
);
return false;
case NOT_DPREC:
fprintf(stderr, "Input file is not a Drawpile recording!\n");
return false;
case CANNOT_READ:
fprintf(stderr, "Unable to read input file: %s\n", qPrintable(reader.errorString()));
return false;
case COMPATIBLE:
case MINOR_INCOMPATIBILITY:
case UNKNOWN_COMPATIBILITY:
// OK to proceed
break;
}
// Open output file (stdout if no filename given)
QScopedPointer<Writer> writer;
if(outputfilename.isEmpty()) {
// No output filename given? Write to stdout
QFile *out = new QFile();
out->open(stdout, QFile::WriteOnly);
writer.reset(new Writer(out));
out->setParent(writer.data());
writer->setEncoding(Writer::Encoding::Text);
} else {
writer.reset(new Writer(outputfilename));
}
// Output format override
if(outputFormat == "text")
writer->setEncoding(Writer::Encoding::Text);
else if(outputFormat == "binary")
writer->setEncoding(Writer::Encoding::Binary);
else if(!outputFormat.isEmpty()) {
fprintf(stderr, "Invalid output format: %s\n", qPrintable(outputFormat));
return false;
}
// Open output file
if(!writer->open()) {
fprintf(stderr, "Couldn't open %s: %s\n",
qPrintable(outputfilename),
qPrintable(writer->errorString())
);
return false;
}
if(!writer->writeHeader(reader.metadata())) {
fprintf(stderr, "Error while writing header: %s\n",
qPrintable(writer->errorString())
);
return false;
}
// Prepare filters
canvas::AclFilter aclFilter;
aclFilter.reset(1, false);
// Convert and/or filter recording
bool notEof = true;
do {
MessageRecord mr = reader.readNext();
switch(mr.status) {
case MessageRecord::OK: {
if(doAclFiltering && !aclFilter.filterMessage(*mr.message)) {
writer->writeMessage(*mr.message->asFiltered());
} else {
if(!writer->writeMessage(*mr.message)) {
fprintf(stderr, "Error while writing message: %s\n",
qPrintable(writer->errorString())
);
return false;
}
}
break;
}
case MessageRecord::INVALID:
writer->writeComment(QStringLiteral("WARNING: Unrecognized message type %1 of length %2 at offset 0x%3")
.arg(int(mr.invalid_type))
.arg(mr.invalid_len)
.arg(reader.currentPosition())
);
break;
case MessageRecord::END_OF_RECORDING:
notEof = false;
break;
}
} while(notEof);
return true;
}
/**
* Print the version number of this recording. The output can be parsed easily in a shell script.
* Output format: <compatibility flag> <protocol version> <client version string>
* Example: C dp:4.20.1 2.0.5
* Compatability flag is one of:
* - C: fully compatible with this dprectool/drawpile-cmd version
* - M: minor incompatibility (might render differently)
* - U: unknown compatibility (made with a newer version: some features may be missing)
* - I: known to be incompatible
*/
bool printRecordingVersion(const QString &inputFilename)
{
Reader reader(inputFilename);
const Compatibility compat = reader.open();
char compatflag = '?';
switch(compat) {
case COMPATIBLE: compatflag = 'C'; break;
case MINOR_INCOMPATIBILITY: compatflag = 'M'; break;
case UNKNOWN_COMPATIBILITY: compatflag = 'U'; break;
case INCOMPATIBLE: compatflag = 'I'; break;
case NOT_DPREC:
fprintf(stderr, "Not a drawpile recording!\n");
return false;
case CANNOT_READ:
fprintf(stderr, "Cannot read file: %s", qPrintable(reader.errorString()));
return false;
}
printf("%c %s %s\n",
compatflag,
qPrintable(reader.formatVersion().asString()),
reader.writerVersion().isEmpty() ? "(no writer version)" : qPrintable(reader.writerVersion())
);
return true;
}
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QCoreApplication::setOrganizationName("drawpile");
QCoreApplication::setOrganizationDomain("drawpile.net");
QCoreApplication::setApplicationName("dprectool");
QCoreApplication::setApplicationVersion(DRAWPILE_VERSION);
// Set up command line arguments
QCommandLineParser parser;
parser.setApplicationDescription("Convert Drawpile recordings between text and binary formats");
parser.addHelpOption();
// --version, -v
QCommandLineOption versionOption(QStringList() << "v" << "version", "Displays version information.");
parser.addOption(versionOption);
// --out, -o
QCommandLineOption outOption(QStringList() << "o" << "out", "Output file", "output");
parser.addOption(outOption);
// --format, -f
QCommandLineOption formatOption(QStringList() << "f" << "format", "Output format (binary/text/version)", "format");
parser.addOption(formatOption);
// --acl, -A
QCommandLineOption aclOption(QStringList() << "A" << "acl", "Perform ACL filtering");
parser.addOption(aclOption);
// --msg-freq
QCommandLineOption msgFreqOption(QStringList() << "msg-freq", "Print message frequency table");
parser.addOption(msgFreqOption);
// input file name
parser.addPositionalArgument("input", "recording file", "<input.dprec>");
// Parse
parser.process(app);
if(parser.isSet(versionOption)) {
printVersion();
return 0;
}
const QStringList inputfiles = parser.positionalArguments();
if(inputfiles.isEmpty()) {
parser.showHelp(1);
return 1;
}
const QString format = parser.value(formatOption);
if(format == "version") {
return !printRecordingVersion(inputfiles.at(0));
}
if(parser.isSet(msgFreqOption)) {
return printMessageFrequency(inputfiles.at(0)) ? 0 : 1;
}
if(!convertRecording(
inputfiles.at(0),
parser.value(outOption),
parser.value(formatOption),
parser.isSet(aclOption)
))
return 1;
return 0;
}
| drawpile/Drawpile | src/tools/dprectool.cpp | C++ | gpl-3.0 | 7,369 |
var classgr__interleave =
[
[ "~gr_interleave", "classgr__interleave.html#ae342ba63322b78359ee71de113e41fc1", null ],
[ "check_topology", "classgr__interleave.html#ade74f196c0fc8a91ca4f853a2d1202e1", null ],
[ "work", "classgr__interleave.html#a44664518c86559da58b3feccb9e45d7f", null ],
[ "gr_make_interleave", "classgr__interleave.html#acf7153a343a7bfbf2687bcc4c98d410e", null ]
]; | aviralchandra/Sandhi | build/gr36/docs/doxygen/html/classgr__interleave.js | JavaScript | gpl-3.0 | 399 |
(function(jQuery){jQuery.fn.addLittleSisToolbar=function(){var defaults={z_index:10002,height:180,width:100,background_color:'#FFF'};return this.each(function(){if(jQuery('#littlesis-toolbar').length==0){var elements=jQuery(this);elements.css({'margin-top':(defaults.height+10)+'px'});var wrapper=jQuery('<div id="littlesis-toolbar"/>').appendTo(elements).css({'display':'block','position':'fixed','background-color':defaults.background_color,'top':0,'z-index':(defaults.z_index-1),'height':defaults.height+'px','width':defaults.width+'%'});jQuery('#littlesis-toolbar').append('<iframe id="littlesis-toolbar-iframe" src="https://littlesis.org/relationship/toolbar?title='+escape(document.title)+'&url='+escape(document.URL)+'">No Support</iframe>');jQuery('#littlesis-toolbar-iframe').css({'width':defaults.width+'%','height':defaults.height+'px','border':0,'border-bottom':'3px solid #ccc'})}})}})(jQuery);
| public-accountability/littlesis-docker | static/js/bookmarklet.js | JavaScript | gpl-3.0 | 908 |
! This file is F-compatible, except for upper/lower case conventions.
!--------------------------------------------------------------------
Module CubatureRule_C2
USE Precision_Model, ONLY: stnd
Implicit NONE
PRIVATE
PUBLIC :: Rule_C2a
CONTAINS
SUBROUTINE Rule_C2a(VER,INFOLD,AREA,NUMFUN,Integrand,BASVAL,RGNERR,NUM)
!
!***BEGIN PROLOGUE Rule_C2a
!***PURPOSE To compute basic integration rule values and
! corresponding error estimates.
! ***REVISION DATE 950531 (YYMMDD) (Fortran90 transformation)
! ***REVISION DATE 990527 (YYMMDD) (F transformation)
! ***AUTHOR
! Ronald Cools, Dept. of Computer Science,
! Katholieke Universiteit Leuven, Celestijnenlaan 200A,
! B-3001 Heverlee, Belgium
! Email: ronald@cs.kuleuven.ac.be
!
! ***REFERENCES
! The cubature formula of degree 13 with 37 points is from
! Rabinowitz & Richter. The tuning of the error estimator
! is described in:
! R. Cools.
! "The subdivision strategy and reliablity in adaptive
! integration revisited."
! Report TW 213, Dept. of Computer Science, K.U.Leuven, 1994.
!
!***DESCRIPTION Rule_C2a computes basic integration rule values
! for a vector of integrands over a rectangular region.
! Rule_C2a also computes estimates for the errors by
! using several null rule approximations.
! ON ENTRY
!
! VER Real array of dimension (2,3).
! The coordinates of the vertices of the parallellogram.
! NUMFUN Integer.
! Number of components of the vector integrand.
! INFOLD Integer array
! Integrand Externally declared subroutine for computing
! all components of the integrand at the given
! evaluation point.
! It must have parameters (DIM,X,NUMFUN,FUNVLS)
! Input parameters:
! DIM = 2
! X(1) The x-coordinate of the evaluation point.
! X(2) The y-coordinate of the evaluation point.
! NUMFUN Integer that defines the number of
! components of I.
! Output parameter:
! FUNVLS Real array of dimension NUMFUN
! that defines NUMFUN components of the integrand.
!
! ON RETURN
!
! BASVAL Real array of dimension NUMFUN.
! The values for the basic rule for each component
! of the integrand.
! RGNERR Real array of dimension NUMFUN.
! The error estimates for each component of the integrand.
! NUM Integer
! The number of function evaluations used.
! INFOLD Integer array
!
!***ROUTINES CALLED Integrand
!***END PROLOGUE Rule_C2a
!
! Global variables.
!
INTERFACE
FUNCTION Integrand(NUMFUN,X) RESULT(Value)
USE Precision_Model
INTEGER, INTENT(IN) :: NUMFUN
REAL(kind=stnd), DIMENSION(:), INTENT(IN) :: X
REAL(kind=stnd), DIMENSION(NUMFUN) :: Value
END FUNCTION Integrand
END INTERFACE
INTEGER, INTENT(IN) :: NUMFUN
INTEGER, INTENT(OUT) :: NUM
INTEGER, DIMENSION(:), INTENT(IN OUT) :: INFOLD
REAL(kind=stnd), INTENT(IN) :: AREA
REAL(kind=stnd), DIMENSION(:,:), INTENT(IN) :: VER
REAL(kind=stnd), DIMENSION(:), INTENT(OUT) :: BASVAL, RGNERR
!
! Parameters
!
INTEGER, DIMENSION(0:3), PARAMETER :: &
K = (/1,2,3,2/) ! Rule structure parameters
INTEGER, PARAMETER :: &
ORBITS = 8 ! Number of orbits in rule
REAL(kind=stnd), PARAMETER :: &
HALF = 0.5_stnd, &
FOUR = 4.0_stnd, &
CRIVAL = 0.4_stnd, &
FACMED = 8.0_stnd, &
FACOPT = FACMED/CRIVAL**2, &
TRES = 50*EPSILON(HALF), &
CUTOFF = 1.0E-4_stnd , &
DFCLEV = 0.55_stnd
REAL(kind=stnd), DIMENSION(0:2), PARAMETER :: &
DFC = (/2.97397430397053625382_stnd, &
1.0_stnd, &
-2.48698715198526812691_stnd /)
!
! Cubature formula of degree 13 with 37 points (Rabinowitz & Richter)
!
!
! Information for the generators
!
INTEGER :: I
REAL(kind=stnd), DIMENSION(1:2), PARAMETER :: &
TYPE1 = (/ 0.9909890363004326469792722978603_stnd, &
0.6283940712305315063814483471116_stnd /)
REAL(kind=stnd), DIMENSION(1:3), PARAMETER :: &
TYPE2 = (/ 0.9194861553393073086142137772149_stnd, &
0.6973201917871173078084506730937_stnd, &
0.3805687186904854497424188074662_stnd /)
REAL(kind=stnd), DIMENSION(1:2,1:2), PARAMETER :: &
TYPE3 = RESHAPE( SOURCE= &
(/ 0.9708504361720225062147290554088_stnd, &
0.6390348393207252159077623446225_stnd, &
0.8623637916722781475018696425693_stnd, &
0.3162277660168700033875075593701_stnd /),&
SHAPE=(/2,2/) )
! The weights of the basic rule and the null rules.
! WEIGHT(1,1),...,WEIGHT(1,ORBITS) are weights for the basic rule.
! WEIGHT(I,1),...,WEIGHT(I,ORBITS) for I>1 are null rule weights.
!
!
! Weights of the cubature formula.
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W1 = (/ &
2.995235559387052215463143056692E-1_stnd , &
3.311006686692356205977471655046E-2_stnd , &
1.802214941550624038355347399683E-1_stnd , &
3.916727896035153300761243260674E-2_stnd , &
1.387748348777288706306435595057E-1_stnd , &
2.268881207335707037147066705814E-1_stnd , &
3.657395765508995601240002438981E-2_stnd , &
1.169047000557533546701746277951E-1_stnd /)
!
! Weights of the rules of degree 7, 7, 5 , 5 , 3 , 3 and 1.
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W2 = (/ &
7.610781847149629154716409791983E-2_stnd , &
1.486101247399760261471935168346E-1_stnd , &
-2.077685631717747007172983323970E-1_stnd , &
6.850758313011924198538315395405E-2_stnd , &
2.024205813317813585572881715385E-1_stnd , &
1.108627473745508429879249169864E-1_stnd , &
-1.187411393304862640859204217487E-1_stnd , &
-5.208857468077715683772080394959E-2_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W3 = (/ &
4.016494861405949747097510013162E-2_stnd , &
-1.093132962444079541048635452881E-1_stnd , &
-2.270251673633777452624380129694E-1_stnd , &
1.231674163356097016086203579325E-2_stnd , &
-1.420402526499201540699111172200E-1_stnd , &
1.189080551229557928776504129312E-1_stnd , &
-4.482039658150474743804189300793E-3_stnd , &
1.730383808319875827592824151609E-1_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W4 = (/ &
-5.643905795781771973971259866415E-1_stnd , &
2.878418073676293225652331648545E-2_stnd , &
1.159354231997583294689565314470E-1_stnd , &
1.376081498690624477894043101438E-1_stnd , &
-7.909780225340130915490382973570E-2_stnd , &
1.174335441429478112778176601234E-1_stnd , &
-1.107251942334134124782600707843E-1_stnd , &
2.094226883312045633400182488252E-2_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W5 = (/ &
-2.269001713589584730602581694579E-1_stnd , &
2.976190892690301120078774620049E-2_stnd , &
-7.440193483272787588251423144751E-2_stnd , &
-1.224665989043784131260454301280E-1_stnd , &
-4.857910454732976198562745578156E-2_stnd , &
2.228157325962656425537280474671E-1_stnd , &
1.459764751457503859063666414952E-1_stnd , &
-1.211789553452468781539987084682E-1_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W6 = (/ &
-3.326760468009974589269134283992E-1_stnd , &
1.796655319904795478676993902115E-1_stnd , &
-4.389976396805911868560791966472E-2_stnd , &
-2.295841771339316497310760908889E-1_stnd , &
6.182618387692816082856552878852E-2_stnd , &
-1.202703885325137746461829140891E-1_stnd , &
5.109536580363550180208564374234E-3_stnd , &
1.126062761533095493689566169969E-1_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W7 = (/ &
2.290638530086106512999345512401E-1_stnd , &
2.702070398116919449911037051753E-1_stnd , &
-9.078047988731123605988441792069E-3_stnd , &
4.618480310858703283999169489655E-2_stnd , &
-2.598231009547631799096616255056E-1_stnd , &
-2.518433931146441037986247681820E-2_stnd , &
-1.257796993152456033984707367389E-2_stnd , &
-2.720818902721190304043617320910E-2_stnd /)
!
REAL(kind=stnd), DIMENSION(ORBITS), PARAMETER :: &
W8 = (/ &
2.746908885094872977794932213372E-1_stnd , &
-1.149427039769738298032807785523E-2_stnd , &
1.596178537820019535731955591283E-1_stnd , &
-2.180626972663360443142752377527E-1_stnd , &
-8.711748038292630173597899697063E-3_stnd , &
1.902786182960269617633915869710E-1_stnd , &
-1.189840649092108827784089292890E-1_stnd , &
2.883382565767354162177931122471E-2_stnd /)
REAL(kind=stnd), DIMENSION(1:8,1:ORBITS), PARAMETER :: &
WEIGHT = RESHAPE( SOURCE= (/ W1,W2,W3,W4,W5,W6,W7,W8 /),&
SHAPE=(/8,ORBITS/), ORDER=(/2,1/) )
!
! Local variables.
!
INTEGER :: J,NUMBER,GENTYPE,NR,P
REAL(kind=stnd):: R1,R2,R3,R,NOISE,DEG7,DEG5,DEG3,DEG1, &
DIFFX,DIFFY,Z1,Z2
REAL(kind=stnd), DIMENSION(2,8) :: X
REAL(kind=stnd), DIMENSION(NUMFUN,7) :: NullRule
REAL(kind=stnd), DIMENSION(NUMFUN) :: SUMVAL
!
!***FIRST EXECUTABLE STATEMENT Rule_C2a
!
! The number of points used by the cubature formula is
! NUM = K(0) + 4*K(1) + 4*K(2) + 8*K(3)
NUM = 37
!
!
! Initialise BASVAL and NullRule
!
BASVAL = 0
NullRule = 0
P = 1
!
! Compute contributions from orbits with 1, 4 and 8 points
!
DO GENTYPE = 0,3
DO NR = 1,K(GENTYPE)
SELECT CASE (GENTYPE)
CASE (0) ! Generator ( 0 , 0 )
NUMBER = 1
X(:,1) = (VER(:,2)+VER(:,3))*HALF
CASE (1) ! Generator ( z1 , 0 )
Z1 = TYPE1(NR)
NUMBER = 4
Z1 = Z1*HALF
X(:,1) = -VER(:,1)*Z1 + VER(:,2)*HALF + &
VER(:,3)* (Z1+HALF)
X(:,2) = VER(:,1)*Z1 + VER(:,2)*HALF + &
VER(:,3)* (-Z1+HALF)
X(:,3) = VER(:,1)*Z1 + VER(:,2)* (-Z1+HALF) + &
VER(:,3)*HALF
X(:,4) = -VER(:,1)*Z1 + VER(:,2)* (Z1+HALF) + &
VER(:,3)*HALF
CASE (2) ! Generator ( z(1) , z(1) )
Z1 = TYPE2(NR)
NUMBER = 4
Z1 = Z1*HALF
X(:,1) = -2*VER(:,1)*Z1 + VER(:,2)* (HALF+Z1) +&
VER(:,3)* (Z1+HALF)
X(:,2) = VER(:,2)* (HALF+Z1) + VER(:,3)* (-Z1+HALF)
X(:,3) = VER(:,2)* (HALF-Z1) + VER(:,3)* (Z1+HALF)
X(:,4) = 2*VER(:,1)*Z1 + VER(:,2)* (HALF-Z1) + &
VER(:,3)* (-Z1+HALF)
CASE (3) ! Generator ( z(1) , z(2) )
Z1 = TYPE3(1,NR)*HALF
Z2 = TYPE3(2,NR)*HALF
NUMBER = 8
X(:,1) = VER(:,1)* (-Z1-Z2) + &
VER(:,2)* (HALF+Z2) + VER(:,3)* (HALF+Z1)
X(:,2) = VER(:,1)* (+Z1-Z2) + &
VER(:,2)* (HALF+Z2) + VER(:,3)* (HALF-Z1)
X(:,3) = VER(:,1)* (-Z1+Z2) + &
VER(:,2)* (HALF-Z2) + VER(:,3)* (HALF+Z1)
X(:,4) = VER(:,1)* (+Z1+Z2) + &
VER(:,2)* (HALF-Z2) + VER(:,3)* (HALF-Z1)
X(:,5) = VER(:,1)* (-Z1-Z2) + &
VER(:,2)* (HALF+Z1) + VER(:,3)* (HALF+Z2)
X(:,6) = VER(:,1)* (+Z2-Z1) + &
VER(:,2)* (HALF+Z1) + VER(:,3)* (HALF-Z2)
X(:,7) = VER(:,1)* (-Z2+Z1) + &
VER(:,2)* (HALF-Z1) + VER(:,3)* (HALF+Z2)
X(:,8) = VER(:,1)* (+Z1+Z2) + &
VER(:,2)* (HALF-Z1) + VER(:,3)* (HALF-Z2)
END SELECT
! CALL Integrand(2,X(1,1),NUMFUN,SUMVAL)
SUMVAL = Integrand(NUMFUN,X(:,1))
SELECT CASE (GENTYPE)
CASE (0)
DIFFy = SUMVAL(1)*DFC(0)
DIFFx = DIFFy
CASE (1)
DIFFy = DIFFy + SUMVAL(1)*DFC(NR)
END SELECT
DO J = 2,NUMBER
RGNERR = Integrand(NUMFUN,X(:,J))
! CALL Integrand(2,X(1,J),NUMFUN,RGNERR)
IF (GENTYPE == 1) THEN
IF (J <= 2) THEN
DIFFy = DIFFy + RGNERR(1)*DFC(NR)
ELSE
DIFFx = DIFFx + RGNERR(1)*DFC(NR)
END IF
END IF
DO I = 1,NUMFUN
SUMVAL(I) = SUMVAL(I) + RGNERR(I)
END DO
END DO
DO J = 1,NUMFUN
BASVAL(J) = BASVAL(J) + WEIGHT(1,P)*SUMVAL(J)
DO I = 1,7
NullRule(J,I) = NullRule(J,I) + WEIGHT(I+1,P)*SUMVAL(J)
END DO
END DO
P = P + 1
END DO
END DO
!
! Decide on future subdivision direction
!
DIFFy = ABS(DIFFy)
DIFFx = ABS(DIFFx)
IF (MAX(DIFFy,DIFFx) < CUTOFF) THEN
INFOLD(4) = 0
ELSE IF (DIFFy < DFCLEV*DIFFx) THEN
INFOLD(4) = 1
ELSE IF (DIFFx < DFCLEV*DIFFy) THEN
INFOLD(4) = 2
ELSE
INFOLD(4) = 0
END IF
!
! Compute errors.
!
DO J = 1,NUMFUN
NOISE = ABS(BASVAL(J))*TRES
DEG7 = SQRT(NullRule(J,1)**2+NullRule(J,2)**2)
IF (DEG7 <= NOISE) THEN
RGNERR(J) = NOISE
ELSE
DEG5 = SQRT(NullRule(J,3)**2+NullRule(J,4)**2)
DEG3 = SQRT(NullRule(J,5)**2+NullRule(J,6)**2)
DEG1 = SQRT(NullRule(J,7)**2+NullRule(J,6)**2)
IF (DEG5 /= 0) THEN
R1 = DEG7/DEG5
ELSE
R1 = 1
END IF
IF (DEG3 /= 0) THEN
R2 = DEG5/DEG3
ELSE
R2 = 1
END IF
IF (DEG1 /= 0) THEN
R3 = DEG3/DEG1
ELSE
R3 = 1
END IF
R = MAX(R1,R2,R3)
IF (R >= 1) THEN
INFOLD(5) = 0
RGNERR(J) = FACMED*DEG7
ELSE IF (R >= CRIVAL) THEN
INFOLD(5) = 0
RGNERR(J) = FACMED*DEG7*R
ELSE
INFOLD(5) = 1
RGNERR(J) = FACOPT* (R**3)*DEG7
END IF
RGNERR(J) = MAX(NOISE,RGNERR(J))
END IF
RGNERR(J) = AREA*RGNERR(J)/FOUR
BASVAL(J) = AREA*BASVAL(J)/FOUR
END DO
RETURN
END SUBROUTINE Rule_C2a
END Module CubatureRule_C2
| COSC499Project/critic2 | src/cubpack/rule_c2.f90 | FORTRAN | gpl-3.0 | 17,434 |
/*
FreeRTOS V7.4.2 - Copyright (C) 2013 Real Time Engineers Ltd.
FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT
http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
***************************************************************************
* *
* FreeRTOS tutorial books are available in pdf and paperback. *
* Complete, revised, and edited pdf reference manuals are also *
* available. *
* *
* Purchasing FreeRTOS documentation will not only help you, by *
* ensuring you get running as quickly as possible and with an *
* in-depth knowledge of how to use FreeRTOS, it will also help *
* the FreeRTOS project to continue with its mission of providing *
* professional grade, cross platform, de facto standard solutions *
* for microcontrollers - completely free of charge! *
* *
* >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
* *
* Thank you for using FreeRTOS, and thank you for your support! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
>>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to
distribute a combined work that includes FreeRTOS without being obliged to
provide the source code for proprietary components outside of the FreeRTOS
kernel.
FreeRTOS 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
and the FreeRTOS license exception along with FreeRTOS; if not it can be
viewed here: http://www.freertos.org/a00114.html and also obtained by
writing to Real Time Engineers Ltd., contact details for whom are available
on the FreeRTOS WEB site.
1 tab == 4 spaces!
***************************************************************************
* *
* Having a problem? Start by reading the FAQ "My application does *
* not run, what could be wrong?" *
* *
* http://www.FreeRTOS.org/FAQHelp.html *
* *
***************************************************************************
http://www.FreeRTOS.org - Documentation, books, training, latest versions,
license and Real Time Engineers Ltd. contact details.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool, and our new
fully thread aware and reentrant UDP/IP stack.
http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
Integrity Systems, who sell the code with commercial support,
indemnification and middleware, under the OpenRTOS brand.
http://www.SafeRTOS.com - High Integrity Systems also provide a safety
engineered and independently SIL3 certified version for use in safety and
mission critical applications that require provable dependability.
*/
#ifndef STACK_MACROS_H
#define STACK_MACROS_H
/*
* Call the stack overflow hook function if the stack of the task being swapped
* out is currently overflowed, or looks like it might have overflowed in the
* past.
*
* Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check
* the current stack state only - comparing the current top of stack value to
* the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1
* will also cause the last few stack bytes to be checked to ensure the value
* to which the bytes were set when the task was created have not been
* overwritten. Note this second test does not guarantee that an overflowed
* stack will always be recognised.
*/
/*-----------------------------------------------------------*/
#if( configCHECK_FOR_STACK_OVERFLOW == 0 )
/* FreeRTOSConfig.h is not set to check for stack overflows. */
#define taskFIRST_CHECK_FOR_STACK_OVERFLOW()
#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()
#endif /* configCHECK_FOR_STACK_OVERFLOW == 0 */
/*-----------------------------------------------------------*/
#if( configCHECK_FOR_STACK_OVERFLOW == 1 )
/* FreeRTOSConfig.h is only set to use the first method of
overflow checking. */
#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()
#endif
/*-----------------------------------------------------------*/
#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH < 0 ) )
/* Only the current stack state is to be checked. */
#define taskFIRST_CHECK_FOR_STACK_OVERFLOW() \
{ \
/* Is the currently saved stack pointer within the stack limit? */ \
if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \
{ \
vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
} \
}
#endif /* configCHECK_FOR_STACK_OVERFLOW > 0 */
/*-----------------------------------------------------------*/
#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH > 0 ) )
/* Only the current stack state is to be checked. */
#define taskFIRST_CHECK_FOR_STACK_OVERFLOW() \
{ \
\
/* Is the currently saved stack pointer within the stack limit? */ \
if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \
{ \
vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
} \
}
#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
/*-----------------------------------------------------------*/
#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) )
#define taskSECOND_CHECK_FOR_STACK_OVERFLOW() \
{ \
static const unsigned char ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \
\
\
/* Has the extremity of the task stack ever been written over? */ \
if( memcmp( ( void * ) pxCurrentTCB->pxStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \
{ \
vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
} \
}
#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
/*-----------------------------------------------------------*/
#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) )
#define taskSECOND_CHECK_FOR_STACK_OVERFLOW() \
{ \
char *pcEndOfStack = ( char * ) pxCurrentTCB->pxEndOfStack; \
static const unsigned char ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \
tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \
\
\
pcEndOfStack -= sizeof( ucExpectedStackBytes ); \
\
/* Has the extremity of the task stack ever been written over? */ \
if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \
{ \
vApplicationStackOverflowHook( ( xTaskHandle ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \
} \
}
#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
/*-----------------------------------------------------------*/
#endif /* STACK_MACROS_H */
| ilikecake/timer-v3 | timer-v3/freertos/inc/StackMacros.h | C | gpl-3.0 | 9,697 |
#ifndef CA_USERTOOLS_H
#define CA_USERTOOLS_H
#include <vector>
namespace ca {
std::vector<int> range(int from, int upto);
}
#endif // CA_USERTOOLS_H
| MrPablozOne/kaira | libs/cailie/usertools.h | C | gpl-3.0 | 157 |
//
// VMime library (http://www.vmime.org)
// Copyright (C) 2002-2013 Vincent Richard <vincent@vmime.org>
//
// 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// Linking this library statically or dynamically with other modules is making
// a combined work based on this library. Thus, the terms and conditions of
// the GNU General Public License cover the whole combination.
//
#include "tests/testUtils.hpp"
VMIME_TEST_SUITE_BEGIN(messageTest)
VMIME_TEST_LIST_BEGIN
VMIME_TEST(testGetGeneratedSize)
VMIME_TEST_LIST_END
void testGetGeneratedSize()
{
vmime::generationContext ctx;
vmime::shared_ptr <vmime::message> msg = vmime::make_shared <vmime::message>();
msg->getHeader()->getField("Foo")->setValue(vmime::string("bar"));
vmime::htmlTextPart textPart;
textPart.setPlainText(vmime::make_shared <vmime::stringContentHandler>("Foo bar bazé foo foo foo"));
textPart.setText(vmime::make_shared <vmime::stringContentHandler>("Foo bar <strong>bazé</strong> foo foo foo"));
textPart.generateIn(msg, msg);
// Estimated/computed generated size must be greater than the actual generated size
const vmime::size_t genSize = msg->getGeneratedSize(ctx);
const vmime::size_t actualSize = msg->generate().length();
std::ostringstream oss;
oss << "estimated size (" << genSize << ") >= actual size (" << actualSize << ")";
VASSERT(oss.str(), genSize >= actualSize);
}
VMIME_TEST_SUITE_END
| alexBraidwood/vmime | tests/parser/messageTest.cpp | C++ | gpl-3.0 | 2,096 |
/*
* This file is part of Cleanflight.
*
* Cleanflight 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.
*
* Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <platform.h>
#include "drivers/io.h"
#include "drivers/pwm_mapping.h"
const uint16_t multiPPM[] = {
PWM1 | (MAP_TO_PPM_INPUT << 8), // PPM input
PWM9 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM10 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM11 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM12 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM13 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM14 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM5 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM6 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM7 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
PWM8 | (MAP_TO_MOTOR_OUTPUT << 8), // Swap to servo if needed
0xFFFF
};
const uint16_t multiPWM[] = {
PWM1 | (MAP_TO_PWM_INPUT << 8), // input #1
PWM2 | (MAP_TO_PWM_INPUT << 8),
PWM3 | (MAP_TO_PWM_INPUT << 8),
PWM4 | (MAP_TO_PWM_INPUT << 8),
PWM5 | (MAP_TO_PWM_INPUT << 8),
PWM6 | (MAP_TO_PWM_INPUT << 8),
PWM7 | (MAP_TO_PWM_INPUT << 8),
PWM8 | (MAP_TO_PWM_INPUT << 8), // input #8
PWM9 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #1 or servo #1 (swap to servo if needed)
PWM10 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #2 or servo #2 (swap to servo if needed)
PWM11 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #1 or #3
PWM12 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM13 | (MAP_TO_MOTOR_OUTPUT << 8),
PWM14 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #4 or #6
0xFFFF
};
const uint16_t airPPM[] = {
PWM1 | (MAP_TO_PPM_INPUT << 8), // PPM input
PWM9 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #1
PWM10 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #2
PWM11 | (MAP_TO_SERVO_OUTPUT << 8), // servo #1
PWM12 | (MAP_TO_SERVO_OUTPUT << 8),
PWM13 | (MAP_TO_SERVO_OUTPUT << 8),
PWM14 | (MAP_TO_SERVO_OUTPUT << 8), // servo #4
PWM5 | (MAP_TO_SERVO_OUTPUT << 8), // servo #5
PWM6 | (MAP_TO_SERVO_OUTPUT << 8),
PWM7 | (MAP_TO_SERVO_OUTPUT << 8),
PWM8 | (MAP_TO_SERVO_OUTPUT << 8), // servo #8
0xFFFF
};
const uint16_t airPWM[] = {
PWM1 | (MAP_TO_PWM_INPUT << 8), // input #1
PWM2 | (MAP_TO_PWM_INPUT << 8),
PWM3 | (MAP_TO_PWM_INPUT << 8),
PWM4 | (MAP_TO_PWM_INPUT << 8),
PWM5 | (MAP_TO_PWM_INPUT << 8),
PWM6 | (MAP_TO_PWM_INPUT << 8),
PWM7 | (MAP_TO_PWM_INPUT << 8),
PWM8 | (MAP_TO_PWM_INPUT << 8), // input #8
PWM9 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #1
PWM10 | (MAP_TO_MOTOR_OUTPUT << 8), // motor #2
PWM11 | (MAP_TO_SERVO_OUTPUT << 8), // servo #1
PWM12 | (MAP_TO_SERVO_OUTPUT << 8),
PWM13 | (MAP_TO_SERVO_OUTPUT << 8),
PWM14 | (MAP_TO_SERVO_OUTPUT << 8), // servo #4
0xFFFF
};
const timerHardware_t timerHardware[USABLE_TIMER_CHANNEL_COUNT] = {
{ TIM1, IO_TAG(PA8), TIM_Channel_1, TIM1_CC_IRQn, 1, IOCFG_AF_PP_PD, GPIO_AF_6 }, // PWM1 - PA8
{ TIM16, IO_TAG(PB8), TIM_Channel_1, TIM1_UP_TIM16_IRQn, 0, IOCFG_AF_PP_PD, GPIO_AF_1 }, // PWM2 - PB8
{ TIM17, IO_TAG(PB9), TIM_Channel_1, TIM1_TRG_COM_TIM17_IRQn, 0, IOCFG_AF_PP_PD, GPIO_AF_1 }, // PWM3 - PB9
{ TIM8, IO_TAG(PC6), TIM_Channel_1, TIM8_CC_IRQn, 1, IOCFG_AF_PP_PD, GPIO_AF_4 }, // PWM4 - PC6
{ TIM8, IO_TAG(PC7), TIM_Channel_2, TIM8_CC_IRQn, 1, IOCFG_AF_PP_PD, GPIO_AF_4 }, // PWM5 - PC7
{ TIM8, IO_TAG(PC8), TIM_Channel_3, TIM8_CC_IRQn, 1, IOCFG_AF_PP_PD, GPIO_AF_4 }, // PWM6 - PC8
{ TIM3, IO_TAG(PB1), TIM_Channel_4, TIM3_IRQn, 0, IOCFG_AF_PP_PD, GPIO_AF_2 }, // PWM7 - PB1
{ TIM3, IO_TAG(PA4), TIM_Channel_2, TIM3_IRQn, 0, IOCFG_AF_PP_PD, GPIO_AF_2 }, // PWM8 - PA2
{ TIM4, IO_TAG(PD12), TIM_Channel_1, TIM4_IRQn, 0, IOCFG_AF_PP, GPIO_AF_2 }, // PWM9 - PD12
{ TIM4, IO_TAG(PD13), TIM_Channel_2, TIM4_IRQn, 0, IOCFG_AF_PP, GPIO_AF_2 }, // PWM10 - PD13
{ TIM4, IO_TAG(PD14), TIM_Channel_3, TIM4_IRQn, 0, IOCFG_AF_PP, GPIO_AF_2 }, // PWM11 - PD14
{ TIM4, IO_TAG(PD15), TIM_Channel_4, TIM4_IRQn, 0, IOCFG_AF_PP, GPIO_AF_2 }, // PWM12 - PD15
{ TIM2, IO_TAG(PA1), TIM_Channel_2, TIM2_IRQn, 0, IOCFG_AF_PP, GPIO_AF_1 }, // PWM13 - PA1
{ TIM2, IO_TAG(PA2), TIM_Channel_3, TIM2_IRQn, 0, IOCFG_AF_PP, GPIO_AF_1 } // PWM14 - PA2
};
| chickadee-tech/betaflight | src/main/target/STM32F3DISCOVERY/target.c | C | gpl-3.0 | 5,121 |
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2.1 of the GNU Lesser General Public License
as published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307,
USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#pragma ident "@(#) libfi/mpp_scan/scanmax_sp_6.c 92.1 07/13/99 10:21:33"
#include <stdlib.h>
#include <liberrno.h>
#include <fmath.h>
#include <cray/dopevec.h>
#include "f90_macros.h"
#define RANK 6
/*
* Compiler generated call: CALL _SCANMAX_SP6(RES, SRC, STOP, DIM, MASK)
*
* Purpose: Determine the maximum value of the elements of SRC
* along dimension DIM corresponding to the true elements
* of MASK. This particular routine handles source arrays
* of rank 6 with a data type of 64-bit floating point.
*
* Arguments:
* RES - Dope vector for temporary result array
* SRC - Dope vector for user source array
* STOP - Dope vector for stop array
* DIM - Dimension to operate along
* MASK - Dope vector for logical mask array
*
* Description:
* This is the MPP version of SCANMAX. This particular
* file contains the the intermediate type-specific
* routines. These routines parse and update the dope
* vectors, allocate either shared or private space for
* the result temporary, and possibly update the shared
* data desriptor (sdd) for the result temporary. Once
* this set-up work is complete, a Fortran subroutine
* is called which uses features from the Fortran
* Programming Model to distribute the word across all
* processors.
*
* Include file segmented_scan_p.h contains the rank independent
* source code for this routine.
*/
void
_SCANMAX_SP6 ( DopeVectorType *result,
DopeVectorType *source,
DopeVectorType *stop,
long *dim,
DopeVectorType *mask)
{
#include "segmented_scan_p.h"
if (stop_flag > 0) {
if (mask_flag == 1) {
SCANMAX_MASK_SP6@ (result_sdd_ptr, source_sdd_ptr,
stop_sdd_ptr, &dim_val, mask_sdd_ptr, src_extents,
blkcnts);
} else {
SCANMAX_NOMASK_SP6@ (result_sdd_ptr, source_sdd_ptr,
stop_sdd_ptr, &dim_val, src_extents, blkcnts);
}
}
}
| uhhpctools/openuh-openacc | osprey/libfi/mpp_scan/scanmax_sp_6.c | C | gpl-3.0 | 3,247 |
/*********************************************************************/
/* */
/* Optimized BLAS libraries */
/* By Kazushige Goto <kgoto@tacc.utexas.edu> */
/* */
/* Copyright (c) The University of Texas, 2009. All rights reserved. */
/* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING */
/* THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, */
/* NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY */
/* THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF */
/* TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO */
/* THE USE OF THE SOFTWARE OR DOCUMENTATION. */
/* Under no circumstances shall University be liable for incidental, */
/* special, indirect, direct or consequential damages or loss of */
/* profits, interruption of business, or related expenses which may */
/* arise from use of Software or Documentation, including but not */
/* limited to those resulting from defects in Software and/or */
/* Documentation, or loss or inaccuracy of data of any kind. */
/*********************************************************************/
#include <stdio.h>
#include "common.h"
#ifndef SMP
#define blas_cpu_number 1
#else
int blas_cpu_number = 1;
int blas_get_cpu_number(void){
return blas_cpu_number;
}
#endif
#define FIXED_PAGESIZE 4096
void *sa = NULL;
void *sb = NULL;
static double static_buffer[BUFFER_SIZE/sizeof(double)];
void *blas_memory_alloc(int numproc){
if (sa == NULL){
#if 1
sa = (void *)qalloc(QFAST, BUFFER_SIZE);
#else
sa = (void *)malloc(BUFFER_SIZE);
#endif
sb = (void *)&static_buffer[0];
}
return sa;
}
void blas_memory_free(void *free_area){
return;
}
| cnr-isti-vclab/meshlab | unsupported/plugins_unsupported/external/GotoBLAS2/driver/others/memory_qalloc.c | C | gpl-3.0 | 2,015 |
#ifdef __cplusplus
extern "C" {
#endif
/* Get next in EBYEDAT data buffers (exogam) */
int acq_ebyedat_get_next_event(UNSINT16* Buffer,
UNSINT16** EvtAddr,
int* EvtNum,
int EvtFormat);
/* Get next in EBYEDAT data buffers (exogam) ; reentrant version */
int acq_ebyedat_get_next_event_r(UNSINT16* Buffer,
UNSINT16** EvtAddr,
int* EvtNum,
int EvtFormat,
UNSINT16** NextEvent);
#ifdef __cplusplus
}
#endif
| jdfrankland/kaliveda | GanTape/include/acq_ebyedat_get_next_event.h | C | gpl-3.0 | 642 |
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
import { observer } from 'mobx-react';
import React, { Component, PropTypes } from 'react';
import { FormattedMessage } from 'react-intl';
import shapeshiftLogo from '~/../assets/images/shapeshift-logo.png';
import { Button, IdentityIcon, Portal } from '~/ui';
import { CancelIcon, DoneIcon } from '~/ui/Icons';
import AwaitingDepositStep from './AwaitingDepositStep';
import AwaitingExchangeStep from './AwaitingExchangeStep';
import CompletedStep from './CompletedStep';
import ErrorStep from './ErrorStep';
import OptionsStep from './OptionsStep';
import Store, { STAGE_COMPLETED, STAGE_OPTIONS, STAGE_WAIT_DEPOSIT, STAGE_WAIT_EXCHANGE } from './store';
import styles from './shapeshift.css';
const STAGE_TITLES = [
<FormattedMessage
id='shapeshift.title.details'
defaultMessage='details'
/>,
<FormattedMessage
id='shapeshift.title.deposit'
defaultMessage='awaiting deposit'
/>,
<FormattedMessage
id='shapeshift.title.exchange'
defaultMessage='awaiting exchange'
/>,
<FormattedMessage
id='shapeshift.title.completed'
defaultMessage='completed'
/>
];
const ERROR_TITLE = (
<FormattedMessage
id='shapeshift.title.error'
defaultMessage='exchange failed'
/>
);
@observer
export default class Shapeshift extends Component {
static contextTypes = {
store: PropTypes.object.isRequired
}
static propTypes = {
address: PropTypes.string.isRequired,
onClose: PropTypes.func
}
store = new Store(this.props.address);
componentDidMount () {
this.store.retrieveCoins();
}
componentWillUnmount () {
this.store.unsubscribe();
}
render () {
const { error, stage } = this.store;
return (
<Portal
activeStep={ stage }
busySteps={ [
STAGE_WAIT_DEPOSIT,
STAGE_WAIT_EXCHANGE
] }
buttons={ this.renderDialogActions() }
onClose={ this.onClose }
open
steps={
error
? null
: STAGE_TITLES
}
title={
error
? ERROR_TITLE
: null
}
>
{ this.renderPage() }
</Portal>
);
}
renderDialogActions () {
const { address } = this.props;
const { coins, error, hasAcceptedTerms, stage } = this.store;
const logo = (
<a
className={ styles.shapeshift }
href='http://shapeshift.io'
key='logo'
target='_blank'
>
<img src={ shapeshiftLogo } />
</a>
);
const cancelBtn = (
<Button
icon={ <CancelIcon /> }
key='cancel'
label={
<FormattedMessage
id='shapeshift.button.cancel'
defaultMessage='Cancel'
/>
}
onClick={ this.onClose }
/>
);
if (error) {
return [
logo,
cancelBtn
];
}
switch (stage) {
case STAGE_OPTIONS:
return [
logo,
cancelBtn,
<Button
disabled={ !coins.length || !hasAcceptedTerms }
icon={
<IdentityIcon
address={ address }
button
/>
}
key='shift'
label={
<FormattedMessage
id='shapeshift.button.shift'
defaultMessage='Shift Funds'
/>
}
onClick={ this.onShift }
/>
];
case STAGE_WAIT_DEPOSIT:
case STAGE_WAIT_EXCHANGE:
return [
logo,
cancelBtn
];
case STAGE_COMPLETED:
return [
logo,
<Button
icon={ <DoneIcon /> }
key='done'
label={
<FormattedMessage
id='shapeshift.button.done'
defaultMessage='Close'
/>
}
onClick={ this.onClose }
/>
];
}
}
renderPage () {
const { error, stage } = this.store;
if (error) {
return (
<ErrorStep store={ this.store } />
);
}
switch (stage) {
case STAGE_OPTIONS:
return (
<OptionsStep store={ this.store } />
);
case STAGE_WAIT_DEPOSIT:
return (
<AwaitingDepositStep store={ this.store } />
);
case STAGE_WAIT_EXCHANGE:
return (
<AwaitingExchangeStep store={ this.store } />
);
case STAGE_COMPLETED:
return (
<CompletedStep store={ this.store } />
);
}
}
onClose = () => {
this.store.setStage(STAGE_OPTIONS);
this.props.onClose && this.props.onClose();
}
onShift = () => {
return this.store.shift();
}
}
| nipunn1313/parity | js/src/modals/Shapeshift/shapeshift.js | JavaScript | gpl-3.0 | 5,450 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program 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.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\network\protocol;
#include <rules/DataPacket.h>
class RemoveBlockPacket extends DataPacket{
const NETWORK_ID = Info::REMOVE_BLOCK_PACKET;
public $x;
public $y;
public $z;
public function getName(){
return "RemoveBlockPacket";
}
public function decode(){
$this->getBlockCoords($this->x, $this->y, $this->z);
}
public function encode(){
}
}
| StarrySky-PE/StarrySky | src/pocketmine/network/protocol/RemoveBlockPacket.php | PHP | gpl-3.0 | 1,097 |
@charset "utf-8";
/* CSS Document */
/* **宽度变换** */
.main, .crumbcon {width:1190px !important;}
.linqigou-nav, .linqigou-filter-box, .tuanIndex, .sscardIndex, .brandList-wrap, .brandIndex, .specialsub-btmnav, .specialsub-con, .specialsub-banner, .specialsub, .specialSell, .specialTop-con, .shanshanNav-con, .headerCon, #sn-con {width:1190px;} | GodFrey118/GreenHouse | GreenHouse/src/main/webapp/css/public/width1190-V2.3.0.css | CSS | gpl-3.0 | 358 |
/*
* gain.cpp
*
* Created on: Sep 28, 2009
* Author: dc
*/
#include <ostream>
#include <gtest/gtest.h>
#include <barrett/systems/gain.h>
#include <barrett/systems/manual_execution_manager.h>
#include <barrett/systems/helpers.h>
#include "./exposed_io_system.h"
namespace {
using namespace barrett;
class GainSystemTest : public ::testing::Test {
public:
GainSystemTest() {
mem.startManaging(eios);
}
protected:
systems::ManualExecutionManager mem;
ExposedIOSystem<double> eios;
};
TEST_F(GainSystemTest, OutputInitiallyUndefined) {
systems::Gain<double> gainSys(12.5);
EXPECT_FALSE(gainSys.input.valueDefined())
<< "value defined without input";
}
TEST_F(GainSystemTest, ConnectsIO) {
systems::Gain<double> gainSys(1.0);
systems::connect(eios.output, gainSys.input);
systems::connect(gainSys.output, eios.input);
checkConnected(mem, &eios, eios, 3463.2);
}
TEST_F(GainSystemTest, MultipliesInput) {
systems::Gain<double> gainSys(14.2);
systems::connect(eios.output, gainSys.input);
systems::connect(gainSys.output, eios.input);
eios.setOutputValue(-38.52);
mem.runExecutionCycle();
EXPECT_EQ(14.2 * -38.52, eios.getInputValue());
}
TEST_F(GainSystemTest, SetGain) {
systems::Gain<double> gainSys(14.2);
systems::connect(eios.output, gainSys.input);
systems::connect(gainSys.output, eios.input);
eios.setOutputValue(-38.52);
mem.runExecutionCycle();
EXPECT_EQ(14.2 * -38.52, eios.getInputValue());
gainSys.setGain(-3.8);
mem.runExecutionCycle();
EXPECT_EQ(-3.8 * -38.52, eios.getInputValue());
}
using std::ostream;
class A;
class B;
class C;
class A {
friend const C operator * (const B& b, const A& a);
private:
float value;
public:
A() : value(0.0) {}
explicit A(float value) :
value(value) {}
};
class B {
friend const C operator * (const B& b, const A& a);
private:
float value;
public:
explicit B(float value) :
value(value) {}
};
class C {
friend ostream& operator<<(ostream& os, C c);
private:
float value;
public:
C() : value(0.0) {}
explicit C(float value) :
value(value) {}
bool operator== (const C& other) const {
return value == other.value;
}
};
const C operator* (const B& b, const A& a) {
return C(a.value * b.value);
}
ostream& operator<<(ostream& os, C c) {
os << c.value;
return os;
}
// mostly, we just want this to compile
TEST_F(GainSystemTest, IGOCanBeDifferentTypes) {
systems::Gain<A, B, C> gainSys(B(-3.0));
ExposedIOSystem<A> out;
ExposedIOSystem<C> in;
mem.startManaging(in);
systems::connect(gainSys.output, in.input);
systems::connect(out.output, gainSys.input);
out.setOutputValue(A(9.0));
mem.runExecutionCycle();
EXPECT_EQ(B(-3.0) * A(9.0), in.getInputValue())
<< "did multiplication wrong";
}
}
| BarrettTechnology/libbarrett | tests/systems/gain.cpp | C++ | gpl-3.0 | 2,733 |
<?php
/**
* OpenSKOS
*
* LICENSE
*
* This source file is subject to the GPLv3 license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/gpl-3.0.txt
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category OpenSKOS
* @package OpenSKOS
* @copyright Copyright (c) 2011 Pictura Database Publishing. (http://www.pictura-dp.nl)
* @author Mark Lindeman
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
*/
class Editor_IndexController extends OpenSKOS_Controller_Editor
{
public function indexAction()
{
$schemesCache = $this->getDI()->get('Editor_Models_ConceptSchemesCache');
$user = OpenSKOS_Db_Table_Users::requireFromIdentity();
$tenant = $this->readTenant()->getOpenSkos2Tenant();
$this->view->assign('conceptSchemes', $schemesCache->fetchUrisMap());
$this->view->assign('disableSearchProfileChanging', $user->disableSearchProfileChanging);
$this->view->assign('exportForm', Editor_Forms_Export::getInstance());
$this->view->assign('deleteForm', Editor_Forms_Delete::getInstance());
$this->view->assign('changeStatusForm', Editor_Forms_ChangeStatus::getInstance());
$this->view->assign('oActiveUser', $user);
$this->view->assign('oActiveTenant', $tenant);
$this->view->assign('searchForm', Editor_Forms_Search::getInstance());
}
}
| CatchPlus/OpenSKOS | application/editor/controllers/IndexController.php | PHP | gpl-3.0 | 1,621 |
. $PSScriptRoot\Shared.ps1
InModuleScope PSJira {
[System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseDeclaredVarsMoreThanAssigments', '', Scope='*', Target='SuppressImportModule')]
$SuppressImportModule = $true
. $PSScriptRoot\Shared.ps1
Describe "Get-JiraIssueCreateMetadata" {
if ($ShowDebugText)
{
Mock 'Write-Debug' {
Write-Host " [DEBUG] $Message" -ForegroundColor Yellow
}
}
Mock Get-JiraConfigServer {
'https://jira.example.com'
}
# If we don't override this in a context or test, we don't want it to
# actually try to query a JIRA instance
Mock Invoke-JiraMethod -ModuleName PSJira {
if ($ShowMockData)
{
Write-Host " Mocked Invoke-WebRequest" -ForegroundColor Cyan
Write-Host " [Uri] $Uri" -ForegroundColor Cyan
Write-Host " [Method] $Method" -ForegroundColor Cyan
}
}
Context "Sanity checking" {
$command = Get-Command -Name Get-JiraIssueCreateMetadata
function defParam($name)
{
It "Has a -$name parameter" {
$command.Parameters.Item($name) | Should Not BeNullOrEmpty
}
}
defParam 'Project'
defParam 'IssueType'
defParam 'Credential'
}
Context "Behavior testing" {
$restResult = ConvertFrom-Json2 @'
{
"expand": "projects",
"projects": [
{
"expand": "issuetypes",
"self": "https://jira.example.com/rest/api/2/project/10003",
"id": "10003",
"key": "TEST",
"name": "Test Project",
"issuetypes": [
{
"self": "https://jira.example.com/rest/api/latest/issuetype/2",
"id": "2",
"iconUrl": "https://jira.example.com/images/icons/issuetypes/newfeature.png",
"name": "Test Issue Type",
"subtask": false,
"expand": "fields",
"fields": {
"summary": {
"required": true,
"schema": {
"type": "string",
"system": "summary"
},
"name": "Summary",
"hasDefaultValue": false,
"operations": [
"set"
]
},
"issuetype": {
"required": true,
"schema": {
"type": "issuetype",
"system": "issuetype"
},
"name": "Issue Type",
"hasDefaultValue": false,
"operations": [],
"allowedValues": [
{
"self": "https://jira.example.com/rest/api/2/issuetype/2",
"id": "2",
"description": "This is a test issue type",
"iconUrl": "https://jira.example.com/images/icons/issuetypes/newfeature.png",
"name": "Test Issue Type",
"subtask": false
}
]
},
"description": {
"required": false,
"schema": {
"type": "string",
"system": "description"
},
"name": "Description",
"hasDefaultValue": false,
"operations": [
"set"
]
},
"project": {
"required": true,
"schema": {
"type": "project",
"system": "project"
},
"name": "Project",
"hasDefaultValue": false,
"operations": [
"set"
],
"allowedValues": [
{
"self": "https://jira.example.com/rest/api/2/project/10003",
"id": "10003",
"key": "TEST",
"name": "Test Project",
"projectCategory": {
"self": "https://jira.example.com/rest/api/2/projectCategory/10000",
"id": "10000",
"description": "All Project Catagories",
"name": "All Project"
}
}
]
},
"reporter": {
"required": true,
"schema": {
"type": "user",
"system": "reporter"
},
"name": "Reporter",
"autoCompleteUrl": "https://jira.example.com/rest/api/latest/user/search?username=",
"hasDefaultValue": false,
"operations": [
"set"
]
},
"assignee": {
"required": false,
"schema": {
"type": "user",
"system": "assignee"
},
"name": "Assignee",
"autoCompleteUrl": "https://jira.example.com/rest/api/latest/user/assignable/search?issueKey=null&username=",
"hasDefaultValue": false,
"operations": [
"set"
]
},
"priority": {
"required": false,
"schema": {
"type": "priority",
"system": "priority"
},
"name": "Priority",
"hasDefaultValue": true,
"operations": [
"set"
],
"allowedValues": [
{
"self": "https://jira.example.com/rest/api/2/priority/1",
"iconUrl": "https://jira.example.com/images/icons/priorities/blocker.png",
"name": "Blocker",
"id": "1"
},
{
"self": "https://jira.example.com/rest/api/2/priority/2",
"iconUrl": "https://jira.example.com/images/icons/priorities/critical.png",
"name": "Critical",
"id": "2"
},
{
"self": "https://jira.example.com/rest/api/2/priority/3",
"iconUrl": "https://jira.example.com/images/icons/priorities/major.png",
"name": "Major",
"id": "3"
},
{
"self": "https://jira.example.com/rest/api/2/priority/4",
"iconUrl": "https://jira.example.com/images/icons/priorities/minor.png",
"name": "Minor",
"id": "4"
},
{
"self": "https://jira.example.com/rest/api/2/priority/5",
"iconUrl": "https://jira.example.com/images/icons/priorities/trivial.png",
"name": "Trivial",
"id": "5"
}
]
},
"labels": {
"required": false,
"schema": {
"type": "array",
"items": "string",
"system": "labels"
},
"name": "Labels",
"autoCompleteUrl": "https://jira.example.com/rest/api/1.0/labels/suggest?query=",
"hasDefaultValue": false,
"operations": [
"add",
"set",
"remove"
]
}
}
}
]
}
]
}
'@
Mock Get-JiraProject -ModuleName PSJira {
[PSCustomObject] @{
ID = 10003;
Name = 'Test Project';
}
}
Mock Get-JiraIssueType -ModuleName PSJira {
[PSCustomObject] @{
ID = 2;
Name = 'Test Issue Type';
}
}
It "Queries Jira for metadata information about creating an issue" {
{ Get-JiraIssueCreateMetadata -Project 10003 -IssueType 2 } | Should Not Throw
Assert-MockCalled -CommandName Invoke-JiraMethod -ModuleName PSJira -Exactly -Times 1 -Scope It -ParameterFilter {$Method -eq 'Get' -and $URI -like '*/rest/api/*/issue/createmeta?projectIds=10003&issuetypeIds=2&expand=projects.issuetypes.fields'}
}
It "Uses ConvertTo-JiraCreateMetaField to output CreateMetaField objects if JIRA returns data" {
# This is a simplified version of what JIRA will give back
Mock Invoke-JiraMethod -ModuleName PSJira {
@{
projects = @{
issuetypes = @{
fields = [PSCustomObject] @{
'a' = 1;
'b' = 2;
}
}
}
}
}
Mock ConvertTo-JiraCreateMetaField -ModuleName PSJira {}
{ Get-JiraIssueCreateMetadata -Project 10003 -IssueType 2 } | Should Not Throw
Assert-MockCalled -CommandName Invoke-JiraMethod -ModuleName PSJira -Exactly -Times 1 -Scope It -ParameterFilter {$Method -eq 'Get' -and $URI -like '*/rest/api/*/issue/createmeta?projectIds=10003&issuetypeIds=2&expand=projects.issuetypes.fields'}
# There are 2 example fields in our mock above, but they should
# be passed to Convert-JiraCreateMetaField as a single object.
# The method should only be called once.
Assert-MockCalled -CommandName ConvertTo-JiraCreateMetaField -ModuleName PSJira -Exactly -Times 1 -Scope It
}
}
}
}
| PSJira/PSJira | Tests/Get-JiraIssueCreateMetadata.Tests.ps1 | PowerShell | gpl-3.0 | 9,826 |
#pragma once
#define LONG_NAME "<%= config.info.longName %>"
#define VERSION_LABEL "<%= config.info.versionLabel %>"
#define UUID "<%= config.info.uuid %>"
<% for (prop in config.info.appKeys) {
%>#define <%= prop %> <%= config.info.appKeys[prop] %>
<% } %>
| thomacer/pebble-open-bike-sharing | src/appinfo.tpl.h | C | gpl-3.0 | 262 |
-----------------------------------
-- Area: Western Adoulin
-- NPC: Pagnelle
-- Type: Standard NPC and Quest NPC
-- Starts, Involved with, and Finishes Quest: 'Raptor Rapture'
-- @zone 256
-- !pos -8 0 -100 256
-----------------------------------
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/Western_Adoulin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Raptor_Rapture = player:getQuestStatus(ADOULIN, RAPTOR_RAPTURE);
local Raptor_Rapture_Status = player:getVar("Raptor_Rapture_Status");
if (Raptor_Rapture == QUEST_AVAILABLE) then
if (Raptor_Rapture_Status < 3) then
-- Starts chain of events for the introduction CS for Quest: 'Raptor Rapture'.
-- If player somehow doesn't finish the chain of events, they can just talk to Pagnelle again to retry.
player:setVar("Raptor_Rapture_Status", 1);
player:startEvent(0x13A8);
else
-- Player has finished introductory CS event chain, but didn't accept the quest.
-- Offers Quest: 'Raptor Rapture' if player has yet to accept it.
player:startEvent(0x13C5);
end
elseif (Raptor_Rapture == QUEST_ACCEPTED) then
if (Raptor_Rapture_Status == 4) then
-- Reminder during Quest: 'Raptor Rapture', speak to Ilney.
player:startEvent(0x13A9);
elseif (Raptor_Rapture_Status == 5) then
-- Progresses Quest: 'Raptor Rapture', spoke to Ilney.
player:startEvent(0x13AB);
elseif (Raptor_Rapture_Status == 6) then
local Has_Rockberries = player:hasKeyItem(ROCKBERRY1) and player:hasKeyItem(ROCKBERRY2) and player:hasKeyItem(ROCKBERRY3)
if (Has_Rockberries) then
-- Progresses Quest: 'Raptor Rapture', turning in rockberries.
player:startEvent(0x13AD);
else
-- Reminder during Quest: 'Raptor Rapture', bring rockberries.
player:startEvent(0x13AC);
end
elseif (Raptor_Rapture_Status == 7) then
-- Reminder during Quest: 'Raptor Rapture', go to Rala.
player:startEvent(0x13AE);
elseif (Raptor_Rapture_Status == 8) then
-- Finishes Quest: 'Raptor Rapture'
player:startEvent(0x13AF);
end
else
if (player:needToZone()) then
-- Dialogue after finishing Quest: 'Raptor Rapture', before zoning
player:startEvent(0x13B0);
else
-- Dialogue after finishing Quest: 'Raptor Rapture', after zoning
player:startEvent(0x13B1);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x13A8) then
-- Warps player to Rala Waterways to continue intrductory CS for Quest: 'Raptor Rapture'
player:setPos(0, 0, 0, 0, 258);
elseif ((csid == 0x13C5) and (option == 1)) then
-- Starts Quest: 'Raptor Rapture'
player:addQuest(ADOULIN, RAPTOR_RAPTURE);
player:setVar("Raptor_Rapture_Status", 4);
elseif (csid == 0x13AB) then
-- Progresses Quest: 'Raptor Rapture', spoke to Ilney, now need rockberries.
player:setVar("Raptor_Rapture_Status", 6);
elseif (csid == 0x13AD) then
-- Progresses Quest: 'Raptor Rapture', brought rockberries, now need to go to Rala.
player:delKeyItem(ROCKBERRY1);
player:delKeyItem(ROCKBERRY2);
player:delKeyItem(ROCKBERRY3);
player:setVar("Raptor_Rapture_Status", 7);
elseif (csid == 0x13AF) then
-- Finishing Quest: 'Raptor Rapture'
player:setVar("Raptor_Rapture_Status", 0);
player:completeQuest(ADOULIN, RAPTOR_RAPTURE);
player:addCurrency('bayld', 1000 * BAYLD_RATE);
player:messageSpecial(BAYLD_OBTAINED, 1000 * BAYLD_RATE);
player:addFame(ADOULIN);
player:needToZone(true);
end
end;
| RebootRevival/FFXI_Test | scripts/zones/Western_Adoulin/npcs/Pagnelle.lua | Lua | gpl-3.0 | 4,476 |
#ifndef COIN_3DSLOADER_H
#define COIN_3DSLOADER_H
/**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) 1998-2005 by Systems in Motion. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Systems in Motion about acquiring
* a Coin Professional Edition License.
*
* See <URL:http://www.coin3d.org/> for more information.
*
* Systems in Motion, Postboks 1283, Pirsenteret, 7462 Trondheim, NORWAY.
* <URL:http://www.sim.no/>.
*
\**************************************************************************/
#include <Inventor/C/basic.h> // for M_PI
class SoInput;
class SoSeparator;
SbBool coin_3ds_read_file(SoInput * in, SoSeparator *& root,
int appendNormals = 2,
float creaseAngle = 25.f/180.f*M_PI,
SbBool loadMaterials = TRUE,
SbBool loadTextures = TRUE,
SbBool loadObjNames = FALSE,
SbBool indexedTriSet = FALSE,
SbBool centerModel = TRUE,
float modelSize = 10.f);
#endif // !COIN_3DSLOADER_H
| jmespadero/coindesigner | src/3dsLoader.h | C | gpl-3.0 | 1,704 |
<?php
/**
* @file
* This is the template file for the metadata description for an object.
*
* Available variables:
* - $islandora_object: The Islandora object rendered in this template file
* - $found: Boolean indicating if a Solr doc was found for the current object.
*
* @see template_preprocess_islandora_solr_metadata_description()
* @see template_process_islandora_solr_metadata_description()
*/
?>
<?php if ($found && !empty($description)): ?>
<div class="islandora-solr-metadata-sidebar">
<?php if ($combine): ?>
<h2><?php if (count($description) > 1):
print (t('Description'));
else:
$desc_array = reset($description);
print ($desc_array['display_label']); ?>
<?php endif; ?></h2>
<?php foreach($description as $value): ?>
<p property="description"><?php print check_markup(implode("\n", $value['value']), 'filtered_html'); ?></p>
<?php endforeach; ?>
<?php else: ?>
<?php foreach ($description as $value): ?>
<h2><?php print $value['display_label']; ?></h2>
<p><?php print check_markup(implode("\n", $value['value']), 'filtered_html'); ?></p>
<?php endforeach; ?>
<?php endif; ?>
</div>
<?php endif; ?>
| jordandukart/islandora_solr_metadata | theme/islandora-solr-metadata-description.tpl.php | PHP | gpl-3.0 | 1,232 |
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
Copyright (C) 2015 Robert Beckebans
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 Source Code 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.
Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
#include "precompiled.h"
#pragma hdrstop
#include "dmap.h"
idList<interAreaPortal_t> interAreaPortals;
int c_active_portals;
int c_peak_portals;
/*
===========
AllocPortal
===========
*/
uPortal_t* AllocPortal()
{
uPortal_t* p;
c_active_portals++;
if( c_active_portals > c_peak_portals )
{
c_peak_portals = c_active_portals;
}
p = ( uPortal_t* )Mem_Alloc( sizeof( uPortal_t ), TAG_TOOLS );
memset( p, 0, sizeof( uPortal_t ) );
return p;
}
void FreePortal( uPortal_t* p )
{
if( p->winding )
{
delete p->winding;
}
c_active_portals--;
Mem_Free( p );
}
//==============================================================
/*
=============
Portal_Passable
Returns true if the portal has non-opaque leafs on both sides
=============
*/
static bool Portal_Passable( uPortal_t* p )
{
if( !p->onnode )
{
return false; // to global outsideleaf
}
if( p->nodes[0]->planenum != PLANENUM_LEAF
|| p->nodes[1]->planenum != PLANENUM_LEAF )
{
common->Error( "Portal_EntityFlood: not a leaf" );
}
if( !p->nodes[0]->opaque && !p->nodes[1]->opaque )
{
return true;
}
return false;
}
//=============================================================================
int c_tinyportals;
/*
=============
AddPortalToNodes
=============
*/
void AddPortalToNodes( uPortal_t* p, node_t* front, node_t* back )
{
if( p->nodes[0] || p->nodes[1] )
{
common->Error( "AddPortalToNode: allready included" );
}
p->nodes[0] = front;
p->next[0] = front->portals;
front->portals = p;
p->nodes[1] = back;
p->next[1] = back->portals;
back->portals = p;
}
/*
=============
RemovePortalFromNode
=============
*/
void RemovePortalFromNode( uPortal_t* portal, node_t* l )
{
uPortal_t** pp, *t;
// remove reference to the current portal
pp = &l->portals;
while( 1 )
{
t = *pp;
if( !t )
{
common->Error( "RemovePortalFromNode: portal not in leaf" );
}
if( t == portal )
{
break;
}
if( t->nodes[0] == l )
{
pp = &t->next[0];
}
else if( t->nodes[1] == l )
{
pp = &t->next[1];
}
else
{
common->Error( "RemovePortalFromNode: portal not bounding leaf" );
}
}
if( portal->nodes[0] == l )
{
*pp = portal->next[0];
portal->nodes[0] = NULL;
}
else if( portal->nodes[1] == l )
{
*pp = portal->next[1];
portal->nodes[1] = NULL;
}
else
{
common->Error( "RemovePortalFromNode: mislinked" );
}
}
//============================================================================
void PrintPortal( uPortal_t* p )
{
int i;
idWinding* w;
w = p->winding;
for( i = 0; i < w->GetNumPoints(); i++ )
{
common->Printf( "(%5.0f,%5.0f,%5.0f)\n", ( *w )[i][0], ( *w )[i][1], ( *w )[i][2] );
}
}
/*
================
MakeHeadnodePortals
The created portals will face the global outside_node
================
*/
#define SIDESPACE 8
static void MakeHeadnodePortals( tree_t* tree )
{
idBounds bounds;
int i, j, n;
uPortal_t* p, *portals[6];
idPlane bplanes[6], *pl;
node_t* node;
node = tree->headnode;
tree->outside_node.planenum = PLANENUM_LEAF;
tree->outside_node.brushlist = NULL;
tree->outside_node.portals = NULL;
tree->outside_node.opaque = false;
// if no nodes, don't go any farther
if( node->planenum == PLANENUM_LEAF )
{
return;
}
// pad with some space so there will never be null volume leafs
for( i = 0 ; i < 3 ; i++ )
{
bounds[0][i] = tree->bounds[0][i] - SIDESPACE;
bounds[1][i] = tree->bounds[1][i] + SIDESPACE;
if( bounds[0][i] >= bounds[1][i] )
{
common->Error( "Backwards tree volume" );
}
}
for( i = 0 ; i < 3 ; i++ )
{
for( j = 0 ; j < 2 ; j++ )
{
n = j * 3 + i;
p = AllocPortal();
portals[n] = p;
pl = &bplanes[n];
memset( pl, 0, sizeof( *pl ) );
if( j )
{
( *pl )[i] = -1;
( *pl )[3] = bounds[j][i];
}
else
{
( *pl )[i] = 1;
( *pl )[3] = -bounds[j][i];
}
p->plane = *pl;
p->winding = new idWinding( *pl );
AddPortalToNodes( p, node, &tree->outside_node );
}
}
// clip the basewindings by all the other planes
for( i = 0 ; i < 6 ; i++ )
{
for( j = 0 ; j < 6 ; j++ )
{
if( j == i )
{
continue;
}
portals[i]->winding = portals[i]->winding->Clip( bplanes[j], ON_EPSILON );
}
}
}
//===================================================
/*
================
BaseWindingForNode
================
*/
#define BASE_WINDING_EPSILON 0.001f
#define SPLIT_WINDING_EPSILON 0.001f
idWinding* BaseWindingForNode( node_t* node )
{
idWinding* w;
node_t* n;
w = new idWinding( dmapGlobals.mapPlanes[node->planenum] );
// clip by all the parents
for( n = node->parent ; n && w ; )
{
idPlane& plane = dmapGlobals.mapPlanes[n->planenum];
if( n->children[0] == node )
{
// take front
w = w->Clip( plane, BASE_WINDING_EPSILON );
}
else
{
// take back
idPlane back = -plane;
w = w->Clip( back, BASE_WINDING_EPSILON );
}
node = n;
n = n->parent;
}
return w;
}
//============================================================
/*
==================
MakeNodePortal
create the new portal by taking the full plane winding for the cutting plane
and clipping it by all of parents of this node
==================
*/
static void MakeNodePortal( node_t* node )
{
uPortal_t* new_portal, *p;
idWinding* w;
idVec3 normal;
int side;
w = BaseWindingForNode( node );
// clip the portal by all the other portals in the node
for( p = node->portals ; p && w; p = p->next[side] )
{
idPlane plane;
if( p->nodes[0] == node )
{
side = 0;
plane = p->plane;
}
else if( p->nodes[1] == node )
{
side = 1;
plane = -p->plane;
}
else
{
common->Error( "CutNodePortals_r: mislinked portal" );
side = 0; // quiet a compiler warning
}
w = w->Clip( plane, CLIP_EPSILON );
}
if( !w )
{
return;
}
if( w->IsTiny() )
{
c_tinyportals++;
delete w;
return;
}
new_portal = AllocPortal();
new_portal->plane = dmapGlobals.mapPlanes[node->planenum];
new_portal->onnode = node;
new_portal->winding = w;
AddPortalToNodes( new_portal, node->children[0], node->children[1] );
}
/*
==============
SplitNodePortals
Move or split the portals that bound node so that the node's
children have portals instead of node.
==============
*/
static void SplitNodePortals( node_t* node )
{
uPortal_t* p, *next_portal, *new_portal;
node_t* f, *b, *other_node;
int side;
idPlane* plane;
idWinding* frontwinding, *backwinding;
plane = &dmapGlobals.mapPlanes[node->planenum];
f = node->children[0];
b = node->children[1];
for( p = node->portals ; p ; p = next_portal )
{
if( p->nodes[0] == node )
{
side = 0;
}
else if( p->nodes[1] == node )
{
side = 1;
}
else
{
common->Error( "SplitNodePortals: mislinked portal" );
side = 0; // quiet a compiler warning
}
next_portal = p->next[side];
other_node = p->nodes[!side];
RemovePortalFromNode( p, p->nodes[0] );
RemovePortalFromNode( p, p->nodes[1] );
//
// cut the portal into two portals, one on each side of the cut plane
//
p->winding->Split( *plane, SPLIT_WINDING_EPSILON, &frontwinding, &backwinding );
if( frontwinding && frontwinding->IsTiny() )
{
delete frontwinding;
frontwinding = NULL;
c_tinyportals++;
}
if( backwinding && backwinding->IsTiny() )
{
delete backwinding;
backwinding = NULL;
c_tinyportals++;
}
if( !frontwinding && !backwinding )
{
// tiny windings on both sides
continue;
}
if( !frontwinding )
{
delete backwinding;
if( side == 0 )
{
AddPortalToNodes( p, b, other_node );
}
else
{
AddPortalToNodes( p, other_node, b );
}
continue;
}
if( !backwinding )
{
delete frontwinding;
if( side == 0 )
{
AddPortalToNodes( p, f, other_node );
}
else
{
AddPortalToNodes( p, other_node, f );
}
continue;
}
// the winding is split
new_portal = AllocPortal();
*new_portal = *p;
new_portal->winding = backwinding;
delete p->winding;
p->winding = frontwinding;
if( side == 0 )
{
AddPortalToNodes( p, f, other_node );
AddPortalToNodes( new_portal, b, other_node );
}
else
{
AddPortalToNodes( p, other_node, f );
AddPortalToNodes( new_portal, other_node, b );
}
}
node->portals = NULL;
}
/*
================
CalcNodeBounds
================
*/
void CalcNodeBounds( node_t* node )
{
uPortal_t* p;
int s;
int i;
// calc mins/maxs for both leafs and nodes
node->bounds.Clear();
for( p = node->portals ; p ; p = p->next[s] )
{
s = ( p->nodes[1] == node );
for( i = 0; i < p->winding->GetNumPoints(); i++ )
{
node->bounds.AddPoint( ( *p->winding )[i].ToVec3() );
}
}
}
/*
==================
MakeTreePortals_r
==================
*/
void MakeTreePortals_r( node_t* node )
{
int i;
CalcNodeBounds( node );
if( node->bounds[0][0] >= node->bounds[1][0] )
{
common->Warning( "node without a volume" );
}
for( i = 0; i < 3; i++ )
{
if( node->bounds[0][i] < MIN_WORLD_COORD || node->bounds[1][i] > MAX_WORLD_COORD )
{
common->Warning( "node with unbounded volume" );
break;
}
}
if( node->planenum == PLANENUM_LEAF )
{
return;
}
MakeNodePortal( node );
SplitNodePortals( node );
MakeTreePortals_r( node->children[0] );
MakeTreePortals_r( node->children[1] );
}
/*
==================
MakeTreePortals
==================
*/
void MakeTreePortals( tree_t* tree )
{
common->Printf( "----- MakeTreePortals -----\n" );
MakeHeadnodePortals( tree );
MakeTreePortals_r( tree->headnode );
}
/*
=========================================================
FLOOD ENTITIES
=========================================================
*/
int c_floodedleafs;
/*
=============
FloodPortals_r
=============
*/
void FloodPortals_r( node_t* node, int dist )
{
uPortal_t* p;
int s;
if( node->occupied )
{
return;
}
if( node->opaque )
{
return;
}
c_floodedleafs++;
node->occupied = dist;
for( p = node->portals ; p ; p = p->next[s] )
{
s = ( p->nodes[1] == node );
FloodPortals_r( p->nodes[!s], dist + 1 );
}
}
/*
=============
PlaceOccupant
=============
*/
bool PlaceOccupant( node_t* headnode, idVec3 origin, uEntity_t* occupant )
{
node_t* node;
float d;
idPlane* plane;
// find the leaf to start in
node = headnode;
while( node->planenum != PLANENUM_LEAF )
{
plane = &dmapGlobals.mapPlanes[node->planenum];
d = plane->Distance( origin );
if( d >= 0.0f )
{
node = node->children[0];
}
else
{
node = node->children[1];
}
}
if( node->opaque )
{
return false;
}
node->occupant = occupant;
FloodPortals_r( node, 1 );
return true;
}
/*
=============
FloodEntities
Marks all nodes that can be reached by entites
=============
*/
bool FloodEntities( tree_t* tree )
{
int i;
idVec3 origin;
const char* cl;
bool inside;
node_t* headnode;
headnode = tree->headnode;
common->Printf( "--- FloodEntities ---\n" );
inside = false;
tree->outside_node.occupied = 0;
c_floodedleafs = 0;
bool errorShown = false;
for( i = 1 ; i < dmapGlobals.num_entities ; i++ )
{
idMapEntity* mapEnt;
mapEnt = dmapGlobals.uEntities[i].mapEntity;
if( !mapEnt->epairs.GetVector( "origin", "", origin ) )
{
continue;
}
// any entity can have "noFlood" set to skip it
if( mapEnt->epairs.GetString( "noFlood", "", &cl ) )
{
continue;
}
mapEnt->epairs.GetString( "classname", "", &cl );
if( !strcmp( cl, "light" ) )
{
const char* v;
// don't place lights that have a light_start field, because they can still
// be valid if their origin is outside the world
mapEnt->epairs.GetString( "light_start", "", &v );
if( v[0] )
{
continue;
}
// don't place fog lights, because they often
// have origins outside the light
mapEnt->epairs.GetString( "texture", "", &v );
if( v[0] )
{
const idMaterial* mat = declManager->FindMaterial( v );
if( mat->IsFogLight() )
{
continue;
}
}
}
if( PlaceOccupant( headnode, origin, &dmapGlobals.uEntities[i] ) )
{
inside = true;
}
if( tree->outside_node.occupied && !errorShown )
{
errorShown = true;
common->Printf( "Leak on entity # %d\n", i );
const char* p;
mapEnt->epairs.GetString( "classname", "", &p );
common->Printf( "Entity classname was: %s\n", p );
mapEnt->epairs.GetString( "name", "", &p );
common->Printf( "Entity name was: %s\n", p );
idVec3 origin;
if( mapEnt->epairs.GetVector( "origin", "", origin ) )
{
common->Printf( "Entity origin is: %f %f %f\n\n\n", origin.x, origin.y, origin.z );
}
}
}
common->Printf( "%5i flooded leafs\n", c_floodedleafs );
if( !inside )
{
common->Printf( "no entities in open -- no filling\n" );
}
else if( tree->outside_node.occupied )
{
common->Printf( "entity reached from outside -- no filling\n" );
}
return ( bool )( inside && !tree->outside_node.occupied );
}
/*
=========================================================
FLOOD AREAS
=========================================================
*/
static int c_areas;
static int c_areaFloods;
/*
=================
FindSideForPortal
=================
*/
static side_t* FindSideForPortal( uPortal_t* p )
{
int i, j, k;
node_t* node;
uBrush_t* b, *orig;
side_t* s, *s2;
// scan both bordering nodes brush lists for a portal brush
// that shares the plane
for( i = 0 ; i < 2 ; i++ )
{
node = p->nodes[i];
for( b = node->brushlist ; b ; b = b->next )
{
if( !( b->contents & CONTENTS_AREAPORTAL ) )
{
continue;
}
orig = b->original;
for( j = 0 ; j < orig->numsides ; j++ )
{
s = orig->sides + j;
if( !s->visibleHull )
{
continue;
}
if( !( s->material->GetContentFlags() & CONTENTS_AREAPORTAL ) )
{
continue;
}
if( ( s->planenum & ~1 ) != ( p->onnode->planenum & ~1 ) )
{
continue;
}
// remove the visible hull from any other portal sides of this portal brush
for( k = 0; k < orig->numsides; k++ )
{
if( k == j )
{
continue;
}
s2 = orig->sides + k;
if( s2->visibleHull == NULL )
{
continue;
}
if( !( s2->material->GetContentFlags() & CONTENTS_AREAPORTAL ) )
{
continue;
}
common->Warning( "brush has multiple area portal sides at %s", s2->visibleHull->GetCenter().ToString() );
delete s2->visibleHull;
s2->visibleHull = NULL;
}
return s;
}
}
}
return NULL;
}
// RB: extra function to avoid many allocations
static bool CheckTrianglesForPortal( uPortal_t* p )
{
int i;
node_t* node;
mapTri_t* tri;
// scan both bordering nodes triangle lists for portal triangles that share the plane
for( i = 0 ; i < 2 ; i++ )
{
node = p->nodes[i];
for( tri = node->areaPortalTris; tri; tri = tri->next )
{
if( !( tri->material->GetContentFlags() & CONTENTS_AREAPORTAL ) )
{
continue;
}
if( ( tri->planeNum & ~1 ) != ( p->onnode->planenum & ~1 ) )
{
continue;
}
return true;
}
}
return false;
}
static bool FindTrianglesForPortal( uPortal_t* p, idList<mapTri_t*>& tris )
{
int i;
node_t* node;
mapTri_t* tri;
tris.Clear();
// scan both bordering nodes triangle lists for portal triangles that share the plane
for( i = 0 ; i < 2 ; i++ )
{
node = p->nodes[i];
for( tri = node->areaPortalTris; tri; tri = tri->next )
{
if( !( tri->material->GetContentFlags() & CONTENTS_AREAPORTAL ) )
{
continue;
}
if( ( tri->planeNum & ~1 ) != ( p->onnode->planenum & ~1 ) )
{
continue;
}
tris.Append( tri );
}
}
return tris.Num() > 0;
}
// RB end
/*
=============
FloodAreas_r
=============
*/
void FloodAreas_r( node_t* node )
{
uPortal_t* p;
int s;
if( node->area != -1 )
{
return; // allready got it
}
if( node->opaque )
{
return;
}
c_areaFloods++;
node->area = c_areas;
for( p = node->portals ; p ; p = p->next[s] )
{
node_t* other;
s = ( p->nodes[1] == node );
other = p->nodes[!s];
if( !Portal_Passable( p ) )
{
continue;
}
// can't flood through an area portal
if( FindSideForPortal( p ) )
{
continue;
}
// RB: check area portal triangles as well
if( CheckTrianglesForPortal( p ) )
{
continue;
}
FloodAreas_r( other );
}
}
/*
=============
FindAreas_r
Just decend the tree, and for each node that hasn't had an
area set, flood fill out from there
=============
*/
void FindAreas_r( node_t* node )
{
if( node->planenum != PLANENUM_LEAF )
{
FindAreas_r( node->children[0] );
FindAreas_r( node->children[1] );
return;
}
if( node->opaque )
{
return;
}
if( node->area != -1 )
{
return; // allready got it
}
c_areaFloods = 0;
FloodAreas_r( node );
common->Printf( "area %i has %i leafs\n", c_areas, c_areaFloods );
c_areas++;
}
/*
============
CheckAreas_r
============
*/
void CheckAreas_r( node_t* node )
{
if( node->planenum != PLANENUM_LEAF )
{
CheckAreas_r( node->children[0] );
CheckAreas_r( node->children[1] );
return;
}
if( !node->opaque && node->area < 0 )
{
common->Error( "CheckAreas_r: area = %i", node->area );
}
}
/*
============
ClearAreas_r
Set all the areas to -1 before filling
============
*/
void ClearAreas_r( node_t* node )
{
if( node->planenum != PLANENUM_LEAF )
{
ClearAreas_r( node->children[0] );
ClearAreas_r( node->children[1] );
return;
}
node->area = -1;
}
//=============================================================
/*
=================
FindInterAreaPortals_r
=================
*/
static void FindInterAreaPortals_r( node_t* node )
{
uPortal_t* p;
int s;
int i;
idWinding* w;
interAreaPortal_t* iap;
side_t* side;
if( node->planenum != PLANENUM_LEAF )
{
FindInterAreaPortals_r( node->children[0] );
FindInterAreaPortals_r( node->children[1] );
return;
}
if( node->opaque )
{
return;
}
for( p = node->portals ; p ; p = p->next[s] )
{
node_t* other;
s = ( p->nodes[1] == node );
other = p->nodes[!s];
if( other->opaque )
{
continue;
}
// only report areas going from lower number to higher number
// so we don't report the portal twice
if( other->area <= node->area )
{
continue;
}
side = FindSideForPortal( p );
// w = p->winding;
if( !side )
{
common->Warning( "FindSideForPortal failed at %s", p->winding->GetCenter().ToString() );
continue;
}
w = side->visibleHull;
if( !w )
{
continue;
}
// see if we have created this portal before
for( i = 0; i < interAreaPortals.Num(); i++ )
{
iap = &interAreaPortals[i];
if( side == iap->side &&
( ( p->nodes[0]->area == iap->area0 && p->nodes[1]->area == iap->area1 )
|| ( p->nodes[1]->area == iap->area0 && p->nodes[0]->area == iap->area1 ) ) )
{
break;
}
}
if( i != interAreaPortals.Num() )
{
continue; // already emited
}
iap = &interAreaPortals.Alloc();
if( side->planenum == p->onnode->planenum )
{
iap->area0 = p->nodes[0]->area;
iap->area1 = p->nodes[1]->area;
}
else
{
iap->area0 = p->nodes[1]->area;
iap->area1 = p->nodes[0]->area;
}
iap->side = side;
}
// RB: check area portal triangles
idList<mapTri_t*> apTriangles;
for( p = node->portals ; p ; p = p->next[s] )
{
node_t* other;
s = ( p->nodes[1] == node );
other = p->nodes[!s];
if( other->opaque )
{
continue;
}
// only report areas going from lower number to higher number
// so we don't report the portal twice
if( other->area <= node->area )
{
continue;
}
FindTrianglesForPortal( p, apTriangles );
if( apTriangles.Num() < 2 )
{
//common->Warning( "FindTrianglesForPortal failed at %s", p->winding->GetCenter().ToString() );
continue;
}
// see if we have created this portal before
for( i = 0; i < interAreaPortals.Num(); i++ )
{
iap = &interAreaPortals[i];
if( apTriangles[0]->polygonId == iap->polygonId &&
( ( p->nodes[0]->area == iap->area0 && p->nodes[1]->area == iap->area1 )
|| ( p->nodes[1]->area == iap->area0 && p->nodes[0]->area == iap->area1 ) ) )
{
break;
}
}
if( i != interAreaPortals.Num() )
{
continue; // already emited
}
iap = &interAreaPortals.Alloc();
if( apTriangles[0]->planeNum == p->onnode->planenum )
{
iap->area0 = p->nodes[0]->area;
iap->area1 = p->nodes[1]->area;
}
else
{
iap->area0 = p->nodes[1]->area;
iap->area1 = p->nodes[0]->area;
}
iap->polygonId = apTriangles[0]->polygonId;
// merge triangles to a new winding
for( int j = 0; j < apTriangles.Num(); j++ )
{
mapTri_t* tri = apTriangles[j];
idVec3 planeNormal = dmapGlobals.mapPlanes[ tri->planeNum].Normal();
for( int k = 0; k < 3; k++ )
{
iap->w.AddToConvexHull( tri->v[k].xyz, planeNormal );
}
}
}
// RB end
}
/*
=============
FloodAreas
Mark each leaf with an area, bounded by CONTENTS_AREAPORTAL
Sets e->areas.numAreas
=============
*/
void FloodAreas( uEntity_t* e )
{
common->Printf( "--- FloodAreas ---\n" );
// set all areas to -1
ClearAreas_r( e->tree->headnode );
// flood fill from non-opaque areas
c_areas = 0;
FindAreas_r( e->tree->headnode );
common->Printf( "%5i areas\n", c_areas );
e->numAreas = c_areas;
// make sure we got all of them
CheckAreas_r( e->tree->headnode );
// identify all portals between areas if this is the world
if( e == &dmapGlobals.uEntities[0] )
{
interAreaPortals.Clear();
FindInterAreaPortals_r( e->tree->headnode );
}
}
/*
======================================================
FILL OUTSIDE
======================================================
*/
static int c_outside;
static int c_inside;
static int c_solid;
void FillOutside_r( node_t* node )
{
if( node->planenum != PLANENUM_LEAF )
{
FillOutside_r( node->children[0] );
FillOutside_r( node->children[1] );
return;
}
// anything not reachable by an entity
// can be filled away
if( !node->occupied )
{
if( !node->opaque )
{
c_outside++;
node->opaque = true;
}
else
{
c_solid++;
}
}
else
{
c_inside++;
}
}
/*
=============
FillOutside
Fill (set node->opaque = true) all nodes that can't be reached by entities
=============
*/
void FillOutside( uEntity_t* e )
{
c_outside = 0;
c_inside = 0;
c_solid = 0;
common->Printf( "--- FillOutside ---\n" );
FillOutside_r( e->tree->headnode );
common->Printf( "%5i solid leafs\n", c_solid );
common->Printf( "%5i leafs filled\n", c_outside );
common->Printf( "%5i inside leafs\n", c_inside );
}
| raynorpat/RBDOOM-3-BFG | neo/tools/compilers/dmap/portals.cpp | C++ | gpl-3.0 | 23,955 |
-----------------------------------
-- Area: King Ranperre's Tomb
-- NPC: Tombstone
-- Involved in Quest: Grave Concerns
-- @pos 1 0.1 -101 190
-----------------------------------
package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/zones/King_Ranperres_Tomb/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,GRAVE_CONCERNS) == QUEST_ACCEPTED) then
if(trade:hasItemQty(567,1) and trade:getItemCount() == 1) then -- Trade Well Water
player:startEvent(0x0003);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local currentMission = player:getCurrentMission(SANDORIA);
local MissionStatus = player:getVar("MissionStatus");
local BatHuntCompleted = player:hasCompletedMission(SANDORIA,BAT_HUNT); -- quest repeatable and clicking tombstone should not produce cutscene on repeat
local X = npc:getXPos();
local Z = npc:getZPos();
if(X >= -1 and X <= 1 and Z >= -106 and Z <= -102) then
if(player:getCurrentMission(SANDORIA) == BAT_HUNT and MissionStatus <= 1 and BatHuntCompleted == false) then -- Bug caused players to have MissionStatus 1 at start, so self-healing is necessary.
player:startEvent(0x0004);
else
player:startEvent(0x0002);
end
elseif(currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 2) then
player:startEvent(0x0008);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0004) then
player:setVar("MissionStatus",2);
elseif(csid == 0x0002) then
local graveConcerns = player:getQuestStatus(SANDORIA,GRAVE_CONCERNS);
if(graveConcerns == QUEST_ACCEPTED and player:hasItem(547) == false and player:hasItem(567) == false) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,547); -- Tomb Waterskin
else
player:addItem(547);
player:messageSpecial(ITEM_OBTAINED,547); -- Tomb Waterskin
end
end
elseif(csid == 0x0003) then
player:tradeComplete();
player:setVar("OfferingWaterOK",1);
player:addItem(547);
player:messageSpecial(ITEM_OBTAINED,547); -- Tomb Waterskin
elseif(csid == 0x0008) then
player:setVar("MissionStatus",3);
player:addKeyItem(ANCIENT_SANDORIAN_BOOK);
player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_SANDORIAN_BOOK);
end
end;
| b03605079/darkstar | scripts/zones/King_Ranperres_Tomb/npcs/Tombstone.lua | Lua | gpl-3.0 | 3,054 |
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'committer',
'version': '1.0'}
DOCUMENTATION = """
---
module: ec2_asg
short_description: Create or delete AWS Autoscaling Groups
description:
- Can create or delete AWS Autoscaling Groups
- Works with the ec2_lc module to manage Launch Configurations
version_added: "1.6"
author: "Gareth Rushgrove (@garethr)"
options:
state:
description:
- register or deregister the instance
required: false
choices: ['present', 'absent']
default: present
name:
description:
- Unique name for group to be created or deleted
required: true
load_balancers:
description:
- List of ELB names to use for the group
required: false
availability_zones:
description:
- List of availability zone names in which to create the group. Defaults to all the availability zones in the region if vpc_zone_identifier is not set.
required: false
launch_config_name:
description:
- Name of the Launch configuration to use for the group. See the ec2_lc module for managing these.
required: true
min_size:
description:
- Minimum number of instances in group, if unspecified then the current group value will be used.
required: false
max_size:
description:
- Maximum number of instances in group, if unspecified then the current group value will be used.
required: false
placement_group:
description:
- Physical location of your cluster placement group created in Amazon EC2.
required: false
version_added: "2.3"
default: None
desired_capacity:
description:
- Desired number of instances in group, if unspecified then the current group value will be used.
required: false
replace_all_instances:
description:
- In a rolling fashion, replace all instances with an old launch configuration with one from the current launch configuration.
required: false
version_added: "1.8"
default: False
replace_batch_size:
description:
- Number of instances you'd like to replace at a time. Used with replace_all_instances.
required: false
version_added: "1.8"
default: 1
replace_instances:
description:
- List of instance_ids belonging to the named ASG that you would like to terminate and be replaced with instances matching the current launch configuration.
required: false
version_added: "1.8"
default: None
lc_check:
description:
- Check to make sure instances that are being replaced with replace_instances do not already have the current launch_config.
required: false
version_added: "1.8"
default: True
vpc_zone_identifier:
description:
- List of VPC subnets to use
required: false
default: None
tags:
description:
- A list of tags to add to the Auto Scale Group. Optional key is 'propagate_at_launch', which defaults to true.
required: false
default: None
version_added: "1.7"
health_check_period:
description:
- Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.
required: false
default: 500 seconds
version_added: "1.7"
health_check_type:
description:
- The service you want the health status from, Amazon EC2 or Elastic Load Balancer.
required: false
default: EC2
version_added: "1.7"
choices: ['EC2', 'ELB']
default_cooldown:
description:
- The number of seconds after a scaling activity completes before another can begin.
required: false
default: 300 seconds
version_added: "2.0"
wait_timeout:
description:
- how long before wait instances to become viable when replaced. Used in conjunction with instance_ids option.
default: 300
version_added: "1.8"
wait_for_instances:
description:
- Wait for the ASG instances to be in a ready state before exiting. If instances are behind an ELB, it will wait until the ELB determines all instances have a lifecycle_state of "InService" and a health_status of "Healthy".
version_added: "1.9"
default: yes
required: False
termination_policies:
description:
- An ordered list of criteria used for selecting instances to be removed from the Auto Scaling group when reducing capacity.
- For 'Default', when used to create a new autoscaling group, the "Default"i value is used. When used to change an existent autoscaling group, the current termination policies are maintained.
required: false
default: Default
choices: ['OldestInstance', 'NewestInstance', 'OldestLaunchConfiguration', 'ClosestToNextInstanceHour', 'Default']
version_added: "2.0"
notification_topic:
description:
- A SNS topic ARN to send auto scaling notifications to.
default: None
required: false
version_added: "2.2"
notification_types:
description:
- A list of auto scaling events to trigger notifications on.
default: ['autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR', 'autoscaling:EC2_INSTANCE_TERMINATE', 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR']
required: false
version_added: "2.2"
suspend_processes:
description:
- A list of scaling processes to suspend.
required: False
default: []
choices: ['Launch', 'Terminate', 'HealthCheck', 'ReplaceUnhealthy', 'AZRebalance', 'AlarmNotification', 'ScheduledActions', 'AddToLoadBalancer']
version_added: "2.3"
extends_documentation_fragment:
- aws
- ec2
"""
EXAMPLES = '''
# Basic configuration
- ec2_asg:
name: special
load_balancers: [ 'lb1', 'lb2' ]
availability_zones: [ 'eu-west-1a', 'eu-west-1b' ]
launch_config_name: 'lc-1'
min_size: 1
max_size: 10
desired_capacity: 5
vpc_zone_identifier: [ 'subnet-abcd1234', 'subnet-1a2b3c4d' ]
tags:
- environment: production
propagate_at_launch: no
# Rolling ASG Updates
Below is an example of how to assign a new launch config to an ASG and terminate old instances.
All instances in "myasg" that do not have the launch configuration named "my_new_lc" will be terminated in
a rolling fashion with instances using the current launch configuration, "my_new_lc".
This could also be considered a rolling deploy of a pre-baked AMI.
If this is a newly created group, the instances will not be replaced since all instances
will have the current launch configuration.
- name: create launch config
ec2_lc:
name: my_new_lc
image_id: ami-lkajsf
key_name: mykey
region: us-east-1
security_groups: sg-23423
instance_type: m1.small
assign_public_ip: yes
- ec2_asg:
name: myasg
launch_config_name: my_new_lc
health_check_period: 60
health_check_type: ELB
replace_all_instances: yes
min_size: 5
max_size: 5
desired_capacity: 5
region: us-east-1
To only replace a couple of instances instead of all of them, supply a list
to "replace_instances":
- ec2_asg:
name: myasg
launch_config_name: my_new_lc
health_check_period: 60
health_check_type: ELB
replace_instances:
- i-b345231
- i-24c2931
min_size: 5
max_size: 5
desired_capacity: 5
region: us-east-1
'''
import time
import logging as log
import traceback
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
log.getLogger('boto').setLevel(log.CRITICAL)
#log.basicConfig(filename='/tmp/ansible_ec2_asg.log',level=log.DEBUG, format='%(asctime)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
try:
import boto.ec2.autoscale
from boto.ec2.autoscale import AutoScaleConnection, AutoScalingGroup, Tag
from boto.exception import BotoServerError
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
ASG_ATTRIBUTES = ('availability_zones', 'default_cooldown', 'desired_capacity',
'health_check_period', 'health_check_type', 'launch_config_name',
'load_balancers', 'max_size', 'min_size', 'name', 'placement_group',
'termination_policies', 'vpc_zone_identifier')
INSTANCE_ATTRIBUTES = ('instance_id', 'health_status', 'lifecycle_state', 'launch_config_name')
def enforce_required_arguments(module):
''' As many arguments are not required for autoscale group deletion
they cannot be mandatory arguments for the module, so we enforce
them here '''
missing_args = []
for arg in ('min_size', 'max_size', 'launch_config_name'):
if module.params[arg] is None:
missing_args.append(arg)
if missing_args:
module.fail_json(msg="Missing required arguments for autoscaling group create/update: %s" % ",".join(missing_args))
def get_properties(autoscaling_group):
properties = dict((attr, getattr(autoscaling_group, attr)) for attr in ASG_ATTRIBUTES)
# Ugly hack to make this JSON-serializable. We take a list of boto Tag
# objects and replace them with a dict-representation. Needed because the
# tags are included in ansible's return value (which is jsonified)
if 'tags' in properties and isinstance(properties['tags'], list):
serializable_tags = {}
for tag in properties['tags']:
serializable_tags[tag.key] = [tag.value, tag.propagate_at_launch]
properties['tags'] = serializable_tags
properties['healthy_instances'] = 0
properties['in_service_instances'] = 0
properties['unhealthy_instances'] = 0
properties['pending_instances'] = 0
properties['viable_instances'] = 0
properties['terminating_instances'] = 0
instance_facts = {}
if autoscaling_group.instances:
properties['instances'] = [i.instance_id for i in autoscaling_group.instances]
for i in autoscaling_group.instances:
instance_facts[i.instance_id] = {'health_status': i.health_status,
'lifecycle_state': i.lifecycle_state,
'launch_config_name': i.launch_config_name }
if i.health_status == 'Healthy' and i.lifecycle_state == 'InService':
properties['viable_instances'] += 1
if i.health_status == 'Healthy':
properties['healthy_instances'] += 1
else:
properties['unhealthy_instances'] += 1
if i.lifecycle_state == 'InService':
properties['in_service_instances'] += 1
if i.lifecycle_state == 'Terminating':
properties['terminating_instances'] += 1
if i.lifecycle_state == 'Pending':
properties['pending_instances'] += 1
properties['instance_facts'] = instance_facts
properties['load_balancers'] = autoscaling_group.load_balancers
if getattr(autoscaling_group, "tags", None):
properties['tags'] = dict((t.key, t.value) for t in autoscaling_group.tags)
return properties
def elb_dreg(asg_connection, module, group_name, instance_id):
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
as_group = asg_connection.get_all_groups(names=[group_name])[0]
wait_timeout = module.params.get('wait_timeout')
props = get_properties(as_group)
count = 1
if as_group.load_balancers and as_group.health_check_type == 'ELB':
try:
elb_connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params)
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
else:
return
for lb in as_group.load_balancers:
elb_connection.deregister_instances(lb, instance_id)
log.debug("De-registering {0} from ELB {1}".format(instance_id, lb))
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and count > 0:
count = 0
for lb in as_group.load_balancers:
lb_instances = elb_connection.describe_instance_health(lb)
for i in lb_instances:
if i.instance_id == instance_id and i.state == "InService":
count += 1
log.debug("{0}: {1}, {2}".format(i.instance_id, i.state, i.description))
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for instance to deregister. {0}".format(time.asctime()))
def elb_healthy(asg_connection, elb_connection, module, group_name):
healthy_instances = set()
as_group = asg_connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
# get healthy, inservice instances from ASG
instances = []
for instance, settings in props['instance_facts'].items():
if settings['lifecycle_state'] == 'InService' and settings['health_status'] == 'Healthy':
instances.append(instance)
log.debug("ASG considers the following instances InService and Healthy: {0}".format(instances))
log.debug("ELB instance status:")
for lb in as_group.load_balancers:
# we catch a race condition that sometimes happens if the instance exists in the ASG
# but has not yet show up in the ELB
try:
lb_instances = elb_connection.describe_instance_health(lb, instances=instances)
except boto.exception.BotoServerError as e:
if e.error_code == 'InvalidInstance':
return None
module.fail_json(msg=str(e))
for i in lb_instances:
if i.state == "InService":
healthy_instances.add(i.instance_id)
log.debug("{0}: {1}".format(i.instance_id, i.state))
return len(healthy_instances)
def wait_for_elb(asg_connection, module, group_name):
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
wait_timeout = module.params.get('wait_timeout')
# if the health_check_type is ELB, we want to query the ELBs directly for instance
# status as to avoid health_check_grace period that is awarded to ASG instances
as_group = asg_connection.get_all_groups(names=[group_name])[0]
if as_group.load_balancers and as_group.health_check_type == 'ELB':
log.debug("Waiting for ELB to consider instances healthy.")
try:
elb_connection = connect_to_aws(boto.ec2.elb, region, **aws_connect_params)
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
wait_timeout = time.time() + wait_timeout
healthy_instances = elb_healthy(asg_connection, elb_connection, module, group_name)
while healthy_instances < as_group.min_size and wait_timeout > time.time():
healthy_instances = elb_healthy(asg_connection, elb_connection, module, group_name)
log.debug("ELB thinks {0} instances are healthy.".format(healthy_instances))
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for ELB instances to be healthy. %s" % time.asctime())
log.debug("Waiting complete. ELB thinks {0} instances are healthy.".format(healthy_instances))
def suspend_processes(as_group, module):
suspend_processes = set(module.params.get('suspend_processes'))
try:
suspended_processes = set([p.process_name for p in as_group.suspended_processes])
except AttributeError:
# New ASG being created, no suspended_processes defined yet
suspended_processes = set()
if suspend_processes == suspended_processes:
return False
resume_processes = list(suspended_processes - suspend_processes)
if resume_processes:
as_group.resume_processes(resume_processes)
if suspend_processes:
as_group.suspend_processes(list(suspend_processes))
return True
def create_autoscaling_group(connection, module):
group_name = module.params.get('name')
load_balancers = module.params['load_balancers']
availability_zones = module.params['availability_zones']
launch_config_name = module.params.get('launch_config_name')
min_size = module.params['min_size']
max_size = module.params['max_size']
placement_group = module.params.get('placement_group')
desired_capacity = module.params.get('desired_capacity')
vpc_zone_identifier = module.params.get('vpc_zone_identifier')
set_tags = module.params.get('tags')
health_check_period = module.params.get('health_check_period')
health_check_type = module.params.get('health_check_type')
default_cooldown = module.params.get('default_cooldown')
wait_for_instances = module.params.get('wait_for_instances')
as_groups = connection.get_all_groups(names=[group_name])
wait_timeout = module.params.get('wait_timeout')
termination_policies = module.params.get('termination_policies')
notification_topic = module.params.get('notification_topic')
notification_types = module.params.get('notification_types')
if not vpc_zone_identifier and not availability_zones:
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
try:
ec2_connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
elif vpc_zone_identifier:
vpc_zone_identifier = ','.join(vpc_zone_identifier)
asg_tags = []
for tag in set_tags:
for k,v in tag.items():
if k !='propagate_at_launch':
asg_tags.append(Tag(key=k,
value=v,
propagate_at_launch=bool(tag.get('propagate_at_launch', True)),
resource_id=group_name))
if not as_groups:
if not vpc_zone_identifier and not availability_zones:
availability_zones = module.params['availability_zones'] = [zone.name for zone in ec2_connection.get_all_zones()]
enforce_required_arguments(module)
launch_configs = connection.get_all_launch_configurations(names=[launch_config_name])
if len(launch_configs) == 0:
module.fail_json(msg="No launch config found with name %s" % launch_config_name)
ag = AutoScalingGroup(
group_name=group_name,
load_balancers=load_balancers,
availability_zones=availability_zones,
launch_config=launch_configs[0],
min_size=min_size,
max_size=max_size,
placement_group=placement_group,
desired_capacity=desired_capacity,
vpc_zone_identifier=vpc_zone_identifier,
connection=connection,
tags=asg_tags,
health_check_period=health_check_period,
health_check_type=health_check_type,
default_cooldown=default_cooldown,
termination_policies=termination_policies)
try:
connection.create_auto_scaling_group(ag)
suspend_processes(ag, module)
if wait_for_instances:
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_capacity, 'viable_instances')
wait_for_elb(connection, module, group_name)
if notification_topic:
ag.put_notification_configuration(notification_topic, notification_types)
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
changed = True
return(changed, asg_properties)
except BotoServerError as e:
module.fail_json(msg="Failed to create Autoscaling Group: %s" % str(e), exception=traceback.format_exc(e))
else:
as_group = as_groups[0]
changed = False
if suspend_processes(as_group, module):
changed = True
for attr in ASG_ATTRIBUTES:
if module.params.get(attr, None) is not None:
module_attr = module.params.get(attr)
if attr == 'vpc_zone_identifier':
module_attr = ','.join(module_attr)
group_attr = getattr(as_group, attr)
# we do this because AWS and the module may return the same list
# sorted differently
if attr != 'termination_policies':
try:
module_attr.sort()
except:
pass
try:
group_attr.sort()
except:
pass
if group_attr != module_attr:
changed = True
setattr(as_group, attr, module_attr)
if len(set_tags) > 0:
have_tags = {}
want_tags = {}
for tag in asg_tags:
want_tags[tag.key] = [tag.value, tag.propagate_at_launch]
dead_tags = []
for tag in as_group.tags:
have_tags[tag.key] = [tag.value, tag.propagate_at_launch]
if tag.key not in want_tags:
changed = True
dead_tags.append(tag)
if dead_tags != []:
connection.delete_tags(dead_tags)
if have_tags != want_tags:
changed = True
connection.create_or_update_tags(asg_tags)
# handle loadbalancers separately because None != []
load_balancers = module.params.get('load_balancers') or []
if load_balancers and as_group.load_balancers != load_balancers:
changed = True
as_group.load_balancers = module.params.get('load_balancers')
if changed:
try:
as_group.update()
except BotoServerError as e:
module.fail_json(msg="Failed to update Autoscaling Group: %s" % str(e), exception=traceback.format_exc(e))
if notification_topic:
try:
as_group.put_notification_configuration(notification_topic, notification_types)
except BotoServerError as e:
module.fail_json(msg="Failed to update Autoscaling Group notifications: %s" % str(e), exception=traceback.format_exc(e))
if wait_for_instances:
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_capacity, 'viable_instances')
wait_for_elb(connection, module, group_name)
try:
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
except BotoServerError as e:
module.fail_json(msg="Failed to read existing Autoscaling Groups: %s" % str(e), exception=traceback.format_exc(e))
return(changed, asg_properties)
def delete_autoscaling_group(connection, module):
group_name = module.params.get('name')
notification_topic = module.params.get('notification_topic')
if notification_topic:
ag.delete_notification_configuration(notification_topic)
groups = connection.get_all_groups(names=[group_name])
if groups:
group = groups[0]
group.max_size = 0
group.min_size = 0
group.desired_capacity = 0
group.update()
instances = True
while instances:
tmp_groups = connection.get_all_groups(names=[group_name])
if tmp_groups:
tmp_group = tmp_groups[0]
if not tmp_group.instances:
instances = False
time.sleep(10)
group.delete()
while len(connection.get_all_groups(names=[group_name])):
time.sleep(5)
changed=True
return changed
else:
changed=False
return changed
def get_chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]
def update_size(group, max_size, min_size, dc):
log.debug("setting ASG sizes")
log.debug("minimum size: {0}, desired_capacity: {1}, max size: {2}".format(min_size, dc, max_size ))
group.max_size = max_size
group.min_size = min_size
group.desired_capacity = dc
group.update()
def replace(connection, module):
batch_size = module.params.get('replace_batch_size')
wait_timeout = module.params.get('wait_timeout')
group_name = module.params.get('name')
max_size = module.params.get('max_size')
min_size = module.params.get('min_size')
desired_capacity = module.params.get('desired_capacity')
lc_check = module.params.get('lc_check')
replace_instances = module.params.get('replace_instances')
as_group = connection.get_all_groups(names=[group_name])[0]
wait_for_new_inst(module, connection, group_name, wait_timeout, as_group.min_size, 'viable_instances')
props = get_properties(as_group)
instances = props['instances']
if replace_instances:
instances = replace_instances
#check if min_size/max_size/desired capacity have been specified and if not use ASG values
if min_size is None:
min_size = as_group.min_size
if max_size is None:
max_size = as_group.max_size
if desired_capacity is None:
desired_capacity = as_group.desired_capacity
# check to see if instances are replaceable if checking launch configs
new_instances, old_instances = get_instances_by_lc(props, lc_check, instances)
num_new_inst_needed = desired_capacity - len(new_instances)
if lc_check:
if num_new_inst_needed == 0 and old_instances:
log.debug("No new instances needed, but old instances are present. Removing old instances")
terminate_batch(connection, module, old_instances, instances, True)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
changed = True
return(changed, props)
# we don't want to spin up extra instances if not necessary
if num_new_inst_needed < batch_size:
log.debug("Overriding batch size to {0}".format(num_new_inst_needed))
batch_size = num_new_inst_needed
if not old_instances:
changed = False
return(changed, props)
# set temporary settings and wait for them to be reached
# This should get overwritten if the number of instances left is less than the batch size.
as_group = connection.get_all_groups(names=[group_name])[0]
update_size(as_group, max_size + batch_size, min_size + batch_size, desired_capacity + batch_size)
wait_for_new_inst(module, connection, group_name, wait_timeout, as_group.min_size, 'viable_instances')
wait_for_elb(connection, module, group_name)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
instances = props['instances']
if replace_instances:
instances = replace_instances
log.debug("beginning main loop")
for i in get_chunks(instances, batch_size):
# break out of this loop if we have enough new instances
break_early, desired_size, term_instances = terminate_batch(connection, module, i, instances, False)
wait_for_term_inst(connection, module, term_instances)
wait_for_new_inst(module, connection, group_name, wait_timeout, desired_size, 'viable_instances')
wait_for_elb(connection, module, group_name)
as_group = connection.get_all_groups(names=[group_name])[0]
if break_early:
log.debug("breaking loop")
break
update_size(as_group, max_size, min_size, desired_capacity)
as_group = connection.get_all_groups(names=[group_name])[0]
asg_properties = get_properties(as_group)
log.debug("Rolling update complete.")
changed=True
return(changed, asg_properties)
def get_instances_by_lc(props, lc_check, initial_instances):
new_instances = []
old_instances = []
# old instances are those that have the old launch config
if lc_check:
for i in props['instances']:
if props['instance_facts'][i]['launch_config_name'] == props['launch_config_name']:
new_instances.append(i)
else:
old_instances.append(i)
else:
log.debug("Comparing initial instances with current: {0}".format(initial_instances))
for i in props['instances']:
if i not in initial_instances:
new_instances.append(i)
else:
old_instances.append(i)
log.debug("New instances: {0}, {1}".format(len(new_instances), new_instances))
log.debug("Old instances: {0}, {1}".format(len(old_instances), old_instances))
return new_instances, old_instances
def list_purgeable_instances(props, lc_check, replace_instances, initial_instances):
instances_to_terminate = []
instances = ( inst_id for inst_id in replace_instances if inst_id in props['instances'])
# check to make sure instances given are actually in the given ASG
# and they have a non-current launch config
if lc_check:
for i in instances:
if props['instance_facts'][i]['launch_config_name'] != props['launch_config_name']:
instances_to_terminate.append(i)
else:
for i in instances:
if i in initial_instances:
instances_to_terminate.append(i)
return instances_to_terminate
def terminate_batch(connection, module, replace_instances, initial_instances, leftovers=False):
batch_size = module.params.get('replace_batch_size')
min_size = module.params.get('min_size')
desired_capacity = module.params.get('desired_capacity')
group_name = module.params.get('name')
wait_timeout = int(module.params.get('wait_timeout'))
lc_check = module.params.get('lc_check')
decrement_capacity = False
break_loop = False
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
desired_size = as_group.min_size
new_instances, old_instances = get_instances_by_lc(props, lc_check, initial_instances)
num_new_inst_needed = desired_capacity - len(new_instances)
# check to make sure instances given are actually in the given ASG
# and they have a non-current launch config
instances_to_terminate = list_purgeable_instances(props, lc_check, replace_instances, initial_instances)
log.debug("new instances needed: {0}".format(num_new_inst_needed))
log.debug("new instances: {0}".format(new_instances))
log.debug("old instances: {0}".format(old_instances))
log.debug("batch instances: {0}".format(",".join(instances_to_terminate)))
if num_new_inst_needed == 0:
decrement_capacity = True
if as_group.min_size != min_size:
as_group.min_size = min_size
as_group.update()
log.debug("Updating minimum size back to original of {0}".format(min_size))
#if are some leftover old instances, but we are already at capacity with new ones
# we don't want to decrement capacity
if leftovers:
decrement_capacity = False
break_loop = True
instances_to_terminate = old_instances
desired_size = min_size
log.debug("No new instances needed")
if num_new_inst_needed < batch_size and num_new_inst_needed !=0 :
instances_to_terminate = instances_to_terminate[:num_new_inst_needed]
decrement_capacity = False
break_loop = False
log.debug("{0} new instances needed".format(num_new_inst_needed))
log.debug("decrementing capacity: {0}".format(decrement_capacity))
for instance_id in instances_to_terminate:
elb_dreg(connection, module, group_name, instance_id)
log.debug("terminating instance: {0}".format(instance_id))
connection.terminate_instance(instance_id, decrement_capacity=decrement_capacity)
# we wait to make sure the machines we marked as Unhealthy are
# no longer in the list
return break_loop, desired_size, instances_to_terminate
def wait_for_term_inst(connection, module, term_instances):
batch_size = module.params.get('replace_batch_size')
wait_timeout = module.params.get('wait_timeout')
group_name = module.params.get('name')
lc_check = module.params.get('lc_check')
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
count = 1
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and count > 0:
log.debug("waiting for instances to terminate")
count = 0
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
instance_facts = props['instance_facts']
instances = ( i for i in instance_facts if i in term_instances)
for i in instances:
lifecycle = instance_facts[i]['lifecycle_state']
health = instance_facts[i]['health_status']
log.debug("Instance {0} has state of {1},{2}".format(i,lifecycle,health ))
if lifecycle == 'Terminating' or health == 'Unhealthy':
count += 1
time.sleep(10)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for old instances to terminate. %s" % time.asctime())
def wait_for_new_inst(module, connection, group_name, wait_timeout, desired_size, prop):
# make sure we have the latest stats after that last loop.
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
log.debug("Waiting for {0} = {1}, currently {2}".format(prop, desired_size, props[prop]))
# now we make sure that we have enough instances in a viable state
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time() and desired_size > props[prop]:
log.debug("Waiting for {0} = {1}, currently {2}".format(prop, desired_size, props[prop]))
time.sleep(10)
as_group = connection.get_all_groups(names=[group_name])[0]
props = get_properties(as_group)
if wait_timeout <= time.time():
# waiting took too long
module.fail_json(msg = "Waited too long for new instances to become viable. %s" % time.asctime())
log.debug("Reached {0}: {1}".format(prop, desired_size))
return props
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
name=dict(required=True, type='str'),
load_balancers=dict(type='list'),
availability_zones=dict(type='list'),
launch_config_name=dict(type='str'),
min_size=dict(type='int'),
max_size=dict(type='int'),
placement_group=dict(type='str'),
desired_capacity=dict(type='int'),
vpc_zone_identifier=dict(type='list'),
replace_batch_size=dict(type='int', default=1),
replace_all_instances=dict(type='bool', default=False),
replace_instances=dict(type='list', default=[]),
lc_check=dict(type='bool', default=True),
wait_timeout=dict(type='int', default=300),
state=dict(default='present', choices=['present', 'absent']),
tags=dict(type='list', default=[]),
health_check_period=dict(type='int', default=300),
health_check_type=dict(default='EC2', choices=['EC2', 'ELB']),
default_cooldown=dict(type='int', default=300),
wait_for_instances=dict(type='bool', default=True),
termination_policies=dict(type='list', default='Default'),
notification_topic=dict(type='str', default=None),
notification_types=dict(type='list', default=[
'autoscaling:EC2_INSTANCE_LAUNCH',
'autoscaling:EC2_INSTANCE_LAUNCH_ERROR',
'autoscaling:EC2_INSTANCE_TERMINATE',
'autoscaling:EC2_INSTANCE_TERMINATE_ERROR'
]),
suspend_processes=dict(type='list', default=[])
),
)
module = AnsibleModule(
argument_spec=argument_spec,
mutually_exclusive = [['replace_all_instances', 'replace_instances']]
)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
state = module.params.get('state')
replace_instances = module.params.get('replace_instances')
replace_all_instances = module.params.get('replace_all_instances')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
try:
connection = connect_to_aws(boto.ec2.autoscale, region, **aws_connect_params)
if not connection:
module.fail_json(msg="failed to connect to AWS for the given region: %s" % str(region))
except boto.exception.NoAuthHandlerFound as e:
module.fail_json(msg=str(e))
changed = create_changed = replace_changed = False
if state == 'present':
create_changed, asg_properties=create_autoscaling_group(connection, module)
elif state == 'absent':
changed = delete_autoscaling_group(connection, module)
module.exit_json( changed = changed )
if replace_all_instances or replace_instances:
replace_changed, asg_properties=replace(connection, module)
if create_changed or replace_changed:
changed = True
module.exit_json( changed = changed, **asg_properties )
if __name__ == '__main__':
main()
| zahodi/ansible | lib/ansible/modules/cloud/amazon/ec2_asg.py | Python | gpl-3.0 | 38,091 |
using EloBuddy;
using LeagueSharp.Common;
namespace Nasus
{
using LeagueSharp.Common;
public class MenuInit
{
public static Menu Menu;
public static void Initialize()
{
Menu = new Menu("Nasus - The Crazy Dog", "L# Nasus", true);
var orbwalkerMenu = new Menu("Orbwalker", "orbwalker");
Standards.Orbwalker = new Orbwalking.Orbwalker(orbwalkerMenu);
Menu.AddSubMenu(orbwalkerMenu);
TargetSelector.AddToMenu(TargetSelectorMenu());
#region Combo Menu
var comboMenu = Menu.AddSubMenu(new Menu("Combo", "MenuCombo"));
{
comboMenu
.AddItem(new MenuItem("Combo.Use.Q", "Use Q").SetValue(true));
comboMenu
.AddItem(new MenuItem("Combo.Use.W", "Use W").SetValue(true));
comboMenu
.AddItem(new MenuItem("Combo.Use.E", "Use E").SetValue(true));
comboMenu
.AddItem(new MenuItem("Combo.Use.R", "Use R").SetValue(true));
comboMenu
.AddItem(new MenuItem("Combo.Min.HP.Use.R", "HP to use R").SetValue(new Slider(35)));
}
#endregion
#region Harass Menu
var harassMenu = Menu.AddSubMenu(new Menu("Harass", "MenuHarass"));
{
harassMenu
.AddItem(new MenuItem("Harass.Use.Q", "Use Q").SetValue(true));
harassMenu
.AddItem(new MenuItem("Harass.Use.W", "Use W").SetValue(true));
harassMenu
.AddItem(new MenuItem("Harass.Use.E", "Use E").SetValue(true));
}
#endregion
#region Lane Clear
var laneClearMenu = Menu.AddSubMenu(new Menu("Lane Clear", "MenuLaneClear"));
{
laneClearMenu
.AddItem(new MenuItem("LaneClear.Use.Q", "Use Q").SetValue(true));
laneClearMenu
.AddItem(new MenuItem("LaneClear.Use.E", "Use E").SetValue(true));
}
#endregion
#region Last Hit
var lastHitMenu = Menu.AddSubMenu(new Menu("Stack Siphoning Strike", "MenuStackQ"));
{
lastHitMenu
.AddItem(new MenuItem("Use.StackQ", "Stack").SetValue(true));
}
#endregion
Menu.AddItem(new MenuItem("devCredits", "Dev by @ TwoHam"));
Menu.AddToMainMenu();
}
private static Menu TargetSelectorMenu()
{
return Menu.AddSubMenu(new Menu("Target Selector", "TargetSelector"));
}
}
}
| tk8226/YamiPortAIO-v2 | Core/Champion Ports/Nasus/Nasus The Crazy Dog/MenuInit.cs | C# | gpl-3.0 | 2,750 |
import lxml.html as l
import requests
def key_char_parse(char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.cssselect('.mainbox .charimg img')[0].attrib['src']
gender = root.cssselect('.chardetails table thead tr td abbr')[0].attrib['title']
try:
bloodtype = root.cssselect('.chardetails table thead tr td span')[0].text
except IndexError:
bloodtype = None
table = root.cssselect('.chardetails table')[0]
for row in table:
if row.tag == 'tr':
if len(row) == 2:
try:
key = row[0][0].text
except IndexError:
key = row[0].text
value = None
try:
if row[1][0].tag == 'a':
value = row[1][0].text
else:
value = []
for span in row[1]:
if 'charspoil_1' in span.classes:
tag = 'minor spoiler'
elif 'charspoil_2' in span.classes:
tag = 'spoiler'
elif 'sexual' in span.classes:
tag = 'sexual trait'
else:
tag = None
value.append({'value': span[1].text, 'tag': tag})
except IndexError:
value = row[1].text
if key == 'Visual novels':
value = []
for span in row[1]:
if span.tag == 'span':
value.append(span.text + span[0].text)
desc = root.cssselect('.chardetails table td.chardesc')[0][1].text
character = {
'URL': url,
'Name': name,
'Name_J': kanji_name,
'Image': img,
'Gender': gender,
'Blood_Type': bloodtype,
'Description': desc
}
return character
| aurora-pro/apex-sigma | sigma/plugins/fun/vn_char.py | Python | gpl-3.0 | 2,210 |
<?php
// Heading
$_['heading_title'] = 'OpenBay Pro';
// Text
$_['text_module'] = 'フィード設定';
$_['text_installed'] = 'OpenBayProモジュールがインストールされました。 拡張機能 -> OpenBay Proで利用することができます'; | huylv-hust/opencart | admin/language/japanese/feed/openbaypro.php | PHP | gpl-3.0 | 264 |
/*
* Copyright (C) 2009 Lalit Pant <pant.lalit@gmail.com>
*
* The contents of this file are subject to the GNU General Public License
* Version 3 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.gnu.org/copyleft/gpl.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
*/
package net.kogics.kojo
package staging
//import org.junit.After
//import org.junit.Before
import org.junit.Test
import org.junit.Assert._
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.{CountDownLatch, TimeUnit}
import net.kogics.kojo.core.RunContext
import net.kogics.kojo.util._
/* Testing policy
*
* Every member of the interface shall be tested, preferably for effect but at
* least for executability.
*
* The implementation is tested as needed but is generally considered to be
* sufficiently correct if the interface works correctly.
*
*/
// cargo coding off CodePaneTest
class StagingTestBase extends KojoTestBase {
initNetbeansDirs()
val runCtx = new TestRunContext(this)
val codeRunner = new xscala.ScalaCodeRunner(runCtx, SpriteCanvas.instance)
val pane = new javax.swing.JEditorPane()
val Delimiter = ""
var latch: CountDownLatch = _
def runCode() {
latch = new CountDownLatch(1)
codeRunner.runCode(pane.getText())
latch.await()
}
object Tester {
var resCounter = 0
var res = ""
def postIncrCounter = {
val c = resCounter
resCounter += 1
c
}
def isMultiLine(cmd: String) = cmd.contains("\n") || cmd.contains(" ; ")
def outputPrefix(cmd: String) = {
if (isMultiLine(cmd)) ""
else "res" + postIncrCounter + ": "
}
def apply (cmd: String, s: Option[String] = None) = {
runCtx.clearOutput
pane.setText(cmd)
runCtx.success.set(false)
runCode()
Utils.runInSwingThreadAndWait { /* noop */ }
assertTrue(runCtx.success.get)
val output = stripCrLfs(runCtx.getCurrentOutput)
s foreach { ss =>
if (ss isEmpty) {
// an empty expected string means print output
println(output)
} else if (ss(0) == '$') {
val regexp = outputPrefix(cmd) + ss.tail
assertTrue(output matches regexp)
} else {
val expect = outputPrefix(cmd) + ss
assertEquals(expect, output)
}
}
}
}
type PNode = edu.umd.cs.piccolo.PNode
type PPath = edu.umd.cs.piccolo.nodes.PPath
def stripCrLfs(str: String) = str.replaceAll("\r?\n", "")
val CL = java.awt.geom.PathIterator.SEG_CLOSE // 4
val CT = java.awt.geom.PathIterator.SEG_CUBICTO // 3
val LT = java.awt.geom.PathIterator.SEG_LINETO // 1
val MT = java.awt.geom.PathIterator.SEG_MOVETO // 0
val QT = java.awt.geom.PathIterator.SEG_QUADTO // 2
val fmt = "%g"
def segmentToString(t: Int, coords: Array[Double]) = t match {
case MT =>
"M" + (fmt format coords(0)) + "," + (fmt format coords(1)) + " "
case LT =>
"L" + (fmt format coords(0)) + "," + (fmt format coords(1)) + " "
case QT =>
"Q" + (fmt format coords(0)) + "," + (fmt format coords(1)) + " " +
(fmt format coords(2)) + "," + (fmt format coords(3)) + " "
case CT =>
"C" + (fmt format coords(0)) + "," + (fmt format coords(1)) + " " +
(fmt format coords(2)) + "," + (fmt format coords(3)) + " " +
(fmt format coords(4)) + "," + (fmt format coords(5)) + " "
case CL =>
"z "
}
def pathIteratorToString(pi: java.awt.geom.PathIterator) = {
var res = new StringBuffer
while (!pi.isDone) {
pi.next
val coords = Array[Double](0, 0, 0, 0, 0, 0)
val t = pi.currentSegment(coords)
res.append(segmentToString(t, coords))
}
res.toString
}
def pathReferenceToString(pr: java.awt.geom.Path2D) = {
val at = new java.awt.geom.AffineTransform
val pi = pr.getPathIterator(at)
pathIteratorToString(pi)
}
def pathData(polyLine: kgeom.PolyLine) = {
pathReferenceToString(polyLine.polyLinePath)
}
def pathData(ppath: PPath) = {
pathReferenceToString(ppath.getPathReference)
}
def makeString(pnode: PNode) = {
val x = pnode.getX.round + 1
val y = pnode.getY.round + 1
if (pnode.isInstanceOf[kgeom.PolyLine]) {
"PolyLine(" + (x + 1) + "," + (y + 1) + " " +
pathData(pnode.asInstanceOf[kgeom.PolyLine]) + ")"
}
else if (pnode.isInstanceOf[PPath]) {
"PPath(" + x + "," + y + " " +
pathData(pnode.asInstanceOf[PPath]) + ")"
}
else pnode.toString
}
}
| vnkmr7620/kojo | KojoEnv/test/qa-functional/src/net/kogics/kojo/staging/StagingTestBase.scala | Scala | gpl-3.0 | 4,798 |
/* Copyright (C) 2003-2013 Runtime Revolution Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "w32prefix.h"
#include "globdefs.h"
#include "filedefs.h"
#include "objdefs.h"
#include "parsedef.h"
#include "mcio.h"
//#include "execpt.h"
bool MCFileSystemPathToNative(const char *p_path, void*& r_native_path)
{
unichar_t *t_w_path;
t_w_path = nil;
if (!MCCStringToUnicode(p_path, t_w_path))
return false;
for(uint32_t i = 0; t_w_path[i] != 0; i++)
if (t_w_path[i] == '/')
t_w_path[i] = '\\';
r_native_path = t_w_path;
return true;
}
bool MCFileSystemPathFromNative(const void *p_native_path, char*& r_path)
{
char *t_path;
t_path = nil;
if (!MCCStringFromUnicode((const unichar_t *)p_native_path, t_path))
return false;
for(uint32_t i = 0; t_path[i] != 0; i++)
if (t_path[i] == '\\')
t_path[i] = '/';
r_path = t_path;
return true;
}
bool MCFileSystemListEntries(const char *p_folder, uint32_t p_options, MCFileSystemListCallback p_callback, void *p_context)
{
bool t_success;
t_success = true;
char *t_pattern;
t_pattern = nil;
if (t_success)
t_success = MCCStringFormat(t_pattern, "%s%s", p_folder, MCCStringEndsWith(p_folder, "/") ? "*" : "/*");
void *t_native_pattern;
t_native_pattern = nil;
if (t_success)
t_success = MCFileSystemPathToNative(t_pattern, t_native_pattern);
HANDLE t_find_handle;
WIN32_FIND_DATAW t_find_data;
t_find_handle = INVALID_HANDLE_VALUE;
if (t_success)
{
t_find_handle = FindFirstFileW((LPCWSTR)t_native_pattern, &t_find_data);
if (t_find_handle == INVALID_HANDLE_VALUE)
t_success = false;
}
while(t_success)
{
char *t_entry_filename;
if (t_success)
t_success = MCFileSystemPathFromNative(t_find_data . cFileName, t_entry_filename);
MCFileSystemEntry t_entry;
if (t_success)
{
t_entry . type = (t_find_data . dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 ? kMCFileSystemEntryFolder : kMCFileSystemEntryFile;
MCStringCreateWithCString(t_entry_filename, t_entry.filename);
//t_entry . filename = t_entry_filename;
t_success = p_callback(p_context, t_entry);
}
MCCStringFree(t_entry_filename);
////
if (!FindNextFileW(t_find_handle, &t_find_data))
{
if (GetLastError() == ERROR_NO_MORE_FILES)
break;
t_success = false;
}
}
if (t_find_handle != INVALID_HANDLE_VALUE)
FindClose(t_find_handle);
MCMemoryDeallocate(t_native_pattern);
MCCStringFree(t_pattern);
return t_success;
}
bool MCFileSystemPathResolve(const char *p_path, char*& r_resolved_path)
{
return MCCStringClone(p_path, r_resolved_path);
}
bool MCFileSystemPathExists(const char *p_path, bool p_folder, bool& r_exists)
{
bool t_success;
t_success = true;
void *t_native_path;
t_native_path = nil;
if (t_success)
t_success = MCFileSystemPathToNative(p_path, t_native_path);
if (t_success)
{
DWORD t_result;
t_result = GetFileAttributesW((LPCWSTR)t_native_path);
if (t_result != INVALID_FILE_ATTRIBUTES)
{
r_exists =
((t_result & (FILE_ATTRIBUTE_DIRECTORY)) == 0 && !p_folder) ||
((t_result & (FILE_ATTRIBUTE_DIRECTORY)) != 0 && p_folder);
}
else
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
r_exists = false;
else
t_success = false;
}
}
MCMemoryDeleteArray(t_native_path);
return t_success;
}
| LiveCodeSteven/livecode | engine/src/sysw32fs.cpp | C++ | gpl-3.0 | 3,808 |
define(
[
'jquery',
'stapes',
'./conditionals'
],
function(
$,
Stapes,
conditionalsMediator
) {
'use strict';
/**
* Global Mediator (included on every page)
* @module Globals
* @implements {Stapes}
*/
var Mediator = Stapes.subclass({
/**
* Reference to conditionals mediator singleton
* @type {Object}
*/
conditionals: conditionalsMediator,
/**
* Mediator Constructor
* @return {void}
*/
constructor: function (){
var self = this;
self.initEvents();
$(function(){
self.emit('domready');
});
},
/**
* Initialize events
* @return {void}
*/
initEvents: function(){
var self = this;
self.on('domready', self.onDomReady);
// // DEBUG
// conditionalsMediator.on('all', function(val, e){
// console.log(e.type, val);
// });
},
/**
* DomReady Callback
* @return {void}
*/
onDomReady: function(){
var self = this;
}
});
return new Mediator();
}
);
| minutelabsio/sed-postcard-map | app/library/js/mediators/globals.js | JavaScript | gpl-3.0 | 1,501 |
<html><head><body>Pet Manager Lundy:<br>
All the people who can give you information about pet wolves are here in the <font color="LEVEL">Town of Gludio</font>.<br>
First, go see <font color="LEVEL">Gatekeeper Bella</font>.
</body></html> | karolusw/l2j | game/data/scripts/quests/Q00210_ObtainAWolfPet/30827-07.html | HTML | gpl-3.0 | 238 |
require 'spec_helper'
describe 'puppet::agent' do
on_supported_os.each do |os, os_facts|
next if only_test_os() and not only_test_os.include?(os)
next if exclude_test_os() and exclude_test_os.include?(os)
context "on #{os}" do
let (:default_facts) do
os_facts.merge({
:clientcert => 'puppetmaster.example.com',
:concat_basedir => '/nonexistant',
:fqdn => 'puppetmaster.example.com',
:puppetversion => Puppet.version,
}) end
if Puppet.version < '4.0'
client_package = 'puppet'
confdir = '/etc/puppet'
case os_facts[:osfamily]
when 'FreeBSD'
client_package = 'puppet38'
confdir = '/usr/local/etc/puppet'
when 'windows'
client_package = 'puppet'
confdir = 'C:/ProgramData/PuppetLabs/puppet/etc'
end
additional_facts = {}
else
client_package = 'puppet-agent'
confdir = '/etc/puppetlabs/puppet'
additional_facts = {:rubysitedir => '/opt/puppetlabs/puppet/lib/ruby/site_ruby/2.1.0'}
case os_facts[:osfamily]
when 'FreeBSD'
client_package = 'puppet4'
confdir = '/usr/local/etc/puppet'
additional_facts = {}
when 'windows'
client_package = 'puppet-agent'
confdir = 'C:/ProgramData/PuppetLabs/puppet/etc'
additional_facts = {}
end
end
let :facts do
default_facts.merge(additional_facts)
end
describe 'with no custom parameters' do
let :pre_condition do
"class {'puppet': agent => true}"
end
it { should contain_class('puppet::agent::install') }
it { should contain_class('puppet::agent::config') }
it { should contain_class('puppet::agent::service') }
it { should contain_file(confdir).with_ensure('directory') }
it { should contain_concat("#{confdir}/puppet.conf") }
it { should contain_package(client_package).with_ensure('present') }
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/^\[agent\]/).
with({})
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/server.*puppetmaster\.example\.com/)
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
without_content(/prerun_command\s*=/)
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
without_content(/postrun_command\s*=/)
end
end
describe 'puppetmaster parameter overrides server fqdn' do
let(:pre_condition) { "class {'puppet': agent => true, puppetmaster => 'mymaster.example.com'}" }
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/server.*mymaster\.example\.com/)
end
end
describe 'global puppetmaster overrides fqdn' do
let(:pre_condition) { "class {'puppet': agent => true}" }
let :facts do
default_facts.merge({:puppetmaster => 'mymaster.example.com'})
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/server.*mymaster\.example\.com/)
end
end
describe 'puppetmaster parameter overrides global puppetmaster' do
let(:pre_condition) { "class {'puppet': agent => true, puppetmaster => 'mymaster.example.com'}" }
let :facts do
default_facts.merge({:puppetmaster => 'global.example.com'})
end
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/server.*mymaster\.example\.com/)
end
end
describe 'use_srv_records removes server setting' do
let(:pre_condition) { "class {'puppet': agent => true, use_srv_records => true}" }
it do
should contain_concat__fragment('puppet.conf+20-agent').
without_content(/server\s*=/)
end
end
describe 'set prerun_command will be included in config' do
let(:pre_condition) { "class {'puppet': agent => true, prerun_command => '/my/prerun'}" }
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/prerun_command.*\/my\/prerun/)
end
end
describe 'set postrun_command will be included in config' do
let(:pre_condition) { "class {'puppet': agent => true, postrun_command => '/my/postrun'}" }
it do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/postrun_command.*\/my\/postrun/)
end
end
describe 'with additional settings' do
let :pre_condition do
"class {'puppet':
agent_additional_settings => {ignoreschedules => true},
}"
end
it 'should configure puppet.conf' do
should contain_concat__fragment('puppet.conf+20-agent').
with_content(/^\s+ignoreschedules\s+= true$/).
with({}) # So we can use a trailing dot on each with_content line
end
end
end
end
end
| szemlyanoy/puppet-puppet | spec/classes/puppet_agent_spec.rb | Ruby | gpl-3.0 | 5,356 |
/*
Copyright 2005, 2006, 2007 Dennis van Weeren
Copyright 2008, 2009 Jakub Bednarski
This file is part of Minimig
Minimig 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.
Minimig 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/>.
*/
// 2009-11-14 - OSD labels changed
// 2009-12-15 - added display of directory name extensions
// 2010-01-09 - support for variable number of tracks
//#include "AT91SAM7S256.h"
//#include "stdbool.h"
#include "stdio.h"
#include "string.h"
#include "errors.h"
#include "mmc.h"
#include "fat.h"
#include "osd.h"
#include "fpga.h"
#include "fdd.h"
#include "hdd.h"
#include "hardware.h"
#include "firmware.h"
#include "config.h"
#include "menu.h"
// other constants
#define DIRSIZE 8 // number of items in directory display window
unsigned char menustate = MENU_NONE1;
unsigned char parentstate;
unsigned char menusub = 0;
unsigned int menumask = 0; // Used to determine which rows are selectable...
unsigned long menu_timer;
extern unsigned char drives;
extern adfTYPE df[4];
extern configTYPE config;
extern fileTYPE file;
extern char s[40];
extern unsigned char fat32;
extern DIRENTRY DirEntry[MAXDIRENTRIES];
extern unsigned char sort_table[MAXDIRENTRIES];
extern unsigned char nDirEntries;
extern unsigned char iSelectedEntry;
extern unsigned long iCurrentDirectory;
extern char DirEntryLFN[MAXDIRENTRIES][261];
char DirEntryInfo[MAXDIRENTRIES][5]; // disk number info of dir entries
char DiskInfo[5]; // disk number info of selected entry
extern const char version[];
const char *config_filter_msg[] = {"none", "HORIZONTAL", "VERTICAL", "H+V"};
const char *config_memory_chip_msg[] = {"0.5 MB", "1.0 MB", "1.5 MB", "2.0 MB"};
const char *config_memory_slow_msg[] = {"none ", "0.5 MB", "1.0 MB", "1.5 MB"};
const char *config_scanlines_msg[] = {"off", "dim", "black"};
const char *config_memory_fast_msg[] = {"none ", "2.0 MB", "4.0 MB"};
const char *config_cpu_msg[] = {"68000 ", "68010", "-----","020 alpha"};
const char *config_hdf_msg[] = {"Disabled", "Hardfile (disk img)", "MMC/SD card", "MMC/SD partition 1", "MMC/SD partition 2", "MMC/SD partition 3", "MMC/SD partition 4"};
const char *config_chipset_msg[] = {"OCS-A500", "OCS-A1000", "ECS", "---"};
char *config_autofire_msg[] = {" AUTOFIRE OFF", " AUTOFIRE FAST", " AUTOFIRE MEDIUM", " AUTOFIRE SLOW"};
enum HelpText_Message {HELPTEXT_NONE,HELPTEXT_MAIN,HELPTEXT_HARDFILE,HELPTEXT_CHIPSET,HELPTEXT_MEMORY,HELPTEXT_VIDEO};
const char *helptexts[]={
0,
" Welcome to Minimig! Use the cursor keys to navigate the menus. Use space bar or enter to select an item. Press Esc or F12 to exit the menus. Joystick emulation on the numeric keypad can be toggled with the numlock key, while pressing Ctrl-Alt-0 (numeric keypad) toggles autofire mode.",
" Minimig can emulate an A600 IDE harddisk interface. The emulation can make use of Minimig-style hardfiles (complete disk images) or UAE-style hardfiles (filesystem images with no partition table). It is also possible to use either the entire SD card or an individual partition as an emulated harddisk.",
" Minimig's processor core can emulate a 68000 or 68020 processor (though the 68020 mode is still experimental.) If you're running software built for 68000, there's no advantage to using the 68020 mode, since the 68000 emulation runs just as fast.",
#ifdef ACTIONREPLAY_BROKEN
" Minimig can make use of up to 2 megabytes of Chip RAM, up to 1.5 megabytes of Slow RAM (A500 Trapdoor RAM), and up to 8 megabytes of true Fast RAM.",
#else
" Minimig can make use of up to 2 megabytes of Chip RAM, up to 1.5 megabytes of Slow RAM (A500 Trapdoor RAM), and up to 8 megabytes of true Fast RAM. To use the Action Replay feature you will need an Action Replay 3 ROM file on the SD card, named AR3.ROM. You will also need to set Fast RAM to no more than 2 megabytes.",
#endif
" Minimig's video features include a blur filter, to simulate the poorer picture quality on older monitors, and also scanline generation to simulate the appearance of a screen with low vertical resolution.",
0
};
//extern unsigned char DEBUG;
unsigned char config_autofire = 0;
// file selection menu variables
char *fs_pFileExt = NULL;
unsigned char fs_Options;
unsigned char fs_MenuSelect;
unsigned char fs_MenuCancel;
static char debuglines[8*32+1];
static char debugptr=0;
void _showdebugmessages()
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L2);
int i;
for(i=0;i<8;++i)
{
int j=(debugptr+i)&7;
debuglines[j*32+31]=0;
OsdWrite(i,&debuglines[j*32],i==7,0);
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L2);
}
void SelectFile(char* pFileExt, unsigned char Options, unsigned char MenuSelect, unsigned char MenuCancel)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
// this function displays file selection menu
if (strncmp(pFileExt, fs_pFileExt, 3) != 0) // check desired file extension
{ // if different from the current one go to the root directory and init entry buffer
ChangeDirectory(DIRECTORY_ROOT);
ScanDirectory(SCAN_INIT, pFileExt, Options);
}
fs_pFileExt = pFileExt;
fs_Options = Options;
fs_MenuSelect = MenuSelect;
fs_MenuCancel = MenuCancel;
menustate = MENU_FILE_SELECT1;
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
#define STD_EXIT " exit"
#define HELPTEXT_DELAY 10000
#define FRAME_DELAY 150
void ShowSplash()
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L0);
OsdSetTitle("Welcome",0);
OsdWrite(0, "", 0,0);
OsdDrawLogo(1,0,0);
OsdDrawLogo(2,1,0);
OsdDrawLogo(3,2,0);
OsdDrawLogo(4,3,0);
OsdDrawLogo(5,4,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
OsdEnable(0);
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L0);
}
void HideSplash()
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L0);
OsdDisable();
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L0);
}
void HandleUI(void)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L2);
unsigned char i, c, up, down, select, menu, right, left, plus, minus;
unsigned long len;
static hardfileTYPE t_hardfile[2]; // temporary copy of former hardfile configuration
static unsigned char ctrl = false;
static unsigned char lalt = false;
char enable;
static long helptext_timer;
static const char *helptext;
static char helpstate=0;
// get user control codes
c = OsdGetCtrl();
// decode and set events
menu = false;
select = false;
up = false;
down = false;
left = false;
right = false;
plus=false;
minus=false;
switch (c)
{
case KEY_CTRL :
ctrl = true;
break;
case KEY_CTRL | KEY_UPSTROKE :
ctrl = false;
break;
case KEY_LALT :
lalt = true;
break;
case KEY_LALT | KEY_UPSTROKE :
lalt = false;
break;
case KEY_KPPLUS :
if (ctrl && lalt)
{
config.chipset |= CONFIG_TURBO;
ConfigChipset(config.chipset);
if (menustate == MENU_SETTINGS_CHIPSET2)
menustate = MENU_SETTINGS_CHIPSET1;
else if (menustate == MENU_NONE2 || menustate == MENU_INFO)
InfoMessage(" TURBO");
}
else
plus=true;
break;
case KEY_KPMINUS :
if (ctrl && lalt)
{
config.chipset &= ~CONFIG_TURBO;
ConfigChipset(config.chipset);
if (menustate == MENU_SETTINGS_CHIPSET2)
menustate = MENU_SETTINGS_CHIPSET1;
else if (menustate == MENU_NONE2 || menustate == MENU_INFO)
InfoMessage(" NORMAL");
}
else
minus=true;
break;
case KEY_KP0 :
if (ctrl && lalt)
{
if (menustate == MENU_NONE2 || menustate == MENU_INFO)
{
config_autofire++;
config_autofire &= 3;
ConfigAutofire(config_autofire);
if (menustate == MENU_NONE2 || menustate == MENU_INFO)
InfoMessage(config_autofire_msg[config_autofire]);
}
}
break;
case KEY_MENU :
if (ctrl && lalt)
{
OsdSetTitle("Debug",0);
DebugMode=DebugMode^1;
menustate = MENU_NONE1;
}
else
menu = true;
break;
case KEY_ESC :
if (menustate != MENU_NONE2)
menu = true;
break;
case KEY_ENTER :
case KEY_SPACE :
select = true;
break;
case KEY_UP :
up = true;
break;
case KEY_DOWN :
down = true;
break;
case KEY_LEFT :
left = true;
break;
case KEY_RIGHT :
right = true;
break;
}
if(menu || select || up || down || left || right )
{
if(helpstate)
OsdWrite(7,STD_EXIT,(menumask-((1<<(menusub+1))-1))<=0,0); // Redraw the Exit line...
helpstate=0;
helptext_timer=GetTimer(HELPTEXT_DELAY);
}
if(helptext)
{
if(helpstate<9)
{
if(CheckTimer(helptext_timer))
{
helptext_timer=GetTimer(FRAME_DELAY);
OsdWriteOffset(7,STD_EXIT,0,0,helpstate);
++helpstate;
}
}
else if(helpstate==9)
{
ScrollReset();
++helpstate;
}
else
ScrollText(7,helptext,0,0,0);
}
// Standardised menu up/down.
// The screen should set menumask, bit 0 to make the top line selectable, bit 1 for the 2nd line, etc.
// (Lines in this context don't have to correspond to rows on the OSD.)
// Also set parentstate to the appropriate menustate.
if(menumask)
{
if ((unsigned)down && ((unsigned)menumask>=(unsigned)(1<<(menusub+1)))) // Any active entries left?
{
do
menusub++;
while((menumask & (1<<menusub)) == 0);
menustate = parentstate;
}
if (up && menusub > 0 && (menumask<<(8-menusub)))
{
do
--menusub;
while((menumask & (1<<menusub)) == 0);
menustate = parentstate;
}
}
switch (menustate)
{
/******************************************************************/
/* no menu selected */
/******************************************************************/
case MENU_NONE1 :
helptext=helptexts[HELPTEXT_NONE];
menumask=0;
if(DebugMode)
{
helptext=helptexts[HELPTEXT_NONE];
OsdEnable(0);
}
else
OsdDisable();
menustate = MENU_NONE2;
break;
case MENU_NONE2 :
if(DebugMode)
_showdebugmessages();
if (menu)
{
menustate = MENU_MAIN1;
menusub = 0;
OsdClear();
OsdEnable(DISABLE_KEYBOARD);
}
break;
/******************************************************************/
/* main menu */
/******************************************************************/
case MENU_MAIN1 :
menumask=0x70; // b01110000 Floppy turbo, Harddisk options & Exit.
OsdSetTitle("Minimig",OSD_ARROW_RIGHT);
helptext=helptexts[HELPTEXT_MAIN];
// floppy drive info
// We display a line for each drive that's active
// in the config file, but grey out any that the FPGA doesn't think are active.
// We also print a help text in place of the last drive if it's inactive.
for (i = 0; i < 4; i++)
{
if(i==config.floppy.drives+1)
OsdWrite(i," KP +/- to add/remove drives",0,1);
else
{
strcpy(s, " dfx: ");
s[3] = i + '0';
if(i<=drives)
{
menumask|=(1<<i); // Make enabled drives selectable
if (df[i].status & DSK_INSERTED) // floppy disk is inserted
{
strncpy(&s[6], df[i].name, sizeof(df[0].name));
if(!(df[i].status & DSK_WRITABLE))
strcpy(&s[6 + sizeof(df[i].name)-1], " \x17"); // padlock icon for write-protected disks
else
strcpy(&s[6 + sizeof(df[i].name)-1], " "); // clear padlock icon for write-enabled disks
}
else // no floppy disk
{
strcat(s, "* no disk *");
}
}
else if(i<=config.floppy.drives)
{
strcat(s,"* active after reset *");
}
else
strcpy(s,"");
OsdWrite(i, s, menusub == i,(i>drives)||(i>config.floppy.drives));
}
}
sprintf(s," Floppy disk turbo : %s",config.floppy.speed ? "on" : "off");
OsdWrite(4, s, menusub==4,0);
OsdWrite(5, " Hard disk settings \x16", menusub == 5,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 6,0);
menustate = MENU_MAIN2;
parentstate=MENU_MAIN1;
break;
case MENU_MAIN2 :
if (menu)
menustate = MENU_NONE1;
else if(plus && (config.floppy.drives<3))
{
config.floppy.drives++;
ConfigFloppy(config.floppy.drives,config.floppy.speed);
menustate = MENU_MAIN1;
}
else if(minus && (config.floppy.drives>0))
{
config.floppy.drives--;
ConfigFloppy(config.floppy.drives,config.floppy.speed);
menustate = MENU_MAIN1;
}
else if (select)
{
if (menusub < 4)
{
if (df[menusub].status & DSK_INSERTED) // eject selected floppy
{
df[menusub].status = 0;
menustate = MENU_MAIN1;
}
else
{
df[menusub].status = 0;
SelectFile("ADF", SCAN_DIR | SCAN_LFN, MENU_FILE_SELECTED, MENU_MAIN1);
}
}
else if (menusub == 4) // Toggle floppy turbo
{
config.floppy.speed^=1;
ConfigFloppy(config.floppy.drives,config.floppy.speed);
menustate = MENU_MAIN1;
}
else if (menusub == 5) // Go to harddrives page.
{
t_hardfile[0] = config.hardfile[0];
t_hardfile[1] = config.hardfile[1];
menustate = MENU_SETTINGS_HARDFILE1;
menusub=0;
}
else if (menusub == 6)
menustate = MENU_NONE1;
}
else if (c == KEY_BACK) // eject all floppies
{
for (i = 0; i <= drives; i++)
df[i].status = 0;
menustate = MENU_MAIN1;
}
else if (right)
{
menustate = MENU_MAIN2_1;
menusub = 0;
}
break;
case MENU_FILE_SELECTED : // file successfully selected
InsertFloppy(&df[menusub]);
menustate = MENU_MAIN1;
menusub++;
if (menusub > drives)
menusub = 6;
break;
/******************************************************************/
/* second part of the main menu */
/******************************************************************/
case MENU_MAIN2_1 :
helptext=helptexts[HELPTEXT_MAIN];
menumask=0x3f;
OsdSetTitle("Settings",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, " load configuration", menusub == 0,0);
OsdWrite(1, " save configuration", menusub == 1,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, " chipset settings \x16", menusub == 2,0);
OsdWrite(4, " memory settings \x16", menusub == 3,0);
OsdWrite(5, " video settings \x16", menusub == 4,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 5,0);
parentstate = menustate;
menustate = MENU_MAIN2_2;
break;
case MENU_MAIN2_2 :
if (menu)
menustate = MENU_NONE1;
else if (select)
{
if (menusub == 0)
{
menusub = 0;
menustate = MENU_LOADCONFIG_1;
}
else if (menusub == 1)
{
menusub = 0;
menustate = MENU_SAVECONFIG_1;
}
else if (menusub == 2)
{
menustate = MENU_SETTINGS_CHIPSET1;
menusub = 0;
}
else if (menusub == 3)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
else if (menusub == 4)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
else if (menusub == 5)
menustate = MENU_NONE1;
}
else if (left)
{
menustate = MENU_MAIN1;
menusub = 0;
}
else if (right)
{
menustate = MENU_MISC1;
menusub = 0;
}
break;
case MENU_MISC1 :
helptext=helptexts[HELPTEXT_MAIN];
menumask=0x0f; // Reset, about and exit.
OsdSetTitle("Misc",OSD_ARROW_LEFT);
OsdWrite(0, " Reset", menusub == 0,0);
OsdWrite(1, "", 0,0);
OsdWrite(2, " Return to Chameleon", menusub == 1,0);
// OsdWrite(3, " (Not yet implemented)", 0,1);
OsdWrite(3, "", 0,0);
OsdWrite(4, " About", menusub == 2,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 3,0);
parentstate = menustate;
menustate = MENU_MISC2;
break;
case MENU_MISC2 :
if (menu)
menusub=0, menustate = MENU_NONE1;
if (left)
menusub=0, menustate = MENU_MAIN2_1;
else if (select)
{
if (menusub == 0) // Reset
{
menusub = 0;
menustate=MENU_RESET1;
}
if (menusub == 1) // Reconfig
{
menusub=0;
menustate=MENU_RECONF1;
}
if (menusub == 2) // About
{
menusub=0;
menustate=MENU_ABOUT1;
}
if (menusub == 3) // Exit
{
menustate=MENU_NONE1;
}
}
break;
case MENU_ABOUT1 :
helptext=helptexts[HELPTEXT_NONE];
menumask=0x01; // Just Exit
OsdSetTitle("About",0);
OsdDrawLogo(0,0,1);
OsdDrawLogo(1,1,1);
OsdDrawLogo(2,2,1);
OsdDrawLogo(3,3,1);
OsdDrawLogo(4,4,1);
OsdDrawLogo(6,6,1);
// OsdWrite(1, "", 0,0);
// OsdWriteDoubleSize(2," Minimig",0);
// OsdWriteDoubleSize(3," Minimig",1);
// OsdWrite(4, "", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 0,0);
StarsInit();
ScrollReset();
parentstate = menustate;
menustate = MENU_ABOUT2;
break;
case MENU_ABOUT2 :
StarsUpdate();
OsdDrawLogo(0,0,1);
OsdDrawLogo(1,1,1);
OsdDrawLogo(2,2,1);
OsdDrawLogo(3,3,1);
OsdDrawLogo(4,4,1);
OsdDrawLogo(6,6,1);
ScrollText(5," Minimig by Dennis van Weeren. Chipset improvements by Jakub Bednarski and Sascha Boing. TG68 softcore and Chameleon port by Tobias Gubener. Menu / disk code by Dennis van Weeren, Jakub Bednarski and Alastair M. Robinson. Build process, repository and tooling by Christian Vogelgsang. Minimig logo based on a design by Loriano Pagni. Minimig is distributed under the terms of the GNU General Public License version 3.",0,0,0);
if (select || menu)
{
menusub = 2;
menustate=MENU_MISC1;
}
break;
case MENU_LOADCONFIG_1 :
helptext=helptexts[HELPTEXT_NONE];
if(parentstate!=menustate) // First run?
{
menumask=0x20;
SetConfigurationFilename(0); if(ConfigurationExists(0)) menumask|=0x01;
SetConfigurationFilename(1); if(ConfigurationExists(0)) menumask|=0x02;
SetConfigurationFilename(2); if(ConfigurationExists(0)) menumask|=0x04;
SetConfigurationFilename(3); if(ConfigurationExists(0)) menumask|=0x08;
SetConfigurationFilename(4); if(ConfigurationExists(0)) menumask|=0x10;
}
parentstate=menustate;
OsdSetTitle("Load",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " Default", menusub == 0,(menumask & 1)==0);
OsdWrite(2, " 1", menusub == 1,(menumask & 2)==0);
OsdWrite(3, " 2", menusub == 2,(menumask & 4)==0);
OsdWrite(4, " 3", menusub == 3,(menumask & 8)==0);
OsdWrite(5, " 4", menusub == 4,(menumask & 0x10)==0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 5,0);
menustate = MENU_LOADCONFIG_2;
break;
case MENU_LOADCONFIG_2 :
if (down)
{
// if (menusub < 3)
if (menusub < 5)
menusub++;
menustate = MENU_LOADCONFIG_1;
}
else if (select)
{
if(menusub<5)
{
OsdDisable();
SetConfigurationFilename(menusub);
LoadConfiguration(NULL);
// OsdReset(RESET_NORMAL);
menustate = MENU_NONE1;
}
else
{
menustate = MENU_MAIN2_1;
menusub = 0;
}
}
if (menu) // exit menu
{
menustate = MENU_MAIN2_1;
menusub = 0;
}
break;
/******************************************************************/
/* file selection menu */
/******************************************************************/
case MENU_FILE_SELECT1 :
helptext=helptexts[HELPTEXT_NONE];
OsdSetTitle("Select",0);
PrintDirectory();
menustate = MENU_FILE_SELECT2;
break;
case MENU_FILE_SELECT2 :
menumask=0;
ScrollLongName(); // scrolls file name if longer than display line
if (c == KEY_HOME)
{
ScanDirectory(SCAN_INIT, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
if (c == KEY_BACK)
{
if (iCurrentDirectory) // if not root directory
{
ScanDirectory(SCAN_INIT, fs_pFileExt, fs_Options);
ChangeDirectory(DirEntry[sort_table[iSelectedEntry]].StartCluster + (fat32 ? (DirEntry[sort_table[iSelectedEntry]].HighCluster & 0x0FFF) << 16 : 0));
if (ScanDirectory(SCAN_INIT_FIRST, fs_pFileExt, fs_Options))
ScanDirectory(SCAN_INIT_NEXT, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
}
if (c == KEY_PGUP)
{
ScanDirectory(SCAN_PREV_PAGE, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1; }
if (c == KEY_PGDN)
{
ScanDirectory(SCAN_NEXT_PAGE, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
if (down) // scroll down one entry
{
ScanDirectory(SCAN_NEXT, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
if (up) // scroll up one entry
{
ScanDirectory(SCAN_PREV, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
if ((i = GetASCIIKey(c)))
{ // find an entry beginning with given character
if (nDirEntries)
{
if (DirEntry[sort_table[iSelectedEntry]].Attributes & ATTR_DIRECTORY)
{ // it's a directory
if (i < DirEntry[sort_table[iSelectedEntry]].Name[0])
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR);
}
else if (i > DirEntry[sort_table[iSelectedEntry]].Name[0])
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE);
}
else
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options)) // find nexr
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR);
}
}
else
{ // it's a file
if (i < DirEntry[sort_table[iSelectedEntry]].Name[0])
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE);
}
else if (i > DirEntry[sort_table[iSelectedEntry]].Name[0])
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR);
}
else
{
if (!ScanDirectory(i, fs_pFileExt, fs_Options)) // find next
if (!ScanDirectory(i, fs_pFileExt, fs_Options | FIND_DIR))
ScanDirectory(i, fs_pFileExt, fs_Options | FIND_FILE);
}
}
}
menustate = MENU_FILE_SELECT1;
}
if (select)
{
if (DirEntry[sort_table[iSelectedEntry]].Attributes & ATTR_DIRECTORY)
{
ChangeDirectory(DirEntry[sort_table[iSelectedEntry]].StartCluster + (fat32 ? (DirEntry[sort_table[iSelectedEntry]].HighCluster & 0x0FFF) << 16 : 0));
{
if (strncmp((char*)DirEntry[sort_table[iSelectedEntry]].Name, "..", 2) == 0)
{ // parent dir selected
if (ScanDirectory(SCAN_INIT_FIRST, fs_pFileExt, fs_Options))
ScanDirectory(SCAN_INIT_NEXT, fs_pFileExt, fs_Options);
else
ScanDirectory(SCAN_INIT, fs_pFileExt, fs_Options);
}
else
ScanDirectory(SCAN_INIT, fs_pFileExt, fs_Options);
menustate = MENU_FILE_SELECT1;
}
}
else
{
if (nDirEntries)
{
file.long_name[0] = 0;
len = strlen(DirEntryLFN[sort_table[iSelectedEntry]]);
if (len > 4)
if (DirEntryLFN[sort_table[iSelectedEntry]][len-4] == '.')
len -= 4; // remove extension
if (len > sizeof(file.long_name))
len = sizeof(file.long_name);
strncpy(file.name, (const char*)DirEntry[sort_table[iSelectedEntry]].Name, sizeof(file.name));
memset(file.long_name, 0, sizeof(file.long_name));
strncpy(file.long_name, DirEntryLFN[sort_table[iSelectedEntry]], len);
strncpy(DiskInfo, DirEntryInfo[iSelectedEntry], sizeof(DiskInfo));
file.size = DirEntry[sort_table[iSelectedEntry]].FileSize;
file.attributes = DirEntry[sort_table[iSelectedEntry]].Attributes;
file.start_cluster = DirEntry[sort_table[iSelectedEntry]].StartCluster + (fat32 ? (DirEntry[sort_table[iSelectedEntry]].HighCluster & 0x0FFF) << 16 : 0);
file.cluster = file.start_cluster;
file.sector = 0;
menustate = fs_MenuSelect;
}
}
}
if (menu)
{
menustate = fs_MenuCancel;
}
break;
/******************************************************************/
/* reset menu */
/******************************************************************/
case MENU_RESET1 :
helptext=helptexts[HELPTEXT_NONE];
OsdSetTitle("Reset",0);
menumask=0x03; // Yes / No
parentstate=menustate;
OsdWrite(0, "", 0,0);
OsdWrite(1, " Reset Minimig?", 0,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, " yes", menusub == 0,0);
OsdWrite(4, " no", menusub == 1,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
menustate = MENU_RESET2;
break;
case MENU_RESET2 :
if (select && menusub == 0)
{
menustate = MENU_NONE1;
OsdReset(RESET_NORMAL);
}
if (menu || (select && (menusub == 1))) // exit menu
{
menustate = MENU_MISC1;
menusub = 0;
}
break;
/******************************************************************/
/* reconfigure confirmation */
/******************************************************************/
case MENU_RECONF1 :
helptext=helptexts[HELPTEXT_NONE];
OsdSetTitle("Exit",0);
menumask=0x03; // Yes / No
parentstate=menustate;
OsdWrite(0, "", 0,0);
OsdWrite(1, " Return to Chameleon?", 0,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, " yes", menusub == 0,0);
OsdWrite(4, " no", menusub == 1,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
menustate = MENU_RECONF2;
break;
case MENU_RECONF2 :
if (select && menusub == 0)
{
OsdReconfig();
}
if (menu || (select && (menusub == 1))) // exit menu
{
menustate = MENU_MISC1;
menusub = 1;
}
break;
/******************************************************************/
/* settings menu */
/******************************************************************/
/*
case MENU_SETTINGS1 :
menumask=0;
OsdSetTitle("Settings",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " chipset", menusub == 0,0);
OsdWrite(2, " memory", menusub == 1,0);
OsdWrite(3, " drives", menusub == 2,0);
OsdWrite(4, " video", menusub == 3,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
if (menusub == 5)
OsdWrite(7, " \x12 save \x12", 1,0);
else if (menusub == 4)
OsdWrite(7, " \x13 exit \x13", 1,0);
else
OsdWrite(7, STD_EXIT, 0,0);
menustate = MENU_SETTINGS2;
break;
case MENU_SETTINGS2 :
if (down && menusub < 5)
{
menusub++;
menustate = MENU_SETTINGS1;
}
if (up && menusub > 0)
{
menusub--;
menustate = MENU_SETTINGS1;
}
if (select)
{
if (menusub == 0)
{
menustate = MENU_SETTINGS_CHIPSET1;
menusub = 0;
}
else if (menusub == 1)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
else if (menusub == 2)
{
menustate = MENU_SETTINGS_DRIVES1;
menusub = 0;
}
else if (menusub == 3)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
else if (menusub == 4)
{
menustate = MENU_MAIN2_1;
menusub = 1;
}
else if (menusub == 5)
{
// SaveConfiguration(0); // Use slot-based config filename instead
menustate = MENU_SAVECONFIG_1;
menusub = 0;
}
}
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 1;
}
break;
*/
case MENU_SAVECONFIG_1 :
helptext=helptexts[HELPTEXT_NONE];
menumask=0x3f;
parentstate=menustate;
OsdSetTitle("Save",0);
OsdWrite(0, "", 0, 0);
OsdWrite(1, " Default", menusub == 0,0);
OsdWrite(2, " 1", menusub == 1,0);
OsdWrite(3, " 2", menusub == 2,0);
OsdWrite(4, " 3", menusub == 3,0);
OsdWrite(5, " 4", menusub == 4,0);
OsdWrite(6, "", 0,0);
// OsdWrite(7, " exit", menusub == 3);
OsdWrite(7, STD_EXIT, menusub == 5,0);
menustate = MENU_SAVECONFIG_2;
break;
case MENU_SAVECONFIG_2 :
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 5;
}
else if (up)
{
if (menusub > 0)
menusub--;
menustate = MENU_SAVECONFIG_1;
}
else if (down)
{
// if (menusub < 3)
if (menusub < 5)
menusub++;
menustate = MENU_SAVECONFIG_1;
}
else if (select)
{
if(menusub<5)
{
SetConfigurationFilename(menusub);
SaveConfiguration(NULL);
menustate = MENU_NONE1;
}
else
{
menustate = MENU_MAIN2_1;
menusub = 1;
}
}
if (menu) // exit menu
{
menustate = MENU_MAIN2_1;
menusub = 1;
}
break;
/******************************************************************/
/* chipset settings menu */
/******************************************************************/
case MENU_SETTINGS_CHIPSET1 :
helptext=helptexts[HELPTEXT_CHIPSET];
menumask=0;
OsdSetTitle("Chipset",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, "", 0,0);
strcpy(s, " CPU : ");
// strcat(s, config.chipset & CONFIG_TURBO ? "turbo" : "normal");
strcat(s, config_cpu_msg[config.cpu & 0x03]);
OsdWrite(1, s, menusub == 0,0);
strcpy(s, " Video : ");
strcat(s, config.chipset & CONFIG_NTSC ? "NTSC" : "PAL");
OsdWrite(2, s, menusub == 1,0);
strcpy(s, " Chipset : ");
strcat(s, config_chipset_msg[config.chipset >> 2 & 3]);
OsdWrite(3, s, menusub == 2,0);
OsdWrite(4, "", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 3,0);
menustate = MENU_SETTINGS_CHIPSET2;
break;
case MENU_SETTINGS_CHIPSET2 :
if (down && menusub < 3)
{
menusub++;
menustate = MENU_SETTINGS_CHIPSET1;
}
if (up && menusub > 0)
{
menusub--;
menustate = MENU_SETTINGS_CHIPSET1;
}
if (select)
{
if (menusub == 0)
{
// config.chipset ^= CONFIG_TURBO;
menustate = MENU_SETTINGS_CHIPSET1;
config.cpu += 1;
if ((config.cpu & 0x03)==0x02)
config.cpu += 1;
// ConfigChipset(config.chipset);
ConfigCPU(config.cpu);
}
else if (menusub == 1)
{
config.chipset ^= CONFIG_NTSC;
menustate = MENU_SETTINGS_CHIPSET1;
ConfigChipset(config.chipset);
}
else if (menusub == 2)
{
if (config.chipset & CONFIG_ECS)
config.chipset &= ~(CONFIG_ECS|CONFIG_A1000);
else
config.chipset += CONFIG_A1000;
menustate = MENU_SETTINGS_CHIPSET1;
ConfigChipset(config.chipset);
}
else if (menusub == 3)
{
menustate = MENU_MAIN2_1;
menusub = 2;
}
}
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 2;
}
else if (right)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
else if (left)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
break;
/******************************************************************/
/* memory settings menu */
/******************************************************************/
case MENU_SETTINGS_MEMORY1 :
helptext=helptexts[HELPTEXT_MEMORY];
menumask=0x3f;
parentstate=menustate;
OsdSetTitle("Memory",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, "", 0,0);
strcpy(s, " CHIP : ");
strcat(s, config_memory_chip_msg[config.memory & 0x03]);
OsdWrite(1, s, menusub == 0,0);
strcpy(s, " SLOW : ");
strcat(s, config_memory_slow_msg[config.memory >> 2 & 0x03]);
OsdWrite(2, s, menusub == 1,0);
strcpy(s, " FAST : ");
strcat(s, config_memory_fast_msg[config.memory >> 4 & 0x03]);
OsdWrite(3, s, menusub == 2,0);
OsdWrite(4, "", 0,0);
strcpy(s, " ROM : ");
if (config.kickstart.long_name[0])
strncat(s, config.kickstart.long_name, sizeof(config.kickstart.long_name));
else
strncat(s, config.kickstart.name, sizeof(config.kickstart.name));
OsdWrite(5, s, menusub == 3,0);
#ifdef ACTIONREPLAY_BROKEN
OsdWrite(0, "", 0,0);
menumask&=0xef; // Remove bit 4
#else
strcpy(s, " AR3 : ");
strcat(s, config.disable_ar3 ? "disabled" : "enabled ");
OsdWrite(6, s, menusub == 4,config.memory&0x20); // Grey out AR3 if more than 2MB fast memory
#endif
OsdWrite(7, STD_EXIT, menusub == 5,0);
menustate = MENU_SETTINGS_MEMORY2;
break;
case MENU_SETTINGS_MEMORY2 :
if (select)
{
if (menusub == 0)
{
config.memory = ((config.memory + 1) & 0x03) | (config.memory & ~0x03);
menustate = MENU_SETTINGS_MEMORY1;
ConfigMemory(config.memory);
}
else if (menusub == 1)
{
config.memory = ((config.memory + 4) & 0x0C) | (config.memory & ~0x0C);
menustate = MENU_SETTINGS_MEMORY1;
ConfigMemory(config.memory);
}
else if (menusub == 2)
{
config.memory = ((config.memory + 0x10) & 0x30) | (config.memory & ~0x30);
if ((config.memory & 0x30) == 0x30)
config.memory -= 0x30;
// if (!(config.disable_ar3 & 0x01)&&(config.memory & 0x20))
// config.memory &= ~0x30;
menustate = MENU_SETTINGS_MEMORY1;
ConfigMemory(config.memory);
}
else if (menusub == 3)
{
SelectFile("ROM", SCAN_LFN, MENU_ROMFILE_SELECTED, MENU_SETTINGS_MEMORY1);
}
else if (menusub == 4)
{
if (!(config.disable_ar3 & 0x01)||(config.memory & 0x20))
config.disable_ar3 |= 0x01;
else
config.disable_ar3 &= 0xFE;
menustate = MENU_SETTINGS_MEMORY1;
}
else if (menusub == 5)
{
menustate = MENU_MAIN2_1;
menusub = 3;
}
}
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 3;
}
else if (right)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
else if (left)
{
menustate = MENU_SETTINGS_CHIPSET1;
menusub = 0;
}
break;
/******************************************************************/
/* drive settings menu */
/******************************************************************/
/*
case MENU_SETTINGS_DRIVES1 :
menumask=0;
OsdSetTitle("Drives",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, "", 0,0);
sprintf(s, " drives : %d", config.floppy.drives + 1,0);
OsdWrite(1, s, menusub == 0,0);
strcpy(s, " speed : ");
strcat(s, config.floppy.speed ? "fast " : "normal");
OsdWrite(2, s, menusub == 1,0);
OsdWrite(3, "", 0,0);
strcpy(s, " A600 IDE : ");
strcat(s, config.enable_ide ? "on " : "off");
OsdWrite(4, s, menusub == 2,0);
sprintf(s, " hardfiles : %d", (config.hardfile[0].present & config.hardfile[0].enabled) + (config.hardfile[1].present & config.hardfile[1].enabled));
OsdWrite(5,s, menusub == 3,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 4,0);
menustate = MENU_SETTINGS_DRIVES2;
break;
case MENU_SETTINGS_DRIVES2 :
if (down && menusub < 4)
{
menusub++;
menustate = MENU_SETTINGS_DRIVES1;
}
if (up && menusub > 0)
{
menusub--;
menustate = MENU_SETTINGS_DRIVES1;
}
if (select)
{
if (menusub == 0)
{
config.floppy.drives++;
config.floppy.drives &= 0x03;
menustate = MENU_SETTINGS_DRIVES1;
ConfigFloppy(config.floppy.drives, config.floppy.speed);
}
else if (menusub == 1)
{
config.floppy.speed++;
config.floppy.speed &= 0x01;
menustate = MENU_SETTINGS_DRIVES1;
ConfigFloppy(config.floppy.drives, config.floppy.speed);
}
else if (menusub == 2)
{
config.enable_ide ^= 0x01;
menustate = MENU_SETTINGS_DRIVES1;
ConfigIDE(config.enable_ide, config.hardfile[0].present && config.hardfile[0].enabled, config.hardfile[1].present && config.hardfile[1].enabled);
}
else if (menusub == 3)
{
t_hardfile[0] = config.hardfile[0];
t_hardfile[1] = config.hardfile[1];
menustate = MENU_SETTINGS_HARDFILE1;
menusub = 4;
}
else if (menusub == 4)
{
menustate = MENU_SETTINGS1;
menusub = 2;
}
}
if (menu)
{
menustate = MENU_SETTINGS1;
menusub = 2;
}
else if (right)
{
menustate = MENU_SETTINGS_VIDEO1;
menusub = 0;
}
else if (left)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
break;
*/
/******************************************************************/
/* hardfile settings menu */
/******************************************************************/
// FIXME! Nasty race condition here. Changing HDF type has immediate effect
// which could be disastrous if the user's writing to the drive at the time!
// Make the menu work on the copy, not the original, and copy on acceptance,
// not on rejection.
case MENU_SETTINGS_HARDFILE1 :
helptext=helptexts[HELPTEXT_HARDFILE];
OsdSetTitle("Harddisks",0);
parentstate = menustate;
menumask=0x21; // b00100001 - On/off & exit enabled by default...
if(config.enable_ide)
menumask|=0x0a; // b00001010 - HD0 and HD1 type
strcpy(s, " A600 IDE : ");
strcat(s, config.enable_ide ? "on " : "off");
OsdWrite(0, s, menusub == 0,0);
OsdWrite(1, "", 0,0);
strcpy(s, " Master : ");
if(config.hardfile[0].enabled==(HDF_FILE|HDF_SYNTHRDB))
strcat(s,"Hardfile (filesys)");
else
strcat(s, config_hdf_msg[config.hardfile[0].enabled & HDF_TYPEMASK]);
OsdWrite(2, s, config.enable_ide ? (menusub == 1) : 0 ,config.enable_ide==0);
if (config.hardfile[0].present)
{
strcpy(s, " ");
if (config.hardfile[0].long_name[0])
strncpy(&s[14], config.hardfile[0].long_name, sizeof(config.hardfile[0].long_name));
else
strncpy(&s[14], config.hardfile[0].name, sizeof(config.hardfile[0].name));
}
else
strcpy(s, " ** file not found **");
enable=config.enable_ide && ((config.hardfile[0].enabled&HDF_TYPEMASK)==HDF_FILE);
if(enable)
menumask|=0x04; // Make hardfile selectable
OsdWrite(3, s, enable ? (menusub == 2) : 0 , enable==0);
strcpy(s, " Slave : ");
if(config.hardfile[1].enabled==(HDF_FILE|HDF_SYNTHRDB))
strcat(s,"Hardfile (filesys)");
else
strcat(s, config_hdf_msg[config.hardfile[1].enabled & HDF_TYPEMASK]);
OsdWrite(4, s, config.enable_ide ? (menusub == 3) : 0 ,config.enable_ide==0);
if (config.hardfile[1].present)
{
strcpy(s, " ");
if (config.hardfile[1].long_name[0])
strncpy(&s[14], config.hardfile[1].long_name, sizeof(config.hardfile[0].long_name));
else
strncpy(&s[14], config.hardfile[1].name, sizeof(config.hardfile[0].name));
}
else
strcpy(s, " ** file not found **");
enable=config.enable_ide && ((config.hardfile[1].enabled&HDF_TYPEMASK)==HDF_FILE);
if(enable)
menumask|=0x10; // Make hardfile selectable
OsdWrite(5, s, enable ? (menusub == 4) : 0 ,enable==0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 5,0);
menustate = MENU_SETTINGS_HARDFILE2;
break;
case MENU_SETTINGS_HARDFILE2 :
if (select)
{
if (menusub == 0)
{
config.enable_ide=(config.enable_ide==0);
menustate = MENU_SETTINGS_HARDFILE1;
}
if (menusub == 1)
{
if(config.hardfile[0].enabled==HDF_FILE)
{
config.hardfile[0].enabled|=HDF_SYNTHRDB;
}
else if(config.hardfile[0].enabled==(HDF_FILE|HDF_SYNTHRDB))
{
config.hardfile[0].enabled&=~HDF_SYNTHRDB;
config.hardfile[0].enabled +=1;
}
else
{
config.hardfile[0].enabled +=1;
config.hardfile[0].enabled %=HDF_CARDPART0+partitioncount;
}
menustate = MENU_SETTINGS_HARDFILE1;
}
else if (menusub == 2)
{
SelectFile("HDF", SCAN_LFN, MENU_HARDFILE_SELECTED, MENU_SETTINGS_HARDFILE1);
}
else if (menusub == 3)
{
if(config.hardfile[1].enabled==HDF_FILE)
{
config.hardfile[1].enabled|=HDF_SYNTHRDB;
}
else if(config.hardfile[1].enabled==(HDF_FILE|HDF_SYNTHRDB))
{
config.hardfile[1].enabled&=~HDF_SYNTHRDB;
config.hardfile[1].enabled +=1;
}
else
{
config.hardfile[1].enabled +=1;
config.hardfile[1].enabled %=HDF_CARDPART0+partitioncount;
}
menustate = MENU_SETTINGS_HARDFILE1;
}
else if (menusub == 4)
{
SelectFile("HDF", SCAN_LFN, MENU_HARDFILE_SELECTED, MENU_SETTINGS_HARDFILE1);
}
else if (menusub == 5) // return to previous menu
{
menustate = MENU_HARDFILE_EXIT;
}
}
if (menu) // return to previous menu
{
menustate = MENU_HARDFILE_EXIT;
}
break;
/******************************************************************/
/* hardfile selected menu */
/******************************************************************/
case MENU_HARDFILE_SELECTED :
if (menusub == 2) // master drive selected
{
// Read RDB from selected drive and determine type...
memcpy((void*)config.hardfile[0].name, (void*)file.name, sizeof(config.hardfile[0].name));
memcpy((void*)config.hardfile[0].long_name, (void*)file.long_name, sizeof(config.hardfile[0].long_name));
switch(GetHDFFileType(file.name))
{
case HDF_FILETYPE_RDB:
config.hardfile[0].enabled=HDF_FILE;
config.hardfile[0].present = 1;
menustate = MENU_SETTINGS_HARDFILE1;
break;
case HDF_FILETYPE_DOS:
config.hardfile[0].enabled=HDF_FILE|HDF_SYNTHRDB;
config.hardfile[0].present = 1;
menustate = MENU_SETTINGS_HARDFILE1;
break;
case HDF_FILETYPE_UNKNOWN:
config.hardfile[0].present = 1;
if(config.hardfile[0].enabled==HDF_FILE) // Warn if we can't detect the type
menustate=MENU_SYNTHRDB1;
else
menustate=MENU_SYNTHRDB2_1;
menusub=0;
break;
case HDF_FILETYPE_NOTFOUND:
default:
config.hardfile[0].present = 0;
menustate = MENU_SETTINGS_HARDFILE1;
break;
}
}
if (menusub == 4) // slave drive selected
{
memcpy((void*)config.hardfile[1].name, (void*)file.name, sizeof(config.hardfile[1].name));
memcpy((void*)config.hardfile[1].long_name, (void*)file.long_name, sizeof(config.hardfile[1].long_name));
switch(GetHDFFileType(file.name))
{
case HDF_FILETYPE_RDB:
config.hardfile[1].enabled=HDF_FILE;
config.hardfile[1].present = 1;
menustate = MENU_SETTINGS_HARDFILE1;
break;
case HDF_FILETYPE_DOS:
config.hardfile[1].enabled=HDF_FILE|HDF_SYNTHRDB;
config.hardfile[1].present = 1;
menustate = MENU_SETTINGS_HARDFILE1;
break;
case HDF_FILETYPE_UNKNOWN:
config.hardfile[1].present = 1;
if(config.hardfile[1].enabled==HDF_FILE) // Warn if we can't detect the type...
menustate=MENU_SYNTHRDB1;
else
menustate=MENU_SYNTHRDB2_1;
menusub=0;
break;
case HDF_FILETYPE_NOTFOUND:
default:
config.hardfile[1].present = 0;
menustate = MENU_SETTINGS_HARDFILE1;
break;
}
}
break;
// check if hardfile configuration has changed
case MENU_HARDFILE_EXIT :
if (memcmp(config.hardfile, t_hardfile, sizeof(t_hardfile)) != 0)
{
menustate = MENU_HARDFILE_CHANGED1;
menusub = 1;
}
else
{
menustate = MENU_MAIN1;
menusub = 5;
}
break;
// hardfile configuration has changed, ask user if he wants to use the new settings
case MENU_HARDFILE_CHANGED1 :
menumask=0x03;
parentstate=menustate;
OsdSetTitle("Confirm",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " Changing configuration", 0,0);
OsdWrite(2, " requires reset.", 0,0);
OsdWrite(3, "", 0,0);
OsdWrite(4, " Reset Minimig?", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, " yes", menusub == 0,0);
OsdWrite(7, " no", menusub == 1,0);
menustate = MENU_HARDFILE_CHANGED2;
break;
case MENU_HARDFILE_CHANGED2 :
if (select)
{
if (menusub == 0) // yes
{
// FIXME - waiting for user-confirmation increases the window of opportunity for file corruption!
if ((config.hardfile[0].enabled != t_hardfile[0].enabled)
|| (strncmp(config.hardfile[0].name, t_hardfile[0].name, sizeof(t_hardfile[0].name)) != 0))
{
OpenHardfile(0);
// if((config.hardfile[0].enabled == HDF_FILE) && !FindRDB(0))
// menustate = MENU_SYNTHRDB1;
}
if (config.hardfile[1].enabled != t_hardfile[1].enabled
|| (strncmp(config.hardfile[1].name, t_hardfile[1].name, sizeof(t_hardfile[1].name)) != 0))
{
OpenHardfile(1);
// if((config.hardfile[1].enabled == HDF_FILE) && !FindRDB(1))
// menustate = MENU_SYNTHRDB2_1;
}
if(menustate==MENU_HARDFILE_CHANGED2)
{
ConfigIDE(config.enable_ide, config.hardfile[0].present && config.hardfile[0].enabled, config.hardfile[1].present && config.hardfile[1].enabled);
OsdReset(RESET_NORMAL);
menustate = MENU_NONE1;
}
}
else if (menusub == 1) // no
{
memcpy(config.hardfile, t_hardfile, sizeof(t_hardfile)); // restore configuration
menustate = MENU_MAIN1;
menusub = 3;
}
}
if (menu)
{
memcpy(config.hardfile, t_hardfile, sizeof(t_hardfile)); // restore configuration
menustate = MENU_MAIN1;
menusub = 3;
}
break;
case MENU_SYNTHRDB1 :
menumask=0x01;
parentstate=menustate;
OsdSetTitle("Warning",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " No partition table found -", 0,0);
OsdWrite(2, " Hardfile image may need", 0,0);
OsdWrite(3, " to be prepped with HDToolbox,", 0,0);
OsdWrite(4, " then formatted.", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, " OK", menusub == 0,0);
menustate = MENU_SYNTHRDB2;
break;
case MENU_SYNTHRDB2_1 :
menumask=0x01;
parentstate=menustate;
OsdSetTitle("Warning",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " No filesystem recognised.", 0,0);
OsdWrite(2, " Hardfile may need formatting", 0,0);
OsdWrite(3, " (or may simply be an", 0,0);
OsdWrite(4, " unrecognised filesystem)", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, " OK", menusub == 0,0);
menustate = MENU_SYNTHRDB2;
break;
case MENU_SYNTHRDB2 :
if (select || menu)
{
if (menusub == 0) // OK
menustate = MENU_SETTINGS_HARDFILE1;
}
break;
/******************************************************************/
/* video settings menu */
/******************************************************************/
case MENU_SETTINGS_VIDEO1 :
menumask=0x0f;
parentstate=menustate;
helptext=helptexts[HELPTEXT_VIDEO];
OsdSetTitle("Video",OSD_ARROW_LEFT|OSD_ARROW_RIGHT);
OsdWrite(0, "", 0,0);
strcpy(s, " Lores Filter : ");
strcat(s, config_filter_msg[config.filter.lores & 0x03]);
OsdWrite(1, s, menusub == 0,0);
strcpy(s, " Hires Filter : ");
strcat(s, config_filter_msg[config.filter.hires & 0x03]);
OsdWrite(2, s, menusub == 1,0);
strcpy(s, " Scanlines : ");
strcat(s, config_scanlines_msg[config.scanlines % 3]);
OsdWrite(3, s, menusub == 2,0);
OsdWrite(4, "", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, STD_EXIT, menusub == 3,0);
menustate = MENU_SETTINGS_VIDEO2;
break;
case MENU_SETTINGS_VIDEO2 :
if (select)
{
if (menusub == 0)
{
config.filter.lores++;
config.filter.lores &= 0x03;
menustate = MENU_SETTINGS_VIDEO1;
//ConfigFilter(config.filter.lores, config.filter.hires);
ConfigVideo(config.filter.hires, config.filter.lores, config.scanlines);
}
else if (menusub == 1)
{
config.filter.hires++;
config.filter.hires &= 0x03;
menustate = MENU_SETTINGS_VIDEO1;
//ConfigFilter(config.filter.lores, config.filter.hires);
ConfigVideo(config.filter.hires, config.filter.lores, config.scanlines);
}
else if (menusub == 2)
{
config.scanlines++;
if (config.scanlines > 2)
config.scanlines = 0;
menustate = MENU_SETTINGS_VIDEO1;
//ConfigScanlines(config.scanlines);
ConfigVideo(config.filter.hires, config.filter.lores, config.scanlines);
}
else if (menusub == 3)
{
menustate = MENU_MAIN2_1;
menusub = 4;
}
}
if (menu)
{
menustate = MENU_MAIN2_1;
menusub = 4;
}
else if (right)
{
menustate = MENU_SETTINGS_CHIPSET1;
menusub = 0;
}
else if (left)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 0;
}
break;
/******************************************************************/
/* rom file selected menu */
/******************************************************************/
case MENU_ROMFILE_SELECTED :
menusub = 1;
menustate=MENU_ROMFILE_SELECTED1;
// no break intended
case MENU_ROMFILE_SELECTED1 :
menumask=0x03;
parentstate=menustate;
OsdSetTitle("Confirm",0);
OsdWrite(0, "", 0,0);
OsdWrite(1, " Reload Kickstart?", 0,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, " yes", menusub == 0,0);
OsdWrite(4, " no", menusub == 1,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
menustate = MENU_ROMFILE_SELECTED2;
break;
case MENU_ROMFILE_SELECTED2 :
if (select)
{
if (menusub == 0)
{
memcpy((void*)config.kickstart.name, (void*)file.name, sizeof(config.kickstart.name));
memcpy((void*)config.kickstart.long_name, (void*)file.long_name, sizeof(config.kickstart.long_name));
OsdDisable();
//OsdReset(RESET_BOOTLOADER);
//ConfigChipset(config.chipset | CONFIG_TURBO);
//ConfigFloppy(config.floppy.drives, CONFIG_FLOPPY2X);
EnableOsd();
SPI(OSD_CMD_RST);
rstval = (SPI_RST_CPU | SPI_CPU_HLT);
SPI(rstval);
DisableOsd();
SPIN(); SPIN(); SPIN(); SPIN();
UploadKickstart(config.kickstart.name);
EnableOsd();
SPI(OSD_CMD_RST);
rstval = (SPI_RST_USR | SPI_RST_CPU);
SPI(rstval);
DisableOsd();
SPIN(); SPIN(); SPIN(); SPIN();
EnableOsd();
SPI(OSD_CMD_RST);
rstval = 0;
SPI(rstval);
DisableOsd();
SPIN(); SPIN(); SPIN(); SPIN();
//ConfigChipset(config.chipset); // restore CPU speed mode
//ConfigFloppy(config.floppy.drives, config.floppy.speed); // restore floppy speed mode
menustate = MENU_NONE1;
}
else if (menusub == 1)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 2;
}
}
if (menu)
{
menustate = MENU_SETTINGS_MEMORY1;
menusub = 2;
}
break;
// /******************************************************************/
// /* firmware menu */
// /******************************************************************/
// case MENU_FIRMWARE1 :
//
// OsdWrite(0, " *** Firmware ***", 0);
// OsdWrite(1, "", 0);
// sprintf(s, " ARM s/w ver. %s", version + 5);
// OsdWrite(2, s, 0);
// OsdWrite(3, "", 0);
// OsdWrite(4, " update", menusub == 0);
// OsdWrite(5, " options", menusub == 1);
// OsdWrite(6, "", 0);
// OsdWrite(7, " exit", menusub == 2);
//
// menustate = MENU_FIRMWARE2;
// break;
//
// case MENU_FIRMWARE2 :
//
// if (menu)
// {
// menusub = 2;
// menustate = MENU_MAIN2_1;
// }
// else if (up)
// {
// if (menusub > 0)
// menusub--;
// menustate = MENU_FIRMWARE1;
// }
// else if (down)
// {
// if (menusub < 2)
// menusub++;
// menustate = MENU_FIRMWARE1;
// }
// else if (select)
// {
// if (menusub == 0)
// {
//// if (CheckFirmware(&file, "FIRMWAREUPG"))
//// menustate = MENU_FIRMWARE_UPDATE1;
//// else
// menustate = MENU_FIRMWARE_UPDATE_ERROR1;
// menusub = 1;
// OsdClear();
// }
// else if (menusub == 1)
// {
// menustate = MENU_FIRMWARE_OPTIONS1;
// menusub = 1;
// OsdClear();
// }
// else if (menusub == 2)
// {
// menustate = MENU_MAIN2_1;
// menusub = 2;
// }
// }
// break;
//
// /******************************************************************/
// /* firmware update message menu */
// /******************************************************************/
// case MENU_FIRMWARE_UPDATE1 :
//
// OsdWrite(2, " Are you sure?", 0);
//
// OsdWrite(6, " yes", menusub == 0);
// OsdWrite(7, " no", menusub == 1);
//
// menustate = MENU_FIRMWARE_UPDATE2;
// break;
//
// case MENU_FIRMWARE_UPDATE2 :
//
// if (down && menusub < 1)
// {
// menusub++;
// menustate = MENU_FIRMWARE_UPDATE1;
// }
//
// if (up && menusub > 0)
// {
// menusub--;
// menustate = MENU_FIRMWARE_UPDATE1;
// }
//
// if (select)
// {
// if (menusub == 0)
// {
// menustate = MENU_FIRMWARE_UPDATING1;
// menusub = 0;
// OsdClear();
// }
// else if (menusub == 1)
// {
// menustate = MENU_FIRMWARE1;
// menusub = 2;
// }
// }
// break;
//
// /******************************************************************/
// /* firmware update in progress message menu*/
// /******************************************************************/
// case MENU_FIRMWARE_UPDATING1 :
//
// OsdWrite(1, " Updating firmware", 0);
// OsdWrite(3, " Please wait", 0);
// menustate = MENU_FIRMWARE_UPDATING2;
// break;
//
// case MENU_FIRMWARE_UPDATING2 :
//
//// WriteFirmware(&file);
// Error = ERROR_UPDATE_FAILED;
// menustate = MENU_FIRMWARE_UPDATE_ERROR1;
// menusub = 0;
// OsdClear();
// break;
//
// /******************************************************************/
// /* firmware update error message menu*/
// /******************************************************************/
// case MENU_FIRMWARE_UPDATE_ERROR1 :
//
// switch (Error)
// {
// case ERROR_FILE_NOT_FOUND :
// OsdWrite(1, " Update file", 0);
// OsdWrite(2, " not found!", 0);
// break;
// case ERROR_INVALID_DATA :
// OsdWrite(1, " Invalid ", 0);
// OsdWrite(2, " update file!", 0);
// break;
// case ERROR_UPDATE_FAILED :
// OsdWrite(2, " Update failed!", 0);
// break;
// }
// OsdWrite(7, " OK", 1);
// menustate = MENU_FIRMWARE_UPDATE_ERROR2;
// break;
//
// case MENU_FIRMWARE_UPDATE_ERROR2 :
//
// if (select)
// {
// menustate = MENU_FIRMWARE1;
// menusub = 2;
// }
// break;
//
// /******************************************************************/
// /* firmware options menu */
// /******************************************************************/
// case MENU_FIRMWARE_OPTIONS1 :
//
// OsdWrite(0, " ** Options **", 0);
//
//// if (GetSPIMode() == SPIMODE_FAST)
//// OsdWrite(2, " Fast SPI enabled", menusub == 0);
//// else
// OsdWrite(2, " Enable Fast SPI ", menusub == 0);
//
// OsdWrite(7, " exit", menusub == 1);
//
// menustate = MENU_FIRMWARE_OPTIONS2;
// break;
//
// case MENU_FIRMWARE_OPTIONS2 :
//
// if (c == KEY_F8)
// {
// if (DEBUG)
// {
// DEBUG = 0;
// printf("DEBUG OFF\r");
// }
// else
// {
// DEBUG = 1;
// printf("DEBUG ON\r");
// }
// }
// else if (menu)
// {
// menusub = 1;
// menustate = MENU_FIRMWARE1;
// }
// else if (up)
// {
//// if (menusub > 0 && GetSPIMode() != SPIMODE_FAST)
// menusub--;
//
// menustate = MENU_FIRMWARE_OPTIONS1;
// }
// else if (down)
// {
// if (menusub < 1)
// menusub++;
// menustate = MENU_FIRMWARE_OPTIONS1;
// }
// else if (select)
// {
// if (menusub == 0)
// {
// menusub = 1;
// menustate = MENU_FIRMWARE_OPTIONS_ENABLE1;
// OsdClear();
// }
// else if (menusub == 1)
// {
// menusub = 1;
// menustate = MENU_FIRMWARE1;
// }
// }
// break;
//
// /******************************************************************/
// /* SPI high speed mode enable message menu*/
// /******************************************************************/
// case MENU_FIRMWARE_OPTIONS_ENABLE1 :
//
// OsdWrite(0, " Enabling fast SPI without", 0);
// OsdWrite(1, " hardware modification", 0);
// OsdWrite(2, " will be fatal!", 0);
// OsdWrite(4, " Enable?", 0);
// OsdWrite(6, " yes", menusub == 0);
// OsdWrite(7, " no", menusub == 1);
//
// menustate = MENU_FIRMWARE_OPTIONS_ENABLE2;
// break;
//
// case MENU_FIRMWARE_OPTIONS_ENABLE2 :
//
// if (down && menusub < 1)
// {
// menusub++;
// menustate = MENU_FIRMWARE_OPTIONS_ENABLE1;
// }
//
// if (up && menusub > 0)
// {
// menusub--;
// menustate = MENU_FIRMWARE_OPTIONS_ENABLE1;
// }
//
// if (select)
// {
// if (menusub == 0)
// {
//// SetSPIMode(SPIMODE_FAST);
// menustate = MENU_FIRMWARE_OPTIONS_ENABLED1;
// menusub = 0;
// OsdClear();
// }
// else if (menusub == 1)
// {
// menustate = MENU_FIRMWARE_OPTIONS1;
// menusub = 0;
// OsdClear();
// }
// }
// break;
//
// /******************************************************************/
// /* SPI high speed mode enabled message menu*/
// /******************************************************************/
// case MENU_FIRMWARE_OPTIONS_ENABLED1 :
//
// OsdWrite(1, " Fast SPI mode will be", 0);
// OsdWrite(2, " activated after restart.", 0);
// OsdWrite(3, " Hold MENU button while", 0);
// OsdWrite(4, " powering-on to disable it.", 0);
//
// OsdWrite(7, " OK", menusub == 0);
//
// menustate = MENU_FIRMWARE_OPTIONS_ENABLED2;
// break;
//
// case MENU_FIRMWARE_OPTIONS_ENABLED2 :
//
// if (select)
// {
// menustate = MENU_NONE1;
// menusub = 0;
// OsdClear();
// }
// break;
/******************************************************************/
/* error message menu */
/******************************************************************/
case MENU_ERROR :
if (menu)
menustate = MENU_MAIN1;
break;
/******************************************************************/
/* popup info menu */
/******************************************************************/
case MENU_INFO :
if (menu)
menustate = MENU_MAIN1;
else if (CheckTimer(menu_timer))
menustate = MENU_NONE1;
break;
/******************************************************************/
/* we should never come here */
/******************************************************************/
default :
break;
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L2);
}
void ScrollLongName(void)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L2);
// this function is called periodically when file selection window is displayed
// it checks if predefined period of time has elapsed and scrolls the name if necessary
char k = sort_table[iSelectedEntry];
static int len;
int max_len;
if (DirEntryLFN[k][0]) // && CheckTimer(scroll_timer)) // scroll if long name and timer delay elapsed
{
// FIXME - yuk, we don't want to do this every frame!
len = strlen(DirEntryLFN[k]); // get name length
if (len > 4)
if (DirEntryLFN[k][len - 4] == '.')
len -= 4; // remove extension
max_len = 30; // number of file name characters to display (one more required for scrolling)
if (DirEntry[k].Attributes & ATTR_DIRECTORY)
max_len = 25; // number of directory name characters to display
ScrollText(iSelectedEntry,DirEntryLFN[k],len,max_len,1);
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L2);
}
char* GetDiskInfo(char* lfn, long len)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
// extracts disk number substring form file name
// if file name contains "X of Y" substring where X and Y are one or two digit number
// then the number substrings are extracted and put into the temporary buffer for further processing
// comparision is case sensitive
short i, k;
static char info[] = "XX/XX"; // temporary buffer
static char template[4] = " of "; // template substring to search for
char *ptr1, *ptr2, c;
unsigned char cmp;
if (len > 20) // scan only names which can't be fully displayed
{
for (i = (unsigned short)len - 1 - sizeof(template); i > 0; i--) // scan through the file name starting from its end
{
ptr1 = &lfn[i]; // current start position
ptr2 = template;
cmp = 0;
for (k = 0; (unsigned int)k < sizeof(template); k++) // scan through template
{
cmp |= *ptr1++ ^ *ptr2++; // compare substrings' characters one by one
if (cmp)
break; // stop further comparing if difference already found
}
if (!cmp) // match found
{
k = i - 1; // no need to check if k is valid since i is greater than zero
c = lfn[k]; // get the first character to the left of the matched template substring
if (c >= '0' && c <= '9') // check if a digit
{
info[1] = c; // copy to buffer
info[0] = ' '; // clear previous character
k--; // go to the preceding character
if (k >= 0) // check if index is valid
{
c = lfn[k];
if (c >= '0' && c <= '9') // check if a digit
info[0] = c; // copy to buffer
}
k = i + sizeof(template); // get first character to the right of the mached template substring
c = lfn[k]; // no need to check if index is valid
if (c >= '0' && c <= '9') // check if a digit
{
info[3] = c; // copy to buffer
info[4] = ' '; // clear next char
k++; // go to the followwing character
if (k < len) // check if index is valid
{
c = lfn[k];
if (c >= '0' && c <= '9') // check if a digit
info[4] = c; // copy to buffer
}
return info;
}
}
}
}
}
return NULL;
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
// print directory contents
void PrintDirectory(void)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
unsigned char i;
unsigned char k;
unsigned long len;
char *lfn;
char *info;
char *p;
unsigned char j;
s[32] = 0; // set temporary string length to OSD line length
ScrollReset();
for (i = 0; i < 8; i++)
{
memset(s, ' ', 32); // clear line buffer
if (i < nDirEntries)
{
k = sort_table[i]; // ordered index in storage buffer
lfn = DirEntryLFN[k]; // long file name pointer
DirEntryInfo[i][0] = 0; // clear disk number info buffer
if (lfn[0]) // item has long name
{
len = strlen(lfn); // get name length
info = NULL; // no disk info
if (!(DirEntry[k].Attributes & ATTR_DIRECTORY)) // if a file
{
if (len > 4)
if (lfn[len-4] == '.')
len -= 4; // remove extension
info = GetDiskInfo(lfn, len); // extract disk number info
if (info != NULL)
memcpy(DirEntryInfo[i], info, 5); // copy disk number info if present
}
if (len > 30)
len = 30; // trim display length if longer than 30 characters
if (i != iSelectedEntry && info != NULL)
{ // display disk number info for not selected items
strncpy(s + 1, lfn, 30-6); // trimmed name
strncpy(s + 1+30-5, info, 5); // disk number
}
else
strncpy(s + 1, lfn, len); // display only name
}
else // no LFN
{
strncpy(s + 1, (const char*)DirEntry[k].Name, 8); // if no LFN then display base name (8 chars)
if (DirEntry[k].Attributes & ATTR_DIRECTORY && DirEntry[k].Extension[0] != ' ')
{
p = (char*)&DirEntry[k].Name[7];
j = 8;
do
{
if (*p-- != ' ')
break;
} while (--j);
s[1 + j++] = '.';
strncpy(s + 1 + j, (const char*)DirEntry[k].Extension, 3); // if no LFN then display base name (8 chars)
}
}
if (DirEntry[k].Attributes & ATTR_DIRECTORY) // mark directory with suffix
strcpy(&s[22], " <DIR>");
}
else
{
if (i == 0 && nDirEntries == 0) // selected directory is empty
strcpy(s, " No files!");
}
OsdWrite(i, s, i == iSelectedEntry,0); // display formatted line text
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
void _strncpy(char* pStr1, const char* pStr2, size_t nCount)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L2);
// customized strncpy() function to fill remaing destination string part with spaces
while (*pStr2 && nCount)
{
*pStr1++ = *pStr2++; // copy strings
nCount--;
}
while (nCount--)
*pStr1++ = ' '; // fill remaining space with spaces
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L2);
}
// insert floppy image pointed to to by global <file> into <drive>
void InsertFloppy(adfTYPE *drive)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
unsigned char i, j;
unsigned long tracks;
// calculate number of tracks in the ADF image file
tracks = file.size / (512*11);
if (tracks > MAX_TRACKS)
{
printf("UNSUPPORTED ADF SIZE!!! Too many tracks: %lu\r", tracks);
tracks = MAX_TRACKS;
}
drive->tracks = (unsigned char)tracks;
// fill index cache
for (i = 0; i < tracks; i++) // for every track get its start position within image file
{
drive->cache[i] = file.cluster; // start of the track within image file
for (j = 0; j < 11; j++)
FileNextSector(&file); // advance by track length (11 sectors)
}
// copy image file name into drive struct
if (file.long_name[0]) // file has long name
_strncpy(drive->name, file.long_name, sizeof(drive->name)); // copy long name
else
{
strncpy(drive->name, file.name, 8); // copy base name
memset(&drive->name[8], ' ', sizeof(drive->name) - 8); // fill the rest of the name with spaces
}
if (DiskInfo[0]) // if selected file has valid disk number info then copy it to its name in drive struct
{
drive->name[16] = ' '; // precede disk number info with space character
strncpy(&drive->name[17], DiskInfo, sizeof(DiskInfo)); // copy disk number info
}
// initialize the rest of drive struct
drive->status = DSK_INSERTED;
if (!(file.attributes & ATTR_READONLY)) // read-only attribute
drive->status |= DSK_WRITABLE;
drive->cluster_offset = drive->cache[0];
drive->sector_offset = 0;
drive->track = 0;
drive->track_prev = -1;
// some debug info
if (file.long_name[0])
printf("Inserting floppy: \"%s\"\r", file.long_name);
else
printf("Inserting floppy: \"%.11s\"\r", file.name);
printf("file attributes: 0x%02X\r", file.attributes);
printf("file size: %lu (%lu KB)\r", file.size, file.size >> 10);
printf("drive tracks: %u\r", drive->tracks);
printf("drive status: 0x%02X\r", drive->status);
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
/* Error Message */
void ErrorMessage(const char *message, unsigned char code)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
if (menustate == MENU_NONE2)
menustate = MENU_ERROR;
if (menustate == MENU_ERROR)
{
// OsdClear();
OsdSetTitle("Error",0);
OsdWrite(0, " *** ERROR ***", 1,0);
OsdWrite(1, "", 0,0);
strncpy(s, message, 32);
s[32] = 0;
OsdWrite(2, s, 0,0);
s[0] = 0;
if (code)
sprintf(s, " #%d", code);
OsdWrite(3, "", 0,0);
OsdWrite(4, s, 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
OsdEnable(0); // do not disable KEYBOARD
}
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
void InfoMessage(char *message)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
OsdWaitVBL();
if (menustate != MENU_INFO)
{
// OsdClear();
OsdSetTitle("Message",0);
OsdEnable(0); // do not disable keyboard
}
OsdWrite(0, "", 0,0);
OsdWrite(1, message, 0,0);
OsdWrite(2, "", 0,0);
OsdWrite(3, "", 0,0);
OsdWrite(4, "", 0,0);
OsdWrite(5, "", 0,0);
OsdWrite(6, "", 0,0);
OsdWrite(7, "", 0,0);
menu_timer = GetTimer(1000);
menustate = MENU_INFO;
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
void DebugMessage(char *message)
{
DEBUG_FUNC_IN(DEBUG_F_MENU | DEBUG_L1);
strncpy(&debuglines[debugptr*32],message,31);
debuglines[debugptr*32+31]=0;
debugptr=(debugptr+1)&7;
DEBUG_FUNC_OUT(DEBUG_F_MENU | DEBUG_L1);
}
| rkrajnc/minimig-mist | fw/ctrl/menu.c | C | gpl-3.0 | 80,458 |
<?php
return [
'AF' => 'Afganisztán',
'AX' => 'Åland-szigetek',
'AL' => 'Albánia',
'DZ' => 'Algéria',
'AS' => 'Amerikai Szamoa',
'VI' => 'Amerikai Virgin-szigetek',
'AD' => 'Andorra',
'AO' => 'Angola',
'AI' => 'Anguilla',
'AQ' => 'Antarktisz',
'AG' => 'Antigua és Barbuda',
'AR' => 'Argentína',
'AW' => 'Aruba',
'AU' => 'Ausztrália',
'AT' => 'Ausztria',
'UM' => 'Az USA lakatlan külbirtokai',
'AZ' => 'Azerbajdzsán',
'BS' => 'Bahama-szigetek',
'BH' => 'Bahrein',
'BD' => 'Banglades',
'BB' => 'Barbados',
'BY' => 'Belarusz',
'BE' => 'Belgium',
'BZ' => 'Belize',
'BJ' => 'Benin',
'BM' => 'Bermuda',
'BT' => 'Bhután',
'GW' => 'Bissau-Guinea',
'BO' => 'Bolívia',
'BA' => 'Bosznia-Hercegovina',
'BW' => 'Botswana',
'BV' => 'Bouvet-sziget',
'BR' => 'Brazília',
'IO' => 'Brit Indiai-óceáni Terület',
'VG' => 'Brit Virgin-szigetek',
'BN' => 'Brunei',
'BG' => 'Bulgária',
'BF' => 'Burkina Faso',
'BI' => 'Burundi',
'CL' => 'Chile',
'CY' => 'Ciprus',
'KM' => 'Comore-szigetek',
'CK' => 'Cook-szigetek',
'CR' => 'Costa Rica',
'CW' => 'Curaçao',
'TD' => 'Csád',
'CZ' => 'Csehország',
'DK' => 'Dánia',
'ZA' => 'Dél-afrikai Köztársaság',
'KR' => 'Dél-Korea',
'SS' => 'Dél-Szudán',
'GS' => 'Déli-Georgia és Déli-Sandwich-szigetek',
'DM' => 'Dominika',
'DO' => 'Dominikai Köztársaság',
'DJ' => 'Dzsibuti',
'EC' => 'Ecuador',
'GQ' => 'Egyenlítői-Guinea',
'US' => 'Egyesült Államok',
'AE' => 'Egyesült Arab Emírségek',
'GB' => 'Egyesült Királyság',
'EG' => 'Egyiptom',
'CI' => 'Elefántcsontpart',
'ER' => 'Eritrea',
'KP' => 'Észak-Korea',
'MK' => 'Észak-Macedónia',
'MP' => 'Északi Mariana-szigetek',
'EE' => 'Észtország',
'ET' => 'Etiópia',
'FK' => 'Falkland-szigetek',
'FO' => 'Feröer szigetek',
'FJ' => 'Fidzsi',
'FI' => 'Finnország',
'TF' => 'Francia Déli Területek',
'GF' => 'Francia Guyana',
'PF' => 'Francia Polinézia',
'FR' => 'Franciaország',
'PH' => 'Fülöp-szigetek',
'GA' => 'Gabon',
'GM' => 'Gambia',
'GH' => 'Ghána',
'GI' => 'Gibraltár',
'GR' => 'Görögország',
'GD' => 'Grenada',
'GL' => 'Grönland',
'GE' => 'Grúzia',
'GP' => 'Guadeloupe',
'GU' => 'Guam',
'GT' => 'Guatemala',
'GG' => 'Guernsey',
'GN' => 'Guinea',
'GY' => 'Guyana',
'HT' => 'Haiti',
'HM' => 'Heard-sziget és McDonald-szigetek',
'BQ' => 'Holland Karib-térség',
'NL' => 'Hollandia',
'HN' => 'Honduras',
'HK' => 'Hongkong KKT',
'HR' => 'Horvátország',
'IN' => 'India',
'ID' => 'Indonézia',
'IQ' => 'Irak',
'IR' => 'Irán',
'IE' => 'Írország',
'IS' => 'Izland',
'IL' => 'Izrael',
'JM' => 'Jamaica',
'JP' => 'Japán',
'YE' => 'Jemen',
'JE' => 'Jersey',
'JO' => 'Jordánia',
'KY' => 'Kajmán-szigetek',
'KH' => 'Kambodzsa',
'CM' => 'Kamerun',
'CA' => 'Kanada',
'CX' => 'Karácsony-sziget',
'QA' => 'Katar',
'KZ' => 'Kazahsztán',
'TL' => 'Kelet-Timor',
'KE' => 'Kenya',
'CN' => 'Kína',
'KG' => 'Kirgizisztán',
'KI' => 'Kiribati',
'CC' => 'Kókusz (Keeling)-szigetek',
'CO' => 'Kolumbia',
'CG' => 'Kongó – Brazzaville',
'CD' => 'Kongó – Kinshasa',
'CF' => 'Közép-afrikai Köztársaság',
'CU' => 'Kuba',
'KW' => 'Kuvait',
'LA' => 'Laosz',
'PL' => 'Lengyelország',
'LS' => 'Lesotho',
'LV' => 'Lettország',
'LB' => 'Libanon',
'LR' => 'Libéria',
'LY' => 'Líbia',
'LI' => 'Liechtenstein',
'LT' => 'Litvánia',
'LU' => 'Luxemburg',
'MG' => 'Madagaszkár',
'HU' => 'Magyarország',
'MO' => 'Makaó KKT',
'MY' => 'Malajzia',
'MW' => 'Malawi',
'MV' => 'Maldív-szigetek',
'ML' => 'Mali',
'MT' => 'Málta',
'IM' => 'Man-sziget',
'MA' => 'Marokkó',
'MH' => 'Marshall-szigetek',
'MQ' => 'Martinique',
'MR' => 'Mauritánia',
'MU' => 'Mauritius',
'YT' => 'Mayotte',
'MX' => 'Mexikó',
'MM' => 'Mianmar',
'FM' => 'Mikronézia',
'MD' => 'Moldova',
'MC' => 'Monaco',
'MN' => 'Mongólia',
'ME' => 'Montenegró',
'MS' => 'Montserrat',
'MZ' => 'Mozambik',
'NA' => 'Namíbia',
'NR' => 'Nauru',
'DE' => 'Németország',
'NP' => 'Nepál',
'NI' => 'Nicaragua',
'NE' => 'Niger',
'NG' => 'Nigéria',
'NU' => 'Niue',
'NF' => 'Norfolk-sziget',
'NO' => 'Norvégia',
'EH' => 'Nyugat-Szahara',
'IT' => 'Olaszország',
'OM' => 'Omán',
'RU' => 'Oroszország',
'AM' => 'Örményország',
'PK' => 'Pakisztán',
'PW' => 'Palau',
'PS' => 'Palesztin Autonómia',
'PA' => 'Panama',
'PG' => 'Pápua Új-Guinea',
'PY' => 'Paraguay',
'PE' => 'Peru',
'PN' => 'Pitcairn-szigetek',
'PT' => 'Portugália',
'PR' => 'Puerto Rico',
'RE' => 'Réunion',
'RO' => 'Románia',
'RW' => 'Ruanda',
'KN' => 'Saint Kitts és Nevis',
'LC' => 'Saint Lucia',
'MF' => 'Saint Martin',
'VC' => 'Saint Vincent és a Grenadine-szigetek',
'BL' => 'Saint-Barthélemy',
'PM' => 'Saint-Pierre és Miquelon',
'SB' => 'Salamon-szigetek',
'SV' => 'Salvador',
'SM' => 'San Marino',
'ST' => 'São Tomé és Príncipe',
'SC' => 'Seychelle-szigetek',
'SL' => 'Sierra Leone',
'SX' => 'Sint Maarten',
'ES' => 'Spanyolország',
'LK' => 'Srí Lanka',
'SR' => 'Suriname',
'CH' => 'Svájc',
'SJ' => 'Svalbard és Jan Mayen',
'SE' => 'Svédország',
'WS' => 'Szamoa',
'SA' => 'Szaúd-Arábia',
'SN' => 'Szenegál',
'SH' => 'Szent Ilona',
'RS' => 'Szerbia',
'SG' => 'Szingapúr',
'SY' => 'Szíria',
'SK' => 'Szlovákia',
'SI' => 'Szlovénia',
'SO' => 'Szomália',
'SD' => 'Szudán',
'SZ' => 'Szváziföld',
'TJ' => 'Tádzsikisztán',
'TW' => 'Tajvan',
'TZ' => 'Tanzánia',
'TH' => 'Thaiföld',
'TG' => 'Togo',
'TK' => 'Tokelau',
'TO' => 'Tonga',
'TR' => 'Törökország',
'TT' => 'Trinidad és Tobago',
'TN' => 'Tunézia',
'TC' => 'Turks- és Caicos-szigetek',
'TV' => 'Tuvalu',
'TM' => 'Türkmenisztán',
'UG' => 'Uganda',
'NC' => 'Új-Kaledónia',
'NZ' => 'Új-Zéland',
'UA' => 'Ukrajna',
'UY' => 'Uruguay',
'UZ' => 'Üzbegisztán',
'VU' => 'Vanuatu',
'VA' => 'Vatikán',
'VE' => 'Venezuela',
'VN' => 'Vietnám',
'WF' => 'Wallis és Futuna',
'ZM' => 'Zambia',
'ZW' => 'Zimbabwe',
'CV' => 'Zöld-foki Köztársaság',
];
| akaunting/akaunting | resources/lang/hu-HU/countries.php | PHP | gpl-3.0 | 6,780 |
/*
* This file is part of Cleanflight.
*
* Cleanflight is free software. You can redistribute
* this software and/or modify this software 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.
*
* Cleanflight 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 software.
*
* If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdbool.h>
#include <stdint.h>
#include <math.h>
#include "platform.h"
#if defined(USE_MAG_AK8963) || defined(USE_MAG_SPI_AK8963)
#include "build/debug.h"
#include "common/axis.h"
#include "common/maths.h"
#include "common/utils.h"
#include "drivers/bus.h"
#include "drivers/bus_i2c.h"
#include "drivers/bus_i2c_busdev.h"
#include "drivers/bus_spi.h"
#include "drivers/io.h"
#include "drivers/sensor.h"
#include "drivers/time.h"
#include "drivers/compass/compass.h"
#include "drivers/accgyro/accgyro.h"
#include "drivers/accgyro/accgyro_mpu.h"
#include "drivers/accgyro/accgyro_mpu6500.h"
#include "drivers/accgyro/accgyro_spi_mpu6500.h"
#include "drivers/accgyro/accgyro_spi_mpu9250.h"
#include "drivers/compass/compass_ak8963.h"
#include "scheduler/scheduler.h"
// This sensor is also available also part of the MPU-9250 connected to the secondary I2C bus.
// AK8963, mag sensor address
#define AK8963_MAG_I2C_ADDRESS 0x0C
#define AK8963_DEVICE_ID 0x48
// Registers
#define AK8963_MAG_REG_WIA 0x00
#define AK8963_MAG_REG_INFO 0x01
#define AK8963_MAG_REG_ST1 0x02
#define AK8963_MAG_REG_HXL 0x03
#define AK8963_MAG_REG_HXH 0x04
#define AK8963_MAG_REG_HYL 0x05
#define AK8963_MAG_REG_HYH 0x06
#define AK8963_MAG_REG_HZL 0x07
#define AK8963_MAG_REG_HZH 0x08
#define AK8963_MAG_REG_ST2 0x09
#define AK8963_MAG_REG_CNTL1 0x0A
#define AK8963_MAG_REG_CNTL2 0x0B
#define AK8963_MAG_REG_ASCT 0x0C // self test
#define AK8963_MAG_REG_I2CDIS 0x0F
#define AK8963_MAG_REG_ASAX 0x10 // Fuse ROM x-axis sensitivity adjustment value
#define AK8963_MAG_REG_ASAY 0x11 // Fuse ROM y-axis sensitivity adjustment value
#define AK8963_MAG_REG_ASAZ 0x12 // Fuse ROM z-axis sensitivity adjustment value
#define READ_FLAG 0x80
#define I2C_SLV0_EN 0x80
#define ST1_DATA_READY 0x01
#define ST1_DATA_OVERRUN 0x02
#define ST2_MAG_SENSOR_OVERFLOW 0x08
#define CNTL1_MODE_POWER_DOWN 0x00
#define CNTL1_MODE_ONCE 0x01
#define CNTL1_MODE_CONT1 0x02
#define CNTL1_MODE_CONT2 0x06
#define CNTL1_MODE_SELF_TEST 0x08
#define CNTL1_MODE_FUSE_ROM 0x0F
#define CNTL1_BIT_14_BIT 0x00
#define CNTL1_BIT_16_BIT 0x10
#define CNTL2_SOFT_RESET 0x01
#define I2CDIS_DISABLE_MASK 0x1D
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
static bool ak8963SpiWriteRegisterDelay(const busDevice_t *bus, uint8_t reg, uint8_t data)
{
spiBusWriteRegister(bus, reg, data);
delayMicroseconds(10);
return true;
}
static bool ak8963SlaveReadRegisterBuffer(const busDevice_t *slavedev, uint8_t reg, uint8_t *buf, uint8_t len)
{
const busDevice_t *bus = slavedev->busdev_u.mpuSlave.master;
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_ADDR, slavedev->busdev_u.mpuSlave.address | READ_FLAG); // set I2C slave address for read
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_REG, reg); // set I2C slave register
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_CTRL, (len & 0x0F) | I2C_SLV0_EN); // read number of bytes
delay(4);
__disable_irq();
bool ack = spiBusReadRegisterBuffer(bus, MPU_RA_EXT_SENS_DATA_00, buf, len); // read I2C
__enable_irq();
return ack;
}
static bool ak8963SlaveWriteRegister(const busDevice_t *slavedev, uint8_t reg, uint8_t data)
{
const busDevice_t *bus = slavedev->busdev_u.mpuSlave.master;
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_ADDR, slavedev->busdev_u.mpuSlave.address); // set I2C slave address for write
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_REG, reg); // set I2C slave register
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_DO, data); // set I2C sLave value
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_CTRL, (1 & 0x0F) | I2C_SLV0_EN); // write 1 byte
return true;
}
typedef struct queuedReadState_s {
bool waiting;
uint8_t len;
uint32_t readStartedAt; // time read was queued in micros.
} queuedReadState_t;
static queuedReadState_t queuedRead = { false, 0, 0};
static bool ak8963SlaveStartRead(const busDevice_t *slavedev, uint8_t reg, uint8_t len)
{
if (queuedRead.waiting) {
return false;
}
const busDevice_t *bus = slavedev->busdev_u.mpuSlave.master;
queuedRead.len = len;
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_ADDR, slavedev->busdev_u.mpuSlave.address | READ_FLAG); // set I2C slave address for read
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_REG, reg); // set I2C slave register
ak8963SpiWriteRegisterDelay(bus, MPU_RA_I2C_SLV0_CTRL, (len & 0x0F) | I2C_SLV0_EN); // read number of bytes
queuedRead.readStartedAt = micros();
queuedRead.waiting = true;
return true;
}
static uint32_t ak8963SlaveQueuedReadTimeRemaining(void)
{
if (!queuedRead.waiting) {
return 0;
}
int32_t timeSinceStarted = micros() - queuedRead.readStartedAt;
int32_t timeRemaining = 8000 - timeSinceStarted;
if (timeRemaining < 0) {
return 0;
}
return timeRemaining;
}
static bool ak8963SlaveCompleteRead(const busDevice_t *slavedev, uint8_t *buf)
{
uint32_t timeRemaining = ak8963SlaveQueuedReadTimeRemaining();
const busDevice_t *bus = slavedev->busdev_u.mpuSlave.master;
if (timeRemaining > 0) {
delayMicroseconds(timeRemaining);
}
queuedRead.waiting = false;
spiBusReadRegisterBuffer(bus, MPU_RA_EXT_SENS_DATA_00, buf, queuedRead.len); // read I2C buffer
return true;
}
static bool ak8963SlaveReadData(const busDevice_t *busdev, uint8_t *buf)
{
typedef enum {
CHECK_STATUS = 0,
WAITING_FOR_STATUS,
WAITING_FOR_DATA
} ak8963ReadState_e;
static ak8963ReadState_e state = CHECK_STATUS;
bool ack = false;
// we currently need a different approach for the MPU9250 connected via SPI.
// we cannot use the ak8963SlaveReadRegisterBuffer() method for SPI, it is to slow and blocks for far too long.
bool retry = true;
restart:
switch (state) {
case CHECK_STATUS: {
ak8963SlaveStartRead(busdev, AK8963_MAG_REG_ST1, 1);
state = WAITING_FOR_STATUS;
return false;
}
case WAITING_FOR_STATUS: {
uint32_t timeRemaining = ak8963SlaveQueuedReadTimeRemaining();
if (timeRemaining) {
return false;
}
ack = ak8963SlaveCompleteRead(busdev, &buf[0]);
uint8_t status = buf[0];
if (!ack || (status & ST1_DATA_READY) == 0) {
// too early. queue the status read again
state = CHECK_STATUS;
if (retry) {
retry = false;
goto restart;
}
return false;
}
// read the 6 bytes of data and the status2 register
ak8963SlaveStartRead(busdev, AK8963_MAG_REG_HXL, 7);
state = WAITING_FOR_DATA;
return false;
}
case WAITING_FOR_DATA: {
uint32_t timeRemaining = ak8963SlaveQueuedReadTimeRemaining();
if (timeRemaining) {
return false;
}
ack = ak8963SlaveCompleteRead(busdev, &buf[0]);
state = CHECK_STATUS;
}
}
return ack;
}
#endif
static bool ak8963ReadRegisterBuffer(const busDevice_t *busdev, uint8_t reg, uint8_t *buf, uint8_t len)
{
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
if (busdev->bustype == BUSTYPE_MPU_SLAVE) {
return ak8963SlaveReadRegisterBuffer(busdev, reg, buf, len);
}
#endif
return busReadRegisterBuffer(busdev, reg, buf, len);
}
static bool ak8963WriteRegister(const busDevice_t *busdev, uint8_t reg, uint8_t data)
{
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
if (busdev->bustype == BUSTYPE_MPU_SLAVE) {
return ak8963SlaveWriteRegister(busdev, reg, data);
}
#endif
return busWriteRegister(busdev, reg, data);
}
static bool ak8963DirectReadData(const busDevice_t *busdev, uint8_t *buf)
{
uint8_t status;
bool ack = ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_ST1, &status, 1);
if (!ack || (status & ST1_DATA_READY) == 0) {
return false;
}
return ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_HXL, buf, 7);
}
static int16_t parseMag(uint8_t *raw, int16_t gain) {
int ret = (int16_t)(raw[1] << 8 | raw[0]) * gain / 256;
return constrain(ret, INT16_MIN, INT16_MAX);
}
static bool ak8963Read(magDev_t *mag, int16_t *magData)
{
bool ack = false;
uint8_t buf[7];
const busDevice_t *busdev = &mag->busdev;
switch (busdev->bustype) {
#if defined(USE_MAG_SPI_AK8963) || defined(USE_MAG_AK8963)
case BUSTYPE_I2C:
case BUSTYPE_SPI:
ack = ak8963DirectReadData(busdev, buf);
break;
#endif
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
case BUSTYPE_MPU_SLAVE:
ack = ak8963SlaveReadData(busdev, buf);
break;
#endif
default:
break;
}
uint8_t status2 = buf[6];
if (!ack) {
return false;
}
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_BIT_16_BIT | CNTL1_MODE_ONCE); // start reading again uint8_t status2 = buf[6];
if (status2 & ST2_MAG_SENSOR_OVERFLOW) {
return false;
}
magData[X] = parseMag(buf + 0, mag->magGain[X]);
magData[Y] = parseMag(buf + 2, mag->magGain[Y]);
magData[Z] = parseMag(buf + 4, mag->magGain[Z]);
return true;
}
static bool ak8963Init(magDev_t *mag)
{
uint8_t asa[3];
uint8_t status;
const busDevice_t *busdev = &mag->busdev;
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_MODE_POWER_DOWN); // power down before entering fuse mode
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_MODE_FUSE_ROM); // Enter Fuse ROM access mode
ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_ASAX, asa, sizeof(asa)); // Read the x-, y-, and z-axis calibration values
mag->magGain[X] = asa[X] + 128;
mag->magGain[Y] = asa[Y] + 128;
mag->magGain[Z] = asa[Z] + 128;
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_MODE_POWER_DOWN); // power down after reading.
// Clear status registers
ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_ST1, &status, 1);
ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_ST2, &status, 1);
// Trigger first measurement
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL1, CNTL1_BIT_16_BIT | CNTL1_MODE_ONCE);
return true;
}
void ak8963BusInit(busDevice_t *busdev)
{
switch (busdev->bustype) {
#ifdef USE_MAG_AK8963
case BUSTYPE_I2C:
UNUSED(busdev);
break;
#endif
#ifdef USE_MAG_SPI_AK8963
case BUSTYPE_SPI:
IOHi(busdev->busdev_u.spi.csnPin); // Disable
IOInit(busdev->busdev_u.spi.csnPin, OWNER_COMPASS_CS, 0);
IOConfigGPIO(busdev->busdev_u.spi.csnPin, IOCFG_OUT_PP);
#ifdef USE_SPI_TRANSACTION
spiBusTransactionInit(busdev, SPI_MODE3_POL_HIGH_EDGE_2ND, SPI_CLOCK_STANDARD);
#else
spiBusSetDivisor(busdev, SPI_CLOCK_STANDARD);
#endif
break;
#endif
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
case BUSTYPE_MPU_SLAVE:
rescheduleTask(TASK_COMPASS, TASK_PERIOD_HZ(40));
// initialze I2C master via SPI bus
ak8963SpiWriteRegisterDelay(busdev->busdev_u.mpuSlave.master, MPU_RA_INT_PIN_CFG, MPU6500_BIT_INT_ANYRD_2CLEAR | MPU6500_BIT_BYPASS_EN);
ak8963SpiWriteRegisterDelay(busdev->busdev_u.mpuSlave.master, MPU_RA_I2C_MST_CTRL, 0x0D); // I2C multi-master / 400kHz
ak8963SpiWriteRegisterDelay(busdev->busdev_u.mpuSlave.master, MPU_RA_USER_CTRL, 0x30); // I2C master mode, SPI mode only
break;
#endif
default:
break;
}
}
void ak8963BusDeInit(const busDevice_t *busdev)
{
switch (busdev->bustype) {
#ifdef USE_MAG_AK8963
case BUSTYPE_I2C:
UNUSED(busdev);
break;
#endif
#ifdef USE_MAG_SPI_AK8963
case BUSTYPE_SPI:
spiPreinitByIO(busdev->busdev_u.spi.csnPin);
break;
#endif
#if defined(USE_MAG_AK8963) && (defined(USE_GYRO_SPI_MPU6500) || defined(USE_GYRO_SPI_MPU9250))
case BUSTYPE_MPU_SLAVE:
ak8963SpiWriteRegisterDelay(busdev->busdev_u.mpuSlave.master, MPU_RA_INT_PIN_CFG, MPU6500_BIT_INT_ANYRD_2CLEAR);
break;
#endif
default:
break;
}
}
bool ak8963Detect(magDev_t *mag)
{
uint8_t sig = 0;
busDevice_t *busdev = &mag->busdev;
if ((busdev->bustype == BUSTYPE_I2C || busdev->bustype == BUSTYPE_MPU_SLAVE) && busdev->busdev_u.mpuSlave.address == 0) {
busdev->busdev_u.mpuSlave.address = AK8963_MAG_I2C_ADDRESS;
}
ak8963BusInit(busdev);
ak8963WriteRegister(busdev, AK8963_MAG_REG_CNTL2, CNTL2_SOFT_RESET); // reset MAG
delay(4);
bool ack = ak8963ReadRegisterBuffer(busdev, AK8963_MAG_REG_WIA, &sig, 1); // check for AK8963
if (ack && sig == AK8963_DEVICE_ID) // 0x48 / 01001000 / 'H'
{
mag->init = ak8963Init;
mag->read = ak8963Read;
return true;
}
ak8963BusDeInit(busdev);
return false;
}
#endif
| cleanflight/cleanflight | src/main/drivers/compass/compass_ak8963.c | C | gpl-3.0 | 14,689 |
/* GIMP - The GNU Image Manipulation Program
* Copyright (C) 1995 Spencer Kimball and Peter Mattis
*
* gimpuiconfigurer.c
* Copyright (C) 2009 Martin Nordholts <martinn@src.gnome.org>
*
* 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 "config.h"
#include <gtk/gtk.h>
#include "gui-types.h"
#include "core/gimp.h"
#include "core/gimpcontext.h"
#include "widgets/gimpdialogfactory.h"
#include "widgets/gimpdock.h"
#include "widgets/gimpdockcolumns.h"
#include "widgets/gimpdockcontainer.h"
#include "widgets/gimpdockwindow.h"
#include "widgets/gimptoolbox.h"
#include "display/gimpdisplay.h"
#include "display/gimpdisplayshell.h"
#include "display/gimpdisplayshell-appearance.h"
#include "display/gimpimagewindow.h"
#include "menus/menus.h"
#include "gimpuiconfigurer.h"
enum
{
PROP_0,
PROP_GIMP
};
struct _GimpUIConfigurerPrivate
{
Gimp *gimp;
};
static void gimp_ui_configurer_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec);
static void gimp_ui_configurer_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec);
static void gimp_ui_configurer_move_docks_to_columns (GimpUIConfigurer *ui_configurer,
GimpImageWindow *uber_image_window);
static void gimp_ui_configurer_move_shells (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window,
GimpImageWindow *target_image_window);
static void gimp_ui_configurer_separate_docks (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window);
static void gimp_ui_configurer_move_docks_to_window (GimpUIConfigurer *ui_configurer,
GimpDockColumns *dock_columns,
GimpAlignmentType screen_side_destination);
static void gimp_ui_configurer_separate_shells (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window);
static void gimp_ui_configurer_configure_for_single_window (GimpUIConfigurer *ui_configurer);
static void gimp_ui_configurer_configure_for_multi_window (GimpUIConfigurer *ui_configurer);
static GimpImageWindow * gimp_ui_configurer_get_uber_window (GimpUIConfigurer *ui_configurer);
G_DEFINE_TYPE (GimpUIConfigurer, gimp_ui_configurer, GIMP_TYPE_OBJECT)
#define parent_class gimp_ui_configurer_parent_class
static void
gimp_ui_configurer_class_init (GimpUIConfigurerClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->set_property = gimp_ui_configurer_set_property;
object_class->get_property = gimp_ui_configurer_get_property;
g_object_class_install_property (object_class, PROP_GIMP,
g_param_spec_object ("gimp", NULL, NULL,
GIMP_TYPE_GIMP,
GIMP_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY));
g_type_class_add_private (klass,
sizeof (GimpUIConfigurerPrivate));
}
static void
gimp_ui_configurer_init (GimpUIConfigurer *ui_configurer)
{
ui_configurer->p = G_TYPE_INSTANCE_GET_PRIVATE (ui_configurer,
GIMP_TYPE_UI_CONFIGURER,
GimpUIConfigurerPrivate);
}
static void
gimp_ui_configurer_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
GimpUIConfigurer *ui_configurer = GIMP_UI_CONFIGURER (object);
switch (property_id)
{
case PROP_GIMP:
ui_configurer->p->gimp = g_value_get_object (value); /* don't ref */
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gimp_ui_configurer_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
GimpUIConfigurer *ui_configurer = GIMP_UI_CONFIGURER (object);
switch (property_id)
{
case PROP_GIMP:
g_value_set_object (value, ui_configurer->p->gimp);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void
gimp_ui_configurer_get_window_center_pos (GtkWindow *window,
gint *out_x,
gint *out_y)
{
gint x, y, w, h;
gtk_window_get_position (window, &x, &y);
gtk_window_get_size (window, &w, &h);
if (out_x)
*out_x = x + w / 2;
if (out_y)
*out_y = y + h / 2;
}
/**
* gimp_ui_configurer_get_relative_window_pos:
* @window_a:
* @window_b:
*
* Returns: At what side @window_b is relative to @window_a. Either
* GIMP_ALIGN_LEFT or GIMP_ALIGN_RIGHT.
**/
static GimpAlignmentType
gimp_ui_configurer_get_relative_window_pos (GtkWindow *window_a,
GtkWindow *window_b)
{
gint a_x, b_x;
gimp_ui_configurer_get_window_center_pos (window_a, &a_x, NULL);
gimp_ui_configurer_get_window_center_pos (window_b, &b_x, NULL);
return b_x < a_x ? GIMP_ALIGN_LEFT : GIMP_ALIGN_RIGHT;
}
static void
gimp_ui_configurer_move_docks_to_columns (GimpUIConfigurer *ui_configurer,
GimpImageWindow *uber_image_window)
{
GList *dialogs = NULL;
GList *dialog_iter = NULL;
dialogs =
g_list_copy (gimp_dialog_factory_get_open_dialogs (gimp_dialog_factory_get_singleton ()));
for (dialog_iter = dialogs; dialog_iter; dialog_iter = dialog_iter->next)
{
GimpDockWindow *dock_window;
GimpDockContainer *dock_container;
GimpDockColumns *dock_columns;
GList *docks;
GList *dock_iter;
if (!GIMP_IS_DOCK_WINDOW (dialog_iter->data))
continue;
dock_window = GIMP_DOCK_WINDOW (dialog_iter->data);
/* If the dock window is on the left side of the image window,
* move the docks to the left side. If the dock window is on the
* right side, move the docks to the right side of the image
* window.
*/
if (gimp_ui_configurer_get_relative_window_pos (GTK_WINDOW (uber_image_window),
GTK_WINDOW (dock_window)) == GIMP_ALIGN_LEFT)
dock_columns = gimp_image_window_get_left_docks (uber_image_window);
else
dock_columns = gimp_image_window_get_right_docks (uber_image_window);
dock_container = GIMP_DOCK_CONTAINER (dock_window);
g_object_add_weak_pointer (G_OBJECT (dock_window),
(gpointer) &dock_window);
docks = gimp_dock_container_get_docks (dock_container);
for (dock_iter = docks; dock_iter; dock_iter = dock_iter->next)
{
GimpDock *dock = GIMP_DOCK (dock_iter->data);
/* Move the dock from the image window to the dock columns
* widget. Note that we need a ref while the dock is parentless
*/
g_object_ref (dock);
gimp_dock_window_remove_dock (dock_window, dock);
gimp_dock_columns_add_dock (dock_columns, dock, -1);
g_object_unref (dock);
}
g_list_free (docks);
if (dock_window)
g_object_remove_weak_pointer (G_OBJECT (dock_window),
(gpointer) &dock_window);
/* Kill the window if removing the dock didn't destroy it
* already. This will be the case for the toolbox dock window
*/
if (GTK_IS_WIDGET (dock_window))
{
guint docks_len;
docks = gimp_dock_container_get_docks (dock_container);
docks_len = g_list_length (docks);
if (docks_len == 0)
{
gimp_dialog_factory_remove_dialog (gimp_dialog_factory_get_singleton (),
GTK_WIDGET (dock_window));
gtk_widget_destroy (GTK_WIDGET (dock_window));
}
g_list_free (docks);
}
}
g_list_free (dialogs);
}
/**
* gimp_ui_configurer_move_shells:
* @ui_configurer:
* @source_image_window:
* @target_image_window:
*
* Move all display shells from one image window to the another.
**/
static void
gimp_ui_configurer_move_shells (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window,
GimpImageWindow *target_image_window)
{
while (gimp_image_window_get_n_shells (source_image_window) > 0)
{
GimpDisplayShell *shell;
shell = gimp_image_window_get_shell (source_image_window, 0);
g_object_ref (shell);
gimp_image_window_remove_shell (source_image_window, shell);
gimp_image_window_add_shell (target_image_window, shell);
g_object_unref (shell);
}
}
/**
* gimp_ui_configurer_separate_docks:
* @ui_configurer:
* @image_window:
*
* Move out the docks from the image window.
**/
static void
gimp_ui_configurer_separate_docks (GimpUIConfigurer *ui_configurer,
GimpImageWindow *image_window)
{
GimpDockColumns *left_docks = NULL;
GimpDockColumns *right_docks = NULL;
left_docks = gimp_image_window_get_left_docks (image_window);
right_docks = gimp_image_window_get_right_docks (image_window);
gimp_ui_configurer_move_docks_to_window (ui_configurer, left_docks, GIMP_ALIGN_LEFT);
gimp_ui_configurer_move_docks_to_window (ui_configurer, right_docks, GIMP_ALIGN_RIGHT);
}
/**
* gimp_ui_configurer_move_docks_to_window:
* @dock_columns:
* @screen_side_destination: At what side of the screen the dock window
* should be put.
*
* Moves docks in @dock_columns into a new #GimpDockWindow and
* position it on the screen in a non-overlapping manner.
*/
static void
gimp_ui_configurer_move_docks_to_window (GimpUIConfigurer *ui_configurer,
GimpDockColumns *dock_columns,
GimpAlignmentType screen_side_destination)
{
GdkScreen *screen = gtk_widget_get_screen (GTK_WIDGET (dock_columns));
GList *docks = g_list_copy (gimp_dock_columns_get_docks (dock_columns));
GList *iter = NULL;
gboolean contains_toolbox = FALSE;
GtkWidget *dock_window = NULL;
GtkAllocation original_size = { 0, 0, 0, 0 };
/* Are there docks to move at all? */
if (! docks)
return;
/* Remember the size so we can set the new dock window to the same
* size
*/
gtk_widget_get_allocation (GTK_WIDGET (dock_columns), &original_size);
/* Do we need a toolbox window? */
for (iter = docks; iter; iter = iter->next)
{
GimpDock *dock = GIMP_DOCK (iter->data);
if (GIMP_IS_TOOLBOX (dock))
{
contains_toolbox = TRUE;
break;
}
}
/* Create a dock window to put the dock in. Checking for
* GIMP_IS_TOOLBOX() is kind of ugly but not a disaster. We need
* the dock window correctly configured if we create it for the
* toolbox
*/
dock_window =
gimp_dialog_factory_dialog_new (gimp_dialog_factory_get_singleton (),
screen,
NULL /*ui_manager*/,
(contains_toolbox ?
"gimp-toolbox-window" :
"gimp-dock-window"),
-1 /*view_size*/,
FALSE /*present*/);
for (iter = docks; iter; iter = iter->next)
{
GimpDock *dock = GIMP_DOCK (iter->data);
/* Move the dock to the window */
g_object_ref (dock);
gimp_dock_columns_remove_dock (dock_columns, dock);
gimp_dock_window_add_dock (GIMP_DOCK_WINDOW (dock_window), dock, -1);
g_object_unref (dock);
}
/* Position the window */
if (screen_side_destination == GIMP_ALIGN_LEFT)
gtk_window_parse_geometry (GTK_WINDOW (dock_window), "+0+0");
else if (screen_side_destination == GIMP_ALIGN_RIGHT)
gtk_window_parse_geometry (GTK_WINDOW (dock_window), "-0+0");
else
g_assert_not_reached ();
/* Try to keep the same size */
gtk_window_set_default_size (GTK_WINDOW (dock_window),
original_size.width,
original_size.height);
/* Don't forget to show the window */
gtk_widget_show (dock_window);
g_list_free (docks);
}
/**
* gimp_ui_configurer_separate_shells:
* @ui_configurer:
* @source_image_window:
*
* Create one image window per display shell and move it there.
**/
static void
gimp_ui_configurer_separate_shells (GimpUIConfigurer *ui_configurer,
GimpImageWindow *source_image_window)
{
/* The last display shell remains in its window */
while (gimp_image_window_get_n_shells (source_image_window) > 1)
{
GimpImageWindow *new_image_window;
GimpDisplayShell *shell;
/* Create a new image window */
new_image_window = gimp_image_window_new (ui_configurer->p->gimp,
NULL,
global_menu_factory,
gimp_dialog_factory_get_singleton ());
/* Move the shell there */
shell = gimp_image_window_get_shell (source_image_window, 1);
g_object_ref (shell);
gimp_image_window_remove_shell (source_image_window, shell);
gimp_image_window_add_shell (new_image_window, shell);
g_object_unref (shell);
/* FIXME: If we don't set a size request here the window will be
* too small. Get rid of this hack and fix it the proper way
*/
gtk_widget_set_size_request (GTK_WIDGET (new_image_window), 640, 480);
/* Show after we have added the shell */
gtk_widget_show (GTK_WIDGET (new_image_window));
}
}
/**
* gimp_ui_configurer_configure_for_single_window:
* @ui_configurer:
*
* Move docks and display shells into a single window.
**/
static void
gimp_ui_configurer_configure_for_single_window (GimpUIConfigurer *ui_configurer)
{
Gimp *gimp = ui_configurer->p->gimp;
GList *windows = gimp_get_image_windows (gimp);
GList *iter = NULL;
GimpImageWindow *uber_image_window = NULL;
/* Get and setup the window to put everything in */
uber_image_window = gimp_ui_configurer_get_uber_window (ui_configurer);
/* Mve docks to the left and right side of the image window */
gimp_ui_configurer_move_docks_to_columns (ui_configurer,
uber_image_window);
/* Move image shells from other windows to the uber image window */
for (iter = windows; iter; iter = g_list_next (iter))
{
GimpImageWindow *image_window = GIMP_IMAGE_WINDOW (iter->data);
/* Don't move stuff to itself */
if (image_window == uber_image_window)
continue;
/* Put the displays in the rest of the image windows into
* the uber image window
*/
gimp_ui_configurer_move_shells (ui_configurer,
image_window,
uber_image_window);
/* Destroy the window */
gimp_image_window_destroy (image_window);
}
g_list_free (windows);
}
/**
* gimp_ui_configurer_configure_for_multi_window:
* @ui_configurer:
*
* Moves all display shells into their own image window.
**/
static void
gimp_ui_configurer_configure_for_multi_window (GimpUIConfigurer *ui_configurer)
{
Gimp *gimp = ui_configurer->p->gimp;
GList *windows = gimp_get_image_windows (gimp);
GList *iter = NULL;
for (iter = windows; iter; iter = g_list_next (iter))
{
GimpImageWindow *image_window = GIMP_IMAGE_WINDOW (iter->data);
gimp_ui_configurer_separate_docks (ui_configurer, image_window);
gimp_ui_configurer_separate_shells (ui_configurer, image_window);
}
g_list_free (windows);
}
/**
* gimp_ui_configurer_get_uber_window:
* @ui_configurer:
*
* Returns: The window to be used as the main window for single-window
* mode.
**/
static GimpImageWindow *
gimp_ui_configurer_get_uber_window (GimpUIConfigurer *ui_configurer)
{
Gimp *gimp = ui_configurer->p->gimp;
GimpDisplay *display = gimp_get_display_iter (gimp)->data;
GimpDisplayShell *shell = gimp_display_get_shell (display);
GimpImageWindow *image_window = gimp_display_shell_get_window (shell);
return image_window;
}
/**
* gimp_ui_configurer_update_appearance:
* @ui_configurer:
*
* Updates the appearance of all shells in all image windows, so they
* do whatever they deem neccessary to fit the new UI mode mode.
**/
static void
gimp_ui_configurer_update_appearance (GimpUIConfigurer *ui_configurer)
{
Gimp *gimp = ui_configurer->p->gimp;
GList *windows = gimp_get_image_windows (gimp);
GList *list;
for (list = windows; list; list = g_list_next (list))
{
GimpImageWindow *image_window = GIMP_IMAGE_WINDOW (list->data);
gint n_shells;
gint i;
n_shells = gimp_image_window_get_n_shells (image_window);
for (i = 0; i < n_shells; i++)
{
GimpDisplayShell *shell;
shell = gimp_image_window_get_shell (image_window, i);
gimp_display_shell_appearance_update (shell);
}
}
g_list_free (windows);
}
/**
* gimp_ui_configurer_configure:
* @ui_configurer:
* @single_window_mode:
*
* Configure the UI.
**/
void
gimp_ui_configurer_configure (GimpUIConfigurer *ui_configurer,
gboolean single_window_mode)
{
if (single_window_mode)
gimp_ui_configurer_configure_for_single_window (ui_configurer);
else
gimp_ui_configurer_configure_for_multi_window (ui_configurer);
gimp_ui_configurer_update_appearance (ui_configurer);
}
| mardy/gimb | app/gui/gimpuiconfigurer.c | C | gpl-3.0 | 20,013 |
<?php
namespace AfriCC\Tests\EPP\DOM;
use AfriCC\EPP\DOM\DOMElement;
use DOMDocument;
use PHPUnit\Framework\TestCase;
class DOMElementTest extends TestCase
{
public function testHasChildNodes()
{
$dom = new DOMDocument('1.0', 'utf-8');
$parent = new DOMElement('foo');
$dom->appendChild($parent);
$this->assertFalse($parent->hasChildNodes());
$child = new DOMElement('bar');
$parent->appendChild($child);
$this->assertTrue($parent->hasChildNodes());
}
}
| hakger/php-epp2 | tests/EPP/DOM/DOMElementTest.php | PHP | gpl-3.0 | 527 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template customize_stream<Ch, Traits, signed char, void></title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../property_tree/reference.html#header.boost.property_tree.stream_translator_hpp" title="Header <boost/property_tree/stream_translator.hpp>">
<link rel="prev" href="customiz_idm45507095445648.html" title="Struct template customize_stream<Ch, Traits, F, typename boost::enable_if< detail::is_inexact< F > >::type>">
<link rel="next" href="customiz_idm45507101050960.html" title="Struct template customize_stream<Ch, Traits, unsigned char, void>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="customiz_idm45507095445648.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../property_tree/reference.html#header.boost.property_tree.stream_translator_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="customiz_idm45507101050960.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.property_tree.customiz_idm45507087332800"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template customize_stream<Ch, Traits, signed char, void></span></h2>
<p>boost::property_tree::customize_stream<Ch, Traits, signed char, void></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../property_tree/reference.html#header.boost.property_tree.stream_translator_hpp" title="Header <boost/property_tree/stream_translator.hpp>">boost/property_tree/stream_translator.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Ch<span class="special">,</span> <span class="keyword">typename</span> Traits<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="customiz_idm45507087332800.html" title="Struct template customize_stream<Ch, Traits, signed char, void>">customize_stream</a><span class="special"><</span><span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span><span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span><span class="special">,</span> <span class="keyword">void</span><span class="special">></span> <span class="special">{</span>
<span class="comment">// <a class="link" href="customiz_idm45507087332800.html#idm45507087329712-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="customiz_idm45507087332800.html#idm45507087329152-bb"><span class="identifier">insert</span></a><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span><span class="special"><</span> <span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span><span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">void</span> <a class="link" href="customiz_idm45507087332800.html#idm45507101053632-bb"><span class="identifier">extract</span></a><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span><span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idm45555209708384"></a><h2>Description</h2>
<div class="refsect2">
<a name="idm45555209707968"></a><h3>
<a name="idm45507087329712-bb"></a><code class="computeroutput">customize_stream</code> public static functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idm45507087329152-bb"></a><span class="identifier">insert</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span><span class="special"><</span> <span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span> s<span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span> e<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">void</span> <a name="idm45507101053632-bb"></a><span class="identifier">extract</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">Ch</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span> s<span class="special">,</span> <span class="keyword">signed</span> <span class="keyword">char</span> <span class="special">&</span> e<span class="special">)</span><span class="special">;</span></pre></li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2008-2010 Marcin Kalicinski<br>Copyright © 2010-2013 Sebastian
Redl<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="customiz_idm45507095445648.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../property_tree/reference.html#header.boost.property_tree.stream_translator_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="customiz_idm45507101050960.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| gwq5210/litlib | thirdparty/sources/boost_1_60_0/doc/html/boost/property_tree/customiz_idm45507087332800.html | HTML | gpl-3.0 | 8,354 |
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7d23177b1abff1b80b9a2d6ffbc881f6562a2359/hapi/hapi.d.ts
declare module "hapi" {
import http = require("http");
import stream = require("stream");
import Events = require("events");
import url = require("url");
interface IDictionary<T> {
[key: string]: T;
}
interface IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IThenable<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IThenable<U>;
}
interface IPromise<R> extends IThenable<R> {
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
then<U>(onFulfilled?: (value: R) => U | IThenable<U>, onRejected?: (error: any) => void): IPromise<U>;
catch<U>(onRejected?: (error: any) => U | IThenable<U>): IPromise<U>;
}
export interface IHeaderOptions {
append?: boolean;
separator?: string;
override?: boolean;
duplicate?: boolean;
}
/** Boom Module for errors. https://github.com/hapijs/boom
* boom provides a set of utilities for returning HTTP errors. Each utility returns a Boom error response object (instance of Error) which includes the following properties: */
export interface IBoom extends Error {
/** if true, indicates this is a Boom object instance. */
isBoom: boolean;
/** convenience bool indicating status code >= 500. */
isServer: boolean;
/** the error message. */
message: string;
/** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */
output: {
/** the HTTP status code (typically 4xx or 5xx). */
statusCode: number;
/** an object containing any HTTP headers where each key is a header name and value is the header content. */
headers: IDictionary<string>;
/** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */
payload: {
/** the HTTP status code, derived from error.output.statusCode. */
statusCode: number;
/** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */
error: string;
/** the error message derived from error.message. */
message: string;
};
};
/** reformat()rebuilds error.output using the other object properties. */
reformat(): void;
}
/** cache functionality via the "CatBox" module. */
export interface ICatBoxCacheOptions {
/** a prototype function or catbox engine object. */
engine: any;
/** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */
name?: string;
/** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */
shared?: boolean;
}
/** Any connections configuration server defaults can be included to override and customize the individual connection. */
export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults {
/** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/
host?: string;
/** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/
address?: string;
/** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/
port?: string | number;
/** - the full public URI without the path (e.g. 'http://example.com:8080').If present, used as the connection info.uri otherwise constructed from the connection settings.*/
uri?: string;
/** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/
listener?: any;
/** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/
autoListen?: boolean;
/** caching headers configuration: */
cache?: {
/** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */
statuses: number[];
};
/** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/
labels?: string | string[];
/** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */
tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object;
}
export interface IConnectionConfigurationServerDefaults {
/** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */
app?: any;
/** connection load limits configuration where: */
load?: {
/** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxHeapUsedBytes: number;
/** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxRssBytes: number;
/** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxEventLoopDelay: number;
};
/** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */
plugins?: any;
/** controls how incoming request URIs are matched against the routing table: */
router?: {
/** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */
isCaseSensitive: boolean;
/** removes trailing slashes on incoming paths. Defaults to false. */
stripTrailingSlash: boolean;
};
/** a route options object used to set the default configuration for every route. */
routes?: IRouteAdditionalConfigurationOptions;
state?: IServerState;
}
/** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/
export interface IServerOptions {
/** application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */
app?: any;
/** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned:
a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')).
a configuration object with the following options:
enginea prototype function or catbox engine object.
namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well.
sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false.
other options passed to the catbox strategy used.
an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */
cache?: string | ICatBoxCacheOptions | Array<ICatBoxCacheOptions> | any;
/** sets the default connections configuration which can be overridden by each connection where: */
connections?: IConnectionConfigurationServerDefaults;
/** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/
debug?: boolean | {
/** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */
log: string[];
/** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/
request: string[];
};
/** file system related settings*/
files?: {
/** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/
etagsCacheMaxSize?: number;
};
/** process load monitoring*/
load?: {
/** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/
sampleInterval?: number;
};
/** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime.*/
mime?: any;
/** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */
minimal?: boolean;
/** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/
plugins?: IDictionary<any>;
}
export interface IServerViewCompile {
(template: string, options: any): void;
(template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void;
}
export interface IServerViewsAdditionalOptions {
/** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/
path?: string;
/**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path).
*/
partialsPath?: string;
/**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/
helpersPath?: string;
/**relativeTo - a base path used as prefix for path and partialsPath.No default.*/
relativeTo?: string;
/**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/
layout?: boolean | string;
/**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/
layoutPath?: string;
/**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/
layoutKeywork?: string;
/**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/
encoding?: string;
/**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/
isCached?: boolean;
/**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/
allowAbsolutePaths?: boolean;
/**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/
allowInsecureAccess?: boolean;
/**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/
compileOptions?: any;
/**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/
runtimeOptions?: any;
/**contentType - the content type of the engine results.Defaults to 'text/html'.*/
contentType?: string;
/**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/
compileMode?: string;
/**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/
context?: any;
}
export interface IServerViewsEnginesOptions extends IServerViewsAdditionalOptions {
/**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings.
* If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/
module: {
compile?(template: any, options: any): (context: any, options: any) => void;
compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void;
};
}
/**Initializes the server views manager
var Hapi = require('hapi');
var server = new Hapi.Server();
server.views({
engines: {
html: require('handlebars'),
jade: require('jade')
},
path: '/static/templates'
});
When server.views() is called within a plugin, the views manager is only available to plugins methods.
*/
export interface IServerViewsConfiguration extends IServerViewsAdditionalOptions {
/** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/
engines: IDictionary<any> | IServerViewsEnginesOptions;
/** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/
defaultExtension?: string;
}
interface IReplyMethods {
/** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200.
* The data argument is only used for passing back authentication data and is ignored elsewhere. */
continue(credentialData?: any): void;
/** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */
file(/** the file path. */
path: string,
/** optional settings: */
options?: {
/** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/
filename?: string;
/** specifies whether to include the 'Content-Disposition' header with the response. Available values:
false - header is not included. This is the default value.
'attachment'
'inline'*/
mode?: boolean | string;
/** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */
lookupCompressed: boolean;
}): void;
/** Concludes the handler activity by returning control over to the router with a templatized view response.
the response flow control rules apply. */
view(/** the template filename and path, relative to the templates path configured via the server views manager. */
template: string,
/** optional object used by the template to render context-specific result. Defaults to no context {}. */
context?: {},
/** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */
options?: any): Response;
/** Sets a header on the response */
header(name: string, value: string, options?: IHeaderOptions): Response;
/** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed
The response flow control rules do not apply. */
close(options?: {
/** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */
end?: boolean;
}): void;
/** Proxies the request to an upstream endpoint.
the response flow control rules do not apply. */
proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */
options: IProxyHandlerConfig): void;
/** Redirects the client to the specified uri. Same as calling reply().redirect(uri).
he response flow control rules apply. */
redirect(uri: string): ResponseRedirect;
/** Replies with the specified response */
response(result: any): Response;
/** Sets a cookie on the response */
state(name: string, value: any, options?: any): void;
/** Clears a cookie on the response */
unstate(name: string, options?: any): void;
}
/** Concludes the handler activity by setting a response and returning control over to the framework where:
erran optional error response.
result an optional response payload.
Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first.
FLOW CONTROL:
When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */
export interface IReply extends IReplyMethods {
<T>(err: Error,
result?: string | number | boolean | Buffer | stream.Stream | IPromise<T> | T,
/** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */
credentialData?: any): IBoom;
/** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */
<T>(result: string | number | boolean | Buffer | stream.Stream | IPromise<T> | T): Response;
}
/** Concludes the handler activity by setting a response and returning control over to the framework where:
erran optional error response.
result an optional response payload.
Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first.
FLOW CONTROL:
When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */
export interface IStrictReply<T> extends IReplyMethods {
(err: Error,
result?: IPromise<T> | T,
/** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */
credentialData?: any): IBoom;
/** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */
(result: IPromise<T> | T): Response;
}
export interface ISessionHandler {
(request: Request, reply: IReply): void;
<T>(request: Request, reply: IStrictReply<T>): void;
}
export interface IRequestHandler<T> {
(request: Request): T;
}
export interface IFailAction {
(source: string, error: any, next: () => void): void
}
/** generates a reverse proxy handler */
export interface IProxyHandlerConfig {
/** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/
host?: string;
/** the upstream service port. */
port?: number;
/** The protocol to use when making a request to the proxied host:
'http'
'https'*/
protocol?: string;
/** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/
uri?: string;
/** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/
passThrough?: boolean;
/** localStatePassThrough - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/
localStatePassThrough?: boolean;
/**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/
acceptEncoding?: boolean;
/** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/
rejectUnauthorized?: boolean;
/**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/
xforward?: boolean;
/** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/
redirects?: boolean | number;
/**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/
timeout?: number;
/** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where:
request - is the incoming request object.
callback - is function(err, uri, headers) where:
err - internal error condition.
uri - the absolute proxy URI.
headers - optional object where each key is an HTTP request header and the value is the header content.*/
mapUri?: (request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void) => void;
/** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/
onResponse?: (err: any,
res: http.ServerResponse,
req: Request,
reply: IReply,
settings: IProxyHandlerConfig,
ttl: number) => void;
/** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/
ttl?: number;
/** - a node http(s) agent to be used for connections to upstream server. see https://nodejs.org/api/http.html#http_class_http_agent */
agent?: http.Agent;
/** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/
maxSockets?: boolean | number;
}
/** TODO: fill in joi definition */
export interface IJoi {
}
/** a validation function using the signature function(value, options, next) */
export interface IValidationFunction {
(/** the object containing the path parameters. */
value: any,
/** the server validation options. */
options: any,
/** the callback function called when validation is completed. */
next: (err: any, value: any) => void): void;
}
/** a custom error handler function with the signature 'function(request, reply, source, error)` */
export interface IRouteFailFunction {
/** a custom error handler function with the signature 'function(request, reply, source, error)` */
(/** - the [request object]. */
request: Request,
/** the continuation reply interface. */
reply: IReply,
/** the source of the invalid field (e.g. 'path', 'query', 'payload'). */
source: string,
/** the error object prepared for the client response (including the validation function error under error.data). */
error: any): void;
}
/** Each route can be customize to change the default behavior of the request lifecycle using the following options: */
export interface IRouteAdditionalConfigurationOptions {
/** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */
app?: any;
/** authentication configuration.Value can be: false to disable authentication if a default strategy is set.
a string with the name of an authentication strategy registered with server.auth.strategy().
an object */
auth?: boolean | string |
{
/** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values:
'required'authentication is required.
'optional'authentication is optional (must be valid if present).
'try'same as 'optional' but allows for invalid authentication. */
mode?: string;
/** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */
strategies?: string | Array<string>;
/** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values:
falseno payload authentication.This is the default value.
'required'payload authentication required.This is the default value when the scheme sets options.payload to true.
'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */
payload?: string;
/** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */
scope?: string | Array<string> | boolean;
/** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values:
anythe authentication can be on behalf of a user or application.This is the default value.
userthe authentication must be on behalf of a user.
appthe authentication must be on behalf of an application. */
entity?: string;
/**
* an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming
* request and access is granted if at least one rule matches. Each rule object must include at least one of:
*/
access?: IRouteAdditionalConfigurationAuthAccess | IRouteAdditionalConfigurationAuthAccess[];
};
/** an object passed back to the provided handler (via this) when called. */
bind?: any;
/** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */
cache?: {
/** mines the privacy flag included in clientside caching using the 'Cache-Control' header.Values are:
fault'no privacy flag.This is the default setting.
'public'mark the response as suitable for public caching.
'private'mark the response as suitable only for private caching. */
privacy: string;
/** relative expiration expressed in the number of milliseconds since the item was saved in the cache.Cannot be used together with expiresAt. */
expiresIn: number;
/** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire.Cannot be used together with expiresIn. */
expiresAt: string;
};
/** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */
cors?: {
/** a strings array of allowed origin servers ('Access-Control-Allow-Origin').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */
origin?: Array<string>;
/** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the 'Access-Control-Allow-Origin' response header.When false, the origin config is returned as- is.Defaults to true. */
matchOrigin?: boolean;
/** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */
isOriginExposed?: boolean;
/** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */
maxAge?: number;
/** a strings array of allowed headers ('Access-Control-Allow-Headers').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */
headers?: string[];
/** a strings array of additional headers to headers.Use this to keep the default headers in place. */
additionalHeaders?: string[];
/** a strings array of allowed HTTP methods ('Access-Control-Allow-Methods').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */
methods?: string[];
/** a strings array of additional methods to methods.Use this to keep the default methods in place. */
additionalMethods?: string[];
/** a strings array of exposed headers ('Access-Control-Expose-Headers').Defaults to ['WWW-Authenticate', 'Server-Authorization']. */
exposedHeaders?: string[];
/** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */
additionalExposedHeaders?: string[];
/** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials').Defaults to false. */
credentials?: boolean;
/** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */
override?: boolean;
};
/** defines the behavior for serving static resources using the built-in route handlers for files and directories: */
files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */
relativeTo: string;
};
/** an alternative location for the route handler option. */
handler?: ISessionHandler | string | IRouteHandlerConfig;
/** an optional unique identifier used to look up the route using server.lookup(). */
id?: number;
/** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */
json?: {
/** the replacer function or array.Defaults to no action. */
replacer?: Function | string[];
/** number of spaces to indent nested object keys.Defaults to no indentation. */
space?: number | string;
/** string suffix added after conversion to JSON string.Defaults to no suffix. */
suffix?: string;
};
/** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */
jsonp?: string;
/** determines how the request payload is processed: */
payload?: {
/** the type of payload representation requested. The value must be one of:
'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used.
'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties.
'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */
output?: string;
/** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are:
'application/json'
'application/x-www-form-urlencoded'
'application/octet-stream'
'text/ *'
'multipart/form-data' */
parse?: string | boolean;
/** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */
allow?: string | string[];
/** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */
override?: string;
/** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */
maxBytes?: number;
/** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */
timeout?: number;
/** the directory used for writing file uploads.Defaults to os.tmpDir(). */
uploads?: string;
/** determines how to handle payload parsing errors. Allowed values are:
'error'return a Bad Request (400) error response. This is the default value.
'log'report the error but continue processing the request.
'ignore'take no action and continue processing the request. */
failAction?: string;
};
/** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */
plugins?: IDictionary<any>;
/** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */
pre?: any[];
/** validation rules for the outgoing response payload (response body).Can only validate object response: */
response?: {
/** the default HTTP status code when the payload is empty. Value can be 200 or 204.
Note that a 200 status code is converted to a 204 only at the time or response transmission
(the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */
emptyStatusCode?: number;
/** the default response object validation rules (for all non-error responses) expressed as one of:
true - any payload allowed (no validation performed). This is the default.
false - no payload allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
value - the object containing the response object.
options - the server validation options.
next(err) - the callback function called when validation is completed. */
schema?: boolean | any;
/** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */
status?: { [statusCode: number]: boolean | any };
/** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */
sample?: number;
/** defines what to do when a response fails validation.Options are:
errorreturn an Internal Server Error (500) error response.This is the default value.
loglog the error but send the response. */
failAction?: string;
/** if true, applies the validation rule changes to the response.Defaults to false. */
modify?: boolean;
/** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */
options?: any;
};
/** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */
security?: boolean | {
/** controls the 'Strict-Transport-Security' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */
hsts?: boolean | number | {
/** the max- age portion of the header, as a number.Default is 15768000. */
maxAge?: number;
/** a boolean specifying whether to add the includeSubdomains flag to the header. */
includeSubdomains?: boolean;
/** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */
preload?: boolean;
};
/** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */
xframe?: {
/** either 'deny', 'sameorigin', or 'allow-from' */
rule: string;
/** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */
source: string;
};
/** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */
xss?: boolean;
/** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */
noOpen?: boolean;
/** boolean controlling the 'X-Content-Type-Options' header.Defaults to true setting the header to its only and default option, 'nosniff'. */
noSniff?: boolean;
};
/** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */
state?: {
/** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */
parse: boolean;
/** determines how to handle cookie parsing errors.Allowed values are:
'error'return a Bad Request (400) error response.This is the default value.
'log'report the error but continue processing the request.
'ignore'take no action. */
failAction: string;
};
/** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */
validate?: {
/** validation rules for incoming request headers.Values allowed:
* trueany headers allowed (no validation performed).This is the default.
falseno headers allowed (this will cause all valid HTTP requests to fail).
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the request headers.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed.
*/
headers?: boolean | IJoi | IValidationFunction;
/** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed:
trueany path parameters allowed (no validation performed).This is the default.
falseno path variables allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the path parameters.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
params?: boolean | IJoi | IValidationFunction;
/** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed:
trueany query parameters allowed (no validation performed).This is the default.
falseno query parameters allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the query parameters.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
query?: boolean | IJoi | IValidationFunction;
/** validation rules for an incoming request payload (request body).Values allowed:
trueany payload allowed (no validation performed).This is the default.
falseno payload allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the payload object.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
payload?: boolean | IJoi | IValidationFunction;
/** an optional object with error fields copied into every validation error response. */
errorFields?: any;
/** determines how to handle invalid requests.Allowed values are:
'error'return a Bad Request (400) error response.This is the default value.
'log'log the error but continue processing the request.
'ignore'take no action.
OR a custom error handler function with the signature 'function(request, reply, source, error)` where:
requestthe request object.
replythe continuation reply interface.
sourcethe source of the invalid field (e.g. 'path', 'query', 'payload').
errorthe error object prepared for the client response (including the validation function error under error.data). */
failAction?: string | IRouteFailFunction;
/** options to pass to Joi.Useful to set global options such as stripUnknown or abortEarly (the complete list is available here: https://github.com/hapijs/joi#validatevalue-schema-options-callback ).Defaults to no options. */
options?: any;
};
/** define timeouts for processing durations: */
timeout?: {
/** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */
server: boolean | number;
/** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */
socket: boolean | number;
};
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route description used for generating documentation (string).
*/
description?: string;
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route notes used for generating documentation (string or array of strings).
*/
notes?: string | string[];
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route tags used for generating documentation (array of strings).
*/
tags?: string[]
}
/**
* specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches
*/
export interface IRouteAdditionalConfigurationAuthAccess {
/**
* the application scope required to access the route. Value can be a scope string or an array of scope strings.
* The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.
* If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character,
* that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials'
* scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties
* on the request object (query and params} to populate a dynamic scope by using {} characters around the property name,
* such as 'user-{params.id}'. Defaults to false (no scope requirements).
*/
scope?: string | Array<string> | boolean;
/** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values:
* any - the authentication can be on behalf of a user or application. This is the default value.
* user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy.
* app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy.
*/
entity?: string;
}
/** server.realm http://hapijs.com/api#serverrealm
The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(),
the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin).
Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties.
The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]).
exports.register = function (server, options, next) {
console.log(server.realm.modifiers.route.prefix);
return next();
};
*/
export interface IServerRealm {
/** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */
modifiers: {
/** routes preferences: */
route: {
/** - the route path prefix used by any calls to server.route() from the server. */
prefix: string;
/** the route virtual host settings used by any calls to server.route() from the server. */
vhost: string;
};
};
/** the active plugin name (empty string if at the server root). */
plugin: string;
/** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */
plugins: IDictionary<any>;
/** settings overrides */
settings: {
files: {
relativeTo: any;
};
bind: any;
}
}
/** server.state(name, [options]) http://hapijs.com/api#serverstatename-options
HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/
export interface IServerState {
/** - the cookie name string. */name: string;
/** - are the optional cookie settings: */options: {
/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number;
/** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean;
/** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean
/** - the path scope.Defaults to null (no path).*/path: any;
/** - the domain scope.Defaults to null (no domain). */domain: any;
/** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where:
request - the request object.
next - the continuation function using the function(err, value) signature.*/
autoValue: (request: Request, next: (err: any, value: any) => void) => void;
/** - encoding performs on the provided value before serialization. Options are:
'none' - no encoding. When used, the cookie value must be a string. This is the default value.
'base64' - string value is encoded using Base64.
'base64json' - object value is JSON-stringified than encoded using Base64.
'form' - object value is encoded using the x-www-form-urlencoded method.
'iron' - Encrypts and sign the value using iron.*/
encoding: string;
/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: {
/** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any;
/** - password used for HMAC key generation.*/password: string;
};
/** - password used for 'iron' encoding.*/password: string;
/** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any;
/** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean;
/** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean;
/** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean;
/** - overrides the default proxy localStatePassThrough setting.*/passThrough: any;
};
}
export interface IFileHandlerConfig {
/** a path string or function as described above.*/
path: string;
/** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/
filename?: string;
/**- specifies whether to include the 'Content-Disposition' header with the response. Available values:
false - header is not included. This is the default value.
'attachment'
'inline'*/
mode?: boolean | string;
/** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/
lookupCompressed: boolean;
}
/**http://hapijs.com/api#route-handler
Built-in handlers
The framework comes with a few built-in handler types available by setting the route handler config to an object containing one of these keys.*/
export interface IRouteHandlerConfig {
/** generates a static file endpoint for serving a single file. file can be set to:
a relative or absolute file path string (relative paths are resolved based on the route files configuration).
a function with the signature function(request) which returns the relative or absolute file path.
an object with the following options */
file?: string | IRequestHandler<void> | IFileHandlerConfig;
/** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options:
path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be:
a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string.
an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string).
a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response.
index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true.
listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false.
showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false.
redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false.
lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.
defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/
directory?: {
path: string | Array<string> | IRequestHandler<string> | IRequestHandler<Array<string>>;
index?: boolean | string | string[];
listing?: boolean;
showHidden?: boolean;
redirectToSlash?: boolean;
lookupCompressed?: boolean;
defaultExtension?: string;
};
proxy?: IProxyHandlerConfig;
view?: string | {
template: string;
context: {
payload: any;
params: any;
query: any;
pre: any;
}
};
config?: {
handler: any;
bind: any;
app: any;
plugins: {
[name: string]: any;
};
pre: Array<() => void>;
validate: {
headers: any;
params: any;
query: any;
payload: any;
errorFields?: any;
failAction?: string | IFailAction;
};
payload: {
output: {
data: any;
stream: any;
file: any;
};
parse?: any;
allow?: string | Array<string>;
override?: string;
maxBytes?: number;
uploads?: number;
failAction?: string;
};
response: {
schema: any;
sample: number;
failAction: string;
};
cache: {
privacy: string;
expiresIn: number;
expiresAt: number;
};
auth: string | boolean | {
mode: string;
strategies: Array<string>;
payload?: boolean | string;
tos?: boolean | string;
scope?: string | Array<string>;
entity: string;
};
cors?: boolean;
jsonp?: string;
description?: string;
notes?: string | Array<string>;
tags?: Array<string>;
};
}
/** Route configuration
The route configuration object*/
export interface IRouteConfiguration {
/** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/
path: string;
/** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match).
* Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/
method: string | string[];
/** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/
vhost?: string;
/** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/
handler?: ISessionHandler | string | IRouteHandlerConfig;
/** - additional route options.*/
config?: IRouteAdditionalConfigurationOptions;
}
/** Route public interface When route information is returned or made available as a property. http://hapijs.com/api#route-public-interface */
export interface IRoute {
/** the route HTTP method. */
method: string;
/** the route path. */
path: string;
/** the route vhost option if configured. */
vhost?: string | Array<string>;
/** the [active realm] associated with the route.*/
realm: IServerRealm;
/** the [route options] object with all defaults applied. */
settings: IRouteAdditionalConfigurationOptions;
}
export interface IServerAuthScheme {
/** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where:
request - the request object.
reply - the reply interface the authentication method must call when done authenticating the request where:
reply(err, response, result) - is called if authentication failed where:
err - any authentication error.
response - any authentication response action such as redirection. Ignored if err is present, otherwise required.
result - an object containing:
credentials - the authenticated credentials.
artifacts - optional authentication artifacts.
reply.continue(result) - is called if authentication succeeded where:
result - same object as result above.
When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route.
.If the err returned by the reply() method includes a message, no additional strategies will be attempted.
If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference.
var server = new Hapi.Server();
server.connection({ port: 80 });
var scheme = function (server, options) {
return {
authenticate: function (request, reply) {
var req = request.raw.req;
var authorization = req.headers.authorization;
if (!authorization) {
return reply(Boom.unauthorized(null, 'Custom'));
}
return reply(null, { credentials: { user: 'john' } });
}
};
};
server.auth.scheme('custom', scheme);*/
authenticate(request: Request, reply: IReply): void;
authenticate<T>(request: Request, reply: IStrictReply<T>): void;
/** payload(request, reply) - optional function called to authenticate the request payload where:
request - the request object.
reply(err, response) - is called if authentication failed where:
err - any authentication error.
response - any authentication response action such as redirection. Ignored if err is present, otherwise required.
reply.continue() - is called if payload authentication succeeded.
When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/
payload?(request: Request, reply: IReply): void;
payload?<T>(request: Request, reply: IStrictReply<T>): void;
/** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where:
request - the request object.
reply(err, response) - is called if an error occurred where:
err - any authentication error.
response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required.
reply.continue() - is called if the operation succeeded.*/
response?(request: Request, reply: IReply): void;
response?<T>(request: Request, reply: IStrictReply<T>): void;
/** an optional object */
options?: {
/** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/
payload: boolean;
}
}
/**the response object where:
statusCode - the HTTP status code.
headers - an object containing the headers set.
payload - the response payload string.
rawPayload - the raw response payload buffer.
raw - an object with the injection request and response objects:
req - the simulated node request object.
res - the simulated node response object.
result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string).
request - the request object.*/
export interface IServerInjectResponse {
statusCode: number;
headers: IDictionary<string>;
payload: string;
rawPayload: Buffer;
raw: {
req: http.IncomingMessage;
res: http.ServerResponse
};
result: string;
request: Request;
}
export interface IServerInject {
(options: string | IServerInjectOptions, callback: (res: IServerInjectResponse) => void): void;
(options: string | IServerInjectOptions): IPromise<IServerInjectResponse>;
}
export interface IServerInjectOptions {
/** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/
method: string;
/** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/
url: string;
/** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/
headers?: IDictionary<string>;
/** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/
payload?: string | {} | Buffer;
/** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/
credentials?: any;
/** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/
artifacts?: any;
/** sets the initial value of request.app*/
app?: any;
/** sets the initial value of request.plugins*/
plugins?: any;
/** allows access to routes with config.isInternal set to true. Defaults to false.*/
allowInternals?: boolean;
/** sets the remote address for the incoming connection.*/
remoteAddress?: boolean;
/**object with options used to simulate client request stream conditions for testing:
error - if true, emits an 'error' event after payload transmission (if any). Defaults to false.
close - if true, emits a 'close' event after payload transmission (if any). Defaults to false.
end - if false, does not end the stream. Defaults to true.*/
simulate?: {
error: boolean;
close: boolean;
end: boolean;
};
}
/** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts.
The return value is an array where each item is an object containing:
info - the connection.info the connection the table was generated for.
labels - the connection labels.
table - an array of routes where each route contains:
settings - the route config with defaults applied.
method - the HTTP method in lower case.
path - the route path.*/
export interface IConnectionTable {
info: any;
labels: any;
table: IRoute[];
}
export interface ICookieSettings {
/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/
ttl?: number;
/** - sets the 'Secure' flag.Defaults to false.*/
isSecure?: boolean;
/** - sets the 'HttpOnly' flag.Defaults to false.*/
isHttpOnly?: boolean;
/** - the path scope.Defaults to null (no path).*/
path?: string;
/** - the domain scope.Defaults to null (no domain).*/
domain?: any;
/** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where:
request - the request object.
next - the continuation function using the function(err, value) signature.*/
autoValue?: (request: Request, next: (err: any, value: any) => void) => void;
/** - encoding performs on the provided value before serialization.Options are:
'none' - no encoding.When used, the cookie value must be a string.This is the default value.
'base64' - string value is encoded using Base64.
'base64json' - object value is JSON- stringified than encoded using Base64.
'form' - object value is encoded using the x- www - form - urlencoded method. */
encoding?: string;
/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:
integrity - algorithm options.Defaults to require('iron').defaults.integrity.
password - password used for HMAC key generation. */
sign?: { integrity: any; password: string; }
password?: string;
iron?: any;
ignoreErrors?: boolean;
clearInvalid?: boolean;
strictHeader?: boolean;
passThrough?: any;
}
/** method - the method function with the signature is one of:
function(arg1, arg2, ..., argn, next) where:
arg1, arg2, etc. - the method function arguments.
next - the function called when the method is done with the signature function(err, result, ttl) where:
err - error response if the method failed.
result - the return value.
ttl - 0 if result is valid but cannot be cached. Defaults to cache policy.
function(arg1, arg2, ..., argn) where:
arg1, arg2, etc. - the method function arguments.
the callback option is set to false.
the method must returns a value (result, Error, or a promise) or throw an Error.*/
export interface IServerMethod {
//(): void;
//(next: (err: any, result: any, ttl: number) => void): void;
//(arg1: any): void;
//(arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void;
//(arg1: any, arg2: any): void;
(...args: any[]): void;
}
/** options - optional configuration:
bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered.
cache - the same cache configuration used in server.cache().
callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true.
generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/
export interface IServerMethodOptions {
bind?: any;
cache?: ICatBoxCacheOptions;
callback?: boolean;
generateKey?(args: any[]): string;
}
/** Request object
The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle.
Request events
The request object supports the following events:
'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
'finish' - emitted when the request payload finished reading. The event method signature is function ().
'disconnect' - emitted when a request errors or aborts unexpectedly.
var Crypto = require('crypto');
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
var hash = Crypto.createHash('sha1');
request.on('peek', function (chunk) {
hash.update(chunk);
});
request.once('finish', function () {
console.log(hash.digest('hex'));
});
request.once('disconnect', function () {
console.error('request aborted');
});
return reply.continue();
});*/
export class Request extends Events.EventEmitter {
/** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/
app: any;
/** authentication information*/
auth: {
/** true is the request has been successfully authenticated, otherwise false.*/
isAuthenticated: boolean;
/** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/
credentials: any;
/** an artifact object received from the authentication strategy and used in authentication-related actions.*/
artifacts: any;
/** the route authentication mode.*/
mode: any;
/** the authentication error is failed and mode set to 'try'.*/
error: any;
};
/** the connection used by this request*/
connection: ServerConnection;
/** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/
domain: any;
/** the raw request headers (references request.raw.headers).*/
headers: IDictionary<string>;
/** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/
id: number;
/** request information */
info: {
/** the request preferred encoding. */
acceptEncoding: string;
/** if CORS is enabled for the route, contains the following: */
cors: {
isOriginMatch: boolean; /** true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */
};
/** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */
host: string;
/** the hostname part of the 'Host' header (e.g. 'example.com').*/
hostname: string;
/** request reception timestamp. */
received: number;
/** content of the HTTP 'Referrer' (or 'Referer') header. */
referrer: string;
/** remote client IP address. */
remoteAddress: string;
/** remote client port. */
remotePort: number;
/** request response timestamp (0 is not responded yet). */
responded: number;
};
/** the request method in lower case (e.g. 'get', 'post'). */
method: string;
/** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */
mime: string;
/** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/
orig: {
params: any;
query: any;
payload: any;
};
/** an object where each key is a path parameter name with matching value as described in Path parameters.*/
params: IDictionary<string>;
/** an array containing all the path params values in the order they appeared in the path.*/
paramsArray: string[];
/** the request URI's path component. */
path: string;
/** the request payload based on the route payload.output and payload.parse settings.*/
payload: stream.Readable | Buffer | any;
/** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/
plugins: any;
/** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/
pre: IDictionary<any>;
/** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/
response: Response;
/**preResponses - same as pre but represented as the response object created by the pre method.*/
preResponses: any;
/**an object containing the query parameters.*/
query: any;
/** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/
raw: {
req: http.IncomingMessage;
res: http.ServerResponse;
};
/** the route public interface.*/
route: IRoute;
/** the server object. */
server: Server;
/** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */
state: any;
/** complex object contining details on the url */
url: {
/** null when i tested */
auth: any;
/** null when i tested */
hash: any;
/** null when i tested */
host: any;
/** null when i tested */
hostname: any;
href: string;
path: string;
/** path without search*/
pathname: string;
/** null when i tested */
port: any;
/** null when i tested */
protocol: any;
/** querystring parameters*/
query: IDictionary<string>;
/** querystring parameters as a string*/
search: string;
/** null when i tested */
slashes: any;
};
/** request.setUrl(url)
Available only in 'onRequest' extension methods.
Changes the request URI before the router begins processing the request where:
url - the new request path value.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to '/test'
request.setUrl('/test');
return reply.continue();
});*/
setUrl(url: string | url.Url): void;
/** request.setMethod(method)
Available only in 'onRequest' extension methods.
Changes the request method before the router begins processing the request where:
method - is the request HTTP method (e.g. 'GET').
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to 'GET'
request.setMethod('GET');
return reply.continue();
});*/
setMethod(method: string): void;
/** request.log(tags, [data, [timestamp]])
Always available.
Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are:
data - an optional message string or object with the application data being logged.
timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).
Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('request', function (request, event, tags) {
if (tags.error) {
console.log(event);
}
});
var handler = function (request, reply) {
request.log(['test', 'error'], 'Test event');
return reply();
};
*/
log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/
tags: string | string[],
/** an optional message string or object with the application data being logged.*/
data?: any,
/** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/
timestamp?: number): void;
/** request.getLog([tags], [internal])
Always available.
Returns an array containing the events matching any of the tags specified (logical OR)
request.getLog();
request.getLog('error');
request.getLog(['error', 'auth']);
request.getLog(['error'], true);
request.getLog(false);*/
getLog(/** is a single tag string or array of tag strings. If no tags specified, returns all events.*/
tags?: string,
/** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/
internal?: boolean): string[];
/** request.tail([name])
Available until immediately after the 'response' event is emitted.
Adds a request tail which has to complete before the request lifecycle is complete where:
name - an optional tail name used for logging purposes.
Returns a tail function which must be called when the tail activity is completed.
Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it).
When all tails completed, the server emits a 'tail' event.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
var get = function (request, reply) {
var dbTail = request.tail('write to database');
db.save('key', 'value', function () {
dbTail();
});
return reply('Success!');
};
server.route({ method: 'GET', path: '/', handler: get });
server.on('tail', function (request) {
console.log('Request completed including db activity');
});*/
tail(/** an optional tail name used for logging purposes.*/
name?: string): Function;
}
/** Response events
The response object supports the following events:
'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
var Crypto = require('crypto');
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onPreResponse', function (request, reply) {
var response = request.response;
if (response.isBoom) {
return reply();
}
var hash = Crypto.createHash('sha1');
response.on('peek', function (chunk) {
hash.update(chunk);
});
response.once('finish', function () {
console.log(hash.digest('hex'));
});
return reply.continue();
});*/
export class Response extends Events.EventEmitter {
isBoom: boolean;
/** the HTTP response status code. Defaults to 200 (except for errors).*/
statusCode: number;
/** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/
headers: IDictionary<string>;
/** the value provided using the reply interface.*/
source: any;
/** a string indicating the type of source with available values:
'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view).
'buffer' - a Buffer.
'view' - a view generated with reply.view().
'file' - a file generated with reply.file() of via the directory handler.
'stream' - a Stream.
'promise' - a Promise object. */
variety: string;
/** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/
app: any;
/** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */
plugins: any;
/** settings - response handling flags:
charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'.
encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'.
passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true.
stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding.
ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override.
varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/
settings: {
charset: string;
encoding: string;
passThrough: boolean;
stringify: any;
ttl: number;
varyEtag: boolean;
}
/** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where:
length - the header value. Must match the actual payload size.*/
bytes(length: number): Response;
/** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/
charset(charset: string): Response;
/** sets the HTTP status code where:
statusCode - the HTTP status code.*/
code(statusCode: number): Response;
/** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/
created(uri: string): Response;
/** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/
encoding(encoding: string): Response;
/** etag(tag, options) - sets the representation entity tag where:
tag - the entity tag string without the double-quote.
options - optional settings where:
weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false.
vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/
etag(tag: string, options: {
weak: boolean; vary: boolean;
}): Response;
/**header(name, value, options) - sets an HTTP header where:
name - the header name.
value - the header value.
options - optional settings where:
append - if true, the value is appended to any existing header value using separator. Defaults to false.
separator - string used as separator when appending to an exiting value. Defaults to ','.
override - if false, the header value is not set if an existing value present. Defaults to true.*/
header(name: string, value: string, options?: IHeaderOptions): Response;
/** hold() - puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. */
hold(): Response;
/** location(uri) - sets the HTTP 'Location' header where:
uri - an absolute or relative URI used as the 'Location' header value.*/
location(uri: string): Response;
/** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where:
uri - an absolute or relative URI used to redirect the client to another resource. */
redirect(uri: string): Response;
/** replacer(method) - sets the JSON.stringify() replacer argument where:
method - the replacer function or array. Defaults to none.*/
replacer(method: Function | Array<Function>): Response;
/** spaces(count) - sets the JSON.stringify() space argument where:
count - the number of spaces to indent nested object keys. Defaults to no indentation. */
spaces(count: number): Response;
/**state(name, value, [options]) - sets an HTTP cookie where:
name - the cookie name.
value - the cookie value. If no encoding is defined, must be a string.
options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/
state(name: string, value: string, options?: any): Response;
/** send() - resume the response which will be transmitted in the next tick. Available only after response.hold() is called and until response.send() is invoked once. */
send(): void;
/** sets a string suffix when the response is process via JSON.stringify().*/
suffix(suffix: string): void;
/** overrides the default route cache expiration rule for this response instance where:
msec - the time-to-live value in milliseconds.*/
ttl(msec: number): void;
/** type(mimeType) - sets the HTTP 'Content-Type' header where:
mimeType - is the mime type. Should only be used to override the built-in default for each response type. */
type(mimeType: string): Response;
/** clears the HTTP cookie by setting an expired value where:
name - the cookie name.
options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/
unstate(name: string, options?: { [key: string]: string }): Response;
/** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where:
header - the HTTP request header name.*/
vary(header: string): void;
}
/** When using the redirect() method, the response object provides these additional methods */
export class ResponseRedirect extends Response {
/** sets the status code to 302 or 307 (based on the rewritable() setting) where:
isTemporary - if false, sets status to permanent. Defaults to true.*/
temporary(isTemporary: boolean): void;
/** sets the status code to 301 or 308 (based on the rewritable() setting) where:
isPermanent - if true, sets status to temporary. Defaults to false. */
permanent(isPermanent: boolean): void;
/** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments:
isRewritable - if false, sets to non-rewritable. Defaults to true.
Permanent Temporary
Rewritable 301 302(1)
Non-rewritable 308(2) 307
Notes: 1. Default value. 2. Proposed code, not supported by all clients. */
rewritable(isRewritable: boolean): void;
}
/** info about a server connection */
export interface IServerConnectionInfo {
/** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/
id: string;
/** - the connection creation timestamp.*/
created: number;
/** - the connection start timestamp (0 when stopped).*/
started: number;
/** the connection port based on the following rules:
the configured port value before the server has been started.
the actual port assigned when no port is configured or set to 0 after the server has been started.*/
port: number;
/** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/
host: string;
/** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/
address: string;
/** - the protocol used:
'http' - HTTP.
'https' - HTTPS.
'socket' - UNIX domain socket or Windows named pipe.*/
protocol: string;
/** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component.*/
uri: string;
}
/**
* undocumented. The connection object constructed after calling server.connection();
* can be accessed via server.connections; or request.connection;
*/
export class ServerConnection extends Events.EventEmitter {
domain: any;
_events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function };
_eventsCount: number;
settings: IServerConnectionOptions;
server: Server;
/** ex: "tcp" */
type: string;
_started: boolean;
/** dictionary of sockets */
_connections: { [ip_port: string]: any };
_onConnection: Function;
registrations: any;
_extensions: any;
_requestCounter: { value: number; min: number; max: number };
_load: any;
states: {
settings: any; cookies: any; names: any[]
};
auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; api: any; };
_router: any;
MSPluginsCollection: any;
applicationCache: any;
addEventListener: any;
info: IServerConnectionInfo;
}
type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse";
type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop";
/** Server http://hapijs.com/api#server
rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080).
Server events
The server object inherits from Events.EventEmitter and emits the following events:
'log' - events logged with server.log() and server events generated internally by the framework.
'start' - emitted when the server is started using server.start().
'stop' - emitted when the server is stopped using server.stop().
'request' - events generated by request.log(). Does not include any internally generated events.
'request-internal' - request events generated internally by the framework (multiple events per request).
'request-error' - emitted whenever an Internal Server Error (500) error response is sent. Single event per request.
'response' - emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case request.response is null). Single event per request.
'tail' - emitted when a request finished processing, including any registered tails. Single event per request.
Note that the server object should not be used to emit application events as its internal implementation is designed to fan events out to the various plugin selections and not for application events.
MORE EVENTS HERE: http://hapijs.com/api#server-events*/
export class Server extends Events.EventEmitter {
constructor(options?: IServerOptions);
/** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object.
var Hapi = require('hapi');
server = new Hapi.Server();
server.app.key = 'value';
var handler = function (request, reply) {
return reply(request.server.app.key);
}; */
app: any;
/** An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria.
var server = new Hapi.Server();
server.connection({ port: 80, labels: 'a' });
server.connection({ port: 8080, labels: 'b' });
// server.connections.length === 2
var a = server.select('a');
// a.connections.length === 1*/
connections: Array<ServerConnection>;
/** When the server contains exactly one connection, info is an object containing information about the sole connection.
* When the server contains more than one connection, each server.connections array member provides its own connection.info.
var server = new Hapi.Server();
server.connection({ port: 80 });
// server.info.port === 80
server.connection({ port: 8080 });
// server.info === null
// server.connections[1].info.port === 8080
*/
info: IServerConnectionInfo;
/** An object containing the process load metrics (when load.sampleInterval is enabled):
rss - RSS memory usage.
var Hapi = require('hapi');
var server = new Hapi.Server({ load: { sampleInterval: 1000 } });
console.log(server.load.rss);*/
load: {
/** - event loop delay milliseconds.*/
eventLoopDelay: number;
/** - V8 heap usage.*/
heapUsed: number;
};
/** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection.
When the server contains more than one connection, each server.connections array member provides its own connection.listener.
var Hapi = require('hapi');
var SocketIO = require('socket.io');
var server = new Hapi.Server();
server.connection({ port: 80 });
var io = SocketIO.listen(server.listener);
io.sockets.on('connection', function(socket) {
socket.emit({ msg: 'welcome' });
});*/
listener: http.Server;
/** server.methods
An object providing access to the server methods where each server method name is an object property.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.method('add', function (a, b, next) {
return next(null, a + b);
});
server.methods.add(1, 2, function (err, result) {
// result === 3
});*/
methods: IDictionary<Function>;
/** server.mime
Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting.
var Hapi = require('hapi');
var options = {
mime: {
override: {
'node/module': {
source: 'steve',
compressible: false,
extensions: ['node', 'module', 'npm'],
type: 'node/module'
}
}
}
};
var server = new Hapi.Server(options);
// server.mime.path('code.js').type === 'application/javascript'
// server.mime.path('file.npm').type === 'node/module'*/
mime: any;
/**server.plugins
An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method.
exports.register = function (server, options, next) {
server.expose('key', 'value');
// server.plugins.example.key === 'value'
return next();
};
exports.register.attributes = {
name: 'example'
};*/
plugins: IDictionary<any>;
/** server.realm
The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties.
modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes:
route - routes preferences:
prefix - the route path prefix used by any calls to server.route() from the server.
vhost - the route virtual host settings used by any calls to server.route() from the server.
plugin - the active plugin name (empty string if at the server root).
plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state.
settings - settings overrides:
files.relativeTo
bind
The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]).
exports.register = function (server, options, next) {
console.log(server.realm.modifiers.route.prefix);
return next();
};*/
realm: IServerRealm;
/** server.root
The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/
root: Server;
/** server.settings
The server configuration object after defaults applied.
var Hapi = require('hapi');
var server = new Hapi.Server({
app: {
key: 'value'
}
});
// server.settings.app === { key: 'value' }*/
settings: IServerOptions;
/** server.version
The hapi module version number.
var Hapi = require('hapi');
var server = new Hapi.Server();
// server.version === '8.0.0'*/
version: string;
/** server.after(method, [dependencies])
Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where:
after - the method with signature function(plugin, next) where:
server - server object the after() method was called on.
next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where:
err - internal error which is returned back via the server.start() callback.
dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.after(function () {
// Perform some pre-start logic
});
server.start(function (err) {
// After method already executed
});
server.auth.default(options)*/
after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void;
auth: {
/** server.auth.api
An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function.
When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object.
const server = new Hapi.Server();
server.connection({ port: 80 });
const scheme = function (server, options) {
return {
api: {
settings: {
x: 5
}
},
authenticate: function (request, reply) {
const req = request.raw.req;
const authorization = req.headers.authorization;
if (!authorization) {
return reply(Boom.unauthorized(null, 'Custom'));
}
return reply.continue({ credentials: { user: 'john' } });
}
};
};
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
console.log(server.auth.api.default.settings.x); // 5
*/
api: {
[index: string]: any;
}
/** server.auth.default(options)
Sets a default strategy which is applied to every route where:
options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options.
The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior.
The default auth strategy configuration can be accessed via connection.auth.settings.default.
var server = new Hapi.Server();
server.connection({ port: 80 });
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.auth.default('default');
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
return reply(request.auth.credentials.user);
}
});*/
default(options: string): void;
default(options: { strategy: string }): void;
default(options: { strategies: string[] }): void;
/** server.auth.scheme(name, scheme)
Registers an authentication scheme where:
name - the scheme name.
scheme - the method implementing the scheme with signature function(server, options) where:
server - a reference to the server object the scheme is added to.
options - optional scheme settings used to instantiate a strategy.*/
scheme(name: string,
/** When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference.
n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.
server = new Hapi.Server();
server.connection({ port: 80 });
scheme = function (server, options) {
urn {
authenticate: function (request, reply) {
req = request.raw.req;
var authorization = req.headers.authorization;
if (!authorization) {
return reply(Boom.unauthorized(null, 'Custom'));
}
urn reply(null, { credentials: { user: 'john' } });
}
};
};
*/
scheme: (server: Server, options: any) => IServerAuthScheme): void;
/** server.auth.strategy(name, scheme, [mode], [options])
Registers an authentication strategy where:
name - the strategy name.
scheme - the scheme name (must be previously registered using server.auth.scheme()).
mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false.
options - scheme options based on the scheme requirements.
var server = new Hapi.Server();
server.connection({ port: 80 });
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.route({
method: 'GET',
path: '/',
config: {
auth: 'default',
handler: function (request, reply) {
return reply(request.auth.credentials.user);
}
}
});*/
strategy(name: string, scheme: any, mode?: boolean | string, options?: any): void;
/** server.auth.test(strategy, request, next)
Tests a request against an authentication strategy where:
strategy - the strategy name registered with server.auth.strategy().
request - the request object.
next - the callback function with signature function(err, credentials) where:
err - the error if authentication failed.
credentials - the authentication credentials object if authentication was successful.
Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties.
var server = new Hapi.Server();
server.connection({ port: 80 });
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
request.server.auth.test('default', request, function (err, credentials) {
if (err) {
return reply({ status: false });
}
return reply({ status: true, user: credentials.name });
});
}
});*/
test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void;
};
/** server.bind(context)
Sets a global context used as the default bind object when adding a route or an extension where:
context - the object used to bind this in handler and extension methods.
When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set.
var handler = function (request, reply) {
return reply(this.message);
};
exports.register = function (server, options, next) {
var bind = {
message: 'hello'
};
server.bind(bind);
server.route({ method: 'GET', path: '/', handler: handler });
return next();
};*/
bind(context: any): void;
/** server.cache(options)
Provisions a cache segment within the server cache facility where:
options - catbox policy configuration where:
expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn.
generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy.
staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn.
staleTimeout - number of milliseconds to wait before checking if an item is stale.
generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests.
cache - the cache name configured in 'server.cache`. Defaults to the default cache.
segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. Required when called outside of a plugin.
shared - if true, allows multiple cache provisions to share the same segment. Default to false.
var server = new Hapi.Server();
server.connection({ port: 80 });
var cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 });
cache.set('norway', { capital: 'oslo' }, null, function (err) {
cache.get('norway', function (err, value, cached, log) {
// value === { capital: 'oslo' };
});
});*/
cache(options: ICatBoxCacheOptions): void;
/** server.connection([options])
Adds an incoming server connection
Returns a server object with the new connection selected.
Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()).
Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on.
var Hapi = require('hapi');
var server = new Hapi.Server();
var web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] });
var admin = server.connection({ port: 8001, host: 'example.com', labels: ['admin'] });
// server.connections.length === 2
// web.connections.length === 1
// admin.connections.length === 1 */
connection(options: IServerConnectionOptions): Server;
/** server.decorate(type, property, method, [options])
Extends various framework interfaces with custom methods where:
type - the interface being decorated. Supported types:
'reply' - adds methods to the reply interface.
'server' - adds methods to the Server object.
property - the object decoration key name.
method - the extension function.
options - if the type is 'request', supports the following optional settings:
'apply' - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration.
Note that decorations apply to the entire server and all its connections regardless of current selection.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.decorate('reply', 'success', function () {
return this.response({ status: 'ok' });
});
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
return reply.success();
}
});*/
decorate(type: string, property: string, method: Function, options?: { apply: boolean }): void;
/** server.dependency(dependencies, [after])
Used within a plugin to declares a required dependency on other plugins where:
dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies.
after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where:
server - the server the dependency() method was called on.
next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where:
err - internal error condition, which is returned back via the server.start() callback.
exports.register = function (server, options, next) {
server.dependency('yar', after);
return next();
};
var after = function (server, next) {
// Additional plugin registration logic
return next();
};*/
dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void;
/** server.expose(key, value)
Used within a plugin to expose a property via server.plugins[name] where:
key - the key assigned (server.plugins[name][key]).
value - the value assigned.
exports.register = function (server, options, next) {
server.expose('util', function () { console.log('something'); });
return next();
};*/
expose(key: string, value: any): void;
/** server.expose(obj)
Merges a deep copy of an object into to the existing content of server.plugins[name] where:
obj - the object merged into the exposed properties container.
exports.register = function (server, options, next) {
server.expose({ util: function () { console.log('something'); } });
return next();
};*/
expose(obj: any): void;
/** server.ext(event, method, [options])
Registers an extension function in one of the available extension points where:
event - the event name.
method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where:
request - the request object. NOTE: Access the Response via request.response
reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response.
this - the object provided via options.bind or the current active context set with server.bind().
options - an optional object with the following:
before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
bind - a context object passed back to the provided method (via this) when called.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to '/test'
request.setUrl('/test');
return reply.continue();
});
var handler = function (request, reply) {
return reply({ status: 'ok' });
};
server.route({ method: 'GET', path: '/test', handler: handler });
server.start();
// All requests will get routed to '/test'*/
ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
ext<T>(event: RequestExtPoints, method: (request: Request, reply: IStrictReply<T>, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
/** server.handler(name, method)
Registers a new handler type to be used in routes where:
name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type.
method - the function used to generate the route handler using the signature function(route, options) where:
route - the route public interface object.
options - the configuration object provided in the handler config.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ host: 'localhost', port: 8000 });
// Defines new handler for routes on this server
server.handler('test', function (route, options) {
return function (request, reply) {
return reply('new handler: ' + options.msg);
}
});
server.route({
method: 'GET',
path: '/',
handler: { test: { msg: 'test' } }
});
server.start();
The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ host: 'localhost', port: 8000 });
var handler = function (route, options) {
return function (request, reply) {
return reply('new handler: ' + options.msg);
}
};
// Change the default payload processing for this handler
handler.defaults = {
payload: {
output: 'stream',
parse: false
}
};
server.handler('test', handler);*/
handler<THandlerConfig>(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void;
/** server.initialize([callback])
Initializes the server (starts the caches, finalizes plugin registration) but does not start listening
on the connection ports, where:
- `callback` - the callback method when server initialization is completed or failed with the signature
`function(err)` where:
- `err` - any initialization error condition.
If no `callback` is provided, a `Promise` object is returned.
Note that if the method fails and the callback includes an error, the server is considered to be in
an undefined state and should be shut down. In most cases it would be impossible to fully recover as
the various plugins, caches, and other event listeners will get confused by repeated attempts to
start the server or make assumptions about the healthy state of the environment. It is recommended
to assert that no error has been returned after calling `initialize()` to abort the process when the
server fails to start properly. If you must try to resume after an error, call `server.stop()`
first to reset the server state.
*/
initialize(callback?: (error: any) => void): IPromise<void>;
/** When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection.
Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack.
Utilizes the [shot module | https://github.com/hapijs/shot ] for performing injections, with some additional options and response properties
* When the server contains more than one connection, each server.connections array member provides its own connection.inject().
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
var handler = function (request, reply) {
return reply('Success!');
};
server.route({ method: 'GET', path: '/', handler: handler });
server.inject('/', function (res) {
console.log(res.result);
});
*/
inject: IServerInject;
/** server.log(tags, [data, [timestamp]])
Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are:
tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information.
data - an optional message string or object with the application data being logged.
timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('log', function (event, tags) {
if (tags.error) {
console.log(event);
}
});
server.log(['test', 'error'], 'Test event');*/
log(tags: string | string[], data?: string | any, timestamp?: number): void;
/**server.lookup(id)
When the server contains exactly one connection, looks up a route configuration where:
id - the route identifier as set in the route options.
returns the route public interface object if found, otherwise null.
var server = new Hapi.Server();
server.connection();
server.route({
method: 'GET',
path: '/',
config: {
handler: function (request, reply) { return reply(); },
id: 'root'
}
});
var route = server.lookup('root');
When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/
lookup(id: string): IRoute;
/** server.match(method, path, [host])
When the server contains exactly one connection, looks up a route configuration where:
method - the HTTP method (e.g. 'GET', 'POST').
path - the requested path (must begin with '/').
host - optional hostname (to match against routes with vhost).
returns the route public interface object if found, otherwise null.
var server = new Hapi.Server();
server.connection();
server.route({
method: 'GET',
path: '/',
config: {
handler: function (request, reply) { return reply(); },
id: 'root'
}
});
var route = server.match('get', '/');
When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/
match(method: string, path: string, host?: string): IRoute;
/** server.method(name, method, [options])
Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module.
Methods are registered via server.method(name, method, [options])
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
// Simple arguments
var add = function (a, b, next) {
return next(null, a + b);
};
server.method('sum', add, { cache: { expiresIn: 2000 } });
server.methods.sum(4, 5, function (err, result) {
console.log(result);
});
// Object argument
var addArray = function (array, next) {
var sum = 0;
array.forEach(function (item) {
sum += item;
});
return next(null, sum);
};
server.method('sumObj', addArray, {
cache: { expiresIn: 2000 },
generateKey: function (array) {
return array.join(',');
}
});
server.methods.sumObj([5, 6], function (err, result) {
console.log(result);
});
// Synchronous method with cache
var addSync = function (a, b) {
return a + b;
};
server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false });
server.methods.sumSync(4, 5, function (err, result) {
console.log(result);
}); */
method(/** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/
name: string,
method: IServerMethod,
options?: IServerMethodOptions): void;
/**server.method(methods)
Registers a server method function as described in server.method() using a configuration object where:
methods - an object or an array of objects where each one contains:
name - the method name.
method - the method function.
options - optional settings.
var add = function (a, b, next) {
next(null, a + b);
};
server.method({
name: 'sum',
method: add,
options: {
cache: {
expiresIn: 2000
}
}
});*/
method(methods: {
name: string; method: IServerMethod; options?: IServerMethodOptions
} | Array<{
name: string; method: IServerMethod; options?: IServerMethodOptions
}>): void;
/**server.path(relativeTo)
Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where:
relativeTo - the path prefix added to any relative file path starting with '.'.
Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set.
exports.register = function (server, options, next) {
server.path(__dirname + '../static');
server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } });
next();
};*/
path(relativeTo: string): void;
/**
* server.register(plugins, [options], callback)
* Registers a plugin where:
* plugins - an object or array of objects where each one is either:
* a plugin registration function.
* an object with the following:
* register - the plugin registration function.
* options - optional options passed to the registration function when called.
* options - optional registration options (different from the options passed to the registration function):
* select - a string or array of string labels used to pre-select connections for plugin registration.
* routes - modifiers applied to each route added by the plugin:
* prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix.
* vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
* callback - the callback function with signature function(err) where:
* err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework.
*
* If no callback is provided, a Promise object is returned.
*/
register(plugins: any | any[], options: {
select: string | string[];
routes: {
prefix: string; vhost?: string | string[]
};
}, callback: (err: any) => void): void;
register(plugins: any | any[], options: {
select: string | string[];
routes: {
prefix: string; vhost?: string | string[]
};
}): IPromise<any>;
register(plugins: any | any[], callback: (err: any) => void): void;
register(plugins: any | any[]): IPromise<any>;
/**server.render(template, context, [options], callback)
Utilizes the server views manager to render a template where:
template - the template filename and path, relative to the views manager templates path (path or relativeTo).
context - optional object used by the template to render context-specific result. Defaults to no context ({}).
options - optional object used to override the views manager configuration.
callback - the callback function with signature function (err, rendered, config) where:
err - the rendering error if any.
rendered - the result view string.
config - the configuration used to render the template.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.views({
engines: { html: require('handlebars') },
path: __dirname + '/templates'
});
var context = {
title: 'Views Example',
message: 'Hello, World'
};
server.render('hello', context, function (err, rendered, config) {
console.log(rendered);
});*/
render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void;
/** server.route(options)
Adds a connection route where:
options - a route configuration object or an array of configuration objects.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } });
server.route([
{ method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } },
{ method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } }
]);*/
route(options: IRouteConfiguration): void;
route(options: IRouteConfiguration[]): void;
/**server.select(labels)
Selects a subset of the server's connections where:
labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration.
Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, labels: ['a'] });
server.connection({ port: 8080, labels: ['b'] });
server.connection({ port: 8081, labels: ['c'] });
server.connection({ port: 8082, labels: ['c','d'] });
var a = server.select('a'); // The server with port 80
var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080
var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */
select(labels: string | string[]): Server | Server[];
/** server.start([callback])
Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where:
callback - optional callback when server startup is completed or failed with the signature function(err) where:
err - any startup error condition.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.start(function (err) {
console.log('Server started at: ' + server.info.uri);
});*/
start(callback?: (err: any) => void): IPromise<void>;
/** server.state(name, [options])
HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions
State defaults can be modified via the server connections.routes.state configuration option.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
// Set cookie definition
server.state('session', {
ttl: 24 * 60 * 60 * 1000, // One day
isSecure: true,
path: '/',
encoding: 'base64json'
});
// Set state in route handler
var handler = function (request, reply) {
var session = request.state.session;
if (!session) {
session = { user: 'joe' };
}
session.last = Date.now();
return reply('Success').state('session', session);
};
Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('request-internal', function (request, event, tags) {
if (tags.error && tags.state) {
console.error(event);
}
}); */
state(name: string, options?: ICookieSettings): void;
/** server.stop([options], [callback])
Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where:
options - optional object with:
timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds).
callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.stop({ timeout: 60 * 1000 }, function () {
console.log('Server stopped');
});*/
stop(options?: { timeout: number }, callback?: () => void): IPromise<void>;
/**server.table([host])
Returns a copy of the routing table where:
host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts.
The return value is an array where each item is an object containing:
info - the connection.info the connection the table was generated for.
labels - the connection labels.
table - an array of routes where each route contains:
settings - the route config with defaults applied.
method - the HTTP method in lower case.
path - the route path.
Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, host: 'example.com' });
server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } });
var table = server.table();
When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, host: 'example.com' });
server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } });
var table = server.connections[0].table();
//[
// {
// method: 'get',
// path: '/example',
// settings: { ... }
// }
//]
*/
table(host?: any): IConnectionTable;
/**server.views(options)
Initializes the server views manager
var Hapi = require('hapi');
var server = new Hapi.Server();
server.views({
engines: {
html: require('handlebars'),
jade: require('jade')
},
path: '/static/templates'
});
When server.views() is called within a plugin, the views manager is only available to plugins methods.*/
views(options: IServerViewsConfiguration): void;
}
}
| navgurukul/galileo | typings/globals/hapi/index.d.ts | TypeScript | gpl-3.0 | 145,113 |
//-----------------------------------------------------------------------
//
// mod parser::atom TEST
//
//-----------------------------------------------------------------------
use super::Status;
use super::{parse_dot, parse_eof, parse_literal, parse_match, MatchRules};
#[test]
fn test_parse_literal_ok() {
let rules = rules!{};
let status_init = Status::init("aaaaaaaaaaaaaaaa", &rules);
let (status_end, _) = parse_literal(status_init, "aaa").ok().unwrap();
assert!(status_end.pos.col == 3);
assert!(status_end.pos.n == 3);
assert!(status_end.pos.row == 0);
}
#[test]
fn test_parse_literal_ok2() {
let rules = rules!{};
let status_init = Status::init("abcdefghij", &rules);
let (status_end, _) = parse_literal(status_init, "abc").ok().unwrap();
assert_eq!(status_end.pos.col, 3);
assert_eq!(status_end.pos.n, 3);
assert_eq!(status_end.pos.row, 0);
}
#[test]
fn test_parse_literal_fail() {
let rules = rules!{};
let status_init = Status::init("abcdefghij", &rules);
assert!(parse_literal(status_init, "bbb").is_err());
}
#[test]
fn test_parse_literal_fail2() {
let rules = rules!{};
let status_init = Status::init("abcdefghij", &rules);
assert!(parse_literal(status_init, "abd").is_err());
}
#[test]
fn test_parse_literal_fail_short_text2parse() {
let rules = rules!{};
let status_init = Status::init("abcd", &rules);
assert!(parse_literal(status_init, "abcdefghij").is_err());
}
#[test]
fn test_parse_literal_with_new_line() {
let rules = rules!{};
let status_init = Status::init(
"aa
aaaaaaaaaaaaaa",
&rules,
);
let (status_end, _) = parse_literal(
status_init,
"aa
a",
).ok()
.unwrap();
assert!(status_end.pos.col == 1);
assert!(status_end.pos.row == 1);
}
#[test]
fn test_parse_dot() {
let rules = rules!{};
let status = Status::init("ab", &rules);
let (status, _) = parse_dot(status).ok().unwrap();
assert!(status.pos.col == 1);
assert!(status.pos.n == 1);
assert!(status.pos.row == 0);
let (status, _) = parse_dot(status).ok().unwrap();
assert!(status.pos.col == 2);
assert!(status.pos.n == 2);
assert!(status.pos.row == 0);
assert!(parse_dot(status).is_err());
}
#[test]
fn test_parse_match_ok() {
let rules = rules!{};
let status = Status::init("a f0ghi", &rules);
let match_rules = MatchRules::new().with_chars("54321ed_cba");
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert_eq!(status.pos.col, 1);
assert_eq!(status.pos.n, 1);
assert_eq!(status.pos.row, 0);
let (status, _) = parse_dot(status).ok().unwrap();
let match_rules = MatchRules::new().with_bound_chars(vec![('f', 'g'), ('h', 'j')]);
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert_eq!(status.pos.col, 3);
assert_eq!(status.pos.n, 3);
assert_eq!(status.pos.row, 0);
assert!(parse_match(status, &match_rules).is_err());
}
#[test]
fn test_parse_match_err() {
let rules = rules!{};
let status = Status::init("a9", &rules);
let match_rules = MatchRules::new().with_chars("ed_cba");
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert_eq!(status.pos.col, 1);
assert_eq!(status.pos.n, 1);
assert_eq!(status.pos.row, 0);
let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '8')]);
assert!(parse_match(status, &match_rules).is_err());
}
#[test]
fn test_parse_match_eof_ok() {
let rules = rules!{};
let status = Status::init("a", &rules);
let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '9')]);
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert!(parse_eof(status).is_ok());
}
#[test]
fn test_parse_match_eof_error() {
let rules = rules!{};
let status = Status::init("ab", &rules);
let match_rules = MatchRules::new().with_bound_chars(vec![('a', 'z'), ('0', '9')]);
let (status, _) = parse_match(status, &match_rules).ok().unwrap();
assert!(parse_eof(status).is_err());
}
| jleahred/dynparser | src/parser/atom/test.rs | Rust | gpl-3.0 | 4,142 |
/*
* Copyright (C) 2006 by Martin J. Muench <mjm@codito.de>
*
* Part of mpd - mobile phone dumper
*
* Some code stolen from btxml.c by Andreas Oberritter
*
*/
#include "wrap.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/* Simple malloc() wrapper */
void *Malloc(size_t size) {
void *buffer;
buffer = malloc(size);
if(buffer == NULL) {
fprintf(stderr, "malloc() failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
memset(buffer, 0, size);
return(buffer);
}
| firebitsbr/pwn_plug_sources | src/bluetooth/bluebugger/source/wrap.c | C | gpl-3.0 | 527 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Generator;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Psr\Log\LoggerInterface;
/**
* UrlGenerator can generate a URL or a path for any route in the RouteCollection
* based on the passed parameters.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Tobias Schultze <http://tobion.de>
*/
class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
{
/**
* @var RouteCollection
*/
protected $routes;
/**
* @var RequestContext
*/
protected $context;
/**
* @var bool|null
*/
protected $strictRequirements = true;
/**
* @var LoggerInterface|null
*/
protected $logger;
/**
* This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
*
* PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
* to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
* "?" and "#" (would be interpreted wrongly as query and fragment identifier),
* "'" and """ (are used as delimiters in HTML).
*/
protected $decodedChars = array(
// the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
// some webservers don't allow the slash in encoded form in the path for security reasons anyway
// see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
'%2F' => '/',
// the following chars are general delimiters in the URI specification but have only special meaning in the authority component
// so they can safely be used in the path in unencoded form
'%40' => '@',
'%3A' => ':',
// these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
// so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
'%3B' => ';',
'%2C' => ',',
'%3D' => '=',
'%2B' => '+',
'%21' => '!',
'%2A' => '*',
'%7C' => '|',
);
/**
* @var string This regexp matches all characters that are not or should not be encoded by rawurlencode (see list in array above).
*/
private $urlEncodingSkipRegexp = '#[^-.~a-zA-Z0-9_/@:;,=+!*|]#';
/**
* Constructor.
*
* @param RouteCollection $routes A RouteCollection instance
* @param RequestContext $context The context
* @param LoggerInterface|null $logger A logger instance
*/
public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
{
$this->routes = $routes;
$this->context = $context;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
$this->context = $context;
}
/**
* {@inheritdoc}
*/
public function getContext()
{
return $this->context;
}
/**
* {@inheritdoc}
*/
public function setStrictRequirements($enabled)
{
$this->strictRequirements = null === $enabled ? null : (bool) $enabled;
}
/**
* {@inheritdoc}
*/
public function isStrictRequirements()
{
return $this->strictRequirements;
}
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
if (null === $route = $this->routes->get($name)) {
throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
}
// the Route has a cache of its own and is not recompiled as long as it does not get modified
$compiledRoute = $route->compile();
return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
}
/**
* @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
* @throws InvalidParameterException When a parameter value for a placeholder is not correct because
* it does not match the requirement
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
{
$variables = array_flip($variables);
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
// all params must be given
if ($diff = array_diff_key($variables, $mergedParams)) {
throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
}
$url = '';
$optional = true;
foreach ($tokens as $token) {
if ('variable' === $token[0]) {
if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
// check requirement
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$url = $token[1].$mergedParams[$token[3]].$url;
$optional = false;
}
} else {
// static text
$url = $token[1].$url;
$optional = false;
}
}
if ('' === $url) {
$url = '/';
} elseif (preg_match($this->urlEncodingSkipRegexp, $url)) {
// the context base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
$url = strtr(rawurlencode($url), $this->decodedChars);
}
// the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
// so we need to encode them as they are not used for this purpose here
// otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
if (false !== strpos($url, '/.')) {
$url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
if ('/..' === substr($url, -3)) {
$url = substr($url, 0, -2).'%2E%2E';
} elseif ('/.' === substr($url, -2)) {
$url = substr($url, 0, -1).'%2E';
}
}
$schemeAuthority = '';
if ($host = $this->context->getHost()) {
$scheme = $this->context->getScheme();
if ($requiredSchemes) {
if (!in_array($scheme, $requiredSchemes, true)) {
$referenceType = self::ABSOLUTE_URL;
$scheme = current($requiredSchemes);
}
}
if ($hostTokens) {
$routeHost = '';
foreach ($hostTokens as $token) {
if ('variable' === $token[0]) {
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
} else {
$routeHost = $token[1].$routeHost;
}
}
if ($routeHost !== $host) {
$host = $routeHost;
if (self::ABSOLUTE_URL !== $referenceType) {
$referenceType = self::NETWORK_PATH;
}
}
}
if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
$port = '';
if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
$port = ':'.$this->context->getHttpPort();
} elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
$port = ':'.$this->context->getHttpsPort();
}
$schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
$schemeAuthority .= $host.$port;
}
}
if (self::RELATIVE_PATH === $referenceType) {
$url = self::getRelativePath($this->context->getPathInfo(), $url);
} else {
$url = $schemeAuthority.$this->context->getBaseUrl().$url;
}
// add a query string if needed
$extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
return $a == $b ? 0 : 1;
});
if ($extra && $query = http_build_query($extra, '', '&')) {
// "/" and "?" can be left decoded for better user experience, see
// http://tools.ietf.org/html/rfc3986#section-3.4
$url .= '?'.(false === strpos($query, '%2F') ? $query : strtr($query, array('%2F' => '/')));
}
return $url;
}
/**
* Returns the target path as relative reference from the base path.
*
* Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
* Both paths must be absolute and not contain relative parts.
* Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
* Furthermore, they can be used to reduce the link size in documents.
*
* Example target paths, given a base path of "/a/b/c/d":
* - "/a/b/c/d" -> ""
* - "/a/b/c/" -> "./"
* - "/a/b/" -> "../"
* - "/a/b/c/other" -> "other"
* - "/a/x/y" -> "../../x/y"
*
* @param string $basePath The base path
* @param string $targetPath The target path
*
* @return string The relative target path
*/
public static function getRelativePath($basePath, $targetPath)
{
if ($basePath === $targetPath) {
return '';
}
$sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
$targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
array_pop($sourceDirs);
$targetFile = array_pop($targetDirs);
foreach ($sourceDirs as $i => $dir) {
if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
unset($sourceDirs[$i], $targetDirs[$i]);
} else {
break;
}
}
$targetDirs[] = $targetFile;
$path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
// A reference to the same base directory or an empty subdirectory must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
// as the first segment of a relative-path reference, as it would be mistaken for a scheme name
// (see http://tools.ietf.org/html/rfc3986#section-4.2).
return '' === $path || '/' === $path[0]
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
? "./$path" : $path;
}
}
| AngelSanz1/quieroundoc | vendor/symfony/routing/Generator/UrlGenerator.php | PHP | gpl-3.0 | 13,482 |
#ifndef COMPAT_H_RD1Z6YZA
#define COMPAT_H_RD1Z6YZA
namespace oak
{
inline void set_thread_name (char const* threadName)
{
pthread_setname_np(threadName);
}
inline size_t get_gestalt (OSType selector)
{
SInt32 res;
Gestalt(selector, &res);
return res;
}
inline size_t os_major () { return get_gestalt(gestaltSystemVersionMajor); }
inline size_t os_minor () { return get_gestalt(gestaltSystemVersionMinor); }
inline size_t os_patch () { return get_gestalt(gestaltSystemVersionBugFix); }
inline OSStatus execute_with_privileges (AuthorizationRef authorization, std::string const& pathToTool, AuthorizationFlags options, char* const* arguments, FILE** communicationsPipe)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return AuthorizationExecuteWithPrivileges(authorization, pathToTool.c_str(), options, arguments, communicationsPipe);
#pragma clang diagnostic pop
}
} /* oak */
#endif /* end of include guard: COMPAT_H_RD1Z6YZA */
| xuvw/textmate | Shared/include/oak/compat.h | C | gpl-3.0 | 1,004 |
/*
* Copyright (c) 2002 Brian Foley
* Copyright (c) 2002 Dieter Shirley
* Copyright (c) 2003-2004 Romain Dolbeau <romain@dolbeau.org>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_PPC_DSPUTIL_ALTIVEC_H
#define AVCODEC_PPC_DSPUTIL_ALTIVEC_H
#include <stdint.h>
extern int has_altivec(void);
void put_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h);
void avg_pixels16_altivec(uint8_t *block, const uint8_t *pixels, int line_size, int h);
#endif /* AVCODEC_PPC_DSPUTIL_ALTIVEC_H */
| naeemshah/avbin | ffmpeg/libavcodec/ppc/dsputil_altivec.h | C | gpl-3.0 | 1,251 |
// Copyright (C) 2012 Tuma Solutions, LLC
// Team Functionality Add-ons for the Process Dashboard
//
// 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.
//
// Additional permissions also apply; see the README-license.txt
// file in the project root directory for more information.
//
// 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/>.
//
// The author(s) may be contacted at:
// processdash@tuma-solutions.com
// processdash-devel@lists.sourceforge.net
package teamdash.wbs.columns;
import teamdash.wbs.WBSModel;
import teamdash.wbs.WBSNode;
import teamdash.wbs.WBSNodeTest;
public class ErrorNotesColumn extends AbstractNotesColumn {
/** The ID we use for this column in the data model */
public static final String COLUMN_ID = "Error Notes";
/** The attribute this column uses to store task notes for a WBS node */
public static final String VALUE_ATTR = "Error Notes";
public ErrorNotesColumn(String authorName) {
super(VALUE_ATTR, authorName);
this.columnID = COLUMN_ID;
this.columnName = resources.getString("Error_Notes.Name");
}
@Override
protected String getEditDialogTitle() {
return columnName;
}
@Override
protected Object getEditDialogHeader(WBSNode node) {
return new Object[] {
resources.getStrings("Error_Notes.Edit_Dialog_Header"), " " };
}
public static String getTextAt(WBSNode node) {
return getTextAt(node, VALUE_ATTR);
}
public static String getTooltipAt(WBSNode node, boolean includeByline) {
return getTooltipAt(node, includeByline, VALUE_ATTR);
}
/**
* Find nodes that have errors attached, and expand their ancestors as
* needed to ensure that they are visible.
*
* @param wbs
* the WBSModel
* @param belowNode
* an optional starting point for the search, to limit expansion
* to a particular branch of the tree; can be null to search from
* the root
* @param condition
* an optional condition to test; only nodes matching the
* condition will be made visible. Can be null to show all nodes
* with errors
*/
public static void showNodesWithErrors(WBSModel wbs, WBSNode belowNode,
WBSNodeTest condition) {
if (belowNode == null)
belowNode = wbs.getRoot();
for (WBSNode node : wbs.getDescendants(belowNode)) {
String errText = getTextAt(node, VALUE_ATTR);
if (errText != null && errText.trim().length() > 0) {
if (condition == null || condition.test(node))
wbs.makeVisible(node);
}
}
}
}
| superzadeh/processdash | teamdash/src/teamdash/wbs/columns/ErrorNotesColumn.java | Java | gpl-3.0 | 3,288 |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtEnginio module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef ENGINIOCLIENT_H
#define ENGINIOCLIENT_H
#include <Enginio/enginioclient_global.h>
#include <Enginio/enginioclientconnection.h>
#include <QtCore/qjsonobject.h>
QT_BEGIN_NAMESPACE
class QNetworkAccessManager;
class QNetworkReply;
class EnginioReply;
class EnginioClientPrivate;
class ENGINIOCLIENT_EXPORT EnginioClient : public EnginioClientConnection
{
Q_OBJECT
Q_ENUMS(Enginio::Operation) // TODO remove me QTBUG-33577
Q_ENUMS(Enginio::AuthenticationState) // TODO remove me QTBUG-33577
Q_DECLARE_PRIVATE(EnginioClient)
public:
explicit EnginioClient(QObject *parent = 0);
~EnginioClient();
Q_INVOKABLE EnginioReply *customRequest(const QUrl &url, const QByteArray &httpOperation, const QJsonObject &data = QJsonObject());
Q_INVOKABLE EnginioReply *fullTextSearch(const QJsonObject &query);
Q_INVOKABLE EnginioReply *query(const QJsonObject &query, const Enginio::Operation operation = Enginio::ObjectOperation);
Q_INVOKABLE EnginioReply *create(const QJsonObject &object, const Enginio::Operation operation = Enginio::ObjectOperation);
Q_INVOKABLE EnginioReply *update(const QJsonObject &object, const Enginio::Operation operation = Enginio::ObjectOperation);
Q_INVOKABLE EnginioReply *remove(const QJsonObject &object, const Enginio::Operation operation = Enginio::ObjectOperation);
Q_INVOKABLE EnginioReply *uploadFile(const QJsonObject &associatedObject, const QUrl &file);
Q_INVOKABLE EnginioReply *downloadUrl(const QJsonObject &object);
Q_SIGNALS:
void sessionAuthenticated(EnginioReply *reply) const;
void sessionAuthenticationError(EnginioReply *reply) const;
void sessionTerminated() const;
void finished(EnginioReply *reply);
void error(EnginioReply *reply);
};
QT_END_NAMESPACE
#endif // ENGINIOCLIENT_H
| jlspyaozhongkai/Uter | third_party_build/Qt5.5.0/include/Enginio/enginioclient.h | C | gpl-3.0 | 3,394 |
<?php
/**
Copyright 2011-2014 Nick Korbel
This file is part of Booked Scheduler 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 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(ROOT_DIR . 'lib/Graphics/Image.php');
require_once(ROOT_DIR . 'lib/Graphics/ImageFactory.php');
?> | pluanant/booktu | lib/Graphics/namespace.php | PHP | gpl-3.0 | 784 |
' Instat-R
' Copyright (C) 2015
'
' 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 k
' along with this program. If not, see <http://www.gnu.org/licenses/>.
Imports instat.Translations
Public Class dlgReplaceValues
Public bFirstLoad As Boolean = True
Private bReset As Boolean = True
Private Sub dlgReplace_Load(sender As Object, e As EventArgs) Handles MyBase.Load
autoTranslate(Me)
If bFirstLoad Then
InitialiseDialog()
bFirstLoad = False
End If
If bReset Then
SetDefaults()
End If
SetRCodeForControls(bReset)
bReset = False
TestOKEnabled()
End Sub
Private Sub InitialiseDialog()
ucrBase.iHelpTopicID = 47
'ucrSelector
ucrSelectorReplace.SetParameter(New RParameter("data_name", 0))
ucrSelectorReplace.SetParameterIsString()
'ucrReceiver
ucrReceiverReplace.SetParameter(New RParameter("col_names", 1))
ucrReceiverReplace.Selector = ucrSelectorReplace
ucrReceiverReplace.SetMeAsReceiver()
ucrReceiverReplace.SetSingleTypeStatus(True)
ucrReceiverReplace.SetParameterIsString()
ucrReceiverReplace.SetExcludedDataTypes({"Date"})
rdoNewFromAbove.Enabled = False
'' Old:
ucrPnlOld.AddRadioButton(rdoOldValue)
ucrPnlOld.AddRadioButton(rdoOldMissing)
ucrPnlOld.AddRadioButton(rdoOldInterval)
ucrPnlOld.AddParameterPresentCondition(rdoOldValue, "old_value")
ucrPnlOld.AddParameterValuesCondition(rdoOldMissing, "old_is_missing", "TRUE")
ucrPnlOld.AddParameterPresentCondition(rdoOldInterval, "start_value")
ucrPnlOld.AddParameterPresentCondition(rdoOldInterval, "end_value")
ucrPnlOld.AddToLinkedControls(ucrInputOldValue, {rdoOldValue}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True, bNewLinkedChangeToDefaultState:=True)
ucrPnlOld.AddToLinkedControls(ucrInputRangeFrom, {rdoOldInterval}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True, bNewLinkedChangeToDefaultState:=True, objNewDefaultState:=0)
ucrPnlOld.AddToLinkedControls(ucrInputRangeTo, {rdoOldInterval}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True, bNewLinkedChangeToDefaultState:=True, objNewDefaultState:=1)
ucrPnlOld.AddToLinkedControls(ucrChkMin, {rdoOldInterval}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True)
ucrPnlOld.AddToLinkedControls(ucrChkMax, {rdoOldInterval}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True)
'ucrInputOldValue
ucrInputOldValue.SetParameter(New RParameter("old_value", 2))
ucrInputOldValue.bAddRemoveParameter = False
'ucrInputRangeFrom
ucrInputRangeFrom.SetParameter(New RParameter("start_value", 2))
ucrInputRangeFrom.AddQuotesIfUnrecognised = False
ucrInputRangeFrom.bAddRemoveParameter = False
ucrInputRangeFrom.SetLinkedDisplayControl(lblRangeMin)
ucrChkMin.SetParameter(New RParameter("closed_start_value"))
ucrChkMin.SetText("Including")
ucrChkMin.SetValuesCheckedAndUnchecked("TRUE", "FALSE")
ucrChkMin.bAddRemoveParameter = False
ucrChkMin.SetRDefault("FALSE")
'ucrInputRangeTo
ucrInputRangeTo.SetParameter(New RParameter("end_value", 3))
ucrInputRangeTo.AddQuotesIfUnrecognised = False
ucrInputRangeTo.bAddRemoveParameter = False
ucrInputRangeTo.SetLinkedDisplayControl(lblRangeMax)
ucrChkMax.SetParameter(New RParameter("closed_end_value"))
ucrChkMax.SetText("Including")
ucrChkMax.SetValuesCheckedAndUnchecked("TRUE", "FALSE")
ucrChkMax.bAddRemoveParameter = False
ucrChkMax.SetRDefault("FALSE")
'' NEW VALUES:
ucrPnlNew.AddRadioButton(rdoNewValue)
ucrPnlNew.AddRadioButton(rdoNewMissing)
'ucrPnlNew.AddRadioButton(rdoNewFromAbove)
ucrPnlNew.AddParameterPresentCondition(rdoNewValue, "new_value")
ucrPnlNew.AddParameterValuesCondition(rdoNewMissing, "new_is_missing", "TRUE")
ucrPnlNew.AddToLinkedControls(ucrInputNewValue, {rdoNewValue}, bNewLinkedAddRemoveParameter:=True, bNewLinkedHideIfParameterMissing:=True, bNewLinkedChangeToDefaultState:=True, objNewDefaultState:=1)
''ucrInputNewValue
ucrInputNewValue.SetParameter(New RParameter("new_value", 4))
ucrInputNewValue.bAddRemoveParameter = False
End Sub
Private Sub SetDefaults()
Dim clsDefaultFunction As New RFunction
ucrSelectorReplace.Reset()
EnableRange()
clsDefaultFunction.SetRCommand(frmMain.clsRLink.strInstatDataObject & "$replace_value_in_data")
clsDefaultFunction.AddParameter("old_value", "-99")
clsDefaultFunction.AddParameter("new_is_missing", "TRUE")
ucrBase.clsRsyntax.SetBaseRFunction(clsDefaultFunction.Clone())
End Sub
Private Sub SetRCodeForControls(bReset As Boolean)
SetRCode(Me, ucrBase.clsRsyntax.clsBaseFunction, bReset)
End Sub
Private Sub ReopenDialog()
End Sub
Private Sub TestOKEnabled()
If (Not ucrReceiverReplace.IsEmpty()) Then
If ((rdoOldValue.Checked AndAlso Not ucrInputOldValue.IsEmpty) OrElse (rdoOldInterval.Checked AndAlso Not ucrInputRangeFrom.IsEmpty() AndAlso Not ucrInputRangeTo.IsEmpty()) OrElse rdoOldMissing.Checked) AndAlso ((rdoNewValue.Checked AndAlso Not ucrInputNewValue.IsEmpty) OrElse rdoNewMissing.Checked) Then
ucrBase.OKEnabled(True)
Else
ucrBase.OKEnabled(False)
End If
Else
ucrBase.OKEnabled(False)
End If
End Sub
Private Sub ucrBaseReplace_ClickReset(sender As Object, e As EventArgs) Handles ucrBase.ClickReset
SetDefaults()
SetRCodeForControls(True)
TestOKEnabled()
End Sub
Private Sub InputValue()
Dim strVarType As String
If Not ucrReceiverReplace.IsEmpty Then
strVarType = ucrReceiverReplace.GetCurrentItemTypes(True)(0)
If rdoOldValue.Checked Then
If (strVarType = "numeric" OrElse strVarType = "integer") Then
ucrInputOldValue.AddQuotesIfUnrecognised = False
Else
ucrInputOldValue.AddQuotesIfUnrecognised = True
End If
ucrBase.clsRsyntax.RemoveParameter("old_is_missing")
ElseIf rdoOldMissing.Checked Then
ucrBase.clsRsyntax.AddParameter("old_is_missing", "TRUE")
Else
ucrBase.clsRsyntax.RemoveParameter("old_is_missing")
End If
If rdoNewValue.Checked Then
If (strVarType = "numeric" OrElse strVarType = "integer") Then
ucrInputNewValue.AddQuotesIfUnrecognised = False
Else
ucrInputNewValue.AddQuotesIfUnrecognised = True
End If
ucrBase.clsRsyntax.RemoveParameter("new_is_missing")
ElseIf rdoNewMissing.Checked Then
ucrBase.clsRsyntax.AddParameter("new_is_missing", "TRUE")
Else
ucrBase.clsRsyntax.RemoveParameter("new_is_missing")
End If
End If
End Sub
Private Sub EnableRange()
Dim strVarType As String
If Not ucrReceiverReplace.IsEmpty Then
strVarType = ucrReceiverReplace.GetCurrentItemTypes(True)(0)
Else
strVarType = ""
End If
If strVarType = "" OrElse strVarType = "numeric" OrElse strVarType = "integer" Then
rdoOldInterval.Enabled = True
Else
rdoOldInterval.Enabled = False
End If
If rdoOldInterval.Enabled = False Then
If rdoOldInterval.Checked = True Then
rdoOldValue.Checked = True
rdoOldInterval.Checked = False
End If
End If
End Sub
Private Sub ucrReceiverReplace_ControlContentsChanged(ucrChangedControl As ucrCore) Handles ucrReceiverReplace.ControlContentsChanged, ucrPnlNew.ControlContentsChanged, ucrPnlOld.ControlContentsChanged, ucrInputNewValue.ControlContentsChanged, ucrInputOldValue.ControlContentsChanged, ucrInputRangeFrom.ControlContentsChanged, ucrInputRangeTo.ControlContentsChanged
TestOKEnabled()
End Sub
Private Sub ucrPnlOld_ControlValueChanged(ucrChangedControl As ucrCore) Handles ucrPnlOld.ControlValueChanged, ucrPnlNew.ControlValueChanged
InputValue()
EnableRange()
End Sub
Private Sub ucrReceiverReplace_ControlValueChanged(ucrChangedControl As ucrCore) Handles ucrReceiverReplace.ControlValueChanged
InputValue()
EnableRange()
End Sub
End Class | AlexSananka/Instat | instat/dlgReplaceValues.vb | Visual Basic | gpl-3.0 | 9,592 |
package gobol
// Error - defines a common http error interface
type Error interface {
error
StatusCode() int
Message() string
Package() string
Function() string
ErrorCode() string
}
| uol/mycenae | vendor/github.com/uol/gobol/error.go | GO | gpl-3.0 | 189 |
namespace Hfr.Model
{
public enum View
{
Connect,
Main,
Editor,
Settings,
CategoriesList,
CategoryThreadsList,
PrivateChatsList,
PrivateChat
}
}
| ThomasNigro/HFR10 | Hfr/Hfr/Models/Page.cs | C# | gpl-3.0 | 224 |
//===- RegisterBankEmitter.cpp - Generate a Register Bank Desc. -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of a target
// register bank for a code generator.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/BitVector.h"
#include "llvm/Support/Debug.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include "llvm/TableGen/TableGenBackend.h"
#include "CodeGenHwModes.h"
#include "CodeGenRegisters.h"
#include "CodeGenTarget.h"
#define DEBUG_TYPE "register-bank-emitter"
using namespace llvm;
namespace {
class RegisterBank {
/// A vector of register classes that are included in the register bank.
typedef std::vector<const CodeGenRegisterClass *> RegisterClassesTy;
private:
const Record &TheDef;
/// The register classes that are covered by the register bank.
RegisterClassesTy RCs;
/// The register class with the largest register size.
const CodeGenRegisterClass *RCWithLargestRegsSize;
public:
RegisterBank(const Record &TheDef)
: TheDef(TheDef), RCs(), RCWithLargestRegsSize(nullptr) {}
/// Get the human-readable name for the bank.
StringRef getName() const { return TheDef.getValueAsString("Name"); }
/// Get the name of the enumerator in the ID enumeration.
std::string getEnumeratorName() const { return (TheDef.getName() + "ID").str(); }
/// Get the name of the array holding the register class coverage data;
std::string getCoverageArrayName() const {
return (TheDef.getName() + "CoverageData").str();
}
/// Get the name of the global instance variable.
StringRef getInstanceVarName() const { return TheDef.getName(); }
const Record &getDef() const { return TheDef; }
/// Get the register classes listed in the RegisterBank.RegisterClasses field.
std::vector<const CodeGenRegisterClass *>
getExplicitlySpecifiedRegisterClasses(
const CodeGenRegBank &RegisterClassHierarchy) const {
std::vector<const CodeGenRegisterClass *> RCs;
for (const auto *RCDef : getDef().getValueAsListOfDefs("RegisterClasses"))
RCs.push_back(RegisterClassHierarchy.getRegClass(RCDef));
return RCs;
}
/// Add a register class to the bank without duplicates.
void addRegisterClass(const CodeGenRegisterClass *RC) {
if (llvm::is_contained(RCs, RC))
return;
// FIXME? We really want the register size rather than the spill size
// since the spill size may be bigger on some targets with
// limited load/store instructions. However, we don't store the
// register size anywhere (we could sum the sizes of the subregisters
// but there may be additional bits too) and we can't derive it from
// the VT's reliably due to Untyped.
if (RCWithLargestRegsSize == nullptr)
RCWithLargestRegsSize = RC;
else if (RCWithLargestRegsSize->RSI.get(DefaultMode).SpillSize <
RC->RSI.get(DefaultMode).SpillSize)
RCWithLargestRegsSize = RC;
assert(RCWithLargestRegsSize && "RC was nullptr?");
RCs.emplace_back(RC);
}
const CodeGenRegisterClass *getRCWithLargestRegsSize() const {
return RCWithLargestRegsSize;
}
iterator_range<typename RegisterClassesTy::const_iterator>
register_classes() const {
return llvm::make_range(RCs.begin(), RCs.end());
}
};
class RegisterBankEmitter {
private:
CodeGenTarget Target;
RecordKeeper &Records;
void emitHeader(raw_ostream &OS, const StringRef TargetName,
const std::vector<RegisterBank> &Banks);
void emitBaseClassDefinition(raw_ostream &OS, const StringRef TargetName,
const std::vector<RegisterBank> &Banks);
void emitBaseClassImplementation(raw_ostream &OS, const StringRef TargetName,
std::vector<RegisterBank> &Banks);
public:
RegisterBankEmitter(RecordKeeper &R) : Target(R), Records(R) {}
void run(raw_ostream &OS);
};
} // end anonymous namespace
/// Emit code to declare the ID enumeration and external global instance
/// variables.
void RegisterBankEmitter::emitHeader(raw_ostream &OS,
const StringRef TargetName,
const std::vector<RegisterBank> &Banks) {
// <Target>RegisterBankInfo.h
OS << "namespace llvm {\n"
<< "namespace " << TargetName << " {\n"
<< "enum : unsigned {\n";
OS << " InvalidRegBankID = ~0u,\n";
unsigned ID = 0;
for (const auto &Bank : Banks)
OS << " " << Bank.getEnumeratorName() << " = " << ID++ << ",\n";
OS << " NumRegisterBanks,\n"
<< "};\n"
<< "} // end namespace " << TargetName << "\n"
<< "} // end namespace llvm\n";
}
/// Emit declarations of the <Target>GenRegisterBankInfo class.
void RegisterBankEmitter::emitBaseClassDefinition(
raw_ostream &OS, const StringRef TargetName,
const std::vector<RegisterBank> &Banks) {
OS << "private:\n"
<< " static RegisterBank *RegBanks[];\n\n"
<< "protected:\n"
<< " " << TargetName << "GenRegisterBankInfo();\n"
<< "\n";
}
/// Visit each register class belonging to the given register bank.
///
/// A class belongs to the bank iff any of these apply:
/// * It is explicitly specified
/// * It is a subclass of a class that is a member.
/// * It is a class containing subregisters of the registers of a class that
/// is a member. This is known as a subreg-class.
///
/// This function must be called for each explicitly specified register class.
///
/// \param RC The register class to search.
/// \param Kind A debug string containing the path the visitor took to reach RC.
/// \param VisitFn The action to take for each class visited. It may be called
/// multiple times for a given class if there are multiple paths
/// to the class.
static void visitRegisterBankClasses(
const CodeGenRegBank &RegisterClassHierarchy,
const CodeGenRegisterClass *RC, const Twine &Kind,
std::function<void(const CodeGenRegisterClass *, StringRef)> VisitFn,
SmallPtrSetImpl<const CodeGenRegisterClass *> &VisitedRCs) {
// Make sure we only visit each class once to avoid infinite loops.
if (VisitedRCs.count(RC))
return;
VisitedRCs.insert(RC);
// Visit each explicitly named class.
VisitFn(RC, Kind.str());
for (const auto &PossibleSubclass : RegisterClassHierarchy.getRegClasses()) {
std::string TmpKind =
(Kind + " (" + PossibleSubclass.getName() + ")").str();
// Visit each subclass of an explicitly named class.
if (RC != &PossibleSubclass && RC->hasSubClass(&PossibleSubclass))
visitRegisterBankClasses(RegisterClassHierarchy, &PossibleSubclass,
TmpKind + " " + RC->getName() + " subclass",
VisitFn, VisitedRCs);
// Visit each class that contains only subregisters of RC with a common
// subregister-index.
//
// More precisely, PossibleSubclass is a subreg-class iff Reg:SubIdx is in
// PossibleSubclass for all registers Reg from RC using any
// subregister-index SubReg
for (const auto &SubIdx : RegisterClassHierarchy.getSubRegIndices()) {
BitVector BV(RegisterClassHierarchy.getRegClasses().size());
PossibleSubclass.getSuperRegClasses(&SubIdx, BV);
if (BV.test(RC->EnumValue)) {
std::string TmpKind2 = (Twine(TmpKind) + " " + RC->getName() +
" class-with-subregs: " + RC->getName())
.str();
VisitFn(&PossibleSubclass, TmpKind2);
}
}
}
}
void RegisterBankEmitter::emitBaseClassImplementation(
raw_ostream &OS, StringRef TargetName,
std::vector<RegisterBank> &Banks) {
const CodeGenRegBank &RegisterClassHierarchy = Target.getRegBank();
OS << "namespace llvm {\n"
<< "namespace " << TargetName << " {\n";
for (const auto &Bank : Banks) {
std::vector<std::vector<const CodeGenRegisterClass *>> RCsGroupedByWord(
(RegisterClassHierarchy.getRegClasses().size() + 31) / 32);
for (const auto &RC : Bank.register_classes())
RCsGroupedByWord[RC->EnumValue / 32].push_back(RC);
OS << "const uint32_t " << Bank.getCoverageArrayName() << "[] = {\n";
unsigned LowestIdxInWord = 0;
for (const auto &RCs : RCsGroupedByWord) {
OS << " // " << LowestIdxInWord << "-" << (LowestIdxInWord + 31) << "\n";
for (const auto &RC : RCs) {
std::string QualifiedRegClassID =
(Twine(RC->Namespace) + "::" + RC->getName() + "RegClassID").str();
OS << " (1u << (" << QualifiedRegClassID << " - "
<< LowestIdxInWord << ")) |\n";
}
OS << " 0,\n";
LowestIdxInWord += 32;
}
OS << "};\n";
}
OS << "\n";
for (const auto &Bank : Banks) {
std::string QualifiedBankID =
(TargetName + "::" + Bank.getEnumeratorName()).str();
const CodeGenRegisterClass &RC = *Bank.getRCWithLargestRegsSize();
unsigned Size = RC.RSI.get(DefaultMode).SpillSize;
OS << "RegisterBank " << Bank.getInstanceVarName() << "(/* ID */ "
<< QualifiedBankID << ", /* Name */ \"" << Bank.getName()
<< "\", /* Size */ " << Size << ", "
<< "/* CoveredRegClasses */ " << Bank.getCoverageArrayName()
<< ", /* NumRegClasses */ "
<< RegisterClassHierarchy.getRegClasses().size() << ");\n";
}
OS << "} // end namespace " << TargetName << "\n"
<< "\n";
OS << "RegisterBank *" << TargetName
<< "GenRegisterBankInfo::RegBanks[] = {\n";
for (const auto &Bank : Banks)
OS << " &" << TargetName << "::" << Bank.getInstanceVarName() << ",\n";
OS << "};\n\n";
OS << TargetName << "GenRegisterBankInfo::" << TargetName
<< "GenRegisterBankInfo()\n"
<< " : RegisterBankInfo(RegBanks, " << TargetName
<< "::NumRegisterBanks) {\n"
<< " // Assert that RegBank indices match their ID's\n"
<< "#ifndef NDEBUG\n"
<< " unsigned Index = 0;\n"
<< " for (const auto &RB : RegBanks)\n"
<< " assert(Index++ == RB->getID() && \"Index != ID\");\n"
<< "#endif // NDEBUG\n"
<< "}\n"
<< "} // end namespace llvm\n";
}
void RegisterBankEmitter::run(raw_ostream &OS) {
StringRef TargetName = Target.getName();
const CodeGenRegBank &RegisterClassHierarchy = Target.getRegBank();
Records.startTimer("Analyze records");
std::vector<RegisterBank> Banks;
for (const auto &V : Records.getAllDerivedDefinitions("RegisterBank")) {
SmallPtrSet<const CodeGenRegisterClass *, 8> VisitedRCs;
RegisterBank Bank(*V);
for (const CodeGenRegisterClass *RC :
Bank.getExplicitlySpecifiedRegisterClasses(RegisterClassHierarchy)) {
visitRegisterBankClasses(
RegisterClassHierarchy, RC, "explicit",
[&Bank](const CodeGenRegisterClass *RC, StringRef Kind) {
LLVM_DEBUG(dbgs()
<< "Added " << RC->getName() << "(" << Kind << ")\n");
Bank.addRegisterClass(RC);
},
VisitedRCs);
}
Banks.push_back(Bank);
}
// Warn about ambiguous MIR caused by register bank/class name clashes.
Records.startTimer("Warn ambiguous");
for (const auto &Class : RegisterClassHierarchy.getRegClasses()) {
for (const auto &Bank : Banks) {
if (Bank.getName().lower() == StringRef(Class.getName()).lower()) {
PrintWarning(Bank.getDef().getLoc(), "Register bank names should be "
"distinct from register classes "
"to avoid ambiguous MIR");
PrintNote(Bank.getDef().getLoc(), "RegisterBank was declared here");
PrintNote(Class.getDef()->getLoc(), "RegisterClass was declared here");
}
}
}
Records.startTimer("Emit output");
emitSourceFileHeader("Register Bank Source Fragments", OS);
OS << "#ifdef GET_REGBANK_DECLARATIONS\n"
<< "#undef GET_REGBANK_DECLARATIONS\n";
emitHeader(OS, TargetName, Banks);
OS << "#endif // GET_REGBANK_DECLARATIONS\n\n"
<< "#ifdef GET_TARGET_REGBANK_CLASS\n"
<< "#undef GET_TARGET_REGBANK_CLASS\n";
emitBaseClassDefinition(OS, TargetName, Banks);
OS << "#endif // GET_TARGET_REGBANK_CLASS\n\n"
<< "#ifdef GET_TARGET_REGBANK_IMPL\n"
<< "#undef GET_TARGET_REGBANK_IMPL\n";
emitBaseClassImplementation(OS, TargetName, Banks);
OS << "#endif // GET_TARGET_REGBANK_IMPL\n";
}
namespace llvm {
void EmitRegisterBank(RecordKeeper &RK, raw_ostream &OS) {
RegisterBankEmitter(RK).run(OS);
}
} // end namespace llvm
| sabel83/metashell | 3rd/templight/llvm/utils/TableGen/RegisterBankEmitter.cpp | C++ | gpl-3.0 | 12,878 |
# -*- coding: utf-8 -*-
"""
pythoner.net
Copyright (C) 2013 PYTHONER.ORG
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/>.
"""
from django.contrib import admin
from models import *
class ProfileAdmin(admin.ModelAdmin):
list_display = ('screen_name','city','introduction')
admin.site.register(UserProfile,ProfileAdmin) | yohn89/pythoner.net | pythoner/accounts/admin.py | Python | gpl-3.0 | 915 |
//
// MainWindow.h
// fakeThunder
//
// Created by Martian on 12-8-15.
// Copyright (c) 2012年 MartianZ. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface MainWindow : NSWindowController
@end
| yangchenghu/fakeThunder | fakeThunder/fakeThunder/MainWindow.h | C | gpl-3.0 | 209 |
// David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2017
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.0 (2016/06/19)
#include <GTEnginePCH.h>
#include <Graphics/GteViewVolumeNode.h>
using namespace gte;
ViewVolumeNode::ViewVolumeNode(std::shared_ptr<ViewVolume> const& viewVolume)
:
mOnUpdate([](ViewVolumeNode*){})
{
SetViewVolume(viewVolume);
}
void ViewVolumeNode::SetViewVolume(std::shared_ptr<ViewVolume> const& viewVolume)
{
mViewVolume = viewVolume;
if (mViewVolume)
{
Matrix4x4<float> rotate;
#if defined(GTE_USE_MAT_VEC)
rotate.SetCol(0, mViewVolume->GetDVector());
rotate.SetCol(1, mViewVolume->GetUVector());
rotate.SetCol(2, mViewVolume->GetRVector());
rotate.SetCol(3, { 0.0f, 0.0f, 0.0f, 1.0f });
#else
rotate.SetRow(0, mViewVolume->GetDVector());
rotate.SetRow(1, mViewVolume->GetUVector());
rotate.SetRow(2, mViewVolume->GetRVector());
rotate.SetRow(3, { 0.0f, 0.0f, 0.0f, 1.0f });
#endif
localTransform.SetTranslation(mViewVolume->GetPosition());
localTransform.SetRotation(rotate);
Update();
}
}
void ViewVolumeNode::UpdateWorldData(double applicationTime)
{
Node::UpdateWorldData(applicationTime);
if (mViewVolume)
{
Vector4<float> position = worldTransform.GetTranslationW1();
Matrix4x4<float> const& rotate = worldTransform.GetHMatrix();
#if defined(GTE_USE_MAT_VEC)
Vector4<float> dVector = rotate.GetCol(0);
Vector4<float> uVector = rotate.GetCol(1);
Vector4<float> rVector = rotate.GetCol(2);
#else
Vector4<float> dVector = rotate.GetRow(0);
Vector4<float> uVector = rotate.GetRow(1);
Vector4<float> rVector = rotate.GetRow(2);
#endif
mViewVolume->SetFrame(position, dVector, uVector, rVector);
mOnUpdate(this);
}
}
| yijiangh/FrameFab | ext/GTEngine/Source/Graphics/GteViewVolumeNode.cpp | C++ | gpl-3.0 | 2,029 |
from django.conf.urls.defaults import *
from indivo.views import *
from indivo.lib.utils import MethodDispatcher
urlpatterns = patterns('',
(r'^$', MethodDispatcher({
'DELETE' : carenet_delete})),
(r'^/rename$', MethodDispatcher({
'POST' : carenet_rename})),
(r'^/record$', MethodDispatcher({'GET':carenet_record})),
# Manage documents
(r'^/documents/', include('indivo.urls.carenet_documents')),
# Manage accounts
(r'^/accounts/$',
MethodDispatcher({
'GET' : carenet_account_list,
'POST' : carenet_account_create
})),
(r'^/accounts/(?P<account_id>[^/]+)$',
MethodDispatcher({ 'DELETE' : carenet_account_delete })),
# Manage apps
(r'^/apps/$',
MethodDispatcher({ 'GET' : carenet_apps_list})),
(r'^/apps/(?P<pha_email>[^/]+)$',
MethodDispatcher({ 'PUT' : carenet_apps_create,
'DELETE': carenet_apps_delete})),
# Permissions Calls
(r'^/accounts/(?P<account_id>[^/]+)/permissions$',
MethodDispatcher({ 'GET' : carenet_account_permissions })),
(r'^/apps/(?P<pha_email>[^/]+)/permissions$',
MethodDispatcher({ 'GET' : carenet_app_permissions })),
# Reporting Calls
(r'^/reports/minimal/procedures/$',
MethodDispatcher({'GET':carenet_procedure_list})),
(r'^/reports/minimal/simple-clinical-notes/$',
MethodDispatcher({'GET':carenet_simple_clinical_notes_list})),
(r'^/reports/minimal/equipment/$',
MethodDispatcher({'GET':carenet_equipment_list})),
(r'^/reports/minimal/measurements/(?P<lab_code>[^/]+)/$',
MethodDispatcher({'GET':carenet_measurement_list})),
(r'^/reports/(?P<data_model>[^/]+)/$',
MethodDispatcher({'GET':carenet_generic_list})),
# Demographics
(r'^/demographics$', MethodDispatcher({'GET': read_demographics_carenet})),
)
| sayan801/indivo_server | indivo/urls/carenet.py | Python | gpl-3.0 | 1,997 |
# coding: utf-8
import json
import logging
import dateutil.parser
import pytz
from werkzeug import urls
from odoo import api, fields, models, _
from odoo.addons.payment.models.payment_acquirer import ValidationError
from odoo.addons.payment_paypal.controllers.main import PaypalController
from odoo.tools.float_utils import float_compare
_logger = logging.getLogger(__name__)
class AcquirerPaypal(models.Model):
_inherit = 'payment.acquirer'
provider = fields.Selection(selection_add=[('paypal', 'Paypal')])
paypal_email_account = fields.Char('Paypal Email ID', required_if_provider='paypal', groups='base.group_user')
paypal_seller_account = fields.Char(
'Paypal Merchant ID', groups='base.group_user',
help='The Merchant ID is used to ensure communications coming from Paypal are valid and secured.')
paypal_use_ipn = fields.Boolean('Use IPN', default=True, help='Paypal Instant Payment Notification', groups='base.group_user')
paypal_pdt_token = fields.Char(string='Paypal PDT Token', help='Payment Data Transfer allows you to receive notification of successful payments as they are made.', groups='base.group_user')
# Server 2 server
paypal_api_enabled = fields.Boolean('Use Rest API', default=False)
paypal_api_username = fields.Char('Rest API Username', groups='base.group_user')
paypal_api_password = fields.Char('Rest API Password', groups='base.group_user')
paypal_api_access_token = fields.Char('Access Token', groups='base.group_user')
paypal_api_access_token_validity = fields.Datetime('Access Token Validity', groups='base.group_user')
# Default paypal fees
fees_dom_fixed = fields.Float(default=0.35)
fees_dom_var = fields.Float(default=3.4)
fees_int_fixed = fields.Float(default=0.35)
fees_int_var = fields.Float(default=3.9)
def _get_feature_support(self):
"""Get advanced feature support by provider.
Each provider should add its technical in the corresponding
key for the following features:
* fees: support payment fees computations
* authorize: support authorizing payment (separates
authorization and capture)
* tokenize: support saving payment data in a payment.tokenize
object
"""
res = super(AcquirerPaypal, self)._get_feature_support()
res['fees'].append('paypal')
return res
@api.model
def _get_paypal_urls(self, environment):
""" Paypal URLS """
if environment == 'prod':
return {
'paypal_form_url': 'https://www.paypal.com/cgi-bin/webscr',
'paypal_rest_url': 'https://api.paypal.com/v1/oauth2/token',
}
else:
return {
'paypal_form_url': 'https://www.sandbox.paypal.com/cgi-bin/webscr',
'paypal_rest_url': 'https://api.sandbox.paypal.com/v1/oauth2/token',
}
@api.multi
def paypal_compute_fees(self, amount, currency_id, country_id):
""" Compute paypal fees.
:param float amount: the amount to pay
:param integer country_id: an ID of a res.country, or None. This is
the customer's country, to be compared to
the acquirer company country.
:return float fees: computed fees
"""
if not self.fees_active:
return 0.0
country = self.env['res.country'].browse(country_id)
if country and self.company_id.country_id.id == country.id:
percentage = self.fees_dom_var
fixed = self.fees_dom_fixed
else:
percentage = self.fees_int_var
fixed = self.fees_int_fixed
fees = (percentage / 100.0 * amount + fixed) / (1 - percentage / 100.0)
return fees
@api.multi
def paypal_form_generate_values(self, values):
base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
paypal_tx_values = dict(values)
paypal_tx_values.update({
'cmd': '_xclick',
'business': self.paypal_email_account,
'item_name': '%s: %s' % (self.company_id.name, values['reference']),
'item_number': values['reference'],
'amount': values['amount'],
'currency_code': values['currency'] and values['currency'].name or '',
'address1': values.get('partner_address'),
'city': values.get('partner_city'),
'country': values.get('partner_country') and values.get('partner_country').code or '',
'state': values.get('partner_state') and (values.get('partner_state').code or values.get('partner_state').name) or '',
'email': values.get('partner_email'),
'zip_code': values.get('partner_zip'),
'first_name': values.get('partner_first_name'),
'last_name': values.get('partner_last_name'),
'paypal_return': urls.url_join(base_url, PaypalController._return_url),
'notify_url': urls.url_join(base_url, PaypalController._notify_url),
'cancel_return': urls.url_join(base_url, PaypalController._cancel_url),
'handling': '%.2f' % paypal_tx_values.pop('fees', 0.0) if self.fees_active else False,
'custom': json.dumps({'return_url': '%s' % paypal_tx_values.pop('return_url')}) if paypal_tx_values.get('return_url') else False,
})
return paypal_tx_values
@api.multi
def paypal_get_form_action_url(self):
return self._get_paypal_urls(self.environment)['paypal_form_url']
class TxPaypal(models.Model):
_inherit = 'payment.transaction'
paypal_txn_type = fields.Char('Transaction type')
# --------------------------------------------------
# FORM RELATED METHODS
# --------------------------------------------------
@api.model
def _paypal_form_get_tx_from_data(self, data):
reference, txn_id = data.get('item_number'), data.get('txn_id')
if not reference or not txn_id:
error_msg = _('Paypal: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id)
_logger.info(error_msg)
raise ValidationError(error_msg)
# find tx -> @TDENOTE use txn_id ?
txs = self.env['payment.transaction'].search([('reference', '=', reference)])
if not txs or len(txs) > 1:
error_msg = 'Paypal: received data for reference %s' % (reference)
if not txs:
error_msg += '; no order found'
else:
error_msg += '; multiple order found'
_logger.info(error_msg)
raise ValidationError(error_msg)
return txs[0]
@api.multi
def _paypal_form_get_invalid_parameters(self, data):
invalid_parameters = []
_logger.info('Received a notification from Paypal with IPN version %s', data.get('notify_version'))
if data.get('test_ipn'):
_logger.warning(
'Received a notification from Paypal using sandbox'
),
# TODO: txn_id: shoudl be false at draft, set afterwards, and verified with txn details
if self.acquirer_reference and data.get('txn_id') != self.acquirer_reference:
invalid_parameters.append(('txn_id', data.get('txn_id'), self.acquirer_reference))
# check what is buyed
if float_compare(float(data.get('mc_gross', '0.0')), (self.amount + self.fees), 2) != 0:
invalid_parameters.append(('mc_gross', data.get('mc_gross'), '%.2f' % self.amount)) # mc_gross is amount + fees
if data.get('mc_currency') != self.currency_id.name:
invalid_parameters.append(('mc_currency', data.get('mc_currency'), self.currency_id.name))
if 'handling_amount' in data and float_compare(float(data.get('handling_amount')), self.fees, 2) != 0:
invalid_parameters.append(('handling_amount', data.get('handling_amount'), self.fees))
# check buyer
if self.payment_token_id and data.get('payer_id') != self.payment_token_id.acquirer_ref:
invalid_parameters.append(('payer_id', data.get('payer_id'), self.payment_token_id.acquirer_ref))
# check seller
if data.get('receiver_id') and self.acquirer_id.paypal_seller_account and data['receiver_id'] != self.acquirer_id.paypal_seller_account:
invalid_parameters.append(('receiver_id', data.get('receiver_id'), self.acquirer_id.paypal_seller_account))
if not data.get('receiver_id') or not self.acquirer_id.paypal_seller_account:
# Check receiver_email only if receiver_id was not checked.
# In Paypal, this is possible to configure as receiver_email a different email than the business email (the login email)
# In Odoo, there is only one field for the Paypal email: the business email. This isn't possible to set a receiver_email
# different than the business email. Therefore, if you want such a configuration in your Paypal, you are then obliged to fill
# the Merchant ID in the Paypal payment acquirer in Odoo, so the check is performed on this variable instead of the receiver_email.
# At least one of the two checks must be done, to avoid fraudsters.
if data.get('receiver_email') != self.acquirer_id.paypal_email_account:
invalid_parameters.append(('receiver_email', data.get('receiver_email'), self.acquirer_id.paypal_email_account))
return invalid_parameters
@api.multi
def _paypal_form_validate(self, data):
status = data.get('payment_status')
res = {
'acquirer_reference': data.get('txn_id'),
'paypal_txn_type': data.get('payment_type'),
}
if status in ['Completed', 'Processed']:
_logger.info('Validated Paypal payment for tx %s: set as done' % (self.reference))
try:
# dateutil and pytz don't recognize abbreviations PDT/PST
tzinfos = {
'PST': -8 * 3600,
'PDT': -7 * 3600,
}
date = dateutil.parser.parse(data.get('payment_date'), tzinfos=tzinfos).astimezone(pytz.utc)
except:
date = fields.Datetime.now()
res.update(date=date)
self._set_transaction_done()
return self.write(res)
elif status in ['Pending', 'Expired']:
_logger.info('Received notification for Paypal payment %s: set as pending' % (self.reference))
res.update(state_message=data.get('pending_reason', ''))
self._set_transaction_pending()
return self.write(res)
else:
error = 'Received unrecognized status for Paypal payment %s: %s, set as error' % (self.reference, status)
_logger.info(error)
res.update(state_message=error)
self._set_transaction_cancel()
return self.write(res)
| t3dev/odoo | addons/payment_paypal/models/payment.py | Python | gpl-3.0 | 11,083 |
=head1 NAME
apt-cudf.conf - Configuration file for apt-cudf
=head1 DESCRIPTION
The configuration file allows one to define default optimization criterias for
all solvers known by apt-cudf
=head1 SYNTAX
solver: <solver list> | '*'
A comma-separated list of solvers. The character will make the optimization criteria
as default for all solvers without a more specific definition.
upgrade: <optimization criteria>
dist-upgrade: <optimization criteria>
install: <optimization criteria>
remove: <optimization criteria>
Default optimization criteria associated to apt-get actions. The optimization criteria
is solver specific. Specifying a incorrect criteria will result in an error from the
underlying cudf solver. Please refere to the solver man page for the correct syntax
trendy: <optimization criteria>
paranoid: <optimization criteria>
<keyword>: <optimization criteria>
Define a shortcut for an optimization criteria. The shortcut can then be used by apt-get
to pass a specific optimization criteria for a cudf solver
apt-get install gnome --solver aspcud -o "APT::Solver::aspcud::Preferences=trendy"
=head1 EXAMPLE
solver: mccs-cbc , mccs-lpsolve
upgrade: -lex[-new,-removed,-notuptodate]
dist-upgrade: -lex[-notuptodate,-new]
install: -lex[-removed,-changed]
remove: -lex[-removed,-changed]
trendy: -lex[-removed,-notuptodate,-unsat_recommends,-new]
paranoid: -lex[-removed,-changed]
solver: *
upgrade: -new,-removed,-notuptodate
dist-upgrade: -notuptodate,-new
install: -removed,-changed
remove: -removed,-changed
trendy: -removed,-notuptodate,-unsat_recommends,-new
paranoid: -removed,-changed
=head1 SEE ALSO
apt-cudf(8), apt-get(8), update-cudf-solvers(8),
L<README.cudf-solvers|file:///usr/share/doc/apt-cudf/README.cudf-solvers>,
L<README.Debian|file:///usr/share/doc/apt-cudf/README.Debian>
=head1 AUTHOR
Copyright: (C) 2011 Pietro Abate <pietro.abate@pps.jussieu.fr>
Copyright: (C) 2011 Stefano Zacchiroli <zack@debian.org>
License: GNU Lesser General Public License (GPL), version 3 or above
=cut
| avsm/opam-ppa | src_ext/dose/doc/manpages/apt-cudf.conf.pod | Perl | gpl-3.0 | 2,077 |
# 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/>.
# experiments.py
# Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com)
import unittest
import weka.core.jvm as jvm
import weka.core.converters as converters
import weka.classifiers as classifiers
import weka.experiments as experiments
import weka.plot.experiments as plot
import wekatests.tests.weka_test as weka_test
class TestExperiments(weka_test.WekaTest):
def test_plot_experiment(self):
"""
Tests the plot_experiment method.
"""
datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")]
cls = [
classifiers.Classifier("weka.classifiers.trees.REPTree"),
classifiers.Classifier("weka.classifiers.functions.LinearRegression"),
classifiers.Classifier("weka.classifiers.functions.SMOreg"),
]
outfile = self.tempfile("results-rs.arff")
exp = experiments.SimpleRandomSplitExperiment(
classification=False,
runs=10,
percentage=66.6,
preserve_order=False,
datasets=datasets,
classifiers=cls,
result=outfile)
exp.setup()
exp.run()
# evaluate
loader = converters.loader_for_file(outfile)
data = loader.load_file(outfile)
matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText")
tester = experiments.Tester("weka.experiment.PairedCorrectedTTester")
tester.resultmatrix = matrix
comparison_col = data.attribute_by_name("Correlation_coefficient").index
tester.instances = data
tester.header(comparison_col)
tester.multi_resultset_full(0, comparison_col)
# plot
plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False)
plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False)
def suite():
"""
Returns the test suite.
:return: the test suite
:rtype: unittest.TestSuite
"""
return unittest.TestLoader().loadTestsFromTestCase(TestExperiments)
if __name__ == '__main__':
jvm.start()
unittest.TextTestRunner().run(suite())
jvm.stop()
| nvoron23/python-weka-wrapper | tests/wekatests/plottests/experiments.py | Python | gpl-3.0 | 2,900 |
<div class="container" style="background-color:%textbackgroundcolor{.75}%;">
<span class="time_initial">
%time%
</span>
<span class="buddyicon">
<img src="%userIconPath%" width="24" height="24" />
</span>
<div class="placeholder" visible="%userIconPath%">
<span class="sender incoming">
%sender%
</span>
<span class="message incoming_link">
<br>%message%
</span>
</div>
<span class="clear"></span>
</div>
<span id="insert"></span>
| codebutler/synapse | src/Synapse.QtClient/resources/themes/minimal_mod.AdiumMessageStyle/Contents/Resources/Incoming/Content.html | HTML | gpl-3.0 | 522 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>io_service::strand::get_io_service</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../io_service__strand.html" title="io_service::strand">
<link rel="prev" href="dispatch.html" title="io_service::strand::dispatch">
<link rel="next" href="post.html" title="io_service::strand::post">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="dispatch.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../io_service__strand.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="post.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.io_service__strand.get_io_service"></a><a class="link" href="get_io_service.html" title="io_service::strand::get_io_service">io_service::strand::get_io_service</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idm45773618405744"></a>
Get the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> associated with the
strand.
</p>
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span> <span class="special">&</span> <span class="identifier">get_io_service</span><span class="special">();</span>
</pre>
<p>
This function may be used to obtain the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> object that the strand
uses to dispatch handlers for asynchronous operations.
</p>
<h6>
<a name="boost_asio.reference.io_service__strand.get_io_service.h0"></a>
<span class="phrase"><a name="boost_asio.reference.io_service__strand.get_io_service.return_value"></a></span><a class="link" href="get_io_service.html#boost_asio.reference.io_service__strand.get_io_service.return_value">Return
Value</a>
</h6>
<p>
A reference to the <a class="link" href="../io_service.html" title="io_service"><code class="computeroutput"><span class="identifier">io_service</span></code></a> object that the strand
will use to dispatch handlers. Ownership is not transferred to the caller.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="dispatch.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../io_service__strand.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="post.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| gwq5210/litlib | thirdparty/sources/boost_1_60_0/doc/html/boost_asio/reference/io_service__strand/get_io_service.html | HTML | gpl-3.0 | 4,494 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenCL.Net;
namespace Conv.NET
{
[Serializable]
public class FullyConnectedLayer : Layer
{
#region Fields
private double dropoutParameter;
// Host
private float[] weightsHost;
private float[] biasesHost;
// Device
[NonSerialized]
private Mem dropoutMaskGPU;
[NonSerialized]
private Mem weightsGPU;
[NonSerialized]
private Mem biasesGPU;
[NonSerialized]
private Mem weightsGradientsGPU;
[NonSerialized]
private Mem biasesGradientsGPU;
[NonSerialized]
private Mem weightsSpeedGPU;
[NonSerialized]
private Mem biasesSpeedGPU;
// Global and local work-group sizes (for OpenCL kernels) - will be set in SetWorkGroupSizes();
private IntPtr[] forwardGlobalWorkSizePtr;
private IntPtr[] forwardLocalWorkSizePtr;
private IntPtr[] backwardGlobalWorkSizePtr;
private IntPtr[] backwardLocalWorkSizePtr;
private IntPtr[] updateGlobalWorkSizePtr;
private IntPtr[] updateLocalWorkSizePtr;
private IntPtr[] constrainNormGlobalWorkSizePtr;
private IntPtr[] constrainNormLocalWorkSizePtr;
#endregion
#region Properties
public override Mem WeightsGPU
{
get { return weightsGPU; }
}
public override double DropoutParameter
{
set { this.dropoutParameter = value; }
}
#endregion
#region Setup methods
/// <summary>
/// Constructor of fully connected layer type. Specify number of units as argument.
/// </summary>
/// <param name="nUnits"></param>
public FullyConnectedLayer(int nUnits)
{
this.type = "FullyConnected";
this.nOutputUnits = nUnits;
}
public override void SetupOutput()
{
this.outputDepth = nOutputUnits;
this.outputHeight = 1;
this.outputWidth = 1;
this.outputNeurons = new Neurons(this.nOutputUnits);
#if OPENCL_ENABLED
this.dropoutMaskGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)(sizeof(bool) * nOutputUnits * inputNeurons.MiniBatchSize),
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "InitializeParameters(): Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(dropoutMaskGPU, nOutputUnits * inputNeurons.MiniBatchSize, typeof(bool));
#endif
}
public override void InitializeParameters(string Option)
{
base.InitializeParameters(Option); // makes sure this method is only call AFTER "SetupOutput()"
if (Option == "random") // sample new parameters
{
// WEIGHTS are initialized as normally distributed numbers with mean 0 and std equals to sqrt(2/nInputUnits)
// BIASES are initialized to a small positive number, e.g. 0.001
this.weightsHost = new float[nOutputUnits * nInputUnits];
this.biasesHost = new float[nOutputUnits];
double weightsStdDev = Math.Sqrt(2.0 / (10 * nInputUnits));
double uniformRand1;
double uniformRand2;
double tmp;
for (int iRow = 0; iRow < nOutputUnits; iRow++)
{
for (int iCol = 0; iCol < nInputUnits; iCol++)
{
uniformRand1 = Global.rng.NextDouble();
uniformRand2 = Global.rng.NextDouble();
// Use a Box-Muller transform to get a random normal(0,1)
tmp = Math.Sqrt(-2.0 * Math.Log(uniformRand1)) * Math.Sin(2.0 * Math.PI * uniformRand2);
tmp = weightsStdDev * tmp; // rescale
weightsHost[iRow * nInputUnits + iCol] = (float)tmp;
}
biasesHost[iRow] = 0.00f;
}
}
// else Option must be ''load'' => do not sample parameters, just load them from host to device
int weightBufferSize = sizeof(float) * (outputNeurons.NumberOfUnits * inputNeurons.NumberOfUnits);
int biasesBufferSize = sizeof(float) * outputNeurons.NumberOfUnits;
this.weightsGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite | MemFlags.CopyHostPtr,
(IntPtr)weightBufferSize,
weightsHost,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
this.biasesGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite | MemFlags.CopyHostPtr,
(IntPtr)biasesBufferSize,
biasesHost,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
// Also create weightsGradients and biasesGradients buffers and initialize them to zero
this.weightsGradientsGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)weightBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(weightsGradientsGPU, (nInputUnits * nOutputUnits), typeof(float));
this.biasesGradientsGPU = (Mem)Cl.CreateBuffer( OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)biasesBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(biasesGradientsGPU, nOutputUnits, typeof(float));
// Also create weightsSpeed and biasesSpeed buffers and initialize them to zero
this.weightsSpeedGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)weightBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(weightsSpeedGPU, (nInputUnits * nOutputUnits), typeof(float));
this.biasesSpeedGPU = (Mem)Cl.CreateBuffer(OpenCLSpace.Context,
MemFlags.ReadWrite,
(IntPtr)biasesBufferSize,
out OpenCLSpace.ClError);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.CreateBuffer");
OpenCLSpace.WipeBuffer(biasesSpeedGPU, nOutputUnits, typeof(float));
}
public override void SetWorkGroups()
{
// Work group sizes will be set as follows:
// global work size = smallest multiple of OPTIMAL_GROUP_SIZE larger than
// the total number of processes needed (for efficiency).
// local work size = as close as possible to OPTIMAL_GROUP_SIZE (making sure
// that global worksize is a multiple of this)
// OPTIMAL_GROUP_SIZE is a small multiple of BASE_GROUP_SIZE, which in turn is a
// constant multiple of 2, platform-dependent, e.g. 32 (Nvidia
// WARP) or 64 (AMD WAVEFRONT).
int miniBatchSize = outputNeurons.MiniBatchSize;
// FeedForward (2D) ________________________________________________________________________________
// Local
int optimalToBaseRatio = OpenCLSpace.OPTIMAL_GROUP_SIZE / OpenCLSpace.BASE_GROUP_SIZE;
this.forwardLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE, (IntPtr)optimalToBaseRatio };
// Global
int smallestMultiple0 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nOutputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
int smallestMultiple1 = (int)(optimalToBaseRatio * Math.Ceiling((double)(miniBatchSize) / (double)optimalToBaseRatio));
this.forwardGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// BackPropagate (2D) _________________________________________________________________________________
// Local
this.backwardLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE, (IntPtr)optimalToBaseRatio };
// Global
smallestMultiple0 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nInputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE)); // input this time!
this.backwardGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// UpdateSpeeds and UpdateParameters (2D) ________________________________________________________________
// Local
this.updateLocalWorkSizePtr = new IntPtr[] { (IntPtr)optimalToBaseRatio, (IntPtr)OpenCLSpace.BASE_GROUP_SIZE }; // product is OPTIMAL_WORK_SIZE
// Global
smallestMultiple0 = (int)(optimalToBaseRatio * Math.Ceiling((double)(nOutputUnits) / (double)optimalToBaseRatio));
smallestMultiple1 = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nInputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
this.updateGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultiple0, (IntPtr)smallestMultiple1 };
// Max norm constrain
this.constrainNormLocalWorkSizePtr = new IntPtr[] { (IntPtr)OpenCLSpace.BASE_GROUP_SIZE };
int smallestMultipleAux = (int)(OpenCLSpace.BASE_GROUP_SIZE * Math.Ceiling((double)(nOutputUnits) / (double)OpenCLSpace.BASE_GROUP_SIZE));
this.constrainNormGlobalWorkSizePtr = new IntPtr[] { (IntPtr)smallestMultipleAux };
}
public override void CopyBuffersToHost()
{
OpenCLSpace.ClError = Cl.EnqueueReadBuffer( OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
weightsHost, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer weightsGPU");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.EnqueueReadBuffer( OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
biasesHost, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer biasesGPU");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Speeds are not saved.
}
#endregion
#region Methods
public override void FeedForward()
{
#if TIMING_LAYERS
Utils.FCForwardTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCForward, 0, outputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 1, inputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 2, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 3, biasesGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 6, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 7, (IntPtr)sizeof(float), (float)dropoutParameter);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 8, (IntPtr)sizeof(ulong), (ulong)Guid.NewGuid().GetHashCode()); // this should be quite a good random seed
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCForward, 9, dropoutMaskGPU);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.FeedForward(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCForward,
2,
null,
forwardGlobalWorkSizePtr,
forwardLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.FeedForward(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
// TODO: add dropout CPU
// Generate dropout mask
if (dropoutParameter < 1)
{
for (int iUnit = 0; iUnit < nOutputUnits * inputNeurons.MiniBatchSize; ++iUnit)
dropoutMask[iUnit] = Global.RandomDouble() < dropoutParameter;
}
for (int m = 0; m < inputNeurons.MiniBatchSize; m++)
{
double[] unbiasedOutput = Utils.MultiplyMatrixByVector(weights, inputNeurons.GetHost()[m]);
this.outputNeurons.SetHost(m, unbiasedOutput.Zip(biases, (x, y) => x + y).ToArray());
}
#endif
#if TIMING_LAYERS
Utils.FCForwardTimer.Stop();
#endif
}
public override void BackPropagate()
{
#if TIMING_LAYERS
Utils.FCBackpropTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 0, inputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 1, outputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 2, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 3, dropoutMaskGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCBackward, 6, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.BackPropagate(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCBackward,
2,
null,
backwardGlobalWorkSizePtr,
backwardLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.BackPropagate(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
for (int m = 0; m < inputNeurons.MiniBatchSize; m++)
{
inputNeurons.DeltaHost[m] = Utils.MultiplyMatrixTranspByVector(weights, outputNeurons.DeltaHost[m]);
}
#endif
#if TIMING_LAYERS
Utils.FCBackpropTimer.Stop();
#endif
}
public override void UpdateSpeeds(double learningRate, double momentumCoefficient, double weightDecayCoefficient)
{
#if TIMING_LAYERS
Utils.FCUpdateSpeedsTimer.Start();
#endif
#if DEBUGGING_STEPBYSTEP_FC
float[,] weightsBeforeUpdate = new float[output.NumberOfUnits, input.NumberOfUnits];
/* ------------------------- DEBUGGING --------------------------------------------- */
#if OPENCL_ENABLED
// Display weights before update
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * input.NumberOfUnits * sizeof(float)),
weightsBeforeUpdate, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer weightsBeforeUpdate");
#else
weightsBeforeUpdate = weights;
#endif
Console.WriteLine("\nWeights BEFORE update:");
for (int i = 0; i < weightsBeforeUpdate.GetLength(0); i++)
{
for (int j = 0; j < weightsBeforeUpdate.GetLength(1); j++)
Console.Write("{0} ", weightsBeforeUpdate[i, j]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
// Display biases before update
float[] biasesBeforeUpdate = new float[output.NumberOfUnits];
#if OPENCL_ENABLED
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * sizeof(float)),
biasesBeforeUpdate, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer biasesBeforeUpdate");
#else
biasesBeforeUpdate = biases;
#endif
Console.WriteLine("\nBiases BEFORE update:");
for (int i = 0; i < biasesBeforeUpdate.Length; i++)
{
Console.Write("{0} ", biasesBeforeUpdate[i]);
}
Console.WriteLine();
Console.ReadKey();
// Display weight update speed before update
float[,] tmpWeightsUpdateSpeed = new float[output.NumberOfUnits, input.NumberOfUnits];
#if OPENCL_ENABLED
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsUpdateSpeedGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * input.NumberOfUnits * sizeof(float)),
tmpWeightsUpdateSpeed, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer weightsUpdateSpeed");
#else
tmpWeightsUpdateSpeed = weightsUpdateSpeed;
#endif
Console.WriteLine("\nWeight update speed BEFORE update:");
for (int i = 0; i < tmpWeightsUpdateSpeed.GetLength(0); i++)
{
for (int j = 0; j < tmpWeightsUpdateSpeed.GetLength(1); j++)
Console.Write("{0} ", tmpWeightsUpdateSpeed[i, j]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
// Display input activations before update
/*
float[] inputActivations = new float[input.NumberOfUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
input.ActivationsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(input.NumberOfUnits * sizeof(float)),
inputActivations, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer inputActivations");
Console.WriteLine("\nInput activations BEFORE update:");
for (int j = 0; j < inputActivations.Length; j++)
{
Console.Write("{0} ", inputActivations[j]);
}
Console.WriteLine();
Console.ReadKey();
// Display output delta before update
float[] outputDelta = new float[output.NumberOfUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
output.DeltaGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(output.NumberOfUnits * sizeof(float)),
outputDelta, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnectedLayer.UpdateParameters Cl.clEnqueueReadBuffer outputDelta");
Console.WriteLine("\nOutput delta BEFORE update:");
for (int i = 0; i < outputDelta.Length; i++)
{
Console.Write("{0}", outputDelta[i]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadKey();
*/
/*------------------------- END DEBUGGING --------------------------------------------- */
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 0, weightsSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 1, biasesSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 2, weightsGradientsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 3, biasesGradientsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 4, inputNeurons.ActivationsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 5, outputNeurons.DeltaGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 6, dropoutMaskGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 7, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 8, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 9, (IntPtr)sizeof(float), (float)momentumCoefficient);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 10, (IntPtr)sizeof(float), (float)learningRate);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 11, (IntPtr)sizeof(int), inputNeurons.MiniBatchSize);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 12, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateSpeeds, 13, (IntPtr)sizeof(float), (float)weightDecayCoefficient);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateSpeeds(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCUpdateSpeeds,
2,
null,
updateGlobalWorkSizePtr,
updateLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateSpeeds(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
int miniBatchSize = inputNeurons.MiniBatchSize;
for (int m = 0; m < miniBatchSize; m++)
{
for (int i = 0; i < nOutputUnits; i++)
{
// weights speed
for (int j = 0; j < nInputUnits; j++)
{
if (m == 0)
weightsUpdateSpeed[i, j] *= momentumCoefficient;
weightsUpdateSpeed[i, j] -= learningRate/miniBatchSize * inputNeurons.GetHost()[m][j] * outputNeurons.DeltaHost[m][i];
#if GRADIENT_CHECK
weightsGradients[i, j] = inputNeurons.GetHost()[m][j] * outputNeurons.DeltaHost[m][i];
#endif
}
// update biases
if (m == 0)
biasesUpdateSpeed[i] *= momentumCoefficient;
biasesUpdateSpeed[i] -= learningRate/miniBatchSize * outputNeurons.DeltaHost[m][i];
#if GRADIENT_CHECK
biasesGradients[i] = outputNeurons.DeltaHost[m][i];
#endif
}
} // end loop over mini-batch
#endif
#if TIMING_LAYERS
Utils.FCUpdateSpeedsTimer.Stop();
#endif
}
public override void UpdateParameters(double weightMaxNorm)
{
#if TIMING_LAYERS
Utils.FCUpdateParametersTimer.Start();
#endif
#if OPENCL_ENABLED
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 0, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 1, biasesGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 2, weightsSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 3, biasesSpeedGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 4, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCUpdateParameters, 5, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateParameters(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel( OpenCLSpace.Queue,
OpenCLSpace.FCUpdateParameters,
2,
null,
updateGlobalWorkSizePtr,
updateLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FullyConnected.UpdateParameters(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
// Now constrain norm of each weight vector
if (!double.IsInfinity(weightMaxNorm))
{
// Set kernel arguments
OpenCLSpace.ClError = Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 0, weightsGPU);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 1, (IntPtr)sizeof(int), nOutputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 2, (IntPtr)sizeof(int), nInputUnits);
OpenCLSpace.ClError |= Cl.SetKernelArg(OpenCLSpace.FCConstrainWeightNorm, 3, (IntPtr)sizeof(float), (float)weightMaxNorm);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FCConstrainWeightNorm(): Cl.SetKernelArg");
// Run kernel
OpenCLSpace.ClError = Cl.EnqueueNDRangeKernel(OpenCLSpace.Queue,
OpenCLSpace.FCConstrainWeightNorm,
1,
null,
constrainNormGlobalWorkSizePtr,
constrainNormLocalWorkSizePtr,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "FCConstrainWeightNorm(): Cl.EnqueueNDRangeKernel");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
}
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
#else
for (int i = 0; i < nOutputUnits; i++)
{
// weights update
for (int j = 0; j < nInputUnits; j++)
{
weights[i, j] += weightsUpdateSpeed[i, j];
}
// update biases
biases[i] += biasesUpdateSpeed[i];
}
#endif
#if TIMING_LAYERS
Utils.FCUpdateParametersTimer.Stop();
#endif
}
#endregion
#region Gradient check
public override double[] GetParameters()
{
int nParameters = nInputUnits * nOutputUnits + nOutputUnits;
double[] parameters = new double[nParameters];
// Copy weights and biases buffers to host
float[] tmpWeights = new float[nInputUnits * nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeights, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
float[] tmpBiases = new float[nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiases, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Convert to double and write into parameters array
for (int i = 0; i < nInputUnits*nOutputUnits; ++i)
{
parameters[i] = (double)tmpWeights[i];
}
for (int i = 0; i < nOutputUnits; ++i)
{
parameters[nInputUnits * nOutputUnits + i] = (double)tmpBiases[i];
}
return parameters;
}
public override double[] GetParameterGradients()
{
int nParameters = nInputUnits * nOutputUnits + nOutputUnits;
double[] parameterGradients = new double[nParameters];
// Copy weights and biases gradients buffers to host
float[] tmpWeightsGrad = new float[nInputUnits * nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
weightsGradientsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeightsGrad, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
float[] tmpBiasesGrad = new float[nOutputUnits];
OpenCLSpace.ClError = Cl.EnqueueReadBuffer(OpenCLSpace.Queue,
biasesGradientsGPU, // source
Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiasesGrad, // destination
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "clEnqueueReadBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
// Convert to double and write into parameterGradients
//Console.WriteLine("Weight gradients:\n");
for (int i = 0; i < nInputUnits * nOutputUnits; ++i)
{
parameterGradients[i] = (double)tmpWeightsGrad[i];
//Console.Write(" {0}", tmpWeightsGrad[i]);
}
//Console.ReadKey();
for (int i = 0; i < nOutputUnits; ++i)
{
parameterGradients[nInputUnits * nOutputUnits + i] = (double)tmpBiasesGrad[i];
}
return parameterGradients;
}
public override void SetParameters(double[] NewParameters)
{
// Convert to float and write into tmp arrays
float[] tmpWeights = new float[nInputUnits * nOutputUnits];
float[] tmpBiases = new float[nOutputUnits];
for (int i = 0; i < nInputUnits * nOutputUnits; ++i)
{
tmpWeights[i] = (float)NewParameters[i];
}
for (int i = 0; i < nOutputUnits; ++i)
{
tmpBiases[i] = (float)NewParameters[nInputUnits * nOutputUnits + i];
}
// Write arrays into buffers on device
OpenCLSpace.ClError = Cl.EnqueueWriteBuffer(OpenCLSpace.Queue,
weightsGPU,
OpenCL.Net.Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nInputUnits * nOutputUnits),
tmpWeights,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueWriteBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.EnqueueWriteBuffer(OpenCLSpace.Queue,
biasesGPU,
OpenCL.Net.Bool.True,
(IntPtr)0,
(IntPtr)(sizeof(float) * nOutputUnits),
tmpBiases,
0,
null,
out OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.EnqueueWriteBuffer");
OpenCLSpace.ClError = Cl.ReleaseEvent(OpenCLSpace.ClEvent);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.ReleaseEvent");
OpenCLSpace.ClError = Cl.Finish(OpenCLSpace.Queue);
OpenCLSpace.CheckErr(OpenCLSpace.ClError, "Cl.Finish");
}
#endregion
}
}
| jcredi/ConvDotNet | Conv.NET/FullyConnectedLayer.cs | C# | gpl-3.0 | 42,556 |
# Contributing to Viewer
## How to report bugs
### Make sure it is a Viewer bug
Most bugs reported to our bug tracker are actually bugs in user code, not in Viewer code. Keep in mind that just because your code throws an error inside of Viewer, this does *not* mean the bug is a Viewer bug.
Ask for help first in a discussion forum like [Stack Overflow](http://stackoverflow.com/). You will get much quicker support, and you will help avoid tying up the Viewer team with invalid bug reports.
### Disable browser extensions
Make sure you have reproduced the bug with all browser extensions and add-ons disabled, as these can sometimes cause things to break in interesting and unpredictable ways. Try using incognito, stealth or anonymous browsing modes.
### Try the latest version of Viewer
Bugs in old versions of Viewer may have already been fixed. In order to avoid reporting known issues, make sure you are always testing against the [latest release](https://github.com/fengyuanchen/viewerjs/releases/latest). We cannot fix bugs in older released files, if a bug has been fixed in a subsequent version of Viewer the site should upgrade.
### Simplify the test case
When experiencing a problem, [reduce your code](http://webkit.org/quality/reduction.html) to the bare minimum required to reproduce the issue. This makes it *much* easier to isolate and fix the offending code. Bugs reported without reduced test cases take on average 9001% longer to fix than bugs that are submitted with them, so you really should try to do this if at all possible.
### Search for related or duplicate issues
Go to the [Viewer issue tracker](https://github.com/fengyuanchen/viewerjs/issues) and make sure the problem hasn't already been reported. If not, create a new issue there and include your test case.
### Browser support
Remember that Viewer supports multiple browsers and their versions; any contributed code must work in all of them. You can refer to the [browser support page](README.md#browser-support) for the current list of supported browsers.
## Notes for pull request
- Run the test suites in the `test` directory first.
- Don't modify any files in the `dist` directory.
- Follow the same code style as the library.
| pedroengideas/alegraPrueba | assest/viewerjs/CONTRIBUTING.md | Markdown | gpl-3.0 | 2,240 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Code\Scanner;
use Zend\Code\Annotation\AnnotationManager;
use Zend\Code\Exception;
use Zend\Code\NameInformation;
use function array_slice;
use function count;
use function is_int;
use function is_string;
use function ltrim;
use function strtolower;
use function substr_count;
use function var_export;
class MethodScanner implements ScannerInterface
{
/**
* @var bool
*/
protected $isScanned = false;
/**
* @var string
*/
protected $docComment;
/**
* @var ClassScanner
*/
protected $scannerClass;
/**
* @var string
*/
protected $class;
/**
* @var string
*/
protected $name;
/**
* @var int
*/
protected $lineStart;
/**
* @var int
*/
protected $lineEnd;
/**
* @var bool
*/
protected $isFinal = false;
/**
* @var bool
*/
protected $isAbstract = false;
/**
* @var bool
*/
protected $isPublic = true;
/**
* @var bool
*/
protected $isProtected = false;
/**
* @var bool
*/
protected $isPrivate = false;
/**
* @var bool
*/
protected $isStatic = false;
/**
* @var string
*/
protected $body = '';
/**
* @var array
*/
protected $tokens = [];
/**
* @var NameInformation
*/
protected $nameInformation;
/**
* @var array
*/
protected $infos = [];
/**
* @param array $methodTokens
* @param NameInformation $nameInformation
*/
public function __construct(array $methodTokens, NameInformation $nameInformation = null)
{
$this->tokens = $methodTokens;
$this->nameInformation = $nameInformation;
}
/**
* @param string $class
* @return MethodScanner
*/
public function setClass($class)
{
$this->class = (string) $class;
return $this;
}
/**
* @param ClassScanner $scannerClass
* @return MethodScanner
*/
public function setScannerClass(ClassScanner $scannerClass)
{
$this->scannerClass = $scannerClass;
return $this;
}
/**
* @return ClassScanner
*/
public function getClassScanner()
{
return $this->scannerClass;
}
/**
* @return string
*/
public function getName()
{
$this->scan();
return $this->name;
}
/**
* @return int
*/
public function getLineStart()
{
$this->scan();
return $this->lineStart;
}
/**
* @return int
*/
public function getLineEnd()
{
$this->scan();
return $this->lineEnd;
}
/**
* @return string
*/
public function getDocComment()
{
$this->scan();
return $this->docComment;
}
/**
* @param AnnotationManager $annotationManager
* @return AnnotationScanner|false
*/
public function getAnnotations(AnnotationManager $annotationManager)
{
if (($docComment = $this->getDocComment()) == '') {
return false;
}
return new AnnotationScanner($annotationManager, $docComment, $this->nameInformation);
}
/**
* @return bool
*/
public function isFinal()
{
$this->scan();
return $this->isFinal;
}
/**
* @return bool
*/
public function isAbstract()
{
$this->scan();
return $this->isAbstract;
}
/**
* @return bool
*/
public function isPublic()
{
$this->scan();
return $this->isPublic;
}
/**
* @return bool
*/
public function isProtected()
{
$this->scan();
return $this->isProtected;
}
/**
* @return bool
*/
public function isPrivate()
{
$this->scan();
return $this->isPrivate;
}
/**
* @return bool
*/
public function isStatic()
{
$this->scan();
return $this->isStatic;
}
/**
* Override the given name for a method, this is necessary to
* support traits.
*
* @param string $name
* @return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Visibility must be of T_PUBLIC, T_PRIVATE or T_PROTECTED
* Needed to support traits
*
* @param int $visibility T_PUBLIC | T_PRIVATE | T_PROTECTED
* @return self
* @throws \Zend\Code\Exception\InvalidArgumentException
*/
public function setVisibility($visibility)
{
switch ($visibility) {
case T_PUBLIC:
$this->isPublic = true;
$this->isPrivate = false;
$this->isProtected = false;
break;
case T_PRIVATE:
$this->isPublic = false;
$this->isPrivate = true;
$this->isProtected = false;
break;
case T_PROTECTED:
$this->isPublic = false;
$this->isPrivate = false;
$this->isProtected = true;
break;
default:
throw new Exception\InvalidArgumentException('Invalid visibility argument passed to setVisibility.');
}
return $this;
}
/**
* @return int
*/
public function getNumberOfParameters()
{
return count($this->getParameters());
}
/**
* @param bool $returnScanner
* @return array
*/
public function getParameters($returnScanner = false)
{
$this->scan();
$return = [];
foreach ($this->infos as $info) {
if ($info['type'] != 'parameter') {
continue;
}
if (! $returnScanner) {
$return[] = $info['name'];
} else {
$return[] = $this->getParameter($info['name']);
}
}
return $return;
}
/**
* @param int|string $parameterNameOrInfoIndex
* @return ParameterScanner
* @throws Exception\InvalidArgumentException
*/
public function getParameter($parameterNameOrInfoIndex)
{
$this->scan();
if (is_int($parameterNameOrInfoIndex)) {
$info = $this->infos[$parameterNameOrInfoIndex];
if ($info['type'] != 'parameter') {
throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter');
}
} elseif (is_string($parameterNameOrInfoIndex)) {
foreach ($this->infos as $info) {
if ($info['type'] === 'parameter' && $info['name'] === $parameterNameOrInfoIndex) {
break;
}
unset($info);
}
if (! isset($info)) {
throw new Exception\InvalidArgumentException('Index of info offset is not about a parameter');
}
}
$p = new ParameterScanner(
array_slice($this->tokens, $info['tokenStart'], $info['tokenEnd'] - $info['tokenStart']),
$this->nameInformation
);
$p->setDeclaringFunction($this->name);
$p->setDeclaringScannerFunction($this);
$p->setDeclaringClass($this->class);
$p->setDeclaringScannerClass($this->scannerClass);
$p->setPosition($info['position']);
return $p;
}
/**
* @return string
*/
public function getBody()
{
$this->scan();
return $this->body;
}
public static function export()
{
// @todo
}
public function __toString()
{
$this->scan();
return var_export($this, true);
}
protected function scan()
{
if ($this->isScanned) {
return;
}
if (! $this->tokens) {
throw new Exception\RuntimeException('No tokens were provided');
}
/**
* Variables & Setup
*/
$tokens = &$this->tokens; // localize
$infos = &$this->infos; // localize
$tokenIndex = null;
$token = null;
$tokenType = null;
$tokenContent = null;
$tokenLine = null;
$infoIndex = 0;
$parentCount = 0;
/*
* MACRO creation
*/
$MACRO_TOKEN_ADVANCE = function () use (
&$tokens,
&$tokenIndex,
&$token,
&$tokenType,
&$tokenContent,
&$tokenLine
) {
static $lastTokenArray = null;
$tokenIndex = $tokenIndex === null ? 0 : $tokenIndex + 1;
if (! isset($tokens[$tokenIndex])) {
$token = false;
$tokenContent = false;
$tokenType = false;
$tokenLine = false;
return false;
}
$token = $tokens[$tokenIndex];
if (is_string($token)) {
$tokenType = null;
$tokenContent = $token;
$tokenLine += substr_count(
$lastTokenArray[1] ?? '',
"\n"
); // adjust token line by last known newline count
} else {
$lastTokenArray = $token;
[$tokenType, $tokenContent, $tokenLine] = $token;
}
return $tokenIndex;
};
$MACRO_INFO_START = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) {
$infos[$infoIndex] = [
'type' => 'parameter',
'tokenStart' => $tokenIndex,
'tokenEnd' => null,
'lineStart' => $tokenLine,
'lineEnd' => $tokenLine,
'name' => null,
'position' => $infoIndex + 1, // position is +1 of infoIndex
];
};
$MACRO_INFO_ADVANCE = function () use (&$infoIndex, &$infos, &$tokenIndex, &$tokenLine) {
$infos[$infoIndex]['tokenEnd'] = $tokenIndex;
$infos[$infoIndex]['lineEnd'] = $tokenLine;
$infoIndex++;
return $infoIndex;
};
/**
* START FINITE STATE MACHINE FOR SCANNING TOKENS
*/
// Initialize token
$MACRO_TOKEN_ADVANCE();
SCANNER_TOP:
$this->lineStart = $this->lineStart ? : $tokenLine;
switch ($tokenType) {
case T_DOC_COMMENT:
$this->lineStart = null;
if ($this->docComment === null && $this->name === null) {
$this->docComment = $tokenContent;
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_FINAL:
$this->isFinal = true;
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_ABSTRACT:
$this->isAbstract = true;
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_PUBLIC:
// use defaults
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_PROTECTED:
$this->setVisibility(T_PROTECTED);
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_PRIVATE:
$this->setVisibility(T_PRIVATE);
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_STATIC:
$this->isStatic = true;
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_NS_SEPARATOR:
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case T_VARIABLE:
case T_STRING:
if ($tokenType === T_STRING && $parentCount === 0) {
$this->name = $tokenContent;
}
if ($parentCount === 1) {
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
if ($tokenType === T_VARIABLE) {
$infos[$infoIndex]['name'] = ltrim($tokenContent, '$');
}
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case null:
switch ($tokenContent) {
case '&':
if (! isset($infos[$infoIndex])) {
$MACRO_INFO_START();
}
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case '(':
$parentCount++;
goto SCANNER_CONTINUE_SIGNATURE;
// goto (no break needed);
case ')':
$parentCount--;
if ($parentCount > 0) {
goto SCANNER_CONTINUE_SIGNATURE;
}
if ($parentCount === 0) {
if ($infos) {
$MACRO_INFO_ADVANCE();
}
$context = 'body';
}
goto SCANNER_CONTINUE_BODY;
// goto (no break needed);
case ',':
if ($parentCount === 1) {
$MACRO_INFO_ADVANCE();
}
goto SCANNER_CONTINUE_SIGNATURE;
}
}
SCANNER_CONTINUE_SIGNATURE:
if ($MACRO_TOKEN_ADVANCE() === false) {
goto SCANNER_END;
}
goto SCANNER_TOP;
SCANNER_CONTINUE_BODY:
$braceCount = 0;
while ($MACRO_TOKEN_ADVANCE() !== false) {
if ($tokenContent == '}') {
$braceCount--;
}
if ($braceCount > 0) {
$this->body .= $tokenContent;
}
if ($tokenContent == '{') {
$braceCount++;
}
$this->lineEnd = $tokenLine;
}
SCANNER_END:
$this->isScanned = true;
}
}
| monocasual/giada-www | src/forum/vendor/zendframework/zend-code/src/Scanner/MethodScanner.php | PHP | gpl-3.0 | 15,018 |
<?php
/**
* Copyright © OXID eSales AG. All rights reserved.
* See LICENSE file for license details.
*/
declare(strict_types=1);
namespace OxidEsales\EshopCommunity\Internal\Framework\Module\Configuration\Exception;
class ProjectConfigurationIsEmptyException extends \Exception
{
}
| OXID-eSales/oxideshop_ce | source/Internal/Framework/Module/Configuration/Exception/ProjectConfigurationIsEmptyException.php | PHP | gpl-3.0 | 291 |
% This is part of Exercices et corrigés de CdI-1
% Copyright (c) 2011
% Laurent Claessens
% See the file fdl-1.3.txt for copying conditions.
\begin{exercice}\label{exoEqsDiff0005}
Soit $p(t)$ le nombre d'individus d'une population à l'instant $t$. Un modèle de population classique et très simple est celui régi par $p' = K p$ où $K \in \eR$ est le taux de croissance de la population (taux de natalité moins le taux de mortalité). La résolution de cette équation différentielle montre que la croissance de la population est exponentielle, ce qui est généralement satisfaisant tant qu'il n'y a pas de problèmes de surpopulation (territoire et ressource illimités). Pour tenir compte de tels problèmes, on suppose plutôt que $p$ est régie par l'équation différentielle $p' = Kp(M-p)$ où $M \in \eR_0^+$ est le seuil de surpopulation.
\begin{enumerate}
\item
Sachant que $p(0) = p_0$ déterminez $p(t)$.
\item
Déterminez le comportement de $p(t)$ lorsque $t$ tend vers $+\infty $.
\item
Dessiner le champ de pentes correspondant à cette équation et en déduire l'allure des solutions sans utiliser la résolution de l'équation différentielle. Remarquez que $p=M$ est une solution stable, alors que $p=0$ est instable.
\end{enumerate}
\end{exercice}
| LaurentClaessens/mazhe | tex/exocorr/exoEqsDiff0005.tex | TeX | gpl-3.0 | 1,279 |
#ifndef __AGENT_H
#define __AGENT_H
#include "libssh/libssh.h"
/* Messages for the authentication agent connection. */
#define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1
#define SSH_AGENT_RSA_IDENTITIES_ANSWER 2
#define SSH_AGENTC_RSA_CHALLENGE 3
#define SSH_AGENT_RSA_RESPONSE 4
#define SSH_AGENT_FAILURE 5
#define SSH_AGENT_SUCCESS 6
#define SSH_AGENTC_ADD_RSA_IDENTITY 7
#define SSH_AGENTC_REMOVE_RSA_IDENTITY 8
#define SSH_AGENTC_REMOVE_ALL_RSA_IDENTITIES 9
/* private OpenSSH extensions for SSH2 */
#define SSH2_AGENTC_REQUEST_IDENTITIES 11
#define SSH2_AGENT_IDENTITIES_ANSWER 12
#define SSH2_AGENTC_SIGN_REQUEST 13
#define SSH2_AGENT_SIGN_RESPONSE 14
#define SSH2_AGENTC_ADD_IDENTITY 17
#define SSH2_AGENTC_REMOVE_IDENTITY 18
#define SSH2_AGENTC_REMOVE_ALL_IDENTITIES 19
/* smartcard */
#define SSH_AGENTC_ADD_SMARTCARD_KEY 20
#define SSH_AGENTC_REMOVE_SMARTCARD_KEY 21
/* lock/unlock the agent */
#define SSH_AGENTC_LOCK 22
#define SSH_AGENTC_UNLOCK 23
/* add key with constraints */
#define SSH_AGENTC_ADD_RSA_ID_CONSTRAINED 24
#define SSH2_AGENTC_ADD_ID_CONSTRAINED 25
#define SSH_AGENTC_ADD_SMARTCARD_KEY_CONSTRAINED 26
#define SSH_AGENT_CONSTRAIN_LIFETIME 1
#define SSH_AGENT_CONSTRAIN_CONFIRM 2
/* extended failure messages */
#define SSH2_AGENT_FAILURE 30
/* additional error code for ssh.com's ssh-agent2 */
#define SSH_COM_AGENT2_FAILURE 102
#define SSH_AGENT_OLD_SIGNATURE 0x01
struct ssh_agent_struct {
struct socket *sock;
ssh_buffer ident;
unsigned int count;
};
#ifndef _WIN32
/* agent.c */
/**
* @brief Create a new ssh agent structure.
*
* @return An allocated ssh agent structure or NULL on error.
*/
struct ssh_agent_struct *agent_new(struct ssh_session_struct *session);
void agent_close(struct ssh_agent_struct *agent);
/**
* @brief Free an allocated ssh agent structure.
*
* @param agent The ssh agent structure to free.
*/
void agent_free(struct ssh_agent_struct *agent);
/**
* @brief Check if the ssh agent is running.
*
* @param session The ssh session to check for the agent.
*
* @return 1 if it is running, 0 if not.
*/
int agent_is_running(struct ssh_session_struct *session);
int agent_get_ident_count(struct ssh_session_struct *session);
struct ssh_public_key_struct *agent_get_next_ident(struct ssh_session_struct *session,
char **comment);
struct ssh_public_key_struct *agent_get_first_ident(struct ssh_session_struct *session,
char **comment);
ssh_string agent_sign_data(struct ssh_session_struct *session,
struct ssh_buffer_struct *data,
struct ssh_public_key_struct *pubkey);
#endif
#endif /* __AGENT_H */
/* vim: set ts=2 sw=2 et cindent: */
| erichuang1994/fbbs | include/libssh/agent.h | C | gpl-3.0 | 3,014 |
/*
Copyright 2013 Red Hat, Inc. and/or its affiliates.
This file is part of lightblue.
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 com.redhat.lightblue.config;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.redhat.lightblue.Request;
import com.redhat.lightblue.crud.DeleteRequest;
import com.redhat.lightblue.util.test.FileUtil;
import static com.redhat.lightblue.util.JsonUtils.json;
public class CrudValidationTest {
@Test
public void testValidInputWithNonValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, false);
String jsonString = FileUtil.readFile("valid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testInvalidInputWithNonValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, false);
String jsonString = FileUtil.readFile("invalid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testValidInputWithValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, true);
String jsonString = FileUtil.readFile("valid-deletion-req.json");
JsonNode node = json(jsonString);
DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.assertNotNull(req);
}
@Test
public void testInvalidInputWithValidating() throws Exception {
LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration());
// Emulate configuration
lbf.getJsonTranslator().setValidation(Request.class, true);
String jsonString = FileUtil.readFile("invalid-deletion-req.json");
JsonNode node = json(jsonString);
try {
lbf.getJsonTranslator().parse(DeleteRequest.class, node);
Assert.fail();
} catch (Exception e) {
System.out.println(e);
}
}
}
| bserdar/lightblue-core | config/src/test/java/com/redhat/lightblue/config/CrudValidationTest.java | Java | gpl-3.0 | 3,200 |
#pragma once
#include <WeaselIPC.h>
struct KeyInfo
{
UINT repeatCount: 16;
UINT scanCode: 8;
UINT isExtended: 1;
UINT reserved: 4;
UINT contextCode: 1;
UINT prevKeyState: 1;
UINT isKeyUp: 1;
KeyInfo(LPARAM lparam)
{
*this = *reinterpret_cast<KeyInfo*>(&lparam);
}
operator UINT32()
{
return *reinterpret_cast<UINT32*>(this);
}
};
bool ConvertKeyEvent(UINT vkey, KeyInfo kinfo, const LPBYTE keyState, weasel::KeyEvent& result);
namespace ibus
{
// keycodes
enum Keycode
{
VoidSymbol = 0xFFFFFF,
space = 0x020,
grave = 0x060,
BackSpace = 0xFF08,
Tab = 0xFF09,
Linefeed = 0xFF0A,
Clear = 0xFF0B,
Return = 0xFF0D,
Pause = 0xFF13,
Scroll_Lock = 0xFF14,
Sys_Req = 0xFF15,
Escape = 0xFF1B,
Delete = 0xFFFF,
Multi_key = 0xFF20,
Codeinput = 0xFF37,
SingleCandidate = 0xFF3C,
MultipleCandidate = 0xFF3D,
PreviousCandidate = 0xFF3E,
Kanji = 0xFF21,
Muhenkan = 0xFF22,
Henkan_Mode = 0xFF23,
Henkan = 0xFF23,
Romaji = 0xFF24,
Hiragana = 0xFF25,
Katakana = 0xFF26,
Hiragana_Katakana = 0xFF27,
Zenkaku = 0xFF28,
Hankaku = 0xFF29,
Zenkaku_Hankaku = 0xFF2A,
Touroku = 0xFF2B,
Massyo = 0xFF2C,
Kana_Lock = 0xFF2D,
Kana_Shift = 0xFF2E,
Eisu_Shift = 0xFF2F,
Eisu_toggle = 0xFF30,
Kanji_Bangou = 0xFF37,
Zen_Koho = 0xFF3D,
Mae_Koho = 0xFF3E,
Home = 0xFF50,
Left = 0xFF51,
Up = 0xFF52,
Right = 0xFF53,
Down = 0xFF54,
Prior = 0xFF55,
Page_Up = 0xFF55,
Next = 0xFF56,
Page_Down = 0xFF56,
End = 0xFF57,
Begin = 0xFF58,
Select = 0xFF60,
Print = 0xFF61,
Execute = 0xFF62,
Insert = 0xFF63,
Undo = 0xFF65,
Redo = 0xFF66,
Menu = 0xFF67,
Find = 0xFF68,
Cancel = 0xFF69,
Help = 0xFF6A,
Break = 0xFF6B,
Mode_switch = 0xFF7E,
script_switch = 0xFF7E,
Num_Lock = 0xFF7F,
KP_Space = 0xFF80,
KP_Tab = 0xFF89,
KP_Enter = 0xFF8D,
KP_F1 = 0xFF91,
KP_F2 = 0xFF92,
KP_F3 = 0xFF93,
KP_F4 = 0xFF94,
KP_Home = 0xFF95,
KP_Left = 0xFF96,
KP_Up = 0xFF97,
KP_Right = 0xFF98,
KP_Down = 0xFF99,
KP_Prior = 0xFF9A,
KP_Page_Up = 0xFF9A,
KP_Next = 0xFF9B,
KP_Page_Down = 0xFF9B,
KP_End = 0xFF9C,
KP_Begin = 0xFF9D,
KP_Insert = 0xFF9E,
KP_Delete = 0xFF9F,
KP_Equal = 0xFFBD,
KP_Multiply = 0xFFAA,
KP_Add = 0xFFAB,
KP_Separator = 0xFFAC,
KP_Subtract = 0xFFAD,
KP_Decimal = 0xFFAE,
KP_Divide = 0xFFAF,
KP_0 = 0xFFB0,
KP_1 = 0xFFB1,
KP_2 = 0xFFB2,
KP_3 = 0xFFB3,
KP_4 = 0xFFB4,
KP_5 = 0xFFB5,
KP_6 = 0xFFB6,
KP_7 = 0xFFB7,
KP_8 = 0xFFB8,
KP_9 = 0xFFB9,
F1 = 0xFFBE,
F2 = 0xFFBF,
F3 = 0xFFC0,
F4 = 0xFFC1,
F5 = 0xFFC2,
F6 = 0xFFC3,
F7 = 0xFFC4,
F8 = 0xFFC5,
F9 = 0xFFC6,
F10 = 0xFFC7,
F11 = 0xFFC8,
L1 = 0xFFC8,
F12 = 0xFFC9,
L2 = 0xFFC9,
F13 = 0xFFCA,
L3 = 0xFFCA,
F14 = 0xFFCB,
L4 = 0xFFCB,
F15 = 0xFFCC,
L5 = 0xFFCC,
F16 = 0xFFCD,
L6 = 0xFFCD,
F17 = 0xFFCE,
L7 = 0xFFCE,
F18 = 0xFFCF,
L8 = 0xFFCF,
F19 = 0xFFD0,
L9 = 0xFFD0,
F20 = 0xFFD1,
L10 = 0xFFD1,
F21 = 0xFFD2,
R1 = 0xFFD2,
F22 = 0xFFD3,
R2 = 0xFFD3,
F23 = 0xFFD4,
R3 = 0xFFD4,
F24 = 0xFFD5,
R4 = 0xFFD5,
F25 = 0xFFD6,
R5 = 0xFFD6,
F26 = 0xFFD7,
R6 = 0xFFD7,
F27 = 0xFFD8,
R7 = 0xFFD8,
F28 = 0xFFD9,
R8 = 0xFFD9,
F29 = 0xFFDA,
R9 = 0xFFDA,
F30 = 0xFFDB,
R10 = 0xFFDB,
F31 = 0xFFDC,
R11 = 0xFFDC,
F32 = 0xFFDD,
R12 = 0xFFDD,
F33 = 0xFFDE,
R13 = 0xFFDE,
F34 = 0xFFDF,
R14 = 0xFFDF,
F35 = 0xFFE0,
R15 = 0xFFE0,
Shift_L = 0xFFE1,
Shift_R = 0xFFE2,
Control_L = 0xFFE3,
Control_R = 0xFFE4,
Caps_Lock = 0xFFE5,
Shift_Lock = 0xFFE6,
Meta_L = 0xFFE7,
Meta_R = 0xFFE8,
Alt_L = 0xFFE9,
Alt_R = 0xFFEA,
Super_L = 0xFFEB,
Super_R = 0xFFEC,
Hyper_L = 0xFFED,
Hyper_R = 0xFFEE,
Null = 0
};
// modifiers, modified to fit a UINT16
enum Modifier
{
NULL_MASK = 0,
SHIFT_MASK = 1 << 0,
LOCK_MASK = 1 << 1,
CONTROL_MASK = 1 << 2,
ALT_MASK = 1 << 3,
MOD1_MASK = 1 << 3,
MOD2_MASK = 1 << 4,
MOD3_MASK = 1 << 5,
MOD4_MASK = 1 << 6,
MOD5_MASK = 1 << 7,
HANDLED_MASK = 1 << 8, // 24
IGNORED_MASK = 1 << 9, // 25
FORWARD_MASK = 1 << 9, // 25
SUPER_MASK = 1 << 10, // 26
HYPER_MASK = 1 << 11, // 27
META_MASK = 1 << 12, // 28
RELEASE_MASK = 1 << 14, // 30
MODIFIER_MASK = 0x2fff
};
}
| rime/weasel | WeaselIME/KeyEvent.h | C | gpl-3.0 | 4,532 |
/*
* Copyright (c) 2018 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* 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 org.obiba.mica.micaConfig.service;
import org.obiba.mica.micaConfig.domain.PopulationConfig;
import org.obiba.mica.micaConfig.repository.PopulationConfigRepository;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
@Component
public class PopulationConfigService extends EntityConfigService<PopulationConfig> {
@Inject
PopulationConfigRepository populationConfigRepository;
@Override
protected PopulationConfigRepository getRepository() {
return populationConfigRepository;
}
@Override
protected String getDefaultId() {
return "default";
}
@Override
protected PopulationConfig createEmptyForm() {
return new PopulationConfig();
}
@Override
protected String getDefaultDefinitionResourcePath() {
return "classpath:config/population-form/definition.json";
}
@Override
protected String getMandatoryDefinitionResourcePath() {
return "classpath:config/population-form/definition-mandatory.json";
}
@Override
protected String getDefaultSchemaResourcePath() {
return "classpath:config/population-form/schema.json";
}
@Override
protected String getMandatorySchemaResourcePath() {
return "classpath:config/population-form/schema-mandatory.json";
}
}
| obiba/mica2 | mica-core/src/main/java/org/obiba/mica/micaConfig/service/PopulationConfigService.java | Java | gpl-3.0 | 1,583 |
/*
* This file is part of the libsigrok project.
*
* Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
*
* 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; if not, see <http://www.gnu.org/licenses/>.
*/
/* Needed for POSIX.1-2008 locale functions */
/** @cond PRIVATE */
#define _XOPEN_SOURCE 700
/** @endcond */
#include <config.h>
#include <ctype.h>
#include <locale.h>
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <xlocale.h>
#endif
#if defined(__FreeBSD__)
#include <sys/param.h>
#endif
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <errno.h>
#include <libsigrok/libsigrok.h>
#include "libsigrok-internal.h"
/** @cond PRIVATE */
#define LOG_PREFIX "strutil"
/** @endcond */
/**
* @file
*
* Helper functions for handling or converting libsigrok-related strings.
*/
/**
* @defgroup grp_strutil String utilities
*
* Helper functions for handling or converting libsigrok-related strings.
*
* @{
*/
/**
* Convert a string representation of a numeric value (base 10) to a long integer. The
* conversion is strict and will fail if the complete string does not represent
* a valid long integer. The function sets errno according to the details of the
* failure.
*
* @param str The string representation to convert.
* @param ret Pointer to long where the result of the conversion will be stored.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Failure.
*
* @private
*/
SR_PRIV int sr_atol(const char *str, long *ret)
{
long tmp;
char *endptr = NULL;
errno = 0;
tmp = strtol(str, &endptr, 10);
while (endptr && isspace(*endptr))
endptr++;
if (!endptr || *endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
*ret = tmp;
return SR_OK;
}
/**
* Convert a text to a number including support for non-decimal bases.
* Also optionally returns the position after the number, where callers
* can either error out, or support application specific suffixes.
*
* @param[in] str The input text to convert.
* @param[out] ret The conversion result.
* @param[out] end The position after the number.
* @param[in] base The number format's base, can be 0.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Conversion failed.
*
* @private
*
* This routine is more general than @ref sr_atol(), which strictly
* expects the input text to contain just a decimal number, and nothing
* else in addition. The @ref sr_atol_base() routine accepts trailing
* text after the number, and supports non-decimal numbers (bin, hex),
* including automatic detection from prefix text.
*/
SR_PRIV int sr_atol_base(const char *str, long *ret, char **end, int base)
{
long num;
char *endptr;
/* Add "0b" prefix support which strtol(3) may be missing. */
while (str && isspace(*str))
str++;
if (!base && strncmp(str, "0b", strlen("0b")) == 0) {
str += strlen("0b");
base = 2;
}
/* Run the number conversion. Quick bail out if that fails. */
errno = 0;
endptr = NULL;
num = strtol(str, &endptr, base);
if (!endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
*ret = num;
/* Advance to optional non-space trailing suffix. */
while (endptr && isspace(*endptr))
endptr++;
if (end)
*end = endptr;
return SR_OK;
}
/**
* Convert a string representation of a numeric value (base 10) to an integer. The
* conversion is strict and will fail if the complete string does not represent
* a valid integer. The function sets errno according to the details of the
* failure.
*
* @param str The string representation to convert.
* @param ret Pointer to int where the result of the conversion will be stored.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Failure.
*
* @private
*/
SR_PRIV int sr_atoi(const char *str, int *ret)
{
long tmp;
if (sr_atol(str, &tmp) != SR_OK)
return SR_ERR;
if ((int) tmp != tmp) {
errno = ERANGE;
return SR_ERR;
}
*ret = (int) tmp;
return SR_OK;
}
/**
* Convert a string representation of a numeric value to a double. The
* conversion is strict and will fail if the complete string does not represent
* a valid double. The function sets errno according to the details of the
* failure.
*
* @param str The string representation to convert.
* @param ret Pointer to double where the result of the conversion will be stored.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Failure.
*
* @private
*/
SR_PRIV int sr_atod(const char *str, double *ret)
{
double tmp;
char *endptr = NULL;
errno = 0;
tmp = strtof(str, &endptr);
while (endptr && isspace(*endptr))
endptr++;
if (!endptr || *endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
*ret = tmp;
return SR_OK;
}
/**
* Convert a string representation of a numeric value to a float. The
* conversion is strict and will fail if the complete string does not represent
* a valid float. The function sets errno according to the details of the
* failure.
*
* @param str The string representation to convert.
* @param ret Pointer to float where the result of the conversion will be stored.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Failure.
*
* @private
*/
SR_PRIV int sr_atof(const char *str, float *ret)
{
double tmp;
if (sr_atod(str, &tmp) != SR_OK)
return SR_ERR;
if ((float) tmp != tmp) {
errno = ERANGE;
return SR_ERR;
}
*ret = (float) tmp;
return SR_OK;
}
/**
* Convert a string representation of a numeric value to a double. The
* conversion is strict and will fail if the complete string does not represent
* a valid double. The function sets errno according to the details of the
* failure. This version ignores the locale.
*
* @param str The string representation to convert.
* @param ret Pointer to double where the result of the conversion will be stored.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Failure.
*
* @private
*/
SR_PRIV int sr_atod_ascii(const char *str, double *ret)
{
double tmp;
char *endptr = NULL;
errno = 0;
tmp = g_ascii_strtod(str, &endptr);
if (!endptr || *endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
*ret = tmp;
return SR_OK;
}
/**
* Convert a string representation of a numeric value to a float. The
* conversion is strict and will fail if the complete string does not represent
* a valid float. The function sets errno according to the details of the
* failure. This version ignores the locale.
*
* @param str The string representation to convert.
* @param ret Pointer to float where the result of the conversion will be stored.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Failure.
*
* @private
*/
SR_PRIV int sr_atof_ascii(const char *str, float *ret)
{
double tmp;
char *endptr = NULL;
errno = 0;
tmp = g_ascii_strtod(str, &endptr);
if (!endptr || *endptr || errno) {
if (!errno)
errno = EINVAL;
return SR_ERR;
}
/* FIXME This fails unexpectedly. Some other method to safel downcast
* needs to be found. Checking against FLT_MAX doesn't work as well. */
/*
if ((float) tmp != tmp) {
errno = ERANGE;
sr_dbg("ERANGEEEE %e != %e", (float) tmp, tmp);
return SR_ERR;
}
*/
*ret = (float) tmp;
return SR_OK;
}
/**
* Compose a string with a format string in the buffer pointed to by buf.
*
* It is up to the caller to ensure that the allocated buffer is large enough
* to hold the formatted result.
*
* A terminating NUL character is automatically appended after the content
* written.
*
* After the format parameter, the function expects at least as many additional
* arguments as needed for format.
*
* This version ignores the current locale and uses the locale "C" for Linux,
* FreeBSD, OSX and Android.
*
* @param buf Pointer to a buffer where the resulting C string is stored.
* @param format C string that contains a format string (see printf).
* @param ... A sequence of additional arguments, each containing a value to be
* used to replace a format specifier in the format string.
*
* @return On success, the number of characters that would have been written,
* not counting the terminating NUL character.
*
* @since 0.6.0
*/
SR_API int sr_sprintf_ascii(char *buf, const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = sr_vsprintf_ascii(buf, format, args);
va_end(args);
return ret;
}
/**
* Compose a string with a format string in the buffer pointed to by buf.
*
* It is up to the caller to ensure that the allocated buffer is large enough
* to hold the formatted result.
*
* Internally, the function retrieves arguments from the list identified by
* args as if va_arg was used on it, and thus the state of args is likely to
* be altered by the call.
*
* In any case, args should have been initialized by va_start at some point
* before the call, and it is expected to be released by va_end at some point
* after the call.
*
* This version ignores the current locale and uses the locale "C" for Linux,
* FreeBSD, OSX and Android.
*
* @param buf Pointer to a buffer where the resulting C string is stored.
* @param format C string that contains a format string (see printf).
* @param args A value identifying a variable arguments list initialized with
* va_start.
*
* @return On success, the number of characters that would have been written,
* not counting the terminating NUL character.
*
* @since 0.6.0
*/
SR_API int sr_vsprintf_ascii(char *buf, const char *format, va_list args)
{
#if defined(_WIN32)
int ret;
#if 0
/*
* TODO: This part compiles with mingw-w64 but doesn't run with Win7.
* Doesn't start because of "Procedure entry point _create_locale
* not found in msvcrt.dll".
* mingw-w64 should link to msvcr100.dll not msvcrt.dll!
* See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx
*/
_locale_t locale;
locale = _create_locale(LC_NUMERIC, "C");
ret = _vsprintf_l(buf, format, locale, args);
_free_locale(locale);
#endif
/* vsprintf() uses the current locale, may not work correctly for floats. */
ret = vsprintf(buf, format, args);
return ret;
#elif defined(__APPLE__)
/*
* See:
* https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html
* https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html
*/
int ret;
locale_t locale;
locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
ret = vsprintf_l(buf, locale, format, args);
freelocale(locale);
return ret;
#elif defined(__FreeBSD__) && __FreeBSD_version >= 901000
/*
* See:
* https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
* https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
*/
int ret;
locale_t locale;
locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
ret = vsprintf_l(buf, locale, format, args);
freelocale(locale);
return ret;
#elif defined(__ANDROID__)
/*
* The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8"
* aka "en_US.UTF-8"). The decimal point is hard coded as "."
* See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp
*/
int ret;
ret = vsprintf(buf, format, args);
return ret;
#elif defined(__linux__)
int ret;
locale_t old_locale, temp_locale;
/* Switch to C locale for proper float/double conversion. */
temp_locale = newlocale(LC_NUMERIC, "C", NULL);
old_locale = uselocale(temp_locale);
ret = vsprintf(buf, format, args);
/* Switch back to original locale. */
uselocale(old_locale);
freelocale(temp_locale);
return ret;
#elif defined(__unix__) || defined(__unix)
/*
* This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by
* using the current locale for snprintf(). This may not work correctly
* for floats!
*/
int ret;
ret = vsprintf(buf, format, args);
return ret;
#else
/* No implementation for unknown systems! */
return -1;
#endif
}
/**
* Composes a string with a format string (like printf) in the buffer pointed
* by buf (taking buf_size as the maximum buffer capacity to fill).
* If the resulting string would be longer than n - 1 characters, the remaining
* characters are discarded and not stored, but counted for the value returned
* by the function.
* A terminating NUL character is automatically appended after the content
* written.
* After the format parameter, the function expects at least as many additional
* arguments as needed for format.
*
* This version ignores the current locale and uses the locale "C" for Linux,
* FreeBSD, OSX and Android.
*
* @param buf Pointer to a buffer where the resulting C string is stored.
* @param buf_size Maximum number of bytes to be used in the buffer. The
* generated string has a length of at most buf_size - 1, leaving space
* for the additional terminating NUL character.
* @param format C string that contains a format string (see printf).
* @param ... A sequence of additional arguments, each containing a value to be
* used to replace a format specifier in the format string.
*
* @return On success, the number of characters that would have been written if
* buf_size had been sufficiently large, not counting the terminating
* NUL character. On failure, a negative number is returned.
* Notice that only when this returned value is non-negative and less
* than buf_size, the string has been completely written.
*
* @since 0.6.0
*/
SR_API int sr_snprintf_ascii(char *buf, size_t buf_size,
const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = sr_vsnprintf_ascii(buf, buf_size, format, args);
va_end(args);
return ret;
}
/**
* Composes a string with a format string (like printf) in the buffer pointed
* by buf (taking buf_size as the maximum buffer capacity to fill).
* If the resulting string would be longer than n - 1 characters, the remaining
* characters are discarded and not stored, but counted for the value returned
* by the function.
* A terminating NUL character is automatically appended after the content
* written.
* Internally, the function retrieves arguments from the list identified by
* args as if va_arg was used on it, and thus the state of args is likely to
* be altered by the call.
* In any case, arg should have been initialized by va_start at some point
* before the call, and it is expected to be released by va_end at some point
* after the call.
*
* This version ignores the current locale and uses the locale "C" for Linux,
* FreeBSD, OSX and Android.
*
* @param buf Pointer to a buffer where the resulting C string is stored.
* @param buf_size Maximum number of bytes to be used in the buffer. The
* generated string has a length of at most buf_size - 1, leaving space
* for the additional terminating NUL character.
* @param format C string that contains a format string (see printf).
* @param args A value identifying a variable arguments list initialized with
* va_start.
*
* @return On success, the number of characters that would have been written if
* buf_size had been sufficiently large, not counting the terminating
* NUL character. On failure, a negative number is returned.
* Notice that only when this returned value is non-negative and less
* than buf_size, the string has been completely written.
*
* @since 0.6.0
*/
SR_API int sr_vsnprintf_ascii(char *buf, size_t buf_size,
const char *format, va_list args)
{
#if defined(_WIN32)
int ret;
#if 0
/*
* TODO: This part compiles with mingw-w64 but doesn't run with Win7.
* Doesn't start because of "Procedure entry point _create_locale
* not found in msvcrt.dll".
* mingw-w64 should link to msvcr100.dll not msvcrt.dll!.
* See: https://msdn.microsoft.com/en-us/en-en/library/1kt27hek.aspx
*/
_locale_t locale;
locale = _create_locale(LC_NUMERIC, "C");
ret = _vsnprintf_l(buf, buf_size, format, locale, args);
_free_locale(locale);
#endif
/* vsprintf uses the current locale, may cause issues for floats. */
ret = vsnprintf(buf, buf_size, format, args);
return ret;
#elif defined(__APPLE__)
/*
* See:
* https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/printf_l.3.html
* https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/xlocale.3.html
*/
int ret;
locale_t locale;
locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
ret = vsnprintf_l(buf, buf_size, locale, format, args);
freelocale(locale);
return ret;
#elif defined(__FreeBSD__) && __FreeBSD_version >= 901000
/*
* See:
* https://www.freebsd.org/cgi/man.cgi?query=printf_l&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
* https://www.freebsd.org/cgi/man.cgi?query=xlocale&apropos=0&sektion=3&manpath=FreeBSD+9.1-RELEASE
*/
int ret;
locale_t locale;
locale = newlocale(LC_NUMERIC_MASK, "C", NULL);
ret = vsnprintf_l(buf, buf_size, locale, format, args);
freelocale(locale);
return ret;
#elif defined(__ANDROID__)
/*
* The Bionic libc only has two locales ("C" aka "POSIX" and "C.UTF-8"
* aka "en_US.UTF-8"). The decimal point is hard coded as ".".
* See: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/locale.cpp
*/
int ret;
ret = vsnprintf(buf, buf_size, format, args);
return ret;
#elif defined(__linux__)
int ret;
locale_t old_locale, temp_locale;
/* Switch to C locale for proper float/double conversion. */
temp_locale = newlocale(LC_NUMERIC, "C", NULL);
old_locale = uselocale(temp_locale);
ret = vsnprintf(buf, buf_size, format, args);
/* Switch back to original locale. */
uselocale(old_locale);
freelocale(temp_locale);
return ret;
#elif defined(__unix__) || defined(__unix)
/*
* This is a fallback for all other BSDs, *nix and FreeBSD <= 9.0, by
* using the current locale for snprintf(). This may not work correctly
* for floats!
*/
int ret;
ret = vsnprintf(buf, buf_size, format, args);
return ret;
#else
/* No implementation for unknown systems! */
return -1;
#endif
}
/**
* Convert a sequence of bytes to its textual representation ("hex dump").
*
* Callers should free the allocated GString. See sr_hexdump_free().
*
* @param[in] data Pointer to the byte sequence to print.
* @param[in] len Number of bytes to print.
*
* @return NULL upon error, newly allocated GString pointer otherwise.
*
* @private
*/
SR_PRIV GString *sr_hexdump_new(const uint8_t *data, const size_t len)
{
GString *s;
size_t i;
s = g_string_sized_new(3 * len);
for (i = 0; i < len; i++) {
if (i)
g_string_append_c(s, ' ');
g_string_append_printf(s, "%02x", data[i]);
}
return s;
}
/**
* Free a hex dump text that was created by sr_hexdump_new().
*
* @param[in] s Pointer to the GString to release.
*
* @private
*/
SR_PRIV void sr_hexdump_free(GString *s)
{
if (s)
g_string_free(s, TRUE);
}
/**
* Convert a string representation of a numeric value to a sr_rational.
*
* The conversion is strict and will fail if the complete string does not
* represent a valid number. The function sets errno according to the details
* of the failure. This version ignores the locale.
*
* @param str The string representation to convert.
* @param ret Pointer to sr_rational where the result of the conversion will be stored.
*
* @retval SR_OK Conversion successful.
* @retval SR_ERR Failure.
*
* @since 0.5.0
*/
SR_API int sr_parse_rational(const char *str, struct sr_rational *ret)
{
char *endptr = NULL;
int64_t integral;
int64_t fractional = 0;
int64_t denominator = 1;
int32_t fractional_len = 0;
int32_t exponent = 0;
gboolean is_negative = FALSE;
gboolean no_integer, no_fractional;
while (isspace(*str))
str++;
errno = 0;
integral = g_ascii_strtoll(str, &endptr, 10);
if (str == endptr && (str[0] == '-' || str[0] == '+') && str[1] == '.') {
endptr += 1;
no_integer = TRUE;
} else if (str == endptr && str[0] == '.') {
no_integer = TRUE;
} else if (errno) {
return SR_ERR;
} else {
no_integer = FALSE;
}
if (integral < 0 || str[0] == '-')
is_negative = TRUE;
errno = 0;
if (*endptr == '.') {
gboolean is_exp, is_eos;
const char *start = endptr + 1;
fractional = g_ascii_strtoll(start, &endptr, 10);
is_exp = *endptr == 'E' || *endptr == 'e';
is_eos = *endptr == '\0';
if (endptr == start && (is_exp || is_eos)) {
fractional = 0;
errno = 0;
}
if (errno)
return SR_ERR;
no_fractional = endptr == start;
if (no_integer && no_fractional)
return SR_ERR;
fractional_len = endptr - start;
}
errno = 0;
if ((*endptr == 'E') || (*endptr == 'e')) {
exponent = g_ascii_strtoll(endptr + 1, &endptr, 10);
if (errno)
return SR_ERR;
}
if (*endptr != '\0')
return SR_ERR;
for (int i = 0; i < fractional_len; i++)
integral *= 10;
exponent -= fractional_len;
if (!is_negative)
integral += fractional;
else
integral -= fractional;
while (exponent > 0) {
integral *= 10;
exponent--;
}
while (exponent < 0) {
denominator *= 10;
exponent++;
}
ret->p = integral;
ret->q = denominator;
return SR_OK;
}
/**
* Convert a numeric value value to its "natural" string representation
* in SI units.
*
* E.g. a value of 3000000, with units set to "W", would be converted
* to "3 MW", 20000 to "20 kW", 31500 would become "31.5 kW".
*
* @param x The value to convert.
* @param unit The unit to append to the string, or NULL if the string
* has no units.
*
* @return A newly allocated string representation of the samplerate value,
* or NULL upon errors. The caller is responsible to g_free() the
* memory.
*
* @since 0.2.0
*/
SR_API char *sr_si_string_u64(uint64_t x, const char *unit)
{
uint8_t i;
uint64_t quot, divisor[] = {
SR_HZ(1), SR_KHZ(1), SR_MHZ(1), SR_GHZ(1),
SR_GHZ(1000), SR_GHZ(1000 * 1000), SR_GHZ(1000 * 1000 * 1000),
};
const char *p, prefix[] = "\0kMGTPE";
char fmt[16], fract[20] = "", *f;
if (!unit)
unit = "";
for (i = 0; (quot = x / divisor[i]) >= 1000; i++);
if (i) {
sprintf(fmt, ".%%0%d"PRIu64, i * 3);
f = fract + sprintf(fract, fmt, x % divisor[i]) - 1;
while (f >= fract && strchr("0.", *f))
*f-- = 0;
}
p = prefix + i;
return g_strdup_printf("%" PRIu64 "%s %.1s%s", quot, fract, p, unit);
}
/**
* Convert a numeric samplerate value to its "natural" string representation.
*
* E.g. a value of 3000000 would be converted to "3 MHz", 20000 to "20 kHz",
* 31500 would become "31.5 kHz".
*
* @param samplerate The samplerate in Hz.
*
* @return A newly allocated string representation of the samplerate value,
* or NULL upon errors. The caller is responsible to g_free() the
* memory.
*
* @since 0.1.0
*/
SR_API char *sr_samplerate_string(uint64_t samplerate)
{
return sr_si_string_u64(samplerate, "Hz");
}
/**
* Convert a numeric period value to the "natural" string representation
* of its period value.
*
* The period is specified as a rational number's numerator and denominator.
*
* E.g. a pair of (1, 5) would be converted to "200 ms", (10, 100) to "100 ms".
*
* @param v_p The period numerator.
* @param v_q The period denominator.
*
* @return A newly allocated string representation of the period value,
* or NULL upon errors. The caller is responsible to g_free() the
* memory.
*
* @since 0.5.0
*/
SR_API char *sr_period_string(uint64_t v_p, uint64_t v_q)
{
double freq, v;
int prec;
freq = 1 / ((double)v_p / v_q);
if (freq > SR_GHZ(1)) {
v = (double)v_p / v_q * 1000000000000.0;
prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
return g_strdup_printf("%.*f ps", prec, v);
} else if (freq > SR_MHZ(1)) {
v = (double)v_p / v_q * 1000000000.0;
prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
return g_strdup_printf("%.*f ns", prec, v);
} else if (freq > SR_KHZ(1)) {
v = (double)v_p / v_q * 1000000.0;
prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
return g_strdup_printf("%.*f us", prec, v);
} else if (freq > 1) {
v = (double)v_p / v_q * 1000.0;
prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
return g_strdup_printf("%.*f ms", prec, v);
} else {
v = (double)v_p / v_q;
prec = ((v - (uint64_t)v) < FLT_MIN) ? 0 : 3;
return g_strdup_printf("%.*f s", prec, v);
}
}
/**
* Convert a numeric voltage value to the "natural" string representation
* of its voltage value. The voltage is specified as a rational number's
* numerator and denominator.
*
* E.g. a value of 300000 would be converted to "300mV", 2 to "2V".
*
* @param v_p The voltage numerator.
* @param v_q The voltage denominator.
*
* @return A newly allocated string representation of the voltage value,
* or NULL upon errors. The caller is responsible to g_free() the
* memory.
*
* @since 0.2.0
*/
SR_API char *sr_voltage_string(uint64_t v_p, uint64_t v_q)
{
if (v_q == 1000)
return g_strdup_printf("%" PRIu64 " mV", v_p);
else if (v_q == 1)
return g_strdup_printf("%" PRIu64 " V", v_p);
else
return g_strdup_printf("%g V", (float)v_p / (float)v_q);
}
/**
* Convert a "natural" string representation of a size value to uint64_t.
*
* E.g. a value of "3k" or "3 K" would be converted to 3000, a value
* of "15M" would be converted to 15000000.
*
* Value representations other than decimal (such as hex or octal) are not
* supported. Only 'k' (kilo), 'm' (mega), 'g' (giga) suffixes are supported.
* Spaces (but not other whitespace) between value and suffix are allowed.
*
* @param sizestring A string containing a (decimal) size value.
* @param size Pointer to uint64_t which will contain the string's size value.
*
* @return SR_OK upon success, SR_ERR upon errors.
*
* @since 0.1.0
*/
SR_API int sr_parse_sizestring(const char *sizestring, uint64_t *size)
{
uint64_t multiplier;
int done;
double frac_part;
char *s;
*size = strtoull(sizestring, &s, 10);
multiplier = 0;
frac_part = 0;
done = FALSE;
while (s && *s && multiplier == 0 && !done) {
switch (*s) {
case ' ':
break;
case '.':
frac_part = g_ascii_strtod(s, &s);
break;
case 'k':
case 'K':
multiplier = SR_KHZ(1);
break;
case 'm':
case 'M':
multiplier = SR_MHZ(1);
break;
case 'g':
case 'G':
multiplier = SR_GHZ(1);
break;
case 't':
case 'T':
multiplier = SR_GHZ(1000);
break;
case 'p':
case 'P':
multiplier = SR_GHZ(1000 * 1000);
break;
case 'e':
case 'E':
multiplier = SR_GHZ(1000 * 1000 * 1000);
break;
default:
done = TRUE;
s--;
}
s++;
}
if (multiplier > 0) {
*size *= multiplier;
*size += frac_part * multiplier;
} else {
*size += frac_part;
}
if (s && *s && g_ascii_strcasecmp(s, "Hz"))
return SR_ERR;
return SR_OK;
}
/**
* Convert a "natural" string representation of a time value to an
* uint64_t value in milliseconds.
*
* E.g. a value of "3s" or "3 s" would be converted to 3000, a value
* of "15ms" would be converted to 15.
*
* Value representations other than decimal (such as hex or octal) are not
* supported. Only lower-case "s" and "ms" time suffixes are supported.
* Spaces (but not other whitespace) between value and suffix are allowed.
*
* @param timestring A string containing a (decimal) time value.
* @return The string's time value as uint64_t, in milliseconds.
*
* @todo Add support for "m" (minutes) and others.
* @todo Add support for picoseconds?
* @todo Allow both lower-case and upper-case? If no, document it.
*
* @since 0.1.0
*/
SR_API uint64_t sr_parse_timestring(const char *timestring)
{
uint64_t time_msec;
char *s;
/* TODO: Error handling, logging. */
time_msec = strtoull(timestring, &s, 10);
if (time_msec == 0 && s == timestring)
return 0;
if (s && *s) {
while (*s == ' ')
s++;
if (!strcmp(s, "s"))
time_msec *= 1000;
else if (!strcmp(s, "ms"))
; /* redundant */
else
return 0;
}
return time_msec;
}
/** @since 0.1.0 */
SR_API gboolean sr_parse_boolstring(const char *boolstr)
{
/*
* Complete absence of an input spec is assumed to mean TRUE,
* as in command line option strings like this:
* ...:samplerate=100k:header:numchannels=4:...
*/
if (!boolstr || !*boolstr)
return TRUE;
if (!g_ascii_strncasecmp(boolstr, "true", 4) ||
!g_ascii_strncasecmp(boolstr, "yes", 3) ||
!g_ascii_strncasecmp(boolstr, "on", 2) ||
!g_ascii_strncasecmp(boolstr, "1", 1))
return TRUE;
return FALSE;
}
/** @since 0.2.0 */
SR_API int sr_parse_period(const char *periodstr, uint64_t *p, uint64_t *q)
{
char *s;
*p = strtoull(periodstr, &s, 10);
if (*p == 0 && s == periodstr)
/* No digits found. */
return SR_ERR_ARG;
if (s && *s) {
while (*s == ' ')
s++;
if (!strcmp(s, "fs"))
*q = UINT64_C(1000000000000000);
else if (!strcmp(s, "ps"))
*q = UINT64_C(1000000000000);
else if (!strcmp(s, "ns"))
*q = UINT64_C(1000000000);
else if (!strcmp(s, "us"))
*q = 1000000;
else if (!strcmp(s, "ms"))
*q = 1000;
else if (!strcmp(s, "s"))
*q = 1;
else
/* Must have a time suffix. */
return SR_ERR_ARG;
}
return SR_OK;
}
/** @since 0.2.0 */
SR_API int sr_parse_voltage(const char *voltstr, uint64_t *p, uint64_t *q)
{
char *s;
*p = strtoull(voltstr, &s, 10);
if (*p == 0 && s == voltstr)
/* No digits found. */
return SR_ERR_ARG;
if (s && *s) {
while (*s == ' ')
s++;
if (!g_ascii_strcasecmp(s, "mv"))
*q = 1000L;
else if (!g_ascii_strcasecmp(s, "v"))
*q = 1;
else
/* Must have a base suffix. */
return SR_ERR_ARG;
}
return SR_OK;
}
/** @} */
| uwehermann/libsigrok | src/strutil.c | C | gpl-3.0 | 30,226 |
/*
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/>.
*/
/*
control code for tailsitters. Enabled by setting Q_FRAME_CLASS=10
*/
#include "Plane.h"
/*
return true when flying a tailsitter
*/
bool QuadPlane::is_tailsitter(void)
{
return available() && frame_class == AP_Motors::MOTOR_FRAME_TAILSITTER;
}
/*
check if we are flying as a tailsitter
*/
bool QuadPlane::tailsitter_active(void)
{
return is_tailsitter() && in_vtol_mode();
}
/*
run output for tailsitters
*/
void QuadPlane::tailsitter_output(void)
{
if (!is_tailsitter()) {
return;
}
if (!tailsitter_active()) {
if (tailsitter.vectored_forward_gain > 0) {
// thrust vectoring in fixed wing flight
float aileron = SRV_Channels::get_output_scaled(SRV_Channel::k_aileron);
float elevator = SRV_Channels::get_output_scaled(SRV_Channel::k_elevator);
float tilt_left = (elevator + aileron) * tailsitter.vectored_forward_gain;
float tilt_right = (elevator - aileron) * tailsitter.vectored_forward_gain;
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, tilt_left);
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, tilt_right);
} else {
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, 0);
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, 0);
}
return;
}
motors_output();
plane.pitchController.reset_I();
plane.rollController.reset_I();
if (tailsitter.vectored_hover_gain > 0) {
// thrust vectoring VTOL modes
float aileron = SRV_Channels::get_output_scaled(SRV_Channel::k_aileron);
float elevator = SRV_Channels::get_output_scaled(SRV_Channel::k_elevator);
float tilt_left = (elevator + aileron) * tailsitter.vectored_hover_gain;
float tilt_right = (elevator - aileron) * tailsitter.vectored_hover_gain;
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorLeft, tilt_left);
SRV_Channels::set_output_scaled(SRV_Channel::k_tiltMotorRight, tilt_right);
}
if (tailsitter.input_mask_chan > 0 &&
tailsitter.input_mask > 0 &&
hal.rcin->read(tailsitter.input_mask_chan-1) > 1700) {
// the user is learning to prop-hang
if (tailsitter.input_mask & TAILSITTER_MASK_AILERON) {
SRV_Channels::set_output_scaled(SRV_Channel::k_aileron, plane.channel_roll->get_control_in_zero_dz());
}
if (tailsitter.input_mask & TAILSITTER_MASK_ELEVATOR) {
SRV_Channels::set_output_scaled(SRV_Channel::k_elevator, plane.channel_pitch->get_control_in_zero_dz());
}
if (tailsitter.input_mask & TAILSITTER_MASK_THROTTLE) {
SRV_Channels::set_output_scaled(SRV_Channel::k_throttle, plane.channel_throttle->get_control_in_zero_dz());
}
if (tailsitter.input_mask & TAILSITTER_MASK_RUDDER) {
SRV_Channels::set_output_scaled(SRV_Channel::k_rudder, plane.channel_rudder->get_control_in_zero_dz());
}
}
}
/*
return true when we have completed enough of a transition to switch to fixed wing control
*/
bool QuadPlane::tailsitter_transition_complete(void)
{
if (plane.fly_inverted()) {
// transition immediately
return true;
}
if (labs(ahrs_view->pitch_sensor) > tailsitter.transition_angle*100 ||
labs(ahrs_view->roll_sensor) > tailsitter.transition_angle*100 ||
AP_HAL::millis() - transition_start_ms > 2000) {
return true;
}
// still waiting
return false;
}
// handle different tailsitter input types
void QuadPlane::tailsitter_check_input(void)
{
if (tailsitter_active() &&
tailsitter.input_type == TAILSITTER_INPUT_PLANE) {
// the user has asked for body frame controls when tailsitter
// is active. We switch around the control_in value for the
// channels to do this, as that ensures the value is
// consistent throughout the code
int16_t roll_in = plane.channel_roll->get_control_in();
int16_t yaw_in = plane.channel_rudder->get_control_in();
plane.channel_roll->set_control_in(yaw_in);
plane.channel_rudder->set_control_in(-roll_in);
}
}
| ChristopherOlson/ArduHeli | ArduPlane/tailsitter.cpp | C++ | gpl-3.0 | 4,878 |
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
#include "HeadSpin.h"
#include "plComponent.h"
#include "plComponentReg.h"
#include "plMiscComponents.h"
#include "MaxMain/plMaxNode.h"
#include "resource.h"
#include <iparamm2.h>
#pragma hdrstop
#include "MaxMain/plPlasmaRefMsgs.h"
#include "pnSceneObject/plSceneObject.h"
#include "pnSceneObject/plCoordinateInterface.h"
#include "pnSceneObject/plDrawInterface.h"
#include "plMessage/plSimStateMsg.h"
#include "pnMessage/plEnableMsg.h"
#include "MaxMain/plPluginResManager.h"
void DummyCodeIncludeFuncIgnore() {}
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Ignore Component
//
//
//Class that accesses the paramblock below.
class plIgnoreComponent : public plComponent
{
public:
plIgnoreComponent();
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg);
bool Convert(plMaxNode *node, plErrorMsg *pErrMsg);
virtual void CollectNonDrawables(INodeTab& nonDrawables);
};
//Max desc stuff necessary below.
CLASS_DESC(plIgnoreComponent, gIgnoreDesc, "Ignore", "Ignore", COMP_TYPE_IGNORE, Class_ID(0x48326288, 0x528a3dea))
enum
{
kIgnoreMeCheckBx
};
ParamBlockDesc2 gIgnoreBk
(
plComponent::kBlkComp, _T("Ignore"), 0, &gIgnoreDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp,
IDD_COMP_IGNORE, IDS_COMP_IGNORES, 0, 0, NULL,
kIgnoreMeCheckBx, _T("Ignore"), TYPE_BOOL, 0, 0,
p_default, TRUE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_IGNORE_CKBX,
end,
end
);
plIgnoreComponent::plIgnoreComponent()
{
fClassDesc = &gIgnoreDesc;
fClassDesc->MakeAutoParamBlocks(this);
}
void plIgnoreComponent::CollectNonDrawables(INodeTab& nonDrawables)
{
if (fCompPB->GetInt(kIgnoreMeCheckBx))
{
AddTargetsToList(nonDrawables);
}
}
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool plIgnoreComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg)
{
if (fCompPB->GetInt(kIgnoreMeCheckBx))
pNode->SetCanConvert(false);
return true;
}
bool plIgnoreComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg)
{
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// IgnoreLite Component
//
//
//Class that accesses the paramblock below.
class plIgnoreLiteComponent : public plComponent
{
public:
enum {
kSelectedOnly
};
enum LightState {
kTurnOn,
kTurnOff,
kToggle
};
public:
plIgnoreLiteComponent();
void SetState(LightState s);
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg) { return true; }
bool PreConvert(plMaxNode *pNode, plErrorMsg *pErrMsg) { return true; }
bool Convert(plMaxNode *node, plErrorMsg *pErrMsg) { return true; }
};
class plIgnoreLiteProc : public ParamMap2UserDlgProc
{
public:
BOOL DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_COMMAND:
if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_ON) )
{
plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner();
ilc->SetState(plIgnoreLiteComponent::kTurnOn);
return TRUE;
}
if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_OFF) )
{
plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner();
ilc->SetState(plIgnoreLiteComponent::kTurnOff);
return TRUE;
}
if( (HIWORD(wParam) == BN_CLICKED) && (LOWORD(wParam) == IDC_COMP_IGNORELITE_TOGGLE) )
{
plIgnoreLiteComponent* ilc = (plIgnoreLiteComponent*)map->GetParamBlock()->GetOwner();
ilc->SetState(plIgnoreLiteComponent::kToggle);
return TRUE;
}
break;
}
return false;
}
void DeleteThis() {}
};
static plIgnoreLiteProc gIgnoreLiteProc;
//Max desc stuff necessary below.
CLASS_DESC(plIgnoreLiteComponent, gIgnoreLiteDesc, "Control Max Light", "ControlLite", COMP_TYPE_IGNORE, IGNORELITE_CID)
ParamBlockDesc2 gIgnoreLiteBk
(
plComponent::kBlkComp, _T("IgnoreLite"), 0, &gIgnoreLiteDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp,
IDD_COMP_IGNORELITE, IDS_COMP_IGNORELITES, 0, 0, &gIgnoreLiteProc,
plIgnoreLiteComponent::kSelectedOnly, _T("SelectedOnly"), TYPE_BOOL, 0, 0,
p_default, FALSE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_IGNORELITE_SELECTED,
end,
end
);
plIgnoreLiteComponent::plIgnoreLiteComponent()
{
fClassDesc = &gIgnoreLiteDesc;
fClassDesc->MakeAutoParamBlocks(this);
}
void plIgnoreLiteComponent::SetState(LightState s)
{
BOOL selectedOnly = fCompPB->GetInt(kSelectedOnly);
int numTarg = NumTargets();
int i;
for( i = 0; i < numTarg; i++ )
{
plMaxNodeBase* targ = GetTarget(i);
if( targ )
{
if( selectedOnly && !targ->Selected() )
continue;
Object *obj = targ->EvalWorldState(TimeValue(0)).obj;
if (obj && (obj->SuperClassID() == SClass_ID(LIGHT_CLASS_ID)))
{
LightObject* liObj = (LightObject*)obj;
switch( s )
{
case kTurnOn:
liObj->SetUseLight(true);
break;
case kTurnOff:
liObj->SetUseLight(false);
break;
case kToggle:
liObj->SetUseLight(!liObj->GetUseLight());
break;
}
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Barney Component
//
//
//Class that accesses the paramblock below.
class plBarneyComponent : public plComponent
{
public:
plBarneyComponent();
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg);
bool Convert(plMaxNode *node, plErrorMsg *pErrMsg);
};
//Max desc stuff necessary below.
CLASS_DESC(plBarneyComponent, gBarneyDesc, "Barney", "Barney", COMP_TYPE_IGNORE, Class_ID(0x376955dc, 0x2fec50ae))
ParamBlockDesc2 gBarneyBk
(
plComponent::kBlkComp, _T("Barney"), 0, &gBarneyDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp,
IDD_COMP_BARNEY, IDS_COMP_BARNEYS, 0, 0, NULL,
end
);
plBarneyComponent::plBarneyComponent()
{
fClassDesc = &gBarneyDesc;
fClassDesc->MakeAutoParamBlocks(this);
}
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool plBarneyComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg)
{
pNode->SetCanConvert(false);
pNode->SetIsBarney(true);
return true;
}
bool plBarneyComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg)
{
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// NoShow Component
//
//
//Class that accesses the paramblock below.
class plNoShowComponent : public plComponent
{
public:
enum
{
kShowable,
kAffectDraw,
kAffectPhys
};
public:
plNoShowComponent();
virtual void CollectNonDrawables(INodeTab& nonDrawables);
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg);
bool Convert(plMaxNode *node, plErrorMsg *pErrMsg);
};
const Class_ID COMP_NOSHOW_CID(0x41cb2b85, 0x615932c6);
//Max desc stuff necessary below.
CLASS_DESC(plNoShowComponent, gNoShowDesc, "NoShow", "NoShow", COMP_TYPE_IGNORE, COMP_NOSHOW_CID)
ParamBlockDesc2 gNoShowBk
(
plComponent::kBlkComp, _T("NoShow"), 0, &gNoShowDesc, P_AUTO_CONSTRUCT + P_AUTO_UI, plComponent::kRefComp,
IDD_COMP_NOSHOW, IDS_COMP_NOSHOW, 0, 0, NULL,
plNoShowComponent::kShowable, _T("Showable"), TYPE_BOOL, 0, 0,
p_default, FALSE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_SHOWABLE,
end,
plNoShowComponent::kAffectDraw, _T("AffectDraw"), TYPE_BOOL, 0, 0,
p_default, TRUE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_AFFECTDRAW,
end,
plNoShowComponent::kAffectPhys, _T("AffectPhys"), TYPE_BOOL, 0, 0,
p_default, FALSE,
p_ui, TYPE_SINGLECHEKBOX, IDC_COMP_NOSHOW_AFFECTPHYS,
end,
end
);
plNoShowComponent::plNoShowComponent()
{
fClassDesc = &gNoShowDesc;
fClassDesc->MakeAutoParamBlocks(this);
}
// SetupProperties - Internal setup and write-only set properties on the MaxNode. No reading
// of properties on the MaxNode, as it's still indeterminant.
bool plNoShowComponent::SetupProperties(plMaxNode *pNode, plErrorMsg *pErrMsg)
{
if( !fCompPB->GetInt(kShowable) )
{
if( fCompPB->GetInt(kAffectDraw) )
pNode->SetDrawable(false);
if( fCompPB->GetInt(kAffectPhys) )
pNode->SetPhysical(false);
}
return true;
}
bool plNoShowComponent::Convert(plMaxNode *node, plErrorMsg *pErrMsg)
{
plSceneObject* obj = node->GetSceneObject();
if( !obj )
return true;
if( fCompPB->GetInt(kShowable) )
{
if( fCompPB->GetInt(kAffectDraw) )
{
plEnableMsg* eMsg = new plEnableMsg(nil, plEnableMsg::kDisable, plEnableMsg::kDrawable);
eMsg->AddReceiver(obj->GetKey());
eMsg->Send();
}
if( fCompPB->GetInt(kAffectPhys) )
{
hsAssert(0, "Who uses this?");
// plEventGroupEnableMsg* pMsg = new plEventGroupEnableMsg;
// pMsg->SetFlags(plEventGroupEnableMsg::kCollideOff | plEventGroupEnableMsg::kReportOff);
// pMsg->AddReceiver(obj->GetKey());
// pMsg->Send();
}
#if 0
plDrawInterface* di = node->GetDrawInterface();
if( di &&
{
di->SetProperty(plDrawInterface::kDisable, true);
}
#endif
}
return true;
}
void plNoShowComponent::CollectNonDrawables(INodeTab& nonDrawables)
{
if( fCompPB->GetInt(kAffectDraw) )
AddTargetsToList(nonDrawables);
}
| Lyrositor/Plasma | Sources/Tools/MaxComponent/plIgnoreComponent.cpp | C++ | gpl-3.0 | 12,779 |
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "branchmodel.h"
#include "gitclient.h"
#include <utils/qtcassert.h>
#include <vcsbase/vcsoutputwindow.h>
#include <vcsbase/vcscommand.h>
#include <QFont>
using namespace VcsBase;
namespace Git {
namespace Internal {
enum RootNodes {
LocalBranches = 0,
RemoteBranches = 1,
Tags = 2
};
// --------------------------------------------------------------------------
// BranchNode:
// --------------------------------------------------------------------------
class BranchNode
{
public:
BranchNode() :
parent(0),
name(QLatin1String("<ROOT>"))
{ }
BranchNode(const QString &n, const QString &s = QString(), const QString &t = QString()) :
parent(0), name(n), sha(s), tracking(t)
{ }
~BranchNode()
{
while (!children.isEmpty())
delete children.first();
if (parent)
parent->children.removeAll(this);
}
BranchNode *rootNode() const
{
return parent ? parent->rootNode() : const_cast<BranchNode *>(this);
}
int count() const
{
return children.count();
}
bool isLeaf() const
{
return children.isEmpty() && parent && parent->parent;
}
bool childOf(BranchNode *node) const
{
if (this == node)
return true;
return parent ? parent->childOf(node) : false;
}
bool childOfRoot(RootNodes root) const
{
BranchNode *rn = rootNode();
if (rn->isLeaf())
return false;
if (root >= rn->children.count())
return false;
return childOf(rn->children.at(root));
}
bool isTag() const
{
return childOfRoot(Tags);
}
bool isLocal() const
{
return childOfRoot(LocalBranches);
}
BranchNode *childOfName(const QString &name) const
{
for (int i = 0; i < children.count(); ++i) {
if (children.at(i)->name == name)
return children.at(i);
}
return 0;
}
QStringList fullName(bool includePrefix = false) const
{
QTC_ASSERT(isLeaf(), return QStringList());
QStringList fn;
QList<const BranchNode *> nodes;
const BranchNode *current = this;
while (current->parent) {
nodes.prepend(current);
current = current->parent;
}
if (includePrefix)
fn.append(nodes.first()->sha);
nodes.removeFirst();
foreach (const BranchNode *n, nodes)
fn.append(n->name);
return fn;
}
void insert(const QStringList &path, BranchNode *n)
{
BranchNode *current = this;
for (int i = 0; i < path.count(); ++i) {
BranchNode *c = current->childOfName(path.at(i));
if (c)
current = c;
else
current = current->append(new BranchNode(path.at(i)));
}
current->append(n);
}
BranchNode *append(BranchNode *n)
{
n->parent = this;
children.append(n);
return n;
}
QStringList childrenNames() const
{
if (children.count() > 0) {
QStringList names;
foreach (BranchNode *n, children) {
names.append(n->childrenNames());
}
return names;
}
return QStringList(fullName().join(QLatin1Char('/')));
}
int rowOf(BranchNode *node)
{
return children.indexOf(node);
}
BranchNode *parent;
QList<BranchNode *> children;
QString name;
QString sha;
QString tracking;
mutable QString toolTip;
};
// --------------------------------------------------------------------------
// BranchModel:
// --------------------------------------------------------------------------
BranchModel::BranchModel(GitClient *client, QObject *parent) :
QAbstractItemModel(parent),
m_client(client),
m_rootNode(new BranchNode),
m_currentBranch(0)
{
QTC_CHECK(m_client);
// Abuse the sha field for ref prefix
m_rootNode->append(new BranchNode(tr("Local Branches"), QLatin1String("refs/heads")));
m_rootNode->append(new BranchNode(tr("Remote Branches"), QLatin1String("refs/remotes")));
}
BranchModel::~BranchModel()
{
delete m_rootNode;
}
QModelIndex BranchModel::index(int row, int column, const QModelIndex &parentIdx) const
{
if (column != 0)
return QModelIndex();
BranchNode *parentNode = indexToNode(parentIdx);
if (row >= parentNode->count())
return QModelIndex();
return nodeToIndex(parentNode->children.at(row));
}
QModelIndex BranchModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
BranchNode *node = indexToNode(index);
if (node->parent == m_rootNode)
return QModelIndex();
return nodeToIndex(node->parent);
}
int BranchModel::rowCount(const QModelIndex &parentIdx) const
{
if (parentIdx.column() > 0)
return 0;
return indexToNode(parentIdx)->count();
}
int BranchModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return 1;
}
QVariant BranchModel::data(const QModelIndex &index, int role) const
{
BranchNode *node = indexToNode(index);
if (!node)
return QVariant();
switch (role) {
case Qt::DisplayRole: {
QString res = node->name;
if (!node->tracking.isEmpty())
res += QLatin1String(" [") + node->tracking + QLatin1Char(']');
return res;
}
case Qt::EditRole:
return node->name;
case Qt::ToolTipRole:
if (!node->isLeaf())
return QVariant();
if (node->toolTip.isEmpty())
node->toolTip = toolTip(node->sha);
return node->toolTip;
case Qt::FontRole:
{
QFont font;
if (!node->isLeaf()) {
font.setBold(true);
} else if (node == m_currentBranch) {
font.setBold(true);
font.setUnderline(true);
}
return font;
}
default:
return QVariant();
}
}
bool BranchModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole)
return false;
BranchNode *node = indexToNode(index);
if (!node)
return false;
const QString newName = value.toString();
if (newName.isEmpty())
return false;
if (node->name == newName)
return true;
QStringList oldFullName = node->fullName();
node->name = newName;
QStringList newFullName = node->fullName();
QString output;
QString errorMessage;
if (!m_client->synchronousBranchCmd(m_workingDirectory,
QStringList() << QLatin1String("-m")
<< oldFullName.last()
<< newFullName.last(),
&output, &errorMessage)) {
node->name = oldFullName.last();
VcsOutputWindow::appendError(errorMessage);
return false;
}
emit dataChanged(index, index);
return true;
}
Qt::ItemFlags BranchModel::flags(const QModelIndex &index) const
{
BranchNode *node = indexToNode(index);
if (!node)
return Qt::NoItemFlags;
if (node->isLeaf() && node->isLocal())
return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
else
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
}
void BranchModel::clear()
{
foreach (BranchNode *root, m_rootNode->children)
while (root->count())
delete root->children.takeLast();
if (hasTags())
m_rootNode->children.takeLast();
m_currentBranch = 0;
}
bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage)
{
beginResetModel();
clear();
if (workingDirectory.isEmpty()) {
endResetModel();
return false;
}
m_currentSha = m_client->synchronousTopRevision(workingDirectory);
QStringList args;
args << QLatin1String("--format=%(objectname)\t%(refname)\t%(upstream:short)\t%(*objectname)");
QString output;
if (!m_client->synchronousForEachRefCmd(workingDirectory, args, &output, errorMessage))
VcsOutputWindow::appendError(*errorMessage);
m_workingDirectory = workingDirectory;
const QStringList lines = output.split(QLatin1Char('\n'));
foreach (const QString &l, lines)
parseOutputLine(l);
if (m_currentBranch) {
if (m_currentBranch->parent == m_rootNode->children.at(LocalBranches))
m_currentBranch = 0;
setCurrentBranch();
}
endResetModel();
return true;
}
void BranchModel::setCurrentBranch()
{
QString currentBranch = m_client->synchronousCurrentLocalBranch(m_workingDirectory);
if (currentBranch.isEmpty())
return;
BranchNode *local = m_rootNode->children.at(LocalBranches);
int pos = 0;
for (pos = 0; pos < local->count(); ++pos) {
if (local->children.at(pos)->name == currentBranch)
m_currentBranch = local->children[pos];
}
}
void BranchModel::renameBranch(const QString &oldName, const QString &newName)
{
QString errorMessage;
QString output;
if (!m_client->synchronousBranchCmd(m_workingDirectory,
QStringList() << QLatin1String("-m") << oldName << newName,
&output, &errorMessage))
VcsOutputWindow::appendError(errorMessage);
else
refresh(m_workingDirectory, &errorMessage);
}
void BranchModel::renameTag(const QString &oldName, const QString &newName)
{
QString errorMessage;
QString output;
if (!m_client->synchronousTagCmd(m_workingDirectory, QStringList() << newName << oldName,
&output, &errorMessage)
|| !m_client->synchronousTagCmd(m_workingDirectory,
QStringList() << QLatin1String("-d") << oldName,
&output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
} else {
refresh(m_workingDirectory, &errorMessage);
}
}
QString BranchModel::workingDirectory() const
{
return m_workingDirectory;
}
GitClient *BranchModel::client() const
{
return m_client;
}
QModelIndex BranchModel::currentBranch() const
{
if (!m_currentBranch)
return QModelIndex();
return nodeToIndex(m_currentBranch);
}
QString BranchModel::fullName(const QModelIndex &idx, bool includePrefix) const
{
if (!idx.isValid())
return QString();
BranchNode *node = indexToNode(idx);
if (!node || !node->isLeaf())
return QString();
QStringList path = node->fullName(includePrefix);
return path.join(QLatin1Char('/'));
}
QStringList BranchModel::localBranchNames() const
{
if (!m_rootNode || !m_rootNode->count())
return QStringList();
return m_rootNode->children.at(LocalBranches)->childrenNames();
}
QString BranchModel::sha(const QModelIndex &idx) const
{
if (!idx.isValid())
return QString();
BranchNode *node = indexToNode(idx);
return node->sha;
}
bool BranchModel::hasTags() const
{
return m_rootNode->children.count() > Tags;
}
bool BranchModel::isLocal(const QModelIndex &idx) const
{
if (!idx.isValid())
return false;
BranchNode *node = indexToNode(idx);
return node->isLocal();
}
bool BranchModel::isLeaf(const QModelIndex &idx) const
{
if (!idx.isValid())
return false;
BranchNode *node = indexToNode(idx);
return node->isLeaf();
}
bool BranchModel::isTag(const QModelIndex &idx) const
{
if (!idx.isValid() || !hasTags())
return false;
return indexToNode(idx)->isTag();
}
void BranchModel::removeBranch(const QModelIndex &idx)
{
QString branch = fullName(idx);
if (branch.isEmpty())
return;
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-D") << branch;
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
return;
}
removeNode(idx);
}
void BranchModel::removeTag(const QModelIndex &idx)
{
QString tag = fullName(idx);
if (tag.isEmpty())
return;
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-d") << tag;
if (!m_client->synchronousTagCmd(m_workingDirectory, args, &output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
return;
}
removeNode(idx);
}
void BranchModel::checkoutBranch(const QModelIndex &idx)
{
QString branch = fullName(idx, !isLocal(idx));
if (branch.isEmpty())
return;
// No StashGuard since this function for now is only used with clean working dir.
// If it is ever used from another place, please add StashGuard here
m_client->synchronousCheckout(m_workingDirectory, branch);
}
bool BranchModel::branchIsMerged(const QModelIndex &idx)
{
QString branch = fullName(idx);
if (branch.isEmpty())
return false;
QString errorMessage;
QString output;
QStringList args;
args << QLatin1String("-a") << QLatin1String("--contains") << sha(idx);
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage))
VcsOutputWindow::appendError(errorMessage);
QStringList lines = output.split(QLatin1Char('\n'), QString::SkipEmptyParts);
foreach (const QString &l, lines) {
QString currentBranch = l.mid(2); // remove first letters (those are either
// " " or "* " depending on whether it is
// the currently checked out branch or not)
if (currentBranch != branch)
return true;
}
return false;
}
static int positionForName(BranchNode *node, const QString &name)
{
int pos = 0;
for (pos = 0; pos < node->count(); ++pos) {
if (node->children.at(pos)->name >= name)
break;
}
return pos;
}
QModelIndex BranchModel::addBranch(const QString &name, bool track, const QModelIndex &startPoint)
{
if (!m_rootNode || !m_rootNode->count())
return QModelIndex();
const QString trackedBranch = fullName(startPoint);
const QString fullTrackedBranch = fullName(startPoint, true);
QString startSha;
QString output;
QString errorMessage;
QStringList args;
args << (track ? QLatin1String("--track") : QLatin1String("--no-track"));
args << name;
if (!fullTrackedBranch.isEmpty()) {
args << fullTrackedBranch;
startSha = sha(startPoint);
} else {
startSha = m_client->synchronousTopRevision(m_workingDirectory);
}
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) {
VcsOutputWindow::appendError(errorMessage);
return QModelIndex();
}
BranchNode *local = m_rootNode->children.at(LocalBranches);
const int slash = name.indexOf(QLatin1Char('/'));
const QString leafName = slash == -1 ? name : name.mid(slash + 1);
bool added = false;
if (slash != -1) {
const QString nodeName = name.left(slash);
int pos = positionForName(local, nodeName);
BranchNode *child = (pos == local->count()) ? 0 : local->children.at(pos);
if (!child || child->name != nodeName) {
child = new BranchNode(nodeName);
beginInsertRows(nodeToIndex(local), pos, pos);
added = true;
child->parent = local;
local->children.insert(pos, child);
}
local = child;
}
int pos = positionForName(local, leafName);
auto newNode = new BranchNode(leafName, startSha, track ? trackedBranch : QString());
if (!added)
beginInsertRows(nodeToIndex(local), pos, pos);
newNode->parent = local;
local->children.insert(pos, newNode);
endInsertRows();
return nodeToIndex(newNode);
}
void BranchModel::setRemoteTracking(const QModelIndex &trackingIndex)
{
QModelIndex current = currentBranch();
QTC_ASSERT(current.isValid(), return);
const QString currentName = fullName(current);
const QString shortTracking = fullName(trackingIndex);
const QString tracking = fullName(trackingIndex, true);
m_client->synchronousSetTrackingBranch(m_workingDirectory, currentName, tracking);
m_currentBranch->tracking = shortTracking;
emit dataChanged(current, current);
}
void BranchModel::parseOutputLine(const QString &line)
{
if (line.size() < 3)
return;
QStringList lineParts = line.split(QLatin1Char('\t'));
const QString shaDeref = lineParts.at(3);
const QString sha = shaDeref.isEmpty() ? lineParts.at(0) : shaDeref;
const QString fullName = lineParts.at(1);
bool current = (sha == m_currentSha);
bool showTags = m_client->settings().boolValue(GitSettings::showTagsKey);
// insert node into tree:
QStringList nameParts = fullName.split(QLatin1Char('/'));
nameParts.removeFirst(); // remove refs...
BranchNode *root = 0;
if (nameParts.first() == QLatin1String("heads")) {
root = m_rootNode->children.at(LocalBranches);
} else if (nameParts.first() == QLatin1String("remotes")) {
root = m_rootNode->children.at(RemoteBranches);
} else if (showTags && nameParts.first() == QLatin1String("tags")) {
if (!hasTags()) // Tags is missing, add it
m_rootNode->append(new BranchNode(tr("Tags"), QLatin1String("refs/tags")));
root = m_rootNode->children.at(Tags);
} else {
return;
}
nameParts.removeFirst();
// limit depth of list. Git basically only ever wants one / and considers the rest as part of
// the name.
while (nameParts.count() > 3) {
nameParts[2] = nameParts.at(2) + QLatin1Char('/') + nameParts.at(3);
nameParts.removeAt(3);
}
const QString name = nameParts.last();
nameParts.removeLast();
auto newNode = new BranchNode(name, sha, lineParts.at(2));
root->insert(nameParts, newNode);
if (current)
m_currentBranch = newNode;
}
BranchNode *BranchModel::indexToNode(const QModelIndex &index) const
{
if (index.column() > 0)
return 0;
if (!index.isValid())
return m_rootNode;
return static_cast<BranchNode *>(index.internalPointer());
}
QModelIndex BranchModel::nodeToIndex(BranchNode *node) const
{
if (node == m_rootNode)
return QModelIndex();
return createIndex(node->parent->rowOf(node), 0, static_cast<void *>(node));
}
void BranchModel::removeNode(const QModelIndex &idx)
{
QModelIndex nodeIndex = idx; // idx is a leaf, so count must be 0.
BranchNode *node = indexToNode(nodeIndex);
while (node->count() == 0 && node->parent != m_rootNode) {
BranchNode *parentNode = node->parent;
const QModelIndex parentIndex = nodeToIndex(parentNode);
const int nodeRow = nodeIndex.row();
beginRemoveRows(parentIndex, nodeRow, nodeRow);
parentNode->children.removeAt(nodeRow);
delete node;
endRemoveRows();
node = parentNode;
nodeIndex = parentIndex;
}
}
QString BranchModel::toolTip(const QString &sha) const
{
// Show the sha description excluding diff as toolTip
QString output;
QString errorMessage;
QStringList arguments(QLatin1String("-n1"));
arguments << sha;
if (!m_client->synchronousLog(m_workingDirectory, arguments, &output, &errorMessage,
VcsCommand::SuppressCommandLogging)) {
return errorMessage;
}
return output;
}
} // namespace Internal
} // namespace Git
| frostasm/qt-creator | src/plugins/git/branchmodel.cpp | C++ | gpl-3.0 | 21,355 |
/*
This file is part of the FreeRTOS.org distribution.
FreeRTOS.org is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License (version 2) as published
by the Free Software Foundation and modified by the FreeRTOS exception.
FreeRTOS.org 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 FreeRTOS.org; if not, write to the Free Software Foundation, Inc., 59
Temple Place, Suite 330, Boston, MA 02111-1307 USA.
A special exception to the GPL is included to allow you to distribute a
combined work that includes FreeRTOS.org without being obliged to provide
the source code for any proprietary components. See the licensing section
of http://www.FreeRTOS.org for full details.
***************************************************************************
* *
* Get the FreeRTOS eBook! See http://www.FreeRTOS.org/Documentation *
* *
* This is a concise, step by step, 'hands on' guide that describes both *
* general multitasking concepts and FreeRTOS specifics. It presents and *
* explains numerous examples that are written using the FreeRTOS API. *
* Full source code for all the examples is provided in an accompanying *
* .zip file. *
* *
***************************************************************************
1 tab == 4 spaces!
Please ensure to read the configuration and relevant port sections of the
online documentation.
***************************************************************************
* *
* Having a problem? Start by reading the FAQ "My application does *
* not run, what could be wrong? *
* *
* http://www.FreeRTOS.org/FAQHelp.html *
* *
***************************************************************************
http://www.FreeRTOS.org - Documentation, training, latest information,
license and contact details.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool.
Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell
the code with commercial support, indemnification, and middleware, under
the OpenRTOS brand: http://www.OpenRTOS.com. High Integrity Systems also
provide a safety engineered and independently SIL3 certified version under
the SafeRTOS brand: http://www.SafeRTOS.com.
*/
/* Kernel includes. */
#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"
/* Demo includes. */
#include "FEC.h"
#include "fecbd.h"
#include "mii.h"
#include "eth_phy.h"
#include "eth.h"
/* uIP includes. */
#include "uip.h"
#include "uip_arp.h"
/*-----------------------------------------------------------*/
/* FEC hardware specifics. */
#define MCF_FEC_MSCR_MII_SPEED(x) (((x)&0x3F)<<0x1)
#define MCF_FEC_RDAR_R_DES_ACTIVE ( 0x1000000 )
#define MCF_FEC_TDAR_X_DES_ACTIVE ( 0x1000000 )
/* PHY hardware specifics. */
#define PHY_STATUS ( 16 )
#define PHY_DUPLEX_STATUS ( 4 )
/* Delay between polling the PHY to see if a link has been established. */
#define fecLINK_DELAY ( 500 / portTICK_PERIOD_MS )
/* Very short delay to use when waiting for the Tx to finish with a buffer if
we run out of Rx buffers. */
#define fecMINIMAL_DELAY ( 3 / portTICK_PERIOD_MS )
/* Don't block to wait for a buffer more than this many times. */
#define uipBUFFER_WAIT_ATTEMPTS ( 30 )
/* The Tx re-uses the Rx buffers and only has one descriptor. */
#define fecNUM_TX_DESCRIPTORS ( 1 )
/* The total number of buffers available, which should be greater than the
number of Rx descriptors. */
#define fecNUM_BUFFERS ( configNUM_FEC_RX_DESCRIPTORS + 2 )
/*-----------------------------------------------------------*/
/*
* Return an unused buffer to the pool of free buffers.
*/
static void prvReturnBuffer( unsigned char *pucBuffer );
/*
* Find and return the next buffer that is not in use by anything else.
*/
static unsigned char *prvGetFreeBuffer( void );
/*-----------------------------------------------------------*/
/* The semaphore used to wake the uIP task when data arrives. */
SemaphoreHandle_t xFECSemaphore = NULL;
/* The buffer used by the uIP stack. In this case the pointer is used to
point to one of the Rx buffers to avoid having to copy the Rx buffer into
the uIP buffer. */
unsigned char *uip_buf;
/* The DMA descriptors. These are char arrays to allow us to align them
correctly. */
static unsigned char xFECTxDescriptors_unaligned[ ( fecNUM_TX_DESCRIPTORS * sizeof( FECBD ) ) + 16 ];
static unsigned char xFECRxDescriptors_unaligned[ ( configNUM_FEC_RX_DESCRIPTORS * sizeof( FECBD ) ) + 16 ];
static FECBD *pxFECTxDescriptor;
static FECBD *xFECRxDescriptors;
/* The DMA buffer. This is a char arrays to allow it to be aligned correctly. */
static unsigned char ucFECRxBuffers[ ( fecNUM_BUFFERS * configFEC_BUFFER_SIZE ) + 16 ];
/* Index to the next descriptor to be inspected for received data. */
static unsigned long ulNextRxDescriptor = 0;
/* Contains the start address of each Rx buffer, after it has been correctly
aligned. */
static unsigned char *pucAlignedBufferStartAddresses[ fecNUM_BUFFERS ] = { 0 };
/* Each ucBufferInUse index corresponds to a position in the same index in the
pucAlignedBufferStartAddresses array. If the index contains a 1 then the
buffer within pucAlignedBufferStartAddresses is in use, if it contains a 0 then
the buffer is free. */
static unsigned char ucBufferInUse[ fecNUM_BUFFERS ] = { 0 };
/*-----------------------------------------------------------*/
/********************************************************************/
/*
* Write a value to a PHY's MII register.
*
* Parameters:
* ch FEC channel
* phy_addr Address of the PHY.
* reg_addr Address of the register in the PHY.
* data Data to be written to the PHY register.
*
* Return Values:
* 0 on failure
* 1 on success.
*
* Please refer to your PHY manual for registers and their meanings.
* mii_write() polls for the FEC's MII interrupt event and clears it.
* If after a suitable amount of time the event isn't triggered, a
* value of 0 is returned.
*/
static int fec_mii_write( int phy_addr, int reg_addr, int data )
{
int timeout;
unsigned long eimr;
/* Clear the MII interrupt bit */
EIR = EIR_MII;
/* Mask the MII interrupt */
eimr = EIMR;
EIMR &= ~EIMR_MII;
/* Write to the MII Management Frame Register to kick-off the MII write */
MMFR = ( unsigned long ) ( FEC_MMFR_ST_01 | FEC_MMFR_OP_WRITE | FEC_MMFR_PA(phy_addr) | FEC_MMFR_RA(reg_addr) | FEC_MMFR_TA_10 | FEC_MMFR_DATA( data ) );
/* Poll for the MII interrupt (interrupt should be masked) */
for (timeout = 0; timeout < FEC_MII_TIMEOUT; timeout++)
{
if( EIR & EIR_MII)
{
break;
}
}
if( timeout == FEC_MII_TIMEOUT )
{
return 0;
}
/* Clear the MII interrupt bit */
EIR = EIR_MII;
/* Restore the EIMR */
EIMR = eimr;
return 1;
}
/********************************************************************/
/*
* Read a value from a PHY's MII register.
*
* Parameters:
* ch FEC channel
* phy_addr Address of the PHY.
* reg_addr Address of the register in the PHY.
* data Pointer to storage for the Data to be read
* from the PHY register (passed by reference)
*
* Return Values:
* 0 on failure
* 1 on success.
*
* Please refer to your PHY manual for registers and their meanings.
* mii_read() polls for the FEC's MII interrupt event and clears it.
* If after a suitable amount of time the event isn't triggered, a
* value of 0 is returned.
*/
static int fec_mii_read( int phy_addr, int reg_addr, unsigned short* data )
{
int timeout;
unsigned long eimr;
/* Clear the MII interrupt bit */
EIR = 0xffffffff;
/* Mask the MII interrupt */
eimr = EIMR;
EIMR &= ~EIMR_MII;
/* Write to the MII Management Frame Register to kick-off the MII read */
MMFR = ( unsigned long ) ( FEC_MMFR_ST_01 | FEC_MMFR_OP_READ | FEC_MMFR_PA(phy_addr) | FEC_MMFR_RA(reg_addr) | FEC_MMFR_TA_10 );
/* Poll for the MII interrupt (interrupt should be masked) */
for (timeout = 0; timeout < FEC_MII_TIMEOUT; timeout++)
{
if (EIR)
{
break;
}
}
if(timeout == FEC_MII_TIMEOUT)
{
return 0;
}
/* Clear the MII interrupt bit */
EIR = EIR_MII;
/* Restore the EIMR */
EIMR = eimr;
*data = (unsigned short)(MMFR & 0x0000FFFF);
return 1;
}
/********************************************************************/
/*
* Generate the hash table settings for the given address
*
* Parameters:
* addr 48-bit (6 byte) Address to generate the hash for
*
* Return Value:
* The 6 most significant bits of the 32-bit CRC result
*/
static unsigned char fec_hash_address( const unsigned char* addr )
{
unsigned long crc;
unsigned char byte;
int i, j;
crc = 0xFFFFFFFF;
for(i=0; i<6; ++i)
{
byte = addr[i];
for(j=0; j<8; ++j)
{
if((byte & 0x01)^(crc & 0x01))
{
crc >>= 1;
crc = crc ^ 0xEDB88320;
}
else
{
crc >>= 1;
}
byte >>= 1;
}
}
return (unsigned char)(crc >> 26);
}
/********************************************************************/
/*
* Set the Physical (Hardware) Address and the Individual Address
* Hash in the selected FEC
*
* Parameters:
* ch FEC channel
* pa Physical (Hardware) Address for the selected FEC
*/
static void fec_set_address( const unsigned char *pa )
{
unsigned char crc;
/*
* Set the Physical Address
*/
PALR = (unsigned long)((pa[0]<<24) | (pa[1]<<16) | (pa[2]<<8) | pa[3]);
PAUR = (unsigned long)((pa[4]<<24) | (pa[5]<<16));
/*
* Calculate and set the hash for given Physical Address
* in the Individual Address Hash registers
*/
crc = fec_hash_address(pa);
if(crc >= 32)
{
IAUR |= (unsigned long)(1 << (crc - 32));
}
else
{
IALR |= (unsigned long)(1 << crc);
}
}
/*-----------------------------------------------------------*/
static void prvInitialiseFECBuffers( void )
{
unsigned portBASE_TYPE ux;
unsigned char *pcBufPointer;
/* Set the pointer to a correctly aligned address. */
pcBufPointer = &( xFECTxDescriptors_unaligned[ 0 ] );
while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 )
{
pcBufPointer++;
}
pxFECTxDescriptor = ( FECBD * ) pcBufPointer;
/* Likewise the pointer to the Rx descriptor. */
pcBufPointer = &( xFECRxDescriptors_unaligned[ 0 ] );
while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 )
{
pcBufPointer++;
}
xFECRxDescriptors = ( FECBD * ) pcBufPointer;
/* There is no Tx buffer as the Rx buffer is reused. */
pxFECTxDescriptor->length = 0;
pxFECTxDescriptor->status = 0;
/* Align the Rx buffers. */
pcBufPointer = &( ucFECRxBuffers[ 0 ] );
while( ( ( unsigned long ) pcBufPointer & 0x0fUL ) != 0 )
{
pcBufPointer++;
}
/* Then fill in the Rx descriptors. */
for( ux = 0; ux < configNUM_FEC_RX_DESCRIPTORS; ux++ )
{
xFECRxDescriptors[ ux ].status = RX_BD_E;
xFECRxDescriptors[ ux ].length = configFEC_BUFFER_SIZE;
xFECRxDescriptors[ ux ].data = pcBufPointer;
/* Note the start address of the buffer now that it is correctly
aligned. */
pucAlignedBufferStartAddresses[ ux ] = pcBufPointer;
/* The buffer is in use by the descriptor. */
ucBufferInUse[ ux ] = pdTRUE;
pcBufPointer += configFEC_BUFFER_SIZE;
}
/* Note the start address of the last buffer as one more buffer is
allocated than there are Rx descriptors. */
pucAlignedBufferStartAddresses[ ux ] = pcBufPointer;
/* Set uip_buf to point to the last buffer. */
uip_buf = pcBufPointer;
ucBufferInUse[ ux ] = pdTRUE;
/* Set the wrap bit in the last descriptors to form a ring. */
xFECRxDescriptors[ configNUM_FEC_RX_DESCRIPTORS - 1 ].status |= RX_BD_W;
/* We start with descriptor 0. */
ulNextRxDescriptor = 0;
}
/*-----------------------------------------------------------*/
void vInitFEC( void )
{
unsigned short usData;
struct uip_eth_addr xAddr;
const unsigned char ucMACAddress[6] =
{
configMAC_0, configMAC_1,configMAC_2,configMAC_3,configMAC_4,configMAC_5
};
prvInitialiseFECBuffers();
/* Create the semaphore used to wake the uIP task when data arrives. */
vSemaphoreCreateBinary( xFECSemaphore );
/* Set the MAC address within the stack. */
for( usData = 0; usData < 6; usData++ )
{
xAddr.addr[ usData ] = ucMACAddress[ usData ];
}
uip_setethaddr( xAddr );
/* Set the Reset bit and clear the Enable bit */
ECR_RESET = 1;
/* Enable the clock. */
SCGC4 |= SCGC4_FEC_MASK;
/* Wait at least 8 clock cycles */
for( usData = 0; usData < 10; usData++ )
{
asm( "NOP" );
}
/* Set MII speed to 2.5MHz. */
MSCR = MCF_FEC_MSCR_MII_SPEED( ( ( configCPU_CLOCK_HZ / 1000000 ) / 5 ) + 1 );
/*
* Make sure the external interface signals are enabled
*/
PTCPF2_C0 = 1;
PTCPF2_C1 = 1;
PTCPF2_C2 = 1;
PTAPF1 = 0x55;
PTAPF2 = 0x55;
PTBPF1 = 0x55;
PTBPF2 = 0x55;
/* Set all pins to full drive with no filter. */
PTADS = 0x06;
PTAIFE = 0x06;
PTBDS = 0xf4;
PTBIFE = 0xf4;
PTCDS = 0;
PTCIFE = 0;
/* Can we talk to the PHY? */
do
{
vTaskDelay( fecLINK_DELAY );
usData = 0xffff;
fec_mii_read( configPHY_ADDRESS, PHY_PHYIDR1, &usData );
} while( usData == 0xffff );
/* Start auto negotiate. */
fec_mii_write( configPHY_ADDRESS, PHY_BMCR, ( PHY_BMCR_AN_RESTART | PHY_BMCR_AN_ENABLE ) );
/* Wait for auto negotiate to complete. */
do
{
vTaskDelay( fecLINK_DELAY );
fec_mii_read( configPHY_ADDRESS, PHY_BMSR, &usData );
} while( !( usData & PHY_BMSR_AN_COMPLETE ) );
/* When we get here we have a link - find out what has been negotiated. */
usData = 0;
fec_mii_read( configPHY_ADDRESS, PHY_STATUS, &usData );
/* Setup half or full duplex. */
if( usData & PHY_DUPLEX_STATUS )
{
RCR &= (unsigned long)~RCR_DRT;
TCR |= TCR_FDEN;
}
else
{
RCR |= RCR_DRT;
TCR &= (unsigned long)~TCR_FDEN;
}
/* Clear the Individual and Group Address Hash registers */
IALR = 0;
IAUR = 0;
GALR = 0;
GAUR = 0;
/* Set the Physical Address for the selected FEC */
fec_set_address( ucMACAddress );
/* Set Rx Buffer Size */
EMRBR = (unsigned short) configFEC_BUFFER_SIZE;
/* Point to the start of the circular Rx buffer descriptor queue */
ERDSR = ( volatile unsigned long ) &( xFECRxDescriptors[ 0 ] );
/* Point to the start of the circular Tx buffer descriptor queue */
ETSDR = ( volatile unsigned long ) pxFECTxDescriptor;
/* Clear all FEC interrupt events */
EIR = ( unsigned long ) -1;
/* Various mode/status setup. */
RCR = 0;
RCR_MAX_FL = configFEC_BUFFER_SIZE;
RCR_MII_MODE = 1;
#if( configUSE_PROMISCUOUS_MODE == 1 )
{
RCR |= RCR_PROM;
}
#endif
/* Enable interrupts. */
EIMR = EIR_TXF_MASK | EIMR_RXF_MASK | EIMR_RXB_MASK | EIMR_UN_MASK | EIMR_RL_MASK | EIMR_LC_MASK | EIMR_BABT_MASK | EIMR_BABR_MASK | EIMR_HBERR_MASK;
/* Enable the MAC itself. */
ECR = ECR_ETHER_EN_MASK;
/* Indicate that there have been empty receive buffers produced */
RDAR = MCF_FEC_RDAR_R_DES_ACTIVE;
}
/*-----------------------------------------------------------*/
unsigned long ulFECRx( void )
{
unsigned long ulLen = 0UL;
/* Is a buffer ready? */
if( ( xFECRxDescriptors[ ulNextRxDescriptor ].status & RX_BD_E ) == 0 )
{
/* uip_buf is about to be set to a new buffer, so return the buffer it
is already pointing to. */
prvReturnBuffer( uip_buf );
/* Obtain the size of the packet and put it into the "len" variable. */
ulLen = xFECRxDescriptors[ ulNextRxDescriptor ].length;
uip_buf = xFECRxDescriptors[ ulNextRxDescriptor ].data;
/* The buffer that this descriptor was using is now in use by the
TCP/IP stack, so allocate it a new buffer. */
xFECRxDescriptors[ ulNextRxDescriptor ].data = prvGetFreeBuffer();
/* Doing this here could cause corruption! */
xFECRxDescriptors[ ulNextRxDescriptor ].status |= RX_BD_E;
portENTER_CRITICAL();
{
ulNextRxDescriptor++;
if( ulNextRxDescriptor >= configNUM_FEC_RX_DESCRIPTORS )
{
ulNextRxDescriptor = 0;
}
}
portEXIT_CRITICAL();
/* Tell the DMA a new buffer is available. */
RDAR = MCF_FEC_RDAR_R_DES_ACTIVE;
}
return ulLen;
}
/*-----------------------------------------------------------*/
void vFECTx( void )
{
/* When we get here the Tx descriptor should show as having completed. */
while( pxFECTxDescriptor->status & TX_BD_R )
{
vTaskDelay( fecMINIMAL_DELAY );
}
portENTER_CRITICAL();
{
/* To maintain the zero copy implementation, point the Tx descriptor
to the data from the Rx buffer. */
pxFECTxDescriptor->data = uip_buf;
/* Setup the buffer descriptor for transmission */
pxFECTxDescriptor->length = uip_len;
/* NB this assumes only one Tx descriptor! */
pxFECTxDescriptor->status = ( TX_BD_R | TX_BD_L | TX_BD_TC | TX_BD_W );
}
portEXIT_CRITICAL();
/* Continue the Tx DMA task (in case it was waiting for a new TxBD) */
TDAR = MCF_FEC_TDAR_X_DES_ACTIVE;
/* uip_buf is being used by the Tx descriptor. Allocate a new buffer to
uip_buf. */
uip_buf = prvGetFreeBuffer();
}
/*-----------------------------------------------------------*/
static void prvReturnBuffer( unsigned char *pucBuffer )
{
unsigned long ul;
/* Mark a buffer as free for use. */
for( ul = 0; ul < fecNUM_BUFFERS; ul++ )
{
if( pucAlignedBufferStartAddresses[ ul ] == pucBuffer )
{
ucBufferInUse[ ul ] = pdFALSE;
break;
}
}
}
/*-----------------------------------------------------------*/
static unsigned char *prvGetFreeBuffer( void )
{
portBASE_TYPE x;
unsigned char *pucReturn = NULL;
unsigned long ulAttempts = 0;
while( pucReturn == NULL )
{
/* Look through the buffers to find one that is not in use by
anything else. */
for( x = 0; x < fecNUM_BUFFERS; x++ )
{
if( ucBufferInUse[ x ] == pdFALSE )
{
ucBufferInUse[ x ] = pdTRUE;
pucReturn = pucAlignedBufferStartAddresses[ x ];
break;
}
}
/* Was a buffer found? */
if( pucReturn == NULL )
{
ulAttempts++;
if( ulAttempts >= uipBUFFER_WAIT_ATTEMPTS )
{
break;
}
/* Wait then look again. */
vTaskDelay( fecMINIMAL_DELAY );
}
}
return pucReturn;
}
/*-----------------------------------------------------------*/
void interrupt 86 vFECISRHandler( void )
{
unsigned long ulEvent;
portBASE_TYPE xHighPriorityTaskWoken = pdFALSE;
/* Determine the cause of the interrupt. */
ulEvent = EIR & EIMR;
EIR = ulEvent;
if( ulEvent & EIR_RXF_MASK )
{
/* A packet has been received. Wake the handler task in case it is
blocked. */
xSemaphoreGiveFromISR( xFECSemaphore, &xHighPriorityTaskWoken );
}
if( ulEvent & EIR_TXF_MASK )
{
/* The Tx has completed. Mark the buffer it was using as free again. */
prvReturnBuffer( pxFECTxDescriptor->data );
pxFECTxDescriptor->data = NULL;
}
if (ulEvent & ( EIR_UN_MASK | EIR_RL_MASK | EIR_LC_MASK | EIR_EBERR_MASK | EIR_BABT_MASK | EIR_BABR_MASK | EIR_HBERR_MASK ) )
{
/* Sledge hammer error handling. */
prvInitialiseFECBuffers();
RDAR = MCF_FEC_RDAR_R_DES_ACTIVE;
}
portEND_SWITCHING_ISR( xHighPriorityTaskWoken );
}
| RobsonRojas/frertos-udemy | Keil-FreeRTOS-Sample-Project/Keil-FreeRTOS/FreeRTOSv9.0.0/FreeRTOS/Demo/ColdFire_MCF51CN128_CodeWarrior/Sources/FEC.c | C | gpl-3.0 | 20,040 |
-- Account initialisation script for Oracle Trust Service tablespace
-- <![CDATA[Usage: sqlplus / as sysdba @oracle-create-account.sql ]]>
drop user trust cascade;
create user trust identified by trust
default tablespace TRUST_SERVICE
temporary tablespace temp
quota unlimited on TRUST_SERVICE
;
grant connect to trust;
grant create sequence to trust;
grant create view to trust;
grant alter session to trust;
grant create table to trust;
-- XA DataSource support
GRANT SELECT ON sys.dba_pending_transactions TO trust;
GRANT SELECT ON sys.pending_trans$ TO trust;
GRANT SELECT ON sys.dba_2pc_pending TO trust;
-- for Oracle 10g R2 with patch for bug 5945463 applied and higher:
-- GRANT EXECUTE ON sys.dbms_xa TO trust;
-- else
GRANT EXECUTE ON sys.dbms_system TO trust;
| tectronics/eid-trust-service | eid-trust-service-sql-ddl/src/main/resources/oracle-create-account.sql | SQL | gpl-3.0 | 772 |
/**CFile****************************************************************
FileName [ioReadBaf.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [Command processing package.]
Synopsis [Procedures to read AIG in the binary format.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: ioReadBaf.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "ioAbc.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis [Reads the AIG in the binary format.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Abc_Ntk_t * Io_ReadBaf( char * pFileName, int fCheck )
{
ProgressBar * pProgress;
FILE * pFile;
Vec_Ptr_t * vNodes;
Abc_Obj_t * pObj, * pNode0, * pNode1;
Abc_Ntk_t * pNtkNew;
int nInputs, nOutputs, nLatches, nAnds, nFileSize, Num, i;
char * pContents, * pName, * pCur;
unsigned * pBufferNode;
int RetValue;
// read the file into the buffer
nFileSize = Extra_FileSize( pFileName );
pFile = fopen( pFileName, "rb" );
pContents = ABC_ALLOC( char, nFileSize );
RetValue = fread( pContents, nFileSize, 1, pFile );
fclose( pFile );
// skip the comments (comment lines begin with '#' and end with '\n')
for ( pCur = pContents; *pCur == '#'; )
while ( *pCur++ != '\n' );
// read the name
pName = pCur; while ( *pCur++ );
// read the number of inputs
nInputs = atoi( pCur ); while ( *pCur++ );
// read the number of outputs
nOutputs = atoi( pCur ); while ( *pCur++ );
// read the number of latches
nLatches = atoi( pCur ); while ( *pCur++ );
// read the number of nodes
nAnds = atoi( pCur ); while ( *pCur++ );
// allocate the empty AIG
pNtkNew = Abc_NtkAlloc( ABC_NTK_STRASH, ABC_FUNC_AIG, 1 );
pNtkNew->pName = Extra_UtilStrsav( pName );
pNtkNew->pSpec = Extra_UtilStrsav( pFileName );
// prepare the array of nodes
vNodes = Vec_PtrAlloc( 1 + nInputs + nLatches + nAnds );
Vec_PtrPush( vNodes, Abc_AigConst1(pNtkNew) );
// create the PIs
for ( i = 0; i < nInputs; i++ )
{
pObj = Abc_NtkCreatePi(pNtkNew);
Abc_ObjAssignName( pObj, pCur, NULL ); while ( *pCur++ );
Vec_PtrPush( vNodes, pObj );
}
// create the POs
for ( i = 0; i < nOutputs; i++ )
{
pObj = Abc_NtkCreatePo(pNtkNew);
Abc_ObjAssignName( pObj, pCur, NULL ); while ( *pCur++ );
}
// create the latches
for ( i = 0; i < nLatches; i++ )
{
pObj = Abc_NtkCreateLatch(pNtkNew);
Abc_ObjAssignName( pObj, pCur, NULL ); while ( *pCur++ );
pNode0 = Abc_NtkCreateBi(pNtkNew);
Abc_ObjAssignName( pNode0, pCur, NULL ); while ( *pCur++ );
pNode1 = Abc_NtkCreateBo(pNtkNew);
Abc_ObjAssignName( pNode1, pCur, NULL ); while ( *pCur++ );
Vec_PtrPush( vNodes, pNode1 );
Abc_ObjAddFanin( pObj, pNode0 );
Abc_ObjAddFanin( pNode1, pObj );
}
// get the pointer to the beginning of the node array
pBufferNode = (unsigned *)(pContents + (nFileSize - (2 * nAnds + nOutputs + nLatches) * sizeof(int)) );
// make sure we are at the place where the nodes begin
if ( pBufferNode != (unsigned *)pCur )
{
ABC_FREE( pContents );
Vec_PtrFree( vNodes );
Abc_NtkDelete( pNtkNew );
printf( "Warning: Internal reader error.\n" );
return NULL;
}
// create the AND gates
pProgress = Extra_ProgressBarStart( stdout, nAnds );
for ( i = 0; i < nAnds; i++ )
{
Extra_ProgressBarUpdate( pProgress, i, NULL );
pNode0 = Abc_ObjNotCond( (Abc_Obj_t *)Vec_PtrEntry(vNodes, pBufferNode[2*i+0] >> 1), pBufferNode[2*i+0] & 1 );
pNode1 = Abc_ObjNotCond( (Abc_Obj_t *)Vec_PtrEntry(vNodes, pBufferNode[2*i+1] >> 1), pBufferNode[2*i+1] & 1 );
Vec_PtrPush( vNodes, Abc_AigAnd((Abc_Aig_t *)pNtkNew->pManFunc, pNode0, pNode1) );
}
Extra_ProgressBarStop( pProgress );
// read the POs
Abc_NtkForEachCo( pNtkNew, pObj, i )
{
Num = pBufferNode[2*nAnds+i];
if ( Abc_ObjFanoutNum(pObj) > 0 && Abc_ObjIsLatch(Abc_ObjFanout0(pObj)) )
{
Abc_ObjSetData( Abc_ObjFanout0(pObj), (void *)(ABC_PTRINT_T)(Num & 3) );
Num >>= 2;
}
pNode0 = Abc_ObjNotCond( (Abc_Obj_t *)Vec_PtrEntry(vNodes, Num >> 1), Num & 1 );
Abc_ObjAddFanin( pObj, pNode0 );
}
ABC_FREE( pContents );
Vec_PtrFree( vNodes );
// remove the extra nodes
// Abc_AigCleanup( (Abc_Aig_t *)pNtkNew->pManFunc );
// check the result
if ( fCheck && !Abc_NtkCheckRead( pNtkNew ) )
{
printf( "Io_ReadBaf: The network check has failed.\n" );
Abc_NtkDelete( pNtkNew );
return NULL;
}
return pNtkNew;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
| Kinghsy/490_core | lib/abc/src/base/io/ioReadBaf.c | C | gpl-3.0 | 5,781 |
package com.github.bordertech.wcomponents.examples;
import com.github.bordertech.wcomponents.RadioButtonGroup;
import com.github.bordertech.wcomponents.Size;
import com.github.bordertech.wcomponents.WLabel;
import com.github.bordertech.wcomponents.WPanel;
import com.github.bordertech.wcomponents.WRadioButton;
import com.github.bordertech.wcomponents.layout.FlowLayout;
import com.github.bordertech.wcomponents.layout.FlowLayout.Alignment;
/**
* {@link WRadioButton} example.
*
* @author Yiannis Paschalidis
* @since 1.0.0
*/
public class RadioButtonExample extends WPanel {
/**
* Creates a RadioButtonExample.
*/
public RadioButtonExample() {
this.setLayout(new FlowLayout(Alignment.VERTICAL));
WPanel panel = new WPanel();
RadioButtonGroup group1 = new RadioButtonGroup();
panel.add(group1);
WRadioButton rb1 = group1.addRadioButton(1);
panel.add(new WLabel("Default", rb1));
panel.add(rb1);
this.add(panel);
panel = new WPanel();
RadioButtonGroup group2 = new RadioButtonGroup();
panel.add(group2);
WRadioButton rb2 = group2.addRadioButton(1);
rb2.setSelected(true);
panel.add(new WLabel("Initially selected", rb2));
panel.add(rb2);
this.add(panel);
panel = new WPanel();
RadioButtonGroup group3 = new RadioButtonGroup();
panel.add(group3);
WRadioButton rb3 = group3.addRadioButton(1);
rb3.setDisabled(true);
rb3.setToolTip("This is disabled.");
panel.add(new WLabel("Disabled", rb3));
panel.add(rb3);
this.add(panel);
RadioButtonGroup group = new RadioButtonGroup();
WRadioButton rb4 = group.addRadioButton("A");
WRadioButton rb5 = group.addRadioButton("B");
WRadioButton rb6 = group.addRadioButton("C");
panel = new WPanel();
panel.setLayout(new FlowLayout(Alignment.LEFT, Size.MEDIUM));
add(new WLabel("Group"));
panel.add(new WLabel("A", rb4));
panel.add(rb4);
panel.add(new WLabel("B", rb5));
panel.add(rb5);
panel.add(new WLabel("C", rb6));
panel.add(rb6);
panel.add(group);
this.add(panel);
}
}
| bordertechorg/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/RadioButtonExample.java | Java | gpl-3.0 | 2,008 |
/*
* Crafter Studio Web-content authoring solution
* Copyright (C) 2007-2016 Crafter Software Corporation.
*
* 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 org.craftercms.studio.impl.v1.service.activity;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.craftercms.commons.validation.annotations.param.ValidateIntegerParam;
import org.craftercms.commons.validation.annotations.param.ValidateParams;
import org.craftercms.commons.validation.annotations.param.ValidateSecurePathParam;
import org.craftercms.commons.validation.annotations.param.ValidateStringParam;
import org.craftercms.studio.api.v1.constant.StudioConstants;
import org.craftercms.studio.api.v1.constant.DmConstants;
import org.craftercms.studio.api.v1.dal.AuditFeed;
import org.craftercms.studio.api.v1.dal.AuditFeedMapper;
import org.craftercms.studio.api.v1.exception.ServiceException;
import org.craftercms.studio.api.v1.exception.SiteNotFoundException;
import org.craftercms.studio.api.v1.log.Logger;
import org.craftercms.studio.api.v1.log.LoggerFactory;
import org.craftercms.studio.api.v1.service.AbstractRegistrableService;
import org.craftercms.studio.api.v1.service.activity.ActivityService;
import org.craftercms.studio.api.v1.service.content.ContentService;
import org.craftercms.studio.api.v1.service.deployment.DeploymentService;
import org.craftercms.studio.api.v1.service.objectstate.State;
import org.craftercms.studio.api.v1.service.site.SiteService;
import org.craftercms.studio.api.v1.to.ContentItemTO;
import org.craftercms.studio.api.v1.util.DebugUtils;
import org.craftercms.studio.api.v1.util.StudioConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.craftercms.studio.api.v1.service.security.SecurityService;
import static org.craftercms.studio.api.v1.constant.StudioConstants.CONTENT_TYPE_PAGE;
import static org.craftercms.studio.api.v1.util.StudioConfiguration.ACTIVITY_USERNAME_CASE_SENSITIVE;
public class ActivityServiceImpl extends AbstractRegistrableService implements ActivityService {
private static final Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);
protected static final int MAX_LEN_USER_ID = 255; // needs to match schema:
// feed_user_id,
// post_user_id
protected static final int MAX_LEN_SITE_ID = 255; // needs to match schema:
// site_network
protected static final int MAX_LEN_ACTIVITY_TYPE = 255; // needs to match
// schema:
// activity_type
protected static final int MAX_LEN_ACTIVITY_DATA = 4000; // needs to match
// schema:
// activity_data
protected static final int MAX_LEN_APP_TOOL_ID = 36; // needs to match
// schema: app_tool
/** activity post properties **/
protected static final String ACTIVITY_PROP_ACTIVITY_SUMMARY = "activitySummary";
protected static final String ACTIVITY_PROP_ID = "id";
protected static final String ACTIVITY_PROP_POST_DATE = "postDate";
protected static final String ACTIVITY_PROP_USER = "user";
protected static final String ACTIVITY_PROP_FEEDUSER = "feedUserId";
protected static final String ACTIVITY_PROP_CONTENTID = "contentId";
/** activity feed format **/
protected static final String ACTIVITY_FEED_FORMAT = "json";
@Autowired
protected AuditFeedMapper auditFeedMapper;
protected SiteService siteService;
protected ContentService contentService;
protected SecurityService securityService;
protected StudioConfiguration studioConfiguration;
protected DeploymentService deploymentService;
@Override
public void register() {
getServicesManager().registerService(ActivityService.class, this);
}
@Override
@ValidateParams
public void postActivity(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateSecurePathParam(name = "contentId") String contentId, ActivityType activity, ActivitySource source, Map<String,String> extraInfo) {
JSONObject activityPost = new JSONObject();
activityPost.put(ACTIVITY_PROP_USER, user);
activityPost.put(ACTIVITY_PROP_ID, contentId);
if (extraInfo != null) {
activityPost.putAll(extraInfo);
}
String contentType = null;
if (extraInfo != null) {
contentType = extraInfo.get(DmConstants.KEY_CONTENT_TYPE);
}
postActivity(activity.toString(), source.toString(), site, null, activityPost.toString(),contentId,contentType, user);
}
private void postActivity(String activityType, String activitySource, String siteNetwork, String appTool, String activityData,
String contentId, String contentType, String approver) {
String currentUser = (StringUtils.isEmpty(approver)) ? securityService.getCurrentUser() : approver;
try {
// optional - default to empty string
if (siteNetwork == null) {
siteNetwork = "";
} else if (siteNetwork.length() > MAX_LEN_SITE_ID) {
throw new ServiceException("Invalid site network - exceeds " + MAX_LEN_SITE_ID + " chars: "
+ siteNetwork);
}
// optional - default to empty string
if (appTool == null) {
appTool = "";
} else if (appTool.length() > MAX_LEN_APP_TOOL_ID) {
throw new ServiceException("Invalid app tool - exceeds " + MAX_LEN_APP_TOOL_ID + " chars: " + appTool);
}
// required
if (StringUtils.isEmpty(activityType)) {
throw new ServiceException("Invalid activity type - activity type is empty");
} else if (activityType.length() > MAX_LEN_ACTIVITY_TYPE) {
throw new ServiceException("Invalid activity type - exceeds " + MAX_LEN_ACTIVITY_TYPE + " chars: "
+ activityType);
}
// optional - default to empty string
if (activityData == null) {
activityData = "";
} else if (activityType.length() > MAX_LEN_ACTIVITY_DATA) {
throw new ServiceException("Invalid activity data - exceeds " + MAX_LEN_ACTIVITY_DATA + " chars: "
+ activityData);
}
// required
if (StringUtils.isEmpty(currentUser)) {
throw new ServiceException("Invalid user - user is empty");
} else if (currentUser.length() > MAX_LEN_USER_ID) {
throw new ServiceException("Invalid user - exceeds " + MAX_LEN_USER_ID + " chars: " + currentUser);
} else {
// user names are not case-sensitive
currentUser = currentUser.toLowerCase();
}
if (contentType == null) {
contentType = CONTENT_TYPE_PAGE;
}
} catch (ServiceException e) {
// log error and throw exception
logger.error("Error in getting feeds", e);
}
try {
ZonedDateTime postDate = ZonedDateTime.now(ZoneOffset.UTC);
AuditFeed activityPost = new AuditFeed();
activityPost.setUserId(currentUser);
activityPost.setSiteNetwork(siteNetwork);
activityPost.setSummary(activityData);
activityPost.setType(activityType);
activityPost.setCreationDate(postDate);
activityPost.setModifiedDate(postDate);
activityPost.setSummaryFormat("json");
activityPost.setContentId(contentId);
activityPost.setContentType(contentType);
activityPost.setSource(activitySource);
try {
activityPost.setCreationDate(ZonedDateTime.now(ZoneOffset.UTC));
long postId = insertFeedEntry(activityPost);
activityPost.setId(postId);
logger.debug("Posted: " + activityPost);
} catch (Exception e) {
throw new ServiceException("Failed to post activity: " + e, e);
}
}
catch (ServiceException e) {
// log error, subsume exception (for post activity)
logger.error("Error in posting feed", e);
}
}
private long insertFeedEntry(AuditFeed activityFeed) {
DebugUtils.addDebugStack(logger);
logger.debug("Insert activity " + activityFeed.getContentId());
Long id = auditFeedMapper.insertActivityFeed(activityFeed);
return (id != null ? id : -1);
}
@Override
@ValidateParams
public void renameContentId(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "oldUrl") String oldUrl, @ValidateSecurePathParam(name = "newUrl") String newUrl) {
DebugUtils.addDebugStack(logger);
logger.debug("Rename " + oldUrl + " to " + newUrl);
Map<String, String> params = new HashMap<String, String>();
params.put("newPath", newUrl);
params.put("site", site);
params.put("oldPath", oldUrl);
auditFeedMapper.renameContent(params);
}
@Override
@ValidateParams
public List<ContentItemTO> getActivities(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateIntegerParam(name = "num") int num, @ValidateStringParam(name = "sort") String sort, boolean ascending, boolean excludeLive, @ValidateStringParam(name = "filterType") String filterType) throws ServiceException {
int startPos = 0;
List<ContentItemTO> contentItems = new ArrayList<ContentItemTO>();
boolean hasMoreItems = true;
while(contentItems.size() < num && hasMoreItems){
int remainingItems = num - contentItems.size();
hasMoreItems = getActivityFeeds(user, site, startPos, num , filterType, excludeLive,contentItems,remainingItems);
startPos = startPos+num;
}
if(contentItems.size() > num){
return contentItems.subList(0, num);
}
return contentItems;
}
/**
*
* Returns all non-live items if hideLiveItems is true, else should return all feeds back
*
*/
protected boolean getActivityFeeds(String user, String site,int startPos, int size, String filterType,boolean hideLiveItems,List<ContentItemTO> contentItems,int remainingItem){
List<String> activityFeedEntries = new ArrayList<String>();
if (!getUserNamesAreCaseSensitive()) {
user = user.toLowerCase();
}
List<AuditFeed> activityFeeds = null;
activityFeeds = selectUserFeedEntries(user, ACTIVITY_FEED_FORMAT, site, startPos, size,
filterType, hideLiveItems);
for (AuditFeed activityFeed : activityFeeds) {
activityFeedEntries.add(activityFeed.getJSONString());
}
boolean hasMoreItems=true;
//if number of items returned is less than size it means that table has no more records
if(activityFeedEntries.size()<size){
hasMoreItems=false;
}
if (activityFeedEntries != null && activityFeedEntries.size() > 0) {
for (int index = 0; index < activityFeedEntries.size() && remainingItem!=0; index++) {
JSONObject feedObject = JSONObject.fromObject(activityFeedEntries.get(index));
String id = (feedObject.containsKey(ACTIVITY_PROP_CONTENTID)) ? feedObject.getString(ACTIVITY_PROP_CONTENTID) : "";
ContentItemTO item = createActivityItem(site, feedObject, id);
item.published = true;
item.setPublished(true);
ZonedDateTime pubDate = deploymentService.getLastDeploymentDate(site, id);
item.publishedDate = pubDate;
item.setPublishedDate(pubDate);
contentItems.add(item);
remainingItem--;
}
}
logger.debug("Total Item post live filter : " + contentItems.size() + " hasMoreItems : "+hasMoreItems);
return hasMoreItems;
}
/**
* create an activity from the given feed
*
* @param site
* @param feedObject
* @return activity
*/
protected ContentItemTO createActivityItem(String site, JSONObject feedObject, String id) {
try {
ContentItemTO item = contentService.getContentItem(site, id, 0);
if(item == null || item.isDeleted()) {
item = contentService.createDummyDmContentItemForDeletedNode(site, id);
String modifier = (feedObject.containsKey(ACTIVITY_PROP_FEEDUSER)) ? feedObject.getString(ACTIVITY_PROP_FEEDUSER) : "";
if(modifier != null && !modifier.isEmpty()) {
item.user = modifier;
}
String activitySummary = (feedObject.containsKey(ACTIVITY_PROP_ACTIVITY_SUMMARY)) ? feedObject.getString(ACTIVITY_PROP_ACTIVITY_SUMMARY) : "";
JSONObject summaryObject = JSONObject.fromObject(activitySummary);
if (summaryObject.containsKey(DmConstants.KEY_CONTENT_TYPE)) {
String contentType = (String)summaryObject.get(DmConstants.KEY_CONTENT_TYPE);
item.contentType = contentType;
}
if(summaryObject.containsKey(StudioConstants.INTERNAL_NAME)) {
String internalName = (String)summaryObject.get(StudioConstants.INTERNAL_NAME);
item.internalName = internalName;
}
if(summaryObject.containsKey(StudioConstants.BROWSER_URI)) {
String browserUri = (String)summaryObject.get(StudioConstants.BROWSER_URI);
item.browserUri = browserUri;
}
item.setLockOwner("");
}
String postDate = (feedObject.containsKey(ACTIVITY_PROP_POST_DATE)) ? feedObject.getString(ACTIVITY_PROP_POST_DATE) : "";
ZonedDateTime editedDate = ZonedDateTime.parse(postDate);
if (editedDate != null) {
item.eventDate = editedDate.withZoneSameInstant(ZoneOffset.UTC);
} else {
item.eventDate = editedDate;
}
return item;
} catch (Exception e) {
logger.error("Error fetching content item for [" + id + "]", e.getMessage());
return null;
}
}
private List<AuditFeed> selectUserFeedEntries(String feedUserId, String format, String siteId, int startPos, int feedSize, String contentType, boolean hideLiveItems) {
HashMap<String,Object> params = new HashMap<String,Object>();
params.put("userId",feedUserId);
params.put("summaryFormat",format);
params.put("siteNetwork",siteId);
params.put("startPos", startPos);
params.put("feedSize", feedSize);
params.put("activities", Arrays.asList(ActivityType.CREATED, ActivityType.DELETED, ActivityType.UPDATED, ActivityType.MOVED));
if(StringUtils.isNotEmpty(contentType) && !contentType.toLowerCase().equals("all")){
params.put("contentType",contentType.toLowerCase());
}
if (hideLiveItems) {
List<String> statesValues = new ArrayList<String>();
for (State state : State.LIVE_STATES) {
statesValues.add(state.name());
}
params.put("states", statesValues);
return auditFeedMapper.selectUserFeedEntriesHideLive(params);
} else {
return auditFeedMapper.selectUserFeedEntries(params);
}
}
@Override
@ValidateParams
public AuditFeed getDeletedActivity(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "path") String path) {
HashMap<String,String> params = new HashMap<String,String>();
params.put("contentId", path);
params.put("siteNetwork", site);
String activityType = ActivityType.DELETED.toString();
params.put("activityType", activityType);
return auditFeedMapper.getDeletedActivity(params);
}
@Override
@ValidateParams
public void deleteActivitiesForSite(@ValidateStringParam(name = "site") String site) {
Map<String, String> params = new HashMap<String, String>();
params.put("site", site);
auditFeedMapper.deleteActivitiesForSite(params);
}
@Override
@ValidateParams
public List<AuditFeed> getAuditLogForSite(@ValidateStringParam(name = "site") String site, @ValidateIntegerParam(name = "start") int start, @ValidateIntegerParam(name = "number") int number, @ValidateStringParam(name = "user") String user, List<String> actions)
throws SiteNotFoundException {
if (!siteService.exists(site)) {
throw new SiteNotFoundException();
} else {
Map<String, Object> params = new HashMap<String, Object>();
params.put("site", site);
params.put("start", start);
params.put("number", number);
if (StringUtils.isNotEmpty(user)) {
params.put("user", user);
}
if (CollectionUtils.isNotEmpty(actions)) {
params.put("actions", actions);
}
return auditFeedMapper.getAuditLogForSite(params);
}
}
@Override
@ValidateParams
public long getAuditLogForSiteTotal(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, List<String> actions)
throws SiteNotFoundException {
if (!siteService.exists(site)) {
throw new SiteNotFoundException();
} else {
Map<String, Object> params = new HashMap<String, Object>();
params.put("site", site);
if (StringUtils.isNotEmpty(user)) {
params.put("user", user);
}
if (CollectionUtils.isNotEmpty(actions)) {
params.put("actions", actions);
}
return auditFeedMapper.getAuditLogForSiteTotal(params);
}
}
public boolean getUserNamesAreCaseSensitive() {
boolean toReturn = Boolean.parseBoolean(studioConfiguration.getProperty(ACTIVITY_USERNAME_CASE_SENSITIVE));
return toReturn;
}
public SiteService getSiteService() {
return siteService;
}
public void setSiteService(final SiteService siteService) {
this.siteService = siteService;
}
public void setContentService(ContentService contentService) {
this.contentService = contentService;
}
public SecurityService getSecurityService() {return securityService; }
public void setSecurityService(SecurityService securityService) { this.securityService = securityService; }
public StudioConfiguration getStudioConfiguration() { return studioConfiguration; }
public void setStudioConfiguration(StudioConfiguration studioConfiguration) { this.studioConfiguration = studioConfiguration; }
public DeploymentService getDeploymentService() { return deploymentService; }
public void setDeploymentService(DeploymentService deploymentService) { this.deploymentService = deploymentService; }
}
| dejan-brkic/studio2 | src/main/java/org/craftercms/studio/impl/v1/service/activity/ActivityServiceImpl.java | Java | gpl-3.0 | 20,008 |
package org.thoughtcrime.securesms.testutil;
import org.signal.core.util.logging.Log;
public final class SystemOutLogger extends Log.Logger {
@Override
public void v(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('v', tag, message, t);
}
@Override
public void d(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('d', tag, message, t);
}
@Override
public void i(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('i', tag, message, t);
}
@Override
public void w(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('w', tag, message, t);
}
@Override
public void e(String tag, String message, Throwable t, boolean keepLonger) {
printlnFormatted('e', tag, message, t);
}
@Override
public void flush() { }
private void printlnFormatted(char level, String tag, String message, Throwable t) {
System.out.println(format(level, tag, message, t));
}
private String format(char level, String tag, String message, Throwable t) {
if (t != null) {
return String.format("%c[%s] %s %s:%s", level, tag, message, t.getClass().getSimpleName(), t.getMessage());
} else {
return String.format("%c[%s] %s", level, tag, message);
}
}
}
| WhisperSystems/Signal-Android | app/src/test/java/org/thoughtcrime/securesms/testutil/SystemOutLogger.java | Java | gpl-3.0 | 1,332 |
// Openbravo POS is a point of sales application designed for touch screens.
// Copyright (C) 2007-2009 Openbravo, S.L.
// http://www.openbravo.com/product/pos
//
// This file is part of Openbravo POS.
//
// Openbravo POS 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.
//
// Openbravo POS 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 Openbravo POS. If not, see <http://www.gnu.org/licenses/>.
package com.openbravo.pos.printer.escpos;
public class CodesIthaca extends Codes {
private static final byte[] INITSEQUENCE = {};
private static final byte[] CHAR_SIZE_0 = {0x1D, 0x21, 0x00};
private static final byte[] CHAR_SIZE_1 = {0x1D, 0x21, 0x01};
private static final byte[] CHAR_SIZE_2 = {0x1D, 0x21, 0x30};
private static final byte[] CHAR_SIZE_3 = {0x1D, 0x21, 0x31};
public static final byte[] BOLD_SET = {0x1B, 0x45, 0x01};
public static final byte[] BOLD_RESET = {0x1B, 0x45, 0x00};
public static final byte[] UNDERLINE_SET = {0x1B, 0x2D, 0x01};
public static final byte[] UNDERLINE_RESET = {0x1B, 0x2D, 0x00};
private static final byte[] OPEN_DRAWER = {0x1B, 0x78, 0x01};
private static final byte[] PARTIAL_CUT = {0x1B, 0x50, 0x00};
private static final byte[] IMAGE_HEADER = {0x1D, 0x76, 0x30, 0x03};
private static final byte[] NEW_LINE = {0x0D, 0x0A}; // Print and carriage return
/** Creates a new instance of CodesIthaca */
public CodesIthaca() {
}
public byte[] getInitSequence() { return INITSEQUENCE; }
public byte[] getSize0() { return CHAR_SIZE_0; }
public byte[] getSize1() { return CHAR_SIZE_1; }
public byte[] getSize2() { return CHAR_SIZE_2; }
public byte[] getSize3() { return CHAR_SIZE_3; }
public byte[] getBoldSet() { return BOLD_SET; }
public byte[] getBoldReset() { return BOLD_RESET; }
public byte[] getUnderlineSet() { return UNDERLINE_SET; }
public byte[] getUnderlineReset() { return UNDERLINE_RESET; }
public byte[] getOpenDrawer() { return OPEN_DRAWER; }
public byte[] getCutReceipt() { return PARTIAL_CUT; }
public byte[] getNewLine() { return NEW_LINE; }
public byte[] getImageHeader() { return IMAGE_HEADER; }
public int getImageWidth() { return 256; }
}
| ZarGate/OpenbravoPOS | src-pos/com/openbravo/pos/printer/escpos/CodesIthaca.java | Java | gpl-3.0 | 2,760 |
-----------------------------------
-- Area: Nashmau
-- NPC: Yuyuroon
-- Standard Info NPC
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0109);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| salamader/ffxi-a | scripts/zones/Nashmau/npcs/Yuyuroon.lua | Lua | gpl-3.0 | 858 |
#ifndef UTIL_BIT_PACKING__
#define UTIL_BIT_PACKING__
/* Bit-level packing routines */
#include <assert.h>
#ifdef __APPLE__
#include <architecture/byte_order.h>
#elif __linux__
#include <endian.h>
#else
#include <arpa/nameser_compat.h>
#endif
#include <inttypes.h>
namespace util {
/* WARNING WARNING WARNING:
* The write functions assume that memory is zero initially. This makes them
* faster and is the appropriate case for mmapped language model construction.
* These routines assume that unaligned access to uint64_t is fast and that
* storage is little endian. This is the case on x86_64. I'm not sure how
* fast unaligned 64-bit access is on x86 but my target audience is large
* language models for which 64-bit is necessary.
*
* Call the BitPackingSanity function to sanity check. Calling once suffices,
* but it may be called multiple times when that's inconvenient.
*/
// Fun fact: __BYTE_ORDER is wrong on Solaris Sparc, but the version without __ is correct.
#if BYTE_ORDER == LITTLE_ENDIAN
inline uint8_t BitPackShift(uint8_t bit, uint8_t /*length*/) {
return bit;
}
#elif BYTE_ORDER == BIG_ENDIAN
inline uint8_t BitPackShift(uint8_t bit, uint8_t length) {
return 64 - length - bit;
}
#else
#error "Bit packing code isn't written for your byte order."
#endif
inline uint64_t ReadOff(const void *base, uint64_t bit_off) {
return *reinterpret_cast<const uint64_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3));
}
/* Pack integers up to 57 bits using their least significant digits.
* The length is specified using mask:
* Assumes mask == (1 << length) - 1 where length <= 57.
*/
inline uint64_t ReadInt57(const void *base, uint64_t bit_off, uint8_t length, uint64_t mask) {
return (ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, length)) & mask;
}
/* Assumes value < (1 << length) and length <= 57.
* Assumes the memory is zero initially.
*/
inline void WriteInt57(void *base, uint64_t bit_off, uint8_t length, uint64_t value) {
*reinterpret_cast<uint64_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |=
(value << BitPackShift(bit_off & 7, length));
}
/* Same caveats as above, but for a 25 bit limit. */
inline uint32_t ReadInt25(const void *base, uint64_t bit_off, uint8_t length, uint32_t mask) {
return (*reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3)) >> BitPackShift(bit_off & 7, length)) & mask;
}
inline void WriteInt25(void *base, uint64_t bit_off, uint8_t length, uint32_t value) {
*reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |=
(value << BitPackShift(bit_off & 7, length));
}
typedef union { float f; uint32_t i; } FloatEnc;
inline float ReadFloat32(const void *base, uint64_t bit_off) {
FloatEnc encoded;
encoded.i = ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 32);
return encoded.f;
}
inline void WriteFloat32(void *base, uint64_t bit_off, float value) {
FloatEnc encoded;
encoded.f = value;
WriteInt57(base, bit_off, 32, encoded.i);
}
const uint32_t kSignBit = 0x80000000;
inline void SetSign(float &to) {
FloatEnc enc;
enc.f = to;
enc.i |= kSignBit;
to = enc.f;
}
inline void UnsetSign(float &to) {
FloatEnc enc;
enc.f = to;
enc.i &= ~kSignBit;
to = enc.f;
}
inline float ReadNonPositiveFloat31(const void *base, uint64_t bit_off) {
FloatEnc encoded;
encoded.i = ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 31);
// Sign bit set means negative.
encoded.i |= kSignBit;
return encoded.f;
}
inline void WriteNonPositiveFloat31(void *base, uint64_t bit_off, float value) {
FloatEnc encoded;
encoded.f = value;
encoded.i &= ~kSignBit;
WriteInt57(base, bit_off, 31, encoded.i);
}
void BitPackingSanity();
// Return bits required to store integers upto max_value. Not the most
// efficient implementation, but this is only called a few times to size tries.
uint8_t RequiredBits(uint64_t max_value);
struct BitsMask {
static BitsMask ByMax(uint64_t max_value) {
BitsMask ret;
ret.FromMax(max_value);
return ret;
}
static BitsMask ByBits(uint8_t bits) {
BitsMask ret;
ret.bits = bits;
ret.mask = (1ULL << bits) - 1;
return ret;
}
void FromMax(uint64_t max_value) {
bits = RequiredBits(max_value);
mask = (1ULL << bits) - 1;
}
uint8_t bits;
uint64_t mask;
};
} // namespace util
#endif // UTIL_BIT_PACKING__
| kpm/kenlm-rb | util/bit_packing.hh | C++ | gpl-3.0 | 4,424 |
#region Copyright & License Information
/*
* Copyright 2007-2011 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. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using OpenRA.FileFormats;
using OpenRA.Traits;
namespace OpenRA.Mods.RA
{
[Desc("Used to waypoint units after production or repair is finished.")]
public class RallyPointInfo : ITraitInfo
{
public readonly int[] RallyPoint = { 1, 3 };
public readonly string IndicatorPalettePrefix = "player";
public object Create(ActorInitializer init) { return new RallyPoint(init.self, this); }
}
public class RallyPoint : IIssueOrder, IResolveOrder, ISync
{
[Sync] public CPos rallyPoint;
public int nearEnough = 1;
public RallyPoint(Actor self, RallyPointInfo info)
{
rallyPoint = self.Location + new CVec(info.RallyPoint[0], info.RallyPoint[1]);
self.World.AddFrameEndTask(w => w.Add(new Effects.RallyPoint(self, info.IndicatorPalettePrefix)));
}
public IEnumerable<IOrderTargeter> Orders
{
get { yield return new RallyPointOrderTargeter(); }
}
public Order IssueOrder( Actor self, IOrderTargeter order, Target target, bool queued )
{
if( order.OrderID == "SetRallyPoint" )
return new Order(order.OrderID, self, false) { TargetLocation = target.CenterPosition.ToCPos() };
return null;
}
public void ResolveOrder( Actor self, Order order )
{
if( order.OrderString == "SetRallyPoint" )
rallyPoint = order.TargetLocation;
}
class RallyPointOrderTargeter : IOrderTargeter
{
public string OrderID { get { return "SetRallyPoint"; } }
public int OrderPriority { get { return 0; } }
public bool CanTarget(Actor self, Target target, List<Actor> othersAtTarget, TargetModifiers modifiers, ref string cursor)
{
if (target.Type != TargetType.Terrain)
return false;
var location = target.CenterPosition.ToCPos();
if (self.World.Map.IsInMap(location))
{
cursor = "ability";
return true;
}
return false;
}
public bool IsQueued { get { return false; } } // unused
}
}
}
| obrakmann/OpenRA | OpenRA.Mods.RA/RallyPoint.cs | C# | gpl-3.0 | 2,264 |
<!--
Data Source: http://www.htmlhelp.com/reference/html40/entities/symbols.html
HTML To Convert JSON http://convertjson.com/html-table-to-json.htm
Creator : ARGE|LOG github@argelog.com.tr
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>summernote</title>
<!-- include jquery -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<!-- include libs stylesheets -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.js"></script>
<!-- include summernote -->
<link rel="stylesheet" href="../dist/summernote-bs4.css">
<script type="text/javascript" src="../dist/summernote-bs4.js"></script>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('.summernote').summernote({
height: 200,
hint: {
match: /=(\w{0,})$/,
search: function(keyword, callback) {
$.ajax({
url: 'symbols_mathematical-symbols_Greek-letters.json?v=1'
}).then(function (data) {
callback(data.filter(function(item){return item.Character.indexOf(keyword)>-1 || item.FIELD6.indexOf(keyword)>-1;}));
});
},
content: function(item) {
return item.FIELD6;
},
template: function(item) {
return '[<strong>' + item.FIELD6 + '</strong>] ' + item.Character;
}
}
});
});
</script>
</head>
<body>
<textarea class="summernote">type #su</textarea>
</body>
</html>
| Yunfeng/h5buk | public/assets/vendor/summernote/examples/hint-symbols_mathematical-symbols_Greek-letters.html | HTML | gpl-3.0 | 1,895 |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "namespaces" collection of methods.
* Typical usage is:
* <code>
* $runService = new Google_Service_CloudRun(...);
* $namespaces = $runService->namespaces;
* </code>
*/
class Google_Service_CloudRun_Resource_ProjectsLocationsNamespaces extends Google_Service_Resource
{
/**
* Rpc to get information about a namespace. (namespaces.get)
*
* @param string $name Required. The name of the namespace being retrieved. If
* needed, replace {namespace_id} with the project ID.
* @param array $optParams Optional parameters.
* @return Google_Service_CloudRun_RunNamespace
*/
public function get($name, $optParams = array())
{
$params = array('name' => $name);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_CloudRun_RunNamespace");
}
/**
* Rpc to update a namespace. (namespaces.patch)
*
* @param string $name Required. The name of the namespace being retrieved. If
* needed, replace {namespace_id} with the project ID.
* @param Google_Service_CloudRun_RunNamespace $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string updateMask Required. Indicates which fields in the provided
* namespace to update. This field is currently unused.
* @return Google_Service_CloudRun_RunNamespace
*/
public function patch($name, Google_Service_CloudRun_RunNamespace $postBody, $optParams = array())
{
$params = array('name' => $name, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_CloudRun_RunNamespace");
}
}
| ftisunpar/BlueTape | vendor/google/apiclient-services/src/Google/Service/CloudRun/Resource/ProjectsLocationsNamespaces.php | PHP | gpl-3.0 | 2,264 |
<?php
/**
* Mahara: Electronic portfolio, weblog, resume builder and social networking
* Copyright (C) 2006-2009 Catalyst IT Ltd and others; see:
* http://wiki.mahara.org/Contributors
*
* 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 mahara
* @subpackage lang
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL
* @copyright (C) 2006-2009 Catalyst IT Ltd http://catalyst.net.nz
*
*/
defined('INTERNAL') || die();
$string['pluginname'] = 'Profile';
$string['profile'] = 'Profile';
$string['mandatory'] = 'Mandatory';
$string['public'] = 'Public';
$string['aboutdescription'] = 'Enter your real first and last name here. If you want to show a different name to people in the system, put that name in as your display name.';
$string['infoisprivate'] = 'This information is private until you include it in a page that is shared with others.';
$string['viewmyprofile'] = 'View my profile';
// profile categories
$string['aboutme'] = 'About me';
$string['contact'] = 'Contact information';
$string['messaging'] = 'Messaging';
$string['general'] = 'General';
// profile fields
$string['firstname'] = 'First Name';
$string['lastname'] = 'Last Name';
$string['fullname'] = 'Full Name';
$string['institution'] = 'Institution';
$string['studentid'] = 'Student ID';
$string['preferredname'] = 'Display Name';
$string['introduction'] = 'Introduction';
$string['email'] = 'Email Address';
$string['maildisabled'] = 'Email Disabled';
$string['officialwebsite'] = 'Official Website Address';
$string['personalwebsite'] = 'Personal Website Address';
$string['blogaddress'] = 'Blog Address';
$string['address'] = 'Postal Address';
$string['town'] = 'Town';
$string['city'] = 'City/Region';
$string['country'] = 'Country';
$string['homenumber'] = 'Home Phone';
$string['businessnumber'] = 'Business Phone';
$string['mobilenumber'] = 'Mobile Phone';
$string['faxnumber'] = 'Fax Number';
$string['icqnumber'] = 'ICQ Number';
$string['msnnumber'] = 'MSN Chat';
$string['aimscreenname'] = 'AIM Screen Name';
$string['yahoochat'] = 'Yahoo Chat';
$string['skypeusername'] = 'Skype Username';
$string['jabberusername'] = 'Jabber Username';
$string['occupation'] = 'Occupation';
$string['industry'] = 'Industry';
// Field names for view user and search user display
$string['name'] = 'Name';
$string['principalemailaddress'] = 'Primary email';
$string['emailaddress'] = 'Alternative email';
$string['saveprofile'] = 'Save Profile';
$string['profilesaved'] = 'Profile saved successfully';
$string['profilefailedsaved'] = 'Profile saving failed';
$string['emailvalidation_subject'] = 'Email validation';
$string['emailvalidation_body'] = <<<EOF
Hello %s,
You have added email address %s to your user account in Mahara. Please visit the link below to activate this address.
%s
If this email belongs to you but you have not requested adding it to your Mahara account, follow the link below to decline email activation.
%s
EOF;
$string['validationemailwillbesent'] = 'a validation email will be sent when you save your profile';
$string['validationemailsent'] = 'a validation email has been sent';
$string['emailactivation'] = 'Email Activation';
$string['emailactivationsucceeded'] = 'Email Activation Successful';
$string['emailalreadyactivated'] = 'Email already activiated';
$string['emailactivationfailed'] = 'Email Activation Failed';
$string['emailactivationdeclined'] = 'Email Activation Declined Successfully';
$string['verificationlinkexpired'] = 'Verification link expired';
$string['invalidemailaddress'] = 'Invalid email address';
$string['unvalidatedemailalreadytaken'] = 'The e-mail address you are trying to validate is already taken';
$string['addbutton'] = 'Add';
$string['emailingfailed'] = 'Profile saved, but emails were not sent to: %s';
$string['loseyourchanges'] = 'Lose your changes?';
$string['Title'] = 'Title';
$string['Created'] = 'Created';
$string['Description'] = 'Description';
$string['Download'] = 'Download';
$string['lastmodified'] = 'Last Modified';
$string['Owner'] = 'Owner';
$string['Preview'] = 'Preview';
$string['Size'] = 'Size';
$string['Type'] = 'Type';
$string['profileinformation'] = 'Profile Information';
$string['profilepage'] = 'Profile Page';
$string['viewprofilepage'] = 'View profile page';
$string['viewallprofileinformation'] = 'View all profile information';
| plymouthstate/mahara | htdocs/artefact/internal/lang/en.utf8/artefact.internal.php | PHP | gpl-3.0 | 4,994 |
#include <parmetislib.h>
/* Byte-wise swap two items of size SIZE. */
#define QSSWAP(a, b, stmp) do { stmp = (a); (a) = (b); (b) = stmp; } while (0)
/* Discontinue quicksort algorithm when partition gets below this size.
This particular magic number was chosen to work best on a Sun 4/260. */
#define MAX_THRESH 20
/* Stack node declarations used to store unfulfilled partition obligations. */
typedef struct {
KeyValueType *lo;
KeyValueType *hi;
} stack_node;
/* The next 4 #defines implement a very fast in-line stack abstraction. */
#define STACK_SIZE (8 * sizeof(unsigned long int))
#define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
#define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
#define STACK_NOT_EMPTY (stack < top)
void ikeyvalsort(int total_elems, KeyValueType *pbase)
{
KeyValueType pivot, stmp;
if (total_elems == 0)
/* Avoid lossage with unsigned arithmetic below. */
return;
if (total_elems > MAX_THRESH) {
KeyValueType *lo = pbase;
KeyValueType *hi = &lo[total_elems - 1];
stack_node stack[STACK_SIZE]; /* Largest size needed for 32-bit int!!! */
stack_node *top = stack + 1;
while (STACK_NOT_EMPTY) {
KeyValueType *left_ptr;
KeyValueType *right_ptr;
KeyValueType *mid = lo + ((hi - lo) >> 1);
if (mid->key < lo->key || (mid->key == lo->key && mid->val < lo->val))
QSSWAP(*mid, *lo, stmp);
if (hi->key < mid->key || (hi->key == mid->key && hi->val < mid->val))
QSSWAP(*mid, *hi, stmp);
else
goto jump_over;
if (mid->key < lo->key || (mid->key == lo->key && mid->val < lo->val))
QSSWAP(*mid, *lo, stmp);
jump_over:;
pivot = *mid;
left_ptr = lo + 1;
right_ptr = hi - 1;
/* Here's the famous ``collapse the walls'' section of quicksort.
Gotta like those tight inner loops! They are the main reason
that this algorithm runs much faster than others. */
do {
while (left_ptr->key < pivot.key || (left_ptr->key == pivot.key && left_ptr->val < pivot.val))
left_ptr++;
while (pivot.key < right_ptr->key || (pivot.key == right_ptr->key && pivot.val < right_ptr->val))
right_ptr--;
if (left_ptr < right_ptr) {
QSSWAP (*left_ptr, *right_ptr, stmp);
left_ptr++;
right_ptr--;
}
else if (left_ptr == right_ptr) {
left_ptr++;
right_ptr--;
break;
}
} while (left_ptr <= right_ptr);
/* Set up pointers for next iteration. First determine whether
left and right partitions are below the threshold size. If so,
ignore one or both. Otherwise, push the larger partition's
bounds on the stack and continue sorting the smaller one. */
if ((size_t) (right_ptr - lo) <= MAX_THRESH) {
if ((size_t) (hi - left_ptr) <= MAX_THRESH)
/* Ignore both small partitions. */
POP (lo, hi);
else
/* Ignore small left partition. */
lo = left_ptr;
}
else if ((size_t) (hi - left_ptr) <= MAX_THRESH)
/* Ignore small right partition. */
hi = right_ptr;
else if ((right_ptr - lo) > (hi - left_ptr)) {
/* Push larger left partition indices. */
PUSH (lo, right_ptr);
lo = left_ptr;
}
else {
/* Push larger right partition indices. */
PUSH (left_ptr, hi);
hi = right_ptr;
}
}
}
/* Once the BASE_PTR array is partially sorted by quicksort the rest
is completely sorted using insertion sort, since this is efficient
for partitions below MAX_THRESH size. BASE_PTR points to the beginning
of the array to sort, and END_PTR points at the very last element in
the array (*not* one beyond it!). */
{
KeyValueType *end_ptr = &pbase[total_elems - 1];
KeyValueType *tmp_ptr = pbase;
KeyValueType *thresh = (end_ptr < pbase + MAX_THRESH ? end_ptr : pbase + MAX_THRESH);
register KeyValueType *run_ptr;
/* Find smallest element in first threshold and place it at the
array's beginning. This is the smallest array element,
and the operation speeds up insertion sort's inner loop. */
for (run_ptr = tmp_ptr + 1; run_ptr <= thresh; run_ptr++)
if (run_ptr->key < tmp_ptr->key || (run_ptr->key == tmp_ptr->key && run_ptr->val < tmp_ptr->val))
tmp_ptr = run_ptr;
if (tmp_ptr != pbase)
QSSWAP(*tmp_ptr, *pbase, stmp);
/* Insertion sort, running from left-hand-side up to right-hand-side. */
run_ptr = pbase + 1;
while (++run_ptr <= end_ptr) {
tmp_ptr = run_ptr - 1;
while (run_ptr->key < tmp_ptr->key || (run_ptr->key == tmp_ptr->key && run_ptr->val < tmp_ptr->val))
tmp_ptr--;
tmp_ptr++;
if (tmp_ptr != run_ptr) {
KeyValueType elmnt = *run_ptr;
KeyValueType *mptr;
for (mptr=run_ptr; mptr>tmp_ptr; mptr--)
*mptr = *(mptr-1);
*mptr = elmnt;
}
}
}
}
| DominicJones/cfdpack | lib/ParMetis-3.1.1/ParMETISLib/ikeyvalsort.c | C | gpl-3.0 | 4,929 |
/* This file is part of HSPlasma.
*
* HSPlasma 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.
*
* HSPlasma 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 HSPlasma. If not, see <http://www.gnu.org/licenses/>.
*/
#include "plSDL.h"
unsigned int plSDL::VariableLengthRead(hsStream* S, size_t size) {
if (size < 0x100)
return S->readByte();
else if (size < 0x10000)
return S->readShort();
else
return S->readInt();
}
void plSDL::VariableLengthWrite(hsStream* S, size_t size, unsigned int value) {
if (size < 0x100)
S->writeByte(value);
else if (size < 0x10000)
S->writeShort(value);
else
S->writeInt(value);
}
| NadnerbD/libhsplasma | core/SDL/plSDL.cpp | C++ | gpl-3.0 | 1,145 |
#Region "Microsoft.VisualBasic::593db87795bffd7fe72a1c6b208d9e4b, ..\sciBASIC#\mime\text%yaml\yaml\Syntax\Tag.vb"
' Author:
'
' asuka (amethyst.asuka@gcmodeller.org)
' xieguigang (xie.guigang@live.com)
' xie (genetics@smrucc.org)
'
' Copyright (c) 2016 GPL3 Licensed
'
'
' GNU GENERAL PUBLIC LICENSE (GPL3)
'
' 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/>.
#End Region
Imports System.Collections.Generic
Imports System.Text
Namespace Syntax
Public Class Tag
End Class
End Namespace
| amethyst-asuka/GCModeller | src/runtime/sciBASIC#/mime/text%yaml/yaml/Syntax/Tag.vb | Visual Basic | gpl-3.0 | 1,199 |
package com.redhat.jcliff;
import java.io.StringBufferInputStream;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.jboss.dmr.ModelNode;
public class DeploymentTest {
@Test
public void replace() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"} }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
Map<String,Set<String>> map=d.findDeploymentsToReplace(newDeployments,existingDeployments);
Assert.assertEquals("app2",map.get("app2").iterator().next());
Assert.assertNull(map.get("app1"));
Assert.assertEquals(1,map.size());
}
@Test
public void newdeployments() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"} }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
String[] news=d.getNewDeployments(newDeployments,existingDeployments.keys());
Assert.assertEquals(1,news.length);
Assert.assertEquals("app3",news[0]);
}
@Test
public void undeployments() throws Exception {
ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"}, \"app4\"=>\"deleted\" }"));
ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}"));
Deployment d=new Deployment(new Ctx(),true);
String[] und=d.getUndeployments(newDeployments,existingDeployments);
Assert.assertEquals(1,und.length);
Assert.assertEquals("app1",und[0]);
}
}
| mkrakowitzer/jcliff | src/test/java/com/redhat/jcliff/DeploymentTest.java | Java | gpl-3.0 | 2,307 |
# Contextual Identities
## What it does
Lists existing identities, lets you create new tabs with an identity and remove all tabs from an identity. For more information on contextual identities: https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers
## What it shows
How to use the contextualIdentities API. Please note: you must have contextualIdentities enabled. You can do that by going to about:config and setting the `privacy.userContext.enabled` preference to true. If you are using web-ext you can do this by running:
web-ext run --pref privacy.userContext.enabled=true
Icon from: https://www.iconfinder.com/icons/290119/card_id_identification_identity_profile_icon#size=128, License: "Free for commercial use".
| mdn/webextensions-examples | contextual-identities/README.md | Markdown | mpl-2.0 | 742 |
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by referrer-policy/generic/tools/generate.py using common/security-features/tools/template/test.release.html.template. -->
<html>
<head>
<title>Referrer-Policy: Referrer Policy is set to 'strict-origin-when-cross-origin'</title>
<meta charset='utf-8'>
<meta name="description" content="Check that a priori insecure subresource gets no referrer information. Otherwise, cross-origin subresources get the origin portion of the referrer URL and same-origin get the stripped referrer URL.">
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-strict-origin-when-cross-origin">
<meta name="assert" content="Referrer Policy: Expects stripped-referrer for fetch to same-http origin and no-redirect redirection from http context.">
<meta name="referrer" content="no-referrer">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/security-features/resources/common.sub.js"></script>
<script src="/referrer-policy/generic/test-case.sub.js"></script>
</head>
<body>
<script>
TestCase(
{
"expectation": "stripped-referrer",
"origin": "same-http",
"redirection": "no-redirect",
"source_context_list": [
{
"policyDeliveries": [
{
"deliveryType": "http-rp",
"key": "referrerPolicy",
"value": "strict-origin-when-cross-origin"
}
],
"sourceContextType": "worker-classic"
}
],
"source_scheme": "http",
"subresource": "fetch",
"subresource_policy_deliveries": []
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
| saneyuki/servo | tests/wpt/web-platform-tests/referrer-policy/gen/worker-classic.http-rp/strict-origin-when-cross-origin/fetch/same-http.no-redirect.http.html | HTML | mpl-2.0 | 2,046 |
package raft
import (
"bytes"
crand "crypto/rand"
"fmt"
"math"
"math/big"
"math/rand"
"time"
"github.com/hashicorp/go-msgpack/codec"
)
func init() {
// Ensure we use a high-entropy seed for the pseudo-random generator
rand.Seed(newSeed())
}
// returns an int64 from a crypto random source
// can be used to seed a source for a math/rand.
func newSeed() int64 {
r, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
panic(fmt.Errorf("failed to read random bytes: %v", err))
}
return r.Int64()
}
// randomTimeout returns a value that is between the minVal and 2x minVal.
func randomTimeout(minVal time.Duration) <-chan time.Time {
if minVal == 0 {
return nil
}
extra := (time.Duration(rand.Int63()) % minVal)
return time.After(minVal + extra)
}
// min returns the minimum.
func min(a, b uint64) uint64 {
if a <= b {
return a
}
return b
}
// max returns the maximum.
func max(a, b uint64) uint64 {
if a >= b {
return a
}
return b
}
// generateUUID is used to generate a random UUID.
func generateUUID() string {
buf := make([]byte, 16)
if _, err := crand.Read(buf); err != nil {
panic(fmt.Errorf("failed to read random bytes: %v", err))
}
return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
buf[0:4],
buf[4:6],
buf[6:8],
buf[8:10],
buf[10:16])
}
// asyncNotifyCh is used to do an async channel send
// to a single channel without blocking.
func asyncNotifyCh(ch chan struct{}) {
select {
case ch <- struct{}{}:
default:
}
}
// drainNotifyCh empties out a single-item notification channel without
// blocking, and returns whether it received anything.
func drainNotifyCh(ch chan struct{}) bool {
select {
case <-ch:
return true
default:
return false
}
}
// asyncNotifyBool is used to do an async notification
// on a bool channel.
func asyncNotifyBool(ch chan bool, v bool) {
select {
case ch <- v:
default:
}
}
// overrideNotifyBool is used to notify on a bool channel
// but override existing value if value is present.
// ch must be 1-item buffered channel.
//
// This method does not support multiple concurrent calls.
func overrideNotifyBool(ch chan bool, v bool) {
select {
case ch <- v:
// value sent, all done
case <-ch:
// channel had an old value
select {
case ch <- v:
default:
panic("race: channel was sent concurrently")
}
}
}
// Decode reverses the encode operation on a byte slice input.
func decodeMsgPack(buf []byte, out interface{}) error {
r := bytes.NewBuffer(buf)
hd := codec.MsgpackHandle{}
dec := codec.NewDecoder(r, &hd)
return dec.Decode(out)
}
// Encode writes an encoded object to a new bytes buffer.
func encodeMsgPack(in interface{}) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(buf, &hd)
err := enc.Encode(in)
return buf, err
}
// backoff is used to compute an exponential backoff
// duration. Base time is scaled by the current round,
// up to some maximum scale factor.
func backoff(base time.Duration, round, limit uint64) time.Duration {
power := min(round, limit)
for power > 2 {
base *= 2
power--
}
return base
}
// Needed for sorting []uint64, used to determine commitment
type uint64Slice []uint64
func (p uint64Slice) Len() int { return len(p) }
func (p uint64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
| hartsock/vault | vendor/github.com/hashicorp/raft/util.go | GO | mpl-2.0 | 3,420 |
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by upgrade-insecure-requests/generic/tools/generate.py using common/security-features/tools/template/test.release.html.template. -->
<html>
<head>
<title>Upgrade-Insecure-Requests: With upgrade-insecure-request</title>
<meta charset='utf-8'>
<meta name="description" content="With upgrade-insecure-request">
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="https://w3c.github.io/webappsec-upgrade-insecure-requests/">
<meta name="assert" content="Upgrade-Insecure-Requests: Expects allowed for xhr to same-http-downgrade origin and no-redirect redirection from https context.">
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/security-features/resources/common.sub.js"></script>
<script src="/upgrade-insecure-requests/generic/test-case.sub.js"></script>
</head>
<body>
<script>
TestCase(
{
"expectation": "allowed",
"origin": "same-http-downgrade",
"redirection": "no-redirect",
"source_context_list": [
{
"policyDeliveries": [],
"sourceContextType": "worker-classic-data"
}
],
"source_scheme": "https",
"subresource": "xhr",
"subresource_policy_deliveries": []
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
| DominoTree/servo | tests/wpt/web-platform-tests/upgrade-insecure-requests/gen/worker-classic-data.meta/upgrade/xhr/same-http-downgrade.no-redirect.https.html | HTML | mpl-2.0 | 1,688 |
package net.tropicraft.world.genlayer;
import net.minecraft.world.gen.layer.IntCache;
public class GenLayerTropiVoronoiZoom extends GenLayerTropicraft {
public enum Mode {
CARTESIAN, MANHATTAN;
}
public Mode zoomMode;
public GenLayerTropiVoronoiZoom(long seed, GenLayerTropicraft parent, Mode zoomMode)
{
super(seed);
super.parent = parent;
this.zoomMode = zoomMode;
this.setZoom(1);
}
/**
* Returns a list of integer values generated by this layer. These may be interpreted as temperatures, rainfall
* amounts, or biomeList[] indices based on the particular GenLayer subclass.
*/
public int[] getInts(int x, int y, int width, int length)
{
final int randomResolution = 1024;
final double half = 0.5D;
final double almostTileSize = 3.6D;
final double tileSize = 4D;
x -= 2;
y -= 2;
int scaledX = x >> 2;
int scaledY = y >> 2;
int scaledWidth = (width >> 2) + 2;
int scaledLength = (length >> 2) + 2;
int[] parentValues = this.parent.getInts(scaledX, scaledY, scaledWidth, scaledLength);
int bitshiftedWidth = scaledWidth - 1 << 2;
int bitshiftedLength = scaledLength - 1 << 2;
int[] aint1 = IntCache.getIntCache(bitshiftedWidth * bitshiftedLength);
int i;
for(int j = 0; j < scaledLength - 1; ++j) {
i = 0;
int baseValue = parentValues[i + 0 + (j + 0) * scaledWidth];
for(int advancedValueJ = parentValues[i + 0 + (j + 1) * scaledWidth]; i < scaledWidth - 1; ++i) {
this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY << 2));
double offsetY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
double offsetX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY << 2));
double offsetYY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
double offsetXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY + 1 << 2));
double offsetYX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize;
double offsetXX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY + 1 << 2));
double offsetYXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
double offsetXXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize;
int advancedValueI = parentValues[i + 1 + (j + 0) * scaledWidth] & 255;
int advancedValueIJ = parentValues[i + 1 + (j + 1) * scaledWidth] & 255;
for(int innerX = 0; innerX < 4; ++innerX) {
int index = ((j << 2) + innerX) * bitshiftedWidth + (i << 2);
for(int innerY = 0; innerY < 4; ++innerY) {
double baseDistance;
double distanceY;
double distanceX;
double distanceXY;
switch(zoomMode) {
case CARTESIAN:
baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY);
distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY);
distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX);
distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY);
break;
case MANHATTAN:
baseDistance = Math.abs(innerX - offsetX) + Math.abs(innerY - offsetY);
distanceY = Math.abs(innerX - offsetXY) + Math.abs(innerY - offsetYY);
distanceX = Math.abs(innerX - offsetXX) + Math.abs(innerY - offsetYX);
distanceXY = Math.abs(innerX - offsetXXY) + Math.abs(innerY - offsetYXY);
break;
default:
baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY);
distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY);
distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX);
distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY);
}
if(baseDistance < distanceY && baseDistance < distanceX && baseDistance < distanceXY) {
aint1[index++] = baseValue;
} else if(distanceY < baseDistance && distanceY < distanceX && distanceY < distanceXY) {
aint1[index++] = advancedValueI;
} else if(distanceX < baseDistance && distanceX < distanceY && distanceX < distanceXY) {
aint1[index++] = advancedValueJ;
} else {
aint1[index++] = advancedValueIJ;
}
}
}
baseValue = advancedValueI;
advancedValueJ = advancedValueIJ;
}
}
int[] aint2 = IntCache.getIntCache(width * length);
for(i = 0; i < length; ++i) {
System.arraycopy(aint1, (i + (y & 3)) * bitshiftedWidth + (x & 3), aint2, i * width, width);
}
return aint2;
}
@Override
public void setZoom(int zoom) {
this.zoom = zoom;
parent.setZoom(zoom * 4);
}
} | Vexatos/Tropicraft | src/main/java/net/tropicraft/world/genlayer/GenLayerTropiVoronoiZoom.java | Java | mpl-2.0 | 6,674 |
initSidebarItems({"mod":[["color",""],["geometry",""],["layers",""],["platform",""],["rendergl",""],["scene",""],["texturegl","OpenGL-specific implementation of texturing."],["tiling",""],["util",""]]}); | susaing/doc.servo.org | servo/layers/sidebar-items.js | JavaScript | mpl-2.0 | 203 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.