repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
FantomJAC/bekko | bekko-util/src/main/java/com/valleycampus/zigbee/io/FrameBuffer.java | 3394 | /*
* Copyright (C) 2014 Valley Campus Japan, Inc.
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.valleycampus.zigbee.io;
/**
*
* @author Shotaro Uchida <[email protected]>
*/
public class FrameBuffer extends ByteBuffer {
public static final byte TRUE = 0x01;
public static final byte FALSE = 0x00;
public static final int BO_LITTLE_ENDIAN = 0;
public static final int BO_BIG_ENDIAN = 1;
private int byteOrder;
public FrameBuffer(byte[] buffer, int offset, int length) {
this(BO_LITTLE_ENDIAN, buffer, offset, length);
}
public FrameBuffer(int byteOrder, byte[] buffer, int offset, int length) {
super(buffer, offset, length);
this.byteOrder = byteOrder;
}
public FrameBuffer(byte[] buffer) {
this(BO_LITTLE_ENDIAN, buffer);
}
public FrameBuffer(int byteOrder,byte[] buffer) {
super(buffer);
this.byteOrder = byteOrder;
}
private ByteUtil getByteUtil() {
if (byteOrder == BO_LITTLE_ENDIAN) {
return ByteUtil.LITTLE_ENDIAN;
} else {
return ByteUtil.BIG_ENDIAN;
}
}
public int getByteOrder() {
return byteOrder;
}
public FrameBuffer setByteOrder(int byteOrder) {
this.byteOrder = byteOrder;
return this;
}
public FrameBuffer putFrame(Frame frame) {
frame.pull(this);
return this;
}
public FrameBuffer putInt8(int i) {
put((byte) (i & 0xFF));
return this;
}
public FrameBuffer putInt16(int i) {
put(getByteUtil().toByteArray(i, ByteUtil.INT_16_SIZE));
return this;
}
public FrameBuffer putInt32(int i) {
put(getByteUtil().toByteArray(i, ByteUtil.INT_32_SIZE));
return this;
}
public FrameBuffer putBoolean(boolean b) {
put(b ? TRUE : FALSE);
return this;
}
public FrameBuffer getFrame(Frame frame) {
frame.drain(this);
return this;
}
public int getInt8() {
return get() & 0xFF;
}
public byte getByte() {
return get();
}
public int getInt16() {
return getByteUtil().toInt16(getByteArray(ByteUtil.INT_16_SIZE), 0);
}
public short getShort() {
return (short) getInt16();
}
public int getInt32() {
return getByteUtil().toInt32(getByteArray(ByteUtil.INT_32_SIZE), 0);
}
public FrameBuffer putInt64(long l) {
put(getByteUtil().toByteArray(l, ByteUtil.INT_64_SIZE));
return this;
}
public long getInt64() {
return getByteUtil().toInt64(getByteArray(ByteUtil.INT_64_SIZE), 0);
}
public boolean getBoolean() {
return (get() == TRUE);
}
}
| lgpl-3.0 |
andrepuschmann/iris_modules_ospecorr | components/gpp/phy/OfdmDemodulator/OfdmDemodulatorComponent.cpp | 17427 | /**
* \file components/gpp/phy/OfdmDemodulator/OfdmDemodulatorComponent.cpp
* \version 1.0
*
* \section COPYRIGHT
*
* Copyright 2012-2013 The Iris Project Developers. See the
* COPYRIGHT file at the top-level directory of this distribution
* and at http://www.softwareradiosystems.com/iris/copyright.html.
*
* \section LICENSE
*
* This file is part of the Iris Project.
*
* Iris 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.
*
* Iris 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.
*
* A copy of the GNU Lesser General Public License can be found in
* the LICENSE file in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/.
*
* \section DESCRIPTION
*
* Implementation of the OfdmDemodulator component.
*/
#include "OfdmDemodulatorComponent.h"
#include <cmath>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <numeric>
#include "irisapi/LibraryDefs.h"
#include "irisapi/Version.h"
#include "modulation/OfdmIndexGenerator.h"
#include "modulation/Crc.h"
#include "modulation/Whitener.h"
#include "utility/RawFileUtility.h"
using namespace std;
using namespace boost::lambda;
namespace iris
{
namespace phy
{
// export library symbols
IRIS_COMPONENT_EXPORTS(PhyComponent, OfdmDemodulatorComponent);
OfdmDemodulatorComponent::OfdmDemodulatorComponent(std::string name)
: PhyComponent(name, // component name
"ofdmdemodulator", // component type
"An OFDM demodulation component", // description
"Paul Sutton", // author
"1.0") // version
,numHeaderBytes_(7)
,frameDetected_(false)
,haveHeader_(false)
,symbolLength_(0)
,rxNumBytes_(0)
,rxNumSymbols_(0)
,headerIndex_(0)
,frameIndex_(0)
,halfFft_(NULL)
,halfFftData_(NULL)
,fullFft_(NULL)
,fullFftData_(NULL)
,numRxFrames_(0)
,numRxFails_(0)
,symbolCount_(0)
{
registerParameter(
"debug", "Whether to write debug data to file.",
"false", true, debug_x);
registerParameter(
"reportrate", "Report performance stats every reportrate frames.",
"1000", true, reportRate_x);
registerParameter(
"numdatacarriers", "Number of data carriers (excluding pilots)",
"192", true, numDataCarriers_x, Interval<int>(1,65536));
registerParameter(
"numpilotcarriers", "Number of pilot carriers",
"8", true, numPilotCarriers_x, Interval<int>(1,65536));
registerParameter(
"numguardcarriers", "Number of guard carriers",
"55", true, numGuardCarriers_x, Interval<int>(1,65536));
registerParameter(
"cyclicprefixlength", "Length of cyclic prefix",
"16", true, cyclicPrefixLength_x, Interval<int>(1,65536));
registerParameter(
"threshold", "Frame detection threshold",
"0.827", true, threshold_x, Interval<float>(0.0,1.0));
// Create our pilot sequence
typedef Cplx c;
c seq[] = {c(1,0),c(1,0),c(-1,0),c(-1,0),c(-1,0),c(1,0),c(-1,0),c(1,0),};
pilotSequence_.assign(begin(seq), end(seq));
}
OfdmDemodulatorComponent::~OfdmDemodulatorComponent()
{
destroy();
}
void OfdmDemodulatorComponent::registerPorts()
{
registerInputPort("input1", TypeInfo< complex<float> >::identifier);
registerOutputPort("output1", TypeInfo< uint8_t >::identifier);
}
void OfdmDemodulatorComponent::calculateOutputTypes(
std::map<std::string,int>& inputTypes,
std::map<std::string,int>& outputTypes)
{
outputTypes["output1"] = TypeInfo< uint8_t >::identifier;
}
void OfdmDemodulatorComponent::initialize()
{
setup();
}
void OfdmDemodulatorComponent::process()
{
getInputDataSet("input1", in_);
timeStamp_ = in_->timeStamp;
sampleRate_ = in_->sampleRate;
CplxVecIt begin = in_->data.begin();
CplxVecIt end = in_->data.end();
try
{
while(begin != end)
{
if(!frameDetected_)
begin = searchInput(begin, end);
else
begin = processFrame(begin, end);
}
}
catch(IrisException& e)
{
LOG(LDEBUG) << e.what();
headerIndex_ = 0;
frameIndex_ = 0;
frameDetected_ = false;
haveHeader_ = false;
numRxFails_++;
}
releaseInputDataSet("input1", in_);
if(numRxFrames_ >= reportRate_x)
{
float successRate = 1-((float)numRxFails_/numRxFrames_);
LOG(LINFO) << "Frame succcess rate: " << successRate*100 << "%";
numRxFrames_ = 0;
numRxFails_ = 0;
}
}
void OfdmDemodulatorComponent::parameterHasChanged(std::string name)
{
if(name == "numdatacarriers" || name == "numpilotcarriers" ||
name == "numguardcarriers" || name == "cyclicprefixlength")
{
destroy();
setup();
}
if(name == "threshold")
detector_.reset(numBins_,cyclicPrefixLength_x,threshold_x);
}
void OfdmDemodulatorComponent::setup()
{
// Set up index vectors
pilotIndices_.clear();
pilotIndices_.resize(numPilotCarriers_x);
dataIndices_.clear();
dataIndices_.resize(numDataCarriers_x);
OfdmIndexGenerator::generateIndices(numDataCarriers_x,
numPilotCarriers_x,
numGuardCarriers_x,
pilotIndices_.begin(), pilotIndices_.end(),
dataIndices_.begin(), dataIndices_.end());
numBins_ = numDataCarriers_x + numPilotCarriers_x + numGuardCarriers_x + 1;
symbolLength_ = numBins_ + cyclicPrefixLength_x;
numHeaderSymbols_ = (int)ceil(numHeaderBytes_/((float)numDataCarriers_x/8));
preamble_.clear();
preamble_.resize(numBins_);
preambleBins_.resize(numBins_/2);
preambleGen_.generatePreamble(numDataCarriers_x,
numPilotCarriers_x,
numGuardCarriers_x,
preamble_.begin(),
preamble_.end());
if(debug_x)
RawFileUtility::write(preamble_.begin(), preamble_.end(),
"OutputData/RxKnownPreamble");
halfFftData_ = reinterpret_cast<Cplx*>(
fftwf_malloc(sizeof(fftwf_complex) * numBins_/2));
fill(&halfFftData_[0], &halfFftData_[numBins_/2], Cplx(0,0));
fullFftData_ = reinterpret_cast<Cplx*>(
fftwf_malloc(sizeof(fftwf_complex) * numBins_));
fill(&fullFftData_[0], &fullFftData_[numBins_], Cplx(0,0));
halfFft_ = fftwf_plan_dft_1d(numBins_/2,
(fftwf_complex*)halfFftData_,
(fftwf_complex*)halfFftData_,
FFTW_FORWARD,
FFTW_MEASURE);
fullFft_ = fftwf_plan_dft_1d(numBins_,
(fftwf_complex*)fullFftData_,
(fftwf_complex*)fullFftData_,
FFTW_FORWARD,
FFTW_MEASURE);
copy(preamble_.begin(), preamble_.begin()+numBins_/2, halfFftData_);
fftwf_execute(halfFft_);
copy(halfFftData_, halfFftData_+numBins_/2, preambleBins_.begin());
transform(preambleBins_.begin(),
preambleBins_.end(),
preambleBins_.begin(),
2.0f*_1);
if(debug_x)
RawFileUtility::write(preambleBins_.begin(), preambleBins_.end(),
"OutputData/RxKnownPreambleBins");
rxPreamble_.resize(symbolLength_);
corrector_.resize(symbolLength_);
rxHeader_.resize(symbolLength_*numHeaderSymbols_);
equalizer_.resize(numBins_);
detector_.reset(numBins_,cyclicPrefixLength_x,threshold_x, debug_x);
}
void OfdmDemodulatorComponent::destroy()
{
if(halfFft_ != NULL)
fftwf_destroy_plan(halfFft_);
if(fullFft_ != NULL)
fftwf_destroy_plan(fullFft_);
if(halfFftData_ != NULL)
fftwf_free(halfFftData_);
if(fullFftData_ != NULL)
fftwf_free(fullFftData_);
}
OfdmDemodulatorComponent::CplxVecIt
OfdmDemodulatorComponent::searchInput(CplxVecIt begin, CplxVecIt end)
{
float snr(0);
CplxVecIt it = detector_.search(begin, end,
rxPreamble_.begin(), rxPreamble_.end(),
frameDetected_, fracFreqOffset_, snr);
if(frameDetected_)
{
int idx = (it-in_->data.begin()) - (numBins_+cyclicPrefixLength_x);
timeStamp_ = timeStamp_ + (idx/sampleRate_);
extractPreamble();
}
return it;
}
OfdmDemodulatorComponent::CplxVecIt
OfdmDemodulatorComponent::processFrame(CplxVecIt begin, CplxVecIt end)
{
for(; begin != end; begin++)
{
if(!haveHeader_)
{
rxHeader_[headerIndex_++] = *begin;
if(headerIndex_ == symbolLength_*numHeaderSymbols_)
extractHeader();
}
else
{
rxFrame_[frameIndex_++] = *begin;
if(frameIndex_ == symbolLength_*rxNumSymbols_)
{
demodFrame();
return ++begin;
}
}
}
return begin;
}
void OfdmDemodulatorComponent::extractPreamble()
{
generateFractionalOffsetCorrector(fracFreqOffset_);
correctFractionalOffset(rxPreamble_.begin(), rxPreamble_.end());
int off = cyclicPrefixLength_x-4;
CplxVecIt begin = rxPreamble_.begin() + off;
CplxVecIt end = rxPreamble_.begin() + off + (numBins_/2);
if(debug_x)
RawFileUtility::write(begin, end, "OutputData/RxPreamble");
int halfBins = numBins_/2;
CplxVec bins(halfBins);
copy(begin, end, halfFftData_);
fftwf_execute(halfFft_);
copy(halfFftData_, halfFftData_+halfBins, bins.begin());
transform(bins.begin(), bins.end(), bins.begin(), _1*Cplx(2,0));
if(debug_x)
RawFileUtility::write(bins.begin(), bins.end(),
"OutputData/RxPreambleHalfBins");
intFreqOffset_ = findIntegerOffset(bins.begin(), bins.end());
int shift = (halfBins-intFreqOffset_)%halfBins;
rotate(bins.begin(), bins.begin()+shift, bins.end());
if(debug_x)
RawFileUtility::write(bins.begin(), bins.end(),
"OutputData/RxPreambleHalfBinsRotated");
generateEqualizer(bins.begin(), bins.end());
}
void OfdmDemodulatorComponent::extractHeader()
{
symbolCount_ = 0;
numRxFrames_++;
int bytesPerHeader = numDataCarriers_x/8;
ByteVec data(numHeaderSymbols_*bytesPerHeader);
ByteVecIt dataIt = data.begin();
CplxVecIt symIt = rxHeader_.begin();
for(int i=0; i<numHeaderSymbols_; i++)
{
demodSymbol(symIt, symIt+symbolLength_,
dataIt, dataIt+bytesPerHeader, BPSK);
symIt += symbolLength_;
dataIt += numDataCarriers_x/8;
symbolCount_++;
}
Whitener::whiten(data.begin(), data.end());
rxCrc_ = 0;
rxCrc_ = data[3];
rxCrc_ |= (data[2] << 8);
rxCrc_ |= (data[1] << 16);
rxCrc_ |= (data[0] << 24);
rxModulation_ = data[6] & 0xFF;
if(rxModulation_!=BPSK && rxModulation_!=QPSK && rxModulation_!=QAM16)
throw IrisException("Invalid modulation depth - dropping frame.");
rxNumBytes_ = ((data[4]<<8) | data[5]) & 0xFFFF;
int bytesPerSymbol = (numDataCarriers_x*rxModulation_)/8;
rxNumSymbols_ = ceil(rxNumBytes_/(float)bytesPerSymbol);
if(rxNumSymbols_>32 || rxNumSymbols_<1)
throw IrisException("Invalid frame length - dropping frame.");
rxFrame_.resize(rxNumSymbols_*symbolLength_);
haveHeader_ = true;
}
void OfdmDemodulatorComponent::demodFrame()
{
int bytesPerSymbol = (numDataCarriers_x*rxModulation_)/8;
int frameDataLen = (rxNumSymbols_*bytesPerSymbol);
frameData_.resize(frameDataLen);
CplxVecIt inIt = rxFrame_.begin();
ByteVecIt outIt = frameData_.begin();
for(int i=0;i<rxNumSymbols_;i++)
{
demodSymbol(inIt, inIt+symbolLength_,
outIt, outIt+bytesPerSymbol,
rxModulation_);
inIt += symbolLength_;
outIt += bytesPerSymbol;
symbolCount_++;
}
outIt = frameData_.begin();
Whitener::whiten(outIt, outIt+rxNumBytes_);
uint32_t crc = Crc::generate(outIt, outIt+rxNumBytes_);
if(crc != rxCrc_)
throw IrisException("CRC mismatch - dropping frame.");
DataSet< uint8_t>* out;
getOutputDataSet("output1", out, rxNumBytes_);
out->sampleRate = sampleRate_;
out->timeStamp = timeStamp_;
copy(outIt, outIt+rxNumBytes_, out->data.begin());
releaseOutputDataSet("output1", out);
headerIndex_ = 0;
frameIndex_ = 0;
frameDetected_ = false;
haveHeader_ = false;
}
void OfdmDemodulatorComponent::demodSymbol(CplxVecIt inBegin, CplxVecIt inEnd,
ByteVecIt outBegin, ByteVecIt outEnd,
int modulationDepth)
{
correctFractionalOffset(inBegin, inEnd);
int off = cyclicPrefixLength_x-4;
CplxVecIt begin = inBegin + off;
CplxVecIt end = inBegin + off + numBins_;
CplxVec bins(numBins_);
copy(begin, end, fullFftData_);
fftwf_execute(fullFft_);
copy(fullFftData_, fullFftData_+numBins_, bins.begin());
if(debug_x)
{
stringstream fileName;
fileName << "OutputData//RxSymbolBins" << symbolCount_;
RawFileUtility::write(bins.begin(), bins.end(),
fileName.str());
}
int shift = (numBins_-intFreqOffset_*2)%numBins_;
rotate(bins.begin(), bins.begin()+shift, bins.end());
if(debug_x)
{
stringstream fileName;
fileName << "OutputData//RxSymbolBinsRotated" << symbolCount_;
RawFileUtility::write(bins.begin(), bins.end(),
fileName.str());
}
equalizeSymbol(bins.begin(), bins.end());
if(debug_x)
{
stringstream fileName;
fileName << "OutputData//RxSymbolBinsEqualized" << symbolCount_;
RawFileUtility::write(bins.begin(), bins.end(),
fileName.str());
}
CplxVec qamSymbols;
for(int i=0; i<numDataCarriers_x; i++)
qamSymbols.push_back(bins[dataIndices_[i]]);
if(debug_x)
{
stringstream fileName;
fileName << "OutputData//RxSymbolData" << symbolCount_;
RawFileUtility::write(qamSymbols.begin(), qamSymbols.end(),
fileName.str());
}
qDemod_.demodulate(qamSymbols.begin(), qamSymbols.end(),
outBegin, outEnd, modulationDepth);
}
void OfdmDemodulatorComponent::generateFractionalOffsetCorrector(float offset)
{
float relFreq = -offset/numBins_;
toneGenerator_.generate(corrector_.begin(), corrector_.end(), relFreq);
if(debug_x)
RawFileUtility::write(corrector_.begin(), corrector_.end(),
"OutputData/RxFreqCorrector");
}
void OfdmDemodulatorComponent::correctFractionalOffset(CplxVecIt begin,
CplxVecIt end)
{
transform(begin, end, corrector_.begin(), begin, _1*_2);
}
int OfdmDemodulatorComponent::findIntegerOffset(CplxVecIt begin, CplxVecIt end)
{
FloatVec magRxBins(numBins_/2);
transform(begin, end, magRxBins.begin(), opAbs());
FloatVec magTxBins(numBins_);
transform(preambleBins_.begin(), preambleBins_.end(),
magTxBins.begin(), opAbs());
FloatVecIt it = magTxBins.begin();
copy(it, it+(numBins_/2), it+(numBins_/2));
FloatVec correlations;
//Calculate negative offset correlations
FloatVecIt txIt = magTxBins.begin()+(numBins_/2);
for(int i=-16; i<0; i++)
{
float res = inner_product(txIt+i, txIt+i+(numBins_/2),
magRxBins.begin(), 0.0f);
correlations.push_back(res);
}
//Calculate positive offset correlations
txIt = magTxBins.begin();
for(int i=0; i<17; i++)
{
float res = inner_product(txIt+i, txIt+i+(numBins_/2),
magRxBins.begin(), 0.0f);
correlations.push_back(res);
}
if(debug_x)
RawFileUtility::write(correlations.begin(), correlations.end(),
"OutputData/RxFreqOffsetCorrelations");
FloatVecIt result = max_element(correlations.begin(), correlations.end());
int off = (int)distance(correlations.begin(), result) - 16;
return off;
}
void OfdmDemodulatorComponent::generateEqualizer(CplxVecIt begin, CplxVecIt end)
{
CplxVec shortEq(numBins_/2);
transform(begin, end, preambleBins_.begin(), shortEq.begin(), _2/_1);
if(debug_x)
RawFileUtility::write(shortEq.begin(), shortEq.end(),
"OutputData/RxShortEqualizer");
shortEq[0] = (shortEq[(numBins_/2)-1] + shortEq[1])/Cplx(2,0);
for(int i=0; i<numBins_/2; i++)
equalizer_[i*2] = shortEq[i];
for(int i=1; i<numBins_; i+=2)
equalizer_[i] = (equalizer_[i-1] + equalizer_[(i+1)%numBins_])/Cplx(2,0);
equalizer_[0] = Cplx(0,0);
if(debug_x)
RawFileUtility::write(equalizer_.begin(), equalizer_.end(),
"OutputData/RxEqualizer");
}
void OfdmDemodulatorComponent::equalizeSymbol(CplxVecIt begin, CplxVecIt end)
{
transform(begin, end, equalizer_.begin(), begin, _1*_2);
CplxVec pilots;
for(int i=0; i<numPilotCarriers_x; i++)
pilots.push_back(*(begin+pilotIndices_[i]));
CplxVec diffs;
for(int i=0; i<numPilotCarriers_x; i++)
diffs.push_back(pilotSequence_[i%numPilotCarriers_x]/pilots[i]);
Cplx sum = accumulate(diffs.begin(), diffs.end(), Cplx(0,0));
float ave = arg(sum/(float)numPilotCarriers_x);
Cplx corrector = Cplx(cos(ave), sin(ave));
transform(begin, end, begin, _1*corrector);
}
} // namesapce phy
} // namespace iris
| lgpl-3.0 |
m-abboud/FontVerter | src/main/java/org/mabb/fontverter/opentype/TtfInstructions/instructions/graphic/AlignPoints.java | 1362 | /*
* Copyright (C) Maddie Abboud 2016
*
* FontVerter 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.
*
* FontVerter 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 FontVerter. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mabb.fontverter.opentype.TtfInstructions.instructions.graphic;
import org.mabb.fontverter.io.FontDataInputStream;
import org.mabb.fontverter.opentype.TtfInstructions.InstructionStack;
import org.mabb.fontverter.opentype.TtfInstructions.instructions.TtfInstruction;
import java.io.IOException;
public class AlignPoints extends TtfInstruction {
public int[] getCodeRanges() {
return new int[]{0x27};
}
public void read(FontDataInputStream in) throws IOException {
}
public void execute(InstructionStack stack) throws IOException {
long p1 = stack.popUint32();
long p2 = stack.popUint32();
}
}
| lgpl-3.0 |
SOCR/HTML5_WebSite | SOCR2.8/src/edu/ucla/stat/SOCR/util/DieProbabilityDialog.java | 3378 | /****************************************************
Statistics Online Computational Resource (SOCR)
http://www.StatisticsResource.org
All SOCR programs, materials, tools and resources are developed by and freely disseminated to the entire community.
Users may revise, extend, redistribute, modify under the terms of the Lesser GNU General Public License
as published by the Open Source Initiative http://opensource.org/licenses/. All efforts should be made to develop and distribute
factually correct, useful, portable and extensible resource all available in all digital formats for free over the Internet.
SOCR resources are distributed in the hope that they will be useful, but without
any warranty; without any explicit, implicit or implied warranty for merchantability or
fitness for a particular purpose. See the GNU Lesser General Public License for
more details see http://opensource.org/licenses/lgpl-license.php.
http://www.SOCR.ucla.edu
http://wiki.stat.ucla.edu/socr
It s Online, Therefore, It Exists!
****************************************************/
package edu.ucla.stat.SOCR.util;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
public class DieProbabilityDialog extends ProbabilityDialog {
private JPanel buttonPanel = new JPanel();
private JButton fairButton = new JButton("Fair");
private JButton flat16Button = new JButton("1-6 Flat");
private JButton flat25Button = new JButton("2-5 Flat");
private JButton flat34Button = new JButton("3-4 Flat");
private JButton leftButton = new JButton("Skewed Left");
private JButton rightButton = new JButton("Skewed Right");
public DieProbabilityDialog(Frame owner) {
super(owner, "Die Probabilities", 6);
//Event Listeners
fairButton.addActionListener(this);
flat16Button.addActionListener(this);
flat25Button.addActionListener(this);
flat34Button.addActionListener(this);
leftButton.addActionListener(this);
rightButton.addActionListener(this);
//Layout
invalidate();
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
buttonPanel.add(fairButton);
buttonPanel.add(flat16Button);
buttonPanel.add(flat25Button);
buttonPanel.add(flat34Button);
buttonPanel.add(leftButton);
buttonPanel.add(rightButton);
getContentPane().add(buttonPanel, BorderLayout.NORTH);
//Labels
for (int i = 0; i < 6; i++) setLabel(i, String.valueOf(i + 1));
pack();
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == fairButton) setProbabilities(new double[] {1.0 / 6, 1.0 / 6, 1.0 / 6, 1.0 / 6, 1.0 / 6, 1.0 / 6});
else if (event.getSource() == flat16Button) setProbabilities(new double[] {1.0 / 4, 1.0 / 8, 1.0 / 8, 1.0 / 8, 1.0 / 8, 1.0 / 4});
else if (event.getSource() == flat25Button) setProbabilities(new double[] {1.0 / 8, 1.0 / 4, 1.0 / 8, 1.0 / 8, 1.0 / 4, 1.0 / 8});
else if (event.getSource() == flat34Button) setProbabilities(new double[] {1.0 / 8, 1.0 / 8, 1.0 / 4, 1.0 / 4, 1.0 / 8, 1.0 / 8});
else if (event.getSource() == leftButton) setProbabilities(new double[] {1.0 / 21, 2.0 / 21, 3.0 / 21, 4.0 / 21, 5.0 / 21, 6.0 / 21});
else if (event.getSource() == rightButton) setProbabilities(new double[] {6.0 / 21, 5.0 / 21, 4.0 / 21, 3.0 / 21, 2.0 / 21, 1.0 / 21});
else super.actionPerformed(event);
}
}
| lgpl-3.0 |
tiagocoutinho/bliss | tests/comm/test_scpi.py | 6046 | import pytest
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
from bliss.comm.scpi import sanitize_msgs, min_max_cmd, cmd_expr_to_reg_expr
from bliss.comm.scpi import SCPI, COMMANDS, Commands
from bliss.comm.scpi import (Cmd, FuncCmd, IntCmd, IntCmdRO, IntCmdWO,
FloatCmdRO, StrCmdRO, IDNCmd, ErrCmd)
def test_sanitize_msgs():
r = sanitize_msgs('*rst', '*idn?;*cls')
assert r == (['*rst', '*idn?', '*cls'], ['*idn?'], '*rst\n*idn?\n*cls\n')
r = sanitize_msgs('*rst', '*idn?;*cls', eol='\r\n')
assert r == (['*rst', '*idn?', '*cls'], ['*idn?'], '*rst\r\n*idn?\r\n*cls\r\n')
r = sanitize_msgs('*rst', '*idn?;*cls', strict_query=False)
assert r == (['*rst', '*idn?', '*cls'], ['*idn?'], '*rst\n*idn?;*cls\n')
r = sanitize_msgs('*rst', '*idn?;*cls', strict_query=False)
assert r == (['*rst', '*idn?', '*cls'], ['*idn?'], '*rst\n*idn?;*cls\n')
def test_min_max_cmd():
assert min_max_cmd('*OPC') == ('*OPC', '*OPC')
assert min_max_cmd(':*OPC') == ('*OPC', '*OPC')
assert min_max_cmd('SYSTem:ERRor[:NEXT]') == ('SYST:ERR', 'SYSTEM:ERROR:NEXT')
assert min_max_cmd('MEASure[:CURRent[:DC]]') == ('MEAS', 'MEASURE:CURRENT:DC')
assert min_max_cmd('[SENSe[1]:]CURRent[:DC]:RANGe[:UPPer]') == ('CURR:RANG', 'SENSE1:CURRENT:DC:RANGE:UPPER')
def test_cmd_expr_to_reg_expr():
cmd_exprs = {
'idn' : ('*IDN', '\\:?\\*IDN$'),
'err' : ('SYSTem:ERRor[:NEXT]', '\\:?SYST(EM)?\\:ERR(OR)?(\\:NEXT)?$'),
'meas': ('MEASure[:CURRent[:DC]]', '\\:?MEAS(URE)?(\\:CURR(ENT)?(\\:DC)?)?$'),
'rupper': ('[SENSe[1]:]CURRent[:DC]:RANGe[:UPPer]', '\\:?(SENS(E)?(1)?\\:)?CURR(ENT)?(\\:DC)?\\:RANG(E)?(\\:UPP(ER)?)?$')
}
for _, (expr, reg_expr) in cmd_exprs.items():
assert cmd_expr_to_reg_expr(expr).pattern == reg_expr
cmd_re = dict([(k, cmd_expr_to_reg_expr(expr))
for k, (expr, _) in cmd_exprs.items()])
idn_re = cmd_re['idn']
assert idn_re.match('*IDN')
assert idn_re.match('*idn')
assert not idn_re.match('IDN')
def test_cmd(name, match, no_match):
reg_expr = cmd_re[name]
for m in match:
assert reg_expr.match(m), '{0}: {1} does not match {2}'.format(name, m, cmd_exprs[name][0])
for m in no_match:
assert not reg_expr.match(m), '{0}: {1} matches {2}'.format(name, m, cmd_exprs[name][0])
test_cmd('idn',
('*IDN', '*idn', '*IdN'),
('IDN', ' *IDN', '**IDN', '*IDN '))
test_cmd('err',
('SYST:ERR', 'SYSTEM:ERROR:NEXT', 'syst:error', 'system:err:next'),
('sys', 'syst:erro', 'system:next'))
test_cmd('err',
('SYST:ERR', 'SYSTEM:ERROR:NEXT', 'syst:error', 'system:err:next'),
('sys', 'syst:erro', 'system:next'))
test_cmd('rupper',
('CURR:RANG', 'SENS:CURR:RANG:UPP', 'SENSE1:CURRENT:DC:RANGE:UPPER'),
('sense:curren:rang', 'sens1:range:upp'))
def test_commands():
commands = Commands({
'*CLS': FuncCmd(doc='clear status'),
'*ESE': IntCmd(doc='standard event status enable register'),
'*ESR': IntCmdRO(doc='standard event event status register'),
'*IDN': IDNCmd(),
'*OPC': IntCmdRO(set=None, doc='operation complete'),
'*OPT': IntCmdRO(doc='return model number of any installed options'),
'*RCL': IntCmdWO(set=int, doc='return to user saved setup'),
'*RST': FuncCmd(doc='reset'),
'*SAV': IntCmdWO(doc='save the preset setup as the user-saved setup'),
'*SRE': IntCmdWO(doc='service request enable register'),
'*STB': StrCmdRO(doc='status byte register'),
'*TRG': FuncCmd(doc='bus trigger'),
'*TST': Cmd(get=lambda x : not decode_OnOff(x),
doc='self-test query'),
'*WAI': FuncCmd(doc='wait to continue'),
'SYSTem:ERRor[:NEXT]': ErrCmd(doc='return and clear oldest system error'),
}, {
'MEASure[:CURRent[:DC]]': FloatCmdRO(get=lambda x: float(x[:-1])),
})
assert '*idn' in commands
assert commands['*idn'] is commands['*IDN']
assert commands.get('idn') == None
assert 'SYST:ERR' in commands
assert 'SYSTEM:ERROR:NEXT' in commands
assert 'syst:error' in commands
assert commands['SYST:ERR'] is commands['system:error:next']
assert commands['MEAS'] is commands['measure:current:dc']
assert commands[':*idn']['min_command'] == '*IDN'
assert commands['system:error:next']['min_command'] == 'SYST:ERR'
with pytest.raises(KeyError) as err:
commands['IDN']
assert 'IDN' in str(err.value)
@pytest.fixture
def interface():
mock = Mock(_eol='\n')
mock.idn = 'BLISS INSTRUMENTS INC.,6485,123456,B04'
mock.meas = 1.2345
mock.idn_obj = dict(zip(('manufacturer', 'model', 'serial', 'version'), mock.idn.split(',')))
mock.values = {
'*IDN?': mock.idn,
'MEAS?': '%EA' % mock.meas,
}
mock.commands = []
def write_readline(msg):
return mock.values[msg.rstrip(mock._eol).upper()]
mock.write_readline = write_readline
def write_readlines(msg, n):
msgs = [msg for submsg in msg.splitlines() for msg in submsg.split(';')]
reply = [mock.values[m.upper()] for m in msgs if '?' in m]
return reply[:n]
mock.write_readlines = write_readlines
def write(msg):
mock.commands.append(msg)
mock.write = write
return mock
def test_SCPI(interface):
scpi = SCPI(interface=interface)
assert scpi['*IDN'] == interface.idn_obj
assert scpi('*IDN?')[0][1] == interface.idn_obj
scpi('*CLS')
assert interface.commands == ['*CLS\n']
scpi('*RST')
assert interface.commands == ['*CLS\n', '*RST\n']
cmds = Commands(COMMANDS,
{'MEASure[:CURRent[:DC]]': FloatCmdRO(get=lambda x: float(x[:-1]))})
meas_scpi = SCPI(interface=interface, commands=cmds)
with pytest.raises(KeyError):
scpi['MEAS']
assert meas_scpi['MEAS'] == interface.meas
| lgpl-3.0 |
lbndev/sonarqube | server/sonar-server/src/main/java/org/sonar/server/ws/ws/WebServicesWsModule.java | 1117 | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.ws.ws;
import org.sonar.core.platform.Module;
public class WebServicesWsModule extends Module {
@Override
protected void configureModule() {
add(
WebServicesWs.class,
ListAction.class,
ResponseExampleAction.class);
}
}
| lgpl-3.0 |
pcolby/libqtaws | src/kms/signresponse.cpp | 6504 | /*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "signresponse.h"
#include "signresponse_p.h"
#include <QDebug>
#include <QNetworkReply>
#include <QXmlStreamReader>
namespace QtAws {
namespace KMS {
/*!
* \class QtAws::KMS::SignResponse
* \brief The SignResponse class provides an interace for KMS Sign responses.
*
* \inmodule QtAwsKMS
*
* <fullname>AWS Key Management Service</fullname>
*
* AWS Key Management Service (AWS KMS) is an encryption and key management web service. This guide describes the AWS KMS
* operations that you can call programmatically. For general information about AWS KMS, see the <a
* href="https://docs.aws.amazon.com/kms/latest/developerguide/"> <i>AWS Key Management Service Developer Guide</i>
*
* </a>> <note>
*
* AWS provides SDKs that consist of libraries and sample code for various programming languages and platforms (Java, Ruby,
* .Net, macOS, Android, etc.). The SDKs provide a convenient way to create programmatic access to AWS KMS and other AWS
* services. For example, the SDKs take care of tasks such as signing requests (see below), managing errors, and retrying
* requests automatically. For more information about the AWS SDKs, including how to download and install them, see <a
* href="http://aws.amazon.com/tools/">Tools for Amazon Web
*
* Services</a>> </note>
*
* We recommend that you use the AWS SDKs to make programmatic API calls to AWS
*
* KMS>
*
* Clients must support TLS (Transport Layer Security) 1.0. We recommend TLS 1.2. Clients must also support cipher suites
* with Perfect Forward Secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral Diffie-Hellman
* (ECDHE). Most modern systems such as Java 7 and later support these
*
* modes>
*
* <b>Signing Requests</b>
*
* </p
*
* Requests must be signed by using an access key ID and a secret access key. We strongly recommend that you <i>do not</i>
* use your AWS account (root) access key ID and secret key for everyday work with AWS KMS. Instead, use the access key ID
* and secret access key for an IAM user. You can also use the AWS Security Token Service to generate temporary security
* credentials that you can use to sign
*
* requests>
*
* All AWS KMS operations require <a
* href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version
*
* 4</a>>
*
* <b>Logging API Requests</b>
*
* </p
*
* AWS KMS supports AWS CloudTrail, a service that logs AWS API calls and related events for your AWS account and delivers
* them to an Amazon S3 bucket that you specify. By using the information collected by CloudTrail, you can determine what
* requests were made to AWS KMS, who made the request, when it was made, and so on. To learn more about CloudTrail,
* including how to turn it on and find your log files, see the <a
* href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/">AWS CloudTrail User
*
* Guide</a>>
*
* <b>Additional Resources</b>
*
* </p
*
* For more information about credentials and request signing, see the
*
* following> <ul> <li>
*
* <a href="https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html">AWS Security Credentials</a> -
* This topic provides general information about the types of credentials used for accessing
*
* AWS> </li> <li>
*
* <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html">Temporary Security Credentials</a> -
* This section of the <i>IAM User Guide</i> describes how to create and use temporary security
*
* credentials> </li> <li>
*
* <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 Signing Process</a>
* - This set of topics walks you through the process of signing a request using an access key ID and a secret access
*
* key> </li> </ul>
*
* <b>Commonly Used API Operations</b>
*
* </p
*
* Of the API operations discussed in this guide, the following will prove the most useful for most applications. You will
* likely perform operations other than these, such as creating keys and assigning policies, by using the
*
* console> <ul> <li>
*
* <a>Encrypt</a>
*
* </p </li> <li>
*
* <a>Decrypt</a>
*
* </p </li> <li>
*
* <a>GenerateDataKey</a>
*
* </p </li> <li>
*
* <a>GenerateDataKeyWithoutPlaintext</a>
*
* \sa KmsClient::sign
*/
/*!
* Constructs a SignResponse object for \a reply to \a request, with parent \a parent.
*/
SignResponse::SignResponse(
const SignRequest &request,
QNetworkReply * const reply,
QObject * const parent)
: KmsResponse(new SignResponsePrivate(this), parent)
{
setRequest(new SignRequest(request));
setReply(reply);
}
/*!
* \reimp
*/
const SignRequest * SignResponse::request() const
{
Q_D(const SignResponse);
return static_cast<const SignRequest *>(d->request);
}
/*!
* \reimp
* Parses a successful KMS Sign \a response.
*/
void SignResponse::parseSuccess(QIODevice &response)
{
//Q_D(SignResponse);
QXmlStreamReader xml(&response);
/// @todo
}
/*!
* \class QtAws::KMS::SignResponsePrivate
* \brief The SignResponsePrivate class provides private implementation for SignResponse.
* \internal
*
* \inmodule QtAwsKMS
*/
/*!
* Constructs a SignResponsePrivate object with public implementation \a q.
*/
SignResponsePrivate::SignResponsePrivate(
SignResponse * const q) : KmsResponsePrivate(q)
{
}
/*!
* Parses a KMS Sign response element from \a xml.
*/
void SignResponsePrivate::parseSignResponse(QXmlStreamReader &xml)
{
Q_ASSERT(xml.name() == QLatin1String("SignResponse"));
Q_UNUSED(xml) ///< @todo
}
} // namespace KMS
} // namespace QtAws
| lgpl-3.0 |
pcolby/libqtaws | src/elasticbeanstalk/describeinstanceshealthresponse.cpp | 4278 | /*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "describeinstanceshealthresponse.h"
#include "describeinstanceshealthresponse_p.h"
#include <QDebug>
#include <QNetworkReply>
#include <QXmlStreamReader>
namespace QtAws {
namespace ElasticBeanstalk {
/*!
* \class QtAws::ElasticBeanstalk::DescribeInstancesHealthResponse
* \brief The DescribeInstancesHealthResponse class provides an interace for ElasticBeanstalk DescribeInstancesHealth responses.
*
* \inmodule QtAwsElasticBeanstalk
*
* <fullname>AWS Elastic Beanstalk</fullname>
*
* AWS Elastic Beanstalk makes it easy for you to create, deploy, and manage scalable, fault-tolerant applications running
* on the Amazon Web Services
*
* cloud>
*
* For more information about this product, go to the <a href="http://aws.amazon.com/elasticbeanstalk/">AWS Elastic
* Beanstalk</a> details page. The location of the latest AWS Elastic Beanstalk WSDL is <a
* href="https://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl">https://elasticbeanstalk.s3.amazonaws.com/doc/2010-12-01/AWSElasticBeanstalk.wsdl</a>.
* To install the Software Development Kits (SDKs), Integrated Development Environment (IDE) Toolkits, and command line
* tools that enable you to access the API, go to <a href="http://aws.amazon.com/tools/">Tools for Amazon Web
*
* Services</a>>
*
* <b>Endpoints</b>
*
* </p
*
* For a list of region-specific endpoints that AWS Elastic Beanstalk supports, go to <a
* href="https://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region">Regions and Endpoints</a> in the
* <i>Amazon Web Services
*
* \sa ElasticBeanstalkClient::describeInstancesHealth
*/
/*!
* Constructs a DescribeInstancesHealthResponse object for \a reply to \a request, with parent \a parent.
*/
DescribeInstancesHealthResponse::DescribeInstancesHealthResponse(
const DescribeInstancesHealthRequest &request,
QNetworkReply * const reply,
QObject * const parent)
: ElasticBeanstalkResponse(new DescribeInstancesHealthResponsePrivate(this), parent)
{
setRequest(new DescribeInstancesHealthRequest(request));
setReply(reply);
}
/*!
* \reimp
*/
const DescribeInstancesHealthRequest * DescribeInstancesHealthResponse::request() const
{
Q_D(const DescribeInstancesHealthResponse);
return static_cast<const DescribeInstancesHealthRequest *>(d->request);
}
/*!
* \reimp
* Parses a successful ElasticBeanstalk DescribeInstancesHealth \a response.
*/
void DescribeInstancesHealthResponse::parseSuccess(QIODevice &response)
{
//Q_D(DescribeInstancesHealthResponse);
QXmlStreamReader xml(&response);
/// @todo
}
/*!
* \class QtAws::ElasticBeanstalk::DescribeInstancesHealthResponsePrivate
* \brief The DescribeInstancesHealthResponsePrivate class provides private implementation for DescribeInstancesHealthResponse.
* \internal
*
* \inmodule QtAwsElasticBeanstalk
*/
/*!
* Constructs a DescribeInstancesHealthResponsePrivate object with public implementation \a q.
*/
DescribeInstancesHealthResponsePrivate::DescribeInstancesHealthResponsePrivate(
DescribeInstancesHealthResponse * const q) : ElasticBeanstalkResponsePrivate(q)
{
}
/*!
* Parses a ElasticBeanstalk DescribeInstancesHealth response element from \a xml.
*/
void DescribeInstancesHealthResponsePrivate::parseDescribeInstancesHealthResponse(QXmlStreamReader &xml)
{
Q_ASSERT(xml.name() == QLatin1String("DescribeInstancesHealthResponse"));
Q_UNUSED(xml) ///< @todo
}
} // namespace ElasticBeanstalk
} // namespace QtAws
| lgpl-3.0 |
mobilesec/openuat | src/org/codec/audio/common/AudioEncoder.java | 8192 | package org.codec.audio.common;
import org.codec.utils.ArrayUtils;
import org.codec.utils.Constants;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Copyright 2002 by the authors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Crista Lopes (lopes at uci dot edu)
* @version 1.0
*/
public class AudioEncoder implements Constants {
/**
* encodeStream is the public function of class org.codec.audio.Encoder.
*
* @param input the stream of bytes to encode
* @param output the stream of audio samples representing the input,
* prefixed with an hail signal and a calibration signal
*/
public static void encodeStream(InputStream input, OutputStream output) throws IOException {
byte[] zeros = new byte[kSamplesPerDuration];
//write out the hail and calibration sequences
output.write(zeros);
output.write(getHailSequence());
output.write(getCalibrationSequence());
//now write the data
int read = 0;
byte[] buff = new byte[kBytesPerDuration];
while ((read = input.read(buff)) == kBytesPerDuration) {
output.write(AudioEncoder.encodeDuration(buff));
}
if (read > 0) {
System.out.println("CHECK");
for (int i = read; i < kBytesPerDuration; i++) {
buff[i] = 0;
}
output.write(AudioEncoder.encodeDuration(buff));
output.write(AudioEncoder.encodeDuration(buff));
} else
output.write(AudioEncoder.encodeDuration(buff));
}
/**
* @param bitPosition the position in the kBytesPerDuration wide byte array for which you want a frequency
* @return the frequency in which to sound to indicate a 1 for this bitPosition
* NOTE!: This blindly assumes that bitPosition is in the range [0 - 7]
*/
public static double getFrequency(int bitPosition) {
return Constants.kFrequencies[bitPosition];
}
/**
* @param input a kBytesPerDuration long array of bytes to encode
* @return an array of audio samples of type AudioUtil.kDefaultFormat
*/
private static byte[] encodeDuration(byte[] input) {
double[] signal = new double[kSamplesPerDuration];
for (int j = 0; j < kBytesPerDuration; j++) {
for (int k = 0; k < kBitsPerByte; k++) {
if (((input[j] >> k) & 0x1) == 0) {
//no need to go through encoding a zero
continue;
}
//add a sinusoid of getFrequency(j), amplitude kAmplitude and duration kDuration
double innerMultiplier = getFrequency((j * kBitsPerByte) + k)
* (1 / kSamplingFrequency) * 2 * Math.PI;
for (int l = 0; l < signal.length; l++) {
signal[l] = signal[l] + (kAmplitude * Math.cos(innerMultiplier * l));
}
}
}
return ArrayUtils.getByteArrayFromDoubleArray(smoothWindow(signal));
}
/**
* @return audio samples for a duration of the hail frequency, org.codec.utils.Constants.kHailFrequency
*/
private static byte[] getHailSequence() {
double[] signal = new double[kSamplesPerDuration];
//add a sinusoid of the hail frequency, amplitude kAmplitude and duration kDuration
double innerMultiplier = Constants.kHailFrequency * (1 / kSamplingFrequency) * 2 * Math.PI;
for (int l = 0; l < signal.length; l++) {
signal[l] = /*kAmplitude **/ Math.cos(innerMultiplier * l);
}
return ArrayUtils.getByteArrayFromDoubleArray(smoothWindow(signal, 0.3));
}
/**
* @return audio samples (of length 2 * kSamplesPerDuration), used to calibrate the decoding
*/
private static byte[] getCalibrationSequence() {
byte[] results = new byte[2 * kSamplesPerDuration];
byte[] inputBytes1 = new byte[kBytesPerDuration];
byte[] inputBytes2 = new byte[kBytesPerDuration];
for (int i = 0; i < kBytesPerDuration; i++) {
inputBytes1[i] = (byte) 0xAA;
inputBytes2[i] = (byte) 0x55;
}
//encode inputBytes1 and 2 in sequence
byte[] partialResult = encodeDuration(inputBytes1);
for (int k = 0; k < kSamplesPerDuration; k++) {
results[k] = partialResult[k];
}
partialResult = encodeDuration(inputBytes2);
for (int k = 0; k < kSamplesPerDuration; k++) {
results[k + kSamplesPerDuration] = partialResult[k];
}
return results;
}
/**
* About smoothwindow.
* This is a data set in with the following form:
* <p/>
* |
* 1 | +-------------------+
* | / \
* |/ \
* +--|-------------------|--+---
* 0.01 0.09 0.1 time
* <p/>
* It is used to smooth the edges of the signal in each duration
*/
private static double[] smoothWindow(double[] input, double magicScalingNumber) {
double[] smoothWindow = new double[input.length];
double minVal = 0;
double maxVal = 0;
int peaks = (int) (input.length * 0.2
);
double steppingValue = 1 / (double) peaks;
for (int i = 0; i < smoothWindow.length; i++) {
if (i < peaks) {
smoothWindow[i] = input[i] * (steppingValue * i) /* / magicScalingNumber*/;
} else if (i > input.length - peaks) {
smoothWindow[i] = input[i] * (steppingValue * (input.length - i - 1)) /* / magicScalingNumber */;
} else {
//don't touch the middle values
smoothWindow[i] = input[i] /* / magicScalingNumber */;
}
if (smoothWindow[i] < minVal) {
minVal = smoothWindow[i];
}
if (smoothWindow[i] > maxVal) {
maxVal = smoothWindow[i];
}
}
return smoothWindow;
}
private static double[] smoothWindow(double[] input) {
double magicScalingNumber = 0.8;
return smoothWindow(input, magicScalingNumber);
}
/**
* This isn't used at the moment, but it does sound nice
*/
private static double[] blackmanSmoothWindow(double[] input) {
double magicScalingNumber = 3.5;
double[] smoothWindow = new double[input.length];
double steppingValue = 2 * Math.PI / (input.length - 1);
double maxVal = 0;
double minVal = 0;
for (int i = 0; i < smoothWindow.length; i++) {
smoothWindow[i] = (input[i] * (0.42 - 0.5 * Math.cos(steppingValue * i) +
0.08 * Math.cos(steppingValue * i))) * 3.5;
if (smoothWindow[i] < minVal) {
minVal = smoothWindow[i];
}
if (smoothWindow[i] > maxVal) {
maxVal = smoothWindow[i];
}
}
return smoothWindow;
}
}
| lgpl-3.0 |
esohns/libACENetwork | test_u/client_server/test_u_module_headerparser.cpp | 3920 | /***************************************************************************
* Copyright (C) 2009 by Erik Sohns *
* [email protected] *
* *
* 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "stdafx.h"
//#include "ace/Synch.h"
#include "test_u_stream.h"
#include "test_u_sessionmessage.h"
#include "test_u_module_headerparser.h"
#include "ace/Log_Msg.h"
#include "net_macros.h"
#include "test_u_defines.h"
#include "test_u_message.h"
Test_U_Module_HeaderParser::Test_U_Module_HeaderParser (ISTREAM_T* stream_in)
: inherited (stream_in)
{
NETWORK_TRACE (ACE_TEXT ("Test_U_Module_HeaderParser::Test_U_Module_HeaderParser"));
}
bool
Test_U_Module_HeaderParser::initialize (const struct ClientServer_ModuleHandlerConfiguration& configuration_in,
Stream_IAllocator* allocator_in)
{
NETWORK_TRACE (ACE_TEXT ("Test_U_Module_HeaderParser::initialize"));
// sanity check(s)
if (inherited::isInitialized_)
{
} // end IF
return inherited::initialize (configuration_in,
allocator_in);
}
void
Test_U_Module_HeaderParser::handleDataMessage (Test_U_Message*& message_inout,
bool& passMessageDownstream_out)
{
NETWORK_TRACE (ACE_TEXT ("Test_U_Module_HeaderParser::handleDataMessage"));
// don't care (implies yes per default, if part of a stream)
ACE_UNUSED_ARG (passMessageDownstream_out);
// // interpret the message header...
// Net_Remote_Comm::MessageHeader message_header = message_inout->getHeader ();
//ACE_DEBUG ((LM_DEBUG,
// ACE_TEXT ("received protocol message (ID: %u): [length: %u; type: \"%s\"]...\n"),
// message_inout->getID (),
// message_header.messageLength,
// ACE_TEXT (Net_Message::CommandType2String (message_header.messageType).c_str ())));
}
void
Test_U_Module_HeaderParser::dump_state () const
{
NETWORK_TRACE (ACE_TEXT ("Test_U_Module_HeaderParser::dump_state"));
// ACE_DEBUG ((LM_DEBUG,
// ACE_TEXT (" ***** MODULE: \"%s\" state *****\n"),
// ACE_TEXT (inherited::name ())));
//
// ACE_DEBUG ((LM_DEBUG,
// ACE_TEXT (" ***** MODULE: \"%s\" state *****\\END\n"),
// ACE_TEXT (inherited::name ())));
}
//////////////////////////////////////////
//Net_Export const char libacenetwork_default_test_u_headerparser_module_name_string[] =
// ACE_TEXT_ALWAYS_CHAR (TEST_U_STREAM_MODULE_HEADERPARSER_NAME);
const char libacenetwork_default_test_u_headerparser_module_name_string[] =
ACE_TEXT_ALWAYS_CHAR (TEST_U_STREAM_MODULE_HEADERPARSER_NAME);
| lgpl-3.0 |
mkelly1495/montessoricompass | app/view/activity/ActivityReports.js | 868 |
Ext.define("MontessoriCompass.view.activity.ActivityReports",{
extend: "Ext.navigation.View",
xtype: 'activityreports',
requires: [
"MontessoriCompass.view.activity.ActivityReportsController",
"MontessoriCompass.view.activity.ActivityReportsModel",
'Ext.dataview.List'
],
controller: "activityreports",
viewModel: {
type: "activityreports"
},
items: [
{
xtype: 'list',
title: 'Activities',
store: {
model: 'MontessoriCompass.model.Activity',
proxy: {
type: 'memory'
}
},
itemTpl: ['<div><tpl if="isNew"><b></tpl>{title}<tpl if="isNew"></b></tpl></div>'],
listeners: {
itemsingletap: 'onActivitySelected'
}
}
]
});
| lgpl-3.0 |
souvikdc9/aadhaarapi.net | Source/Uidai.Aadhaar.Sample/Auth.cs | 4012 | using System;
using System.Threading.Tasks;
using Uidai.Aadhaar.Agency;
using Uidai.Aadhaar.Api;
using Uidai.Aadhaar.Device;
using Uidai.Aadhaar.Resident;
using Uidai.Aadhaar.Security;
namespace Uidai.Aadhaar.Sample
{
public class Auth
{
private static readonly string BiometricData = "Rk1SACAyMAAAAADkAAgAyQFnAMUAxQEAAAARIQBqAGsgPgCIAG0fRwC2AG2dSQBVAIUjPABuALShMgCxAL0jMAByAM6lPgCmAN2kQQBwAN8qNAB1AN8mPADJAOcgOQA8AOorNABoAOomOQC+AO2fMQDFAPqlSgCvAP8lRQB8AQuhPABwAQ4fMgB7ASqcRADAAS4iNwCkATMeMwCFATYeNwBLATYwMQBWATcoMQCkATecMQBEATwyMgBJAUciQQCkAU8cNQB9AVQWNgCEAVUVRACoAVgYOgBBAV69NgCsAWeYNwAA";
public static AadhaarOptions Options { get; set; }
public static ISigner Signer { get; set; }
public static IVerifier Verifier { get; set; }
public static async Task AuthenticateAsync()
{
#region Device Level
// Set Personal Info
var personalInfo = new PersonalInfo
{
AadhaarNumber = "999999990019",
Demographic = new Demographic
{
Identity = new Identity
{
Name = "Shivshankar Choudhury",
DateOfBirth = new DateTime(1968, 5, 13, 0, 0, 0),
Gender = Gender.Male,
Phone = "2810806979",
Email = "[email protected]"
},
Address = new Address
{
Street = "12 Maulana Azad Marg",
State = "New Delhi",
Pincode = "110002"
}
}
};
personalInfo.Biometrics.Add(new Biometric
{
Type = BiometricType.Minutiae,
Position = BiometricPosition.LeftIndex,
Data = BiometricData
});
// Set Device Info
var deviceContext = new AuthContext
{
HasResidentConsent = true, // Should not be hardcoded in production environment.
DeviceInfo = Options.DeviceInfo.Create()
};
// Encrypt Data
using (var sessionKey = new SessionKey(Options.UidaiEncryptionKeyPath, false))
await deviceContext.EncryptAsync(personalInfo, sessionKey);
#endregion
#region Device to Agency
// TODO: Wrap DeviceContext{T} into AUA specific protocol and send it to AUA.
// On Device Side:
// var deviceXml = deviceContext.ToXml();
// var wrapped = WrapIntoAuaProtocol(deviceXml);
// On Agency Side:
// var auaXml = UnwrapFromAuaProtocol(wrapped);
// var auaContext = new AuthContext();
// auaContext.FromXml(auaXml);
#endregion
#region Agency Level
// Perform Authentication
var apiClient = new AuthClient
{
AgencyInfo = Options.AgencyInfo,
Request = new AuthRequest(deviceContext) { Signer = Signer },
Response = new AuthResponse { Verifier = Verifier }
};
await apiClient.GetResponseAsync();
Console.WriteLine(string.IsNullOrEmpty(apiClient.Response.ErrorCode)
? $"Is the user authentic: {apiClient.Response.IsAuthentic}"
: $"Error Code: {apiClient.Response.ErrorCode}");
// Review Error, if any
apiClient.Response.AuthInfo.Decode();
var mismatch = string.Join(", ", apiClient.Response.AuthInfo.GetMismatch());
if (!string.IsNullOrEmpty(mismatch))
Console.WriteLine($"Mismatch Attributes: {mismatch}");
#endregion
#region Agency To Device
// TODO: Wrap AuthResponse into AUA specific protocol and send it to device.
#endregion
}
}
} | lgpl-3.0 |
mishley/MooseEdit | TooltipFrame.cpp | 324 | #include "TooltipFrame.h"
#include "ui_TooltipFrame.h"
TooltipFrame::TooltipFrame(QWidget *parent) :
QFrame(parent, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool),
ui(new Ui::TooltipFrame)
{
setAttribute(Qt::WA_ShowWithoutActivating);
ui->setupUi(this);
}
TooltipFrame::~TooltipFrame()
{
delete ui;
}
| lgpl-3.0 |
SkywarnRussia/BALTRAD | baltrad_wms.py | 6934 | #!/usr/bin/env python
# read config
import ConfigParser
from configurator import *
settings = read_config()
from db_setup import *
import mapscript
def get_query_layer(layer_name):
if "_contour" in layer_name:
layer_name = layer_name.replace("_contour","")
return layer_name
def wms_request(req,settings):
map_object = mapscript.mapObj( settings["mapfile_path"] )
request_type = req.getValueByName("REQUEST")
if request_type==None:
raise Exception ( "WMS parameter request is missing!" )
time_value = req.getValueByName("TIME")
opacity = req.getValueByName("OPACITY")
layers = {}
contour = settings["enable_contour_maps"]
if req.getValueByName("LAYERS")!=None:
layers_list = req.getValueByName("LAYERS").split(",")
elif req.getValueByName("LAYER")!=None: #legend
layers_list = [req.getValueByName("LAYER")]
else:
layers_list = None
# create layers
config_dataset_names,config_sections = get_sections_from_config()
for dataset_name in config_sections:
new_layer_name = config.get(dataset_name, "name")
new_layer_title = config.get(dataset_name, "title")
# do not write styles for layers that are not queried
if layers_list:
if (not new_layer_name in layers_list and\
not new_layer_name+"_contour" in layers_list):
continue
if contour:
layer_names = (new_layer_name,new_layer_name+"_contour")
else:
layer_names = (new_layer_name,)
for l_name in layer_names:
processing = []
layers[l_name] = mapscript.layerObj(map_object)
layers[l_name].name = l_name
if "_contour" in l_name:
layers[l_name].type = mapscript.MS_LAYER_LINE
layers[l_name].connectiontype = mapscript.MS_CONTOUR
new_layer_title += " contour"
layers[l_name].addProcessing( "CONTOUR_INTERVAL=0" )
layers[l_name].addProcessing( "CONTOUR_ITEM=pixel" )
layers[l_name].setGeomTransform( "smoothsia([shape], 5)" )
else:
layers[l_name].type = mapscript.MS_LAYER_RASTER
layers[l_name].classitem = "[pixel]"
layers[l_name].status = mapscript.MS_ON
if str(opacity).isdigit():
layers[l_name].opacity = int(opacity)
else:
layers[l_name].opacity = 70 # default opacity
layers[l_name].metadata.set("wms_title", new_layer_title)
layers[l_name].metadata.set("wms_timeitem", "TIFFTAG_DATETIME")
layers[l_name].template = "featureinfo.html"
# set style class
class_name_config = config.get(dataset_name, "style")
for class_values in config.items ( class_name_config ):
item = class_values[1].split (",")
c = mapscript.classObj( layers[l_name] )
style = mapscript.styleObj(c)
c.setExpression( "([pixel] > %s AND [pixel] <= %s)" % (item[1],item[2]) )
if "_contour" in l_name:
processing.append(item[1])
style.width = 2
style.color.setRGB( 0,0,0 )
processing.append(item[1])
else:
c.name = class_values[0]
c.title = item[0]
colors = map(int,item[3:6])
style.color.setRGB( *colors )
if "_contour" in l_name:
processing.reverse()
layers[l_name].type = mapscript.MS_LAYER_LINE
layers[l_name].addProcessing( "CONTOUR_LEVELS=%s" % ",".join(processing) )
if "capabilities" in request_type.lower():
# set online resource
map_object.web.metadata.set("wms_onlineresource", \
config.get("locations","online_resource") )
# write timestamps
for layer_name in layers.keys():
if contour:
layer_types = ("","_contour")
else:
layer_types = ("",)
for layer_type in layer_types:
radar_datasets = session.query(RadarDataset)\
.filter(RadarDataset.name==layer_name)\
.order_by(RadarDataset.timestamp.desc()).all()
radar_timestamps = []
for r in radar_datasets:
radar_timestamps.append(r.timestamp.strftime("%Y-%m-%dT%H:%M:00Z"))
if len(radar_timestamps)==0:
continue
layers[layer_name+layer_type].metadata.set("wms_timeextent", ",".join(radar_timestamps))
layers[layer_name+layer_type].metadata.set("wms_timedefault", radar_timestamps[0])
# setup projection definition
projdef = radar_datasets[0].projdef
if not "epsg" in projdef:
projdef = "epsg:3785" # quite near default settings, affects only bounding boxes
layers[layer_name+layer_type].setProjection( projdef )
layers[layer_name+layer_type].data = radar_datasets[0].geotiff_path
bbox = radar_datasets[0].bbox_original
bbox = map(float, bbox.split(","))
layers[layer_name+layer_type].setExtent( *bbox )
elif time_value not in (None,"-1",""):
# dataset is a combination of timetamp and layer name
time_object = datetime.strptime(time_value,"%Y-%m-%dT%H:%M:00Z")
for layer_name in layers_list:
radar_dataset = session.query(RadarDataset)\
.filter(RadarDataset.name==get_query_layer(layer_name))\
.filter(RadarDataset.timestamp==time_object).one()
layers[layer_name].data = radar_dataset.geotiff_path
layers[layer_name].setProjection( radar_dataset.projdef )
# lon/lat bbox
bbox = map(float,radar_dataset.bbox_original.split(",") )
layers[layer_name].setExtent( *bbox )
else:
for layer_name in layers_list:
# get newest result if timestamp is missing
radar_dataset = session.query(RadarDataset)\
.filter(RadarDataset.name==get_query_layer(layer_name))\
.order_by(RadarDataset.timestamp.desc()).all()
layers[layer_name].data = radar_dataset[0].geotiff_path
layers[layer_name].setProjection( radar_dataset[0].projdef )
bbox = map(float,radar_dataset[0].bbox_original.split(",") )
layers[layer_name].setExtent( *bbox )
session.close()
return map_object
if __name__ == '__main__': # CGI
settings = read_config()
req = mapscript.OWSRequest()
req.loadParams()
map_object = wms_request(req,settings)
# dispatch
map_object.OWSDispatch( req )
| lgpl-3.0 |
TheAnswer/FirstTest | bin/scripts/skills/creatureSkills/lok/npcs/miscAttacks.lua | 3472 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--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 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
miscAttack1 = {
attackname = "miscAttack1",
animation = "creature_attack_light",
requiredWeaponType = NONE,
range = 10,
damageRatio = 1.2,
speedRatio = 4,
areaRange = 0,
accuracyBonus = 0,
knockdownChance = 0,
postureDownChance = 0,
postureUpChance = 0,
dizzyChance = 0,
blindChance = 0,
stunChance = 0,
intimidateChance = 0,
CbtSpamBlock = "attack_block",
CbtSpamCounter = "attack_counter",
CbtSpamEvade = "attack_evade",
CbtSpamHit = "attack_hit",
CbtSpamMiss = "attack_miss",
invalidStateMask = 0,
invalidPostures = "",
instant = 0
}
AddRandomPoolAttackTargetSkill(miscAttack1)
---------------------------------------------------------------------------------------
miscAttack2 = {
attackname = "miscAttack2",
animation = "droid_attack_medium",
requiredWeaponType = RANGED,
range = 64,
damageRatio = 1.2,
speedRatio = 1,
coneAngle = 0,
accuracyBonus = 0,
knockdownChance = 0,
postureDownChance = 0,
postureUpChance = 0,
dizzyChance = 0,
blindChance = 0,
stunChance = 0,
intimidateChance = 10,
CbtSpamBlock = "attack_block",
CbtSpamCounter = "attack_counter",
CbtSpamEvade = "attack_evade",
CbtSpamHit = "attack_hit",
CbtSpamMiss = "attack_miss",
invalidStateMask = 0,
invalidPostures = "",
instant = 0
}
AddRandomPoolAttackTargetSkill(miscAttack2)
| lgpl-3.0 |
chandrureddy/kimchi-wok-chandra | plugins/kimchi/model/vmifaces.py | 6163 | #
# Project Kimchi
#
# Copyright IBM, Corp. 2014-2015
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import libvirt
import random
from lxml import etree, objectify
from wok.exception import InvalidParameter, MissingParameter
from wok.exception import NotFoundError, InvalidOperation
from ..xmlutils.interface import get_iface_xml
from config import CapabilitiesModel
from vms import DOM_STATE_MAP, VMModel
class VMIfacesModel(object):
def __init__(self, **kargs):
self.conn = kargs['conn']
self.caps = CapabilitiesModel(**kargs)
def get_list(self, vm):
macs = []
for iface in self.get_vmifaces(vm, self.conn):
macs.append(iface.mac.get('address'))
return macs
def create(self, vm, params):
conn = self.conn.get()
networks = conn.listNetworks() + conn.listDefinedNetworks()
networks = map(lambda x: x.decode('utf-8'), networks)
if params['type'] == 'network':
network = params.get("network")
if network is None:
raise MissingParameter('KCHVMIF0007E')
if network not in networks:
raise InvalidParameter('KCHVMIF0002E',
{'name': vm, 'network': network})
macs = (iface.mac.get('address')
for iface in self.get_vmifaces(vm, self.conn))
# user defined customized mac address
if 'mac' in params and params['mac']:
# make sure it is unique
if params['mac'] in macs:
raise InvalidParameter('KCHVMIF0009E',
{'name': vm, 'mac': params['mac']})
# otherwise choose a random mac address
else:
while True:
params['mac'] = VMIfacesModel.random_mac()
if params['mac'] not in macs:
break
dom = VMModel.get_vm(vm, self.conn)
os_data = VMModel.vm_get_os_metadata(dom, self.caps.metadata_support)
os_version, os_distro = os_data
xml = get_iface_xml(params, conn.getInfo()[0], os_distro, os_version)
flags = 0
if dom.isPersistent():
flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG
if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
flags |= libvirt.VIR_DOMAIN_AFFECT_LIVE
dom.attachDeviceFlags(xml, flags)
return params['mac']
@staticmethod
def get_vmifaces(vm, conn):
dom = VMModel.get_vm(vm, conn)
xml = dom.XMLDesc(0)
root = objectify.fromstring(xml)
return root.devices.findall("interface")
@staticmethod
def random_mac():
mac = [0x52, 0x54, 0x00,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff)]
return ':'.join(map(lambda x: u'%02x' % x, mac))
class VMIfaceModel(object):
def __init__(self, **kargs):
self.conn = kargs['conn']
def _get_vmiface(self, vm, mac):
ifaces = VMIfacesModel.get_vmifaces(vm, self.conn)
for iface in ifaces:
if iface.mac.get('address') == mac:
return iface
return None
def lookup(self, vm, mac):
info = {}
iface = self._get_vmiface(vm, mac)
if iface is None:
raise NotFoundError("KCHVMIF0001E", {'name': vm, 'iface': mac})
info['type'] = iface.attrib['type']
info['mac'] = iface.mac.get('address')
if iface.find("model") is not None:
info['model'] = iface.model.get('type')
if info['type'] == 'network':
info['network'] = iface.source.get('network')
if info['type'] == 'bridge':
info['bridge'] = iface.source.get('bridge')
return info
def delete(self, vm, mac):
dom = VMModel.get_vm(vm, self.conn)
iface = self._get_vmiface(vm, mac)
if iface is None:
raise NotFoundError("KCHVMIF0001E", {'name': vm, 'iface': mac})
flags = 0
if dom.isPersistent():
flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG
if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
flags |= libvirt.VIR_DOMAIN_AFFECT_LIVE
dom.detachDeviceFlags(etree.tostring(iface), flags)
def update(self, vm, mac, params):
dom = VMModel.get_vm(vm, self.conn)
iface = self._get_vmiface(vm, mac)
if iface is None:
raise NotFoundError("KCHVMIF0001E", {'name': vm, 'iface': mac})
# cannot change mac address in a running system
if DOM_STATE_MAP[dom.info()[0]] != "shutoff":
raise InvalidOperation('KCHVMIF0011E')
# mac address is a required parameter
if 'mac' not in params:
raise MissingParameter('KCHVMIF0008E')
# new mac address must be unique
if self._get_vmiface(vm, params['mac']) is not None:
raise InvalidParameter('KCHVMIF0009E',
{'name': vm, 'mac': params['mac']})
flags = 0
if dom.isPersistent():
flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG
# remove the current nic
xml = etree.tostring(iface)
dom.detachDeviceFlags(xml, flags=flags)
# add the nic with the desired mac address
iface.mac.attrib['address'] = params['mac']
xml = etree.tostring(iface)
dom.attachDeviceFlags(xml, flags=flags)
return [vm, params['mac']]
| lgpl-3.0 |
dreamzor/alphaTab | Source/AlphaTab/Rendering/TabBarRenderer.cs | 7597 | /*
* This file is part of alphaTab.
* Copyright (c) 2014, Daniel Kuschny and Contributors, All rights reserved.
*
* 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 3.0 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.
*/
using AlphaTab.Model;
using AlphaTab.Platform;
using AlphaTab.Rendering.Glyphs;
using AlphaTab.Rendering.Utils;
namespace AlphaTab.Rendering
{
/// <summary>
/// This BarRenderer renders a bar using guitar tablature notation
/// </summary>
public class TabBarRenderer : GroupedBarRenderer
{
public const float LineSpacing = 10;
private BarHelpers _helpers;
public TabBarRenderer(Bar bar)
: base(bar)
{
}
public float LineOffset
{
get
{
return ((LineSpacing + 1) * Scale);
}
}
public override float GetNoteX(Note note, bool onEnd = true)
{
var beat = (TabBeatGlyph)GetOnNotesPosition(note.Beat.Voice.Index, note.Beat.Index);
if (beat != null)
{
return beat.Container.X + beat.X + beat.NoteNumbers.GetNoteX(note, onEnd);
}
return PostBeatGlyphsStart;
}
public float GetBeatX(Beat beat)
{
var bg = (TabBeatGlyph)GetPreNotesPosition(beat.Voice.Index, beat.Index);
if (bg != null)
{
return bg.Container.X + bg.X;
}
return 0;
}
public override float GetNoteY(Note note)
{
var beat = (TabBeatGlyph)GetOnNotesPosition(note.Beat.Voice.Index, note.Beat.Index);
if (beat != null)
{
return beat.NoteNumbers.GetNoteY(note);
}
return 0;
}
public override void DoLayout()
{
_helpers = Stave.StaveGroup.Helpers.Helpers[Bar.Track.Index][Bar.Index];
base.DoLayout();
Height = LineOffset * (Bar.Track.Tuning.Length - 1) + (NumberOverflow * 2);
if (Index == 0)
{
Stave.RegisterStaveTop(NumberOverflow);
Stave.RegisterStaveBottom(Height - NumberOverflow);
}
}
protected override void CreatePreBeatGlyphs()
{
if (Bar.MasterBar.IsRepeatStart)
{
AddPreBeatGlyph(new RepeatOpenGlyph(0, 0, 1.5f, 3));
}
// Clef
if (IsFirstOfLine)
{
AddPreBeatGlyph(new TabClefGlyph(0, 0));
}
AddPreBeatGlyph(new BarNumberGlyph(0, GetTabY(-1, -3), Bar.Index + 1, !Stave.IsFirstInAccolade));
if (Bar.IsEmpty)
{
AddPreBeatGlyph(new SpacingGlyph(0, 0, 30 * Scale, false));
}
}
protected override void CreateBeatGlyphs()
{
#if MULTIVOICE_SUPPORT
foreach (Voice v in Bar.Voices)
{
CreateVoiceGlyphs(v);
}
#else
CreateVoiceGlyphs(Bar.Voices[0]);
#endif
}
private void CreateVoiceGlyphs(Voice v)
{
for (int i = 0, j = v.Beats.Count; i < j; i++)
{
var b = v.Beats[i];
var container = new TabBeatContainerGlyph(b);
container.PreNotes = new TabBeatPreNotesGlyph();
container.OnNotes = new TabBeatGlyph();
((TabBeatGlyph)container.OnNotes).BeamingHelper = _helpers.BeamHelperLookup[v.Index][b.Index];
container.PostNotes = new TabBeatPostNotesGlyph();
AddBeatGlyph(container);
}
}
protected override void CreatePostBeatGlyphs()
{
if (Bar.MasterBar.IsRepeatEnd)
{
AddPostBeatGlyph(new RepeatCloseGlyph(X, 0));
if (Bar.MasterBar.RepeatCount > 2)
{
var line = IsLast || IsLastOfLine ? -1 : -4;
AddPostBeatGlyph(new RepeatCountGlyph(0, GetTabY(line, -3), Bar.MasterBar.RepeatCount));
}
}
else if (Bar.MasterBar.IsDoubleBar)
{
AddPostBeatGlyph(new BarSeperatorGlyph(0, 0));
AddPostBeatGlyph(new SpacingGlyph(0, 0, 3 * Scale, false));
AddPostBeatGlyph(new BarSeperatorGlyph(0, 0));
}
else if (Bar.NextBar == null || !Bar.NextBar.MasterBar.IsRepeatStart)
{
AddPostBeatGlyph(new BarSeperatorGlyph(0, 0, IsLast));
}
}
public override float TopPadding
{
get { return NumberOverflow; }
}
public override float BottomPadding
{
get { return NumberOverflow; }
}
/// <summary>
/// Gets the relative y position of the given steps relative to first line.
/// </summary>
/// <param name="line">the amount of steps while 2 steps are one line</param>
/// <param name="correction"></param>
/// <returns></returns>
public float GetTabY(int line, float correction = 0)
{
return (LineOffset * line) + (correction * Scale);
}
/// <summary>
/// gets the padding needed to place numbers within the bounding box
/// </summary>
public float NumberOverflow
{
get
{
var res = Resources;
return (res.TablatureFont.Size / 2) + (res.TablatureFont.Size * 0.2f);
}
}
protected override void PaintBackground(float cx, float cy, ICanvas canvas)
{
base.PaintBackground(cx, cy, canvas);
var res = Resources;
//
// draw string lines
//
canvas.Color = res.StaveLineColor;
var lineY = cy + Y + NumberOverflow;
for (int i = 0, j = Bar.Track.Tuning.Length; i < j; i++)
{
if (i > 0) lineY += LineOffset;
canvas.BeginPath();
canvas.MoveTo(cx + X, (int)lineY);
canvas.LineTo(cx + X + Width, (int)lineY);
canvas.Stroke();
}
canvas.Color = res.MainGlyphColor;
// Info guides for debugging
//DrawInfoGuide(canvas, cx, cy, 0, new Color(255, 0, 0)); // top
//DrawInfoGuide(canvas, cx, cy, stave.StaveTop, new Color(0, 255, 0)); // stavetop
//DrawInfoGuide(canvas, cx, cy, stave.StaveBottom, new Color(0,255,0)); // stavebottom
//DrawInfoGuide(canvas, cx, cy, Height, new Color(255, 0, 0)); // bottom
}
//private void DrawInfoGuide(ICanvas canvas, int cx, int cy, int y, Color c)
//{
// canvas.Color = c;
// canvas.BeginPath();
// canvas.MoveTo(cx + X, cy + Y + y);
// canvas.LineTo(cx + X + Width, cy + Y + y);
// canvas.Stroke();
//}
}
}
| lgpl-3.0 |
theFisher86/MBINCompiler | libMBIN/Source/Models/Structs/GcPhotoBuilding.cs | 302 | namespace libMBIN.Models.Structs
{
public class GcPhotoBuilding : NMSTemplate
{
public enum PhotoBuildingTypeEnum { Shelter, Abandoned, Shop, Outpost, RadioTower, Observatory, Depot, Monolith, Factory, Portal, Ruin, MissionTower }
public PhotoBuildingTypeEnum PhotoBuildingType;
}
}
| lgpl-3.0 |
tkaczmarzyk/beandiff | src/main/scala/org/beandiff/support/AnnotationUtil.scala | 2397 | /**
* Copyright (c) 2012-2013, Tomasz Kaczmarzyk.
*
* This file is part of BeanDiff.
*
* BeanDiff 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.
*
* BeanDiff 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 BeanDiff; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.beandiff.support
import java.lang.annotation.Annotation
import java.lang.reflect.Field
import org.beandiff.support.ObjectSupport.RichObject
import java.lang.reflect.Method
object AnnotationUtil {
implicit def enrich(o: Any): AnnotationUtil = new AnnotationUtil(o)
}
class AnnotationUtil(target: Any) {
def annotatedFields[A <:Annotation](implicit m: Manifest[A]): Traversable[Field] = {
val anno = m.erasure.asInstanceOf[Class[Annotation]]
target.allClasses.foldLeft(List[Field]())(
(acc: List[Field], clazz: Class[_]) => acc ++ annotatedFields(anno, clazz))
}
private def annotatedFields[A <:Annotation, T](anno: Class[A], clazz: Class[T]): Traversable[Field] = {
val annotated = clazz.getDeclaredFields().filter(_.getAnnotation(anno) != null)
annotated.map((f: Field) => {
f.setAccessible(true)
f
})
}
def annotatedMethods[A <:Annotation](implicit m: Manifest[A]): Traversable[Method] = {
val anno = m.erasure.asInstanceOf[Class[Annotation]]
target.allClasses.foldLeft(List[Method]())(
(acc: List[Method], clazz: Class[_]) => acc ++ annotatedMethods(anno, clazz))
}
private def annotatedMethods[A <:Annotation, T](anno: Class[A], clazz: Class[T]): Traversable[Method] = {
val annotated = clazz.getDeclaredMethods().filter(_.getAnnotation(anno) != null)
val paramlessNonVoid = annotated.filter((m: Method) => {
m.getParameterTypes().isEmpty && m.getReturnType() != null
})
paramlessNonVoid.map((m: Method) => {
m.setAccessible(true)
m
})
}
} | lgpl-3.0 |
pcolby/libqtaws | src/s3/getbucketaclresponse.cpp | 2629 | /*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws 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.
QtAws 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 the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "getbucketaclresponse.h"
#include "getbucketaclresponse_p.h"
#include <QDebug>
#include <QNetworkReply>
#include <QXmlStreamReader>
namespace QtAws {
namespace S3 {
/*!
* \class QtAws::S3::GetBucketAclResponse
* \brief The GetBucketAclResponse class provides an interace for S3 GetBucketAcl responses.
*
* \inmodule QtAwsS3
*
*
* \sa S3Client::getBucketAcl
*/
/*!
* Constructs a GetBucketAclResponse object for \a reply to \a request, with parent \a parent.
*/
GetBucketAclResponse::GetBucketAclResponse(
const GetBucketAclRequest &request,
QNetworkReply * const reply,
QObject * const parent)
: S3Response(new GetBucketAclResponsePrivate(this), parent)
{
setRequest(new GetBucketAclRequest(request));
setReply(reply);
}
/*!
* \reimp
*/
const GetBucketAclRequest * GetBucketAclResponse::request() const
{
Q_D(const GetBucketAclResponse);
return static_cast<const GetBucketAclRequest *>(d->request);
}
/*!
* \reimp
* Parses a successful S3 GetBucketAcl \a response.
*/
void GetBucketAclResponse::parseSuccess(QIODevice &response)
{
//Q_D(GetBucketAclResponse);
QXmlStreamReader xml(&response);
/// @todo
}
/*!
* \class QtAws::S3::GetBucketAclResponsePrivate
* \brief The GetBucketAclResponsePrivate class provides private implementation for GetBucketAclResponse.
* \internal
*
* \inmodule QtAwsS3
*/
/*!
* Constructs a GetBucketAclResponsePrivate object with public implementation \a q.
*/
GetBucketAclResponsePrivate::GetBucketAclResponsePrivate(
GetBucketAclResponse * const q) : S3ResponsePrivate(q)
{
}
/*!
* Parses a S3 GetBucketAcl response element from \a xml.
*/
void GetBucketAclResponsePrivate::parseGetBucketAclResponse(QXmlStreamReader &xml)
{
Q_ASSERT(xml.name() == QLatin1String("GetBucketAclResponse"));
Q_UNUSED(xml) ///< @todo
}
} // namespace S3
} // namespace QtAws
| lgpl-3.0 |
loopingz/webda | src/services/configuration.ts | 2544 | import { Service } from "../index";
interface ConfigurationProvider {
getConfiguration(id: string): Promise<Map<string, any>>;
}
/**
* Handle sessionSecret ( rolling between two secrets ) expire every hour
* Handle longTermSecret ( rolling between two longer secret ) expire every month
*/
export default class ConfigurationService extends Service {
protected _configuration: any;
protected _nextCheck: number;
protected _sourceService: any;
protected _sourceId: string;
private _interval: NodeJS.Timer | number;
async init() {
// Check interval by default every hour
if (!this._params.checkInterval) {
this._params.checkInterval = 3600;
}
if (!this._params.source) {
throw new Error("Need a source for ConfigurationService");
}
let source = this._params.source.split(":");
this._sourceService = this.getService(source[0]);
if (!this._sourceService) {
throw new Error(
'Need a valid service for source ("sourceService:sourceId")'
);
}
this._sourceId = source[1];
if (!this._sourceId) {
throw new Error('Need a valid source ("sourceService:sourceId")');
}
if (!this._sourceService.getConfiguration) {
throw new Error(
`Service ${
source[0]
} is not implementing ConfigurationProvider interface`
);
}
this._configuration = JSON.stringify(this._params.default);
await this._checkUpdate();
this._interval = setInterval(this._checkUpdate.bind(this), 1000);
}
stop() {
// @ts-ignore
clearInterval(this._interval);
}
async reinit(config: any): Promise<void> {
// Need to prevent any reinit
}
async _loadConfiguration(): Promise<Map<string, any>> {
return this._sourceService.getConfiguration(this._sourceId);
}
async _checkUpdate() {
if (this._nextCheck > new Date().getTime()) return;
this.log("DEBUG", "Refreshing configuration");
let newConfig = (await this._loadConfiguration()) || this._params.default;
if (JSON.stringify(newConfig) !== this._configuration) {
this.log("DEBUG", "Apply new configuration");
this._configuration = JSON.stringify(newConfig);
this._webda.reinit(newConfig);
}
this._updateNextCheck();
this.log(
"DEBUG",
"Next configuration refresh in",
this._params.checkInterval,
"s"
);
}
_updateNextCheck() {
this._nextCheck = new Date().getTime() + this._params.checkInterval * 1000;
}
}
export { ConfigurationProvider, ConfigurationService };
| lgpl-3.0 |
Allors/allors1 | Adapters/Allors.Adapters.Object.SqlClient/Predicates/AssociationInstanceOf.cs | 3117 | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssociationInstanceOf.cs" company="Allors bvba">
// Copyright 2002-2016 Allors bvba.
//
// Dual Licensed under
// a) the Lesser General Public Licence v3 (LGPL)
// b) the Allors License
//
// The LGPL License is included in the file lgpl.txt.
// The Allors License is an addendum to your contract.
//
// Allors Platform 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.
//
// For more information visit http://www.allors.com/legal
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Allors.Adapters.Object.SqlClient
{
using Allors.Meta;
using Adapters;
internal sealed class AssociationInstanceOf : Predicate
{
private readonly IAssociationType association;
private readonly IObjectType[] instanceClasses;
internal AssociationInstanceOf(ExtentFiltered extent, IAssociationType association, IObjectType instanceType, IObjectType[] instanceClasses)
{
extent.CheckAssociation(association);
PredicateAssertions.ValidateAssociationInstanceof(association, instanceType);
this.association = association;
this.instanceClasses = instanceClasses;
}
internal override bool BuildWhere(ExtentStatement statement, string alias)
{
var schema = statement.Mapping;
if (this.instanceClasses.Length == 1)
{
statement.Append(" (" + statement.GetJoinName(this.association) + "." + Mapping.ColumnNameForClass + " IS NOT NULL AND ");
statement.Append(" " + statement.GetJoinName(this.association) + "." + Mapping.ColumnNameForClass + "=" + statement.AddParameter(this.instanceClasses[0].Id) + ") ");
}
else if (this.instanceClasses.Length > 1)
{
statement.Append(" ( ");
for (var i = 0; i < this.instanceClasses.Length; i++)
{
statement.Append(" (" + statement.GetJoinName(this.association) + "." + Mapping.ColumnNameForClass + " IS NOT NULL AND ");
statement.Append(" " + statement.GetJoinName(this.association) + "." + Mapping.ColumnNameForClass + "=" + statement.AddParameter(this.instanceClasses[i].Id) + ")");
if (i < this.instanceClasses.Length - 1)
{
statement.Append(" OR ");
}
}
statement.Append(" ) ");
}
return this.Include;
}
internal override void Setup(ExtentStatement statement)
{
statement.UseAssociation(this.association);
statement.UseAssociationInstance(this.association);
}
}
} | lgpl-3.0 |
NeoFragCMS/neofrag-cms | themes/default/default.php | 8958 | <?php
/**
* https://neofr.ag
* @author: Michaël BILCOT <[email protected]>
*/
namespace NF\Themes\Default_;
use NF\NeoFrag\Addons\Theme;
class Default_ extends Theme
{
protected function __info()
{
return [
'title' => 'Thème par défaut',
'description' => 'Base de développement pour la création d\'un thème NeoFrag',
'link' => 'https://neofr.ag',
'author' => 'Michaël BILCOT & Jérémy VALENTIN <[email protected]>',
'license' => 'LGPLv3 <https://neofr.ag/license>',
'zones' => ['Haut', 'Entête', 'Avant-contenu', 'Contenu', 'Post-contenu', 'Pied de page']
];
}
public function __init()
{
$this ->css('bootstrap.min')
->css('icons/fontawesome.min')
->css('style')
->js('jquery-3.2.1.min')
->js('popper.min')
->js('bootstrap.min')
->js('bootstrap-notify.min')
->js('modal')
->js('notify');
}
public function styles_row()
{
//Nothing to do
}
public function styles_widget()
{
//Nothing to do
}
public function install($dispositions = [])
{
$header = function(){
return $this->row(
$this->col(
$this->widget($this->db->insert('nf_widgets', [
'widget' => 'header',
'type' => 'index',
'settings' => serialize([
'display' => 'logo',
'align' => 'text-left',
'title' => '',
'description' => '',
'color-title' => '',
'color-description' => ''
])
]))
)
)
->style('row-default');
};
$navbar = function(){
return $this->row(
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'navigation',
'type' => 'index',
'settings' => serialize([
'links' => [
[
'title' => utf8_htmlentities($this->lang('Accueil')),
'url' => ''
],
[
'title' => utf8_htmlentities($this->lang('Forum')),
'url' => 'forum'
],
[
'title' => utf8_htmlentities($this->lang('Équipes')),
'url' => 'teams'
],
[
'title' => utf8_htmlentities('Matchs'),
'url' => 'events/matches'
],
[
'title' => utf8_htmlentities('Partenaires'),
'url' => 'partners'
],
[
'title' => utf8_htmlentities('Palmarès'),
'url' => 'awards'
]
]
])
]))
->size('col-7')
),
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'user',
'type' => 'index_mini'
]))
->size('col-5')
)
)
->style('row-default');
};
$breadcrumb = function($search = TRUE){
return $this->row(
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'breadcrumb',
'type' => 'index'
]))
->size('col-8')
),
$search ? $this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'search',
'type' => 'index'
]))
->size('col-4')
) : NULL
)
->style('row-default');
};
$dispositions = $this->array();
$dispositions->set('*', 'Contenu', $this->array([
$breadcrumb(),
$this->row(
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'module',
'type' => 'index'
]))
->size('col-8')
),
$this ->col(
$this->widget($this->db->insert('nf_widgets', [
'widget' => 'navigation',
'type' => 'vertical',
'settings' => serialize([
'links' => [
[
'title' => utf8_htmlentities($this->lang('Actualités')),
'url' => 'news'
],
[
'title' => utf8_htmlentities($this->lang('Membres')),
'url' => 'members'
],
[
'title' => utf8_htmlentities('Recrutement'),
'url' => 'recruits'
],
[
'title' => utf8_htmlentities('Photos'),
'url' => 'gallery'
],
[
'title' => utf8_htmlentities($this->lang('Rechercher')),
'url' => 'search'
],
[
'title' => utf8_htmlentities($this->lang('Contact')),
'url' => 'contact'
]
]
])
])),
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'partners',
'type' => 'column',
'settings' => serialize([
'display_style' => 'dark'
])
]))
->style('panel-default'),
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'user',
'type' => 'index'
]))
->style('panel-default'),
$this->widget($this->db->insert('nf_widgets', [
'widget' => 'news',
'type' => 'categories'
])),
$this->widget($this->db->insert('nf_widgets', [
'widget' => 'talks',
'type' => 'index',
'settings' => serialize([
'talk_id' => 2
])
])),
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'members',
'type' => 'online'
]))
->style('panel-default')
)
->size('col-4')
)
->style('row-default')
]));
$dispositions->set('*', 'Avant-contenu', $this->array([
$this->row(
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'forum',
'type' => 'topics'
]))
->size('col-4')
),
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'news',
'type' => 'index'
]))
->style('panel-default')
->size('col-4')
),
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'members',
'type' => 'index'
]))
->style('panel-default')
->size('col-4')
)
)
->style('row-default')
]));
$dispositions->set('*', 'Entête', $this->array([
$header(),
$navbar()
]));
$dispositions->set('*', 'Haut', $this->array([
$this->row(
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'navigation',
'type' => 'index',
'settings' => serialize([
'links' => [
[
'title' => 'Facebook',
'url' => '#'
],
[
'title' => 'Twitter',
'url' => '#'
],
[
'title' => 'Origin',
'url' => '#'
],
[
'title' => 'Steam',
'url' => '#'
]
]
])
]))
->size('col-8')
),
$this->col(
$this->widget($this->db->insert('nf_widgets', [
'widget' => 'members',
'type' => 'online_mini'
]))
->size('col-4')
)
)
->style('row-default')
]));
$dispositions->set('*', 'Pied de page', $this->array([
$this->row(
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'copyright',
'type' => 'index'
]))
->style('panel-default')
)
)
->style('row-default')
]));
$dispositions->set('/', 'Entête', $this->array([
$header(),
$navbar(),
$this->row(
$this->col(
$this->widget($this->db->insert('nf_widgets', [
'widget' => 'slider',
'type' => 'index'
]))
)
)
->style('row-default')
]));
foreach (['forum/*', 'news/_news/*', 'user/*', 'search/*', 'gallery/*'] as $page)
{
$dispositions->set($page, 'Contenu', $this->array([
$breadcrumb($page != 'search/*'),
$this ->row(
$this->col(
$this->widget($this->db->insert('nf_widgets', [
'widget' => 'module',
'type' => 'index'
]))
)
)
->style('row-default')
]));
}
$dispositions->set('forum/*', 'Post-contenu', $this->array([
$this ->row(
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'forum',
'type' => 'statistics'
]))
->style('panel-default')
->size('col-4')
),
$this->col(
$this ->widget($this->db->insert('nf_widgets', [
'widget' => 'forum',
'type' => 'activity'
]))
->style('panel-default')
->size('col-8')
)
)
->style('row-default')
]));
return parent::install($dispositions);
}
public function uninstall($remove = TRUE)
{
return parent::uninstall($remove);
}
}
| lgpl-3.0 |
luquinhasbrito/pot-class | src/OTS_FileNode.php | 3572 | <?php
/**#@+
* @version 0.0.6
* @since 0.0.6
*/
/**
* Code in this file bases on oryginal OTServ binary format loading C++ code (fileloader.h, fileloader.cpp).
*
* @package POT
* @version 0.1.2
* @author Wrzasq <[email protected]>
* @copyright 2007 - 2008 (C) by Wrzasq
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public License, Version 3
*/
/**
* OTServ binary file node representation.
*
* <p>
* This file extends {@link OTS_Buffer OTS_Buffer class} for nodes tree logic with siblings and childs.
* </p>
*
* @package POT
* @version 0.1.2
* @property OTS_FileNode $next Next sibling node.
* @property OTS_FileNode $child First child node.
* @property int $type Node type.
*/
class OTS_FileNode extends OTS_Buffer
{
/**
* Next sibling node.
*
* @var OTS_FileNode
*/
private $next;
/**
* First child node.
*
* @var OTS_FileNode
*/
private $child;
/**
* Node type.
*
* @var int
*/
private $type;
/**
* Creates clone of object.
*
* <p>
* Creates complete tree copy by copying sibling and child nodes.
* </p>
*/
public function __clone()
{
// clones conencted nodes
if( isset($this->child) )
{
$this->child = clone $this->child;
}
if( isset($this->next) )
{
$this->next = clone $this->next;
}
}
/**
* Returs next sibling.
*
* @return OTS_FileNode Sibling node.
*/
public function getNext()
{
return $this->next;
}
/**
* Sets next sibling.
*
* @param OTS_FileNode Sibling node.
*/
public function setNext(OTS_FileNode $next)
{
$this->next = $next;
}
/**
* Returs first child.
*
* @return OTS_FileNode Child node.
*/
public function getChild()
{
return $this->child;
}
/**
* Sets first child.
*
* @param OTS_FileNode Child node.
*/
public function setChild(OTS_FileNode $child)
{
$this->child = $child;
}
/**
* Returs node type.
*
* @return int Node type.
*/
public function getType()
{
return $this->type;
}
/**
* Sets node type.
*
* @param int Node type.
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Magic PHP5 method.
*
* @version 0.1.2
* @since 0.1.0
* @param string $name Property name.
* @return mixed Property value.
* @throws OutOfBoundsException For non-supported properties.
* @throws E_OTS_OutOfBuffer When there is read attemp after end of stream.
*/
public function __get($name)
{
switch($name)
{
// simple properties
case 'next':
case 'child':
case 'type':
return $this->$name;
default:
return parent::__get($name);
}
}
/**
* Magic PHP5 method.
*
* @version 0.1.2
* @since 0.1.0
* @param string $name Property name.
* @param mixed $value Property value.
* @throws OutOfBoundsException For non-supported properties.
*/
public function __set($name, $value)
{
switch($name)
{
// simple properties
case 'next':
case 'child':
case 'type':
$this->$name = $value;
break;
default:
parent::__set($name, $value);
}
}
}
/**#@-*/
?>
| lgpl-3.0 |
loftuxab/community-edition-old | projects/alfresco-jlan/source/java/org/alfresco/jlan/debug/cluster/DebugClusterMessage.java | 1482 | /*
* Copyright (C) 2006-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.jlan.debug.cluster;
import org.alfresco.jlan.server.filesys.cache.hazelcast.ClusterMessage;
/**
* Debug Cluster Message Class
*
* @author gkspencer
*/
public class DebugClusterMessage extends ClusterMessage {
// Serialization id
private static final long serialVersionUID = 1L;
// Debug message
private String m_debugStr;
/**
* Class constructor
*
* @param fromNode String
* @param debugStr String
*/
public DebugClusterMessage( String fromNode, String debugStr) {
super( ClusterMessage.AllNodes, fromNode, 0);
m_debugStr = debugStr;
}
/**
* Return the debug string
*
* @return String
*/
public final String getDebugString() {
return m_debugStr;
}
}
| lgpl-3.0 |
BeSports/Goldmine-Server | src/enums/Types.js | 48 | export default {
VERTEX: 'v',
EDGE: 'e',
};
| lgpl-3.0 |
TKiura/MetBroker3 | MetBroker3/src/net/agmodel/chizudriver/DEMISMapServer.java | 5078 | package net.agmodel.chizudriver;
import java.awt.*;
import java.awt.image.*;
import java.util.Properties;
import net.agmodel.utility.*;
import net.agmodel.physical.*;
import net.agmodel.chizudata.*;
import net.agmodel.chizudriver.ChizuAccessMechanism;
//for testing only
//import net.agmodel.panel.MapPanel;
//import javax.media.jai.widget.ScrollingImagePanel;
//import javax.swing.*;
import org.apache.log4j.Category;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
*/
//first version http://www.demis.nl/mapserver/request.asp?REQUEST=Map&BBOX=125.630498533724,26.251322228051,130.633431085044,47.1211117895443&WIDTH=682&HEIGHT=749&LAYERS=Bathymetry,Countries,Topography,Coastlines,Waterbodies,Rivers,Streams,Borders,Cities,Ocean+features&FORMAT=PNG&WRAPDATELINE=TRUE
//from Nov 2003 http://www.demis.nl/mapserver/request.asp?WMTVER=1.0.0&REQUEST=Map&SRS=EPSG:4326&BBOX=125.630498533724,26.251322228051,130.633431085044,47.1211117895443&WIDTH=682&HEIGHT=749&LAYERS=Bathymetry,Countries,Topography,Coastlines,Waterbodies,Rivers,Streams,Borders,Cities,Ocean+features&FORMAT=PNG&WRAPDATELINE=TRUE
/**
* Requires the following permissions (at least)
* for chizubroker codeBase and driver codeBase
* SocketPermission to webservice renderv3.staging.mappoint.net
* RuntimePermission to access declared members
* PropertyPermission read and write
* NetPermission set default authenticator
* jwsdp stuff requires FilePermission read
* axis stuff requires AllPermission for now
*/
public class DEMISMapServer implements ChizuAccessMechanism, ImageObserver {
private ChizuSourceForDriver chizuSource;
private Properties prop;
private Category cat = null;
public DEMISMapServer(ChizuSourceForDriver source, Properties p){
this.chizuSource = source;
this.prop = p;
cat = source.getLog4jCategory();
}
public ChizuResult getChizu(ChizuRequest request) throws ConnectionException{
GeographicalBox requestBounds= request.getRegion().getBoundingBox();
Location2D nw=requestBounds.getNorthWestBound();
Location2D se=requestBounds.getSouthEastBound();
//&LAYERS=Bathymetry,Countries,Topography,Coastlines,Waterbodies,Rivers,Streams,Borders,Cities,Ocean+features&FORMAT=PNG&WRAPDATELINE=TRUE
StringBuffer mapURL=new StringBuffer(chizuSource.getParameterValue("mapServerurl")+"request.asp?WMTVER=1.0.0&REQUEST=Map&SRS=EPSG:4326&BBOX=");
double eastern=se.getLongitude();
double western=nw.getLongitude();
if (western>0 && eastern<0)
eastern=360+eastern;
mapURL.append(western+","+se.getLatitude()+","+eastern+","+nw.getLatitude());
mapURL.append("&WIDTH="+request.getWidth()+"&HEIGHT="+request.getHeight());
mapURL.append("&LAYERS=Bathymetry,Countries,Topography,Coastlines,Waterbodies,Rivers,Streams,Borders,Cities,Ocean+features&WRAPDATELINE=TRUE&FORMAT=PNG");
cat.info(mapURL);
return new ChizuResult(new net.agmodel.imageutil.URLImage(mapURL.toString()));
}
public void disconnectFromMetaData(){
}
public boolean connectForMetaData(String username, String password){
return true;
}
public void disconnectFromData(){
}
public void checkForDatabaseUpdates(){}
public boolean connectForData(String username, String password){
return true;
}
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
if ((infoflags & ImageObserver.ERROR)!=0) {
cat.error("Error retrieving image");
return false;
}
if ((infoflags & (ImageObserver.ALLBITS|ImageObserver.FRAMEBITS))!=0) {
return false;
}
return true;
}
/*
public static void main(String[] args){
// GeographicalBox tsukuba=new GeographicalBox(new Location2D(36.125,140.375),new Location2D(36.0,140.5));
GeographicalBox tsukuba=new GeographicalBox(new Location2D(38,139),new Location2D(36.0,141));
// GeographicalBox tsukuba=new GeographicalBox(new Location2D(47.55,-122.5),new Location2D(47.5,-122));
Rectangle screen=new Rectangle(0,0,600,400);
ChizuRequest request=new ChizuRequest(tsukuba.getCenter(),screen,net.agmodel.panel.MapPanel.fitScale(tsukuba,screen),"en","mappoint");
ChizuAccessMechanism testDriver=new DEMISMapServer(chizuSource,prop);
ChizuResult result=null;
try {
testDriver.connectForData("","");
result=testDriver.getChizu(request);
testDriver.disconnectFromData();
}
catch (ConnectionException c) {
c.printStackTrace();
System.exit(1);
}
BufferedImage image3=result.getImage().getBufferedImage();
int width = image3.getWidth();
int height = image3.getHeight();
// Attach image2 to a scrolling panel to be displayed.
ScrollingImagePanel panel = new ScrollingImagePanel(image3, width+5, height+5);
// Create a frame to contain the panel.
JFrame window = new JFrame("JAI Sample Program");
window.setDefaultCloseOperation(3);
window.getContentPane().add(panel);
window.pack();
window.show();
}
*/
} | lgpl-3.0 |
danzone/dspot | dspot/src/test/java/eu/stamp_project/utils/TypeUtilsTest.java | 1447 | package eu.stamp_project.utils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by Benjamin DANGLOT
* [email protected]
* on 07/08/17
*/
public class TypeUtilsTest {
@Test
public void testIsPrimitiveCollection() throws Exception {
/*
Should be named isSupportedCollectionType
*/
assertTrue(TypeUtils.isPrimitiveCollection(new ArrayList<Integer>()));
List<Integer> ints = new ArrayList<>();
ints.add(1);
assertTrue(TypeUtils.isPrimitiveCollection(ints));
assertTrue(TypeUtils.isPrimitiveCollection(Collections.singletonList(1)));
assertTrue(TypeUtils.isPrimitiveCollection(Collections.emptyList()));
assertTrue(TypeUtils.isPrimitiveCollection(Collections.singletonList("String")));
assertTrue(TypeUtils.isPrimitiveCollection(Collections.singleton(1)));
assertFalse(TypeUtils.isPrimitiveCollection(new int[]{1}));
assertFalse(TypeUtils.isPrimitiveCollection(Collections.singletonList(new Object())));
assertFalse(TypeUtils.isPrimitiveCollection(Collections.emptyMap()));
}
@Test
public void testIsPrimitiveMap() throws Exception {
assertTrue(TypeUtils.isPrimitiveMap(Collections.singletonMap(1,1)));
assertTrue(TypeUtils.isPrimitiveMap(Collections.emptyMap()));
assertFalse(TypeUtils.isPrimitiveMap(Collections.emptyList()));
}
}
| lgpl-3.0 |
exoplatform/platform-qa-ui | answer/src/main/java/org/exoplatform/platform/qa/ui/answer/pageobject/AnswerHomePage.java | 1912 | package org.exoplatform.platform.qa.ui.answer.pageobject;
import static com.codeborne.selenide.Selectors.byXpath;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.refresh;
import static org.exoplatform.platform.qa.ui.selenium.locator.answer.AnswerLocator.*;
import static org.exoplatform.platform.qa.ui.selenium.logger.Logger.info;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.Configuration;
import org.exoplatform.platform.qa.ui.selenium.TestBase;
import org.exoplatform.platform.qa.ui.selenium.testbase.ElementEventTestBase;
public class AnswerHomePage {
private final TestBase testBase;
private ElementEventTestBase evt;
/**
* constructor
*
* @param testBase
*/
public AnswerHomePage(TestBase testBase) {
this.testBase = testBase;
this.evt = testBase.getElementEventTestBase();
}
/**
* Go to home category
*/
public void goToHomeCategory() {
refresh();
if (ELEMENT_ICON_GO_TO_HOME_CATEGORIE.is(Condition.exist)) {
info("Go to home category");
ELEMENT_ICON_GO_TO_HOME_CATEGORIE.click();
}
}
/**
* Do quick search
*
* @param key
*/
public void doQuickSearch(String key) {
info("Do quick search");
$(ELEMENT_QUICK_SEARCH_INPUT).setValue(key);
$(ELEMENT_QUICK_SEARCH_BUTTON).click();
$(ELEENT_QUICK_SEARCH_POPUP).waitUntil(Condition.appears, Configuration.timeout);
}
/**
* Go to advance search
*/
public void goToAdvanceSearch() {
info("Go to advance search");
$(ELEMENT_QUICK_SEARCH_INPUT).setValue("search");
$(ELEMENT_QUICK_SEARCH_BUTTON).click();
$(ELEENT_QUICK_SEARCH_POPUP).waitUntil(Condition.appears, Configuration.timeout);
$(byXpath(ELEMENT_QUICK_SEARCH_ADVANCE_SEARCH_BUTTON)).click();
$(ELEMENT_ADVANCE_SEARCH_POPUP).waitUntil(Condition.appears, Configuration.timeout);
}
}
| lgpl-3.0 |
Ektorus/bohrium | vem/proxy/timing.cpp | 1413 | /*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <cstring>
#include <iostream>
#include <bh.h>
#include "timing.h"
#include <set>
static int bh_sleep = -1;
//Sleep a period based on BH_VEM_PROXY_SLEEP (in ms)
void timing_sleep(void)
{
if(bh_sleep == -1)
{
const char *str = getenv("BH_VEM_PROXY_SLEEP");
if(str == NULL)
bh_sleep = 0;
else
bh_sleep = atoi(str);
printf("sleep enabled: %dms\n", bh_sleep);
}
if(bh_sleep == 0)
return;
struct timespec tim, tim2;
tim.tv_sec = bh_sleep/1000;
tim.tv_nsec = bh_sleep%1000 * 1000000;
if(nanosleep(&tim , &tim2) < 0 )
fprintf(stderr,"Nano sleep system call failed \n");
}
| lgpl-3.0 |
swift-nav/piksi_tools | piksi_tools/simulator_almanac_generator.py | 2406 | #!/usr/bin/env python
# Copyright (C) 2011-2014 Swift Navigation Inc.
# Contact: Fergus Noble <[email protected]>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
# EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
# Auto-generate the simulation_data.c file from a given almanac.
# Written by Niels Joubert
# April 2014
from __future__ import print_function
import argparse
from .almanac import Almanac
def to_struct(sat):
return "{ \n\
.gps = { \n\
.ecc = %f,\n\
.toa = %f,\n\
.inc = %f,\n\
.rora = %f,\n\
.a = %f,\n\
.raaw = %f,\n\
.argp = %f,\n\
.ma = %f,\n\
.af0 = %f,\n\
.af1 = %f,\n\
.week = %d\n\
},\n\
.sid = { \n\
.constellation = %d,\n\
.band = %d,\n\
.sat = %d\n\
},\n\
.healthy = %d,\n\
.valid = %d,\n\
}" % (
sat.ecc,
sat.toa,
sat.inc,
sat.rora,
sat.a,
sat.raaw,
sat.argp,
sat.ma,
sat.af0,
sat.af1,
sat.week,
0, # CONSTELLATION_GPS
0, # BAND_L1
sat.prn,
sat.healthy,
1)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Swift Nav Almanac C Generator')
parser.add_argument(
"file", help="the almanac file to process into C structs")
args = parser.parse_args()
alm = Almanac()
with open(args.file) as f:
alm.process_yuma(f.readlines())
print("#include \"simulator_data.h\"")
print("/* AUTO-GENERATED FROM simulator_almanac_generator.py */\n")
print("u16 simulation_week_number = 1787;\n")
print("double simulation_sats_pos[%d][3];\n" % len(alm.sats))
print("double simulation_sats_vel[%d][3];\n" % len(alm.sats))
print("u32 simulation_fake_carrier_bias[%d];\n" % len(alm.sats))
print("u8 simulation_num_almanacs = %d;\n" % len(alm.sats))
print("const almanac_t simulation_almanacs[%d] = {" % len(alm.sats))
for s in alm.sats:
print("%s," % to_struct(s))
print("};")
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-webserver-webapi/src/test/java/org/sonar/server/permission/ws/template/SetDefaultTemplateActionTest.java | 8407 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.permission.ws.template;
import javax.annotation.Nullable;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.db.DbSession;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.l18n.I18nRule;
import org.sonar.server.permission.ws.BasePermissionWsTest;
import org.sonar.server.property.InternalProperties;
import org.sonar.server.ws.TestRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.resources.Qualifiers.VIEW;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class SetDefaultTemplateActionTest extends BasePermissionWsTest<SetDefaultTemplateAction> {
private I18nRule i18n = new I18nRule();
@Override
protected SetDefaultTemplateAction buildWsAction() {
return new SetDefaultTemplateAction(db.getDbClient(), newPermissionWsSupport(), newRootResourceTypes(), userSession, i18n);
}
@Test
public void update_project_default_template() {
PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate();
PermissionTemplateDto portfolioDefaultTemplate = db.permissionTemplates().insertTemplate();
PermissionTemplateDto applicationDefaultTemplate = db.permissionTemplates().insertTemplate();
db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, applicationDefaultTemplate, portfolioDefaultTemplate);
PermissionTemplateDto template = insertTemplate();
loginAsAdmin();
newRequest(template.getUuid(), Qualifiers.PROJECT);
assertDefaultTemplates(template.getUuid(), applicationDefaultTemplate.getUuid(), portfolioDefaultTemplate.getUuid());
}
@Test
public void update_project_default_template_without_qualifier_param() {
db.permissionTemplates().setDefaultTemplates("any-project-template-uuid", "any-view-template-uuid", null);
PermissionTemplateDto template = insertTemplate();
loginAsAdmin();
// default value is project qualifier's value
newRequest(template.getUuid(), null);
assertDefaultTemplates(template.getUuid(), "any-view-template-uuid", null);
}
@Test
public void update_project_default_template_by_template_name() {
PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate();
PermissionTemplateDto portfolioDefaultTemplate = db.permissionTemplates().insertTemplate();
PermissionTemplateDto applicationDefaultTemplate = db.permissionTemplates().insertTemplate();
db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, applicationDefaultTemplate, portfolioDefaultTemplate);
PermissionTemplateDto template = insertTemplate();
loginAsAdmin();
newRequest()
.setParam(PARAM_TEMPLATE_NAME, template.getName().toUpperCase())
.execute();
db.getSession().commit();
assertDefaultTemplates(template.getUuid(), applicationDefaultTemplate.getUuid(), portfolioDefaultTemplate.getUuid());
}
@Test
public void update_view_default_template() {
PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate();
db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, null, null);
PermissionTemplateDto template = insertTemplate();
loginAsAdmin();
newRequest(template.getUuid(), VIEW);
assertDefaultTemplates(projectDefaultTemplate.getUuid(), null, template.getUuid());
}
@Test
public void update_app_default_template() {
PermissionTemplateDto projectDefaultTemplate = db.permissionTemplates().insertTemplate();
db.permissionTemplates().setDefaultTemplates(projectDefaultTemplate, null, null);
PermissionTemplateDto template = insertTemplate();
loginAsAdmin();
newRequest(template.getUuid(), APP);
assertDefaultTemplates(projectDefaultTemplate.getUuid(), template.getUuid(), null);
}
@Test
public void fail_if_anonymous() {
PermissionTemplateDto template = insertTemplate();
userSession.anonymous();
assertThatThrownBy(() -> {
newRequest(template.getUuid(), PROJECT);
})
.isInstanceOf(UnauthorizedException.class);
}
@Test
public void fail_if_not_admin() {
PermissionTemplateDto template = insertTemplate();
userSession.logIn();
assertThatThrownBy(() -> {
newRequest(template.getUuid(), null);
})
.isInstanceOf(ForbiddenException.class);
}
@Test
public void fail_if_template_not_provided() {
assertThatThrownBy(() -> {
newRequest(null, PROJECT);
})
.isInstanceOf(BadRequestException.class);
}
@Test
public void fail_if_template_does_not_exist() {
assertThatThrownBy(() -> {
newRequest("unknown-template-uuid", PROJECT);
})
.isInstanceOf(NotFoundException.class);
}
@Test
public void fail_if_qualifier_is_not_root() {
PermissionTemplateDto template = insertTemplate();
loginAsAdmin();
assertThatThrownBy(() -> {
newRequest(template.getUuid(), Qualifiers.FILE);
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of parameter 'qualifier' (FIL) must be one of: [APP, TRK, VW]");
}
private void newRequest(@Nullable String templateUuid, @Nullable String qualifier) {
TestRequest request = newRequest();
if (templateUuid != null) {
request.setParam(PARAM_TEMPLATE_ID, templateUuid);
}
if (qualifier != null) {
request.setParam(PARAM_QUALIFIER, qualifier);
}
request.execute();
}
private PermissionTemplateDto insertTemplate() {
return db.permissionTemplates().insertTemplate();
}
private void assertDefaultTemplates(@Nullable String projectDefaultTemplateUuid, @Nullable String applicationDefaultTemplateUuid, @Nullable String portfolioDefaultTemplateUuid) {
DbSession dbSession = db.getSession();
if (projectDefaultTemplateUuid != null) {
assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE)).contains(projectDefaultTemplateUuid);
} else {
assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PROJECT_TEMPLATE)).isEmpty();
}
if (portfolioDefaultTemplateUuid != null) {
assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE)).contains(portfolioDefaultTemplateUuid);
} else {
assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_PORTFOLIO_TEMPLATE)).isEmpty();
}
if (applicationDefaultTemplateUuid != null) {
assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE)).contains(applicationDefaultTemplateUuid);
} else {
assertThat(db.getDbClient().internalPropertiesDao().selectByKey(dbSession, InternalProperties.DEFAULT_APPLICATION_TEMPLATE)).isEmpty();
}
}
}
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/mobile/corellia/talon_karrde.lua | 763 | talon_karrde = Creature:new {
objectName = "@npc_spawner_n:talon_karrde",
socialGroup = "townsperson",
pvpFaction = "townsperson",
faction = "townsperson",
level = 100,
chanceHit = 1,
damageMin = 645,
damageMax = 1000,
baseXp = 9429,
baseHAM = 24000,
baseHAMmax = 30000,
armor = 0,
resists = {0,0,0,0,0,0,0,0,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = PACK,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/dressed_talon_karrde.iff"},
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(talon_karrde, "talon_karrde") | lgpl-3.0 |
Ja-ake/Common-Chicken-Runtime-Engine | CommonChickenRuntimeEngine/src/ccre/drivers/ByteFiddling.java | 8994 | /*
* Copyright 2015 Colby Skeggs
*
* This file is part of the CCRE, the Common Chicken Runtime Engine.
*
* The CCRE 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.
*
* The CCRE 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 the CCRE. If not, see <http://www.gnu.org/licenses/>.
*/
package ccre.drivers;
import ccre.log.Logger;
/**
* A collection of useful byte-level fiddling utilities.
*
* @author skeggsc
*/
public class ByteFiddling {
/**
* Find the first index of the byte b in the byte range, or -1 if it cannot
* be found in that range.
*
* @param bytes the byte array.
* @param from the start of the range.
* @param to the end of the range.
* @param b the byte to look for.
* @return the index, or -1 if not found.
*/
public static int indexOf(byte[] bytes, int from, int to, byte b) {
for (int i = from; i < to; i++) {
if (bytes[i] == b) {
return i;
}
}
return -1;
}
/**
* Extracts a subsequence of the bytes.
*
* @param bytes the byte array to copy from.
* @param from the start of the range.
* @param to the end of the range.
* @return the bytes from the range.
*/
public static byte[] sub(byte[] bytes, int from, int to) {
byte[] out = new byte[to - from];
System.arraycopy(bytes, from, out, 0, to - from);
return out;
}
/**
* Parse the ASCII characters in the byte array into an integer.
*
* @param bytes the characters to parse.
* @return the integer, or null if it cannot be parsed.
*/
public static Integer parseInt(byte[] bytes) {
return parseInt(bytes, 0, bytes.length);
}
/**
* Parse the ASCII characters in the byte section into an integer.
*
* @param bytes the byte array to parse.
* @param from the start of the byte section.
* @param to the end of the byte section.
* @return the integer, or null if it cannot be parsed.
*/
public static Integer parseInt(byte[] bytes, int from, int to) {
if (to <= from) {
return null;
}
boolean neg = bytes[from] == '-';
if (neg) {
from++;
if (to <= from) {
return null;
}
}
int num = 0;
for (int i = from; i < to; i++) {
int digit = bytes[i] - '0';
if (digit < 0 || digit > 9) {
return null;
}
num = (num * 10) + digit;
}
return neg ? -num : num;
}
/**
* Counts the number of occurrences of the byte b in the byte array.
*
* @param bytes the byte array to search.
* @param b the byte to look for.
* @return the number of instances of the byte.
*/
public static int count(byte[] bytes, byte b) {
return count(bytes, 0, bytes.length, b);
}
/**
* Counts the number of occurrences of the byte b in the byte section.
*
* @param bytes the byte array to search.
* @param from the start of the byte section.
* @param to the end of the byte section.
* @param b the byte to look for.
* @return the number of instances of the byte.
*/
public static int count(byte[] bytes, int from, int to, byte b) {
int count = 0;
for (int i = from; i < to; i++) {
if (bytes[i] == b) {
count++;
}
}
return count;
}
/**
* Split the byte section into multiple byte arrays with b as the delimiter.
*
* Will always return 1 + n byte arrays, where n is the number of instances
* of the byte in the byte section.
*
* @param bytes the byte array to search.
* @param from the start of the byte section.
* @param to the end of the byte section.
* @param b the byte to split on.
* @return the byte arrays.
*/
public static byte[][] split(byte[] bytes, int from, int to, byte b) {
byte[][] out = new byte[count(bytes, b) + 1][];
for (int i = 0; i < out.length; i++) {
int next = indexOf(bytes, from, to, b);
out[i] = sub(bytes, from, next);
from = next + 1;
}
return out;
}
/**
* Checks if the byte array (interpreted as ASCII) is the same as the given
* string.
*
* @param a the byte array to compare.
* @param b the string to compare.
* @return if the sequences contain the same character data.
*/
public static boolean streq(byte[] a, String b) {
int len = a.length;
if (len != b.length()) {
return false;
}
for (int i = 0; i < len; i++) {
if (a[i] != (byte) b.charAt(i)) {
return false;
}
}
return true;
}
/**
* Parse the ASCII characters in the byte array into a double.
*
* @param bytes the byte array to parse.
* @return the double, or null if it cannot be parsed.
*/
public static Double parseDouble(byte[] bytes) {
return parseDouble(bytes, 0, bytes.length);
}
/**
* Parse the ASCII characters in the byte section into a double.
*
* @param bytes the byte array to parse.
* @param from the start of the byte section.
* @param to the end of the byte section.
* @return the double, or null if it cannot be parsed.
*/
public static Double parseDouble(byte[] bytes, int from, int to) {
try {
return Double.parseDouble(parseASCII(bytes, from, to));
} catch (NumberFormatException ex) {
return null;
}
}
/**
* Parse the ASCII characters in the byte array into a string.
*
* @param bytes the byte array to parse.
* @return the string.
*/
public static String parseASCII(byte[] bytes) {
return parseASCII(bytes, 0, bytes.length);
}
/**
* Parse the ASCII characters in the byte section into a string.
*
* @param bytes the byte array to parse.
* @param from the start of the byte section.
* @param to the end of the byte section.
* @return the string.
*/
public static String parseASCII(byte[] bytes, int from, int to) {
char[] conv = new char[to - from];
for (int i = from, j = 0; i < to; i++, j++) {
conv[j] = (char) (bytes[i] & 0xFF);
}
return new String(conv);
}
/**
* Encode the byte section into a hexadecimal string.
*
* @param bytes the byte array to encode.
* @param from the start of the byte section.
* @param to the end of the byte section.
* @return the hexadecimal version.
*/
public static String toHex(byte[] bytes, int from, int to) {
if (to > bytes.length || to < from || from < 0) {
throw new ArrayIndexOutOfBoundsException("Bad toHex arguments: " + from + ";" + to);
}
char[] out = new char[2 * (to - from)];
for (int i = from, j = 0; i < to; i++) {
try {
out[j++] = hex[(bytes[i] >> 4) & 0xF];
out[j++] = hex[bytes[i] & 0xF];
} catch (ArrayIndexOutOfBoundsException ex) {
Logger.warning("Offending indexes: " + j + "," + i + ": " + from + "," + to + "," + bytes.length + "," + out.length);
throw ex;
}
}
return new String(out);
}
private static final char[] hex = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
* Converts four little-endian bytes from data into an integer.
*
* @param data the data to extract the bytes from
* @param from the index of the first byte
* @return the extracted integer.
*/
public static int asInt32LE(byte[] data, int from) {
return (data[from] & 0xFF) | ((data[from + 1] & 0xFF) << 8) | ((data[from + 2] & 0xFF) << 16) | ((data[from + 3] & 0xFF) << 24);
}
/**
* Converts four big-endian bytes from data into an integer.
*
* @param data the data to extract the bytes from
* @param from the index of the first byte
* @return the extracted integer.
*/
public static int asInt32BE(byte[] data, int from) {
return ((data[from] & 0xFF) << 24) | ((data[from + 1] & 0xFF) << 16) | ((data[from + 2] & 0xFF) << 8) | (data[from + 3] & 0xFF);
}
}
| lgpl-3.0 |
SmartITEngineering/smart-util | rest/atom/src/main/java/com/smartitengineering/util/rest/atom/PaginatedEntitiesWrapper.java | 3314 | /*
* This is a utility project for wide range of applications
*
* Copyright (C) 2010 Imran M Yousuf ([email protected])
*
* 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 3 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 10-1 USA
*/
package com.smartitengineering.util.rest.atom;
import com.smartitengineering.util.rest.client.HttpClient;
import java.util.Collection;
import javax.activation.MimeTypeParseException;
import javax.ws.rs.core.MediaType;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Link;
/**
* A wrapper that allows clients to walk across a paginated collection of homogeneous entries.
* @author imyousuf
*/
public class PaginatedEntitiesWrapper<T> {
private Feed rootFeed;
private HttpClient client;
private EntryReader<T> feedEntryReader;
/**
* Initialize a paginated entities wrapper based on a feed entry reader, client and the root feed to start walking.
* @param rootFeed The feed to start walking from
* @param client The client to use to fetch the next/previous wrapper
* @param feedEntryReader Reader to read the collection entries
* @throws IllegalArgumentException If any parameter is null
*/
public PaginatedEntitiesWrapper(Feed rootFeed, HttpClient client, EntryReader<T> feedEntryReader)
throws
IllegalArgumentException {
if (rootFeed == null || client == null || feedEntryReader == null) {
throw new IllegalArgumentException("No parameter can be null!");
}
this.rootFeed = rootFeed;
this.client = client;
this.feedEntryReader = feedEntryReader;
}
public PaginatedEntitiesWrapper<T> next() {
Link link = rootFeed.getLink(Link.REL_NEXT);
return getPaginatedWrapperFromFeedLink(link);
}
public PaginatedEntitiesWrapper<T> previous() {
Link link = rootFeed.getLink(Link.REL_PREVIOUS);
return getPaginatedWrapperFromFeedLink(link);
}
protected PaginatedEntitiesWrapper<T> getPaginatedWrapperFromFeedLink(Link link) {
try {
if (link != null && link.getMimeType().match(MediaType.APPLICATION_ATOM_XML)) {
Feed newFeed = AtomClientUtil.readEntity(link, client, MediaType.APPLICATION_ATOM_XML, Feed.class);
return new PaginatedEntitiesWrapper<T>(newFeed, client, feedEntryReader);
}
}
catch (MimeTypeParseException ex) {
ex.printStackTrace();
}
return null;
}
public Collection<T> getEntitiesForCurrentPage() {
return feedEntryReader.getEntriesFromFeed(rootFeed);
}
public HttpClient getClient() {
return client;
}
public EntryReader<T> getFeedEntryReader() {
return feedEntryReader;
}
public Feed getRootFeed() {
return rootFeed;
}
}
| lgpl-3.0 |
whot/evemu | python/evemu/__init__.py | 15643 | """
The evemu module provides the Python interface to the kernel-level input device
raw events.
"""
# Copyright 2011-2012 Canonical Ltd.
# Copyright 2014 Red Hat, Inc.
#
# This library is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import ctypes
import glob
import os
import re
import stat
import tempfile
import evemu.base
__all__ = ["Device",
"InputEvent",
"event_get_value",
"event_get_name",
"input_prop_get_value",
"input_prop_get_name"]
_libevdev = evemu.base.LibEvdev()
def event_get_value(event_type, event_code = None):
"""
Return the integer-value for the given event type and/or code string
e.g. "EV_ABS" returns 0x03, ("EV_ABS", "ABS_Y") returns 0x01.
Unknown event types or type/code combinations return None.
If an event code is passed, the event type may be given as integer or
string.
"""
t = -1
c = -1
if isinstance(event_type, int):
event_type = _libevdev.libevdev_event_type_get_name(event_type)
if event_type is None:
return None
event_type = event_type.decode("iso8859-1")
event_type = str(event_type).encode("iso8859-1")
t = _libevdev.libevdev_event_type_from_name(event_type)
if event_code is None:
return None if t < 0 else t
if isinstance(event_code, int):
event_code = _libevdev.libevdev_event_code_get_name(t, event_code)
if event_code is None:
return None
event_code = event_code.decode("iso8859-1")
event_code = str(event_code).encode("iso8859-1")
c = _libevdev.libevdev_event_code_from_name(t, event_code)
return None if c < 0 else c
def event_get_name(event_type, event_code = None):
"""
Return the string-value for the given event type and/or code value
e.g. 0x03 returns "EV_ABS", ("EV_ABS", 0x01) returns "ABS_Y"
Unknown event types or type/code combinations return None.
If an event code is passed, the event type may be given as integer or
string.
"""
if not isinstance(event_type, int):
event_type = event_get_value(event_type)
if event_type is None:
return None
if event_code is None:
type_name = _libevdev.libevdev_event_type_get_name(event_type)
if type_name is None:
return None
return type_name.decode("iso8859-1")
if not isinstance(event_code, int):
event_code = event_get_value(event_type, event_code)
if event_code is None:
return None
code_name = _libevdev.libevdev_event_code_get_name(event_type, event_code)
if code_name is None:
return None
return code_name.decode("iso8859-1")
def input_prop_get_name(prop):
"""
Return the name of the input property, or None if undefined.
"""
if not isinstance(prop, int):
prop = input_prop_get_value(prop)
if prop is None:
return None
prop = _libevdev.libevdev_property_get_name(prop)
if prop is None:
return None
return prop.decode("iso8859-1")
def input_prop_get_value(prop):
"""
Return the value of the input property, or None if undefined.
"""
if isinstance(prop, int):
prop = input_prop_get_name(prop)
if prop is None:
return None
prop = str(prop).encode("iso8859-1")
prop = _libevdev.libevdev_property_from_name(prop)
return None if prop < 0 else prop
class InputEvent(object):
__slots__ = 'sec', 'usec', 'type', 'code', 'value'
def __init__(self, sec, usec, type, code, value):
self.sec = sec
self.usec = usec
self.type = type
self.code = code
self.value = value
def matches(self, type, code = None):
"""
If code is None, return True if the event matches the given event
type. If code is not None, return True if the event matches the
given type/code pair.
type and code may be ints or string-like ("EV_ABS", "ABS_X").
"""
if event_get_value(type) != self.type:
return False
if code != None and event_get_value(self.type, code) != self.code:
return False
return True
def __str__(self):
f = tempfile.TemporaryFile()
libc = evemu.base.LibC()
fp = libc.fdopen(f.fileno(), b"w+")
event = evemu.base.InputEvent()
event.sec = self.sec
event.usec = self.usec
event.type = self.type
event.code = self.code
event.value = self.value
libevemu = evemu.base.LibEvemu()
libevemu.evemu_write_event(fp, ctypes.byref(event))
libc.fflush(fp)
f.seek(0)
return f.readline().rstrip()
class Device(object):
"""
Encapsulates a raw kernel input event device, either an existing one as
reported by the kernel or a pseudodevice as created through a .prop file.
"""
def __init__(self, f, create=True):
"""
Initialize an evemu Device.
args:
f -- a file object or filename string for either an existing input
device node (/dev/input/eventNN) or an evemu prop file that can be used
to create a pseudo-device node.
create -- If f points to an evemu prop file, 'create' specifies if a
uinput device should be created
"""
if type(f) == str:
self._file = open(f)
elif hasattr(f, "read"):
self._file = f
else:
raise TypeError("expected file or file name")
self._is_propfile = self._check_is_propfile(self._file)
self._libc = evemu.base.LibC()
self._libevemu = evemu.base.LibEvemu()
self._evemu_device = self._libevemu.evemu_new(b"")
if self._is_propfile:
fs = self._libc.fdopen(self._file.fileno(), b"r")
self._libevemu.evemu_read(self._evemu_device, fs)
if create:
self._file = self._create_devnode()
else:
self._libevemu.evemu_extract(self._evemu_device,
self._file.fileno())
def __del__(self):
if hasattr(self, "_is_propfile") and self._is_propfile:
self._file.close()
self._libevemu.evemu_destroy(self._evemu_device)
def _create_devnode(self):
self._libevemu.evemu_create_managed(self._evemu_device)
return open(self._find_newest_devnode(self.name), 'r+b', buffering=0)
def _find_newest_devnode(self, target_name):
newest_node = (None, float(0))
for sysname in glob.glob("/sys/class/input/event*/device/name"):
with open(sysname) as f:
name = f.read().rstrip()
if name == target_name:
ev = re.search("(event\d+)", sysname)
if ev:
devname = os.path.join("/dev/input", ev.group(1))
ctime = os.stat(devname).st_ctime
if ctime > newest_node[1]:
newest_node = (devname, ctime)
return newest_node[0]
def _check_is_propfile(self, f):
if stat.S_ISCHR(os.fstat(f.fileno()).st_mode):
return False
result = False
for line in f.readlines():
if line.startswith("N:"):
result = True
break
elif line.startswith("# EVEMU"):
result = True
break
elif line[0] != "#":
raise TypeError("file must be a device special or prop file")
f.seek(0)
return result
def describe(self, prop_file):
"""
Gathers information about the input device and prints it
to prop_file. This information can be parsed later when constructing
a Device to create a virtual input device with the same properties.
You need the required permissions to access the device file to
succeed (usually root).
prop_file must be a real file with fileno(), not file-like.
"""
if not hasattr(prop_file, "fileno"):
raise TypeError("expected file")
fs = self._libc.fdopen(prop_file.fileno(), b"w")
self._libevemu.evemu_write(self._evemu_device, fs)
self._libc.fflush(fs)
def events(self, events_file=None):
"""
Reads the events from the given file and returns them as a list of
dicts.
If not None, events_file must be a real file with fileno(), not
file-like. If None, the file used for creating this device is used.
"""
if events_file:
if not hasattr(events_file, "fileno"):
raise TypeError("expected file")
else:
events_file = self._file
fs = self._libc.fdopen(events_file.fileno(), b"r")
event = evemu.base.InputEvent()
while self._libevemu.evemu_read_event(fs, ctypes.byref(event)) > 0:
yield InputEvent(event.sec, event.usec, event.type, event.code, event.value)
self._libc.rewind(fs)
def play(self, events_file):
"""
Replays an event sequence, as provided by the events_file,
through the input device. The event sequence must be in
the form created by the record method.
You need the required permissions to access the device file to
succeed (usually root).
events_file must be a real file with fileno(), not file-like.
"""
if not hasattr(events_file, "fileno"):
raise TypeError("expected file")
fs = self._libc.fdopen(events_file.fileno(), b"r")
self._libevemu.evemu_play(fs, self._file.fileno())
def record(self, events_file, timeout=10000):
"""
Captures events from the input device and prints them to the
events_file. The events can be parsed by the play method,
allowing a virtual input device to emit the exact same event
sequence.
You need the required permissions to access the device file to
succeed (usually root).
events_file must be a real file with fileno(), not file-like.
"""
if not hasattr(events_file, "fileno"):
raise TypeError("expected file")
fs = self._libc.fdopen(events_file.fileno(), b"w")
self._libevemu.evemu_record(fs, self._file.fileno(), timeout)
self._libc.fflush(fs)
@property
def version(self):
"""
Gets the version of the evemu library used to create the Device.
"""
return self._libevemu.evemu_get_version(self._evemu_device)
@property
def devnode(self):
"""
Gets the name of the /dev node of the input device.
"""
return self._file.name
@property
def name(self):
"""
Gets the name of the input device (as reported by the device).
"""
result = self._libevemu.evemu_get_name(self._evemu_device)
return result.decode("iso8859-1")
@property
def id_bustype(self):
"""
Identifies the kernel device bustype.
"""
return self._libevemu.evemu_get_id_bustype(self._evemu_device)
@property
def id_vendor(self):
"""
Identifies the kernel device vendor.
"""
return self._libevemu.evemu_get_id_vendor(self._evemu_device)
@property
def id_product(self):
"""
Identifies the kernel device product.
"""
return self._libevemu.evemu_get_id_product(self._evemu_device)
@property
def id_version(self):
"""
Identifies the kernel device version.
"""
return self._libevemu.evemu_get_id_version(self._evemu_device)
def get_abs_minimum(self, event_code):
"""
Return the axis minimum for the given EV_ABS value.
event_code may be an int or string-like ("ABS_X").
"""
if not isinstance(event_code, int):
event_code = evemu.event_get_value("EV_ABS", event_code)
return self._libevemu.evemu_get_abs_minimum(self._evemu_device,
event_code)
def get_abs_maximum(self, event_code):
"""
Return the axis maximum for the given EV_ABS value.
event_code may be an int or string-like ("ABS_X").
"""
if not isinstance(event_code, int):
event_code = evemu.event_get_value("EV_ABS", event_code)
return self._libevemu.evemu_get_abs_maximum(self._evemu_device,
event_code)
def get_abs_fuzz(self, event_code):
"""
Return the abs fuzz for the given EV_ABS value.
event_code may be an int or string-like ("ABS_X").
"""
if not isinstance(event_code, int):
event_code = evemu.event_get_value("EV_ABS", event_code)
return self._libevemu.evemu_get_abs_fuzz(self._evemu_device,
event_code)
def get_abs_flat(self, event_code):
"""
Return the abs flat for the given EV_ABS value.
event_code may be an int or string-like ("ABS_X").
"""
if not isinstance(event_code, int):
event_code = evemu.event_get_value("EV_ABS", event_code)
return self._libevemu.evemu_get_abs_flat(self._evemu_device,
event_code)
def get_abs_resolution(self, event_code):
"""
Return the resolution for the given EV_ABS value.
event_code may be an int or string-like ("ABS_X").
"""
if not isinstance(event_code, int):
event_code = evemu.event_get_value("EV_ABS", event_code)
return self._libevemu.evemu_get_abs_resolution(self._evemu_device,
event_code)
# don't change 'event_code' to prop, it breaks API
def has_prop(self, event_code):
"""
Return True if the device supports the given input property,
or False otherwise.
event_code may be an int or string-like ("INPUT_PROP_DIRECT").
"""
if not isinstance(event_code, int):
event_code = evemu.input_prop_get_value(event_code)
result = self._libevemu.evemu_has_prop(self._evemu_device, event_code)
return bool(result)
def has_event(self, event_type, event_code):
"""
Return True if the device supports the given event type/code
pair, or False otherwise.
event_type and event_code may be ints or string-like ("EV_REL",
"REL_X").
"""
if not isinstance(event_type, int):
event_type = evemu.event_get_value(event_type)
if not isinstance(event_code, int):
event_code = evemu.event_get_value(event_type, event_code)
result = self._libevemu.evemu_has_event(self._evemu_device,
event_type,
event_code)
return bool(result)
| lgpl-3.0 |
js-works/js-scenery | boxroom/archive/js-remix_2018-04-27/webpack.config.js | 165 | const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'remix.js',
path: path.resolve(__dirname, 'dist')
}
};
| lgpl-3.0 |
FreeOpcUa/python-opcua | opcua/tools.py | 30498 | import logging
import sys
import argparse
from datetime import datetime, timedelta
import math
import time
try:
from IPython import embed
except ImportError:
import code
def embed():
code.interact(local=dict(globals(), **locals()))
from opcua import ua
from opcua import Client
from opcua import Server
from opcua import Node
from opcua import uamethod
from opcua.ua.uaerrors import UaStatusCodeError
def add_minimum_args(parser):
parser.add_argument("-u",
"--url",
help="URL of OPC UA server (for example: opc.tcp://example.org:4840)",
default='opc.tcp://localhost:4840',
metavar="URL")
parser.add_argument("-v",
"--verbose",
dest="loglevel",
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
default='WARNING',
help="Set log level")
parser.add_argument("--timeout",
dest="timeout",
type=int,
default=1,
help="Set socket timeout (NOT the diverse UA timeouts)")
def add_common_args(parser, default_node='i=84', require_node=False):
add_minimum_args(parser)
parser.add_argument("-n",
"--nodeid",
help="Fully-qualified node ID (for example: i=85). Default: root node",
default=default_node,
required=require_node,
metavar="NODE")
parser.add_argument("-p",
"--path",
help="Comma separated browse path to the node starting at NODE (for example: 3:Mybject,3:MyVariable)",
default='',
metavar="BROWSEPATH")
parser.add_argument("-i",
"--namespace",
help="Default namespace",
type=int,
default=0,
metavar="NAMESPACE")
parser.add_argument("--security",
help="Security settings, for example: Basic256Sha256,SignAndEncrypt,cert.der,pk.pem[,server_cert.der]. Default: None",
default='')
parser.add_argument("--user",
help="User name for authentication. Overrides the user name given in the URL.")
parser.add_argument("--password",
help="Password name for authentication. Overrides the password given in the URL.")
def _require_nodeid(parser, args):
# check that a nodeid has been given explicitly, a bit hackish...
if args.nodeid == "i=84" and args.path == "":
parser.print_usage()
print("{0}: error: A NodeId or BrowsePath is required".format(parser.prog))
sys.exit(1)
def parse_args(parser, requirenodeid=False):
args = parser.parse_args()
logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel))
if args.url and '://' not in args.url:
logging.info("Adding default scheme %s to URL %s", ua.OPC_TCP_SCHEME, args.url)
args.url = ua.OPC_TCP_SCHEME + '://' + args.url
if requirenodeid:
_require_nodeid(parser, args)
return args
def get_node(client, args):
node = client.get_node(args.nodeid)
if args.path:
path = args.path.split(",")
if node.nodeid == ua.NodeId(84, 0) and path[0] == "0:Root":
# let user specify root if not node given
path = path[1:]
node = node.get_child(path)
return node
def uaread():
parser = argparse.ArgumentParser(description="Read attribute of a node, per default reads value of a node")
add_common_args(parser)
parser.add_argument("-a",
"--attribute",
dest="attribute",
type=int,
default=ua.AttributeIds.Value,
help="Set attribute to read")
parser.add_argument("-t",
"--datatype",
dest="datatype",
default="python",
choices=['python', 'variant', 'datavalue'],
help="Data type to return")
args = parse_args(parser, requirenodeid=True)
client = Client(args.url, timeout=args.timeout)
client.set_security_string(args.security)
client.connect()
try:
node = get_node(client, args)
attr = node.get_attribute(args.attribute)
if args.datatype == "python":
print(attr.Value.Value)
elif args.datatype == "variant":
print(attr.Value)
else:
print(attr)
finally:
client.disconnect()
sys.exit(0)
print(args)
def _args_to_array(val, array):
if array == "guess":
if "," in val:
array = "true"
if array == "true":
val = val.split(",")
return val
def _arg_to_bool(val):
return val in ("true", "True")
def _arg_to_variant(val, array, ptype, varianttype=None):
val = _args_to_array(val, array)
if isinstance(val, list):
val = [ptype(i) for i in val]
else:
val = ptype(val)
if varianttype:
return ua.Variant(val, varianttype)
else:
return ua.Variant(val)
def _val_to_variant(val, args):
array = args.array
if args.datatype == "guess":
if val in ("true", "True", "false", "False"):
return _arg_to_variant(val, array, _arg_to_bool)
try:
return _arg_to_variant(val, array, int)
except ValueError:
try:
return _arg_to_variant(val, array, float)
except ValueError:
return _arg_to_variant(val, array, str)
elif args.datatype == "bool":
if val in ("1", "True", "true"):
return ua.Variant(True, ua.VariantType.Boolean)
else:
return ua.Variant(False, ua.VariantType.Boolean)
elif args.datatype == "sbyte":
return _arg_to_variant(val, array, int, ua.VariantType.SByte)
elif args.datatype == "byte":
return _arg_to_variant(val, array, int, ua.VariantType.Byte)
#elif args.datatype == "uint8":
#return _arg_to_variant(val, array, int, ua.VariantType.Byte)
elif args.datatype == "uint16":
return _arg_to_variant(val, array, int, ua.VariantType.UInt16)
elif args.datatype == "uint32":
return _arg_to_variant(val, array, int, ua.VariantType.UInt32)
elif args.datatype == "uint64":
return _arg_to_variant(val, array, int, ua.VariantType.UInt64)
#elif args.datatype == "int8":
#return ua.Variant(int(val), ua.VariantType.Int8)
elif args.datatype == "int16":
return _arg_to_variant(val, array, int, ua.VariantType.Int16)
elif args.datatype == "int32":
return _arg_to_variant(val, array, int, ua.VariantType.Int32)
elif args.datatype == "int64":
return _arg_to_variant(val, array, int, ua.VariantType.Int64)
elif args.datatype == "float":
return _arg_to_variant(val, array, float, ua.VariantType.Float)
elif args.datatype == "double":
return _arg_to_variant(val, array, float, ua.VariantType.Double)
elif args.datatype == "string":
return _arg_to_variant(val, array, str, ua.VariantType.String)
elif args.datatype == "datetime":
raise NotImplementedError
elif args.datatype == "Guid":
return _arg_to_variant(val, array, bytes, ua.VariantType.Guid)
elif args.datatype == "ByteString":
return _arg_to_variant(val, array, bytes, ua.VariantType.ByteString)
elif args.datatype == "xml":
return _arg_to_variant(val, array, str, ua.VariantType.XmlElement)
elif args.datatype == "nodeid":
return _arg_to_variant(val, array, ua.NodeId.from_string, ua.VariantType.NodeId)
elif args.datatype == "expandednodeid":
return _arg_to_variant(val, array, ua.ExpandedNodeId.from_string, ua.VariantType.ExpandedNodeId)
elif args.datatype == "statuscode":
return _arg_to_variant(val, array, int, ua.VariantType.StatusCode)
elif args.datatype in ("qualifiedname", "browsename"):
return _arg_to_variant(val, array, ua.QualifiedName.from_string, ua.VariantType.QualifiedName)
elif args.datatype == "LocalizedText":
return _arg_to_variant(val, array, ua.LocalizedText, ua.VariantType.LocalizedText)
def _configure_client_with_args(client, args):
if args.user:
client.set_user(args.user)
if args.password:
client.set_password(args.password)
client.set_security_string(args.security)
def uawrite():
parser = argparse.ArgumentParser(description="Write attribute of a node, per default write value of node")
add_common_args(parser)
parser.add_argument("-a",
"--attribute",
dest="attribute",
type=int,
default=ua.AttributeIds.Value,
help="Set attribute to read")
parser.add_argument("-l",
"--list",
"--array",
dest="array",
default="guess",
choices=["guess", "true", "false"],
help="Value is an array")
parser.add_argument("-t",
"--datatype",
dest="datatype",
default="guess",
choices=["guess", 'byte', 'sbyte', 'nodeid', 'expandednodeid', 'qualifiedname', 'browsename', 'string', 'float', 'double', 'int16', 'int32', "int64", 'uint16', 'uint32', 'uint64', "bool", "string", 'datetime', 'bytestring', 'xmlelement', 'statuscode', 'localizedtext'],
help="Data type to return")
parser.add_argument("value",
help="Value to be written",
metavar="VALUE")
args = parse_args(parser, requirenodeid=True)
client = Client(args.url, timeout=args.timeout)
_configure_client_with_args(client, args)
client.connect()
try:
node = get_node(client, args)
val = _val_to_variant(args.value, args)
node.set_attribute(args.attribute, ua.DataValue(val))
finally:
client.disconnect()
sys.exit(0)
print(args)
def uals():
parser = argparse.ArgumentParser(description="Browse OPC-UA node and print result")
add_common_args(parser)
parser.add_argument("-l",
dest="long_format",
const=3,
nargs="?",
type=int,
help="use a long listing format")
parser.add_argument("-d",
"--depth",
default=1,
type=int,
help="Browse depth")
args = parse_args(parser)
if args.long_format is None:
args.long_format = 1
client = Client(args.url, timeout=args.timeout)
_configure_client_with_args(client, args)
client.connect()
try:
node = get_node(client, args)
print("Browsing node {0} at {1}\n".format(node, args.url))
if args.long_format == 0:
_lsprint_0(node, args.depth - 1)
elif args.long_format == 1:
_lsprint_1(node, args.depth - 1)
else:
_lsprint_long(node, args.depth - 1)
finally:
client.disconnect()
sys.exit(0)
print(args)
def _lsprint_0(node, depth, indent=""):
if not indent:
print("{0:30} {1:25}".format("DisplayName", "NodeId"))
print("")
for desc in node.get_children_descriptions():
print("{0}{1:30} {2:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string()))
if depth:
_lsprint_0(Node(node.server, desc.NodeId), depth - 1, indent + " ")
def _lsprint_1(node, depth, indent=""):
if not indent:
print("{0:30} {1:25} {2:25} {3:25}".format("DisplayName", "NodeId", "BrowseName", "Value"))
print("")
for desc in node.get_children_descriptions():
if desc.NodeClass == ua.NodeClass.Variable:
try:
val = Node(node.server, desc.NodeId).get_value()
except UaStatusCodeError as err:
val = "Bad (0x{0:x})".format(err.code)
print("{0}{1:30} {2!s:25} {3!s:25}, {4!s:3}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string(), val))
else:
print("{0}{1:30} {2!s:25} {3!s:25}".format(indent, desc.DisplayName.to_string(), desc.NodeId.to_string(), desc.BrowseName.to_string()))
if depth:
_lsprint_1(Node(node.server, desc.NodeId), depth - 1, indent + " ")
def _lsprint_long(pnode, depth, indent=""):
if not indent:
print("{0:30} {1:25} {2:25} {3:10} {4:30} {5:25}".format("DisplayName", "NodeId", "BrowseName", "DataType", "Timestamp", "Value"))
print("")
for node in pnode.get_children():
attrs = node.get_attributes([ua.AttributeIds.DisplayName,
ua.AttributeIds.BrowseName,
ua.AttributeIds.NodeClass,
ua.AttributeIds.WriteMask,
ua.AttributeIds.UserWriteMask,
ua.AttributeIds.DataType,
ua.AttributeIds.Value])
name, bname, nclass, mask, umask, dtype, val = [attr.Value.Value for attr in attrs]
update = attrs[-1].ServerTimestamp
if nclass == ua.NodeClass.Variable:
print("{0}{1:30} {2:25} {3:25} {4:10} {5!s:30} {6!s:25}".format(indent, name.to_string(), node.nodeid.to_string(), bname.to_string(), dtype.to_string(), update, val))
else:
print("{0}{1:30} {2:25} {3:25}".format(indent, name.to_string(), bname.to_string(), node.nodeid.to_string()))
if depth:
_lsprint_long(node, depth - 1, indent + " ")
class SubHandler(object):
def datachange_notification(self, node, val, data):
print("New data change event", node, val, data)
def event_notification(self, event):
print("New event", event)
def uasubscribe():
parser = argparse.ArgumentParser(description="Subscribe to a node and print results")
add_common_args(parser)
parser.add_argument("-t",
"--eventtype",
dest="eventtype",
default="datachange",
choices=['datachange', 'event'],
help="Event type to subscribe to")
args = parse_args(parser, requirenodeid=False)
if args.eventtype == "datachange":
_require_nodeid(parser, args)
else:
# FIXME: this is broken, someone may have written i=84 on purpose
if args.nodeid == "i=84" and args.path == "":
args.nodeid = "i=2253"
client = Client(args.url, timeout=args.timeout)
_configure_client_with_args(client, args)
client.connect()
try:
node = get_node(client, args)
handler = SubHandler()
sub = client.create_subscription(500, handler)
if args.eventtype == "datachange":
sub.subscribe_data_change(node)
else:
sub.subscribe_events(node)
print("Type Ctr-C to exit")
while True:
time.sleep(1)
finally:
client.disconnect()
sys.exit(0)
print(args)
def application_to_strings(app):
result = []
result.append(('Application URI', app.ApplicationUri))
optionals = [
('Product URI', app.ProductUri),
('Application Name', app.ApplicationName.to_string()),
('Application Type', str(app.ApplicationType)),
('Gateway Server URI', app.GatewayServerUri),
('Discovery Profile URI', app.DiscoveryProfileUri),
]
for (n, v) in optionals:
if v:
result.append((n, v))
for url in app.DiscoveryUrls:
result.append(('Discovery URL', url))
return result # ['{}: {}'.format(n, v) for (n, v) in result]
def cert_to_string(der):
if not der:
return '[no certificate]'
try:
from opcua.crypto import uacrypto
except ImportError:
return "{0} bytes".format(len(der))
cert = uacrypto.x509_from_der(der)
return uacrypto.x509_to_string(cert)
def endpoint_to_strings(ep):
result = [('Endpoint URL', ep.EndpointUrl)]
result += application_to_strings(ep.Server)
result += [
('Server Certificate', cert_to_string(ep.ServerCertificate)),
('Security Mode', str(ep.SecurityMode)),
('Security Policy URI', ep.SecurityPolicyUri)]
for tok in ep.UserIdentityTokens:
result += [
('User policy', tok.PolicyId),
(' Token type', str(tok.TokenType))]
if tok.IssuedTokenType or tok.IssuerEndpointUrl:
result += [
(' Issued Token type', tok.IssuedTokenType),
(' Issuer Endpoint URL', tok.IssuerEndpointUrl)]
if tok.SecurityPolicyUri:
result.append((' Security Policy URI', tok.SecurityPolicyUri))
result += [
('Transport Profile URI', ep.TransportProfileUri),
('Security Level', ep.SecurityLevel)]
return result
def uaclient():
parser = argparse.ArgumentParser(description="Connect to server and start python shell. root and objects nodes are available. Node specificed in command line is available as mynode variable")
add_common_args(parser)
parser.add_argument("-c",
"--certificate",
help="set client certificate")
parser.add_argument("-k",
"--private_key",
help="set client private key")
args = parse_args(parser)
client = Client(args.url, timeout=args.timeout)
_configure_client_with_args(client, args)
if args.certificate:
client.load_client_certificate(args.certificate)
if args.private_key:
client.load_private_key(args.private_key)
client.connect()
try:
root = client.get_root_node()
objects = client.get_objects_node()
mynode = get_node(client, args)
embed()
finally:
client.disconnect()
sys.exit(0)
def uaserver():
parser = argparse.ArgumentParser(description="Run an example OPC-UA server. By importing xml definition and using uawrite command line, it is even possible to expose real data using this server")
# we setup a server, this is a bit different from other tool so we do not reuse common arguments
parser.add_argument("-u",
"--url",
help="URL of OPC UA server, default is opc.tcp://0.0.0.0:4840",
default='opc.tcp://0.0.0.0:4840',
metavar="URL")
parser.add_argument("-v",
"--verbose",
dest="loglevel",
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
default='WARNING',
help="Set log level")
parser.add_argument("-x",
"--xml",
metavar="XML_FILE",
help="Populate address space with nodes defined in XML")
parser.add_argument("-p",
"--populate",
action="store_true",
help="Populate address space with some sample nodes")
parser.add_argument("-c",
"--disable-clock",
action="store_true",
help="Disable clock, to avoid seeing many write if debugging an application")
parser.add_argument("-s",
"--shell",
action="store_true",
help="Start python shell instead of randomly changing node values")
parser.add_argument("--certificate",
help="set server certificate")
parser.add_argument("--private_key",
help="set server private key")
args = parser.parse_args()
logging.basicConfig(format="%(levelname)s: %(message)s", level=getattr(logging, args.loglevel))
server = Server()
server.set_endpoint(args.url)
if args.certificate:
server.load_certificate(args.certificate)
if args.private_key:
server.load_private_key(args.private_key)
server.disable_clock(args.disable_clock)
server.set_server_name("FreeOpcUa Example Server")
if args.xml:
server.import_xml(args.xml)
if args.populate:
@uamethod
def multiply(parent, x, y):
print("multiply method call with parameters: ", x, y)
return x * y
uri = "http://examples.freeopcua.github.io"
idx = server.register_namespace(uri)
objects = server.get_objects_node()
myobj = objects.add_object(idx, "MyObject")
mywritablevar = myobj.add_variable(idx, "MyWritableVariable", 6.7)
mywritablevar.set_writable() # Set MyVariable to be writable by clients
myvar = myobj.add_variable(idx, "MyVariable", 6.7)
myarrayvar = myobj.add_variable(idx, "MyVarArray", [6.7, 7.9])
myprop = myobj.add_property(idx, "MyProperty", "I am a property")
mymethod = myobj.add_method(idx, "MyMethod", multiply, [ua.VariantType.Double, ua.VariantType.Int64], [ua.VariantType.Double])
server.start()
try:
if args.shell:
embed()
elif args.populate:
count = 0
while True:
time.sleep(1)
myvar.set_value(math.sin(count / 10))
myarrayvar.set_value([math.sin(count / 10), math.sin(count / 100)])
count += 1
else:
while True:
time.sleep(1)
finally:
server.stop()
sys.exit(0)
def uadiscover():
parser = argparse.ArgumentParser(description="Performs OPC UA discovery and prints information on servers and endpoints.")
add_minimum_args(parser)
parser.add_argument("-n",
"--network",
action="store_true",
help="Also send a FindServersOnNetwork request to server")
#parser.add_argument("-s",
#"--servers",
#action="store_false",
#help="send a FindServers request to server")
#parser.add_argument("-e",
#"--endpoints",
#action="store_false",
#help="send a GetEndpoints request to server")
args = parse_args(parser)
client = Client(args.url, timeout=args.timeout)
if args.network:
print("Performing discovery at {0}\n".format(args.url))
for i, server in enumerate(client.connect_and_find_servers_on_network(), start=1):
print('Server {0}:'.format(i))
#for (n, v) in application_to_strings(server):
#print(' {}: {}'.format(n, v))
print('')
print("Performing discovery at {0}\n".format(args.url))
for i, server in enumerate(client.connect_and_find_servers(), start=1):
print('Server {0}:'.format(i))
for (n, v) in application_to_strings(server):
print(' {0}: {1}'.format(n, v))
print('')
for i, ep in enumerate(client.connect_and_get_server_endpoints(), start=1):
print('Endpoint {0}:'.format(i))
for (n, v) in endpoint_to_strings(ep):
print(' {0}: {1}'.format(n, v))
print('')
sys.exit(0)
def print_history(o):
print("{0:30} {1:10} {2}".format('Source timestamp', 'Status', 'Value'))
for d in o:
print("{0:30} {1:10} {2}".format(str(d.SourceTimestamp), d.StatusCode.name, d.Value.Value))
def str_to_datetime(s, default=None):
if not s:
if default is not None:
return default
return datetime.utcnow()
# FIXME: try different datetime formats
for fmt in ["%Y-%m-%d", "%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S"]:
try:
return datetime.strptime(s, fmt)
except ValueError:
pass
def uahistoryread():
parser = argparse.ArgumentParser(description="Read history of a node")
add_common_args(parser)
parser.add_argument("--starttime",
default=None,
help="Start time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time - one day")
parser.add_argument("--endtime",
default=None,
help="End time, formatted as YYYY-MM-DD [HH:MM[:SS]]. Default: current time")
parser.add_argument("-e",
"--events",
action="store_true",
help="Read event history instead of data change history")
parser.add_argument("-l",
"--limit",
type=int,
default=10,
help="Maximum number of notfication to return")
args = parse_args(parser, requirenodeid=True)
client = Client(args.url, timeout=args.timeout)
_configure_client_with_args(client, args)
client.connect()
try:
node = get_node(client, args)
starttime = str_to_datetime(args.starttime, datetime.utcnow() - timedelta(days=1))
endtime = str_to_datetime(args.endtime, datetime.utcnow())
print("Reading raw history of node {0} at {1}; start at {2}, end at {3}\n".format(node, args.url, starttime, endtime))
if args.events:
evs = node.read_event_history(starttime, endtime, numvalues=args.limit)
for ev in evs:
print(ev)
else:
print_history(node.read_raw_history(starttime, endtime, numvalues=args.limit))
finally:
client.disconnect()
sys.exit(0)
def uacall():
parser = argparse.ArgumentParser(description="Call method of a node")
add_common_args(parser)
parser.add_argument("-m",
"--method",
dest="method",
type=int,
default=None,
help="Set method to call. If not given then (single) method of the selected node is used.")
parser.add_argument("-M",
"--method-name",
dest="method_name",
type=str,
default=None,
help="Set name of method to call. Overrides --method")
parser.add_argument("-l",
"--list",
"--array",
dest="array",
default="guess",
choices=["guess", "true", "false"],
help="Value is an array")
parser.add_argument("-t",
"--datatype",
dest="datatype",
default="guess",
choices=["guess", 'byte', 'sbyte', 'nodeid', 'expandednodeid', 'qualifiedname', 'browsename', 'string', 'float', 'double', 'int16', 'int32', "int64", 'uint16', 'uint32', 'uint64', "bool", "string", 'datetime', 'bytestring', 'xmlelement', 'statuscode', 'localizedtext'],
help="Data type to return")
parser.add_argument("value",
help="Value to use for call to method, if any",
nargs="?",
metavar="VALUE")
args = parse_args(parser, requirenodeid=True)
client = Client(args.url, timeout=args.timeout)
_configure_client_with_args(client, args)
client.connect()
try:
node = get_node(client, args)
# val must be a tuple in order to enable method calls without arguments
if ( args.value is None ):
val = () #empty tuple
else:
val = (_val_to_variant(args.value, args),) # tuple with one element
# determine method to call: Either explicitly given or automatically select the method of the selected node.
methods = node.get_methods()
method_id = None
#print( "methods=%s" % (methods) )
if ( args.method_name is not None ):
method_id = args.method_name
elif ( args.method is None ):
if ( len( methods ) == 0 ):
raise ValueError( "No methods in selected node and no method given" )
elif ( len( methods ) == 1 ):
method_id = methods[0]
else:
raise ValueError( "Selected node has {0:d} methods but no method given. Provide one of {1!s}".format(*(methods)) )
else:
for m in methods:
if ( m.nodeid.Identifier == args.method ):
method_id = m.nodeid
break
if ( method_id is None):
# last resort:
method_id = ua.NodeId( identifier=args.method )#, namespaceidx=? )#, nodeidtype=?): )
#print( "method_id=%s\nval=%s" % (method_id,val) )
result_variants = node.call_method( method_id, *val )
print( "resulting result_variants={0!s}".format(result_variants) )
finally:
client.disconnect()
sys.exit(0)
print(args)
def uageneratestructs():
parser = argparse.ArgumentParser(description="Generate a Python module from the xml structure definition (.bsd)")
add_common_args(parser, require_node=True)
parser.add_argument("-o",
"--output",
dest="output_path",
required=True,
type=str,
default=None,
help="The python file to be generated.",
)
args = parse_args(parser, requirenodeid=True)
client = Client(args.url, timeout=args.timeout)
_configure_client_with_args(client, args)
client.connect()
try:
node = get_node(client, args)
generators, _ = client.load_type_definitions([node])
generators[0].save_to_file(args.output_path, True)
finally:
client.disconnect()
sys.exit(0)
| lgpl-3.0 |
ArticulatedSocialAgentsPlatform/AsapRealizer | Engines/Animation/AsapAnimationEngine/src/asap/animationengine/lipsync/TimedAnimationUnitLipSynchProvider.java | 5224 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer 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 Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package asap.animationengine.lipsync;
import hmi.tts.TTSTiming;
import hmi.tts.Visime;
import java.util.ArrayList;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import saiba.bml.core.Behaviour;
import asap.animationengine.AnimationPlayer;
import asap.animationengine.gesturebinding.SpeechBinding;
import asap.animationengine.motionunit.MUSetupException;
import asap.animationengine.motionunit.TimedAnimationMotionUnit;
import asap.animationengine.motionunit.TimedAnimationUnit;
import asap.realizer.lipsync.LipSynchProvider;
import asap.realizer.pegboard.BMLBlockPeg;
import asap.realizer.pegboard.OffsetPeg;
import asap.realizer.pegboard.PegBoard;
import asap.realizer.pegboard.TimePeg;
import asap.realizer.planunit.PlanManager;
import asap.realizer.planunit.TimedPlanUnit;
/**
* Creates TimedMotionUnit for lipsync
* @author Herwin
*
*/
@Slf4j
public class TimedAnimationUnitLipSynchProvider implements LipSynchProvider
{
private final SpeechBinding speechBinding;
private final PegBoard pegBoard;
private final AnimationPlayer animationPlayer;
private final PlanManager<TimedAnimationUnit> animationPlanManager;
public TimedAnimationUnitLipSynchProvider(SpeechBinding sb, AnimationPlayer ap, PlanManager<TimedAnimationUnit> animationPlanManager,
PegBoard pegBoard)
{
speechBinding = sb;
animationPlayer = ap;
this.pegBoard = pegBoard;
this.animationPlanManager = animationPlanManager;
}
@Override
public void addLipSyncMovement(BMLBlockPeg bbPeg, Behaviour beh, TimedPlanUnit bs, TTSTiming timing)
{
ArrayList<TimedAnimationMotionUnit> tmus = new ArrayList<TimedAnimationMotionUnit>();
double totalDuration = 0d;
double prevDuration = 0d;
HashMap<TimedAnimationMotionUnit, Double> startTimes = new HashMap<TimedAnimationMotionUnit, Double>();
HashMap<TimedAnimationMotionUnit, Double> endTimes = new HashMap<TimedAnimationMotionUnit, Double>();
TimedAnimationMotionUnit tmu = null;
for (Visime vis : timing.getVisimes())
{
// OOK: de visemen zijn nu te kort (sluiten aan op interpolatie 0/0
// ipv 50/50)
// make visemeunit, add to faceplanner...
double start = totalDuration / 1000d - prevDuration / 2000;
double peak = totalDuration / 1000d + vis.getDuration() / 2000d;
double end = totalDuration / 1000d + vis.getDuration() / 1000d;
if (tmu != null)
{
endTimes.put(tmu, peak); // extend previous tfu to the peak of this one!
}
try
{
tmu = speechBinding.getMotionUnit(vis.getNumber(), bbPeg, beh.getBmlId(), beh.id, animationPlayer, pegBoard);
if (tmu == null)
{
tmu = speechBinding.getMotionUnit(0, bbPeg, beh.getBmlId(), beh.id, animationPlayer, pegBoard);
}
startTimes.put(tmu, start);
endTimes.put(tmu, end);
tmus.add(tmu);
tmu.resolveGestureKeyPositions();
totalDuration += vis.getDuration();
prevDuration = vis.getDuration();
}
catch (MUSetupException e)
{
log.warn("Exception planning first timedmotionunit for speechbehavior {}", e, beh);
}
log.debug("Viseme number {}", vis.getNumber());
}
for (TimedAnimationMotionUnit tm : tmus)
{
tm.setSubUnit(true);
animationPlanManager.addPlanUnit(tm);
}
// and now link viseme units to the speech timepeg!
for (TimedAnimationMotionUnit plannedFU : tmus)
{
TimePeg startPeg = new OffsetPeg(bs.getTimePeg("start"), startTimes.get(plannedFU));
plannedFU.setTimePeg("start", startPeg);
TimePeg endPeg = new OffsetPeg(bs.getTimePeg("start"), endTimes.get(plannedFU));
plannedFU.setTimePeg("end", endPeg);
log.debug("adding jaw movement at {}-{}", plannedFU.getStartTime(), plannedFU.getEndTime());
}
}
}
| lgpl-3.0 |
rui-castro/roda | roda-ui/roda-wui/src/main/java/org/roda/wui/filter/CasClient.java | 5847 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE file at the root of the source
* tree and available online at
*
* https://github.com/keeps/roda
*/
package org.roda.wui.filter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.roda.core.data.exceptions.AuthenticationDeniedException;
import org.roda.core.data.exceptions.GenericException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* CAS client.
*
* Adapted from https://wiki.jasig.org/display/casum/restful+api.
*
* @author Rui Castro <[email protected]>
*/
public class CasClient {
/** Logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(CasClient.class);
/** No ticket message. */
private static final String NO_TICKET = "Successful ticket granting request, but no ticket found!";
/** CAS server URL. */
private final String casServerUrlPrefix;
/**
* Constructor.
*
* @param casServerUrlPrefix
* CAS server URL.
*/
public CasClient(final String casServerUrlPrefix) {
this.casServerUrlPrefix = casServerUrlPrefix;
}
/**
* Get a <strong>Ticket Granting Ticket</strong> from the CAS server for the
* specified <i>username</i> and <i>password</i>.
*
* @param username
* the username.
* @param password
* the password.
* @return the <strong>Ticket Granting Ticket</strong>
* @throws AuthenticationDeniedException
* if the CAS server rejected the specified credentials.
* @throws GenericException
* if some error occurred.
*/
public String getTicketGrantingTicket(final String username, final String password)
throws AuthenticationDeniedException, GenericException {
final HttpClient client = new HttpClient();
final PostMethod post = new PostMethod(String.format("%s/v1/tickets", this.casServerUrlPrefix));
post.setRequestBody(
new NameValuePair[] {new NameValuePair("username", username), new NameValuePair("password", password)});
try {
client.executeMethod(post);
final String response = post.getResponseBodyAsString();
if (post.getStatusCode() == HttpStatus.SC_CREATED) {
final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response);
if (matcher.matches()) {
return matcher.group(1);
}
LOGGER.warn(NO_TICKET);
throw new GenericException(NO_TICKET);
} else if (post.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthenticationDeniedException("Could not create ticket: " + post.getStatusText());
} else {
LOGGER.warn(invalidResponseMessage(post));
throw new GenericException(invalidResponseMessage(post));
}
} catch (final IOException e) {
throw new GenericException(e.getMessage(), e);
} finally {
post.releaseConnection();
}
}
/**
* Get a <strong>Service Ticket</strong> from the CAS server for the specified
* <strong>Ticket Granting Ticket</strong> and <strong>service</strong>.
*
* @param ticketGrantingTicket
* the <strong>Ticket Granting Ticket</strong>.
* @param service
* the service URL.
* @return the <strong>Service Ticket</strong>.
* @throws GenericException
* if some error occurred.
*/
public String getServiceTicket(final String ticketGrantingTicket, final String service) throws GenericException {
final HttpClient client = new HttpClient();
final PostMethod post = new PostMethod(String.format("%s/v1/tickets/%s", casServerUrlPrefix, ticketGrantingTicket));
post.setRequestBody(new NameValuePair[] {new NameValuePair("service", service)});
try {
client.executeMethod(post);
final String response = post.getResponseBodyAsString();
if (post.getStatusCode() == HttpStatus.SC_OK) {
return response;
} else {
LOGGER.warn(invalidResponseMessage(post));
throw new GenericException(invalidResponseMessage(post));
}
} catch (final IOException e) {
throw new GenericException(e.getMessage(), e);
} finally {
post.releaseConnection();
}
}
/**
* Logout from the CAS server.
*
* @param ticketGrantingTicket
* the <strong>Ticket Granting Ticket</strong>.
* @throws GenericException
* if some error occurred.
*/
public void logout(final String ticketGrantingTicket) throws GenericException {
final HttpClient client = new HttpClient();
final DeleteMethod method = new DeleteMethod(
String.format("%s/v1/tickets/%s", casServerUrlPrefix, ticketGrantingTicket));
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
LOGGER.info("Logged out");
} else {
LOGGER.warn(invalidResponseMessage(method));
throw new GenericException(invalidResponseMessage(method));
}
} catch (final IOException e) {
throw new GenericException(e.getMessage(), e);
} finally {
method.releaseConnection();
}
}
/**
* Returns an error message for invalid response from CAS server.
*
* @param method
* the HTTP method
* @return a String with the error message.
*/
private String invalidResponseMessage(final HttpMethod method) {
return String.format("Invalid response from CAS server: %s - %s", method.getStatusCode(), method.getStatusText());
}
}
| lgpl-3.0 |
PHPBenelux/App | lib/src/fx/PropertyHandler.js | 12663 | /**
* @class Ext.fx.PropertyHandler
* @ignore
*/
Ext.define('Ext.fx.PropertyHandler', {
/* Begin Definitions */
requires: ['Ext.draw.Draw'],
statics: {
defaultHandler: {
pixelDefaultsRE: /width|height|top$|bottom$|left$|right$/i,
unitRE: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/,
scrollRE: /^scroll/i,
computeDelta: function(from, end, damper, initial, attr) {
damper = (typeof damper == 'number') ? damper : 1;
var unitRE = this.unitRE,
match = unitRE.exec(from),
start, units;
if (match) {
from = match[1];
units = match[2];
if (!this.scrollRE.test(attr) && !units && this.pixelDefaultsRE.test(attr)) {
units = 'px';
}
}
from = +from || 0;
match = unitRE.exec(end);
if (match) {
end = match[1];
units = match[2] || units;
}
end = +end || 0;
start = (initial != null) ? initial : from;
return {
from: from,
delta: (end - start) * damper,
units: units
};
},
get: function(from, end, damper, initialFrom, attr) {
var ln = from.length,
out = [],
i, initial, res, j, len;
for (i = 0; i < ln; i++) {
if (initialFrom) {
initial = initialFrom[i][1].from;
}
if (Ext.isArray(from[i][1]) && Ext.isArray(end)) {
res = [];
j = 0;
len = from[i][1].length;
for (; j < len; j++) {
res.push(this.computeDelta(from[i][1][j], end[j], damper, initial, attr));
}
out.push([from[i][0], res]);
}
else {
out.push([from[i][0], this.computeDelta(from[i][1], end, damper, initial, attr)]);
}
}
return out;
},
set: function(values, easing) {
var ln = values.length,
out = [],
i, val, res, len, j;
for (i = 0; i < ln; i++) {
val = values[i][1];
if (Ext.isArray(val)) {
res = [];
j = 0;
len = val.length;
for (; j < len; j++) {
res.push(val[j].from + (val[j].delta * easing) + (val[j].units || 0));
}
out.push([values[i][0], res]);
} else {
out.push([values[i][0], val.from + (val.delta * easing) + (val.units || 0)]);
}
}
return out;
}
},
color: {
rgbRE: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i,
hexRE: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i,
hex3RE: /^#?([0-9A-F]{1})([0-9A-F]{1})([0-9A-F]{1})$/i,
parseColor : function(color, damper) {
damper = (typeof damper == 'number') ? damper : 1;
var base,
out = false,
match;
Ext.each([this.hexRE, this.rgbRE, this.hex3RE], function(re, idx) {
base = (idx % 2 == 0) ? 16 : 10;
match = re.exec(color);
if (match && match.length == 4) {
if (idx == 2) {
match[1] += match[1];
match[2] += match[2];
match[3] += match[3];
}
out = {
red: parseInt(match[1], base),
green: parseInt(match[2], base),
blue: parseInt(match[3], base)
};
return false;
}
});
return out || color;
},
computeDelta: function(from, end, damper, initial) {
from = this.parseColor(from);
end = this.parseColor(end, damper);
var start = initial ? initial : from,
tfrom = typeof start,
tend = typeof end;
//Extra check for when the color string is not recognized.
if (tfrom == 'string' || tfrom == 'undefined'
|| tend == 'string' || tend == 'undefined') {
return end || start;
}
return {
from: from,
delta: {
red: Math.round((end.red - start.red) * damper),
green: Math.round((end.green - start.green) * damper),
blue: Math.round((end.blue - start.blue) * damper)
}
};
},
get: function(start, end, damper, initialFrom) {
var ln = start.length,
out = [],
i, initial;
for (i = 0; i < ln; i++) {
if (initialFrom) {
initial = initialFrom[i][1].from;
}
out.push([start[i][0], this.computeDelta(start[i][1], end, damper, initial)]);
}
return out;
},
set: function(values, easing) {
var ln = values.length,
out = [],
i, val, parsedString, from, delta;
for (i = 0; i < ln; i++) {
val = values[i][1];
if (val) {
from = val.from;
delta = val.delta;
//multiple checks to reformat the color if it can't recognized by computeDelta.
val = (typeof val == 'object' && 'red' in val)?
'rgb(' + val.red + ', ' + val.green + ', ' + val.blue + ')' : val;
val = (typeof val == 'object' && val.length)? val[0] : val;
if (typeof val == 'undefined') {
return [];
}
parsedString = typeof val == 'string'? val :
'rgb(' + [
(from.red + Math.round(delta.red * easing)) % 256,
(from.green + Math.round(delta.green * easing)) % 256,
(from.blue + Math.round(delta.blue * easing)) % 256
].join(',') + ')';
out.push([
values[i][0],
parsedString
]);
}
}
return out;
}
},
object: {
interpolate: function(prop, damper) {
damper = (typeof damper == 'number') ? damper : 1;
var out = {},
p;
for(p in prop) {
out[p] = parseInt(prop[p], 10) * damper;
}
return out;
},
computeDelta: function(from, end, damper, initial) {
from = this.interpolate(from);
end = this.interpolate(end, damper);
var start = initial ? initial : from,
delta = {},
p;
for(p in end) {
delta[p] = end[p] - start[p];
}
return {
from: from,
delta: delta
};
},
get: function(start, end, damper, initialFrom) {
var ln = start.length,
out = [],
i, initial;
for (i = 0; i < ln; i++) {
if (initialFrom) {
initial = initialFrom[i][1].from;
}
out.push([start[i][0], this.computeDelta(start[i][1], end, damper, initial)]);
}
return out;
},
set: function(values, easing) {
var ln = values.length,
out = [],
outObject = {},
i, from, delta, val, p;
for (i = 0; i < ln; i++) {
val = values[i][1];
from = val.from;
delta = val.delta;
for (p in from) {
outObject[p] = Math.round(from[p] + delta[p] * easing);
}
out.push([
values[i][0],
outObject
]);
}
return out;
}
},
path: {
computeDelta: function(from, end, damper, initial) {
damper = (typeof damper == 'number') ? damper : 1;
var start;
from = +from || 0;
end = +end || 0;
start = (initial != null) ? initial : from;
return {
from: from,
delta: (end - start) * damper
};
},
forcePath: function(path) {
if (!Ext.isArray(path) && !Ext.isArray(path[0])) {
path = Ext.draw.Draw.parsePathString(path);
}
return path;
},
get: function(start, end, damper, initialFrom) {
var endPath = this.forcePath(end),
out = [],
startLn = start.length,
startPathLn, pointsLn, i, deltaPath, initial, j, k, path, startPath;
for (i = 0; i < startLn; i++) {
startPath = this.forcePath(start[i][1]);
deltaPath = Ext.draw.Draw.interpolatePaths(startPath, endPath);
startPath = deltaPath[0];
endPath = deltaPath[1];
startPathLn = startPath.length;
path = [];
for (j = 0; j < startPathLn; j++) {
deltaPath = [startPath[j][0]];
pointsLn = startPath[j].length;
for (k = 1; k < pointsLn; k++) {
initial = initialFrom && initialFrom[0][1][j][k].from;
deltaPath.push(this.computeDelta(startPath[j][k], endPath[j][k], damper, initial));
}
path.push(deltaPath);
}
out.push([start[i][0], path]);
}
return out;
},
set: function(values, easing) {
var ln = values.length,
out = [],
i, j, k, newPath, calcPath, deltaPath, deltaPathLn, pointsLn;
for (i = 0; i < ln; i++) {
deltaPath = values[i][1];
newPath = [];
deltaPathLn = deltaPath.length;
for (j = 0; j < deltaPathLn; j++) {
calcPath = [deltaPath[j][0]];
pointsLn = deltaPath[j].length;
for (k = 1; k < pointsLn; k++) {
calcPath.push(deltaPath[j][k].from + deltaPath[j][k].delta * easing);
}
newPath.push(calcPath.join(','));
}
out.push([values[i][0], newPath.join(',')]);
}
return out;
}
}
/* End Definitions */
}
}, function() {
Ext.each([
'outlineColor',
'backgroundColor',
'borderColor',
'borderTopColor',
'borderRightColor',
'borderBottomColor',
'borderLeftColor',
'fill',
'stroke'
], function(prop) {
this[prop] = this.color;
}, this);
}); | lgpl-3.0 |
jonathanmorgan/msu_phd_work | data/article_coding/archive/article_coding.py | 5588 | # imports
import six
# context_text imports
from context_text.models import Article
from context_text.article_coding.article_coding import ArticleCoding
# declare variables
# declare variables - article filter parameters
start_pub_date = None # should be datetime instance
end_pub_date = None # should be datetime instance
tag_in_list = []
paper_id_in_list = []
section_list = []
article_id_in_list = []
params = {}
# declare variables - processing
do_i_print_updates = True
my_article_coding = None
article_qs = None
article_count = -1
coding_status = ""
limit_to = -1
do_coding = False
# declare variables - results
success_count = -1
success_list = None
got_errors = False
error_count = -1
error_dictionary = None
error_article_id = -1
error_status_list = None
error_status = ""
error_status_counter = -1
# first, get a list of articles to code.
# ! Set param values.
# ==> start and end dates
#start_pub_date = "2009-12-06"
#end_pub_date = "2009-12-12"
# ==> tagged articles
#tag_in_list = "prelim_reliability"
#tag_in_list = "prelim_network"
#tag_in_list = "prelim_unit_test_007"
#tag_in_list = [ "prelim_reliability", "prelim_network" ]
#tag_in_list = [ "prelim_reliability_test" ] # 60 articles - Grand Rapids only.
#tag_in_list = [ "prelim_reliability_combined" ] # 87 articles, Grand Rapids and Detroit.
#tag_in_list = [ "prelim_training_001" ]
tag_in_list = [ "grp_month" ]
# ==> IDs of newspapers to include.
#paper_id_in_list = "1"
# ==> names of sections to include.
#section_list = "Lakeshore,Front Page,City and Region,Business"
# ==> just limit to specific articles by ID.
#article_id_in_list = [ 360962 ]
#article_id_in_list = [ 28598 ]
#article_id_in_list = [ 21653, 21756 ]
#article_id_in_list = [ 90948 ]
#article_id_in_list = [ 21627, 21609, 21579 ]
#article_id_in_list = [ 48778 ]
#article_id_in_list = [ 6065 ]
#article_id_in_list = [ 221858 ]
#article_id_in_list = [ 23804, 22630 ]
article_id_in_list = [ 23804 ]
# filter parameters
params[ ArticleCoding.PARAM_START_DATE ] = start_pub_date
params[ ArticleCoding.PARAM_END_DATE ] = end_pub_date
params[ ArticleCoding.PARAM_TAG_LIST ] = tag_in_list
params[ ArticleCoding.PARAM_PUBLICATION_LIST ] = paper_id_in_list
params[ ArticleCoding.PARAM_SECTION_LIST ] = section_list
params[ ArticleCoding.PARAM_ARTICLE_ID_LIST ] = article_id_in_list
# set coder you want to use.
# OpenCalais REST API v.2
params[ ArticleCoding.PARAM_CODER_TYPE ] = ArticleCoding.ARTICLE_CODING_IMPL_OPEN_CALAIS_API_V2
# get instance of ArticleCoding
my_article_coding = ArticleCoding()
my_article_coding.do_print_updates = do_i_print_updates
# set params
my_article_coding.store_parameters( params )
# create query set - ArticleCoding does the filtering for you.
article_qs = my_article_coding.create_article_query_set()
# limit for an initial test?
if ( ( limit_to is not None ) and ( isinstance( limit_to, int ) == True ) and ( limit_to > 0 ) ):
# yes.
article_qs = article_qs[ : limit_to ]
#-- END check to see if limit --#
# get article count
article_count = article_qs.count()
print( "Query params:" )
print( params )
print( "Matching article count: " + str( article_count ) )
# Do coding?
if ( do_coding == True ):
print( "do_coding == True - it's on!" )
# yes - make sure we have at least one article:
if ( article_count > 0 ):
# invoke the code_article_data( self, query_set_IN ) method.
coding_status = my_article_coding.code_article_data( article_qs )
# output status
print( "\n\n==============================\n\nCoding status: \"" + coding_status + "\"" )
# get success count
success_count = my_article_coding.get_success_count()
print( "\n\n====> Count of articles successfully processed: " + str( success_count ) )
# if successes, list out IDs.
if ( success_count > 0 ):
# there were successes.
success_list = my_article_coding.get_success_list()
print( "- list of successfully processed articles: " + str( success_list ) )
#-- END check to see if successes. --#
# got errors?
got_errors = my_article_coding.has_errors()
if ( got_errors == True ):
# get error dictionary
error_dictionary = my_article_coding.get_error_dictionary()
# get error count
error_count = len( error_dictionary )
print( "\n\n====> Count of articles with errors: " + str( error_count ) )
# loop...
for error_article_id, error_status_list in six.iteritems( error_dictionary ):
# output errors for this article.
print( "- errors for article ID " + str( error_article_id ) + ":" )
# loop over status messages.
error_status_counter = 0
for error_status in error_status_list:
# increment status
error_status_counter += 1
# print status
print( "----> status #" + str( error_status_counter ) + ": " + error_status )
#-- END loop over status messages. --#
#-- END loop over articles. --#
#-- END check to see if errors --#
#-- END check to see if article count. --#
else:
# output matching article count.
print( "do_coding == False, so dry run" )
#-- END check to see if we do_coding --#
| lgpl-3.0 |
DomeA/Nebula | code/Leo/mappingo/servers/micro-service/gis-process/src/main/java/com/domeastudio/mappingo/server/microservice/gisprocess/core/WKT2Geometry.java | 6794 | package com.domeastudio.mappingo.server.microservice.gisprocess.core;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.List;
/**
* Created by domea on 17-5-29.
*/
public class WKT2Geometry {
private static Logger logger = LoggerFactory.getLogger(WKT2Geometry.class);
private WKTReader wktReader = new WKTReader();
private GeometryFactory geometryFactory = new GeometryFactory();
private static class SingletonHolder {
private static final WKT2Geometry INSTANCE = new WKT2Geometry();
}
private WKT2Geometry() {
}
/**
* 获取当前实例
*
* @return 获取当前对象的实例,是线程安全的
*/
public static final WKT2Geometry getInstance() {
return SingletonHolder.INSTANCE;
}
public Geometry getGeometry(String wkt) throws ParseException {
Geometry geometry = wktReader.read(wkt);
if (ValidGeometryHelper.isValidAndNotEmpty(geometry)) {
return geometry;
} else {
logger.error("wkt string is empty or invalid");
throw new RuntimeException("wkt string is empty or invalid");
}
}
public Geometry getGeometry(String wkt, int epsg) throws ParseException {
Geometry geometry = wktReader.read(wkt);
geometry.setSRID(epsg);
if (ValidGeometryHelper.isValidAndNotEmpty(geometry)) {
return geometry;
} else {
logger.error("wkt string is empty or invalid");
throw new RuntimeException("wkt string is empty or invalid");
}
}
public Geometry getGeometryExt(String ewkt) throws ParseException {
Geometry geometry = getGeometry(ewkt.split(";")[1], Integer.parseInt(ewkt.split(";")[0].split("=")[1]));
if (ValidGeometryHelper.isValidAndNotEmpty(geometry)) {
return geometry;
} else {
logger.error("wkt string is empty or invalid");
throw new RuntimeException("wkt string is empty or invalid");
}
}
public LinearRing getLinearRing(Coordinate[] coordinates) {
LinearRing linearRing = geometryFactory.createLinearRing(coordinates);
if (ValidGeometryHelper.isValidAndNotEmpty(linearRing)) {
return linearRing;
} else {
logger.error("linearRing object is empty or invalid");
throw new RuntimeException("linearRing object is empty or invalid");
}
}
public Point getPoint(Coordinate coordinate) {
Point point = geometryFactory.createPoint(coordinate);
if (ValidGeometryHelper.isValidAndNotEmpty(point)) {
return point;
} else {
logger.error("point object is empty or invalid");
throw new RuntimeException("point object is empty or invalid");
}
}
public MultiPoint getMultiPoint(List<Point> pointList) {
MultiPoint multiPoint = geometryFactory.createMultiPoint((Point[]) pointList.toArray());
if (ValidGeometryHelper.isValidAndNotEmpty(multiPoint)) {
return multiPoint;
} else {
logger.error("Multi point object is empty or invalid");
throw new RuntimeException("Multi point object is empty or invalid");
}
}
public MultiPoint getMultiPoint(Coordinate[] coordinates) {
MultiPoint multiPoint = geometryFactory.createMultiPoint(coordinates);
if (ValidGeometryHelper.isValidAndNotEmpty(multiPoint)) {
return multiPoint;
} else {
logger.error("Multi point object is empty or invalid");
throw new RuntimeException("Multi point object is empty or invalid");
}
}
public LineString getLineString(Coordinate[] coordinates) {
LineString lineString = geometryFactory.createLineString(coordinates);
if (ValidGeometryHelper.isValidAndNotEmpty(lineString)) {
return lineString;
} else {
logger.error("LineString object is empty or invalid");
throw new RuntimeException("LineString object is empty or invalid");
}
}
public MultiLineString getMultiLineString(List<LineString> lineStringList) {
MultiLineString multiLineString = geometryFactory.createMultiLineString((LineString[]) lineStringList.toArray());
if (ValidGeometryHelper.isValidAndNotEmpty(multiLineString)) {
return multiLineString;
} else {
logger.error("Multi LineString object is empty or invalid");
throw new RuntimeException("Multi LineString object is empty or invalid");
}
}
public Polygon getPolygon(Coordinate[] coordinates) {
Polygon polygon = geometryFactory.createPolygon(coordinates);
if (ValidGeometryHelper.isValidAndNotEmpty(polygon)) {
return polygon;
} else {
logger.error("polygon object is empty or invalid");
throw new RuntimeException("polygon object is empty or invalid");
}
}
public Polygon getPolygon(LinearRing shell) {
Polygon polygon = geometryFactory.createPolygon(shell);
if (ValidGeometryHelper.isValidAndNotEmpty(polygon)) {
return polygon;
} else {
logger.error("polygon object is empty or invalid");
throw new RuntimeException("polygon object is empty or invalid");
}
}
public Polygon getPolygon(LinearRing shell, LinearRing[] holes) {
Polygon polygon = geometryFactory.createPolygon(shell, holes);
if (ValidGeometryHelper.isValidAndNotEmpty(polygon)) {
return polygon;
} else {
logger.error("polygon object is empty or invalid");
throw new RuntimeException("polygon object is empty or invalid");
}
}
public MultiPolygon getMultiPolygon(Polygon[] polygons) {
MultiPolygon multiPolygon = geometryFactory.createMultiPolygon(polygons);
if (ValidGeometryHelper.isValidAndNotEmpty(multiPolygon)) {
return multiPolygon;
} else {
logger.error("multi Polygon object is empty or invalid");
throw new RuntimeException("multi Polygon object is empty or invalid");
}
}
public Geometry getGeometry(Collection geoList) {
Geometry geometry = geometryFactory.buildGeometry(geoList);
if (ValidGeometryHelper.isValidAndNotEmpty(geometry)) {
return geometry;
} else {
logger.error("geometry object is empty or invalid");
throw new RuntimeException("geometry object is empty or invalid");
}
}
}
| lgpl-3.0 |
joansmith/sonarqube | server/sonar-server/src/main/java/org/sonar/server/rule/ws/CreateAction.java | 6883 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.rule.ws;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.rule.NewRule;
import org.sonar.server.rule.ReactivationException;
import org.sonar.server.rule.Rule;
import org.sonar.server.rule.RuleService;
import org.sonarqube.ws.Rules;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.net.HttpURLConnection.HTTP_CONFLICT;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
/**
* @since 4.4
*/
public class CreateAction implements RulesWsAction {
public static final String PARAM_CUSTOM_KEY = "custom_key";
public static final String PARAM_MANUAL_KEY = "manual_key";
public static final String PARAM_NAME = "name";
public static final String PARAM_DESCRIPTION = "markdown_description";
public static final String PARAM_SEVERITY = "severity";
public static final String PARAM_STATUS = "status";
public static final String PARAM_TEMPLATE_KEY = "template_key";
public static final String PARAMS = "params";
public static final String PARAM_PREVENT_REACTIVATION = "prevent_reactivation";
private final RuleService service;
private final RuleMapping mapping;
public CreateAction(RuleService service, RuleMapping mapping) {
this.service = service;
this.mapping = mapping;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller
.createAction("create")
.setDescription("Create a custom rule or a manual rule")
.setSince("4.4")
.setPost(true)
.setHandler(this);
action
.createParam(PARAM_CUSTOM_KEY)
.setDescription("Key of the custom rule")
.setExampleValue("Todo_should_not_be_used");
action
.createParam(PARAM_MANUAL_KEY)
.setDescription("Key of the manual rule")
.setExampleValue("Error_handling");
action
.createParam(PARAM_TEMPLATE_KEY)
.setDescription("Key of the template rule in order to create a custom rule (mandatory for custom rule)")
.setExampleValue("java:XPath");
action
.createParam(PARAM_NAME)
.setDescription("Rule name")
.setRequired(true)
.setExampleValue("My custom rule");
action
.createParam(PARAM_DESCRIPTION)
.setDescription("Rule description")
.setRequired(true)
.setExampleValue("Description of my custom rule");
action
.createParam(PARAM_SEVERITY)
.setDescription("Rule severity (Only for custom rule)")
.setPossibleValues(Severity.ALL);
action
.createParam(PARAM_STATUS)
.setDescription("Rule status (Only for custom rule)")
.setDefaultValue(RuleStatus.READY)
.setPossibleValues(RuleStatus.values());
action.createParam(PARAMS)
.setDescription("Parameters as semi-colon list of <key>=<value>, for example 'params=key1=v1;key2=v2' (Only for custom rule)");
action
.createParam(PARAM_PREVENT_REACTIVATION)
.setDescription("If set to true and if the rule has been deactivated (status 'REMOVED'), a status 409 will be returned")
.setDefaultValue(false)
.setBooleanPossibleValues();
}
@Override
public void handle(Request request, Response response) throws Exception {
String customKey = request.param(PARAM_CUSTOM_KEY);
String manualKey = request.param(PARAM_MANUAL_KEY);
if (isNullOrEmpty(customKey) && isNullOrEmpty(manualKey)) {
throw new BadRequestException(String.format("Either '%s' or '%s' parameters should be set", PARAM_CUSTOM_KEY, PARAM_MANUAL_KEY));
}
try {
if (!isNullOrEmpty(customKey)) {
NewRule newRule = NewRule.createForCustomRule(customKey, RuleKey.parse(request.mandatoryParam(PARAM_TEMPLATE_KEY)))
.setName(request.mandatoryParam(PARAM_NAME))
.setMarkdownDescription(request.mandatoryParam(PARAM_DESCRIPTION))
.setSeverity(request.mandatoryParam(PARAM_SEVERITY))
.setStatus(RuleStatus.valueOf(request.mandatoryParam(PARAM_STATUS)))
.setPreventReactivation(request.mandatoryParamAsBoolean(PARAM_PREVENT_REACTIVATION));
String params = request.param(PARAMS);
if (!isNullOrEmpty(params)) {
newRule.setParameters(KeyValueFormat.parse(params));
}
writeResponse(request, response, service.create(newRule));
}
if (!isNullOrEmpty(manualKey)) {
NewRule newRule = NewRule.createForManualRule(manualKey)
.setName(request.mandatoryParam(PARAM_NAME))
.setMarkdownDescription(request.mandatoryParam(PARAM_DESCRIPTION))
.setSeverity(request.param(PARAM_SEVERITY))
.setPreventReactivation(request.mandatoryParamAsBoolean(PARAM_PREVENT_REACTIVATION));
writeResponse(request, response, service.create(newRule));
}
} catch (ReactivationException e) {
write409(request, response, e.ruleKey());
}
}
private void writeResponse(Request request, Response response, RuleKey ruleKey) throws Exception {
Rule rule = service.getNonNullByKey(ruleKey);
Rules.CreateResponse createResponse = Rules.CreateResponse.newBuilder()
.setRule(mapping.buildRuleResponse(rule, null /* TODO replace by SearchOptions immutable constant */))
.build();
writeProtobuf(createResponse, request, response);
}
private void write409(Request request, Response response, RuleKey ruleKey) throws Exception {
Rule rule = service.getNonNullByKey(ruleKey);
response.stream().setStatus(HTTP_CONFLICT);
Rules.CreateResponse createResponse = Rules.CreateResponse.newBuilder()
.setRule(mapping.buildRuleResponse(rule, null /* TODO replace by SearchOptions immutable constant */))
.build();
writeProtobuf(createResponse, request, response);
}
}
| lgpl-3.0 |
km-works/portal-rpc | portal-rpc-client/src/main/java/com/liferay/portlet/asset/model/impl/AssetTagModelImpl.java | 16963 | /**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.portlet.asset.model.impl;
import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSON;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.asset.model.AssetTag;
import com.liferay.portlet.asset.model.AssetTagModel;
import com.liferay.portlet.asset.model.AssetTagSoap;
import com.liferay.portlet.expando.model.ExpandoBridge;
import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil;
import java.io.Serializable;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The base model implementation for the AssetTag service. Represents a row in the "AssetTag" database table, with each column mapped to a property of this class.
*
* <p>
* This implementation and its corresponding interface {@link com.liferay.portlet.asset.model.AssetTagModel} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link AssetTagImpl}.
* </p>
*
* @author Brian Wing Shun Chan
* @see AssetTagImpl
* @see com.liferay.portlet.asset.model.AssetTag
* @see com.liferay.portlet.asset.model.AssetTagModel
* @generated
*/
@JSON(strict = true)
public class AssetTagModelImpl extends BaseModelImpl<AssetTag>
implements AssetTagModel {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. All methods that expect a asset tag model instance should use the {@link com.liferay.portlet.asset.model.AssetTag} interface instead.
*/
public static final String TABLE_NAME = "AssetTag";
public static final Object[][] TABLE_COLUMNS = {
{ "tagId", Types.BIGINT },
{ "groupId", Types.BIGINT },
{ "companyId", Types.BIGINT },
{ "userId", Types.BIGINT },
{ "userName", Types.VARCHAR },
{ "createDate", Types.TIMESTAMP },
{ "modifiedDate", Types.TIMESTAMP },
{ "name", Types.VARCHAR },
{ "assetCount", Types.INTEGER }
};
public static final String TABLE_SQL_CREATE = "create table AssetTag (tagId LONG not null primary key,groupId LONG,companyId LONG,userId LONG,userName VARCHAR(75) null,createDate DATE null,modifiedDate DATE null,name VARCHAR(75) null,assetCount INTEGER)";
public static final String TABLE_SQL_DROP = "drop table AssetTag";
public static final String ORDER_BY_JPQL = " ORDER BY assetTag.name ASC";
public static final String ORDER_BY_SQL = " ORDER BY AssetTag.name ASC";
public static final String DATA_SOURCE = "liferayDataSource";
public static final String SESSION_FACTORY = "liferaySessionFactory";
public static final String TX_MANAGER = "liferayTransactionManager";
public static final boolean ENTITY_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.portal.util.PropsUtil.get(
"value.object.entity.cache.enabled.com.liferay.portlet.asset.model.AssetTag"),
true);
public static final boolean FINDER_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.portal.util.PropsUtil.get(
"value.object.finder.cache.enabled.com.liferay.portlet.asset.model.AssetTag"),
true);
public static final boolean COLUMN_BITMASK_ENABLED = GetterUtil.getBoolean(com.liferay.portal.util.PropsUtil.get(
"value.object.column.bitmask.enabled.com.liferay.portlet.asset.model.AssetTag"),
true);
public static long GROUPID_COLUMN_BITMASK = 1L;
public static long NAME_COLUMN_BITMASK = 2L;
/**
* Converts the soap model instance into a normal model instance.
*
* @param soapModel the soap model instance to convert
* @return the normal model instance
*/
public static AssetTag toModel(AssetTagSoap soapModel) {
if (soapModel == null) {
return null;
}
AssetTag model = new AssetTagImpl();
model.setTagId(soapModel.getTagId());
model.setGroupId(soapModel.getGroupId());
model.setCompanyId(soapModel.getCompanyId());
model.setUserId(soapModel.getUserId());
model.setUserName(soapModel.getUserName());
model.setCreateDate(soapModel.getCreateDate());
model.setModifiedDate(soapModel.getModifiedDate());
model.setName(soapModel.getName());
model.setAssetCount(soapModel.getAssetCount());
return model;
}
/**
* Converts the soap model instances into normal model instances.
*
* @param soapModels the soap model instances to convert
* @return the normal model instances
*/
public static List<AssetTag> toModels(AssetTagSoap[] soapModels) {
if (soapModels == null) {
return null;
}
List<AssetTag> models = new ArrayList<AssetTag>(soapModels.length);
for (AssetTagSoap soapModel : soapModels) {
models.add(toModel(soapModel));
}
return models;
}
public static final String MAPPING_TABLE_ASSETENTRIES_ASSETTAGS_NAME = "AssetEntries_AssetTags";
public static final Object[][] MAPPING_TABLE_ASSETENTRIES_ASSETTAGS_COLUMNS = {
{ "entryId", Types.BIGINT },
{ "tagId", Types.BIGINT }
};
public static final String MAPPING_TABLE_ASSETENTRIES_ASSETTAGS_SQL_CREATE = "create table AssetEntries_AssetTags (entryId LONG not null,tagId LONG not null,primary key (entryId, tagId))";
public static final boolean FINDER_CACHE_ENABLED_ASSETENTRIES_ASSETTAGS = GetterUtil.getBoolean(com.liferay.portal.util.PropsUtil.get(
"value.object.finder.cache.enabled.AssetEntries_AssetTags"),
true);
public static final long LOCK_EXPIRATION_TIME = GetterUtil.getLong(com.liferay.portal.util.PropsUtil.get(
"lock.expiration.time.com.liferay.portlet.asset.model.AssetTag"));
public AssetTagModelImpl() {
}
@Override
public long getPrimaryKey() {
return _tagId;
}
@Override
public void setPrimaryKey(long primaryKey) {
setTagId(primaryKey);
}
@Override
public Serializable getPrimaryKeyObj() {
return _tagId;
}
@Override
public void setPrimaryKeyObj(Serializable primaryKeyObj) {
setPrimaryKey(((Long)primaryKeyObj).longValue());
}
@Override
public Class<?> getModelClass() {
return AssetTag.class;
}
@Override
public String getModelClassName() {
return AssetTag.class.getName();
}
@Override
public Map<String, Object> getModelAttributes() {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("tagId", getTagId());
attributes.put("groupId", getGroupId());
attributes.put("companyId", getCompanyId());
attributes.put("userId", getUserId());
attributes.put("userName", getUserName());
attributes.put("createDate", getCreateDate());
attributes.put("modifiedDate", getModifiedDate());
attributes.put("name", getName());
attributes.put("assetCount", getAssetCount());
return attributes;
}
@Override
public void setModelAttributes(Map<String, Object> attributes) {
Long tagId = (Long)attributes.get("tagId");
if (tagId != null) {
setTagId(tagId);
}
Long groupId = (Long)attributes.get("groupId");
if (groupId != null) {
setGroupId(groupId);
}
Long companyId = (Long)attributes.get("companyId");
if (companyId != null) {
setCompanyId(companyId);
}
Long userId = (Long)attributes.get("userId");
if (userId != null) {
setUserId(userId);
}
String userName = (String)attributes.get("userName");
if (userName != null) {
setUserName(userName);
}
Date createDate = (Date)attributes.get("createDate");
if (createDate != null) {
setCreateDate(createDate);
}
Date modifiedDate = (Date)attributes.get("modifiedDate");
if (modifiedDate != null) {
setModifiedDate(modifiedDate);
}
String name = (String)attributes.get("name");
if (name != null) {
setName(name);
}
Integer assetCount = (Integer)attributes.get("assetCount");
if (assetCount != null) {
setAssetCount(assetCount);
}
}
@JSON
@Override
public long getTagId() {
return _tagId;
}
@Override
public void setTagId(long tagId) {
_tagId = tagId;
}
@JSON
@Override
public long getGroupId() {
return _groupId;
}
@Override
public void setGroupId(long groupId) {
_columnBitmask |= GROUPID_COLUMN_BITMASK;
if (!_setOriginalGroupId) {
_setOriginalGroupId = true;
_originalGroupId = _groupId;
}
_groupId = groupId;
}
public long getOriginalGroupId() {
return _originalGroupId;
}
@JSON
@Override
public long getCompanyId() {
return _companyId;
}
@Override
public void setCompanyId(long companyId) {
_companyId = companyId;
}
@JSON
@Override
public long getUserId() {
return _userId;
}
@Override
public void setUserId(long userId) {
_userId = userId;
}
@Override
public String getUserUuid() throws SystemException {
return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid);
}
@Override
public void setUserUuid(String userUuid) {
_userUuid = userUuid;
}
@JSON
@Override
public String getUserName() {
if (_userName == null) {
return StringPool.BLANK;
}
else {
return _userName;
}
}
@Override
public void setUserName(String userName) {
_userName = userName;
}
@JSON
@Override
public Date getCreateDate() {
return _createDate;
}
@Override
public void setCreateDate(Date createDate) {
_createDate = createDate;
}
@JSON
@Override
public Date getModifiedDate() {
return _modifiedDate;
}
@Override
public void setModifiedDate(Date modifiedDate) {
_modifiedDate = modifiedDate;
}
@JSON
@Override
public String getName() {
if (_name == null) {
return StringPool.BLANK;
}
else {
return _name;
}
}
@Override
public void setName(String name) {
_columnBitmask = -1L;
if (_originalName == null) {
_originalName = _name;
}
_name = name;
}
public String getOriginalName() {
return GetterUtil.getString(_originalName);
}
@JSON
@Override
public int getAssetCount() {
return _assetCount;
}
@Override
public void setAssetCount(int assetCount) {
_assetCount = assetCount;
}
public long getColumnBitmask() {
return _columnBitmask;
}
@Override
public ExpandoBridge getExpandoBridge() {
return ExpandoBridgeFactoryUtil.getExpandoBridge(getCompanyId(),
AssetTag.class.getName(), getPrimaryKey());
}
@Override
public void setExpandoBridgeAttributes(ServiceContext serviceContext) {
ExpandoBridge expandoBridge = getExpandoBridge();
expandoBridge.setAttributes(serviceContext);
}
@Override
public AssetTag toEscapedModel() {
if (_escapedModel == null) {
_escapedModel = (AssetTag)ProxyUtil.newProxyInstance(_classLoader,
_escapedModelInterfaces, new AutoEscapeBeanHandler(this));
}
return _escapedModel;
}
@Override
public Object clone() {
AssetTagImpl assetTagImpl = new AssetTagImpl();
assetTagImpl.setTagId(getTagId());
assetTagImpl.setGroupId(getGroupId());
assetTagImpl.setCompanyId(getCompanyId());
assetTagImpl.setUserId(getUserId());
assetTagImpl.setUserName(getUserName());
assetTagImpl.setCreateDate(getCreateDate());
assetTagImpl.setModifiedDate(getModifiedDate());
assetTagImpl.setName(getName());
assetTagImpl.setAssetCount(getAssetCount());
assetTagImpl.resetOriginalValues();
return assetTagImpl;
}
@Override
public int compareTo(AssetTag assetTag) {
int value = 0;
value = getName().compareTo(assetTag.getName());
if (value != 0) {
return value;
}
return 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof AssetTag)) {
return false;
}
AssetTag assetTag = (AssetTag)obj;
long primaryKey = assetTag.getPrimaryKey();
if (getPrimaryKey() == primaryKey) {
return true;
}
else {
return false;
}
}
@Override
public int hashCode() {
return (int)getPrimaryKey();
}
@Override
public void resetOriginalValues() {
AssetTagModelImpl assetTagModelImpl = this;
assetTagModelImpl._originalGroupId = assetTagModelImpl._groupId;
assetTagModelImpl._setOriginalGroupId = false;
assetTagModelImpl._originalName = assetTagModelImpl._name;
assetTagModelImpl._columnBitmask = 0;
}
@Override
public CacheModel<AssetTag> toCacheModel() {
AssetTagCacheModel assetTagCacheModel = new AssetTagCacheModel();
assetTagCacheModel.tagId = getTagId();
assetTagCacheModel.groupId = getGroupId();
assetTagCacheModel.companyId = getCompanyId();
assetTagCacheModel.userId = getUserId();
assetTagCacheModel.userName = getUserName();
String userName = assetTagCacheModel.userName;
if ((userName != null) && (userName.length() == 0)) {
assetTagCacheModel.userName = null;
}
Date createDate = getCreateDate();
if (createDate != null) {
assetTagCacheModel.createDate = createDate.getTime();
}
else {
assetTagCacheModel.createDate = Long.MIN_VALUE;
}
Date modifiedDate = getModifiedDate();
if (modifiedDate != null) {
assetTagCacheModel.modifiedDate = modifiedDate.getTime();
}
else {
assetTagCacheModel.modifiedDate = Long.MIN_VALUE;
}
assetTagCacheModel.name = getName();
String name = assetTagCacheModel.name;
if ((name != null) && (name.length() == 0)) {
assetTagCacheModel.name = null;
}
assetTagCacheModel.assetCount = getAssetCount();
return assetTagCacheModel;
}
@Override
public String toString() {
StringBundler sb = new StringBundler(19);
sb.append("{tagId=");
sb.append(getTagId());
sb.append(", groupId=");
sb.append(getGroupId());
sb.append(", companyId=");
sb.append(getCompanyId());
sb.append(", userId=");
sb.append(getUserId());
sb.append(", userName=");
sb.append(getUserName());
sb.append(", createDate=");
sb.append(getCreateDate());
sb.append(", modifiedDate=");
sb.append(getModifiedDate());
sb.append(", name=");
sb.append(getName());
sb.append(", assetCount=");
sb.append(getAssetCount());
sb.append("}");
return sb.toString();
}
@Override
public String toXmlString() {
StringBundler sb = new StringBundler(31);
sb.append("<model><model-name>");
sb.append("com.liferay.portlet.asset.model.AssetTag");
sb.append("</model-name>");
sb.append(
"<column><column-name>tagId</column-name><column-value><![CDATA[");
sb.append(getTagId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>groupId</column-name><column-value><![CDATA[");
sb.append(getGroupId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>companyId</column-name><column-value><![CDATA[");
sb.append(getCompanyId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>userId</column-name><column-value><![CDATA[");
sb.append(getUserId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>userName</column-name><column-value><![CDATA[");
sb.append(getUserName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>createDate</column-name><column-value><![CDATA[");
sb.append(getCreateDate());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>modifiedDate</column-name><column-value><![CDATA[");
sb.append(getModifiedDate());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>name</column-name><column-value><![CDATA[");
sb.append(getName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>assetCount</column-name><column-value><![CDATA[");
sb.append(getAssetCount());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
private static ClassLoader _classLoader = AssetTag.class.getClassLoader();
private static Class<?>[] _escapedModelInterfaces = new Class[] {
AssetTag.class
};
private long _tagId;
private long _groupId;
private long _originalGroupId;
private boolean _setOriginalGroupId;
private long _companyId;
private long _userId;
private String _userUuid;
private String _userName;
private Date _createDate;
private Date _modifiedDate;
private String _name;
private String _originalName;
private int _assetCount;
private long _columnBitmask;
private AssetTag _escapedModel;
} | lgpl-3.0 |
smba/oak | edu.cmu.cs.oak/src/main/resources/COM.php | 250 | <?php
class COM {
public function __construct($module_name) {
}
public function AddRef() {
}
public function Release() {
}
public function All() {
}
public function Next() {
}
public function Prev() {
}
public function Reset() {
}
}
?> | lgpl-3.0 |
ijon/elliptics | bindings/cpp/callback.cpp | 6167 | /*
* 2008+ Copyright (c) Evgeniy Polyakov <[email protected]>
* 2012+ Copyright (c) Ruslan Nigmatullin <[email protected]>
* All rights reserved.
*
* 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 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 Lesser General Public License for more details.
*/
#include "callback_p.h"
#include "../../library/elliptics.h"
namespace ioremap { namespace elliptics {
namespace detail {
class basic_handler
{
public:
static int handler(dnet_addr *addr, dnet_cmd *cmd, void *priv)
{
basic_handler *that = reinterpret_cast<basic_handler *>(priv);
if (that->handle(addr, cmd)) {
delete that;
}
return 0;
}
basic_handler(const elliptics::logger &logger, async_generic_result &result) :
m_logger(logger, blackhole::log::attributes_t()),
m_handler(result), m_completed(0), m_total(0)
{
}
bool handle(dnet_addr *addr, dnet_cmd *cmd)
{
if (is_trans_destroyed(cmd)) {
return increment_completed();
}
BH_LOG(m_logger, cmd->status ? DNET_LOG_ERROR : DNET_LOG_NOTICE,
"%s: handled reply from: %s, cmd: %s, flags: %s, trans: %lld, status: %d, size: %lld, client: %d, last: %d",
dnet_dump_id(&cmd->id), addr ? dnet_server_convert_dnet_addr(addr) : "<unknown>", dnet_cmd_string(cmd->cmd),
dnet_flags_dump_cflags(cmd->flags), uint64_t(cmd->trans), int(cmd->status), uint64_t(cmd->size),
!(cmd->flags & DNET_FLAGS_REPLY), !(cmd->flags & DNET_FLAGS_MORE));
auto data = std::make_shared<callback_result_data>(addr, cmd);
if (cmd->status)
data->error = create_error(*cmd);
callback_result_entry entry(data);
if (cmd->cmd == DNET_CMD_EXEC && cmd->size > 0) {
data->context = exec_context::parse(entry.data(), &data->error);
}
m_handler.process(entry);
return false;
}
bool set_total(size_t total)
{
m_handler.set_total(total);
m_total = total + 1;
return increment_completed();
}
private:
bool increment_completed()
{
if (++m_completed == m_total) {
m_handler.complete(error_info());
return true;
}
return false;
}
logger m_logger;
async_result_handler<callback_result_entry> m_handler;
std::atomic_size_t m_completed;
std::atomic_size_t m_total;
};
} // namespace detail
template <typename Method, typename T>
async_generic_result send_impl(session &sess, T &control, Method method)
{
scoped_trace_id guard(sess);
async_generic_result result(sess);
detail::basic_handler *handler = new detail::basic_handler(sess.get_logger(), result);
control.complete = detail::basic_handler::handler;
control.priv = handler;
const size_t count = method(sess, control);
if (handler->set_total(count))
delete handler;
return result;
}
static size_t send_to_single_state_impl(session &sess, dnet_trans_control &ctl)
{
dnet_trans_alloc_send(sess.get_native(), &ctl);
return 1;
}
// Send request to specificly set state by id
async_generic_result send_to_single_state(session &sess, const transport_control &control)
{
dnet_trans_control writable_copy = control.get_native();
return send_impl(sess, writable_copy, send_to_single_state_impl);
}
static size_t send_to_single_state_io_impl(session &sess, dnet_io_control &ctl)
{
dnet_io_trans_alloc_send(sess.get_native(), &ctl);
return 1;
}
async_generic_result send_to_single_state(session &sess, dnet_io_control &control)
{
return send_impl(sess, control, send_to_single_state_io_impl);
}
static size_t send_to_each_backend_impl(session &sess, dnet_trans_control &ctl)
{
return dnet_request_cmd(sess.get_native(), &ctl);
}
// Send request to each backend
async_generic_result send_to_each_backend(session &sess, const transport_control &control)
{
dnet_trans_control writable_copy = control.get_native();
return send_impl(sess, writable_copy, send_to_each_backend_impl);
}
static size_t send_to_each_node_impl(session &sess, dnet_trans_control &ctl)
{
dnet_node *node = sess.get_native_node();
dnet_session *native_sess = sess.get_native();
dnet_net_state *st;
ctl.cflags |= DNET_FLAGS_DIRECT;
size_t count = 0;
pthread_mutex_lock(&node->state_lock);
list_for_each_entry(st, &node->dht_state_list, node_entry) {
if (st == node->st)
continue;
dnet_trans_alloc_send_state(native_sess, st, &ctl);
++count;
}
pthread_mutex_unlock(&node->state_lock);
return count;
}
async_generic_result send_to_each_node(session &sess, const transport_control &control)
{
dnet_trans_control writable_copy = control.get_native();
return send_impl(sess, writable_copy, send_to_each_node_impl);
}
static size_t send_to_groups_impl(session &sess, dnet_trans_control &ctl)
{
dnet_session *native = sess.get_native();
size_t counter = 0;
for (int i = 0; i < native->group_num; ++i) {
ctl.id.group_id = native->groups[i];
dnet_trans_alloc_send(native, &ctl);
++counter;
}
return counter;
}
// Send request to one state at each session's group
async_generic_result send_to_groups(session &sess, const transport_control &control)
{
dnet_trans_control writable_copy = control.get_native();
return send_impl(sess, writable_copy, send_to_groups_impl);
}
static size_t send_to_groups_io_impl(session &sess, dnet_io_control &ctl)
{
return dnet_trans_create_send_all(sess.get_native(), &ctl);
}
async_generic_result send_to_groups(session &sess, dnet_io_control &control)
{
return send_impl(sess, control, send_to_groups_io_impl);
}
async_generic_result send_srw_command(session &sess, dnet_id *id, sph *srw_data)
{
scoped_trace_id guard(sess);
async_generic_result result(sess);
detail::basic_handler *handler = new detail::basic_handler(sess.get_logger(), result);
const size_t count = dnet_send_cmd(sess.get_native(), id, detail::basic_handler::handler, handler, srw_data);
if (handler->set_total(count))
delete handler;
return result;
}
} } // namespace ioremap::elliptics
| lgpl-3.0 |
egk696/VHDL_FSM_Visualizer | VHDL FSM Visualizer/Utils.cs | 16229 | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VHDL_FSM_Visualizer
{
class Utils
{
public static Form1 form { get; set; }
public enum logType { Info, Error, Warning, Debug };
static int fsmDeclarationLine = -1;
static int lineOfOpenEnum = -1, indexOfOpenEnum = -1, lineOfCloseEnum = -1, indexOfCloseEnum = -1;
static string fsmDeclerationText = "";
static int fsmCaseStartLine = -1, fsmCaseEndLine = -1;
static string caseStatementStr = "";
public static List<FSM_State> vhdlParseStatesDecleration(string[] linesOfCode, string fsmTypeVariable)
{
List<FSM_State> fsmStates = new List<FSM_State>();
lineOfOpenEnum = -1;
indexOfOpenEnum = -1;
lineOfCloseEnum = -1;
indexOfCloseEnum = -1;
fsmDeclerationText = "";
fsmDeclarationLine = -1;
fsmCaseStartLine = -1;
fsmCaseEndLine = -1;
caseStatementStr = "";
try
{
bool fsmTypeFound = false;
//Find the code line declaring the specified FSM enum for fsmTypeVariable
for (int i = 0; i < linesOfCode.Length; i++)
{
if (linesOfCode[i].Contains(fsmTypeVariable))
{
fsmTypeFound = true;
fsmDeclarationLine = i;
break;
}
}
for (int i = fsmDeclarationLine; i < linesOfCode.Length; i++)
{
string locTemp = linesOfCode[i];
if ((indexOfOpenEnum = locTemp.IndexOf("(")) != -1)
{
lineOfOpenEnum = i;
for (int j = i; j < linesOfCode.Length; j++)
{
fsmDeclerationText += linesOfCode[j];
if ((indexOfCloseEnum = linesOfCode[j].IndexOf(");")) != -1)
{
lineOfCloseEnum = j;
break;
}
}
if (lineOfCloseEnum != -1)
{
break;
}
}
}
//Clear the string
if (fsmDeclerationText.IndexOf("type", StringComparison.CurrentCultureIgnoreCase) != -1)
{
fsmDeclerationText = fsmDeclerationText.Remove(fsmDeclerationText.IndexOf("type", StringComparison.CurrentCultureIgnoreCase), indexOfOpenEnum - fsmDeclerationText.IndexOf("type", StringComparison.CurrentCultureIgnoreCase));
}
else if (fsmDeclerationText.IndexOf("(") != -1)
{
fsmDeclerationText = fsmDeclerationText.Remove(fsmDeclerationText.IndexOf("("), indexOfOpenEnum - fsmDeclerationText.IndexOf("("));
}
fsmDeclerationText = RemoveSpecialCharacters(fsmDeclerationText);
//Split just the state names
string[] statesText = fsmDeclerationText.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
fsmStates = new List<FSM_State>(statesText.Length);
//Create the states
for (int i = 0; i < statesText.Length; i++)
{
fsmStates.Add(new FSM_State(i, statesText[i]));
}
}
catch (Exception ex)
{
Utils.WriteLogFile(Utils.logType.Error, "Exception occured with message: " + ex.Message, "Data: \n" + ex.Data);
}
return fsmStates;
}
public static string[] vhdlRemoveComments(string[] linesOfCode)
{
List<string> linesWithoutComents = new List<string>(linesOfCode.Length);
for (int i = 0; i < linesOfCode.Length; i++)
{
linesWithoutComents.Add(RemoveComments(linesOfCode[i]));
}
return linesWithoutComents.ToArray();
}
public static List<FSM_State> vhdlParseStatesTransitions(List<FSM_State> fsmStates, string[] linesOfCode, string fsmCurrStateVar, string fsmNextStateVar)
{
//Find the case statement corresponding to the FSM defined by fsmCurrStateVar
for (int i = lineOfCloseEnum; i < linesOfCode.Length; i++)
{
string line = linesOfCode[i];
if (CaseForFSMExists(line, fsmCurrStateVar))
{
fsmCaseStartLine = i;
}
else if (EndCaseForFSMExists(line) && fsmCaseStartLine != -1)
{
fsmCaseEndLine = i;
break;
}
}
//Concate the text corresponding to the FSM defined by fsmCurrStateVar
if (fsmCaseStartLine != -1 && fsmCaseEndLine != -1)
{
for (int i = fsmCaseStartLine; i <= fsmCaseEndLine; i++)
{
caseStatementStr += linesOfCode[i];
}
//Find the starting & ending lines numbers of each WHEN text foreach STATE in fsmStates
FSM_State tempState = null, prevState = null;
for (int i = fsmCaseStartLine; i <= fsmCaseEndLine; i++)
{
string line = linesOfCode[i].Replace("\t", String.Empty).Replace("\n", String.Empty);
if ((tempState = GetStateBelongsToWhen(line, fsmStates)) != null)
{
tempState.whenStmentStartLine = i;
if (prevState != null)
{
prevState.whenStmentEndLine = i;
}
prevState = tempState;
}
else if (EndCaseForFSMExists(line) && prevState != null)
{
prevState.whenStmentEndLine = i;
}
}
//Concate the WHEN text foreach STATE foreach state in fsmStates
for (int ii = 0; ii < fsmStates.Count; ii++)
{
FSM_State state = fsmStates[ii];
StringBuilder sb = new StringBuilder();
if (state.whenStmentStartLine != -1 && state.whenStmentEndLine != -1)
{
for (int i = state.whenStmentStartLine; i < state.whenStmentEndLine; i++)
{
string line = RemoveLeadingMultiTabs(linesOfCode[i]);
sb.AppendLine(line);
}
state.whenStmentTxt = sb.ToString().Replace("\t", " ");
Utils.WriteLogFile(Utils.logType.Debug, "State: " + state.name + " ", state.whenStmentTxt.Replace("\t", " "));
}
else
{
Utils.WriteLogFile(Utils.logType.Debug, "State: " + state.name + " doesn't have a WHEN statement");
}
}
//TODO: Find transitions to next states foreach state in fsmStates
foreach (FSM_State state in fsmStates)
{
int startIfLine = -1, endIfLine = -1, startElseLine = -1;
int ifsCount = 0;
for (int i = state.whenStmentStartLine; i < state.whenStmentEndLine; i++)
{
string line = linesOfCode[i].Replace("\t", String.Empty).Replace("\n", String.Empty);
if (ifsCount == 0 && line.IndexOf(fsmNextStateVar) != -1) //transition found outside of Condition
{
FSM_State next_state = GetStateForTransition(line, fsmStates, fsmNextStateVar);
if (next_state != null)
{
state.next_states.Add(next_state, "always");
}
else
{
Utils.WriteLogFile(logType.Error, "line #" + (i + 1) + ": " + line + " has an unknown next state");
}
}
else if (i > startIfLine && (i<startElseLine || startElseLine==-1) && line.IndexOf(fsmNextStateVar) != -1)
{
FSM_State next_state = GetStateForTransition(line, fsmStates, fsmNextStateVar);
if (next_state != null)
{
try
{
state.next_states.Add(next_state, KeepOnlyConditionText(linesOfCode[startIfLine]));
}
catch (Exception ex)
{
Utils.WriteLogFile(logType.Error, "line #" + (i + 1) + ": " + line + " could not add state transition" + state.name +"->"+next_state.name);
}
}
else
{
Utils.WriteLogFile(Utils.logType.Error, "line #" + (i + 1) + ": " + line + " has an unknown next state");
}
}
else if (i > startElseLine && line.IndexOf(fsmNextStateVar) != -1)
{
FSM_State next_state = GetStateForTransition(line, fsmStates, fsmNextStateVar);
if (next_state != null)
{
try
{
state.next_states.Add(next_state, "not(" + KeepOnlyConditionText(linesOfCode[startIfLine]) + ")");
}
catch (Exception ex)
{
Utils.WriteLogFile(logType.Error, "line #" + (i + 1) + ": " + line + " could not add state transition" + state.name + "->" + next_state.name);
}
}
else
{
Utils.WriteLogFile(logType.Error, "line #" + (i + 1) + ": " + line + " has an unknown next state");
}
}
if (IsIfStatement(line))
{
startIfLine = i;
ifsCount++;
}
else if (IsElseIfStatement(line))
{
startIfLine = i;
}
else if (IsElseStatement(line))
{
startElseLine = i;
}
else if (IsEndIfStatement(line))
{
ifsCount--;
}
}
}
}
else
{
WriteLogFile(logType.Debug, "Case statement could not be found for variable", fsmCurrStateVar);
}
return fsmStates;
}
public static FSM_State GetStateForTransition(string line, List<FSM_State> states, string fsmNextStateVar)
{
foreach (FSM_State state in states)
{
if (Regex.IsMatch(line, fsmNextStateVar + @"(\s+|\t+)?<=(\s+|\t+)?(?:^|)" + state.name + @"(?:$|\W)", RegexOptions.IgnoreCase))
{
return state;
}
}
return null;
}
public static FSM_State GetStateBelongsToWhen(string line, List<FSM_State> states)
{
foreach (FSM_State state in states)
{
if (Regex.IsMatch(line, @"when(\s+|\t+)" + state.name + @"(\s+|\t+)?=>", RegexOptions.IgnoreCase))
{
return state;
}
}
if (Regex.IsMatch(line, @"when(\s+|\t+)(.+?)=>", RegexOptions.IgnoreCase)) //capture an unknown state i.e.: WHEN others =>
{
return new FSM_State(-1, "");
}
else //nothing found
{
return null;
}
}
public static bool IsNextStateAssign(string line, string fsmNextStateVar)
{
return Regex.IsMatch(line, fsmNextStateVar + @"(\s+|\t+)<=(.*?);", RegexOptions.Compiled);
}
public static bool IsIfStatement(string line)
{
return Regex.IsMatch(line, @"if(\s+|\t+)(.*?)then", RegexOptions.IgnoreCase);
}
public static bool IsElseIfStatement(string line)
{
return Regex.IsMatch(line, @"elsif(\s+|\t+)(.*?)then", RegexOptions.IgnoreCase);
}
public static bool IsElseStatement(string line)
{
return Regex.IsMatch(line, @"else", RegexOptions.IgnoreCase);
}
public static bool IsEndIfStatement(string line)
{
return Regex.IsMatch(line, @"end(\s+|\t+)if;", RegexOptions.IgnoreCase);
}
public static bool CaseForFSMExists(string line, string fsmCurrStateVar)
{
return Regex.IsMatch(line, @"case(\s+|\t+)" + fsmCurrStateVar + @"(\s+|\t+)is", RegexOptions.IgnoreCase);
}
public static bool EndCaseForFSMExists(string line)
{
return Regex.IsMatch(line, @"end(\s+|\t+)case;", RegexOptions.IgnoreCase);
}
public static string RemoveNonCodeCharacters(string str)
{
return Regex.Replace(str, @"[^a-zA-Z0-9_.,;\(\)\{\}]+", String.Empty, RegexOptions.Compiled);
}
public static string RemoveComments(string str)
{
return Regex.Replace(str, @"\-\-.*", String.Empty, RegexOptions.Compiled);
}
public static string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.,]+", String.Empty, RegexOptions.Compiled);
}
public static string KeepOnlyConditionText(string str)
{
return Regex.Replace(str, @"(if|then|elsif|\t+)", String.Empty, RegexOptions.IgnoreCase);
}
public static string RemoveLeadingMultiTabs(string str)
{
return Regex.Replace(str, @"^([\t]\t)", String.Empty, RegexOptions.Compiled);
}
public static void WriteLogFile(logType type, string message, string extras = "")
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (form != null)
{
if (type == logType.Debug)
{
if (bool.Parse(config.AppSettings.Settings["DebugMode"].Value.ToString()))
{
form.LogOutput.Items.Add(DateTime.Now.ToString("HH:mm:ss") + ": ----" + type.ToString() + ": " + message + " " + extras);
}
}
else
{
form.LogOutput.Items.Add(DateTime.Now.ToString("HH:mm:ss") + ": ----" + type.ToString() + ": " + message + " " + extras);
}
form.LogOutput.SelectedIndex = form.LogOutput.Items.Count - 1;
form.LogOutput.SelectedIndex = -1;
}
else
{
return;
}
}
}
}
| lgpl-3.0 |
clodbrasilino/eficiencia-energetica-web | emulador-see/src/br/edu/ifpi/see/emulador/servlets/LigaPresencaServlet.java | 858 | package br.edu.ifpi.see.emulador.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.edu.ifpi.see.emulador.model.Estado;
import br.edu.ifpi.see.emulador.model.EstadoEmulador;
@WebServlet("/ligaPresenca")
public class LigaPresencaServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
((EstadoEmulador)getServletContext().getAttribute("estadoAtual")).setPresenca(Estado.LIGADO);
request.getRequestDispatcher("/configurar.jsp").forward(request, response);
}
}
| lgpl-3.0 |
bigfug/Fugio | plugins/Serial/serialdecodernode.cpp | 2226 | #include "serialdecodernode.h"
#include <QBitArray>
#include <fugio/core/uuid.h>
#include <fugio/context_interface.h>
SerialDecoderNode::SerialDecoderNode( QSharedPointer<fugio::NodeInterface> pNode )
: NodeControlBase( pNode )
{
FUGID( PIN_INPUT_BITS, "7AC449C1-0CC8-4DEA-A404-BB439BDD976E" );
FUGID( PIN_OUTPUT_DATA, "7A49997F-F720-4EBA-81D3-347F00C55CB9" );
mPinInputBits = pinInput( "Bits", PIN_INPUT_BITS );
mValOutputData = pinOutput<fugio::VariantInterface *>( "Data", mPinOutputData, PID_BYTEARRAY, PIN_OUTPUT_DATA );
}
void SerialDecoderNode::inputsUpdated( qint64 pTimeStamp )
{
if( mPinInputBits->isUpdated( pTimeStamp ) )
{
QBitArray InpDat = variant( mPinInputBits ).toBitArray();
if( !InpDat.isEmpty() )
{
QBitArray SrcDat;
QByteArray DstDat;
// Prepend any buffered data
if( !mBitBuf.isEmpty() )
{
int InpSze = InpDat.size();
int BufSze = mBitBuf.size();
SrcDat.resize( BufSze + InpSze );
for( int i = 0 ; i < BufSze ; i++ )
{
SrcDat.setBit( i, mBitBuf.testBit( i ) );
}
for( int i = 0 ; i < InpSze ; i++ )
{
SrcDat.setBit( BufSze + i, InpDat.testBit( i ) );
}
mBitBuf.clear();
}
else
{
SrcDat.swap( InpDat );
}
// Look for data
// qDebug() << "R:" << SrcDat;
int SrcOff;
for( SrcOff = 0 ; SrcOff < SrcDat.size() - 9 ; )
{
if( SrcDat.testBit( SrcOff ) || !SrcDat.testBit( SrcOff + 9 ) )
{
SrcOff++;
continue;
}
QBitArray T( 8 );
quint8 C = 0;
for( int j = 0 ; j < 8 ; j++ )
{
C |= ( SrcDat.testBit( SrcOff + 1 + j ) ? 0x01 : 0x00 ) << j;
T.setBit( j, SrcDat.testBit( SrcOff + 1 + j ) );
}
// qDebug() << SrcOff << T;
DstDat.append( C );
SrcOff += 10;
}
if( SrcOff < SrcDat.size() )
{
if( SrcOff > 0 )
{
mBitBuf.resize( SrcDat.size() - SrcOff );
for( int i = 0 ; i < mBitBuf.size() ; i++ )
{
mBitBuf.setBit( i, SrcDat.testBit( SrcOff + i ) );
}
}
else
{
SrcDat.swap( mBitBuf );
}
// qDebug() << "B" << mBitBuf;
}
if( !DstDat.isEmpty() )
{
mValOutputData->setVariant( DstDat );
pinUpdated( mPinOutputData );
}
}
}
}
| lgpl-3.0 |
CUCKOO0615/MyCode | CkUpdater/CkUpdater/stdafx.cpp | 215 | // stdafx.cpp : Ö»°üÀ¨±ê×¼°üº¬ÎļþµÄÔ´Îļþ
// CkUpdater.pch ½«×÷ΪԤ±àÒëÍ·
// stdafx.obj ½«°üº¬Ô¤±àÒëÀàÐÍÐÅÏ¢
#include "stdafx.h"
// TODO: ÔÚ STDAFX.H ÖÐ
// ÒýÓÃÈκÎËùÐèµÄ¸½¼ÓÍ·Îļþ£¬¶ø²»ÊÇÔÚ´ËÎļþÖÐÒýÓÃ
| lgpl-3.0 |
stamppot/bcms_store_products | app/models/product_type.rb | 264 | class ProductType < ActiveRecord::Base
acts_as_content_block :belongs_to_attachment => true
has_many :products
belongs_to :user
validates_presence_of :name
validates_uniqueness_of :name
named_scope :published, :conditions => {:published => true}
end
| lgpl-3.0 |
martintreurnicht/ethereumj | ethereumj-core/src/main/java/org/ethereum/sync/HeadersDownloader.java | 4192 | /*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ 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 3 of the License, or
* (at your option) any later version.
*
* The ethereumJ 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 the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.sync;
import org.ethereum.core.BlockHeader;
import org.ethereum.core.BlockHeaderWrapper;
import org.ethereum.core.BlockWrapper;
import org.ethereum.datasource.DataSourceArray;
import org.ethereum.db.DbFlushManager;
import org.ethereum.db.IndexedBlockStore;
import org.ethereum.net.server.Channel;
import org.ethereum.net.server.ChannelManager;
import org.ethereum.validator.BlockHeaderValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Created by Anton Nashatyrev on 27.10.2016.
*/
@Component
@Lazy
public class HeadersDownloader extends BlockDownloader {
private final static Logger logger = LoggerFactory.getLogger("sync");
@Autowired
SyncPool syncPool;
@Autowired
ChannelManager channelManager;
@Autowired
IndexedBlockStore blockStore;
@Autowired @Qualifier("headerSource")
DataSourceArray<BlockHeader> headerStore;
@Autowired
DbFlushManager dbFlushManager;
byte[] genesisHash;
int headersLoaded = 0;
@Autowired
public HeadersDownloader(BlockHeaderValidator headerValidator) {
super(headerValidator);
setHeaderQueueLimit(200000);
setBlockBodiesDownload(false);
logger.info("HeaderDownloader created.");
}
public void init(byte[] startFromBlockHash) {
logger.info("HeaderDownloader init: startHash = " + Hex.toHexString(startFromBlockHash));
SyncQueueReverseImpl syncQueue = new SyncQueueReverseImpl(startFromBlockHash, true);
super.init(syncQueue, syncPool);
syncPool.init(channelManager);
}
@Override
protected synchronized void pushBlocks(List<BlockWrapper> blockWrappers) {}
@Override
protected void pushHeaders(List<BlockHeaderWrapper> headers) {
if (headers.get(headers.size() - 1).getNumber() == 0) {
genesisHash = headers.get(headers.size() - 1).getHash();
}
if (headers.get(headers.size() - 1).getNumber() == 1) {
genesisHash = headers.get(headers.size() - 1).getHeader().getParentHash();
}
logger.info(headers.size() + " headers loaded: " + headers.get(0).getNumber() + " - " + headers.get(headers.size() - 1).getNumber());
for (BlockHeaderWrapper header : headers) {
headerStore.set((int) header.getNumber(), header.getHeader());
headersLoaded++;
}
dbFlushManager.commit();
}
/**
* Headers download could block chain synchronization occupying all peers
* Prevents this by leaving one peer without work
* Fallbacks to any peer when low number of active peers available
*/
@Override
Channel getAnyPeer() {
return syncPool.getActivePeersCount() > 2 ? syncPool.getNotLastIdle() : syncPool.getAnyIdle();
}
@Override
protected int getBlockQueueFreeSize() {
return Integer.MAX_VALUE;
}
public int getHeadersLoaded() {
return headersLoaded;
}
@Override
protected void finishDownload() {
stop();
}
public byte[] getGenesisHash() {
return genesisHash;
}
}
| lgpl-3.0 |
queueit/QueueIT.Security-Php | QueueIT.Security.Tests/simpletest/test/tag_test.php | 21342 | <?php
// $Id: tag_test.php 1748 2008-04-14 01:50:41Z lastcraft $
require_once(dirname(__FILE__) . '/../autorun.php');
require_once(dirname(__FILE__) . '/../tag.php');
require_once(dirname(__FILE__) . '/../encoding.php');
Mock::generate('SimpleMultipartEncoding');
class TestOfTag extends UnitTestCase {
function testStartValuesWithoutAdditionalContent() {
$tag = new SimpleTitleTag(array('a' => '1', 'b' => ''));
$this->assertEquals('title', $tag->getTagName());
$this->assertIdentical($tag->getAttribute('a'), '1');
$this->assertIdentical($tag->getAttribute('b'), '');
$this->assertIdentical($tag->getAttribute('c'), false);
$this->assertIdentical($tag->getContent(), '');
}
function testTitleContent() {
$tag = new SimpleTitleTag(array());
$this->assertTrue($tag->expectEndTag());
$tag->addContent('Hello');
$tag->addContent('World');
$this->assertEquals('HelloWorld', $tag->getText());
}
function testMessyTitleContent() {
$tag = new SimpleTitleTag(array());
$this->assertTrue($tag->expectEndTag());
$tag->addContent('<b>Hello</b>');
$tag->addContent('<em>World</em>');
$this->assertEquals('HelloWorld', $tag->getText());
}
function testTagWithNoEnd() {
$tag = new SimpleTextTag(array());
$this->assertFalse($tag->expectEndTag());
}
function testAnchorHref() {
$tag = new SimpleAnchorTag(array('href' => 'http://here/'));
$this->assertEquals('http://here/', $tag->getHref());
$tag = new SimpleAnchorTag(array('href' => ''));
$this->assertIdentical($tag->getAttribute('href'), '');
$this->assertIdentical($tag->getHref(), '');
$tag = new SimpleAnchorTag(array());
$this->assertIdentical($tag->getAttribute('href'), false);
$this->assertIdentical($tag->getHref(), '');
}
function testIsIdMatchesIdAttribute() {
$tag = new SimpleAnchorTag(array('href' => 'http://here/', 'id' => 7));
$this->assertIdentical($tag->getAttribute('id'), '7');
$this->assertTrue($tag->isId(7));
}
}
class TestOfWidget extends UnitTestCase {
function testTextEmptyDefault() {
$tag = new SimpleTextTag(array('type' => 'text'));
$this->assertIdentical($tag->getDefault(), '');
$this->assertIdentical($tag->getValue(), '');
}
function testSettingOfExternalLabel() {
$tag = new SimpleTextTag(array('type' => 'text'));
$tag->setLabel('it');
$this->assertTrue($tag->isLabel('it'));
}
function testTextDefault() {
$tag = new SimpleTextTag(array('value' => 'aaa'));
$this->assertEquals('aaa', $tag->getDefault());
$this->assertEquals('aaa', $tag->getValue());
}
function testSettingTextValue() {
$tag = new SimpleTextTag(array('value' => 'aaa'));
$tag->setValue('bbb');
$this->assertEquals('bbb', $tag->getValue());
$tag->resetValue();
$this->assertEquals('aaa', $tag->getValue());
}
function testFailToSetHiddenValue() {
$tag = new SimpleTextTag(array('value' => 'aaa', 'type' => 'hidden'));
$this->assertFalse($tag->setValue('bbb'));
$this->assertEquals('aaa', $tag->getValue());
}
function testSubmitDefaults() {
$tag = new SimpleSubmitTag(array('type' => 'submit'));
$this->assertIdentical($tag->getName(), false);
$this->assertEquals('Submit', $tag->getValue());
$this->assertFalse($tag->setValue('Cannot set this'));
$this->assertEquals('Submit', $tag->getValue());
$this->assertEquals('Submit', $tag->getLabel());
$encoding = new MockSimpleMultipartEncoding();
$encoding->expectNever('add');
$tag->write($encoding);
}
function testPopulatedSubmit() {
$tag = new SimpleSubmitTag(
array('type' => 'submit', 'name' => 's', 'value' => 'Ok!'));
$this->assertEquals('s', $tag->getName());
$this->assertEquals('Ok!', $tag->getValue());
$this->assertEquals('Ok!', $tag->getLabel());
$encoding = new MockSimpleMultipartEncoding();
$encoding->expectOnce('add', array('s', 'Ok!'));
$tag->write($encoding);
}
function testImageSubmit() {
$tag = new SimpleImageSubmitTag(
array('type' => 'image', 'name' => 's', 'alt' => 'Label'));
$this->assertEquals('s', $tag->getName());
$this->assertEquals('Label', $tag->getLabel());
$encoding = new MockSimpleMultipartEncoding();
$encoding->expectAt(0, 'add', array('s.x', 20));
$encoding->expectAt(1, 'add', array('s.y', 30));
$tag->write($encoding, 20, 30);
}
function testImageSubmitTitlePreferredOverAltForLabel() {
$tag = new SimpleImageSubmitTag(
array('type' => 'image', 'name' => 's', 'alt' => 'Label', 'title' => 'Title'));
$this->assertEquals('Title', $tag->getLabel());
}
function testButton() {
$tag = new SimpleButtonTag(
array('type' => 'submit', 'name' => 's', 'value' => 'do'));
$tag->addContent('I am a button');
$this->assertEquals('s', $tag->getName());
$this->assertEquals('do', $tag->getValue());
$this->assertEquals('I am a button', $tag->getLabel());
$encoding = new MockSimpleMultipartEncoding();
$encoding->expectOnce('add', array('s', 'do'));
$tag->write($encoding);
}
}
class TestOfTextArea extends UnitTestCase {
function testDefault() {
$tag = new SimpleTextAreaTag(array('name' => 'a'));
$tag->addContent('Some text');
$this->assertEquals('a', $tag->getName());
$this->assertEquals('Some text', $tag->getDefault());
}
function testWrapping() {
$tag = new SimpleTextAreaTag(array('cols' => '10', 'wrap' => 'physical'));
$tag->addContent("Lot's of text that should be wrapped");
$this->assertEqual(
$tag->getDefault(),
"Lot's of\r\ntext that\r\nshould be\r\nwrapped");
$tag->setValue("New long text\r\nwith two lines");
$this->assertEqual(
$tag->getValue(),
"New long\r\ntext\r\nwith two\r\nlines");
}
function testWrappingRemovesLeadingcariageReturn() {
$tag = new SimpleTextAreaTag(array('cols' => '20', 'wrap' => 'physical'));
$tag->addContent("\rStuff");
$this->assertEquals('Stuff', $tag->getDefault());
$tag->setValue("\nNew stuff\n");
$this->assertEquals("New stuff\r\n", $tag->getValue());
}
function testBreaksAreNewlineAndCarriageReturn() {
$tag = new SimpleTextAreaTag(array('cols' => '10'));
$tag->addContent("Some\nText\rwith\r\nbreaks");
$this->assertEquals("Some\r\nText\r\nwith\r\nbreaks", $tag->getValue());
}
}
class TestOfCheckbox extends UnitTestCase {
function testCanSetCheckboxToNamedValueWithBooleanTrue() {
$tag = new SimpleCheckboxTag(array('name' => 'a', 'value' => 'A'));
$this->assertFalse($tag->getValue());
$tag->setValue(true);
$this->assertIdentical($tag->getValue(), 'A');
}
}
class TestOfSelection extends UnitTestCase {
function testEmpty() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$this->assertIdentical($tag->getValue(), '');
}
function testSingle() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$option = new SimpleOptionTag(array());
$option->addContent('AAA');
$tag->addTag($option);
$this->assertEquals('AAA', $tag->getValue());
}
function testSingleDefault() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$option = new SimpleOptionTag(array('selected' => ''));
$option->addContent('AAA');
$tag->addTag($option);
$this->assertEquals('AAA', $tag->getValue());
}
function testSingleMappedDefault() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$option = new SimpleOptionTag(array('selected' => '', 'value' => 'aaa'));
$option->addContent('AAA');
$tag->addTag($option);
$this->assertEquals('aaa', $tag->getValue());
}
function testStartsWithDefault() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$a = new SimpleOptionTag(array());
$a->addContent('AAA');
$tag->addTag($a);
$b = new SimpleOptionTag(array('selected' => ''));
$b->addContent('BBB');
$tag->addTag($b);
$c = new SimpleOptionTag(array());
$c->addContent('CCC');
$tag->addTag($c);
$this->assertEquals('BBB', $tag->getValue());
}
function testSettingOption() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$a = new SimpleOptionTag(array());
$a->addContent('AAA');
$tag->addTag($a);
$b = new SimpleOptionTag(array('selected' => ''));
$b->addContent('BBB');
$tag->addTag($b);
$c = new SimpleOptionTag(array());
$c->addContent('CCC');
$tag->setValue('AAA');
$this->assertEquals('AAA', $tag->getValue());
}
function testSettingMappedOption() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$a = new SimpleOptionTag(array('value' => 'aaa'));
$a->addContent('AAA');
$tag->addTag($a);
$b = new SimpleOptionTag(array('value' => 'bbb', 'selected' => ''));
$b->addContent('BBB');
$tag->addTag($b);
$c = new SimpleOptionTag(array('value' => 'ccc'));
$c->addContent('CCC');
$tag->addTag($c);
$tag->setValue('AAA');
$this->assertEquals('aaa', $tag->getValue());
$tag->setValue('ccc');
$this->assertEquals('ccc', $tag->getValue());
}
function testSelectionDespiteSpuriousWhitespace() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$a = new SimpleOptionTag(array());
$a->addContent(' AAA ');
$tag->addTag($a);
$b = new SimpleOptionTag(array('selected' => ''));
$b->addContent(' BBB ');
$tag->addTag($b);
$c = new SimpleOptionTag(array());
$c->addContent(' CCC ');
$tag->addTag($c);
$this->assertEquals(' BBB ', $tag->getValue());
$tag->setValue('AAA');
$this->assertEquals(' AAA ', $tag->getValue());
}
function testFailToSetIllegalOption() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$a = new SimpleOptionTag(array());
$a->addContent('AAA');
$tag->addTag($a);
$b = new SimpleOptionTag(array('selected' => ''));
$b->addContent('BBB');
$tag->addTag($b);
$c = new SimpleOptionTag(array());
$c->addContent('CCC');
$tag->addTag($c);
$this->assertFalse($tag->setValue('Not present'));
$this->assertEquals('BBB', $tag->getValue());
}
function testNastyOptionValuesThatLookLikeFalse() {
$tag = new SimpleSelectionTag(array('name' => 'a'));
$a = new SimpleOptionTag(array('value' => '1'));
$a->addContent('One');
$tag->addTag($a);
$b = new SimpleOptionTag(array('value' => '0'));
$b->addContent('Zero');
$tag->addTag($b);
$this->assertIdentical($tag->getValue(), '1');
$tag->setValue('Zero');
$this->assertIdentical($tag->getValue(), '0');
}
function testBlankOption() {
$tag = new SimpleSelectionTag(array('name' => 'A'));
$a = new SimpleOptionTag(array());
$tag->addTag($a);
$b = new SimpleOptionTag(array());
$b->addContent('b');
$tag->addTag($b);
$this->assertIdentical($tag->getValue(), '');
$tag->setValue('b');
$this->assertIdentical($tag->getValue(), 'b');
$tag->setValue('');
$this->assertIdentical($tag->getValue(), '');
}
function testMultipleDefaultWithNoSelections() {
$tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => ''));
$a = new SimpleOptionTag(array());
$a->addContent('AAA');
$tag->addTag($a);
$b = new SimpleOptionTag(array());
$b->addContent('BBB');
$tag->addTag($b);
$this->assertIdentical($tag->getDefault(), array());
$this->assertIdentical($tag->getValue(), array());
}
function testMultipleDefaultWithSelections() {
$tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => ''));
$a = new SimpleOptionTag(array('selected' => ''));
$a->addContent('AAA');
$tag->addTag($a);
$b = new SimpleOptionTag(array('selected' => ''));
$b->addContent('BBB');
$tag->addTag($b);
$this->assertIdentical($tag->getDefault(), array('AAA', 'BBB'));
$this->assertIdentical($tag->getValue(), array('AAA', 'BBB'));
}
function testSettingMultiple() {
$tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => ''));
$a = new SimpleOptionTag(array('selected' => ''));
$a->addContent('AAA');
$tag->addTag($a);
$b = new SimpleOptionTag(array());
$b->addContent('BBB');
$tag->addTag($b);
$c = new SimpleOptionTag(array('selected' => '', 'value' => 'ccc'));
$c->addContent('CCC');
$tag->addTag($c);
$this->assertIdentical($tag->getDefault(), array('AAA', 'ccc'));
$this->assertTrue($tag->setValue(array('BBB', 'ccc')));
$this->assertIdentical($tag->getValue(), array('BBB', 'ccc'));
$this->assertTrue($tag->setValue(array()));
$this->assertIdentical($tag->getValue(), array());
}
function testFailToSetIllegalOptionsInMultiple() {
$tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => ''));
$a = new SimpleOptionTag(array('selected' => ''));
$a->addContent('AAA');
$tag->addTag($a);
$b = new SimpleOptionTag(array());
$b->addContent('BBB');
$tag->addTag($b);
$this->assertFalse($tag->setValue(array('CCC')));
$this->assertTrue($tag->setValue(array('AAA', 'BBB')));
$this->assertFalse($tag->setValue(array('AAA', 'CCC')));
}
}
class TestOfRadioGroup extends UnitTestCase {
function testEmptyGroup() {
$group = new SimpleRadioGroup();
$this->assertIdentical($group->getDefault(), false);
$this->assertIdentical($group->getValue(), false);
$this->assertFalse($group->setValue('a'));
}
function testReadingSingleButtonGroup() {
$group = new SimpleRadioGroup();
$group->addWidget(new SimpleRadioButtonTag(
array('value' => 'A', 'checked' => '')));
$this->assertIdentical($group->getDefault(), 'A');
$this->assertIdentical($group->getValue(), 'A');
}
function testReadingMultipleButtonGroup() {
$group = new SimpleRadioGroup();
$group->addWidget(new SimpleRadioButtonTag(
array('value' => 'A')));
$group->addWidget(new SimpleRadioButtonTag(
array('value' => 'B', 'checked' => '')));
$this->assertIdentical($group->getDefault(), 'B');
$this->assertIdentical($group->getValue(), 'B');
}
function testFailToSetUnlistedValue() {
$group = new SimpleRadioGroup();
$group->addWidget(new SimpleRadioButtonTag(array('value' => 'z')));
$this->assertFalse($group->setValue('a'));
$this->assertIdentical($group->getValue(), false);
}
function testSettingNewValueClearsTheOldOne() {
$group = new SimpleRadioGroup();
$group->addWidget(new SimpleRadioButtonTag(
array('value' => 'A')));
$group->addWidget(new SimpleRadioButtonTag(
array('value' => 'B', 'checked' => '')));
$this->assertTrue($group->setValue('A'));
$this->assertIdentical($group->getValue(), 'A');
}
function testIsIdMatchesAnyWidgetInSet() {
$group = new SimpleRadioGroup();
$group->addWidget(new SimpleRadioButtonTag(
array('value' => 'A', 'id' => 'i1')));
$group->addWidget(new SimpleRadioButtonTag(
array('value' => 'B', 'id' => 'i2')));
$this->assertFalse($group->isId('i0'));
$this->assertTrue($group->isId('i1'));
$this->assertTrue($group->isId('i2'));
}
function testIsLabelMatchesAnyWidgetInSet() {
$group = new SimpleRadioGroup();
$button1 = new SimpleRadioButtonTag(array('value' => 'A'));
$button1->setLabel('one');
$group->addWidget($button1);
$button2 = new SimpleRadioButtonTag(array('value' => 'B'));
$button2->setLabel('two');
$group->addWidget($button2);
$this->assertFalse($group->isLabel('three'));
$this->assertTrue($group->isLabel('one'));
$this->assertTrue($group->isLabel('two'));
}
}
class TestOfTagGroup extends UnitTestCase {
function testReadingMultipleCheckboxGroup() {
$group = new SimpleCheckboxGroup();
$group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
$group->addWidget(new SimpleCheckboxTag(
array('value' => 'B', 'checked' => '')));
$this->assertIdentical($group->getDefault(), 'B');
$this->assertIdentical($group->getValue(), 'B');
}
function testReadingMultipleUncheckedItems() {
$group = new SimpleCheckboxGroup();
$group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
$group->addWidget(new SimpleCheckboxTag(array('value' => 'B')));
$this->assertIdentical($group->getDefault(), false);
$this->assertIdentical($group->getValue(), false);
}
function testReadingMultipleCheckedItems() {
$group = new SimpleCheckboxGroup();
$group->addWidget(new SimpleCheckboxTag(
array('value' => 'A', 'checked' => '')));
$group->addWidget(new SimpleCheckboxTag(
array('value' => 'B', 'checked' => '')));
$this->assertIdentical($group->getDefault(), array('A', 'B'));
$this->assertIdentical($group->getValue(), array('A', 'B'));
}
function testSettingSingleValue() {
$group = new SimpleCheckboxGroup();
$group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
$group->addWidget(new SimpleCheckboxTag(array('value' => 'B')));
$this->assertTrue($group->setValue('A'));
$this->assertIdentical($group->getValue(), 'A');
$this->assertTrue($group->setValue('B'));
$this->assertIdentical($group->getValue(), 'B');
}
function testSettingMultipleValues() {
$group = new SimpleCheckboxGroup();
$group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
$group->addWidget(new SimpleCheckboxTag(array('value' => 'B')));
$this->assertTrue($group->setValue(array('A', 'B')));
$this->assertIdentical($group->getValue(), array('A', 'B'));
}
function testSettingNoValue() {
$group = new SimpleCheckboxGroup();
$group->addWidget(new SimpleCheckboxTag(array('value' => 'A')));
$group->addWidget(new SimpleCheckboxTag(array('value' => 'B')));
$this->assertTrue($group->setValue(false));
$this->assertIdentical($group->getValue(), false);
}
function testIsIdMatchesAnyIdInSet() {
$group = new SimpleCheckboxGroup();
$group->addWidget(new SimpleCheckboxTag(array('id' => 1, 'value' => 'A')));
$group->addWidget(new SimpleCheckboxTag(array('id' => 2, 'value' => 'B')));
$this->assertFalse($group->isId(0));
$this->assertTrue($group->isId(1));
$this->assertTrue($group->isId(2));
}
}
class TestOfUploadWidget extends UnitTestCase {
function testValueIsFilePath() {
$upload = new SimpleUploadTag(array('name' => 'a'));
$upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt');
$this->assertEquals(dirname(__FILE__) . '/support/upload_sample.txt', $upload->getValue());
}
function testSubmitsFileContents() {
$encoding = new MockSimpleMultipartEncoding();
$encoding->expectOnce('attach', array(
'a',
'Sample for testing file upload',
'upload_sample.txt'));
$upload = new SimpleUploadTag(array('name' => 'a'));
$upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt');
$upload->write($encoding);
}
}
class TestOfLabelTag extends UnitTestCase {
function testLabelShouldHaveAnEndTag() {
$label = new SimpleLabelTag(array());
$this->assertTrue($label->expectEndTag());
}
function testContentIsTextOnly() {
$label = new SimpleLabelTag(array());
$label->addContent('Here <tag>are</tag> words');
$this->assertEquals('Here are words', $label->getText());
}
}
?> | lgpl-3.0 |
medialab/frontcast | observer/forms.py | 173 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django import forms
from observer.models import Device
class DeviceForm(forms.ModelForm):
class Meta:
model = Device | lgpl-3.0 |
lffg/lffg.github.io | src/components/locale-changer.tsx | 1025 | import { Link } from 'gatsby';
import React from 'react';
import { locales, Locale, createLocalizedPath } from '../../resources/i18n';
import { useLocale } from '../context/locale';
interface Props {
className?: string;
}
export function LocaleChanger({ className }: Props) {
const { currentLocale } = useLocale();
return (
<div className={className || ''}>
{locales
.filter((locale) => locale !== currentLocale)
.map((locale) => (
<Link
key={locale}
to={createLocalizedPath({
base: '/',
locale
})}
>
{getMessage(locale)}
</Link>
))}
</div>
);
}
function getMessage(locale: Locale) {
if (locale === 'pt') {
return 'Mudar para o site em português';
}
if (locale === 'en') {
return 'Switch to English site';
}
// This will ensure all locales are handled above.
const ensureAllLocalesAreHandled: never = locale;
void ensureAllLocalesAreHandled;
}
| lgpl-3.0 |
TheAnswer/FirstTest | bin/scripts/skills/creatureSkills/corellia/creatures/tabageAttacks.lua | 3125 | tabageAttack1 = {
attackname = "tabageAttack1",
animation = "creature_attack_light",
requiredWeaponType = NONE,
range = 7,
damageRatio = 1.2,
speedRatio = 4,
arearange = 7,
accuracyBonus = 0,
knockdownChance = 0,
postureDownChance = 0,
postureUpChance = 0,
dizzyChance = 0,
blindChance = 0,
stunChance = 50,
intimidateChance = 0,
CbtSpamBlock = "attack_block",
CbtSpamCounter = "attack_counter",
CbtSpamEvade = "attack_evade",
CbtSpamHit = "attack_hit",
CbtSpamMiss = "attack_miss",
invalidStateMask = 0,
invalidPostures = "",
instant = 0
}
AddRandomPoolAttackTargetSkill(tabageAttack1)
---------------------------------------------------------------------------------------
tabageAttack2 = {
attackname = "tabageAttack2",
animation = "creature_attack_light",
requiredWeaponType = NONE,
range = 7,
damageRatio = 1.2,
speedRatio = 4,
arearange = 7,
accuracyBonus = 0,
knockdownChance = 0,
postureDownChance = 50,
postureUpChance = 0,
dizzyChance = 0,
blindChance = 0,
stunChance = 0,
intimidateChance = 0,
CbtSpamBlock = "attack_block",
CbtSpamCounter = "attack_counter",
CbtSpamEvade = "attack_evade",
CbtSpamHit = "attack_hit",
CbtSpamMiss = "attack_miss",
invalidStateMask = 0,
invalidPostures = "",
instant = 0
}
AddRandomPoolAttackTargetSkill(tabageAttack2)
---------------------------------------------------------------------------------------
tabageAttack3 = {
attackname = "tabageAttack3",
animation = "creature_attack_light",
requiredWeaponType = NONE,
range = 7,
damageRatio = 1.2,
speedRatio = 4,
arearange = 7,
accuracyBonus = 0,
healthAttackChance = 100,
actionAttackChance = 0,
mindAttackChance = 0,
dotChance = 50,
tickStrengthOfHit = 1,
fireStrength = 0,
fireType = 0,
bleedingStrength = 0,
bleedingType = 0,
poisonStrength = 100,
poisonType = HEALTH,
diseaseStrength = 0,
diseaseType = 0,
knockdownChance = 0,
postureDownChance = 0,
postureUpChance = 0,
dizzyChance = 0,
blindChance = 0,
stunChance = 0,
intimidateChance = 0,
CbtSpamBlock = "attack_block",
CbtSpamCounter = "attack_counter",
CbtSpamEvade = "attack_evade",
CbtSpamHit = "attack_hit",
CbtSpamMiss = "attack_miss",
invalidStateMask = 0,
invalidPostures = "",
instant = 0
}
AddDotPoolAttackTargetSkill(tabageAttack3)
--------------------------------------------------------------------------------------
| lgpl-3.0 |
vamsirajendra/sonarqube | server/sonar-server/src/main/java/org/sonar/server/computation/metric/MetricDtoToMetric.java | 1847 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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 program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.computation.metric;
import com.google.common.base.Function;
import javax.annotation.Nonnull;
import org.sonar.db.metric.MetricDto;
import org.sonar.server.computation.measure.Measure;
import static com.google.common.base.Objects.firstNonNull;
enum MetricDtoToMetric implements Function<MetricDto, Metric> {
INSTANCE;
private static final int DEFAULT_DECIMAL_SCALE = 1;
@Override
@Nonnull
public Metric apply(@Nonnull MetricDto metricDto) {
Metric.MetricType metricType = Metric.MetricType.valueOf(metricDto.getValueType());
Integer decimalScale = null;
if (metricType.getValueType() == Measure.ValueType.DOUBLE) {
decimalScale = firstNonNull(metricDto.getDecimalScale(), DEFAULT_DECIMAL_SCALE);
}
return new MetricImpl(
metricDto.getId(), metricDto.getKey(), metricDto.getShortName(), metricType,
decimalScale,
metricDto.getBestValue(), metricDto.isOptimizedBestValue());
}
}
| lgpl-3.0 |
ezcall-net-tw/EZCall | src/com/csipsimple/service/Downloader.java | 8874 | /**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;
import tw.net.ezcall.R;
import com.csipsimple.ui.SipHome;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.MD5;
public class Downloader extends IntentService {
private final static String THIS_FILE = "Downloader";
public final static String EXTRA_ICON = "icon";
public final static String EXTRA_TITLE = "title";
public final static String EXTRA_OUTPATH = "outpath";
public final static String EXTRA_CHECK_MD5 = "checkMd5";
public final static String EXTRA_PENDING_FINISH_INTENT = "pendingIntent";
private static final int NOTIF_DOWNLOAD = 0;
private NotificationManager notificationManager;
private DefaultHttpClient client;
public Downloader() {
super("Downloader");
}
@Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
client = new DefaultHttpClient();
}
@Override
public void onDestroy() {
super.onDestroy();
client.getConnectionManager().shutdown();
}
@Override
protected void onHandleIntent(Intent intent) {
HttpGet getMethod = new HttpGet(intent.getData().toString());
int result = Activity.RESULT_CANCELED;
String outPath = intent.getStringExtra(EXTRA_OUTPATH);
boolean checkMd5 = intent.getBooleanExtra(EXTRA_CHECK_MD5, false);
int icon = intent.getIntExtra(EXTRA_ICON, 0);
String title = intent.getStringExtra(EXTRA_TITLE);
boolean showNotif = (icon > 0 && !TextUtils.isEmpty(title));
// Build notification
Builder nb = new NotificationCompat.Builder(this);
nb.setWhen(System.currentTimeMillis());
nb.setContentTitle(title);
nb.setSmallIcon(android.R.drawable.stat_sys_download);
nb.setOngoing(true);
Intent i = new Intent(this, SipHome.class);
nb.setContentIntent(PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT));
RemoteViews contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_notif);
contentView.setImageViewResource(R.id.status_icon, icon);
contentView.setTextViewText(R.id.status_text, getResources().getString(R.string.downloading_text));
contentView.setProgressBar(R.id.status_progress, 50, 0, false);
contentView.setViewVisibility(R.id.status_progress_wrapper, View.VISIBLE);
nb.setContent(contentView);
final Notification notification = showNotif ? nb.build() : null;
notification.contentView = contentView;
if(!TextUtils.isEmpty(outPath)) {
try {
File output = new File(outPath);
if (output.exists()) {
output.delete();
}
if(notification != null) {
notificationManager.notify(NOTIF_DOWNLOAD, notification);
}
ResponseHandler<Boolean> responseHandler = new FileStreamResponseHandler(output, new Progress() {
private int oldState = 0;
@Override
public void run(long progress, long total) {
//Log.d(THIS_FILE, "Progress is "+progress+" on "+total);
int newState = (int) Math.round(progress * 50.0f/total);
if(oldState != newState) {
notification.contentView.setProgressBar(R.id.status_progress, 50, newState, false);
notificationManager.notify(NOTIF_DOWNLOAD, notification);
oldState = newState;
}
}
});
boolean hasReply = client.execute(getMethod, responseHandler);
if(hasReply) {
if(checkMd5) {
URL url = new URL(intent.getData().toString().concat(".md5sum"));
InputStream content = (InputStream) url.getContent();
if(content != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(content));
String downloadedMD5 = "";
try {
downloadedMD5 = br.readLine().split(" ")[0];
} catch (NullPointerException e) {
throw new IOException("md5_verification : no sum on server");
}
if (!MD5.checkMD5(downloadedMD5, output)) {
throw new IOException("md5_verification : incorrect");
}
}
}
PendingIntent pendingIntent = (PendingIntent) intent.getParcelableExtra(EXTRA_PENDING_FINISH_INTENT);
try {
Runtime.getRuntime().exec("chmod 644 " + outPath);
} catch (IOException e) {
Log.e(THIS_FILE, "Unable to make the apk file readable", e);
}
Log.d(THIS_FILE, "Download finished of : " + outPath);
if(pendingIntent != null) {
notification.contentIntent = pendingIntent;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = android.R.drawable.stat_sys_download_done;
notification.contentView.setViewVisibility(R.id.status_progress_wrapper, View.GONE);
notification.contentView.setTextViewText(R.id.status_text,
getResources().getString(R.string.done)
// TODO should be a parameter of this class
+" - Click to install");
notificationManager.notify(NOTIF_DOWNLOAD, notification);
/*
try {
pendingIntent.send();
notificationManager.cancel(NOTIF_DOWNLOAD);
} catch (CanceledException e) {
Log.e(THIS_FILE, "Impossible to start pending intent for download finish");
}
*/
}else {
Log.w(THIS_FILE, "Invalid pending intent for finish !!!");
}
result = Activity.RESULT_OK;
}
} catch (IOException e) {
Log.e(THIS_FILE, "Exception in download", e);
}
}
if(result == Activity.RESULT_CANCELED) {
notificationManager.cancel(NOTIF_DOWNLOAD);
}
}
public interface Progress {
void run(long progress, long total);
}
private class FileStreamResponseHandler implements ResponseHandler<Boolean> {
private Progress mProgress;
private File mFile;
FileStreamResponseHandler(File outputFile, Progress progress) {
mFile = outputFile;
mProgress = progress;
}
public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
FileOutputStream fos = new FileOutputStream(mFile.getPath());
HttpEntity entity = response.getEntity();
boolean done = false;
try {
if (entity != null) {
Long length = entity.getContentLength();
InputStream input = entity.getContent();
byte[] buffer = new byte[4096];
int size = 0;
int total = 0;
while (true) {
size = input.read(buffer);
if (size == -1) break;
fos.write(buffer, 0, size);
total += size;
mProgress.run(total, length);
}
done = true;
}
}catch(IOException e) {
Log.e(THIS_FILE, "Problem on downloading");
}finally {
fos.close();
}
return done;
}
}
}
| lgpl-3.0 |
oscarlab/graphene | Examples/python/scripts/test-numpy.py | 387 | #!/usr/bin/env python3
import timeit
import numpy
try:
import numpy.core._dotblas
except ImportError:
pass
print("numpy version: " + numpy.__version__)
x = numpy.random.random((1000, 1000))
setup = "import numpy; x = numpy.random.random((1000, 1000))"
count = 5
t = timeit.Timer("numpy.dot(x, x.T)", setup=setup)
print("numpy.dot: " + str(t.timeit(count)/count) + " sec")
| lgpl-3.0 |
MerlinYoung/boost_protobuf_server | client/server.py | 257 | #!/usr/bin/env python
import t_pb2
import protobuf.socketrpc.server
#class t_service_imp(t_pb2.t_service):
# a
if __name__ == '__main__':
server = protobuf.socketrpc.server.SocketRpcServer(10081)
server.registerService(t_pb2.t_service())
server.run()
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-db-dao/src/testFixtures/java/org/sonar/db/plugin/PluginTesting.java | 1490 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db.plugin;
import org.sonar.core.util.Uuids;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
public class PluginTesting {
private PluginTesting() {
// prevent instantiation
}
/**
* Create an instance of {@link PluginDto} with random field values.
*/
public static PluginDto newPluginDto() {
String uuid = Uuids.createFast();
return new PluginDto()
.setUuid(uuid)
.setKee(uuid)
.setFileHash(randomAlphanumeric(32))
.setCreatedAt(nextLong())
.setUpdatedAt(nextLong());
}
}
| lgpl-3.0 |
LabDin/RobotSystem-Lite | docs/dir_68267d1309a1af8e8297ef4c3efbcdba.js | 605 | var dir_68267d1309a1af8e8297ef4c3efbcdba =
[
[ "actuator.h", "actuator_8h.html", "actuator_8h" ],
[ "config_keys.h", "config__keys_8h_source.html", null ],
[ "input.h", "input_8h.html", "input_8h" ],
[ "motor.h", "motor_8h.html", "motor_8h" ],
[ "robot.h", "robot_8h.html", "robot_8h" ],
[ "sensor.h", "sensor_8h.html", "sensor_8h" ],
[ "shared_dof_variables.h", "shared__dof__variables_8h.html", "shared__dof__variables_8h" ],
[ "shared_robot_control.h", "shared__robot__control_8h.html", "shared__robot__control_8h" ],
[ "system.h", "system_8h.html", "system_8h" ]
]; | lgpl-3.0 |
loftuxab/community-edition-old | projects/repository/source/java/org/alfresco/repo/action/executer/RemoveFeaturesActionExecuter.java | 2649 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.action.executer;
import java.util.List;
import org.alfresco.repo.action.ParameterDefinitionImpl;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.QName;
/**
* Remove features action executor implementation.
*
* @author Roy Wetherall
*/
public class RemoveFeaturesActionExecuter extends ActionExecuterAbstractBase
{
/**
* Action constants
*/
public static final String NAME = "remove-features";
public static final String PARAM_ASPECT_NAME = "aspect-name";
/**
* The node service
*/
private NodeService nodeService;
/**
* Set the node service
*
* @param nodeService the node service
*/
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
/**
* @see org.alfresco.repo.action.executer.ActionExecuter#execute(org.alfresco.service.cmr.repository.NodeRef, NodeRef)
*/
public void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef)
{
if (this.nodeService.exists(actionedUponNodeRef) == true)
{
// Remove the aspect
QName aspectQName = (QName)ruleAction.getParameterValue(PARAM_ASPECT_NAME);
this.nodeService.removeAspect(actionedUponNodeRef, aspectQName);
}
}
/**
* @see org.alfresco.repo.action.ParameterizedItemAbstractBase#addParameterDefinitions(java.util.List)
*/
@Override
protected void addParameterDefinitions(List<ParameterDefinition> paramList)
{
paramList.add(new ParameterDefinitionImpl(PARAM_ASPECT_NAME, DataTypeDefinition.QNAME, true, getParamDisplayLabel(PARAM_ASPECT_NAME), false, "ac-aspects"));
}
}
| lgpl-3.0 |
djvanenckevort/molgenis | molgenis-data-index/src/main/java/org/molgenis/data/index/IndexDependencyModel.java | 3948 | package org.molgenis.data.index;
import com.google.common.collect.ImmutableSet;
import org.molgenis.data.Fetch;
import org.molgenis.data.meta.model.Attribute;
import org.molgenis.data.meta.model.EntityType;
import org.molgenis.util.GenericDependencyResolver;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Stream;
import static com.google.common.collect.Maps.uniqueIndex;
import static java.util.Collections.emptySet;
import static java.util.stream.StreamSupport.stream;
import static org.molgenis.data.meta.model.AttributeMetadata.REF_ENTITY_TYPE;
import static org.molgenis.data.meta.model.EntityTypeMetadata.*;
/**
* Models the dependencies between {@link EntityType}s for the purpose of indexing.
* These dependencies depend on the indexing depth of the entity types.
*/
class IndexDependencyModel
{
private final Map<String, EntityType> entityTypes;
private final GenericDependencyResolver genericDependencyResolver = new GenericDependencyResolver();
/**
* The fetch to use when retrieving the {@link EntityType}s fed to this DependencyModel.
*/
static final Fetch ENTITY_TYPE_FETCH = new Fetch().field(ID)
.field(IS_ABSTRACT)
.field(INDEXING_DEPTH)
.field(EXTENDS, new Fetch().field(ID))
.field(ATTRIBUTES, new Fetch().field(REF_ENTITY_TYPE,
new Fetch().field(ID)));
/**
* Creates an IndexDependencyModel for a list of EntityTypes.
*
* @param entityTypes the EntityTypes for which the DependencyModel is created
*/
IndexDependencyModel(List<EntityType> entityTypes)
{
this.entityTypes = uniqueIndex(entityTypes, EntityType::getId);
}
private Set<String> getReferencingEntities(String entityTypeId)
{
ImmutableSet.Builder<String> result = ImmutableSet.builder();
EntityType entityType = entityTypes.get(entityTypeId);
if (entityType == null)
{
return emptySet();
}
for (Map.Entry<String, EntityType> candidate : entityTypes.entrySet())
{
EntityType candidateEntityType = candidate.getValue();
if (hasAttributeThatReferences(candidateEntityType, entityTypeId))
{
if (candidateEntityType.isAbstract())
{
result.addAll(getDescendants(candidate.getKey()));
}
else
{
result.add(candidate.getKey());
}
}
}
return result.build();
}
private Set<String> getDescendants(String entityTypeId)
{
ImmutableSet.Builder<String> result = ImmutableSet.builder();
for (Map.Entry<String, EntityType> candidate : entityTypes.entrySet())
{
EntityType candidateEntityType = candidate.getValue();
if (extendsFrom(candidateEntityType, entityTypeId))
{
if (candidateEntityType.isAbstract())
{
result.addAll(getDescendants(candidate.getKey()));
}
else
{
result.add(candidate.getKey());
}
}
}
return result.build();
}
private boolean extendsFrom(EntityType candidateEntityType, String entityTypeId)
{
return candidateEntityType.getExtends() != null && entityTypeId.equals(
candidateEntityType.getExtends().getId());
}
/**
* Determines if an entityType has an attribute that references another entity
*
* @param candidate the EntityType that is examined
* @param entityTypeId the ID of the entity that may be referenced
* @return indication if candidate references entityTypeID
*/
private boolean hasAttributeThatReferences(EntityType candidate, String entityTypeId)
{
Iterable<Attribute> attributes = candidate.getOwnAtomicAttributes();
return stream(attributes.spliterator(), false).map(Attribute::getRefEntity).filter(Objects::nonNull).
map(EntityType::getId).anyMatch(entityTypeId::equals);
}
Stream<String> getEntityTypesDependentOn(String entityTypeId)
{
return genericDependencyResolver.getAllDependants(entityTypeId, id -> entityTypes.get(id).getIndexingDepth(),
this::getReferencingEntities).stream();
}
}
| lgpl-3.0 |
ricardogarcia/responsive-webapp | AudienceTool/.meteor/.famono-base/lib/famous/modifiers/Gruntfile.js | 820 | Famono.scope('famous/modifiers/Gruntfile', ["load-grunt-tasks","time-grunt"], function(require, define) {
define(function() {
/*global module:false*/
/*Generated initially from grunt-init, heavily inspired by yo webapp*/
module.exports = function(grunt) {
'use strict';
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Project configuration.
grunt.initConfig({
eslint: {
options: {
config: '.eslintrc'
},
target: ['*.js']
},
jscs: {
src: ['*.js'],
options: {
config: '.jscsrc'
}
}
});
grunt.registerTask('test', [
'jscs',
'eslint'
]);
grunt.registerTask('default', [
'test'
]);
};
});
}); | lgpl-3.0 |
Ohrm/Malgra | src/main/java/ohrm/malgra/api/network/IMalgraLinkable.java | 178 | package ohrm.malgra.api.network;
public interface IMalgraLinkable {
void onLinkedSource(IMalgraLinkable linkedTo);
void onLinkedDestination(IMalgraLinkable linkedTo);
}
| lgpl-3.0 |
dunamis1974/puzzleapps | core/modules/gsitemap/drivers/generator.inc.php | 1413 | <?php
function gsitemap_generate () {
global
$SYS_LANGUAGES,
$_TEXTID,
$EDITLANGUAGE,
$LANGUAGES,
$COREROOT,
$CURRENTPLATFORM,
$MOD_GSITEMAP,
$_dtd_types;
$XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
$type = ($MOD_GSITEMAP["odd"])?$MOD_GSITEMAP["odd"]:"category";
$products = $CURRENTPLATFORM->getAllOfType($type);
foreach ($products AS $key => $product) {
$data_ = $product->translate_object_data();
$lngcnt = count($LANGUAGES);
foreach ($LANGUAGES AS $lang) {
$skip = false;
$url = "http://{$_SERVER["HTTP_HOST"]}/";
if ($MOD_GSITEMAP["seo"] == 1 && $data_["tid"]) {
if ($lngcnt > 1)
$url .= "{$lang}/";
$url .= "{$data_["tid"]}.html";
} else if (!$MOD_GSITEMAP["seo"]) {
$url .= "index.php?id={$product->id}";
if ($lngcnt > 1)
$url .= "&lang={$lang}";
} else {
$skip = true;
}
if (!$skip) {
$time = date("r", $product->_date);
$XML .= "\t<url>\n\t\t<loc>{$url}</loc>\n\t\t<lastmod>{$time}</lastmod>\n\t</url>\n";
}
}
}
$XML .= "</urlset>\n";
return $XML;
}
?> | lgpl-3.0 |
cismet/cismap-plugin | src/main/java/de/cismet/cismap/navigatorplugin/protocol/GeoContextProtocolStep.java | 391 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cismap.navigatorplugin.protocol;
/**
* DOCUMENT ME!
*
* @author jruiz
* @version $Revision$, $Date$
*/
public interface GeoContextProtocolStep extends GeometryProtocolStep {
}
| lgpl-3.0 |
GeirGrusom/WebShard | WebShard/Serialization/Json/TypeHelper.cs | 1127 | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace WebShard.Serialization.Json
{
static class TypeHelper
{
public static DeserializeElement<T> CreateDeserializeProc<T>()
{
var deType = JsonDeserializer.GetDeserializer<T>();
var method = deType.GetMethod("Deserialize", BindingFlags.Public | BindingFlags.Static, null,
new[] {typeof (IEnumerator<Token>).MakeByRefType()}, null);
var input = Expression.Parameter(typeof (IEnumerator<Token>).MakeByRefType());
var l = Expression.Lambda<DeserializeElement<T>>(
Expression.Call(null, method, input), input
);
return l.Compile();
}
public static bool ImplementsInterface<TInterface>(this Type type)
{
return type.GetInterface(typeof(TInterface).Name) != null;
}
public static bool ImplementsInterface(this Type type, Type interfaceType)
{
return type.GetInterface(interfaceType.Name) != null;
}
}
} | lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/types/descriptors/DeliveryMethodTypeDescriptor.java | 3442 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: DeliveryMethodTypeDescriptor.java,v 1.1.1.1 2010-05-04 22:06:02 ryan Exp $
*/
package org.chocolate_milk.model.types.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.types.DeliveryMethodType;
/**
* Class DeliveryMethodTypeDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:02 $
*/
public class DeliveryMethodTypeDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public DeliveryMethodTypeDescriptor() {
super();
_xmlName = "DeliveryMethodType";
_elementDefinition = false;
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.types.DeliveryMethodType.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| lgpl-3.0 |
osjimenez/fuxion | trash/Ordinem/Shell/Xamarin/Forms.Android/MainActivity.cs | 1386 | using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace Ordinem.Shell.Xamarin.Forms.Droid
{
[Activity(Label = "Ordinem.Shell.Xamarin.Forms", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");
global::Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
global::Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
} | lgpl-3.0 |
blackeye42/ChargeBeeDataSync | src/main/scala/core/OptionConf.scala | 1434 | /*
* ________ ____
* / ____/ /_ ____ __________ ____ / __ )___ ___
* / / / __ \/ __ `/ ___/ __ `/ _ \/ __ / _ \/ _ \
* / /___/ / / / /_/ / / / /_/ / __/ /_/ / __/ __/
* \____/_/ /_/\__,_/_/ \__, /\___/_____/\___/\___/
* /____/
*
* __ __
* ___/ /__ _/ /____ _ ___ __ _____ ____
* / _ / _ `/ __/ _ `/ (_-</ // / _ \/ __/
* \_,_/\_,_/\__/\_,_/ /___/\_, /_//_/\__/
* /___/
*
* Copyright (c) Alexandros Mavrommatis.
*
* This file is part of ChargeBeeDataSync.
*
* ChargeBeeDataSync 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.
*
* ChargeBeeDataSync 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 ChargeBeeDataSync. If not, see <http://www.gnu.org/licenses/>.
*/
package core
case class OptionConf(site: String = "", key: String = "", uri: String = "mongodb://localhost:27017",
db: String = "chargeBee")
| lgpl-3.0 |
jkettleb/iris | lib/iris/tests/unit/analysis/maths/__init__.py | 6519 | # (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris 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.
#
# Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>.
"""Unit tests for the :mod:`iris.analysis.maths` module."""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
from abc import ABCMeta, abstractproperty
import numpy as np
from iris.analysis import MEAN
from iris.cube import Cube
import iris.tests.stock as stock
class CubeArithmeticBroadcastingTestMixin(object):
# A framework for testing the broadcasting behaviour of the various cube
# arithmetic operations. (A test for each operation inherits this).
__metaclass__ = ABCMeta
@abstractproperty
def data_op(self):
# Define an operator to be called, I.E. 'operator.xx'.
pass
@abstractproperty
def cube_func(self):
# Define an iris arithmetic function to be called
# I.E. 'iris.analysis.maths.xx'.
pass
def test_transposed(self):
cube = stock.realistic_4d_no_derived()
other = cube.copy()
other.transpose()
res = self.cube_func(cube, other)
self.assertCML(res, checksum=False)
expected_data = self.data_op(cube.data, other.data.T)
self.assertArrayEqual(res.data, expected_data)
def test_collapse_zeroth_dim(self):
cube = stock.realistic_4d_no_derived()
other = cube.collapsed('time', MEAN)
res = self.cube_func(cube, other)
self.assertCML(res, checksum=False)
# No modification to other.data is needed as numpy broadcasting
# should be sufficient.
expected_data = self.data_op(cube.data, other.data)
# Use assertMaskedArrayEqual as collapsing with MEAN results
# in a cube with a masked data array.
self.assertMaskedArrayEqual(res.data, expected_data)
def test_collapse_all_dims(self):
cube = stock.realistic_4d_no_derived()
other = cube.collapsed(cube.coords(dim_coords=True), MEAN)
res = self.cube_func(cube, other)
self.assertCML(res, checksum=False)
# No modification to other.data is needed as numpy broadcasting
# should be sufficient.
expected_data = self.data_op(cube.data, other.data)
# Use assertArrayEqual rather than assertMaskedArrayEqual as
# collapsing all dims does not result in a masked array.
self.assertArrayEqual(res.data, expected_data)
def test_collapse_last_dims(self):
cube = stock.realistic_4d_no_derived()
other = cube.collapsed(['grid_latitude', 'grid_longitude'], MEAN)
res = self.cube_func(cube, other)
self.assertCML(res, checksum=False)
# Transpose the dimensions in self.cube that have been collapsed in
# other to lie at the front, thereby enabling numpy broadcasting to
# function when applying data operator. Finish by transposing back
# again to restore order.
expected_data = self.data_op(cube.data.transpose((2, 3, 0, 1)),
other.data).transpose(2, 3, 0, 1)
self.assertMaskedArrayEqual(res.data, expected_data)
def test_collapse_middle_dim(self):
cube = stock.realistic_4d_no_derived()
other = cube.collapsed(['model_level_number'], MEAN)
res = self.cube_func(cube, other)
self.assertCML(res, checksum=False)
# Add the collapsed dimension back in via np.newaxis to enable
# numpy broadcasting to function.
expected_data = self.data_op(cube.data,
other.data[:, np.newaxis, ...])
self.assertMaskedArrayEqual(res.data, expected_data)
def test_slice(self):
cube = stock.realistic_4d_no_derived()
for dim in range(cube.ndim):
keys = [slice(None)] * cube.ndim
keys[dim] = 3
other = cube[tuple(keys)]
res = self.cube_func(cube, other)
self.assertCML(res, checksum=False)
# Add the collapsed dimension back in via np.newaxis to enable
# numpy broadcasting to function.
keys[dim] = np.newaxis
expected_data = self.data_op(cube.data,
other.data[tuple(keys)])
msg = 'Problem broadcasting cubes when sliced on dimension {}.'
self.assertArrayEqual(res.data, expected_data,
err_msg=msg.format(dim))
class CubeArithmeticMaskingTestMixin(object):
# A framework for testing the mask handling behaviour of the various cube
# arithmetic operations. (A test for each operation inherits this).
__metaclass__ = ABCMeta
@abstractproperty
def data_op(self):
# Define an operator to be called, I.E. 'operator.xx'.
pass
@abstractproperty
def cube_func(self):
# Define an iris arithmetic function to be called
# I.E. 'iris.analysis.maths.xx'.
pass
def _test_partial_mask(self, in_place):
# Helper method for masked data tests.
dat_a = np.ma.array([2., 2., 2., 2.], mask=[1, 0, 1, 0])
dat_b = np.ma.array([2., 2., 2., 2.], mask=[1, 1, 0, 0])
cube_a = Cube(dat_a)
cube_b = Cube(dat_b)
com = self.data_op(dat_b, dat_a)
res = self.cube_func(cube_b, cube_a, in_place=in_place)
return com, res, cube_b
def test_partial_mask_in_place(self):
# Cube in_place arithmetic operation.
com, res, orig_cube = self._test_partial_mask(True)
self.assertMaskedArrayEqual(com, res.data, strict=True)
self.assertIs(res, orig_cube)
def test_partial_mask_not_in_place(self):
# Cube arithmetic not an in_place operation.
com, res, orig_cube = self._test_partial_mask(False)
self.assertMaskedArrayEqual(com, res.data)
self.assertIsNot(res, orig_cube)
| lgpl-3.0 |
Wmaxlees/jarvis-os | Documentation/html/search/all_8.js | 244 | var searchData=
[
['testmodule',['TestModule',['../class_test_module.html',1,'']]],
['testmodule_2ecpp',['TestModule.cpp',['../_test_module_8cpp.html',1,'']]],
['testmodule_2ehpp',['TestModule.hpp',['../_test_module_8hpp.html',1,'']]]
];
| lgpl-3.0 |
MrRiegel/Various-Items | src/main/java/mrriegel/various/gui/jetpack/ContainerJetPack.java | 3274 | package mrriegel.various.gui.jetpack;
import mrriegel.various.config.ConfigHandler;
import mrriegel.various.gui.CrunchItemInventory;
import mrriegel.various.helper.NBTHelper;
import mrriegel.various.init.ModItems;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class ContainerJetPack extends Container {
InventoryPlayer playerInv;
CrunchItemInventory inv;
public ContainerJetPack(InventoryPlayer playerInv, CrunchItemInventory inv) {
this.playerInv = playerInv;
this.inv = inv;
this.addSlotToContainer(new Slot(inv, 0, 80, 13) {
@Override
public boolean isItemValid(ItemStack stack) {
return stackAllowed(stack);
}
@Override
public void onSlotChanged() {
super.onSlotChanged();
change(this);
}
});
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 9; ++j) {
this.addSlotToContainer(new Slot(playerInv, j + i * 9 + 9,
8 + j * 18, 84 - 39 + i * 18));
}
}
for (int i = 0; i < 9; ++i) {
this.addSlotToContainer(new Slot(playerInv, i, 8 + i * 18, 142 - 39));
}
}
@Override
public void onContainerClosed(EntityPlayer playerIn) {
super.onContainerClosed(playerIn);
if (!playerIn.worldObj.isRemote) {
ItemStack itemstack = this.inv.removeStackFromSlot(0);
if (itemstack != null) {
playerIn.dropPlayerItemWithRandomChoice(itemstack, false);
}
}
}
@Override
public boolean canInteractWith(EntityPlayer playerIn) {
return playerIn.getCurrentArmor(2) != null
&& playerIn.getCurrentArmor(2).getItem() == ModItems.jetpack;
}
public void change(Slot slot) {
ItemStack stack = playerInv.armorItemInSlot(2);
ItemStack lava = slot.getStack();
if (lava == null)
return;
if (lava.getItem() == Items.lava_bucket
&& NBTHelper.getInt(stack, "fuel")
+ ConfigHandler.fuelValueLava <= ConfigHandler.jetpackMaxFuel) {
NBTHelper.setInteger(stack, "fuel", NBTHelper.getInt(stack, "fuel")
+ ConfigHandler.fuelValueLava);
slot.inventory.setInventorySlotContents(slot.getSlotIndex(),
new ItemStack(Items.bucket));
}
}
protected boolean stackAllowed(ItemStack stackInSlot) {
return stackInSlot.getItem() == Items.lava_bucket;
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) {
ItemStack itemstack = null;
Slot slot = this.inventorySlots.get(slotIndex);
if (slot != null && slot.getHasStack()) {
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (slotIndex == 0) {
if (!this.mergeItemStack(itemstack1, 1, 37, true)) {
return null;
}
slot.onSlotChange(itemstack1, itemstack);
} else {
boolean merged = false;
if (stackAllowed(itemstack1)
&& this.mergeItemStack(itemstack1, 0, 1, false)) {
merged = true;
}
if (!merged)
return null;
}
if (itemstack1.stackSize == 0) {
slot.putStack((ItemStack) null);
} else {
slot.onSlotChanged();
}
if (itemstack1.stackSize == itemstack.stackSize) {
return null;
}
slot.onPickupFromSlot(player, itemstack1);
}
return itemstack;
}
}
| lgpl-3.0 |
pinf-it/pinf-it-bundler | test/assets/packages/nodejs-multiple/app.js | 184 |
var GREETING = require("greeting");
var LIB = require("./lib");
function main() {
console.log(GREETING[LIB.getGreetingMethodName()]());
}
if (require.main === module) {
main();
}
| unlicense |
bpmartins/sgcm | src/main/webapp/includes/jQuery/jquery.pagination.js | 9057 | /**
* This jQuery plugin displays pagination links inside the selected elements.
*
* This plugin needs at least jQuery 1.4.2
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 2.1
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
*/
(function($){
/**
* @class Class for calculating pagination values
*/
$.PaginationCalculator = function(maxentries, opts) {
this.maxentries = maxentries;
this.opts = opts;
}
$.extend($.PaginationCalculator.prototype, {
/**
* Calculate the maximum number of pages
* @method
* @returns {Number}
*/
numPages:function() {
return Math.ceil(this.maxentries/this.opts.items_per_page);
},
/**
* Calculate start and end point of pagination links depending on
* current_page and num_display_entries.
* @returns {Array}
*/
getInterval:function(current_page) {
var ne_half = Math.floor(this.opts.num_display_entries/2);
var np = this.numPages();
var upper_limit = np - this.opts.num_display_entries;
var start = current_page > ne_half ? Math.max( Math.min(current_page - ne_half, upper_limit), 0 ) : 0;
var end = current_page > ne_half?Math.min(current_page+ne_half + (this.opts.num_display_entries % 2), np):Math.min(this.opts.num_display_entries, np);
return {start:start, end:end};
}
});
// Initialize jQuery object container for pagination renderers
$.PaginationRenderers = {}
/**
* @class Default renderer for rendering pagination links
*/
$.PaginationRenderers.defaultRenderer = function(maxentries, opts) {
this.maxentries = maxentries;
this.opts = opts;
this.pc = new $.PaginationCalculator(maxentries, opts);
}
$.extend($.PaginationRenderers.defaultRenderer.prototype, {
/**
* Helper function for generating a single link (or a span tag if it's the current page)
* @param {Number} page_id The page id for the new item
* @param {Number} current_page
* @param {Object} appendopts Options for the new item: text and classes
* @returns {jQuery} jQuery object containing the link
*/
createLink:function(page_id, current_page, appendopts){
var lnk, np = this.pc.numPages();
page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
appendopts = $.extend({text:page_id+1, classes:""}, appendopts||{});
var img = "";
if (appendopts.classes == "sp") {
img = "<img src='" + js_caminhoImagens + "/i.p.firstpg.gif' border='0' id='" + page_id + "' style='margin-left: 35px;' />";
}
if (appendopts.classes == "prev") {
img = "<img src='" + js_caminhoImagens + "/i.p.prevpg.gif' border='0' id='" + page_id + "' style='margin-left: 5px; margin-right: 5px; display: none;' />";
}
if (appendopts.classes == "next") {
img = "<img src='" + js_caminhoImagens + "/i.p.nextpg.gif' border='0' id='" + page_id + "' style='margin-left: 5px; margin-right: 5px; display: none;' />";
}
if (appendopts.classes == "ep") {
img = "<img src='" + js_caminhoImagens + "/i.p.lastpg.gif' border='0' id='" + page_id + "' style='margin-right: 35px;' />";
}
if(page_id == current_page){
if (img != "") {
lnk = $(img);
} else {
lnk = $("<span class='current'> " + appendopts.text + " </span>");
}
}
else
{
if (img != "") {
lnk = $("<a>" + img + "</a>")
.attr('href', this.opts.link_to.replace(/__id__/,page_id));
} else {
lnk = $(" <a>" + " " +appendopts.text + " " + "</a> ")
.attr('href', this.opts.link_to.replace(/__id__/,page_id));
}
}
if(appendopts.classes){ lnk.addClass(appendopts.classes); }
lnk.data('page_id', page_id);
return lnk;
},
// Generate a range of numeric links
appendRange:function(container, current_page, start, end, opts) {
var i;
for(i=start; i<end; i++) {
this.createLink(i, current_page, opts).appendTo(container);
}
},
getLinks:function(current_page, eventHandler) {
var begin, end,
interval = this.pc.getInterval(current_page),
np = this.pc.numPages(),
fragment = $("<div class='pagination'></div>");
// Generate "First"-Link
if(this.opts.first_text && this.opts.first_show_always){
fragment.append(this.createLink(0, current_page, {text:this.opts.first_text, classes:"sp"}));
}
// Generate "Previous"-Link
if(this.opts.prev_text && (current_page > 0 || this.opts.prev_show_always)){
fragment.append(this.createLink(current_page-1, current_page, {text:this.opts.prev_text, classes:"prev"}));
}
// Generate interval links
this.appendRange(fragment, current_page, interval.start, interval.end);
// Generate "Next"-Link
if(this.opts.next_text && (current_page < np-1 || this.opts.next_show_always)){
fragment.append(this.createLink(current_page+1, current_page, {text:this.opts.next_text, classes:"next"}));
}
// Generate "Last"-Link
if(this.opts.last_text && this.opts.last_show_always){
fragment.append(this.createLink(np-1, current_page, {text:this.opts.last_text, classes:"ep"}));
}
$('a', fragment).click(eventHandler);
return fragment;
}
});
// Extend jQuery
$.fn.pagination = function(maxentries, opts){
// Initialize options with default values
opts = jQuery.extend({
items_per_page:10,
num_display_entries:11,
current_page:0,
link_to:"#",
prev_text:" ",
next_text:" ",
first_text:" ",
last_text:" ",
prev_show_always:true,
next_show_always:true,
first_show_always:true,
last_show_always:true,
renderer:"defaultRenderer",
callback:function(){return false;}
},opts||{});
var containers = this,
renderer, links, current_page;
/**
* This is the event handling function for the pagination links.
* @param {int} page_id The new page number
*/
function paginationClickHandler(evt){
var links,
new_current_page = $(evt.target).data('page_id');
if (new_current_page == undefined) {
new_current_page = $(evt.target).attr('id');
}
var continuePropagation = selectPage(new_current_page);
if (!continuePropagation) {
evt.stopPropagation();
}
return continuePropagation;
}
/**
* This is a utility function for the internal event handlers.
* It sets the new current page on the pagination container objects,
* generates a new HTMl fragment for the pagination links and calls
* the callback function.
*/
function selectPage(new_current_page) {
// update the link display of a all containers
containers.data('current_page', new_current_page);
links = renderer.getLinks(new_current_page, paginationClickHandler);
containers.empty();
links.appendTo(containers);
// call the callback and propagate the event if it does not return false
var continuePropagation = opts.callback(new_current_page, containers);
return continuePropagation;
}
// -----------------------------------
// Initialize containers
// -----------------------------------
current_page = opts.current_page;
containers.data('current_page', current_page);
// Create a sane value for maxentries and items_per_page
maxentries = (!maxentries || maxentries < 0)?1:maxentries;
opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
if(!$.PaginationRenderers[opts.renderer])
{
throw new ReferenceError("Pagination renderer '" + opts.renderer + "' was not found in jQuery.PaginationRenderers object.");
}
renderer = new $.PaginationRenderers[opts.renderer](maxentries, opts);
// Attach control events to the DOM elements
var pc = new $.PaginationCalculator(maxentries, opts);
var np = pc.numPages();
containers.bind('setPage', {numPages:np}, function(evt, page_id) {
if(page_id >= 0 && page_id < evt.data.numPages) {
selectPage(page_id); return false;
}
});
containers.bind('firstPage', function(evt){
var current_page = $(this).data('current_page');
if (current_page > 0) {
selectPage(0);
}
return false;
});
containers.bind('prevPage', function(evt){
var current_page = $(this).data('current_page');
if (current_page > 0) {
selectPage(current_page - 1);
}
return false;
});
containers.bind('nextPage', {numPages:np}, function(evt){
var current_page = $(this).data('current_page');
if(current_page < evt.data.numPages - 1) {
selectPage(current_page + 1);
}
return false;
});
containers.bind('lastPage', {numPages:np}, function(evt){
var current_page = $(this).data('current_page');
if(current_page < evt.data.numPages - 1) {
selectPage(evt.data.numPages - 1);
}
return false;
});
// When all initialisation is done, draw the links
links = renderer.getLinks(current_page, paginationClickHandler);
containers.empty();
links.appendTo(containers);
// call callback function
opts.callback(current_page, containers);
} // End of $.fn.pagination block
})(jQuery);
| unlicense |
pepe1914/jfx_libbase | src-datasource1/javafx/org/scene/effect/shaderstore/topmng/ZSS_EffTopMngITF.java | 761 | /* ZSS_EffTopMngITF.java */
package javafx.org.scene.effect.shaderstore.topmng;
import javafx.org.scene.effect.shaderstore.mng.ZSS_EffMngITF;
import com.sun.javafx.org.annotations.ZAdded;
import com.sun.javafx.org.shaderstore.topmng.ZSS_AbsTopMngITF;
/**
* This interface is only used to store the effect shader storage.<br>
*
* @author ZZZ. No copyright(c). Public Domain.
* @param <OBJ>
*/
@ZAdded(comments = "Actually solved by the use of static instance, but this is not the better...")
public interface ZSS_EffTopMngITF<OBJ extends ZSS_EffMngITF>
extends ZSS_AbsTopMngITF<OBJ> {
// ========================================================================
// ========================================================================
}
| unlicense |
6tail/nlf | WebContent/js/util/MD5.js | 5355 | /**
* I.util.MD5
* <i>MD5编码</i>
* <u>I.util.MD5.encode(s);</u>
*/
I.regist('util.MD5',function(W,D){
var hex_chr = "0123456789abcdef";
var rhex = function(num){
var str = '';
for(var j = 0; j <= 3; j++){
str += hex_chr.charAt((num >> (j * 8 + 4)) & 0x0F) + hex_chr.charAt((num >> (j * 8)) & 0x0F);
}
return str;
};
var str2blks_MD5 = function(str){
var nblk = ((str.length + 8) >> 6) + 1;
var blks = new Array(nblk * 16);
for(var i = 0; i < nblk * 16; i++) blks[i] = 0;
for(var i = 0; i < str.length; i++) blks[i >> 2] |= str.charCodeAt(i) << ((i % 4) * 8);
blks[i >> 2] |= 0x80 << ((i % 4) * 8);
blks[nblk * 16 - 2] = str.length * 8;
return blks;
};
var add = function(x, y){
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
var rol = function(num, cnt){
return (num << cnt) | (num >>> (32 - cnt));
};
var cmn = function(q, a, b, x, s, t){
return add(rol(add(add(a, q), add(x, t)), s), b);
};
var ff = function(a, b, c, d, x, s, t){
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
};
var gg = function(a, b, c, d, x, s, t){
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
};
var hh = function(a, b, c, d, x, s, t){
return cmn(b ^ c ^ d, a, b, x, s, t);
};
var ii = function(a, b, c, d, x, s, t){
return cmn(c ^ (b | (~d)), a, b, x, s, t);
};
var _encode = function(str){
var x = str2blks_MD5(str);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16){
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = ff(c, d, a, b, x[i+10], 17, -42063);
b = ff(b, c, d, a, x[i+11], 22, -1990404162);
a = ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = ff(d, a, b, c, x[i+13], 12, -40341101);
c = ff(c, d, a, b, x[i+14], 17, -1502002290);
b = ff(b, c, d, a, x[i+15], 22, 1236535329);
a = gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = gg(c, d, a, b, x[i+11], 14, 643717713);
b = gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = gg(d, a, b, c, x[i+10], 9 , 38016083);
c = gg(c, d, a, b, x[i+15], 14, -660478335);
b = gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = gg(b, c, d, a, x[i+12], 20, -1926607734);
a = hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = hh(c, d, a, b, x[i+11], 16, 1839030562);
b = hh(b, c, d, a, x[i+14], 23, -35309556);
a = hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = hh(b, c, d, a, x[i+10], 23, -1094730640);
a = hh(a, b, c, d, x[i+13], 4 , 681279174);
d = hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = hh(d, a, b, c, x[i+12], 11, -421815835);
c = hh(c, d, a, b, x[i+15], 16, 530742520);
b = hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = ii(c, d, a, b, x[i+14], 15, -1416354905);
b = ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = ii(c, d, a, b, x[i+10], 15, -1051523);
b = ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = ii(d, a, b, c, x[i+15], 10, -30611744);
c = ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = ii(b, c, d, a, x[i+13], 21, 1309151649);
a = ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = ii(d, a, b, c, x[i+11], 10, -1120210379);
c = ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = add(a, olda);
b = add(b, oldb);
c = add(c, oldc);
d = add(d, oldd);
}
return rhex(a) + rhex(b) + rhex(c) + rhex(d);
};
return {
encode:function(s) {
return _encode(s);
}
};
}+''); | unlicense |
BazkieBumpercar/GameplayFootball | src/onthepitch/player/controller/strategies/offtheball/default_off.hpp | 668 | // written by bastiaan konings schuiling 2008 - 2015
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#ifndef _HPP_STRATEGY_DEFAULT_OFFENSE
#define _HPP_STRATEGY_DEFAULT_OFFENSE
#include "../strategy.hpp"
class DefaultOffenseStrategy : public Strategy {
public:
DefaultOffenseStrategy(ElizaController *controller);
virtual ~DefaultOffenseStrategy();
virtual void RequestInput(const MentalImage *mentalImage, Vector3 &direction, float &velocity);
protected:
};
#endif
| unlicense |
arfo90/node-tips-tricks-sample-code | network/net-watcher.js | 775 | 'use strict';
const
fs = require('fs'),
net = require('net'),
filename = process.argv[2],
server = net.createServer(function(connection) {
//reporting
console.log('Subscriber connected.');
connection.write("Now Watching '" + filename + "'for changes...\n'");
//watcher setup
let watcher = fs.watch(filename, function() {
connection.write("File'" + filename + "'changed: " + Date.now() + "\n");
console.log('it is changing')
});
//Cleanup
connection.on('close', function(){
console.log('Subscription disconnected.');
watcher.close();
});
});
if (!filename){
throw Error('No Target');
}
server.listen(5432, function(){
console.log('listening for subscribers...');
});
| unlicense |
ucodescs/CMS | application/models/utilizadores_model.php | 4126 | <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Utilizadores_model extends CI_Model
{
//Admin
//Backend
function be_get_users()
{
$query = $this->db->query("SELECT * FROM utilizadores");
return $query->result();
}
function be_get_user_by_hash($hash)
{
$query = $this->db->query("SELECT * FROM utilizadores WHERE USRHASH='".$hash."'");
return $query->row();
}
function be_insert_backend($data, $foto=0)
{
if($foto==1){
$query = $this->db->query("INSERT INTO utilizadores (USRFOTO, USRPASSWORD, USREMAIL, USRHASH, USRNOME, USRACESSO, USRACTIVO, USRU01, USRU02, USRU03, USRU04, USRU05, USRU06, USRU07, USRU08, USRU09, USRU10, USRU11, USRU12, USRU13, USRU14, USRU15, USRU16) Values('".$data['usrfoto']."', '".$data['usrpassword']."', '".$data['usremail']."', '".$data['usrhash']."', '".$data['usrnome']."', ".$data['usracesso'].", ".$data['usractivo'].", '".$data['usru01']."', '".$data['usru02']."', '".$data['usru03']."', '".$data['usru04']."', '".$data['usru05']."', '".$data['usru06']."', '".$data['usru07']."', '".$data['usru08']."', '".$data['usru09']."', '".$data['usru10']."', ".$data['usru11'].", ".$data['usru12'].", ".$data['usru13'].", ".$data['usru14'].", ".$data['usru15'].", '".$data['usru16']."') ");
}else{
$query = $this->db->query("INSERT INTO utilizadores (USRPASSWORD, USREMAIL, USRHASH, USRNOME, USRACESSO, USRACTIVO, USRU01, USRU02, USRU03, USRU04, USRU05, USRU06, USRU07, USRU08, USRU09, USRU10, USRU11, USRU12, USRU13, USRU14, USRU15, USRU16) Values('".$data['usrpassword']."', '".$data['usremail']."', '".$data['usrhash']."', '".$data['usrnome']."', ".$data['usracesso'].", ".$data['usractivo'].", '".$data['usru01']."', '".$data['usru02']."', '".$data['usru03']."', '".$data['usru04']."', '".$data['usru05']."', '".$data['usru06']."', '".$data['usru07']."', '".$data['usru08']."', '".$data['usru09']."', '".$data['usru10']."', ".$data['usru11'].", ".$data['usru12'].", ".$data['usru13'].", ".$data['usru14'].", ".$data['usru15'].", '".$data['usru16']."') ");
}
}
function be_update_backend($data, $foto=0)
{
if($foto==1){
$query = $this->db->query("UPDATE utilizadores SET USRFOTO='".$data['usrfoto']."', USRNOME='".$data['usrnome']."', USRACESSO=".$data['usracesso'].", USRACTIVO=".$data['usractivo'].", USRU01='".$data['usru01']."', USRU02='".$data['usru02']."', USRU03='".$data['usru03']."', USRU04='".$data['usru04']."', USRU05='".$data['usru05']."', USRU06='".$data['usru06']."',USRU07='".$data['usru07']."', USRU08='".$data['usru08']."', USRU09='".$data['usru09']."',USRU10='".$data['usru10']."', USRU11=".$data['usru11'].", USRU12=".$data['usru12'].", USRU13=".$data['usru13'].", USRU14=".$data['usru14'].", USRU15=".$data['usru15'].", USRU16='".$data['usru16']."' WHERE USRID=".$data['usrid']);
}else{
$query = $this->db->query("UPDATE utilizadores SET USRNOME='".$data['usrnome']."', USRACESSO=".$data['usracesso'].", USRACTIVO=".$data['usractivo'].", USRU01='".$data['usru01']."', USRU02='".$data['usru02']."', USRU03='".$data['usru03']."', USRU04='".$data['usru04']."', USRU05='".$data['usru05']."', USRU06='".$data['usru06']."',USRU07='".$data['usru07']."', USRU08='".$data['usru08']."', USRU09='".$data['usru09']."',USRU10='".$data['usru10']."', USRU11=".$data['usru11'].", USRU12=".$data['usru12'].", USRU13=".$data['usru13'].", USRU14=".$data['usru14'].", USRU15=".$data['usru15'].", USRU16='".$data['usru16']."' WHERE USRID=".$data['usrid']);
}
}
function be_delete_backend($hash)
{
$query = $this->db->query("DELETE FROM utilizadores WHERE USRHASH='".$hash."'");
}
function be_check_email($usremail)
{
$query = $this->db->query("SELECT COUNT(usremail) AS COUNT FROM utilizadores WHERE usremail='".$usremail."'");
return $query->row();
}
//Frontend
function checkuser($email,$pass)
{
$query = $this->db->query("SELECT USRID, USREMAIL, USRPASSWORD, USRNOME, USRFOTO, USRACESSO, USRREGISTO, USRHASH FROM utilizadores WHERE USRACTIVO=1 AND USREMAIL='".$email."' AND USRPASSWORD='".$pass."'");
return $query->row();
}
}
| unlicense |
ajmrive/poll_intention | protected/views/response/update.php | 582 | <?php
/* @var $this ResponseController */
/* @var $model response */
$this->breadcrumbs=array(
'Responses'=>array('index'),
$model->id=>array('view','id'=>$model->id),
'Update',
);
$this->menu=array(
array('label'=>'List response', 'url'=>array('index')),
array('label'=>'Create response', 'url'=>array('create')),
array('label'=>'View response', 'url'=>array('view', 'id'=>$model->id)),
array('label'=>'Manage response', 'url'=>array('admin')),
);
?>
<h1>Update response <?php echo $model->id; ?></h1>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?> | unlicense |
MichaelWoodhams/HybridSeq | src/hybridseq/SimpleWeightedTree.java | 405 | package hybridseq;
import pal.tree.SimpleTree;
import pal.tree.Tree;
@SuppressWarnings("serial")
public class SimpleWeightedTree extends SimpleTree implements WeightedTree {
private double weight;
public SimpleWeightedTree(Tree tree, double weight) {
super(tree);
this.weight = weight;
}
public void setWeight(double wt) {
weight = wt;
}
public double getWeight() {
return weight;
}
}
| unlicense |
OlegPshenichniy/RabbitMQ-Python | with_txamqp/rabbit.py | 13467 | import optparse
import sys
import uuid
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet.protocol import ClientCreator
from txamqp.client import TwistedDelegate
from txamqp.content import Content
from txamqp.protocol import AMQClient
import txamqp.spec
NUM_MSGS = 1
DEFAULT_TOPICS = 'info'
QUEUE_NAME = 'txamqp_example_queue'
ROUTING_TOPIC = 'txamqp_example_topic'
EXCHANGE_NAME = 'txamqp_example_exchange'
SEVERITIES = ('info', 'warning', 'debug')
FACILITIES = ('kern', 'mail')
@inlineCallbacks
def gotConnection(connection, username, password):
print ' Got connection, authenticating.'
# Older version of AMQClient have no authenticate
# yield connection.authenticate(username, password)
# This produces the same effect
yield connection.start({'LOGIN': username, 'PASSWORD': password})
channel = yield connection.channel(1)
yield channel.channel_open()
returnValue((connection, channel))
def setup_queue_cleanup(result):
"""Executed in consumers on Ctrl-C, but not in publishers."""
connection, channel = result
reactor.addSystemEventTrigger('before', 'shutdown',
consumer_cleanup, channel)
return result
def consumer_cleanup(channel):
return channel.queue_delete(QUEUE_NAME)
@inlineCallbacks
def publisher_cleanup(result):
# import pdb; pdb.set_trace()
connection, channel = result
# yield channel.queue_delete(queue=QUEUE_NAME)
yield channel.channel_close()
chan0 = yield connection.channel(0)
yield chan0.connection_close()
reactor.stop()
@inlineCallbacks
def consume1(result, topics):
connection, channel = result
yield channel.queue_declare(queue=QUEUE_NAME)
msgnum = 0
print ' [*] Waiting for messages. To exit press CTRL+C'
yield channel.basic_consume(queue=QUEUE_NAME, no_ack=True,
consumer_tag='qtag')
queue = yield connection.queue('qtag')
while True:
msg = yield queue.get()
msgnum += 1
print " [%04d] Received %r from channel #%d" % (
msgnum, msg.content.body, channel.id)
returnValue(result)
@inlineCallbacks
def consume2(result, topics):
connection, channel = result
yield channel.queue_declare(queue=QUEUE_NAME, durable=True)
msgnum = 0
print ' [*] Waiting for messages. To exit press CTRL+C'
yield channel.basic_qos(prefetch_count=1)
yield channel.basic_consume(queue=QUEUE_NAME, consumer_tag='qtag')
queue = yield connection.queue('qtag')
while True:
msg = yield queue.get()
msgnum += 1
print " [%04d] Received %r from channel #%d" % (
msgnum, msg.content.body, channel.id)
channel.basic_ack(delivery_tag=msg.delivery_tag)
returnValue(result)
@inlineCallbacks
def consume3(result, topics):
connection, channel = result
yield channel.exchange_declare(exchange=EXCHANGE_NAME, type='fanout')
reply = yield channel.queue_declare(exclusive=True)
queue_name = reply.queue
msgnum = 0
channel.queue_bind(exchange=EXCHANGE_NAME, queue=queue_name)
print ' [*] Waiting for messages. To exit press CTRL+C'
yield channel.basic_consume(
queue=queue_name, no_ack=True, consumer_tag='qtag')
queue = yield connection.queue('qtag')
while True:
msg = yield queue.get()
msgnum += 1
print " [%04d] Received %r from channel #%d" % (
msgnum, msg.content.body, channel.id)
returnValue(result)
@inlineCallbacks
def consume4(result, topics):
connection, channel = result
exchange_name = '%s_4' % EXCHANGE_NAME
yield channel.exchange_declare(exchange=exchange_name, type='direct')
reply = yield channel.queue_declare(exclusive=True)
queue_name = reply.queue
msgnum = 0
severities = topics.split(',')
for severity in severities:
channel.queue_bind(
exchange=exchange_name, queue=queue_name, routing_key=severity)
print ' [*] Waiting for messages. To exit press CTRL+C'
yield channel.basic_consume(
queue=queue_name, no_ack=True, consumer_tag='qtag')
queue = yield connection.queue('qtag')
while True:
msg = yield queue.get()
msgnum += 1
print " [%04d] Received %r from channel #%d with severity [%s]" % (
msgnum, msg.content.body, channel.id, msg.routing_key)
returnValue(result)
@inlineCallbacks
def consume5(result, topics):
connection, channel = result
exchange_name = '%s_5' % EXCHANGE_NAME
yield channel.exchange_declare(exchange=exchange_name, type='topic')
reply = yield channel.queue_declare(exclusive=True)
queue_name = reply.queue
msgnum = 0
routing_keys = topics.split(',')
for routing_key in routing_keys:
channel.queue_bind(
exchange=exchange_name, queue=queue_name, routing_key=routing_key)
print ' [*] Waiting for messages. To exit press CTRL+C'
yield channel.basic_consume(
queue=queue_name, no_ack=True, consumer_tag='qtag')
queue = yield connection.queue('qtag')
while True:
msg = yield queue.get()
msgnum += 1
print (' [%04d] Received %r from channel #%d '
'with facility and severity [%s]') % (
msgnum, msg.content.body, channel.id, msg.routing_key)
returnValue(result)
@inlineCallbacks
def consume6(result, topics):
connection, channel = result
yield channel.queue_declare(queue='rpc_queue')
msgnum = 0
print ' [*] Waiting for RPC requests. To exit press CTRL+C'
yield channel.basic_qos(prefetch_count=1)
yield channel.basic_consume(
queue='rpc_queue', no_ack=True, consumer_tag='qtag')
queue = yield connection.queue('qtag')
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
while True:
msg = yield queue.get()
input_ = msg.content.body
properties = msg.content.properties
msgnum += 1
print ' [%04d] Received fib(%r) from channel #%d' % (
msgnum, input_, channel.id)
output = fib(int(input_))
response = Content(str(output))
response['correlation id'] = properties['correlation id']
channel.basic_publish(exchange='', routing_key=properties['reply to'],
content=response)
returnValue(result)
@inlineCallbacks
def publish1(result, message, count_):
connection, channel = result
yield channel.queue_declare(queue=QUEUE_NAME)
for i in range(count_):
msg = Content('%s [%04d]' % (message, i,))
yield channel.basic_publish(
exchange='', routing_key=QUEUE_NAME, content=msg)
print ' [x] Sent "%s [%04d]"' % (message, i,)
returnValue(result)
@inlineCallbacks
def publish2(result, message, count_):
connection, channel = result
yield channel.queue_declare(queue=QUEUE_NAME, durable=True)
for i in range(count_):
msg = Content('%s [%04d]' % (message, i,))
msg['delivery mode'] = 2
yield channel.basic_publish(
exchange='', routing_key=QUEUE_NAME, content=msg)
print ' [x] Sent "%s [%04d]"' % (message, i,)
returnValue(result)
@inlineCallbacks
def publish3(result, message, count_):
connection, channel = result
yield channel.exchange_declare(exchange=EXCHANGE_NAME, type='fanout')
for i in range(count_):
msg = Content('%s [%04d]' % (message, i,))
yield channel.basic_publish(
exchange=EXCHANGE_NAME, routing_key='', content=msg)
print ' [x] Sent "%s [%04d]"' % (message, i,)
returnValue(result)
@inlineCallbacks
def publish4(result, message, count_):
connection, channel = result
exchange_name = '%s_4' % EXCHANGE_NAME
yield channel.exchange_declare(exchange=exchange_name, type='direct')
for i in range(count_):
msg = Content('%s [%04d]' % (message, i,))
severity = SEVERITIES[i % len(SEVERITIES)]
yield channel.basic_publish(
exchange=exchange_name, routing_key=severity, content=msg)
print ' [x] Sent "%s [%04d]" with severity [%s]' % (
message, i, severity,)
returnValue(result)
@inlineCallbacks
def publish5(result, message, count_):
connection, channel = result
exchange_name = '%s_5' % EXCHANGE_NAME
yield channel.exchange_declare(exchange=exchange_name, type='topic')
for i in range(count_):
msg = Content('%s [%04d]' % (message, i))
severity = SEVERITIES[i % len(SEVERITIES)]
facility = FACILITIES[i % len(FACILITIES)]
routing_key = '%s.%s' % (facility, severity)
yield channel.basic_publish(
exchange=exchange_name, routing_key=routing_key, content=msg)
print ' [x] Sent "%s [%04d]" with facility and severity [%s]' % (
message, i, routing_key)
returnValue(result)
@inlineCallbacks
def publish6(result, message, count_):
connection, channel = result
@inlineCallbacks
def call(n):
corr_id = str(uuid.uuid4())
reply = yield channel.queue_declare(exclusive=True)
callback_queue = reply.queue
msg = Content(str(n))
msg['correlation id'] = corr_id
msg['reply to'] = callback_queue
yield channel.basic_publish(
exchange='', routing_key='rpc_queue', content=msg)
print ' [x] Sent "%s"' % n
yield channel.basic_consume(
queue=callback_queue, no_ack=True, consumer_tag='qtag')
queue = yield connection.queue('qtag')
while True:
response = yield queue.get()
if response.content.properties['correlation id'] == corr_id:
returnValue(response.content.body)
print ' [x] Requesting fib(%s)' % message
response = yield call(message)
print ' [.] Got %r' % response
returnValue(result)
PUBLISH_EXAMPLES = {
'publish1': publish1,
'publish2': publish2,
'publish3': publish3,
'publish4': publish4,
'publish5': publish5,
'publish6': publish6,
}
CONSUME_EXAMPLES = {
'consume1': consume1,
'consume2': consume2,
'consume3': consume3,
'consume4': consume4,
'consume5': consume5,
'consume6': consume6,
}
ALL_EXAMPLES = {}
ALL_EXAMPLES.update(PUBLISH_EXAMPLES)
ALL_EXAMPLES.update(CONSUME_EXAMPLES)
def check_cmd_line(options, args, abort):
"""
Check the command line options and args, and exit with an error message
if something is not acceptable.
"""
if args:
abort('No arguments needed')
if not 0 < options.port < 65536:
abort('Please specify a port number between 1 and 65535 included')
if options.example not in ALL_EXAMPLES.keys():
abort('Please specify one of the following, as an example name: %s' %
ALL_EXAMPLES.keys())
if options.example in PUBLISH_EXAMPLES and options.message is None:
abort('Please provide a message to publish')
if options.message is not None and (
options.example not in PUBLISH_EXAMPLES):
abort('Setting the message is only meaningful for publish examples')
if options.count < 1:
abort('Please set a positive number of messages')
return (options.port, options.example, options.message, options.count,
options.topics)
def parse_cmd_line(parser, all_args):
"""
Parse command line arguments using the optparse library.
Return (options, args).
"""
parser.set_usage(
'Usage: %s -p -e [producer options: -m -c | '
'consumer options: -t topic1,topic2,...]' % all_args[0])
all_args = all_args[1:]
parser.add_option('-p', '--port', dest='port', type='int',
help='RabbitMQ server port number')
parser.add_option('-e', '--example', dest='example',
help='example name: "produceX" or "consumeX", with X from 1 to 6')
parser.add_option('-m', '--message', dest='message',
help='message to send as a producer')
parser.add_option('-c', '--count', dest='count', type='int',
help='num. of messages to send as a producer: default: %d' % NUM_MSGS)
parser.add_option('-t', '--topics', dest='topics',
help='topics to subscribe this consumer to')
parser.set_defaults(count=NUM_MSGS, topics=DEFAULT_TOPICS)
return parser.parse_args(all_args)
def main(all_args=None):
"""The main"""
all_args = all_args or []
parser = optparse.OptionParser()
options, args = parse_cmd_line(parser, all_args)
(port, example, message, count_, topics) = check_cmd_line(
options, args, parser.error)
host = 'localhost'
vhost = '/'
username = 'guest'
password = 'guest'
spec = txamqp.spec.load('your_specs_path.xml')
delegate = TwistedDelegate()
d = ClientCreator(reactor, AMQClient, delegate=delegate, vhost=vhost,
spec=spec).connectTCP(host, port)
d.addCallback(gotConnection, username, password)
if example in PUBLISH_EXAMPLES:
d.addCallback(ALL_EXAMPLES[example], message, count_)
else:
d.addCallback(ALL_EXAMPLES[example], topics)
d.addCallback(publisher_cleanup)
d.addErrback(lambda f: sys.stderr.write(str(f)))
reactor.run()
if __name__ == "__main__":
main(all_args=sys.argv) | unlicense |
boredgamerz/block-Chaos | Assets/Scripts/Paddle.cs | 2582 | using UnityEngine;
using System.Collections;
public class Paddle : MonoBehaviour {
public bool autoPlay = false;
public bool MoveWithArrowKeys = false;
public float speed = 3f;
private Ball ball;
public float padding = 1;
private float xmax = -5;
private float xmin = 5;
void Start(){
ball = GameObject.FindObjectOfType<Ball>();
GetCamera();
}
// Update is called once per frame
void Update () {
if (!autoPlay){
Movement();
}else{
AutoPlay();
}
}
void AutoPlay(){
Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);
Vector3 ballPos = ball.transform.position;
paddlePos.x = Mathf.Clamp(ballPos.x, 0.25f, 16.65f);
this.transform.position = paddlePos;
}
void Movement() {
if(!MoveWithArrowKeys){
Vector3 mousepos = Input.mousePosition;
mousepos.z = 1.0f;
float mouseXPosWorldUnits = Camera.main.ScreenToWorldPoint(mousepos).x;
// Creates the new position for the paddle
Vector3 paddlePos = new Vector3 (
Mathf.Clamp(mouseXPosWorldUnits, 0.25f, 16.65f), // limits from visual inpection
this.transform.position.y,// keep old y pos
this.transform.position.z // keep old z pos
);
this.transform.position = paddlePos;
}else{
if(MoveWithArrowKeys){
if(Input.GetKey(KeyCode.RightArrow)){
Vector3 paddlePos = new Vector3 (0.5f, this.transform.position.y, 0f);
paddlePos.x++;
this.transform.position = paddlePos;
}else{
if(Input.GetKey(KeyCode.LeftArrow)){
Vector3 paddlePos = new Vector2 (0.5f, 0f);
paddlePos.x--;
this.transform.position = paddlePos;
}
}
}
}
}
public void GetCamera(){
Camera camera = Camera.main;
float distance = transform.position.z - camera.transform.position.z;
xmin = camera.ViewportToWorldPoint(new Vector3 (0,0, distance)).x + padding;
xmax = camera.ViewportToWorldPoint(new Vector3 (1,1, distance)).x - padding;
}
public void MoveWithKeys(){
if (Input.GetKey(KeyCode.RightArrow)){
transform.position = new Vector3(Mathf.Clamp(transform.position.x + speed * Time.deltaTime, xmin, xmax)
,transform.position.y,
transform.position.z
);
}else if (Input.GetKey(KeyCode.LeftArrow)){
transform.position = new Vector3 (Mathf.Clamp(transform.position.x -speed * Time.deltaTime, xmin, xmax)
,transform.position.y,
transform.position.z
);
}
}
}
| unlicense |
marouanopen/PTS4-PhotoStore | src/main/java/fotowebstore/util/PasswordHandler.java | 549 | package fotowebstore.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class PasswordHandler {
public static byte[] hash(byte[] input) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.reset();
return messageDigest.digest(input);
}
public static byte[] salt() {
SecureRandom secRand = new SecureRandom();
return secRand.generateSeed(32);
}
}
| unlicense |
fdolci/cj-ztYt7MVxgtFy5vL3 | modules/AjaxUpload/ajax/subir_un_afiche.php | 5691 | <?php
$mipath='../';
include ($mipath.'../../inc/config.php');
$datos_ajaxupload = request('datos_ajaxupload','');
if(empty($datos_ajaxupload)) { echo "error ";}
$ajaxupload = unserialize( base64_decode($datos_ajaxupload) );
/*
$ajaxupload['tabla'] = 'publicaciones_imagenes';
$ajaxupload['campo'] = 'publicacion_id';
$ajaxupload['id'] = $Pub['id'];
$ajaxupload['cual'] = 'miniatura';
$ajaxupload['identificador'] = $identificador;
$ajaxupload['donde_subir'] = PUB_SUBIR_FOTOS;
$ajaxupload['donde_ver'] = PUB_VER_FOTOS;
$ajaxupload['tn_ancho'] = 240;
$ajaxupload['tn_alto'] = 120;
$ajaxupload['ancho'] = 240;
$ajaxupload['alto'] = 120;
*/
$tn_ancho = $ajaxupload['tn_ancho'];
$tn_alto = $ajaxupload['tn_alto'];
$ancho = $ajaxupload['ancho'];
$alto = $ajaxupload['alto'];
if($_GET['action'] == 'listFotos'){
$sql = "select * from {$ajaxupload['tabla']} where {$ajaxupload['campo']}='{$ajaxupload['id']}' and cual='{$ajaxupload['cual']}' and identificador='{$ajaxupload['identificador']}' ";
$rs = $db->SelectLimit($sql,1) ;
$Foto = $rs->FetchRow();
if ($Foto){
echo "<li id='img_{$Foto['id']}' ><a href='#' title='Eliminar la imagen'><img src='".URL."/img/del.gif' onclick='eliminar_afiche({$Foto['id']});' ></a>";
if ($tn_ancho>0 and $tn_alto>0) {
echo "<img src='{$ajaxupload['donde_ver']}/mini/tn_{$Foto[imagen]}' />";
} else {
echo "<img src='{$ajaxupload['donde_ver']}/{$Foto[imagen]}' />";
}
echo "</li>";
}
} elseif($_GET['action'] == 'eliminar'){
$id = $_GET['id'];
$rs = $db->SelectLimit("select * from {$ajaxupload['tabla']} where id='$id'",1);
$foto = $rs->FetchRow();
$destino = $ajaxupload['donde_subir'];
$nombre_foto = $destino.$foto['imagen'];
$miniatura = $destino.'mini/tn_'.$foto['imagen'];
unlink($nombre_foto);
unlink($miniatura);
$ok = $db->Execute("delete from {$ajaxupload['tabla']} where id='$id'");
} else {
//--- Elimino las anteriores si habia...
$sql = "select * from {$ajaxupload['tabla']} where {$ajaxupload['campo']}='{$ajaxupload['id']}' and cual='{$ajaxupload['cual']}' and identificador='{$ajaxupload['identificador']}' ";
$rs = $db->Execute($sql);
$Fotos = $rs->GetRows();
$destino = $ajaxupload['donde_subir'] ;
foreach ($Fotos as $foto) {
$nombre_foto = $destino.$foto['imagen'];
$miniatura = $destino.'mini/tn_'.$foto['imagen'];
unlink($nombre_foto);
unlink($miniatura);
}
$ok = $db->Execute("delete from {$ajaxupload['tabla']} where {$ajaxupload['campo']}='{$ajaxupload['campo']}' and cual='{$ajaxupload['cual']}' and identificador='{$ajaxupload['identificador']}' ");
$destino = $ajaxupload['donde_subir'] ."/";
if(isset($_FILES['image'])){
$x = explode('.',$_FILES['image']['name']);
$ext = end($x);
$x = md5(microtime().'_'.$_SERVER["REMOTE_ADDR"]);
$nombre = $x.'.'.$ext; //$_FILES['image']['name'];
// echo $nombre;
$temp = $_FILES['image']['tmp_name'];
// subir imagen al servidor
if(move_uploaded_file($temp, $destino.$nombre)) {
//---------------------- Ajustamos el tamaño de la imagen
$ruta_imagen = $destino.$nombre;
$info_imagen = getimagesize($ruta_imagen);
$imagen_ancho = $info_imagen[0];
$imagen_alto = $info_imagen[1];
$imagen_tipo = $info_imagen['mime'];
switch ( $imagen_tipo ){
case "image/jpg":
case "image/jpeg":
$imagen = imagecreatefromjpeg( $ruta_imagen );
break;
case "image/png":
$imagen = imagecreatefrompng( $ruta_imagen );
break;
case "image/gif":
$imagen = imagecreatefromgif( $ruta_imagen );
break;
}
if ($tn_ancho>0 and $tn_alto>0) {
// hago el thumbsnail
$lienzo = imagecreatetruecolor( $tn_ancho, $tn_alto );
imagecopyresampled($lienzo, $imagen, 0, 0, 0, 0, $tn_ancho, $tn_alto, $imagen_ancho, $imagen_alto);
imagejpeg( $lienzo, $destino.'mini/tn_'.$nombre, 90 );
// le cambio el tamaño a la imagen original
$lienzo = imagecreatetruecolor( $ancho, $alto );
imagecopyresampled($lienzo, $imagen, 0, 0, 0, 0, $ancho, $alto, $imagen_ancho, $imagen_alto);
$ok = imagejpeg( $lienzo, $destino.$nombre, 90 );
}
$sql = "insert into {$ajaxupload['tabla']} ({$ajaxupload['campo']}, imagen, cual, identificador) values ('{$ajaxupload['id']}', '$nombre','{$ajaxupload['cual']}', '{$ajaxupload['identificador']}' )";
$rs = $db->Execute($sql);
$id = $db->Insert_ID();
echo "<li id='img_$id' ><a href='#' title='Eliminar la imagen'><img src='".URL."/img/del.gif' onclick='eliminar($id);' ></a>";
echo "<img src='{$ajaxupload['donde_ver']}/$nombre' />";
echo "</li>";
}
}
}
?> | unlicense |
SeanShubin/contract | domain/src/main/scala/com/seanshubin/contract/domain/FilesDelegate.scala | 8010 | package com.seanshubin.contract.domain
import java.io.{BufferedReader, BufferedWriter, InputStream, OutputStream}
import java.nio.channels.SeekableByteChannel
import java.nio.charset.Charset
import java.nio.file.DirectoryStream.Filter
import java.nio.file._
import java.nio.file.attribute._
import java.util.function.BiPredicate
import java.util.stream
import java.{lang, util}
object FilesDelegate extends FilesContract {
override def newInputStream(path: Path, options: OpenOption*): InputStream = Files.newInputStream(path, options: _*)
override def getLastModifiedTime(path: Path, options: LinkOption*): FileTime = Files.getLastModifiedTime(path, options: _*)
override def move(source: Path, target: Path, options: CopyOption*): Path = Files.move(source, target, options: _*)
override def newOutputStream(path: Path, options: OpenOption*): OutputStream = Files.newOutputStream(path, options: _*)
override def createDirectory(dir: Path, attrs: FileAttribute[_]*): Path = Files.createDirectory(dir, attrs: _*)
override def createTempFile(dir: Path, prefix: String, suffix: String, attrs: FileAttribute[_]*): Path = Files.createTempFile(dir, prefix, suffix, attrs: _*)
override def createTempFile(prefix: String, suffix: String, attrs: FileAttribute[_]*): Path = Files.createTempFile(prefix, suffix, attrs: _*)
override def isReadable(path: Path): Boolean = Files.isReadable(path)
override def probeContentType(path: Path): String = Files.probeContentType(path)
override def createDirectories(dir: Path, attrs: FileAttribute[_]*): Path = Files.createDirectories(dir, attrs: _*)
override def newBufferedReader(path: Path, cs: Charset): BufferedReader = Files.newBufferedReader(path, cs)
override def newBufferedReader(path: Path): BufferedReader = Files.newBufferedReader(path)
override def walkFileTree(start: Path, options: util.Set[FileVisitOption], maxDepth: Int, visitor: FileVisitor[_ >: Path]): Path = Files.walkFileTree(start, options, maxDepth, visitor)
override def walkFileTree(start: Path, visitor: FileVisitor[_ >: Path]): Path = Files.walkFileTree(start, visitor)
override def newByteChannel(path: Path, options: util.Set[_ <: OpenOption], attrs: FileAttribute[_]*): SeekableByteChannel = Files.newByteChannel(path, options, attrs: _*)
override def newByteChannel(path: Path, options: OpenOption*): SeekableByteChannel = Files.newByteChannel(path, options: _*)
override def createFile(path: Path, attrs: FileAttribute[_]*): Path = Files.createFile(path, attrs: _*)
override def isRegularFile(path: Path, options: LinkOption*): Boolean = Files.isRegularFile(path, options: _*)
override def createSymbolicLink(link: Path, target: Path, attrs: FileAttribute[_]*): Path = Files.createSymbolicLink(link, target, attrs: _*)
override def walk(start: Path, maxDepth: Int, options: FileVisitOption*): stream.Stream[Path] = Files.walk(start, maxDepth, options: _*)
override def walk(start: Path, options: FileVisitOption*): stream.Stream[Path] = Files.walk(start, options: _*)
override def getAttribute(path: Path, attribute: String, options: LinkOption*): AnyRef = Files.getAttribute(path, attribute, options: _*)
override def createLink(link: Path, existing: Path): Path = Files.createLink(link, existing)
override def isHidden(path: Path): Boolean = Files.isHidden(path)
override def getPosixFilePermissions(path: Path, options: LinkOption*): util.Set[PosixFilePermission] = Files.getPosixFilePermissions(path, options: _*)
override def size(path: Path): Long = Files.size(path)
override def lines(path: Path, cs: Charset): stream.Stream[String] = Files.lines(path, cs)
override def lines(path: Path): stream.Stream[String] = Files.lines(path)
override def copy(source: Path, target: Path, options: CopyOption*): Path = Files.copy(source, target, options: _*)
override def copy(in: InputStream, target: Path, options: CopyOption*): Long = Files.copy(in, target, options: _*)
override def copy(source: Path, out: OutputStream): Long = Files.copy(source, out)
override def notExists(path: Path, options: LinkOption*): Boolean = Files.notExists(path, options: _*)
override def delete(path: Path): Unit = Files.delete(path)
override def newDirectoryStream(dir: Path): DirectoryStream[Path] = Files.newDirectoryStream(dir)
override def newDirectoryStream(dir: Path, glob: String): DirectoryStream[Path] = Files.newDirectoryStream(dir, glob)
override def newDirectoryStream(dir: Path, filter: Filter[_ >: Path]): DirectoryStream[Path] = Files.newDirectoryStream(dir, filter)
override def write(path: Path, bytes: Array[Byte], options: OpenOption*): Path = Files.write(path, bytes.toArray, options: _*)
override def write(path: Path, lines: lang.Iterable[_ <: CharSequence], cs: Charset, options: OpenOption*): Path = Files.write(path, lines, cs, options: _*)
override def write(path: Path, lines: lang.Iterable[_ <: CharSequence], options: OpenOption*): Path = Files.write(path, lines, options: _*)
override def isDirectory(path: Path, options: LinkOption*): Boolean = Files.isDirectory(path, options: _*)
override def isExecutable(path: Path): Boolean = Files.isExecutable(path)
override def setAttribute(path: Path, attribute: String, value: AnyRef, options: LinkOption*): Path = Files.setAttribute(path, attribute, value, options: _*)
override def list(dir: Path): stream.Stream[Path] = Files.list(dir)
override def getOwner(path: Path, options: LinkOption*): UserPrincipal = Files.getOwner(path, options: _*)
override def isWritable(path: Path): Boolean = Files.isWritable(path)
override def readAllLines(path: Path, cs: Charset): util.List[String] = Files.readAllLines(path, cs)
override def readAllLines(path: Path): util.List[String] = Files.readAllLines(path)
override def isSymbolicLink(path: Path): Boolean = Files.isSymbolicLink(path)
override def readSymbolicLink(link: Path): Path = Files.readSymbolicLink(link)
override def readAttributes[A <: BasicFileAttributes](path: Path, theType: Class[A], options: LinkOption*): A = Files.readAttributes(path, theType, options: _*)
override def readAttributes(path: Path, attributes: String, options: LinkOption*): util.Map[String, AnyRef] = Files.readAttributes(path, attributes, options: _*)
override def isSameFile(path: Path, path2: Path): Boolean = Files.isSameFile(path, path2)
override def createTempDirectory(dir: Path, prefix: String, attrs: FileAttribute[_]*): Path = Files.createTempDirectory(dir, prefix, attrs: _*)
override def createTempDirectory(prefix: String, attrs: FileAttribute[_]*): Path = Files.createTempDirectory(prefix, attrs: _*)
override def getFileAttributeView[V <: FileAttributeView](path: Path, theType: Class[V], options: LinkOption*): V = Files.getFileAttributeView(path, theType, options: _*)
override def find(start: Path, maxDepth: Int, matcher: BiPredicate[Path, BasicFileAttributes], options: FileVisitOption*): stream.Stream[Path] = Files.find(start, maxDepth, matcher, options: _*)
override def deleteIfExists(path: Path): Boolean = Files.deleteIfExists(path)
override def setPosixFilePermissions(path: Path, perms: util.Set[PosixFilePermission]): Path = Files.setPosixFilePermissions(path, perms)
override def setLastModifiedTime(path: Path, time: FileTime): Path = Files.setLastModifiedTime(path, time)
override def readAllBytes(path: Path): Array[Byte] = Files.readAllBytes(path)
override def exists(path: Path, options: LinkOption*): Boolean = Files.exists(path, options: _*)
override def setOwner(path: Path, owner: UserPrincipal): Path = Files.setOwner(path, owner)
override def newBufferedWriter(path: Path, cs: Charset, options: OpenOption*): BufferedWriter = Files.newBufferedWriter(path, cs, options: _*)
override def newBufferedWriter(path: Path, options: OpenOption*): BufferedWriter = Files.newBufferedWriter(path, options: _*)
override def getFileStore(path: Path): FileStore = Files.getFileStore(path)
}
| unlicense |
iamstupid/toybi | zemmud/pRNG.cpp | 1261 | #ifndef pRNG_impl
#define pRNG_impl
namespace pRNG{
template<class result_type>
struct pRNG{
void*data_region;
typedef result_type(*function_type)(void*);
function_type iterate_function;
pRNG(void*data_region,function_type iterate_function):
data_region(data_region),
iterate_function(iterate_function){}
inline result_type operator()(){
return iterate_function(data_region);
}
template<typename T,typename...vv>
void seed(vv...args){
((T*)data_region)->seed(args...);
}
template<typename T>
inline T&instance(){return *(T*)data_region;}
};
template<typename T>
typename T::result_type pRNG_next(
void*T_Ptr
){
return ((T*)T_Ptr)->operator()();
}
template<class T>
pRNG<typename T::result_type>pRNG_adapt(T&prng_instance){
return pRNG<typename T::result_type>((void*)(&prng_instance),pRNG_next<T>);
}
template<typename T,typename...args>
pRNG<typename T::result_type>pRNG_create(args...vv){
return pRNG_adapt(*(new T(vv...)));
}
template<typename T>
pRNG<typename T::result_type>pRNG_duplicate(pRNG<typename T::result_type>gg){
return pRNG_adapt(*(new T(gg.template instance<T>())));
}
template<typename T>
void pRNG_free(pRNG<typename T::result_type>gg){
delete (T*)(gg.data_region);
}
}
#endif
| unlicense |
rm-code/love-IDEA-plugin | love_0100/audio.lua | 526 | module('love.audio')
function getDistanceModel() end
function getDopplerScale() end
function getSourceCount() end
function getOrientation() end
function getPosition() end
function getVelocity() end
function getVolume() end
function newSource() end
function pause() end
function play() end
function resume() end
function rewind() end
function setDistanceModel() end
function setDopplerScale() end
function setOrientation() end
function setPosition() end
function setVelocity() end
function setVolume() end
function stop() end
| unlicense |
elnormous/ouzel | engine/audio/mixer/Data.hpp | 769 | // Ouzel by Elviss Strazdins
#ifndef OUZEL_AUDIO_MIXER_DATA_HPP
#define OUZEL_AUDIO_MIXER_DATA_HPP
#include <memory>
#include "Object.hpp"
namespace ouzel::audio::mixer
{
class Stream;
class Data: public Object
{
public:
Data() noexcept = default;
Data(std::uint32_t initChannels, std::uint32_t initSampleRate) noexcept:
channels{initChannels}, sampleRate{initSampleRate}
{
}
virtual std::unique_ptr<Stream> createStream() = 0;
auto getChannels() const noexcept { return channels; }
auto getSampleRate() const noexcept { return sampleRate; }
protected:
std::uint32_t channels = 0;
std::uint32_t sampleRate = 0;
};
}
#endif // OUZEL_AUDIO_MIXER_DATA_HPP
| unlicense |
amounir86/amounir86-2011-elections | voter-info/shapes/json/205_2615.js | 6362 | GoogleElectionMap.shapeReady({name:"205_2615",type:"state",state:"205_2615",bounds:[],centroid:[],shapes:[
{points:[
{x:32.1777917019685,y: 26.1031848443499}
,
{x:32.1780157397597,y: 26.103115932385}
,
{x:32.1781421104793,y: 26.1033390570173}
,
{x:32.1799916301116,y: 26.102765569028}
,
{x:32.1879139920243,y: 26.1003087258643}
,
{x:32.1921666456821,y: 26.0991652402263}
,
{x:32.1919673475093,y: 26.0987457566596}
,
{x:32.1914099844044,y: 26.0975725963787}
,
{x:32.1906482727334,y: 26.0959692694191}
,
{x:32.1922503117441,y: 26.0946726306793}
,
{x:32.1910039858343,y: 26.0928161535592}
,
{x:32.1890712827332,y: 26.0933571289185}
,
{x:32.1861864985785,y: 26.0891806352744}
,
{x:32.1849562304372,y: 26.0892925297476}
,
{x:32.1839196811767,y: 26.0886158884973}
,
{x:32.1826841062549,y: 26.0878093077122}
,
{x:32.1828673413398,y: 26.0867577440258}
,
{x:32.1839802751948,y: 26.0865021900334}
,
{x:32.1838588255879,y: 26.086376986097}
,
{x:32.1833753171164,y: 26.0858785271945}
,
{x:32.177761608596,y: 26.0800907735892}
,
{x:32.1771904326512,y: 26.0795611805777}
,
{x:32.1793530818725,y: 26.078346330702}
,
{x:32.1819956073646,y: 26.0763007372013}
,
{x:32.1842434415113,y: 26.0745605834478}
,
{x:32.1843208402309,y: 26.0745062280771}
,
{x:32.1874920118627,y: 26.072279100055}
,
{x:32.1895949298546,y: 26.0708021297993}
,
{x:32.1914139973026,y: 26.0690322354702}
,
{x:32.1916482768379,y: 26.0692026558442}
,
{x:32.1952390878405,y: 26.0643119478051}
,
{x:32.1944449630036,y: 26.0638363421534}
,
{x:32.1937413751692,y: 26.0634149509289}
,
{x:32.1932215545357,y: 26.0628813423886}
,
{x:32.1926801145502,y: 26.0610137709081}
,
{x:32.1944296977472,y: 26.0600711504642}
,
{x:32.1971856718393,y: 26.0587583428508}
,
{x:32.1956481772666,y: 26.0565686779389}
,
{x:32.1928826954189,y: 26.056343835418}
,
{x:32.1914209640624,y: 26.0547796749423}
,
{x:32.18314028882,y: 26.0493984987155}
,
{x:32.1672483982046,y: 26.0486734115659}
,
{x:32.1737048434342,y: 26.0397598080108}
,
{x:32.1758667640569,y: 26.0367747574448}
,
{x:32.1770203522829,y: 26.0358277191615}
,
{x:32.1830211675074,y: 26.0340516200821}
,
{x:32.1858475130645,y: 26.0332149843142}
,
{x:32.1869436349429,y: 26.0328683679756}
,
{x:32.185066975249,y: 26.0302265921233}
,
{x:32.1887387369524,y: 26.0274106812191}
,
{x:32.198897778044,y: 26.022475668542}
,
{x:32.1987739574338,y: 26.0216962324241}
,
{x:32.1964016232029,y: 26.0185158514923}
,
{x:32.1985869194539,y: 26.0166903243044}
,
{x:32.1973136791928,y: 26.0149082518715}
,
{x:32.1965823401185,y: 26.0138846141604}
,
{x:32.1953249869662,y: 26.0121246714635}
,
{x:32.192126870906,y: 26.0085510259042}
,
{x:32.1980957594822,y: 26.0047302040283}
,
{x:32.1970040305811,y: 26.0030820796463}
,
{x:32.1950242320695,y: 26.0011555685598}
,
{x:32.1931956839321,y: 25.9986324534689}
,
{x:32.1902607191739,y: 25.9990805336439}
,
{x:32.1892582154666,y: 25.9937172600914}
,
{x:32.1882351132992,y: 25.9925827899492}
,
{x:32.1882820969227,y: 25.9925627232187}
,
{x:32.1879697771972,y: 25.9926155533455}
,
{x:32.1860417926143,y: 25.988374957139}
,
{x:32.1863542192458,y: 25.9882219369098}
,
{x:32.1656656848243,y: 25.9648513905027}
,
{x:32.1419364051849,y: 25.9777935293669}
,
{x:32.1048443683713,y: 25.995624935983}
,
{x:32.058155518848,y: 26.0259351664029}
,
{x:32.0756611055424,y: 26.0423692188232}
,
{x:32.0753874857802,y: 26.0425028948691}
,
{x:32.0850478175879,y: 26.0513531974734}
,
{x:32.0849154927363,y: 26.0515593255466}
,
{x:32.0913527773147,y: 26.055844956269}
,
{x:32.0990524958791,y: 26.0600446440031}
,
{x:32.1023309086037,y: 26.0618325823374}
,
{x:32.0991976975633,y: 26.0655289810067}
,
{x:32.0985632743273,y: 26.0662774057434}
,
{x:32.0952140779362,y: 26.0686955221002}
,
{x:32.0991390645331,y: 26.0726741758188}
,
{x:32.1028524657345,y: 26.0687305837618}
,
{x:32.1033891893804,y: 26.0685745875809}
,
{x:32.103401460222,y: 26.0685710214631}
,
{x:32.1037964622182,y: 26.0688705035215}
,
{x:32.1081489019524,y: 26.0721702531937}
,
{x:32.1099199976148,y: 26.0735128945108}
,
{x:32.1130207723074,y: 26.0707033869393}
,
{x:32.1142301920463,y: 26.0712533762467}
,
{x:32.117462482515,y: 26.0746775400896}
,
{x:32.1182523030569,y: 26.07551420376}
,
{x:32.1144482022312,y: 26.0784429896965}
,
{x:32.1116373688539,y: 26.0808750689291}
,
{x:32.1131747741267,y: 26.083349090435}
,
{x:32.1158718659991,y: 26.0864308273039}
,
{x:32.1186829838404,y: 26.0891314863031}
,
{x:32.1205072171402,y: 26.0914254743717}
,
{x:32.122458487929,y: 26.0938790815449}
,
{x:32.1206004516727,y: 26.0950838480192}
,
{x:32.1179253687775,y: 26.0956179202666}
,
{x:32.1159057026461,y: 26.0969059991965}
,
{x:32.1158080020494,y: 26.0971587309124}
,
{x:32.1166575019369,y: 26.0977414699094}
,
{x:32.1170920852609,y: 26.0974815985894}
,
{x:32.117463737412,y: 26.0974984505025}
,
{x:32.1179481053039,y: 26.0978111152387}
,
{x:32.1180559617935,y: 26.097730635863}
,
{x:32.118823250461,y: 26.0971581153188}
,
{x:32.1198513101211,y: 26.0977777340692}
,
{x:32.118532287094,y: 26.0995619475938}
,
{x:32.1196312360338,y: 26.1002242808818}
,
{x:32.1208151610316,y: 26.1006294413232}
,
{x:32.122565914925,y: 26.1008920622913}
,
{x:32.1226409882406,y: 26.0998119256959}
,
{x:32.1231714239299,y: 26.0982435020259}
,
{x:32.1239989467185,y: 26.0957965523043}
,
{x:32.1245954003229,y: 26.0940327981959}
,
{x:32.1246260234178,y: 26.0926702319834}
,
{x:32.1242996955199,y: 26.09209340781}
,
{x:32.1329880227338,y: 26.0848412714639}
,
{x:32.1348629526255,y: 26.0830015270215}
,
{x:32.135372437987,y: 26.0829161965232}
,
{x:32.1395572445116,y: 26.082215232471}
,
{x:32.1396961080453,y: 26.0822867341421}
,
{x:32.1403691516502,y: 26.0821098673904}
,
{x:32.145888853444,y: 26.0806592226212}
,
{x:32.1497532565825,y: 26.079643466853}
,
{x:32.151689087726,y: 26.0788707274653}
,
{x:32.1560057113256,y: 26.0771475048213}
,
{x:32.1591477798382,y: 26.0802006708012}
,
{x:32.1609083362041,y: 26.0822581219066}
,
{x:32.1619019795384,y: 26.0840836135549}
,
{x:32.1620480195259,y: 26.0839985492825}
,
{x:32.1628398321977,y: 26.0866872073608}
,
{x:32.163508307618,y: 26.088956964012}
,
{x:32.167747762987,y: 26.0930062964121}
,
{x:32.1687738427425,y: 26.0922396054301}
,
{x:32.1691043825949,y: 26.0929953080402}
,
{x:32.1717785907979,y: 26.0955404330722}
,
{x:32.1730694720315,y: 26.0954132657929}
,
{x:32.1765499963587,y: 26.1010435848071}
,
{x:32.1772476345042,y: 26.1033521885208}
,
{x:32.1777917019685,y: 26.1031848443499}
]}
]})
| unlicense |
shaabans/simple-android-image-picker | src/com/polkadotninja/util/AndroidTools.java | 2431 | package com.polkadotninja.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.ImageView;
public class AndroidTools {
public static void setPic(Context activity, Uri currentPhotoUri, ImageView imageView) {
setPic(getRealPathFromURI(activity, currentPhotoUri), imageView);
}
public static void setPic(String currentPhotoPath, ImageView imageView) {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
}
public static Bitmap getBitmapFromCameraData(Intent data, Activity context){
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return BitmapFactory.decodeFile(picturePath);
}
public static String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
| unlicense |
bsielski/fantasy-name-generator | group.js | 1234 | function generateGroupGUI(groupLabel) {
const element = generateElement("section", {class: "group-box"})
const header = generateElement("div", {textNode: groupLabel, class: "group-box__header"})
const body = generateElement("div", {class: "group-box__body"})
element.appendChild(header)
element.appendChild(body)
const left = generateElement("div", {class: "group-box__column"})
const right = generateElement("div", {class: "group-box__column"})
body.appendChild(left)
body.appendChild(right)
return element
}
class Group {
constructor(groupLabel, lefts, rights) {
this._label = groupLabel
this._lefts = lefts
this._rights = rights
this._uiElement = generateGroupGUI(groupLabel)
this.addNamesetElements()
this._nameSets = lefts.concat(rights)
}
get uiElement() {
return this._uiElement
}
get label() {
return this._label
}
get nameSets() {
return this._nameSets
}
addNamesetElements() {
this._lefts.forEach( nameset => {
this.uiElement.childNodes[1].childNodes[0].appendChild(nameset.uiElement)
})
this._rights.forEach( nameset => {
this.uiElement.childNodes[1].childNodes[1].appendChild(nameset.uiElement)
})
}
}
| unlicense |
PartyPlanner64/PartyPlanner64 | src/audio/ALKeyMap.ts | 713 | export class ALKeyMap {
private __type: string = "ALKey";
public velocityMin!: number;
public velocityMax!: number;
public keyMin!: number;
public keyMax!: number;
public keyBase!: number;
public detune!: number;
constructor(B1view: DataView, keymapOffset: number) {
this._extract(B1view, keymapOffset);
}
_extract(B1view: DataView, keymapOffset: number) {
this.velocityMin = B1view.getUint8(keymapOffset);
this.velocityMax = B1view.getUint8(keymapOffset + 1);
this.keyMin = B1view.getUint8(keymapOffset + 2);
this.keyMax = B1view.getUint8(keymapOffset + 3);
this.keyBase = B1view.getUint8(keymapOffset + 4);
this.detune = B1view.getInt8(keymapOffset + 5);
}
} | unlicense |
Hoverbear/rust-rosetta | tasks/holidays-related-to-easter/src/main.rs | 1604 | use std::ops::Add;
use chrono::{prelude::*, Duration};
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_wrap)]
fn get_easter_day(year: u32) -> chrono::NaiveDate {
let k = (f64::from(year) / 100.).floor();
let d = (19 * (year % 19)
+ ((15 - ((13. + 8. * k) / 25.).floor() as u32 + k as u32 - (k / 4.).floor() as u32) % 30))
% 30;
let e =
(2 * (year % 4) + 4 * (year % 7) + 6 * d + ((4 + k as u32 - (k / 4.).floor() as u32) % 7))
% 7;
let (month, day) = match d {
29 if e == 6 => (4, 19),
28 if e == 6 => (4, 18),
_ if d + e < 10 => (3, 22 + d + e),
_ => (4, d + e - 9),
};
NaiveDate::from_ymd(year as i32, month, day)
}
fn main() {
let holidays = vec![
("Easter", Duration::days(0)),
("Ascension", Duration::days(39)),
("Pentecost", Duration::days(49)),
("Trinity", Duration::days(56)),
("Corpus Christi", Duration::days(60)),
];
for year in (400..=2100).step_by(100).chain(2010..=2020) {
print!("{}: ", year);
for (name, offset) in &holidays {
print!(
"{}: {}, ",
name,
get_easter_day(year).add(*offset).format("%a %d %h")
);
}
println!();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_easter_day() {
assert_eq!(NaiveDate::from_ymd(1777, 3, 30), get_easter_day(1777));
assert_eq!(NaiveDate::from_ymd(2021, 4, 4), get_easter_day(2021));
}
}
| unlicense |
sangshub/55231 | Client/Logo.cpp | 1927 | #include "stdafx.h"
#include "Logo.h"
#include "SceneMgr.h"
#include "TextureMgr.h"
#include "Device.h"
#include "TimeMgr.h"
CLogo::CLogo()
{
}
CLogo::~CLogo()
{
Release();
}
HRESULT CLogo::Initialize()
{
m_tFrame.fCnt = 2;
m_tFrame.fMax = 5;
m_tFrame.fFrame = 0;
m_pDevice->SoundPlay(TEXT("Menu"), 1);
return S_OK;
}
void CLogo::Progress()
{
FrameMove();
if(GetAsyncKeyState(VK_RETURN) & 0x0001)
NextStage();
if(GetAsyncKeyState('G') & 0x0001)
ReStage();
}
void CLogo::Render()
{
m_pDevice->GetDevice()->Clear(0, NULL
, D3DCLEAR_STENCIL | D3DCLEAR_ZBUFFER | D3DCLEAR_TARGET
, D3DCOLOR_ARGB(255, 0, 0, 0), 1.f, 6);
m_pDevice->GetDevice()->BeginScene();
m_pDevice->GetSprite()->Begin(D3DXSPRITE_ALPHABLEND);
m_pDevice->GetDevice()->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DX_FILTER_NONE);
const TEXINFO* pTexInfo = m_pTextureMgr->GetTexture(TEXT("Loading"), TEXT("Normal"), TEXT(""), (int)m_tFrame.fFrame);
if(pTexInfo == NULL)
return;
D3DXMATRIX matTrans;
D3DXMatrixTranslation(&matTrans, (float)WINCX * 0.5f, (float)WINCY * 0.5f, 0.f);
m_pDevice->GetSprite()->SetTransform(&matTrans);
m_pDevice->GetSprite()->Draw(pTexInfo->pTexture, NULL,
&D3DXVECTOR3(float(pTexInfo->ImgInfo.Width>>1), float(pTexInfo->ImgInfo.Height>>1), 0.f), NULL, D3DCOLOR_ARGB(255, 255, 255, 255));
D3DXMatrixTranslation(&matTrans, 0.f, 0.f, 0.f);
m_pDevice->GetSprite()->SetTransform(&matTrans);
m_pDevice->GetSprite()->End();
m_pDevice->GetDevice()->EndScene();
m_pDevice->GetDevice()->Present(NULL, NULL, NULL, NULL);
}
void CLogo::Release()
{
m_pDevice->SoundStop(TEXT("Menu"));
}
void CLogo::FrameMove(void)
{
m_tFrame.fFrame += m_tFrame.fCnt * GETTIME;
if(m_tFrame.fFrame > m_tFrame.fMax)
m_tFrame.fFrame = 0.f;
}
void CLogo::NextStage()
{
m_pSceneMgr->SetSceneChange(SCENE_TUTORIAL);
}
void CLogo::ReStage()
{
m_pSceneMgr->SetSceneChange(SCENE_LOGO);
}
void CLogo::StopBgm()
{
} | unlicense |
LouisT/MetaInfo | apis/enabled/deviantartcom.js | 385 | /*
MetaInfo - Louis T. <[email protected]>
https://github.com/LouisT/MetaInfo
For more information on oEmbed visit http://oembed.com/
*/
module.exports = {
url: 'http://backend.deviantart.com/oembed?url={:id}',
regex: /(?:https?:\/\/)(?:.*\.)?(fav\.me|sta\.sh|deviantart\.com)\/(?:.[^\?]+)/i,
fullurl: true,
shortcuts: ['dart','deviant','deviantart'],
};
| unlicense |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.