code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
* 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.scanner.repository;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.bootstrap.ScannerProperties;
import org.sonar.scanner.rule.QualityProfiles;
import org.springframework.context.annotation.Bean;
public class QualityProfilesProvider {
private static final Logger LOG = Loggers.get(QualityProfilesProvider.class);
private static final String LOG_MSG = "Load quality profiles";
@Bean("QualityProfiles")
public QualityProfiles provide(QualityProfileLoader loader, ScannerProperties props) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
QualityProfiles profiles = new QualityProfiles(loader.load(props.getProjectKey()));
profiler.stopInfo();
return profiles;
}
}
| SonarSource/sonarqube | sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/QualityProfilesProvider.java | Java | lgpl-3.0 | 1,663 |
using System;
using System.Runtime.InteropServices;
using NvAPIWrapper.Native.Helpers;
using NvAPIWrapper.Native.Interfaces;
namespace NvAPIWrapper.Native.GPU.Structures
{
/// <summary>
/// Holds information regarding a piecewise linear RGB control method
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct IlluminationZoneControlDataPiecewiseLinearRGB : IInitializable
{
private const int NumberColorEndPoints = 2;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = NumberColorEndPoints)]
internal IlluminationZoneControlDataManualRGBParameters[] _EndPoints;
internal IlluminationZoneControlDataPiecewiseLinear _PiecewiseLinearData;
/// <summary>
/// Creates a new instance of <see cref="IlluminationZoneControlDataPiecewiseLinearRGB" />.
/// </summary>
/// <param name="endPoints">The list of RGB piecewise function endpoints.</param>
/// <param name="piecewiseLinearData">The piecewise function settings.</param>
public IlluminationZoneControlDataPiecewiseLinearRGB(
IlluminationZoneControlDataManualRGBParameters[] endPoints,
IlluminationZoneControlDataPiecewiseLinear piecewiseLinearData)
{
if (endPoints?.Length != NumberColorEndPoints)
{
throw new ArgumentOutOfRangeException(nameof(endPoints));
}
this = typeof(IlluminationZoneControlDataPiecewiseLinearRGB)
.Instantiate<IlluminationZoneControlDataPiecewiseLinearRGB>();
_PiecewiseLinearData = piecewiseLinearData;
Array.Copy(endPoints, 0, _EndPoints, 0, endPoints.Length);
}
/// <summary>
/// Gets the piecewise function settings
/// </summary>
public IlluminationZoneControlDataPiecewiseLinear PiecewiseLinearData
{
get => _PiecewiseLinearData;
}
/// <summary>
/// Gets the list of RGB function endpoints
/// </summary>
public IlluminationZoneControlDataManualRGBParameters[] EndPoints
{
get => _EndPoints;
}
}
} | falahati/NvAPIWrapper | NvAPIWrapper/Native/GPU/Structures/IlluminationZoneControlDataPiecewiseLinearRGB.cs | C# | lgpl-3.0 | 2,194 |
#include <Guirlande.h>
static int h;
long EffectShade(long step) {
if (step == 0) {
h = 17;
}
for(byte i = 0; i < STRIP_LEN; i++) {
stripSetHL(i, h, (i+1) * 3);
}
stripUpdate();
h = h * 4;
return -1;
}
| piif/Guirlande | EffectShade.cpp | C++ | lgpl-3.0 | 216 |
/* Sound_enhance.cpp
*
* Copyright (C) 1992-2011 Paul Boersma
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* pb 2002/07/16 GPL
* pb 2004/11/22 simplified Sound_to_Spectrum ()
* pb 2007/01/28 made compatible with stereo sounds (by rejecting them)
* pb 2007/07/22 renamed the overlap-add method in such a way that it does not sound like a trademark for diphone concatenation
* pb 2008/01/19 double
* pb 2011/06/07 C++
*/
#include "Manipulation.h"
#include "Sound_to_Pitch.h"
#include "Pitch_to_PitchTier.h"
#include "Pitch_to_PointProcess.h"
#include "Sound_and_Spectrum.h"
Sound Sound_lengthen_overlapAdd (Sound me, double fmin, double fmax, double factor) {
try {
if (my ny > 1)
Melder_throw ("Overlap-add works only on mono sounds.");
autoSound sound = Data_copy (me);
Vector_subtractMean (sound.peek());
autoPitch pitch = Sound_to_Pitch (sound.peek(), 0.8 / fmin, fmin, fmax);
autoPointProcess pulses = Sound_Pitch_to_PointProcess_cc (sound.peek(), pitch.peek());
autoPitchTier pitchTier = Pitch_to_PitchTier (pitch.peek());
autoDurationTier duration = DurationTier_create (my xmin, my xmax);
RealTier_addPoint (duration.peek(), 0.5 * (my xmin + my xmax), factor);
autoSound thee = Sound_Point_Pitch_Duration_to_Sound (sound.peek(), pulses.peek(), pitchTier.peek(), duration.peek(), 1.5 / fmin);
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": not lengthened.");
}
}
Sound Sound_deepenBandModulation (Sound me, double enhancement_dB,
double flow, double fhigh, double slowModulation, double fastModulation, double bandSmoothing)
{
try {
autoSound thee = Data_copy (me);
double maximumFactor = pow (10, enhancement_dB / 20), alpha = sqrt (log (2.0));
double alphaslow = alpha / slowModulation, alphafast = alpha / fastModulation;
for (long channel = 1; channel <= my ny; channel ++) {
autoSound channelSound = Sound_extractChannel (me, channel);
autoSpectrum orgspec = Sound_to_Spectrum (channelSound.peek(), TRUE);
/*
* Keep the part of the sound that is outside the filter bank.
*/
autoSpectrum spec = Data_copy (orgspec.peek());
Spectrum_stopHannBand (spec.peek(), flow, fhigh, bandSmoothing);
autoSound filtered = Spectrum_to_Sound (spec.peek());
long n = thy nx;
double *amp = thy z [channel];
for (long i = 1; i <= n; i ++) amp [i] = filtered -> z [1] [i];
autoMelderProgress progress (L"Deepen band modulation...");
double fmin = flow;
while (fmin < fhigh) {
/*
* Take a one-bark frequency band.
*/
double fmid_bark = NUMhertzToBark (fmin) + 0.5, ceiling;
double fmax = NUMbarkToHertz (NUMhertzToBark (fmin) + 1);
if (fmax > fhigh) fmax = fhigh;
Melder_progress (fmin / fhigh, L"Band: ", Melder_fixed (fmin, 0), L" ... ", Melder_fixed (fmax, 0), L" Hz");
NUMmatrix_copyElements (orgspec -> z, spec -> z, 1, 2, 1, spec -> nx);
Spectrum_passHannBand (spec.peek(), fmin, fmax, bandSmoothing);
autoSound band = Spectrum_to_Sound (spec.peek());
/*
* Compute a relative intensity contour.
*/
autoSound intensity = Data_copy (band.peek());
n = intensity -> nx;
amp = intensity -> z [1];
for (long i = 1; i <= n; i ++) amp [i] = 10 * log10 (amp [i] * amp [i] + 1e-6);
autoSpectrum intensityFilter = Sound_to_Spectrum (intensity.peek(), TRUE);
n = intensityFilter -> nx;
for (long i = 1; i <= n; i ++) {
double frequency = intensityFilter -> x1 + (i - 1) * intensityFilter -> dx;
double slow = alphaslow * frequency, fast = alphafast * frequency;
double factor = exp (- fast * fast) - exp (- slow * slow);
intensityFilter -> z [1] [i] *= factor;
intensityFilter -> z [2] [i] *= factor;
}
intensity.reset (Spectrum_to_Sound (intensityFilter.peek()));
n = intensity -> nx;
amp = intensity -> z [1];
for (long i = 1; i <= n; i ++) amp [i] = pow (10, amp [i] / 2);
/*
* Clip to maximum enhancement.
*/
ceiling = 1 + (maximumFactor - 1.0) * (0.5 - 0.5 * cos (NUMpi * fmid_bark / 13));
for (long i = 1; i <= n; i ++) amp [i] = 1 / (1 / amp [i] + 1 / ceiling);
n = thy nx;
amp = thy z [channel];
for (long i = 1; i <= n; i ++) amp [i] += band -> z [1] [i] * intensity -> z [1] [i];
fmin = fmax;
}
}
Vector_scale (thee.peek(), 0.99);
/* Truncate. */
thy xmin = my xmin;
thy xmax = my xmax;
thy nx = my nx;
thy x1 = my x1;
return thee.transfer();
} catch (MelderError) {
Melder_throw (me, ": band modulation not deepened.");
}
}
/* End of file Sound_enhance.cpp */
| PeterWolf-tw/NeoPraat | sources_5401/fon/Sound_enhance.cpp | C++ | lgpl-3.0 | 5,230 |
package quickml.supervised.classifier.twoStageModel;
import com.google.common.collect.Lists;
import quickml.data.AttributesMap;
import quickml.data.ClassifierInstance;
import quickml.supervised.PredictiveModelBuilder;
import quickml.supervised.classifier.Classifier;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* Created by alexanderhawk on 10/7/14.
*/
public class TwoStageModelBuilder implements PredictiveModelBuilder<TwoStageClassifier, ClassifierInstance> {
PredictiveModelBuilder< ? extends Classifier, ClassifierInstance> wrappedModelBuilder1;
PredictiveModelBuilder<? extends Classifier, ClassifierInstance> wrappedModelBuilder2;
public TwoStageModelBuilder(PredictiveModelBuilder< ? extends Classifier, ClassifierInstance> wrappedModelBuilder1,
PredictiveModelBuilder<? extends Classifier, ClassifierInstance> wrappedModelBuilder2) {
this.wrappedModelBuilder1 = wrappedModelBuilder1;
this.wrappedModelBuilder2 = wrappedModelBuilder2;
}
@Override
public TwoStageClassifier buildPredictiveModel(Iterable<ClassifierInstance> trainingData) {
List<ClassifierInstance> stage1Data = Lists.newArrayList();
List<ClassifierInstance> stage2Data = Lists.newArrayList();
List<ClassifierInstance> validationData = Lists.newArrayList();
for (ClassifierInstance instance : trainingData) {
if (instance.getLabel().equals("positive-both")) {
stage1Data.add(new ClassifierInstance(instance.getAttributes(), 1.0));
stage2Data.add(new ClassifierInstance(instance.getAttributes(), 1.0));
validationData.add(new ClassifierInstance(instance.getAttributes(), 1.0));
} else if (instance.getLabel().equals("positive-first")) {
stage1Data.add(new ClassifierInstance(instance.getAttributes(), 1.0));
stage2Data.add(new ClassifierInstance(instance.getAttributes(), 0.0));
validationData.add(new ClassifierInstance(instance.getAttributes(), 0.0));
} else if (instance.getLabel().equals("negative")) {
stage1Data.add(new ClassifierInstance(instance.getAttributes(), 0.0));
validationData.add(new ClassifierInstance(instance.getAttributes(), 0.0));
} else {
throw new RuntimeException("missing valid label");
}
}
Classifier c1 = wrappedModelBuilder1.buildPredictiveModel(stage1Data);
Classifier c2 = wrappedModelBuilder2.buildPredictiveModel(stage2Data);
return new TwoStageClassifier(c1, c2);
}
@Override
public void updateBuilderConfig(Map<String, Serializable> config) {
wrappedModelBuilder1.updateBuilderConfig(config);
wrappedModelBuilder2.updateBuilderConfig(config);
}
}
| lenovor/quickml | src/main/java/quickml/supervised/classifier/twoStageModel/TwoStageModelBuilder.java | Java | lgpl-3.0 | 2,871 |
/*
Copyright (C) 2010 Zone Five Software
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
// Author: Aaron Averill
using System;
using System.Collections.Generic;
using System.Text;
namespace ZoneFiveSoftware.SportTracks.Device.Globalsat
{
public class GhPacketBase
{
//Public properties - Mostly response, send handles PacketData
public byte CommandId;
public Int16 PacketLength;
//PacketData contains the usefuldata, not everything to send
public byte[] PacketData;
//Only used when receiving - sending is only included in the sent data
//Not stored now
//public byte Checksum;
public void InitPacket(byte CommandId, Int16 PacketLength)
{
this.CommandId = CommandId;
this.PacketLength = PacketLength;
this.PacketData = new byte[PacketLength];
for (int i = 0; i < this.PacketData.Length; i++ )
{
this.PacketData[i] = 0;
}
}
//The Gloabalsat specs does not explicitly write that the format is same for all
public const byte CommandWhoAmI = 0xBF;
public const byte CommandGetSystemInformation = 0x85;
public const byte CommandGetSystemConfiguration = 0x86;
public const byte CommandSetSystemConfiguration = 0x96;
public const byte CommandSetSystemInformation = 0x98;
public const byte CommandGetScreenshot = 0x83;
public const byte CommandGetWaypoints = 0x77;
public const byte CommandSendWaypoint = 0x76;
public const byte CommandDeleteWaypoints = 0x75;
public const byte CommandSendRoute = 0x93;
public const byte CommandDeleteAllRoutes = 0x97;
public const byte CommandGetTrackFileHeaders = 0x78;
public const byte CommandGetTrackFileSections = 0x80;
public const byte CommandGetNextTrackSection = 0x81;
//public const byte CommandReGetLastSection = 0x82;
public const byte CommandId_FINISH = 0x8A;
public const byte CommandSendTrackStart = 0x90;
public const byte CommandSendTrackSection = 0x91;
public const byte CommandDeleteTracks = 0x79;
//505, 580, 625XT, determines info in the trackpackets at TrainHeaderCTypeOffset
public const byte HeaderTypeLaps = 0xAA;
public const byte HeaderTypeTrackPoints = 0x55;
//Certain appearing responses, likely more exists
public const byte ResponseInsuficientMemory = 0x95;
public const byte ResponseResendTrackSection = 0x92;
public const byte ResponseSendTrackFinish = 0x9A;
public class Header
{
public DateTime StartTime;
public Int32 TrackPointCount; //Int16 in all but 625XT
public TimeSpan TotalTime;
public Int32 TotalDistanceMeters;
public Int16 LapCount; //Not used in all
}
public class Train : Header
{
//public Int16 StartPointIndex=0;
//public Int16 EndPointIndex=0;
//public bool Multisport;
public Int16 TotalCalories = 0;
public double MaximumSpeed = 0;
public byte MaximumHeartRate = 0;
public byte AverageHeartRate = 0;
public Int16 TotalAscend = 0;
public Int16 TotalDescend = 0;
//public Int16 MinimumAltitude;
//public Int16 MaximumAltitude;
public Int16 AverageCadence = 0;
public Int16 MaximumCadence = 0;
public Int16 AveragePower = 0;
public Int16 MaximumPower = 0;
//byte Sport1;
//byte Sport2;
//byte Sport3;
//byte Sport4;
//byte Sport5;
//public Int16 AverageTemperature; //GB580P
//public Int16 MaximumTemperature;
//public Int16 MaximumTemperature;
public IList<TrackPoint> TrackPoints = new List<TrackPoint>();
public IList<Lap> Laps = new List<Lap>();
//data related to the import, for instance if start date is changed
public string Comment = "";
}
public class TrackFileHeader : Header
{
public Int32 TrackPointIndex;
}
public class Lap
{
public TimeSpan EndTime;
public TimeSpan LapTime;
public Int32 LapDistanceMeters;
public Int16 LapCalories;
public double MaximumSpeed; //Int16 for some devices
public byte MaximumHeartRate;
public byte AverageHeartRate;
public Int16 MinimumAltitude;
public Int16 MaximumAltitude;
public Int16 AverageCadence;
public Int16 MaximumCadence;
public Int16 AveragePower;
public Int16 MaximumPower;
//public bool Multisport;
//public Int16 AverageTemperature; //GB580P
//public Int16 MaximumTemperature;
//public Int16 MaximumTemperature;
// public Int16 StartPointIndex;
// public Int16 EndPointIndex;
}
//Superset of all trackpoints
public class TrackPoint
{
//Same in all
public double Latitude; //4bit, Degrees * 1000000
public double Longitude; //4bit, Degrees * 1000000
//Int32 in GB580, Int16 in GH625XT, GH505, GH625, GH615
public Int32 Altitude; // Meters
//Int32 in GH625XT, Int16 in GB580, GH505, GH625, GH615
public double Speed=0; //4bit, Kilometers per hour * 100
public Byte HeartRate=0;
//Int32 in GH625XT, GB580, GH505, Int16 in GH625, GH615
public double IntervalTime=0; // Seconds * 10
//Int16 in GH625XT, GB580, GH505, (but not available?)
public Int16 Power=0; // Power, unknown units
//Int16 in GH625XT, GB580 (but not available, unknown use)
public Int16 PowerCadence=0; // unknown units
//Int16 in GH625XT, GB580, GH505, (but not available?)
public Int16 Cadence=0; // Cadence, RPM - revolutions per minute
public Int16 Temperature=0x7fff; //GB580P
}
public byte[] ConstructPayload(bool bigEndianPacketLength)
{
byte[] data = new byte[5 + this.PacketLength];
data[0] = 0x02;
//Add CommandId to length, always big endian
//Write(true, data, 1, (Int16)(this.PacketLength + 1));
byte[] b = BitConverter.GetBytes((Int16)(this.PacketLength + 1));
if (bigEndianPacketLength)
{
data[1] = b[1];
data[2] = b[0];
}
else
{
//Only for the 561
data[1] = b[0];
data[2] = b[1];
}
data[3] = this.CommandId;
for (int i = 0; i < this.PacketLength; i++)
{
data[4 + i] = this.PacketData[i];
}
data[this.PacketLength + 4] = GetCrc(false);
return data;
}
private byte GetCrc(bool received)
{
byte checksum = 0;
int len = this.PacketLength;
if (!received)
{
//For sent packets, include the packetid
len++;
}
byte[] b = BitConverter.GetBytes(len);
checksum ^= b[0];
checksum ^= b[1];
if (!received)
{
checksum ^= this.CommandId;
}
for (int i = 0; i < this.PacketLength; i++)
{
checksum ^= this.PacketData[i];
}
return checksum;
}
public bool ValidResponseCrc(byte checksum)
{
return (GetCrc(true) == checksum);
}
/// <summary>
/// Read a six byte representation of a date and time starting at the offset in the following format:
/// Year = 2000 + byte[0]
/// Month = byte[1]
/// Day = byte[2]
/// Hour = byte[3]
/// Minute = byte[4]
/// Second = byte[5]
/// </summary>
protected DateTime ReadDateTime(int offset)
{
return new DateTime(PacketData[offset + 0] + 2000, PacketData[offset + 1], PacketData[offset + 2], PacketData[offset + 3], PacketData[offset + 4], PacketData[offset + 5]);
}
protected int Write(int offset, DateTime t)
{
int year = (int)Math.Max(0, t.Year - 2000);
this.PacketData[offset+0] = (byte)year;
this.PacketData[offset+1] = (byte)t.Month;
this.PacketData[offset+2] = (byte)t.Day;
this.PacketData[offset+3] = (byte)t.Hour;
this.PacketData[offset+4] = (byte)t.Minute;
this.PacketData[offset+5] = (byte)t.Second;
return 6;
}
/// <summary>
/// Read a string starting at the offset.
/// </summary>
public string ByteArr2String(int startIndex, int length)
{
for (int i = startIndex; i < Math.Min(startIndex + length, PacketData.Length); i++)
{
if (PacketData[i] == 0x0)
{
length = i - startIndex;
break;
}
}
string str = UTF8Encoding.UTF8.GetString(PacketData, startIndex, length);
return str;
}
public int Write(int startIndex, int length, string s)
{
for (int j = 0; j < length; j++)
{
byte c = (byte)(j < s.Length ? s[j] : '\0');
this.PacketData[startIndex + j] = c;
}
//Ensure null termination
this.PacketData[startIndex + length - 1] = 0;
return length;
}
/// <summary>
/// Read a two byte integer starting at the offset.
/// </summary>
protected Int16 ReadInt16(int offset)
{
if (!IsLittleEndian)
{
return (Int16)((this.PacketData[offset] << 8) + this.PacketData[offset + 1]);
}
else
{
return BitConverter.ToInt16(this.PacketData, offset);
}
}
/// <summary>
/// Read a four byte integer starting at the offset.
/// </summary>
protected Int32 ReadInt32(int offset)
{
if (!IsLittleEndian)
{
return (this.PacketData[offset] << 24) + (this.PacketData[offset + 1] << 16) + (this.PacketData[offset + 2] << 8) + this.PacketData[offset + 3];
}
else
{
return BitConverter.ToInt32(this.PacketData, offset);
}
}
protected double ReadLatLon(int offset)
{
return ReadInt32(offset) / 1000000.0;
}
//Some static methods for standard field formats
static public Int32 ToGlobLatLon(double latlon)
{
return (int)Math.Round(latlon * 1000000);
}
static public Int16 ToGlobSpeed(double speed)
{
return (Int16)Math.Round(speed * 100 * 3.6);
}
static public double FromGlobSpeed(int speed)
{
return speed / 100.0 / 3.6;
}
static public Int32 ToGlobTime(double time)
{
return (Int32)Math.Round(time * 10);
}
static public Int16 ToGlobTime16(double time)
{
return (Int16)ToGlobTime(time);
}
static public double FromGlobTime(int time)
{
return time/10.0;
}
/// <summary>
/// Write a two byte integer starting at the offset.
/// </summary>
protected int Write(int offset, Int16 i)
{
return Write(offset, i, this.IsLittleEndian);
}
protected int Write(int offset, Int16 i, bool isLittleEndian)
{
byte[] b = BitConverter.GetBytes(i);
if (!isLittleEndian)
{
this.PacketData[offset + 0] = b[1];
this.PacketData[offset + 1] = b[0];
}
else
{
this.PacketData[offset + 0] = b[0];
this.PacketData[offset + 1] = b[1];
}
return 2;
}
/// <summary>
/// Write a four byte integer in little-endian format starting at the offset.
/// </summary>
//No overload to make sure correct
protected int Write32(int offset, Int32 i)
{
byte[] b = BitConverter.GetBytes(i);
if (!IsLittleEndian)
{
this.PacketData[offset + 0] = b[3];
this.PacketData[offset + 1] = b[2];
this.PacketData[offset + 2] = b[1];
this.PacketData[offset + 3] = b[0];
}
else
{
this.PacketData[offset + 0] = b[0];
this.PacketData[offset + 1] = b[1];
this.PacketData[offset + 2] = b[2];
this.PacketData[offset + 3] = b[3];
}
return 4;
}
//Note: The assumption is that the platform is LittleEndian
protected virtual bool IsLittleEndian { get { return false; } }
}
}
| xeonvs/globalsat-sporttracks-plugin | Device/GhPacketBase.cs | C# | lgpl-3.0 | 14,491 |
/**
* Kopernicus Planetary System Modifier
* ====================================
* Created by: - Bryce C Schroeder (bryce.schroeder@gmail.com)
* - Nathaniel R. Lewis (linux.robotdude@gmail.com)
*
* Maintained by: - Thomas P.
* - NathanKell
*
* Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace
* -------------------------------------------------------------
* 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 02110-1301 USA
*
* This library is intended to be used as a plugin for Kerbal Space Program
* which is copyright 2011-2014 Squad. Your usage of Kerbal Space Program
* itself is governed by the terms of its EULA, not the license above.
*
* https://kerbalspaceprogram.com
*/
using System;
namespace Kopernicus
{
namespace Configuration
{
/**
* Exception representing a missing field
**/
public class ParserTargetMissingException : Exception
{
public ParserTargetMissingException (string message) : base(message) { }
}
}
}
| HappyFaceIndustries/Kopernicus | Kopernicus/Configuration/Parser/Exceptions/ParserTargetMissingException.cs | C# | lgpl-3.0 | 1,776 |
/**
*
*/
package com.ihp;
/**
* @author Michael Maaser
*
*/
public class CalculationInLoop implements BenchmarkImplementation {
/* (non-Javadoc)
* @see com.ihp.TestImplementation#runTest(int)
*/
public void runTest(int times) {
for (;times>0;times--){
int a = 1;
for (int i = 1; i < 70; i++) {
a*=i;
}
}
}
/* (non-Javadoc)
* @see com.ihp.TestImplementation#getName()
*/
public String getName() {
return "Calculation 69! in a loop";
}
// public static void main(String[] args) {
// BenchmarkImplementation test = new CalculationInLoop();
// test.runTest(1);
// }
}
| RWTH-OS/ostfriesentee-examples | app/benchmark/java/com/ihp/CalculationInLoop.java | Java | lgpl-3.0 | 611 |
/*
* jesadido-poc
* Copyright (C) 2016 Stefan K. Baur
*
* Licensed under the GNU Lesser General Public License, Version 3.0 (LGPL-3.0)
* https://www.gnu.org/licenses/lgpl-3.0.txt
*/
package org.jesadido.poc.core.semantics.translating.en;
import java.util.Arrays;
import java.util.LinkedList;
import org.jesadido.poc.core.semantics.translating.TranslationResult;
import org.jesadido.poc.core.semantics.translating.TransletParameters;
import org.jesadido.poc.core.semantics.translating.Transletor;
import org.jesadido.poc.core.syntax.tokens.TokenType;
public final class EnTransletors {
private static final Transletor NOMINAL_TRANSLETOR = new Transletor()
.add(Arrays.asList(TokenType.SUBSTANTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getIndefinite(r.getTranslator(), p.getConcept(0), new LinkedList<>())))
.add(Arrays.asList(TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getIndefinite(r.getTranslator(), p.getConcept(0), p.getConcepts().subList(1, 2))))
.add(Arrays.asList(TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getIndefinite(r.getTranslator(), p.getConcept(0), p.getConcepts().subList(1, 3))))
.add(Arrays.asList(TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getIndefinite(r.getTranslator(), p.getConcept(0), p.getConcepts().subList(1, 4))))
.add(Arrays.asList(TokenType.ARTICLE, TokenType.SUBSTANTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getDefinite(r.getTranslator(), p.getConcept(0), p.getConcept(1), new LinkedList<>())))
.add(Arrays.asList(TokenType.ARTICLE, TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getDefinite(r.getTranslator(), p.getConcept(0), p.getConcept(1), p.getConcepts().subList(2, 3))))
.add(Arrays.asList(TokenType.ARTICLE, TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getDefinite(r.getTranslator(), p.getConcept(0), p.getConcept(1), p.getConcepts().subList(2, 4))))
.add(Arrays.asList(TokenType.ARTICLE, TokenType.SUBSTANTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR, TokenType.ADJECTIVE_SINGULAR), (TranslationResult r, TransletParameters p) -> r.setTranslation(EnUtils.getDefinite(r.getTranslator(), p.getConcept(0), p.getConcept(1), p.getConcepts().subList(2, 5))))
;
private EnTransletors() {
// A private utility class constructor
}
public static Transletor getNominalTransletor() {
return NOMINAL_TRANSLETOR;
}
}
| stefan-baur/jesadido-poc | src/main/java/org/jesadido/poc/core/semantics/translating/en/EnTransletors.java | Java | lgpl-3.0 | 3,102 |
namespace Microsoft.Web.Mvc.Resources {
using System.Globalization;
using System.Net;
using System.Net.Mime;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Resources;
/// <summary>
/// Returns the response in the format specified by the request. By default, supports returning the model
/// as a HTML view, XML and JSON.
/// If the response format requested is not supported, then the NotAcceptable status code is returned
/// </summary>
public class MultiFormatActionResult : ActionResult {
object model;
ContentType responseFormat;
HttpStatusCode statusCode;
public MultiFormatActionResult(object model, ContentType responseFormat)
: this(model, responseFormat, HttpStatusCode.OK) {
}
public MultiFormatActionResult(object model, ContentType responseFormat, HttpStatusCode statusCode) {
this.model = model;
this.responseFormat = responseFormat;
this.statusCode = statusCode;
}
public override void ExecuteResult(ControllerContext context) {
if (!TryExecuteResult(context, this.model, this.responseFormat)) {
throw new HttpException((int)HttpStatusCode.NotAcceptable, string.Format(CultureInfo.CurrentCulture, MvcResources.Resources_UnsupportedFormat, this.responseFormat));
}
}
public virtual bool TryExecuteResult(ControllerContext context, object model, ContentType responseFormat) {
if (!FormatManager.Current.CanSerialize(responseFormat)) {
return false;
}
context.HttpContext.Response.ClearContent();
context.HttpContext.Response.StatusCode = (int)this.statusCode;
FormatManager.Current.Serialize(context, model, responseFormat);
return true;
}
}
}
| consumentor/Server | trunk/tools/ASP.NET MVC 2/trunk/src/MvcFutures/Mvc/Resources/MultiFormatActionResult.cs | C# | lgpl-3.0 | 1,935 |
from pyactor.context import set_context, create_host, sleep, shutdown,\
serve_forever
class Someclass(object):
_tell = {'show_things'}
def __init__(self, op, thing):
self.things = [op, thing]
def show_things(self):
print(self.things)
if __name__ == '__main__':
set_context()
h = create_host()
params = ["hi", "you"]
# kparams = {"op":"hi", "thing":"you"}
# t = h.spawn('t', Someclass, *params)
t = h.spawn('t', Someclass, *["hi", "you"])
t.show_things()
shutdown()
| pedrotgn/pyactor | examples/initparams.py | Python | lgpl-3.0 | 539 |
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.batch;
import org.apache.commons.configuration.Configuration;
import org.picocontainer.Characteristics;
import org.picocontainer.MutablePicoContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.Plugins;
import org.sonar.api.resources.Project;
import org.sonar.api.utils.HttpDownloader;
import org.sonar.api.utils.IocContainer;
import org.sonar.api.utils.ServerHttpClient;
import org.sonar.batch.indexer.DefaultSonarIndex;
import org.sonar.core.plugin.JpaPluginDao;
import org.sonar.jpa.session.DatabaseSessionProvider;
import org.sonar.jpa.session.DriverDatabaseConnector;
import org.sonar.jpa.session.ThreadLocalDatabaseSessionFactory;
import java.net.URLClassLoader;
public class Batch {
private static final Logger LOG = LoggerFactory.getLogger(Batch.class);
private Configuration configuration;
private Object[] components;
public Batch(Configuration configuration, Object... components) {
this.configuration = configuration;
this.components = components;
}
public void execute() {
MutablePicoContainer container = null;
try {
container = buildPicoContainer();
container.start();
analyzeProjects(container);
} finally {
if (container != null) {
container.stop();
}
}
}
private void analyzeProjects(MutablePicoContainer container) {
// a child container is built to ensure database connector is up
MutablePicoContainer batchContainer = container.makeChildContainer();
batchContainer.as(Characteristics.CACHE).addComponent(ServerMetadata.class);
batchContainer.as(Characteristics.CACHE).addComponent(ProjectTree.class);
batchContainer.as(Characteristics.CACHE).addComponent(DefaultResourceCreationLock.class);
batchContainer.as(Characteristics.CACHE).addComponent(DefaultSonarIndex.class);
batchContainer.as(Characteristics.CACHE).addComponent(JpaPluginDao.class);
batchContainer.as(Characteristics.CACHE).addComponent(BatchPluginRepository.class);
batchContainer.as(Characteristics.CACHE).addComponent(Plugins.class);
batchContainer.as(Characteristics.CACHE).addComponent(ServerHttpClient.class);
batchContainer.as(Characteristics.CACHE).addComponent(HttpDownloader.class);
batchContainer.start();
ProjectTree projectTree = batchContainer.getComponent(ProjectTree.class);
DefaultSonarIndex index = batchContainer.getComponent(DefaultSonarIndex.class);
analyzeProject(batchContainer, index, projectTree.getRootProject());
// batchContainer is stopped by its parent
}
private MutablePicoContainer buildPicoContainer() {
MutablePicoContainer container = IocContainer.buildPicoContainer();
register(container, configuration);
URLClassLoader fullClassloader = RemoteClassLoader.createForJdbcDriver(configuration).getClassLoader();
// set as the current context classloader for hibernate, else it does not find the JDBC driver.
Thread.currentThread().setContextClassLoader(fullClassloader);
register(container, new DriverDatabaseConnector(configuration, fullClassloader));
register(container, ThreadLocalDatabaseSessionFactory.class);
container.as(Characteristics.CACHE).addAdapter(new DatabaseSessionProvider());
for (Object component : components) {
register(container, component);
}
return container;
}
private void register(MutablePicoContainer container, Object component) {
container.as(Characteristics.CACHE).addComponent(component);
}
private void analyzeProject(MutablePicoContainer container, DefaultSonarIndex index, Project project) {
for (Project module : project.getModules()) {
analyzeProject(container, index, module);
}
LOG.info("------------- Analyzing " + project.getName());
new ProjectBatch(container).execute(index, project);
}
}
| yangjiandong/appjruby | app-batch/src/main/java/org/sonar/batch/Batch.java | Java | lgpl-3.0 | 4,700 |
/*
* Copyright (c) 2008, 2011 Poesys Associates. All rights reserved.
*
* This file is part of Poesys-DB.
*
* Poesys-DB 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.
*
* Poesys-DB 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
* Poesys-DB. If not, see <http://www.gnu.org/licenses/>.
*/
package com.poesys.db.dao.delete;
import java.sql.PreparedStatement;
import com.poesys.db.dto.IDbDto;
import com.poesys.db.pk.IPrimaryKey;
/**
* SQL statement specification for deleting a standard object. The concrete
* subclass contains the SQL statement and an implementation of
* <code>IDeleteSql.getSql()</code> that calls the <code>getSql</code> method in
* this class:
*
* <pre>
* public class DeleteTestSql extends AbstractDeleteSql {
*
* private static final String SQL = "DELETE FROM Test WHERE ";
*
* public String getSql(IPrimaryKey key) {
* return super.getSql(key, SQL);
* }
* }
* </pre>
*
* @author Robert J. Muller
* @param <T> the DTO type
*/
public abstract class AbstractDeleteSql<T extends IDbDto> implements
IDeleteSql<T> {
/**
* A helper method that takes the SQL from the caller (usually a concrete
* subclass of this class) and builds a complete SQL statement by adding the
* key to the WHERE clause
*
* @param key the primary key to add to the WHERE clause
* @param sql the SQL statement
* @return a complete SQL statement
*/
public String getSql(IPrimaryKey key, String sql) {
StringBuilder builder = new StringBuilder(sql);
builder.append(key.getSqlWhereExpression(""));
return builder.toString();
}
@Override
public <P extends IDbDto> int setParams(PreparedStatement stmt, int next,
P dto) {
next = dto.getPrimaryKey().setParams(stmt, next);
return next;
}
}
| Poesys-Associates/poesys-db | poesys-db/src/com/poesys/db/dao/delete/AbstractDeleteSql.java | Java | lgpl-3.0 | 2,290 |
/*
* Copyright (C) 2005-2019 Alfresco Software Limited.
*
* This file is part of Gytheio
*
* Gytheio 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.
*
* Gytheio 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 Gytheio. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gytheio.content.handler;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.gytheio.content.ContentIOException;
import org.gytheio.content.ContentReference;
import org.gytheio.content.file.FileProvider;
import org.gytheio.content.file.FileProviderImpl;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class DelegatingContentHandlerImplTest
{
private ContentReferenceHandler handlerA;
private ContentReferenceHandler handlerB;
private FileContentReferenceHandler delegatingHandler;
private ContentReference contentReferenceFile1a;
private ContentReference contentReferenceFile1b;
private ContentReference contentReferenceFile1c;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() throws Exception
{
FileProvider fileProviderA = new FileProviderImpl("content-handler-a");
handlerA = new MockFileContentReferenceHandlerImpl("content-handler-a");
((FileContentReferenceHandlerImpl) handlerA).setFileProvider(fileProviderA);
FileProvider fileProviderB = new FileProviderImpl("content-handler-b");
handlerB = new MockFileContentReferenceHandlerImpl("content-handler-b");
((FileContentReferenceHandlerImpl) handlerB).setFileProvider(fileProviderB);
ArrayList<ContentReferenceHandler> delegates = new ArrayList<ContentReferenceHandler>();
delegates.add(handlerA);
delegates.add(handlerB);
delegatingHandler = new DelegatingContentHandlerImpl();
((DelegatingContentHandlerImpl) delegatingHandler).setDelegates(delegates);
contentReferenceFile1a = getTextReference("/content-handler-a/file-a-1.txt");
contentReferenceFile1b = getTextReference("/content-handler-b/file-b-1.txt");
contentReferenceFile1c = getTextReference("/content-handler-c/file-c-1.txt");
}
private ContentReference getTextReference(String testPath) throws URISyntaxException
{
return getContentReference(testPath, "text/plain");
}
private ContentReference getContentReference(String testPath, String mediaType) throws URISyntaxException
{
return new ContentReference(this.getClass().getResource(testPath).toURI().toString(), mediaType);
}
@Test
public void testIsAvailable()
{
assertTrue(delegatingHandler.isAvailable());
((FileContentReferenceHandlerImpl) handlerA).setFileProvider(null);
assertFalse(delegatingHandler.isAvailable());
}
@Test
public void testIsContentReferenceSupported()
{
assertTrue(delegatingHandler.isContentReferenceSupported(contentReferenceFile1a));
assertTrue(delegatingHandler.isContentReferenceSupported(contentReferenceFile1b));
assertFalse(delegatingHandler.isContentReferenceSupported(contentReferenceFile1c));
}
@Test
public void testIsContentReferenceExists()
{
assertTrue(delegatingHandler.isContentReferenceExists(contentReferenceFile1a));
assertTrue(delegatingHandler.isContentReferenceExists(contentReferenceFile1b));
thrown.expect(UnsupportedOperationException.class);
delegatingHandler.isContentReferenceExists(contentReferenceFile1c);
}
@Test
public void testCreateContentReference()
{
thrown.expect(UnsupportedOperationException.class);
delegatingHandler.createContentReference("testCreate.txt", "text/plain");
}
@Test
public void testGetFile() throws Exception
{
File sourceFile = delegatingHandler.getFile(contentReferenceFile1a, false);
assertTrue(sourceFile.exists());
}
@Test
public void testNonFileDelegate() throws Exception
{
MockEmptyContentReferenceHandlerImpl handlerC = new MockEmptyContentReferenceHandlerImpl();
ArrayList<ContentReferenceHandler> delegates = new ArrayList<ContentReferenceHandler>();
delegates.add(handlerA);
delegates.add(handlerB);
delegates.add(handlerC);
ContentReference contentReference = new ContentReference("mock://empty.txt", "text/plain");
thrown.expect(UnsupportedOperationException.class);
delegatingHandler.getFile(contentReference, false);
}
@Test
public void testGetInputStream() throws Exception
{
InputStream sourceInputStream = delegatingHandler.getInputStream(contentReferenceFile1a, false);
assertEquals(15, sourceInputStream.available());
}
@Test
public void testPutFile() throws Exception
{
File sourceFile = new File(this.getClass().getResource(
"/content-handler-a/file-a-1.txt").toURI());
String targetFolder = "/content-handler-a";
ContentReference targetContentReference = getTextReference(targetFolder);
targetContentReference.setUri(targetContentReference.getUri() + "/file-a-3.txt");
delegatingHandler.putFile(sourceFile, targetContentReference);
File targetFile = new File(new URI(targetContentReference.getUri()));
assertTrue(targetFile.exists());
}
@Test
public void testPutInputStream() throws Exception
{
InputStream sourceInputStream = (this.getClass().getResourceAsStream(
"/content-handler-a/file-a-1.txt"));
String targetFolder = "/content-handler-a";
ContentReference targetContentReference = getTextReference(targetFolder);
targetContentReference.setUri(targetContentReference.getUri() + "/file-a-4.txt");
delegatingHandler.putInputStream(sourceInputStream, targetContentReference);
File targetFile = new File(new URI(targetContentReference.getUri()));
assertTrue(targetFile.exists());
}
@Test
public void testDelete() throws Exception
{
File sourceFile = new File(this.getClass().getResource(
"/content-handler-b/file-b-1.txt").toURI());
ContentReference targetContentReferenceToDelete = getTextReference("/content-handler-b");
targetContentReferenceToDelete.setUri(targetContentReferenceToDelete.getUri() + "/file-b-3.txt");
delegatingHandler.putFile(sourceFile, targetContentReferenceToDelete);
File fileToDelete = new File(new URI(targetContentReferenceToDelete.getUri()));
assertTrue(fileToDelete.exists());
delegatingHandler.delete(targetContentReferenceToDelete);
assertFalse(fileToDelete.exists());
}
/**
* Test class that allows checking for specific paths
*/
public class MockFileContentReferenceHandlerImpl extends FileContentReferenceHandlerImpl
{
private String supportedUriPath;
public MockFileContentReferenceHandlerImpl(String supportedUriPath)
{
this.supportedUriPath = supportedUriPath;
}
@Override
public boolean isContentReferenceSupported(ContentReference contentReference)
{
if (contentReference == null)
{
return false;
}
return contentReference.getUri().contains(supportedUriPath);
}
}
/**
* Test class for non-file content references
*/
public class MockEmptyContentReferenceHandlerImpl implements ContentReferenceHandler
{
@Override
public boolean isContentReferenceSupported(ContentReference contentReference)
{
return contentReference.getUri().startsWith("mock:/");
}
@Override
public boolean isContentReferenceExists(ContentReference contentReference)
{
return true;
}
@Override
public ContentReference createContentReference(String fileName, String mediaType) throws ContentIOException
{
return null;
}
@Override
public InputStream getInputStream(ContentReference contentReference, boolean waitForAvailability)
throws ContentIOException, InterruptedException
{
return null;
}
@Override
public long putInputStream(InputStream sourceInputStream, ContentReference targetContentReference)
throws ContentIOException
{
return 0;
}
@Override
public long putFile(File sourceFile, ContentReference targetContentReference) throws ContentIOException
{
return 0;
}
@Override
public void delete(ContentReference contentReference) throws ContentIOException
{
}
@Override
public boolean isAvailable()
{
return true;
}
}
}
| Alfresco/gytheio | gytheio-commons/src/test/java/org/gytheio/content/handler/DelegatingContentHandlerImplTest.java | Java | lgpl-3.0 | 9,751 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Generated By:JJTree: Do not edit this line. AstFalse.java */
package org.apache.el.parser;
import javax.el.ELException;
import org.apache.el.lang.EvaluationContext;
/**
* @author Jacob Hookom [jacob@hookom.net]
* @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: remy.maucherat@jboss.com $
*/
public final class AstFalse extends BooleanNode {
public AstFalse(int id) {
super(id);
}
public Object getValue(EvaluationContext ctx)
throws ELException {
return Boolean.FALSE;
}
}
| benothman/jboss-web-nio2 | java/org/apache/el/parser/AstFalse.java | Java | lgpl-3.0 | 1,350 |
# *-* encoding: utf-8 *-*
import os
import codecs
import unicodedata
try:
from lxml import etree
except ImportError:
try:
# Python 2.5 - cElementTree
import xml.etree.cElementTree as etree
except ImportError:
try:
# Python 2.5 - ElementTree
import xml.etree.ElementTree as etree
except ImportError:
try:
# Instalacao normal do cElementTree
import cElementTree as etree
except ImportError:
try:
# Instalacao normal do ElementTree
import elementtree.ElementTree as etree
except ImportError:
raise Exception('Falhou ao importar lxml/ElementTree')
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import flags
# from geraldo.utils import memoize
# @memoize
def so_numeros(texto):
"""Retorna o texto informado mas somente os numeros"""
return ''.join(filter(lambda c: ord(c) in range(48, 58), texto))
# @memoize
def obter_pais_por_codigo(codigo):
# TODO
if codigo == '1058':
return 'Brasil'
CAMINHO_DATA = os.path.join(os.path.dirname(
os.path.abspath(__file__)), '..', 'data')
CAMINHO_MUNICIPIOS = os.path.join(CAMINHO_DATA, 'MunIBGE')
CARACTERS_ACENTUADOS = {
ord(u'á'): u'a',
ord(u'â'): u'a',
ord(u'à'): u'a',
ord(u'ã'): u'a',
ord(u'é'): u'e',
ord(u'ê'): u'e',
ord(u'í'): u'i',
ord(u'ó'): u'o',
ord(u'õ'): u'o',
ord(u'ô'): u'o',
ord(u'ú'): u'u',
ord(u'ç'): u'c',
}
# @memoize
def normalizar_municipio(municipio):
if not isinstance(municipio, unicode):
municipio = municipio.decode('utf-8')
return municipio.lower().translate(CARACTERS_ACENTUADOS).upper()
# @memoize
def carregar_arquivo_municipios(uf, reverso=False):
if isinstance(uf, basestring):
try:
uf = int(uf)
except ValueError:
uf = flags.CODIGOS_ESTADOS[uf.upper()]
caminho_arquivo = os.path.join(CAMINHO_MUNICIPIOS, 'MunIBGE-UF%s.txt' % uf)
# Carrega o conteudo do arquivo
fp = codecs.open(caminho_arquivo, "r", "utf-8-sig")
linhas = list(fp.readlines())
fp.close()
municipios_dict = {}
for linha in linhas:
codigo, municipio = linha.split('\t')
codigo = codigo.strip()
municipio = municipio.strip()
if not reverso:
municipios_dict[codigo] = municipio
else:
municipios_dict[normalizar_municipio(municipio)] = codigo
return municipios_dict
# @memoize
def obter_codigo_por_municipio(municipio, uf):
# TODO: fazer UF ser opcional
municipios = carregar_arquivo_municipios(uf, True)
return municipios[normalizar_municipio(municipio)]
# @memoize
def obter_municipio_por_codigo(codigo, uf, normalizado=False):
# TODO: fazer UF ser opcional
municipios = carregar_arquivo_municipios(uf)
municipio = municipios.get(unicode(codigo))
if municipio is None:
raise ValueError
if normalizado:
return normalizar_municipio(municipio)
return municipio
# @memoize
def obter_municipio_e_codigo(dados, uf):
'''Retorna código e município
municipio_ou_codigo - espera receber um dicionário no formato:
{codigo: 121212, municipio: u'municipio'}
'''
cod = dados.get('codigo', '')
mun = normalizar_municipio(dados.get('municipio', ''))
try:
cod = int(cod)
except ValueError:
cod = obter_codigo_por_municipio(mun, uf)
# TODO: se ainda com este teste apresentar erros de nessa seção
# desenvolver um retorno que informe ao cliente quais nfes estão com erro
# e não explodir esse a geração das outras nfes
municipio = obter_municipio_por_codigo(cod, uf, normalizado=True)
return cod, municipio
# @memoize
def extrair_tag(root):
return root.tag.split('}')[-1]
def formatar_decimal(dec):
if dec * 100 - int(dec * 100):
return str(dec)
else:
return "%.2f" % dec
def safe_str(str_):
if not isinstance(str_, unicode):
if isinstance(str_, str):
str_ = str_.decode('utf8')
else:
str_ = unicode(str_)
return unicodedata.normalize('NFKD', str_).encode('ascii', 'ignore')
def obter_uf_por_codigo(codigo_uf):
if isinstance(codigo_uf, basestring) and codigo_uf.isalpha():
return codigo_uf
estados = {v: k for k, v in flags.CODIGOS_ESTADOS.items()}
return estados[unicode(codigo_uf)]
| YACOWS/PyNFe | pynfe/utils/__init__.py | Python | lgpl-3.0 | 4,553 |
using System;
namespace HookManager
{
public static partial class Hooker
{
public enum WM : uint
{
NULL = 0x0000,
CREATE = 0x0001,
DESTROY = 0x0002,
MOVE = 0x0003,
SIZE = 0x0005,
ACTIVATE = 0x0006,
SETFOCUS = 0x0007,
KILLFOCUS = 0x0008,
ENABLE = 0x000A,
SETREDRAW = 0x000B,
SETTEXT = 0x000C,
GETTEXT = 0x000D,
GETTEXTLENGTH = 0x000E,
PAINT = 0x000F,
CLOSE = 0x0010,
QUERYENDSESSION = 0x0011,
QUERYOPEN = 0x0013,
ENDSESSION = 0x0016,
QUIT = 0x0012,
ERASEBKGND = 0x0014,
SYSCOLORCHANGE = 0x0015,
SHOWWINDOW = 0x0018,
WININICHANGE = 0x001A,
SETTINGCHANGE = WININICHANGE,
DEVMODECHANGE = 0x001B,
ACTIVATEAPP = 0x001C,
FONTCHANGE = 0x001D,
TIMECHANGE = 0x001E,
CANCELMODE = 0x001F,
SETCURSOR = 0x0020,
MOUSEACTIVATE = 0x0021,
CHILDACTIVATE = 0x0022,
QUEUESYNC = 0x0023,
GETMINMAXINFO = 0x0024,
PAINTICON = 0x0026,
ICONERASEBKGND = 0x0027,
NEXTDLGCTL = 0x0028,
SPOOLERSTATUS = 0x002A,
DRAWITEM = 0x002B,
MEASUREITEM = 0x002C,
DELETEITEM = 0x002D,
VKEYTOITEM = 0x002E,
CHARTOITEM = 0x002F,
SETFONT = 0x0030,
GETFONT = 0x0031,
SETHOTKEY = 0x0032,
GETHOTKEY = 0x0033,
QUERYDRAGICON = 0x0037,
COMPAREITEM = 0x0039,
GETOBJECT = 0x003D,
COMPACTING = 0x0041,
[Obsolete]
COMMNOTIFY = 0x0044,
WINDOWPOSCHANGING = 0x0046,
WINDOWPOSCHANGED = 0x0047,
[Obsolete]
POWER = 0x0048,
COPYDATA = 0x004A,
CANCELJOURNAL = 0x004B,
NOTIFY = 0x004E,
INPUTLANGCHANGEREQUEST = 0x0050,
INPUTLANGCHANGE = 0x0051,
TCARD = 0x0052,
HELP = 0x0053,
USERCHANGED = 0x0054,
NOTIFYFORMAT = 0x0055,
CONTEXTMENU = 0x007B,
STYLECHANGING = 0x007C,
STYLECHANGED = 0x007D,
DISPLAYCHANGE = 0x007E,
GETICON = 0x007F,
SETICON = 0x0080,
NCCREATE = 0x0081,
NCDESTROY = 0x0082,
NCCALCSIZE = 0x0083,
NCHITTEST = 0x0084,
NCPAINT = 0x0085,
NCACTIVATE = 0x0086,
GETDLGCODE = 0x0087,
SYNCPAINT = 0x0088,
NCMOUSEMOVE = 0x00A0,
NCLBUTTONDOWN = 0x00A1,
NCLBUTTONUP = 0x00A2,
NCLBUTTONDBLCLK = 0x00A3,
NCRBUTTONDOWN = 0x00A4,
NCRBUTTONUP = 0x00A5,
NCRBUTTONDBLCLK = 0x00A6,
NCMBUTTONDOWN = 0x00A7,
NCMBUTTONUP = 0x00A8,
NCMBUTTONDBLCLK = 0x00A9,
NCXBUTTONDOWN = 0x00AB,
NCXBUTTONUP = 0x00AC,
NCXBUTTONDBLCLK = 0x00AD,
INPUT_DEVICE_CHANGE = 0x00FE,
INPUT = 0x00FF,
KEYFIRST = 0x0100,
KEYDOWN = 0x0100,
KEYUP = 0x0101,
CHAR = 0x0102,
DEADCHAR = 0x0103,
SYSKEYDOWN = 0x0104,
SYSKEYUP = 0x0105,
SYSCHAR = 0x0106,
SYSDEADCHAR = 0x0107,
UNICHAR = 0x0109,
KEYLAST = 0x0109,
IME_STARTCOMPOSITION = 0x010D,
IME_ENDCOMPOSITION = 0x010E,
IME_COMPOSITION = 0x010F,
IME_KEYLAST = 0x010F,
INITDIALOG = 0x0110,
COMMAND = 0x0111,
SYSCOMMAND = 0x0112,
TIMER = 0x0113,
HSCROLL = 0x0114,
VSCROLL = 0x0115,
INITMENU = 0x0116,
INITMENUPOPUP = 0x0117,
MENUSELECT = 0x011F,
MENUCHAR = 0x0120,
ENTERIDLE = 0x0121,
MENURBUTTONUP = 0x0122,
MENUDRAG = 0x0123,
MENUGETOBJECT = 0x0124,
UNINITMENUPOPUP = 0x0125,
MENUCOMMAND = 0x0126,
CHANGEUISTATE = 0x0127,
UPDATEUISTATE = 0x0128,
QUERYUISTATE = 0x0129,
CTLCOLORMSGBOX = 0x0132,
CTLCOLOREDIT = 0x0133,
CTLCOLORLISTBOX = 0x0134,
CTLCOLORBTN = 0x0135,
CTLCOLORDLG = 0x0136,
CTLCOLORSCROLLBAR = 0x0137,
CTLCOLORSTATIC = 0x0138,
MOUSEFIRST = 0x0200,
MOUSEMOVE = 0x0200,
LBUTTONDOWN = 0x0201,
LBUTTONUP = 0x0202,
LBUTTONDBLCLK = 0x0203,
RBUTTONDOWN = 0x0204,
RBUTTONUP = 0x0205,
RBUTTONDBLCLK = 0x0206,
MBUTTONDOWN = 0x0207,
MBUTTONUP = 0x0208,
MBUTTONDBLCLK = 0x0209,
MOUSEWHEEL = 0x020A,
XBUTTONDOWN = 0x020B,
XBUTTONUP = 0x020C,
XBUTTONDBLCLK = 0x020D,
MOUSEHWHEEL = 0x020E,
MOUSELAST = 0x020E,
PARENTNOTIFY = 0x0210,
ENTERMENULOOP = 0x0211,
EXITMENULOOP = 0x0212,
NEXTMENU = 0x0213,
SIZING = 0x0214,
CAPTURECHANGED = 0x0215,
MOVING = 0x0216,
POWERBROADCAST = 0x0218,
DEVICECHANGE = 0x0219,
MDICREATE = 0x0220,
MDIDESTROY = 0x0221,
MDIACTIVATE = 0x0222,
MDIRESTORE = 0x0223,
MDINEXT = 0x0224,
MDIMAXIMIZE = 0x0225,
MDITILE = 0x0226,
MDICASCADE = 0x0227,
MDIICONARRANGE = 0x0228,
MDIGETACTIVE = 0x0229,
MDISETMENU = 0x0230,
ENTERSIZEMOVE = 0x0231,
EXITSIZEMOVE = 0x0232,
DROPFILES = 0x0233,
MDIREFRESHMENU = 0x0234,
IME_SETCONTEXT = 0x0281,
IME_NOTIFY = 0x0282,
IME_CONTROL = 0x0283,
IME_COMPOSITIONFULL = 0x0284,
IME_SELECT = 0x0285,
IME_CHAR = 0x0286,
IME_REQUEST = 0x0288,
IME_KEYDOWN = 0x0290,
IME_KEYUP = 0x0291,
MOUSEHOVER = 0x02A1,
MOUSELEAVE = 0x02A3,
NCMOUSEHOVER = 0x02A0,
NCMOUSELEAVE = 0x02A2,
WTSSESSION_CHANGE = 0x02B1,
TABLET_FIRST = 0x02c0,
TABLET_LAST = 0x02df,
CUT = 0x0300,
COPY = 0x0301,
PASTE = 0x0302,
CLEAR = 0x0303,
UNDO = 0x0304,
RENDERFORMAT = 0x0305,
RENDERALLFORMATS = 0x0306,
DESTROYCLIPBOARD = 0x0307,
DRAWCLIPBOARD = 0x0308,
PAINTCLIPBOARD = 0x0309,
VSCROLLCLIPBOARD = 0x030A,
SIZECLIPBOARD = 0x030B,
ASKCBFORMATNAME = 0x030C,
CHANGECBCHAIN = 0x030D,
HSCROLLCLIPBOARD = 0x030E,
QUERYNEWPALETTE = 0x030F,
PALETTEISCHANGING = 0x0310,
PALETTECHANGED = 0x0311,
HOTKEY = 0x0312,
PRINT = 0x0317,
PRINTCLIENT = 0x0318,
APPCOMMAND = 0x0319,
THEMECHANGED = 0x031A,
CLIPBOARDUPDATE = 0x031D,
DWMCOMPOSITIONCHANGED = 0x031E,
DWMNCRENDERINGCHANGED = 0x031F,
DWMCOLORIZATIONCOLORCHANGED = 0x0320,
DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
GETTITLEBARINFOEX = 0x033F,
HANDHELDFIRST = 0x0358,
HANDHELDLAST = 0x035F,
AFXFIRST = 0x0360,
AFXLAST = 0x037F,
PENWINFIRST = 0x0380,
PENWINLAST = 0x038F,
APP = 0x8000,
USER = 0x0400,
CPL_LAUNCH = USER + 0x1000,
CPL_LAUNCHED = USER + 0x1001,
SYSTIMER = 0x118
}
public enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14
}
public const int WH_KEYBOARD = 2;
public const int WH_MOUSE = 7;
public const int WH_KEYBOARD_LL = 13;
public const int WH_MOUSE_LL = 14;
public const int VK_SHIFT = 0x10;
public const int VK_CAPITAL = 0x14;
public const int VK_NUMLOCK = 0x90;
public const int WM_KEYDOWN = 0x100;
public const int WM_KEYUP = 0x101;
public const int WM_SYSKEYDOWN = 0x104;
public const int WM_SYSKEYUP = 0x105;
public const int WM_MOUSEMOVE = 0x200;
public const int WM_LBUTTONDOWN = 0x201;
public const int WM_LBUTTONUP = 0x202;
public const int WM_LBUTTONDBLCLK = 0x203;
public const int WM_RBUTTONDOWN = 0x204;
public const int WM_RBUTTONUP = 0x205;
public const int WM_RBUTTONDBLCLK = 0x206;
public const int WM_MBUTTONDOWN = 0x207;
public const int WM_MBUTTONUP = 0x208;
public const int WM_MBUTTONDBLCLK = 0x209;
public const int WM_MOUSEWHEEL = 0x20A;
}
}
| shurizzle/Scroto | HookManager/Hooker.Constants.cs | C# | lgpl-3.0 | 7,936 |
# (C) British Crown Copyright 2016, Met Office
#
# This file is part of cartopy.
#
# cartopy 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.
#
# cartopy 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 cartopy. If not, see <https://www.gnu.org/licenses/>.
"""
Tests for the NearsidePerspective projection.
"""
from __future__ import (absolute_import, division, print_function)
import unittest
from numpy.testing import assert_almost_equal
from nose.tools import assert_equal
from cartopy.tests.crs.test_geostationary import (GeostationaryTestsMixin,
check_proj4_params)
from cartopy.crs import NearsidePerspective
class TestEquatorialDefault(unittest.TestCase, GeostationaryTestsMixin):
# Check that it behaves just like Geostationary, in the absence of a
# central_latitude parameter.
test_class = NearsidePerspective
expected_proj_name = 'nsper'
class TestOwnSpecifics(unittest.TestCase):
def test_central_latitude(self):
# Check the effect of the added 'central_latitude' key.
geos = NearsidePerspective(central_latitude=53.7)
expected = ['+ellps=WGS84', 'h=35785831', 'lat_0=53.7', 'lon_0=0.0',
'no_defs',
'proj=nsper',
'units=m', 'x_0=0', 'y_0=0']
check_proj4_params(geos, expected)
assert_almost_equal(geos.boundary.bounds,
(-5372584.78443894, -5372584.78443894,
5372584.78443894, 5372584.78443894),
decimal=4)
if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
| zak-k/cartopy | lib/cartopy/tests/crs/test_nearside_perspective.py | Python | lgpl-3.0 | 2,158 |
// Version information for the "groupsock" library
// Copyright (c) 1996-2018 Live Networks, Inc. All rights reserved.
#ifndef _GROUPSOCK_VERSION_HH
#define _GROUPSOCK_VERSION_HH
#define GROUPSOCK_LIBRARY_VERSION_STRING "2018.08.28"
#define GROUPSOCK_LIBRARY_VERSION_INT 1535414400
#endif
| xanview/live555 | groupsock/include/groupsock_version.hh | C++ | lgpl-3.0 | 294 |
package zeditor.tools.banque;
import java.awt.Point;
import java.util.Arrays;
import zeditor.tools.tiles.Banque;
import zeditor.tools.tiles.GraphChange;
// Foret4 = exteria8 (194 tiles)
public class Foret4 extends Banque {
public Foret4() {
coords = new Point[] {
/* Ruines */
/* Bordures de collines */
// Orange flower
new Point(0, 0), new Point(16, 0), new Point(32, 0), new Point(48, 0),
new Point(0, 16), new Point(16, 16), new Point(32, 16),
new Point(48, 16), new Point(0, 32), new Point(32, 32),
new Point(48, 32), new Point(0, 48), new Point(16, 48),
new Point(32, 48), new Point(48, 48),
/* Sols */
new Point(32, 64), new Point(48, 64), new Point(64, 64),
new Point(32, 80), new Point(64, 48),
/* Grand pilier */
new Point(96, 0), new Point(112, 0), new Point(144, 0),
new Point(192, 0), new Point(96, 16), new Point(112, 16),
new Point(192, 16), new Point(128, 16), new Point(144, 16),
new Point(96, 32), new Point(112, 32), new Point(128, 32),
new Point(144, 32), new Point(96, 48), new Point(112, 48),
new Point(128, 48), new Point(144, 48),
/* Statues */
new Point(0, 64), new Point(16, 64), new Point(0, 80),
new Point(16, 80), new Point(160, 0), new Point(176, 0),
new Point(160, 16), new Point(176, 16), new Point(160, 32),
new Point(176, 32),
/* Maison jaune */
new Point(208, 0), new Point(224, 0), new Point(272, 0),
new Point(208, 16), new Point(224, 16), new Point(240, 16),
new Point(256, 16), new Point(272, 16), new Point(208, 32),
new Point(224, 32), new Point(272, 32), new Point(208, 48),
new Point(224, 48),
/* Déco de palais */
new Point(64, 0), new Point(64, 16), new Point(64, 32),
new Point(80, 0), new Point(80, 16), new Point(80, 32),
new Point(192, 32), new Point(0, 96), new Point(16, 96),
new Point(0, 112), new Point(16, 112), new Point(32, 112),
new Point(48, 112),
/* Forˆt enchant‚e */
/* Sols bosquet */
new Point(240, 80), new Point(240, 96), new Point(240, 112),
/* Bordures forˆt */
new Point(224, 64), new Point(240, 64), new Point(256, 64),
new Point(224, 80), new Point(256, 80), new Point(208, 96),
new Point(272, 96), new Point(208, 112), new Point(224, 112),
new Point(256, 112), new Point(272, 112), new Point(224, 128),
new Point(240, 128), new Point(256, 128),
/* Bas du grand arbre */
new Point(96, 64), new Point(112, 64), new Point(128, 64),
new Point(144, 64), new Point(96, 80), new Point(112, 80),
new Point(128, 80), new Point(144, 80),
/* Petits arbres */
new Point(288, 80), new Point(304, 80), new Point(288, 96),
new Point(304, 96), new Point(272, 48), new Point(288, 48),
new Point(272, 64), new Point(288, 64),
/* Tronc d'arbre tunnel */
new Point(160, 48), new Point(176, 48), new Point(192, 48),
new Point(160, 64), new Point(176, 64), new Point(192, 64),
new Point(160, 80), new Point(176, 80), new Point(192, 80),
new Point(160, 96), new Point(176, 96), new Point(192, 96),
new Point(160, 112), new Point(176, 112), new Point(192, 112),
new Point(160, 128), new Point(176, 128), new Point(192, 128),
new Point(96, 96), new Point(112, 96),
/* Souche creuse */
new Point(128, 96), new Point(144, 96), new Point(128, 112),
new Point(144, 112), new Point(128, 128), new Point(144, 128),
/* Clairière */
/* Feuillage */
new Point(0, 128), new Point(16, 128), new Point(32, 128),
new Point(48, 128), new Point(0, 144), new Point(16, 144),
new Point(32, 144), new Point(48, 144), new Point(0, 160),
new Point(16, 160), new Point(32, 160), new Point(48, 160),
new Point(0, 176), new Point(16, 176), new Point(32, 176),
new Point(64, 128), new Point(80, 128),
new Point(96, 128), new Point(112, 128), new Point(64, 144),
new Point(80, 144), new Point(96, 144), new Point(112, 144),
new Point(64, 160), new Point(80, 160), new Point(96, 160),
new Point(112, 160), new Point(80, 176),
new Point(96, 176), new Point(112, 176),
/* Ombres */
new Point(144, 144), new Point(160, 144), new Point(128, 160),
new Point(144, 160), new Point(176, 160),
new Point(144, 176), new Point(160, 176),
/* Estrade de pierre */
new Point(224, 144), new Point(240, 144), new Point(256, 144),
new Point(208, 144), new Point(208, 160), new Point(224, 160),
new Point(240, 160), new Point(256, 160), new Point(192, 144),
new Point(192, 160), new Point(176, 176), new Point(192, 176),
new Point(208, 176), new Point(224, 176), new Point(240, 176),
new Point(256, 176), new Point(272, 176), new Point(288, 176),
/* Piédestal */
new Point(272, 144), new Point(288, 144), new Point(272, 160),
new Point(288, 160),
/* Close trees */
new Point(304, 0), new Point(304, 16), new Point(304, 32),
new Point(304, 48), new Point(304, 64),
/* Buche creuse */
new Point(208, 112),
/* Wood stairs */
new Point(272, 128),
/* Hole in the ground */
new Point(304, 112),
/* Ill tree */
new Point(0, 304), new Point(16, 304), new Point(32, 304), new Point(48, 304),
new Point(0, 320), new Point(16, 320), new Point(32, 320), new Point(48, 320),
new Point(0, 336), new Point(16, 336), new Point(32, 336), new Point(48, 336),
new Point(0, 352), new Point(16, 352), new Point(32, 352), new Point(48, 352),
// Flowers (215)
new Point(208, 112), new Point(224, 112), new Point(240, 112), // Blue
new Point(208, 128), new Point(224, 128), new Point(240, 128), // Blue pack
new Point(176, 128), new Point(192, 144), new Point(208, 144), // Red flower
// Water mud (224)
new Point(224, 144),
// Higher stump
new Point(144, 176), new Point(160, 176), new Point(144, 192), new Point(160, 192),
// Water mud border
new Point(176, 160), new Point(192, 160),
// Nettle
new Point(160, 48), new Point(176, 48),
// Higher stump top
new Point(144, 208), new Point(160, 208),
// Birch (bouleau) 235
new Point(0, 208), new Point(16, 208), new Point(32, 208), new Point(48, 208),
new Point(0, 224), new Point(16, 224), new Point(32, 224), new Point(48, 224),
new Point(0, 240), new Point(16, 240), new Point(32, 240), new Point(48, 240),
new Point(0, 256), new Point(16, 256), new Point(32, 256), new Point(48, 256),
new Point(0, 272), new Point(16, 272), new Point(32, 272), new Point(48, 272)
};
pkmChanges = Arrays.asList(new GraphChange[] {
new GraphChange("exteria8", 0, 0),
new GraphChange("exteria1", 215, 80),
new GraphChange("exteria1", 235, -80)});
}
}
| tchegito/zildo | zeditor/src/zeditor/tools/banque/Foret4.java | Java | lgpl-3.0 | 6,694 |
/**
* 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.portal.model.impl;
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.LayoutRevision;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Date;
/**
* The cache model class for representing LayoutRevision in entity cache.
*
* @author Brian Wing Shun Chan
* @see LayoutRevision
* @generated
*/
public class LayoutRevisionCacheModel implements CacheModel<LayoutRevision>,
Externalizable {
@Override
public String toString() {
StringBundler sb = new StringBundler(63);
sb.append("{layoutRevisionId=");
sb.append(layoutRevisionId);
sb.append(", groupId=");
sb.append(groupId);
sb.append(", companyId=");
sb.append(companyId);
sb.append(", userId=");
sb.append(userId);
sb.append(", userName=");
sb.append(userName);
sb.append(", createDate=");
sb.append(createDate);
sb.append(", modifiedDate=");
sb.append(modifiedDate);
sb.append(", layoutSetBranchId=");
sb.append(layoutSetBranchId);
sb.append(", layoutBranchId=");
sb.append(layoutBranchId);
sb.append(", parentLayoutRevisionId=");
sb.append(parentLayoutRevisionId);
sb.append(", head=");
sb.append(head);
sb.append(", major=");
sb.append(major);
sb.append(", plid=");
sb.append(plid);
sb.append(", privateLayout=");
sb.append(privateLayout);
sb.append(", name=");
sb.append(name);
sb.append(", title=");
sb.append(title);
sb.append(", description=");
sb.append(description);
sb.append(", keywords=");
sb.append(keywords);
sb.append(", robots=");
sb.append(robots);
sb.append(", typeSettings=");
sb.append(typeSettings);
sb.append(", iconImage=");
sb.append(iconImage);
sb.append(", iconImageId=");
sb.append(iconImageId);
sb.append(", themeId=");
sb.append(themeId);
sb.append(", colorSchemeId=");
sb.append(colorSchemeId);
sb.append(", wapThemeId=");
sb.append(wapThemeId);
sb.append(", wapColorSchemeId=");
sb.append(wapColorSchemeId);
sb.append(", css=");
sb.append(css);
sb.append(", status=");
sb.append(status);
sb.append(", statusByUserId=");
sb.append(statusByUserId);
sb.append(", statusByUserName=");
sb.append(statusByUserName);
sb.append(", statusDate=");
sb.append(statusDate);
sb.append("}");
return sb.toString();
}
@Override
public LayoutRevision toEntityModel() {
LayoutRevisionImpl layoutRevisionImpl = new LayoutRevisionImpl();
layoutRevisionImpl.setLayoutRevisionId(layoutRevisionId);
layoutRevisionImpl.setGroupId(groupId);
layoutRevisionImpl.setCompanyId(companyId);
layoutRevisionImpl.setUserId(userId);
if (userName == null) {
layoutRevisionImpl.setUserName(StringPool.BLANK);
}
else {
layoutRevisionImpl.setUserName(userName);
}
if (createDate == Long.MIN_VALUE) {
layoutRevisionImpl.setCreateDate(null);
}
else {
layoutRevisionImpl.setCreateDate(new Date(createDate));
}
if (modifiedDate == Long.MIN_VALUE) {
layoutRevisionImpl.setModifiedDate(null);
}
else {
layoutRevisionImpl.setModifiedDate(new Date(modifiedDate));
}
layoutRevisionImpl.setLayoutSetBranchId(layoutSetBranchId);
layoutRevisionImpl.setLayoutBranchId(layoutBranchId);
layoutRevisionImpl.setParentLayoutRevisionId(parentLayoutRevisionId);
layoutRevisionImpl.setHead(head);
layoutRevisionImpl.setMajor(major);
layoutRevisionImpl.setPlid(plid);
layoutRevisionImpl.setPrivateLayout(privateLayout);
if (name == null) {
layoutRevisionImpl.setName(StringPool.BLANK);
}
else {
layoutRevisionImpl.setName(name);
}
if (title == null) {
layoutRevisionImpl.setTitle(StringPool.BLANK);
}
else {
layoutRevisionImpl.setTitle(title);
}
if (description == null) {
layoutRevisionImpl.setDescription(StringPool.BLANK);
}
else {
layoutRevisionImpl.setDescription(description);
}
if (keywords == null) {
layoutRevisionImpl.setKeywords(StringPool.BLANK);
}
else {
layoutRevisionImpl.setKeywords(keywords);
}
if (robots == null) {
layoutRevisionImpl.setRobots(StringPool.BLANK);
}
else {
layoutRevisionImpl.setRobots(robots);
}
if (typeSettings == null) {
layoutRevisionImpl.setTypeSettings(StringPool.BLANK);
}
else {
layoutRevisionImpl.setTypeSettings(typeSettings);
}
layoutRevisionImpl.setIconImage(iconImage);
layoutRevisionImpl.setIconImageId(iconImageId);
if (themeId == null) {
layoutRevisionImpl.setThemeId(StringPool.BLANK);
}
else {
layoutRevisionImpl.setThemeId(themeId);
}
if (colorSchemeId == null) {
layoutRevisionImpl.setColorSchemeId(StringPool.BLANK);
}
else {
layoutRevisionImpl.setColorSchemeId(colorSchemeId);
}
if (wapThemeId == null) {
layoutRevisionImpl.setWapThemeId(StringPool.BLANK);
}
else {
layoutRevisionImpl.setWapThemeId(wapThemeId);
}
if (wapColorSchemeId == null) {
layoutRevisionImpl.setWapColorSchemeId(StringPool.BLANK);
}
else {
layoutRevisionImpl.setWapColorSchemeId(wapColorSchemeId);
}
if (css == null) {
layoutRevisionImpl.setCss(StringPool.BLANK);
}
else {
layoutRevisionImpl.setCss(css);
}
layoutRevisionImpl.setStatus(status);
layoutRevisionImpl.setStatusByUserId(statusByUserId);
if (statusByUserName == null) {
layoutRevisionImpl.setStatusByUserName(StringPool.BLANK);
}
else {
layoutRevisionImpl.setStatusByUserName(statusByUserName);
}
if (statusDate == Long.MIN_VALUE) {
layoutRevisionImpl.setStatusDate(null);
}
else {
layoutRevisionImpl.setStatusDate(new Date(statusDate));
}
layoutRevisionImpl.resetOriginalValues();
return layoutRevisionImpl;
}
@Override
public void readExternal(ObjectInput objectInput) throws IOException {
layoutRevisionId = objectInput.readLong();
groupId = objectInput.readLong();
companyId = objectInput.readLong();
userId = objectInput.readLong();
userName = objectInput.readUTF();
createDate = objectInput.readLong();
modifiedDate = objectInput.readLong();
layoutSetBranchId = objectInput.readLong();
layoutBranchId = objectInput.readLong();
parentLayoutRevisionId = objectInput.readLong();
head = objectInput.readBoolean();
major = objectInput.readBoolean();
plid = objectInput.readLong();
privateLayout = objectInput.readBoolean();
name = objectInput.readUTF();
title = objectInput.readUTF();
description = objectInput.readUTF();
keywords = objectInput.readUTF();
robots = objectInput.readUTF();
typeSettings = objectInput.readUTF();
iconImage = objectInput.readBoolean();
iconImageId = objectInput.readLong();
themeId = objectInput.readUTF();
colorSchemeId = objectInput.readUTF();
wapThemeId = objectInput.readUTF();
wapColorSchemeId = objectInput.readUTF();
css = objectInput.readUTF();
status = objectInput.readInt();
statusByUserId = objectInput.readLong();
statusByUserName = objectInput.readUTF();
statusDate = objectInput.readLong();
}
@Override
public void writeExternal(ObjectOutput objectOutput)
throws IOException {
objectOutput.writeLong(layoutRevisionId);
objectOutput.writeLong(groupId);
objectOutput.writeLong(companyId);
objectOutput.writeLong(userId);
if (userName == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(userName);
}
objectOutput.writeLong(createDate);
objectOutput.writeLong(modifiedDate);
objectOutput.writeLong(layoutSetBranchId);
objectOutput.writeLong(layoutBranchId);
objectOutput.writeLong(parentLayoutRevisionId);
objectOutput.writeBoolean(head);
objectOutput.writeBoolean(major);
objectOutput.writeLong(plid);
objectOutput.writeBoolean(privateLayout);
if (name == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(name);
}
if (title == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(title);
}
if (description == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(description);
}
if (keywords == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(keywords);
}
if (robots == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(robots);
}
if (typeSettings == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(typeSettings);
}
objectOutput.writeBoolean(iconImage);
objectOutput.writeLong(iconImageId);
if (themeId == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(themeId);
}
if (colorSchemeId == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(colorSchemeId);
}
if (wapThemeId == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(wapThemeId);
}
if (wapColorSchemeId == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(wapColorSchemeId);
}
if (css == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(css);
}
objectOutput.writeInt(status);
objectOutput.writeLong(statusByUserId);
if (statusByUserName == null) {
objectOutput.writeUTF(StringPool.BLANK);
}
else {
objectOutput.writeUTF(statusByUserName);
}
objectOutput.writeLong(statusDate);
}
public long layoutRevisionId;
public long groupId;
public long companyId;
public long userId;
public String userName;
public long createDate;
public long modifiedDate;
public long layoutSetBranchId;
public long layoutBranchId;
public long parentLayoutRevisionId;
public boolean head;
public boolean major;
public long plid;
public boolean privateLayout;
public String name;
public String title;
public String description;
public String keywords;
public String robots;
public String typeSettings;
public boolean iconImage;
public long iconImageId;
public String themeId;
public String colorSchemeId;
public String wapThemeId;
public String wapColorSchemeId;
public String css;
public int status;
public long statusByUserId;
public String statusByUserName;
public long statusDate;
} | km-works/portal-rpc | portal-rpc-client/src/main/java/com/liferay/portal/model/impl/LayoutRevisionCacheModel.java | Java | lgpl-3.0 | 10,917 |
/* -------------------------------------------------------------------------- *
*
* Simple test of the HCOD class with assertion.
*
* -------------------------------------------------------------------------- */
#define SOTH_DEBUG
#define SOTH_DEBUG_MODE 10
#define SOTH_TEMPLATE_DEBUG_MODE 10
#include "RandomGenerator.hpp"
#include "soth/HCOD.hpp"
#include "soth/Random.hpp"
#include "soth/debug.hpp"
using namespace soth;
int main(int, char**) {
soth::sotDebugTrace::openFile();
soth::Random::setSeed(7);
const int NB_STAGE = 3;
const int RANKFREE[] = {3, 4, 3, 5, 3};
const int RANKLINKED[] = {2, 2, 1, 5, 3};
const int NR[] = {5, 4, 5, 5, 8};
const int NC = 12;
/* Initialize J and b. */
std::vector<Eigen::MatrixXd> J(NB_STAGE);
std::vector<soth::VectorBound> b(NB_STAGE);
soth::generateDeficientDataSet(J, b, NB_STAGE, RANKFREE, RANKLINKED, NR, NC);
b[0][1] = std::make_pair(-0.1, 2.37);
for (int i = 0; i < NB_STAGE; ++i) {
sotDEBUG(0) << "J" << i + 1 << " = " << (soth::MATLAB)J[i] << std::endl;
sotDEBUG(0) << "e" << i + 1 << " = " << b[i] << ";" << std::endl;
}
std::cout << J[0](0, 0) << std::endl;
assert(std::abs(J[0](0, 0) - 0.544092) < 1e-5);
/* SOTH structure construction. */
soth::HCOD hcod(NC, NB_STAGE);
for (int i = 0; i < NB_STAGE; ++i) {
hcod.pushBackStage(J[i], b[i]);
assert(NR[i] > 0);
}
hcod.setInitialActiveSet();
hcod.setNameByOrder("stage_");
hcod.initialize();
hcod.Y.computeExplicitly();
hcod.computeSolution(true);
std::cout << hcod.rank() << " " << hcod[0].rank() << " " << hcod[1].rank()
<< " " << hcod[2].rank() << std::endl;
assert((hcod.rank() == 4) && (hcod[0].rank() == 0) && (hcod[1].rank() == 2) &&
(hcod[2].rank() == 2));
double tau = hcod.computeStepAndUpdate();
hcod.makeStep(tau);
std::cout << "tau:" << tau << " " << std::abs(tau - 0.486522) << " "
<< soth::Stage::EPSILON << std::endl;
assert((std::abs(tau - 0.486522) <= 50 * soth::Stage::EPSILON) &&
"Check bound test failed.");
hcod.computeLagrangeMultipliers(hcod.nbStages());
bool testL = hcod.testLagrangeMultipliers(hcod.nbStages(), std::cout);
sotDEBUG(5) << "Test multipliers: " << ((testL) ? "Passed!" : "Failed...")
<< std::endl;
assert(testL && "Lagrange Multipliers test failed.");
}
| stack-of-tasks/soth | unitTesting/thcod.cpp | C++ | lgpl-3.0 | 2,350 |
/*
* Copyright (c) 2005-2010 Substance Kirill Grouchnikov. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of Substance Kirill Grouchnikov nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.pushingpixels.substance.api;
/**
* Defines transformation on a color scheme.
*
* @author Kirill Grouchnikov
*/
public interface ColorSchemeTransform {
/**
* Transforms the specified color scheme.
*
* @param scheme
* The original color scheme to transform.
* @return The transformed color scheme.
*/
public SubstanceColorScheme transform(SubstanceColorScheme scheme);
}
| Depter/JRLib | NetbeansProject/jreserve-dummy/substance/src/main/java/org/pushingpixels/substance/api/ColorSchemeTransform.java | Java | lgpl-3.0 | 2,058 |
/**
Copyright 2015 W. Max Lees
This file is part of Jarvis OS.
Jarvis OS 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.
Jarvis OS 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 Jarvis OS. If not, see <http://www.gnu.org/licenses/>.
*/
/**
FILE: SNLayer.cpp
@author W. Max Lees
@docdate 06.12.2015
@descr Layer of neurons for the Sigmoid Neuron Network implementation
*/
#include "SNLayer.hpp"
namespace Jarvis {
namespace JarvisNLP {
/*!
Initializes the layer based on the number of previous neurons
and the size of the current layer
*/
template <typename T>
void SigmoidNeuronLayer<T>::init(int prevLayerSize, int layerSize) {
}
}
} | Wmaxlees/jarvis-os | jarvis-nlp/src/SNLayer.cpp | C++ | lgpl-3.0 | 1,179 |
# Copyright (c) 2003-2013 LOGILAB S.A. (Paris, FRANCE).
# 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.
"""utilities methods and classes for reporters"""
import sys
import locale
import os
from .. import utils
CMPS = ['=', '-', '+']
# py3k has no more cmp builtin
if sys.version_info >= (3, 0):
def cmp(a, b):
return (a > b) - (a < b)
def diff_string(old, new):
"""given a old and new int value, return a string representing the
difference
"""
diff = abs(old - new)
diff_str = "%s%s" % (CMPS[cmp(old, new)], diff and ('%.2f' % diff) or '')
return diff_str
class Message(object):
"""This class represent a message to be issued by the reporters"""
def __init__(self, reporter, msg_id, location, msg):
self.msg_id = msg_id
self.abspath, self.module, self.obj, self.line, self.column = location
self.path = self.abspath.replace(reporter.path_strip_prefix, '')
self.msg = msg
self.C = msg_id[0]
self.category = utils.MSG_TYPES[msg_id[0]]
self.symbol = reporter.linter.check_message_id(msg_id).symbol
def format(self, template):
"""Format the message according to the given template.
The template format is the one of the format method :
cf. http://docs.python.org/2/library/string.html#formatstrings
"""
return template.format(**(self.__dict__))
class BaseReporter(object):
"""base class for reporters
symbols: show short symbolic names for messages.
"""
extension = ''
def __init__(self, output=None):
self.linter = None
# self.include_ids = None # Deprecated
# self.symbols = None # Deprecated
self.section = 0
self.out = None
self.out_encoding = None
self.encode = None
self.set_output(output)
# Build the path prefix to strip to get relative paths
self.path_strip_prefix = os.getcwd() + os.sep
def add_message(self, msg_id, location, msg):
"""Client API to send a message"""
# Shall we store the message objects somewhere, do some validity checking ?
raise NotImplementedError
def set_output(self, output=None):
"""set output stream"""
self.out = output or sys.stdout
# py3k streams handle their encoding :
if sys.version_info >= (3, 0):
self.encode = lambda x: x
return
def encode(string):
if not isinstance(string, unicode):
return string
encoding = (getattr(self.out, 'encoding', None) or
locale.getdefaultlocale()[1] or
sys.getdefaultencoding())
# errors=replace, we don't want to crash when attempting to show
# source code line that can't be encoded with the current locale
# settings
return string.encode(encoding, 'replace')
self.encode = encode
def writeln(self, string=''):
"""write a line in the output buffer"""
print >> self.out, self.encode(string)
def display_results(self, layout):
"""display results encapsulated in the layout tree"""
self.section = 0
if hasattr(layout, 'report_id'):
layout.children[0].children[0].data += ' (%s)' % layout.report_id
self._display(layout)
def _display(self, layout):
"""display the layout"""
raise NotImplementedError()
# Event callbacks
def on_set_current_module(self, module, filepath):
"""starting analyzis of a module"""
pass
def on_close(self, stats, previous_stats):
"""global end of analyzis"""
pass
def initialize(linter):
"""initialize linter with reporters in this package """
utils.register_plugins(linter, __path__[0])
| lukaszpiotr/pylama_with_gjslint | pylama/checkers/pylint/reporters/__init__.py | Python | lgpl-3.0 | 4,482 |
package de.lmu.ifi.bio.croco.cyto.ui;
import java.awt.Component;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class OperationsTable extends JTable {
class OperationModel extends AbstractTableModel{
private static final long serialVersionUID = 1L;
List<JButton> possibleOperations = null;
public OperationModel(List<JButton> possibleOperations) {
this.possibleOperations = possibleOperations;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return JButton.class;
}
@Override
public int getColumnCount() {
return 1;
}
@Override
public int getRowCount() {
return possibleOperations.size();
}
@Override
public String getColumnName(int column) {
return "Operation";
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return possibleOperations.get(rowIndex);
}
}
//class OperationRendered im
class Renderer implements TableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
return (JButton)value;
}
}
public OperationsTable( List<JButton> possibleOperations){
this.setModel(new OperationModel(possibleOperations));
this.setDefaultRenderer(JButton.class, new Renderer() );
}
}
| croco-bio/croco-cyto | src/main/java/de/lmu/ifi/bio/croco/cyto/ui/OperationsTable.java | Java | lgpl-3.0 | 1,482 |
package de.ovgu.variantsync;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.texteditor.ITextEditor;
import org.osgi.framework.BundleContext;
import de.ovgu.variantsync.applicationlayer.ModuleFactory;
import de.ovgu.variantsync.applicationlayer.Util;
import de.ovgu.variantsync.applicationlayer.context.ContextProvider;
import de.ovgu.variantsync.applicationlayer.context.IContextOperations;
import de.ovgu.variantsync.applicationlayer.datamodel.context.Context;
import de.ovgu.variantsync.applicationlayer.datamodel.context.FeatureExpressions;
import de.ovgu.variantsync.applicationlayer.datamodel.monitoring.MonitorItemStorage;
import de.ovgu.variantsync.applicationlayer.deltacalculation.DeltaOperationProvider;
import de.ovgu.variantsync.applicationlayer.features.FeatureProvider;
import de.ovgu.variantsync.applicationlayer.features.IFeatureOperations;
import de.ovgu.variantsync.applicationlayer.monitoring.ChangeListener;
import de.ovgu.variantsync.applicationlayer.monitoring.MonitorNotifier;
import de.ovgu.variantsync.applicationlayer.synchronization.SynchronizationProvider;
import de.ovgu.variantsync.persistencelayer.IPersistanceOperations;
import de.ovgu.variantsync.presentationlayer.controller.ControllerHandler;
import de.ovgu.variantsync.presentationlayer.controller.ControllerTypes;
import de.ovgu.variantsync.presentationlayer.view.AbstractView;
import de.ovgu.variantsync.presentationlayer.view.console.ChangeOutPutConsole;
import de.ovgu.variantsync.presentationlayer.view.context.MarkerHandler;
import de.ovgu.variantsync.presentationlayer.view.context.PartAdapter;
import de.ovgu.variantsync.presentationlayer.view.eclipseadjustment.VSyncSupportProjectNature;
import de.ovgu.variantsync.utilitylayer.UtilityModel;
import de.ovgu.variantsync.utilitylayer.log.LogOperations;
/**
* Entry point to start plugin variantsync. Variantsync supports developers to
* synchronize similar software projects which are developed in different
* variants. This version is based on first version of variantsync which was
* developed by Lei Luo in 2012.
*
* @author Tristan Pfofe (tristan.pfofe@st.ovgu.de)
* @version 2.0
* @since 14.05.2015
*/
public class VariantSyncPlugin extends AbstractUIPlugin {
// shared instance
private static VariantSyncPlugin plugin;
private ChangeOutPutConsole console;
private List<IProject> projectList = new ArrayList<IProject>();
private Map<IProject, MonitorItemStorage> synchroInfoMap = new HashMap<IProject, MonitorItemStorage>();
private ChangeListener resourceModificationListener;
private IPersistanceOperations persistenceOp = ModuleFactory
.getPersistanceOperations();
private IContextOperations contextOp = ModuleFactory.getContextOperations();
private IFeatureOperations featureOp = ModuleFactory.getFeatureOperations();
private ControllerHandler controller = ControllerHandler.getInstance();
@Override
public void start(BundleContext context) {
try {
super.start(context);
} catch (Exception e) {
LogOperations.logError("Plugin could not be started.", e);
}
plugin = this;
console = new ChangeOutPutConsole();
removeAllMarkers();
initMVC();
initContext();
initFeatureExpressions();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
listenForActiveClass();
}
});
try {
initResourceMonitoring();
} catch (CoreException e) {
LogOperations.logError(
"Resouce monitoring could not be initialized.", e);
}
}
/**
* Listen whether the active file in the java editor changes.
*/
public void listenForActiveClass() {
IWorkbench wb = PlatformUI.getWorkbench();
IWorkbenchWindow ww = wb.getActiveWorkbenchWindow();
IWorkbenchPage page = ww.getActivePage();
if (page == null)
return;
page.addPartListener(new PartAdapter());
}
@Override
public void stop(BundleContext context) {
persistenceOp.saveFeatureExpressions(featureOp.getFeatureExpressions());
// stop default-context or any other active context
try {
contextOp.stopRecording();
persistenceOp.saveContext(contextOp
.getContext(VariantSyncConstants.DEFAULT_CONTEXT), Util
.parseStorageLocation(contextOp
.getContext(VariantSyncConstants.DEFAULT_CONTEXT)));
} catch (NullPointerException e) {
// recordings was already stopped and contexts were cleaned up
}
plugin = null;
try {
super.stop(context);
} catch (Exception e) {
LogOperations.logError("Plugin could not be started.", e);
}
IWorkspace ws = ResourcesPlugin.getWorkspace();
ws.removeResourceChangeListener(resourceModificationListener);
}
public String getWorkspaceLocation() {
return ResourcesPlugin.getWorkspace().getRoot().getLocation()
.toString();
}
/**
* Returns list of projects which has eclipse nature support and variantsync
* nature id.
*
* @return list of projects
*/
public List<IProject> getSupportProjectList() {
this.projectList.clear();
for (IProject project : ResourcesPlugin.getWorkspace().getRoot()
.getProjects()) {
try {
if (project.isOpen()
&& project
.hasNature(VSyncSupportProjectNature.NATURE_ID)) {
this.projectList.add(project);
}
} catch (CoreException e) {
UtilityModel.getInstance().handleError(e,
"nature support could not be checked");
}
}
return new ArrayList<IProject>(projectList);
}
/**
* Updates synchroInfoMap. This map contains IProject-objects mapped to
* SynchroInfo objects.
*/
public void updateSynchroInfo() {
this.synchroInfoMap.clear();
List<IProject> projects = this.getSupportProjectList();
for (IProject project : projects) {
IFile infoFile = project.getFolder(
VariantSyncConstants.ADMIN_FOLDER).getFile(
VariantSyncConstants.ADMIN_FILE);
MonitorItemStorage info = new MonitorItemStorage();
if (infoFile.exists()) {
try {
info = persistenceOp.readSynchroXMLFile(infoFile
.getContents());
} catch (CoreException e) {
UtilityModel.getInstance().handleError(e,
"info file could not be read");
}
}
this.synchroInfoMap.put(project, info);
}
}
/**
* Initializes model view controller implementation to encapsulate gui
* elements from business logic.
*/
private void initMVC() {
// register models as request handler for controller
controller.addModel(new SynchronizationProvider(),
ControllerTypes.SYNCHRONIZATION);
controller
.addModel(new DeltaOperationProvider(), ControllerTypes.DELTA);
controller.addModel(new FeatureProvider(), ControllerTypes.FEATURE);
controller.addModel(new ContextProvider(), ControllerTypes.CONTEXT);
controller.addModel(MonitorNotifier.getInstance(),
ControllerTypes.MONITOR);
}
/**
* Loads all contexts which are saved in a XML-file.
*/
private void initContext() {
String storageLocation = VariantSyncPlugin.getDefault()
.getWorkspaceLocation() + VariantSyncConstants.CONTEXT_PATH;
File folder = new File(storageLocation);
if (folder.exists() && folder.isDirectory()) {
File[] files = folder.listFiles();
for (File f : files) {
Context c = persistenceOp.loadContext(f.getPath());
if (c != null)
contextOp.addContext(c);
else
System.out.println(f.toString());
}
}
contextOp.activateContext(VariantSyncConstants.DEFAULT_CONTEXT);
}
/**
* Loads all feature expressions which are saved in a XML-file.
*/
private void initFeatureExpressions() {
String storageLocation = VariantSyncPlugin.getDefault()
.getWorkspaceLocation()
+ VariantSyncConstants.FEATURE_EXPRESSION_PATH;
File folder = new File(storageLocation.substring(0,
storageLocation.lastIndexOf("/")));
if (folder.exists() && folder.isDirectory()) {
File[] files = folder.listFiles();
for (File f : files) {
FeatureExpressions featureExpressions = persistenceOp
.loadFeatureExpressions(f.getPath());
Iterator<String> it = featureExpressions
.getFeatureExpressions().iterator();
while (it.hasNext()) {
featureOp.addFeatureExpression(it.next());
}
it = featureOp.getFeatureModel().getFeatureNames().iterator();
while (it.hasNext()) {
featureOp.addFeatureExpression(it.next());
}
}
}
}
/**
* Prepares resource monitoring in eclipse workspace. Resource monitoring
* means that projects will be watches. If a projects´s resource changes and
* change was saved, monitoring will notice changed resource (POST_CHANGE).
* A resource is a file or folder.
*
* @throws CoreException
* resources could not be monitored
*/
private void initResourceMonitoring() throws CoreException {
resourceModificationListener = new ChangeListener();
ResourcesPlugin.getWorkspace().addResourceChangeListener(
resourceModificationListener, IResourceChangeEvent.POST_CHANGE);
resourceModificationListener.registerSaveParticipant();
}
/**
* Returns monitored items of specific project.
*
* @param project
* the project to get monitored items from
* @return MonitorItemStorage
*/
public MonitorItemStorage getSynchroInfoFrom(IProject project) {
if (this.synchroInfoMap.get(project) == null) {
this.updateSynchroInfo();
}
return this.synchroInfoMap.get(project);
}
/**
* Registers a view. If a model fires an event, all registered views receive
* this element.
*
* @param view
* view to register
*/
public void registerView(AbstractView view, ControllerTypes type) {
controller.addView(view, type);
}
/**
* Removes a view from controller. If a model fires an event, this view will
* no longer receive this event.
*
* @param view
* view to remove
*/
public void removeView(AbstractView view, ControllerTypes type) {
controller.removeView(view, type);
}
/**
* @return the display
*/
public static Display getStandardDisplay() {
Display display = Display.getCurrent();
if (display == null) {
display = Display.getDefault();
}
return display;
}
/**
* Logs a message on eclipse console.
*
* @param msg
* the message to log
*/
public void logMessage(String msg) {
console.logMessage(msg);
}
/**
* @return the console
*/
public ChangeOutPutConsole getConsole() {
return console;
}
/**
* @return the controller
*/
public ControllerHandler getController() {
return controller;
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static VariantSyncPlugin getDefault() {
return plugin;
}
/**
* Always good to have this static method as when dealing with IResources
* having a interface to get the editor is very handy
*
* @return
*/
public static ITextEditor getEditor() {
return (ITextEditor) getActiveWorkbenchWindow().getActivePage()
.getActiveEditor();
}
public static Shell getShell() {
return getActiveWorkbenchWindow().getShell();
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
private void removeAllMarkers() {
List<IProject> projects = getSupportProjectList();
for (IProject p : projects) {
MarkerHandler.getInstance().clearAllMarker(p);
}
}
public ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(VariantSyncConstants.PLUGIN_ID, path);
}
}
| 1Tristan/VariantSync | src/de/ovgu/variantsync/VariantSyncPlugin.java | Java | lgpl-3.0 | 12,061 |
/* MOD_V2.0
* Copyright (c) 2012 OpenDA Association
* All rights reserved.
*
* This file is part of OpenDA.
*
* OpenDA 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.
*
* OpenDA 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 OpenDA. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openda.model_hspf;
import java.io.File;
import java.text.ParseException;
import java.util.*;
import org.openda.blackbox.interfaces.IoObjectInterface;
import org.openda.exchange.DoubleExchangeItem;
import org.openda.exchange.timeseries.TimeUtils;
import org.openda.interfaces.IExchangeItem;
import org.openda.interfaces.IExchangeItem.Role;
import org.openda.utils.Results;
/**
* IoObject for one WDM (Watershed Data Management) file.
*
* See http://water.usgs.gov/cgi-bin/man_wrdapp?wdm(1) :
* A WDM file is a binary, direct-access file used to store
* hydrologic, hydraulic, meteorologic, water-quality, and
* physiographic data. The WDM file is organized into data
* sets (DSN = Data Set Number). Each data set contains a specific type of data, such
* as streamflow at a specific site or air temperature at a
* weather station. Each data set contains attributes that
* describe the data, such as station identification number,
* time step of data, latitude, and longitude. A WDM file may
* contain a single data set or as many as 200,000 data sets.
* A data set may be described by a few attributes or by
* hundreds of attributes. Data can be added, deleted, and
* modified without restructuring the data in the file. Space
* from deleted data sets is reused.
*
* To manually open and edit a wdm file use WDMUtil, which
* is installed as part of the BASINS package, which is available from:
* http://water.epa.gov/scitech/datait/models/basins/index.cfm
*
* The HSPF model can be installed as part of the BASINS package,
* which is available from:
* http://water.epa.gov/scitech/datait/models/basins/index.cfm
*
* @author Arno Kockx
*/
@Deprecated
//use WdmTimeSeriesDataObject instead.
public class WdmTimeSeriesIoObject implements IoObjectInterface {
/**
* The timeZone that is used by the model.
* This is required to convert the times of the data values
* to/from the timeZone that is used by the model.
* Default is GMT.
*/
private TimeZone timeZone = TimeZone.getTimeZone("GMT");
/**
* Absolute path name of the file containing the data for this IoObject.
*/
private String wdmTimeSeriesFilePath;
private int wdmTimeSeriesFileNumber;
/**
* Absolute path name of the wdm message file.
* The wdm message file is required for the fortran wdm library
* methods to work properly.
*/
private String wdmMessageFilePath;
private WdmDll wdmDll;
private Role role;
private IExchangeItem startTimeExchangeItem = null;
private IExchangeItem endTimeExchangeItem = null;
private double startTimeDouble = Double.NaN;
private double endTimeDouble = Double.NaN;
private List<WdmTimeSeriesExchangeItem> wdmTimeSeriesExchangeItems = new ArrayList<WdmTimeSeriesExchangeItem>();
/**
* @param workingDir the working directory.
* @param fileName the pathname of the file containing the data for this IoObject (relative to the working directory).
* @param arguments the first argument should be the pathname of the wdm.dll file (relative to the working directory),
* the second argument should be the pathname of the message file (relative to working directory),
* the third argument should be the role of this IoObject. Role can be 'input' or 'output',
* the fourth argument should be the timeZone that is used by the model (in hours with respect to GMT, between -12 and 12),
* for role INPUT the fifth and sixth arguments should be the ids of the startTime and endTime exchangeItems respectively,
* for role OUTPUT the fifth and sixth arguments should be respectively the startTime and endTime of the model run,
* the (optional) seventh and further arguments should be the location and parameter ids of the time series for which exchange items should be made,
* if no seventh and further arguments present then exchange items will be created for all time series in the file.
*/
public void initialize(File workingDir, String fileName, String[] arguments) {
//initialize wdmTimeSeriesFilePath.
File wdmTimeSeriesFile = new File(workingDir, fileName);
if (!wdmTimeSeriesFile.exists()) {
throw new IllegalArgumentException(getClass().getSimpleName() + ": Time series file '" + wdmTimeSeriesFile.getAbsolutePath() + "' does not exist.");
}
this.wdmTimeSeriesFilePath = wdmTimeSeriesFile.getAbsolutePath();
//create a unique fortran file unit number to use for the wdmTimeSeriesFile.
this.wdmTimeSeriesFileNumber = WdmUtils.generateUniqueFortranFileUnitNumber();
//initialize wdmDll.
if (arguments == null || arguments.length < 1) {
throw new IllegalArgumentException(getClass().getSimpleName() + ": No arguments specified. The first argument should be the path of the wdm.dll file (relative to working directory).");
}
this.wdmDll = WdmUtils.initializeWdmDll(workingDir, arguments[0]);
//initialize wdmMessageFilePath.
if (arguments.length < 2) {
throw new IllegalArgumentException(getClass().getSimpleName() + ": No arguments specified. The second argument should be the path of the message file (relative to working directory).");
}
this.wdmMessageFilePath = WdmUtils.initializeWdmMessageFilePath(workingDir, arguments[1]);
//initialize role.
if (arguments.length < 3) {
throw new IllegalArgumentException(getClass().getSimpleName() + ": No role argument specified. The third argument should be the role of this IoObject. Role can be 'input' or 'output'.");
}
this.role = WdmUtils.initializeRole(arguments[2]);
//get timeZone.
if (arguments.length < 4) {
throw new IllegalArgumentException("No timeZone argument specified for " + getClass().getSimpleName()
+ ". The fourth argument should be the timeZone that is used by the model (in hours with respect to GMT, between -12 and 12).");
}
try {
double timeZoneOffsetInHours = Double.parseDouble(arguments[3]);
this.timeZone = TimeUtils.createTimeZoneFromDouble(timeZoneOffsetInHours);
} catch (Exception e) {
throw new IllegalArgumentException("Cannot parse fourth argument '" + arguments[3] + "' for " + getClass().getSimpleName()
+ ". The fourth argument should be the timeZone that is used by the model (in hours with respect to GMT, between -12 and 12).", e);
}
//this object can be used for either input or output. In both cases the run startTime and endTime
//are needed. However the timeInfoExchangeItems are only set for input ioObjects (see BBModelInstance.compute)
//and the aliases are only available for output ioObjects (because the aliases are set after the input ioObjects
//have already been initialized). Therefore depending on the role use different arguments to get the
//startTime and endTime here.
//Note: the timeInfoExchangeItems are also set after the input ioObjects have already been initialized,
//but the timeInfoExchangeItems need only be created during ioObject initialization and can then be
//used later, after they have been set.
if (this.role == Role.Input) {
//create exchange items.
if (arguments.length < 6) {
throw new IllegalArgumentException("No start/endTime exchange item ids arguments specified for " + getClass().getSimpleName()
+ ". For role INPUT the fifth and sixth arguments should be the ids of the startTime and endTime exchangeItems respectively.");
}
//get start and end time.
this.startTimeExchangeItem = new DoubleExchangeItem(arguments[4], 0);
this.endTimeExchangeItem = new DoubleExchangeItem(arguments[5], 0);
} else {
if (arguments.length < 6) {
throw new IllegalArgumentException("No start/endTime arguments specified for " + getClass().getSimpleName()
+ ". For role OUTPUT the fifth and sixth arguments should be respectively the startTime and endTime of the model run.");
}
//get start time.
try {
this.startTimeDouble = TimeUtils.date2Mjd(arguments[4]);
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid startTime argument specified for " + getClass().getSimpleName()
+ ". Cannot parse fifth argument '" + arguments[4] + "'. For role OUTPUT the fifth and sixth arguments should be respectively the startTime and endTime of the model run.", e);
}
//get end time.
try {
this.endTimeDouble = TimeUtils.date2Mjd(arguments[5]);
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid endTime argument specified for " + getClass().getSimpleName()
+ ". Cannot parse sixth argument '" + arguments[5] + "'. For role OUTPUT the fifth and sixth arguments should be respectively the startTime and endTime of the model run.", e);
}
}
//initialize wdmTimeSeriesExchangeItems.
if (arguments.length < 7) {
Results.putMessage(getClass().getSimpleName() + ": No time series ids arguments specified. Exchange items will be created for all time series in the file.");
createWdmTimeSeriesExchangeItemsFromFile();
} else {
//create exchange items for specified time series only.
Results.putMessage(getClass().getSimpleName() + ": Time series ids arguments specified. Exchange items will be created for specified time series ids only.");
String[] timeSeriesIdList = Arrays.copyOfRange(arguments, 6, arguments.length);
createWdmTimeSeriesExchangeItemsFromList(timeSeriesIdList);
}
//read all values for all exchangeItems in one go, so that not needed to open/close same file for each read separately.
readValuesAndTimesFromFile();
}
private void createWdmTimeSeriesExchangeItemsFromList(String[] timeSeriesIdList) {
//reset this.timeSeriesExchangeItems list.
this.wdmTimeSeriesExchangeItems.clear();
//create exchange items for all time series ids in the list.
WdmUtils.openWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.wdmMessageFilePath);
this.wdmTimeSeriesExchangeItems.addAll(WdmUtils.createExchangeItemsFromList(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.role, timeSeriesIdList));
WdmUtils.closeWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber);
if (this.wdmTimeSeriesExchangeItems.isEmpty()) throw new IllegalStateException(this.getClass().getSimpleName() + ": this.wdmTimeSeriesExchangeItems.isEmpty()");
}
private void createWdmTimeSeriesExchangeItemsFromFile() {
//reset this.timeSeriesExchangeItems list.
this.wdmTimeSeriesExchangeItems.clear();
//create exchange items for all time series in the file.
WdmUtils.openWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.wdmMessageFilePath);
this.wdmTimeSeriesExchangeItems.addAll(WdmUtils.createExchangeItemsFromFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.role));
WdmUtils.closeWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber);
if (this.wdmTimeSeriesExchangeItems.isEmpty()) throw new IllegalArgumentException(this.getClass().getSimpleName() + ": No time series found in time series file '" + this.wdmTimeSeriesFilePath + "'.");
}
public IExchangeItem[] getExchangeItems() {
//return all available exchange items.
List<IExchangeItem> exchangeItems = new ArrayList<IExchangeItem>(this.wdmTimeSeriesExchangeItems);
if (this.startTimeExchangeItem != null && this.endTimeExchangeItem != null) {
exchangeItems.add(this.startTimeExchangeItem);
exchangeItems.add(this.endTimeExchangeItem);
}
return exchangeItems.toArray(new IExchangeItem[exchangeItems.size()]);
}
/**
* If this IoObject has role Output (i.e. output from the model), then this method
* reads the data from the wdm file and stores it in the wdmTimeSeriesExchangeItems
* in this IoObject.
*
* Updates the in-memory stored values and times by reading from the wdm file.
*/
private void readValuesAndTimesFromFile() {
if (this.role == Role.Input) {
return;
}
if (Double.isNaN(this.startTimeDouble) || Double.isNaN(this.endTimeDouble)) {
throw new IllegalStateException(getClass().getSimpleName() + " not initialized yet.");
}
Results.putMessage(getClass().getSimpleName() + ": reading " + this.wdmTimeSeriesExchangeItems.size()
+ " output time series from file " + this.wdmTimeSeriesFilePath + " with fortran unit number " + this.wdmTimeSeriesFileNumber + ".");
//open wdm file.
WdmUtils.openWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.wdmMessageFilePath);
for (WdmTimeSeriesExchangeItem wdmTimeSeriesExchangeItem : this.wdmTimeSeriesExchangeItems) {
//read data from file and set in wdmTimeSeriesExchangeItem.
WdmUtils.readTimesAndValues(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, wdmTimeSeriesExchangeItem, this.startTimeDouble, this.endTimeDouble, this.timeZone);
}
//close wdm file.
WdmUtils.closeWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber);
}
/**
* If this IoObject has role Input (i.e. input for the model), then this method writes the data
* from all wdmTimeSeriesExchangeItems in this IoObject to the wdm file
* so that it can be used as input by the model.
*/
public void finish() {
if (this.role == Role.Output) {
return;
}
if (this.startTimeExchangeItem == null || this.endTimeExchangeItem == null) {
throw new IllegalStateException(getClass().getSimpleName() + " not initialized yet.");
}
Results.putMessage(getClass().getSimpleName() + ": writing " + this.wdmTimeSeriesExchangeItems.size()
+ " input time series to file " + this.wdmTimeSeriesFilePath + " with fortran unit number " + this.wdmTimeSeriesFileNumber + ".");
//get start and end times.
double startTime = (Double) this.startTimeExchangeItem.getValues();
double endTime = (Double) this.endTimeExchangeItem.getValues();
//open wdm file.
WdmUtils.openWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, this.wdmMessageFilePath);
for (WdmTimeSeriesExchangeItem wdmTimeSeriesExchangeItem : this.wdmTimeSeriesExchangeItems) {
//write data from wdmTimeSeriesExchangeItem to file.
WdmUtils.writeTimesAndValues(this.wdmDll, this.wdmTimeSeriesFileNumber, this.wdmTimeSeriesFilePath, wdmTimeSeriesExchangeItem, startTime, endTime, this.timeZone);
}
//close wdm file.
WdmUtils.closeWdmFile(this.wdmDll, this.wdmTimeSeriesFileNumber);
}
}
| OpenDA-Association/OpenDA | model_hspf/java/src/org/openda/model_hspf/WdmTimeSeriesIoObject.java | Java | lgpl-3.0 | 16,319 |
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package queueit.security.uribuilder;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* Miscellaneous object utility methods.
*
* <p>Mainly for internal use within the framework; consider
* <a href="http://jakarta.apache.org/commons/lang/">Jakarta's Commons Lang</a>
* for a more comprehensive suite of object utilities.
*
* <p>Thanks to Alex Ruiz for contributing several enhancements to this class!
*
* @author Juergen Hoeller
* @author Keith Donald
* @author Rod Johnson
* @author Rob Harrop
* @author Chris Beams
* @since 19.03.2004
* @see org.apache.commons.lang.ObjectUtils
*/
public abstract class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* Return whether the given throwable is a checked exception:
* that is, neither a RuntimeException nor an Error.
* @param ex the throwable to check
* @return whether the throwable is a checked exception
* @see java.lang.Exception
* @see java.lang.RuntimeException
* @see java.lang.Error
*/
public static boolean isCheckedException(Throwable ex) {
return !(ex instanceof RuntimeException || ex instanceof Error);
}
/**
* Check whether the given exception is compatible with the exceptions
* declared in a throws clause.
* @param ex the exception to checked
* @param declaredExceptions the exceptions declared in the throws clause
* @return whether the given exception is compatible
*/
public static boolean isCompatibleWithThrowsClause(Throwable ex, Class[] declaredExceptions) {
if (!isCheckedException(ex)) {
return true;
}
if (declaredExceptions != null) {
int i = 0;
while (i < declaredExceptions.length) {
if (declaredExceptions[i].isAssignableFrom(ex.getClass())) {
return true;
}
i++;
}
}
return false;
}
/**
* Determine whether the given object is an array:
* either an Object array or a primitive array.
* @param obj the object to check
*/
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* Determine whether the given array is empty:
* i.e. {@code null} or of zero length.
* @param array the array to check
*/
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
/**
* Check whether the given array contains the given element.
* @param array the array to check (may be {@code null},
* in which case the return value will always be {@code false})
* @param element the element to check for
* @return whether the element has been found in the given array
*/
public static boolean containsElement(Object[] array, Object element) {
if (array == null) {
return false;
}
for (Object arrayEle : array) {
if (nullSafeEquals(arrayEle, element)) {
return true;
}
}
return false;
}
/**
* Check whether the given array of enum constants contains a constant with the given name,
* ignoring case when determining a match.
* @param enumValues the enum values to check, typically the product of a call to MyEnum.values()
* @param constant the constant name to find (must not be null or empty string)
* @return whether the constant has been found in the given array
*/
public static boolean containsConstant(Enum<?>[] enumValues, String constant) {
return containsConstant(enumValues, constant, false);
}
/**
* Check whether the given array of enum constants contains a constant with the given name.
* @param enumValues the enum values to check, typically the product of a call to MyEnum.values()
* @param constant the constant name to find (must not be null or empty string)
* @param caseSensitive whether case is significant in determining a match
* @return whether the constant has been found in the given array
*/
public static boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive) {
for (Enum<?> candidate : enumValues) {
if (caseSensitive ?
candidate.toString().equals(constant) :
candidate.toString().equalsIgnoreCase(constant)) {
return true;
}
}
return false;
}
/**
* Case insensitive alternative to {@link Enum#valueOf(Class, String)}.
* @param <E> the concrete Enum type
* @param enumValues the array of all Enum constants in question, usually per Enum.values()
* @param constant the constant to get the enum value of
* @throws IllegalArgumentException if the given constant is not found in the given array
* of enum values. Use {@link #containsConstant(Enum[], String)} as a guard to avoid this exception.
*/
public static <E extends Enum<?>> E caseInsensitiveValueOf(E[] enumValues, String constant) {
for (E candidate : enumValues) {
if(candidate.toString().equalsIgnoreCase(constant)) {
return candidate;
}
}
throw new IllegalArgumentException(
String.format("constant [%s] does not exist in enum type %s",
constant, enumValues.getClass().getComponentType().getName()));
}
/**
* Append the given object to the given array, returning a new array
* consisting of the input array contents plus the given object.
* @param array the array to append to (can be {@code null})
* @param obj the object to append
* @return the new array (of the same component type; never {@code null})
*/
public static <A,O extends A> A[] addObjectToArray(A[] array, O obj) {
Class<?> compType = Object.class;
if (array != null) {
compType = array.getClass().getComponentType();
}
else if (obj != null) {
compType = obj.getClass();
}
int newArrLength = (array != null ? array.length + 1 : 1);
@SuppressWarnings("unchecked")
A[] newArr = (A[]) Array.newInstance(compType, newArrLength);
if (array != null) {
System.arraycopy(array, 0, newArr, 0, array.length);
}
newArr[newArr.length - 1] = obj;
return newArr;
}
/**
* Convert the given array (which may be a primitive array) to an
* object array (if necessary of primitive wrapper objects).
* <p>A {@code null} source value will be converted to an
* empty Object array.
* @param source the (potentially primitive) array
* @return the corresponding object array (never {@code null})
* @throws IllegalArgumentException if the parameter is not an array
*/
public static Object[] toObjectArray(Object source) {
if (source instanceof Object[]) {
return (Object[]) source;
}
if (source == null) {
return new Object[0];
}
if (!source.getClass().isArray()) {
throw new IllegalArgumentException("Source is not an array: " + source);
}
int length = Array.getLength(source);
if (length == 0) {
return new Object[0];
}
Class wrapperType = Array.get(source, 0).getClass();
Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(source, i);
}
return newArray;
}
//---------------------------------------------------------------------
// Convenience methods for content-based equality/hash-code handling
//---------------------------------------------------------------------
/**
* Determine if the given objects are equal, returning {@code true}
* if both are {@code null} or {@code false} if only one is
* {@code null}.
* <p>Compares arrays with {@code Arrays.equals}, performing an equality
* check based on the array elements rather than the array reference.
* @param o1 first Object to compare
* @param o2 second Object to compare
* @return whether the given objects are equal
* @see java.util.Arrays#equals
*/
public static boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
}
}
return false;
}
/**
* Return as hash code for the given object; typically the value of
* {@code {@link Object#hashCode()}}. If the object is an array,
* this method will delegate to any of the {@code nullSafeHashCode}
* methods for arrays in this class. If the object is {@code null},
* this method returns 0.
* @see #nullSafeHashCode(Object[])
* @see #nullSafeHashCode(boolean[])
* @see #nullSafeHashCode(byte[])
* @see #nullSafeHashCode(char[])
* @see #nullSafeHashCode(double[])
* @see #nullSafeHashCode(float[])
* @see #nullSafeHashCode(int[])
* @see #nullSafeHashCode(long[])
* @see #nullSafeHashCode(short[])
*/
public static int nullSafeHashCode(Object obj) {
if (obj == null) {
return 0;
}
if (obj.getClass().isArray()) {
if (obj instanceof Object[]) {
return nullSafeHashCode((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeHashCode((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeHashCode((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeHashCode((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeHashCode((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeHashCode((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeHashCode((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeHashCode((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeHashCode((short[]) obj);
}
}
return obj.hashCode();
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(Object[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + nullSafeHashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(boolean[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(byte[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(char[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(double[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(float[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(int[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(long[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* Return a hash code based on the contents of the specified array.
* If {@code array} is {@code null}, this method returns 0.
*/
public static int nullSafeHashCode(short[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* Return the same value as {@link Boolean#hashCode()}}.
* @see Boolean#hashCode()
*/
public static int hashCode(boolean bool) {
return bool ? 1231 : 1237;
}
/**
* Return the same value as {@link Double#hashCode()}}.
* @see Double#hashCode()
*/
public static int hashCode(double dbl) {
long bits = Double.doubleToLongBits(dbl);
return hashCode(bits);
}
/**
* Return the same value as {@link Float#hashCode()}}.
* @see Float#hashCode()
*/
public static int hashCode(float flt) {
return Float.floatToIntBits(flt);
}
/**
* Return the same value as {@link Long#hashCode()}}.
* @see Long#hashCode()
*/
public static int hashCode(long lng) {
return (int) (lng ^ (lng >>> 32));
}
//---------------------------------------------------------------------
// Convenience methods for toString output
//---------------------------------------------------------------------
/**
* Return a String representation of an object's overall identity.
* @param obj the object (may be {@code null})
* @return the object's identity as String representation,
* or an empty String if the object was {@code null}
*/
public static String identityToString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return obj.getClass().getName() + "@" + getIdentityHexString(obj);
}
/**
* Return a hex String form of an object's identity hash code.
* @param obj the object
* @return the object's identity code in hex notation
*/
public static String getIdentityHexString(Object obj) {
return Integer.toHexString(System.identityHashCode(obj));
}
/**
* Return a content-based String representation if {@code obj} is
* not {@code null}; otherwise returns an empty String.
* <p>Differs from {@link #nullSafeToString(Object)} in that it returns
* an empty String rather than "null" for a {@code null} value.
* @param obj the object to build a display String for
* @return a display String representation of {@code obj}
* @see #nullSafeToString(Object)
*/
public static String getDisplayString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return nullSafeToString(obj);
}
/**
* Determine the class name for the given object.
* <p>Returns {@code "null"} if {@code obj} is {@code null}.
* @param obj the object to introspect (may be {@code null})
* @return the corresponding class name
*/
public static String nullSafeClassName(Object obj) {
return (obj != null ? obj.getClass().getName() : NULL_STRING);
}
/**
* Return a String representation of the specified Object.
* <p>Builds a String representation of the contents in case of an array.
* Returns {@code "null"} if {@code obj} is {@code null}.
* @param obj the object to build a String representation for
* @return a String representation of {@code obj}
*/
public static String nullSafeToString(Object obj) {
if (obj == null) {
return NULL_STRING;
}
if (obj instanceof String) {
return (String) obj;
}
if (obj instanceof Object[]) {
return nullSafeToString((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeToString((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeToString((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeToString((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeToString((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeToString((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeToString((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeToString((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeToString((short[]) obj);
}
String str = obj.toString();
return (str != null ? str : EMPTY_STRING);
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(Object[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(String.valueOf(array[i]));
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(boolean[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(byte[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(char[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append("'").append(array[i]).append("'");
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(double[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(float[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(int[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(long[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* Return a String representation of the contents of the specified array.
* <p>The String representation consists of a list of the array's elements,
* enclosed in curly braces ({@code "{}"}). Adjacent elements are separated
* by the characters {@code ", "} (a comma followed by a space). Returns
* {@code "null"} if {@code array} is {@code null}.
* @param array the array to build a String representation for
* @return a String representation of {@code array}
*/
public static String nullSafeToString(short[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
} | queueit/QueueIT.Security-JavaEE | QueueIT.Security/src/queueit/security/uribuilder/ObjectUtils.java | Java | lgpl-3.0 | 27,162 |
/*
* Copyright (c) 2014, Fashiontec (http://fashiontec.org)
* Licensed under LGPL, Version 3
*/
package org.fashiontec.bodyapps.sync;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Class to handle main sync methods
*/
public class Sync {
static final String TAG = Sync.class.getName();
protected String baseURL = "http://freelayers.org"; //base URL of the API
public void setBaseURL(String baseURL) {
this.baseURL = baseURL;
}
/**
* Method which makes all the post calls
*
* @param url
* @param json
* @return
*/
public HttpResponse post(String url, String json, int conTimeOut, int socTimeOut) {
HttpResponse response = null;
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
response = httpclient.execute(httpPost);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return response;
}
/**
* Downloads a file from given URL.
*
* @param url
* @param file
* @return
*/
public int download(String url, String file) {
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setConnectTimeout(2000);
c.setRequestProperty("Accept", "application/vnd.valentina.hdf");
c.connect();
FileOutputStream f = new FileOutputStream(new File(file));
InputStream in = c.getInputStream();
//download code
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return -1;
}
return 1;
}
/**
* Manages get requests.
*
* @param url
* @param conTimeOut
* @param socTimeOut
* @return
*/
public HttpResponse get(String url, int conTimeOut, int socTimeOut) {
HttpResponse response = null;
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
response = client.execute(request);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return response;
}
/**
* Manages put requests
*
* @param url
* @param json
* @param conTimeOut
* @param socTimeOut
* @return
*/
public HttpResponse put(String url, String json, int conTimeOut, int socTimeOut) {
HttpResponse response = null;
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpPut request = new HttpPut(url);
StringEntity se = new StringEntity(json);
request.setEntity(se);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
response = client.execute(request);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return response;
}
/**
* Manages delete requests.
*
* @param url
* @param conTimeOut
* @param socTimeOut
* @return
*/
public HttpResponse DELETE(String url, int conTimeOut, int socTimeOut) {
HttpResponse response = null;
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpDelete request = new HttpDelete(url);
request.setHeader("Accept", "application/json");
response = client.execute(request);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return response;
}
}
| fashiontec/bodyapps-android | app/src/main/java/org/fashiontec/bodyapps/sync/Sync.java | Java | lgpl-3.0 | 5,676 |
/* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: .......
*
* File Description:
* .......
*
* Remark:
* This code was originally generated by application DATATOOL
* using the following specifications:
* 'seqfeat.asn'.
*/
// standard includes
#include <ncbi_pch.hpp>
// generated includes
#include <objects/seqfeat/MultiOrgName.hpp>
// generated classes
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
// destructor
CMultiOrgName::~CMultiOrgName(void)
{
}
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
/* Original file checksum: lines: 57, chars: 1733, CRC32: 90d381d7 */
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/objects/seqfeat/MultiOrgName.cpp | C++ | lgpl-3.0 | 1,860 |
package cm.gov.daf.sif.titrefoncier.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
import cm.gov.daf.sif.model.BaseEntity;
/**
* Encapsule les informations sur la parcelle
*
* @author Albert
*/
@Entity
@Table(name = "parcelles")
public class Parcelle extends BaseEntity {
@Column(name = "num", length = 100)
@NotEmpty
private String num;
@Column(name = "type", length = 100)
@NotEmpty
private String type;
@Column(name = "superficie")
@NotEmpty
private Integer superficie;
@ManyToOne
@JoinColumn(name = "lot_id")
private Lot lot;
@ManyToOne
@JoinColumn(name = "proprietaire_id")
@NotEmpty
private Proprietaire proprietaire;
public Parcelle() {
super();
// TODO Auto-generated constructor stub
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getSuperficie() {
return superficie;
}
public void setSuperficie(Integer superficie) {
this.superficie = superficie;
}
public Lot getLot() {
return lot;
}
public void setLot(Lot lot) {
this.lot = lot;
}
public Proprietaire getProprietaire() {
return proprietaire;
}
public void setProprietaire(Proprietaire proprietaire) {
this.proprietaire = proprietaire;
}
@Override
public String toString() {
return "Parcelle [num=" + num + ", superficie=" + superficie + ", id=" + id + "]";
}
}
| defus/daf-architcture | commons/src/main/java/cm/gov/daf/sif/titrefoncier/model/Parcelle.java | Java | lgpl-3.0 | 1,753 |
/*
* Hex - a hex viewer and annotator
* Copyright (C) 2009-2014,2016-2017,2021 Hakanai, Hex Project
*
* 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 org.trypticon.hex.plaf;
import org.trypticon.hex.HexViewer;
import javax.annotation.Nonnull;
/**
* Action to move the selection up one row.
*
* @author trejkaz
*/
// Swing's own guidelines say not to use serialisation.
@SuppressWarnings("serial")
class SelectionUpAction extends AbstractRelativeSelectionMoveAction {
@Override
protected int getShift(@Nonnull HexViewer viewer) {
return -viewer.getBytesPerRow();
}
}
| trejkaz/hex-components | viewer/src/main/java/org/trypticon/hex/plaf/SelectionUpAction.java | Java | lgpl-3.0 | 1,229 |
//
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using CoreLocation;
using System.Threading.Tasks;
using System.Threading;
using Foundation;
using UIKit;
using Xamarin.Forms;
using WF.Player.Services.Geolocation;
using Vernacular;
using WF.Player.Services.Settings;
[assembly: Dependency(typeof(WF.Player.iOS.Services.Geolocation.Geolocator))]
namespace WF.Player.iOS.Services.Geolocation
{
public class Geolocator : IGeolocator
{
UIDeviceOrientation? _orientation;
NSObject _observer;
public Geolocator()
{
this.manager = GetManager();
this.manager.AuthorizationChanged += OnAuthorizationChanged;
this.manager.Failed += OnFailed;
// if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0))
this.manager.LocationsUpdated += OnLocationsUpdated;
// else
// this.manager.UpdatedLocation += OnUpdatedLocation;
this.manager.UpdatedHeading += OnUpdatedHeading;
}
public event EventHandler<PositionErrorEventArgs> PositionError;
public event EventHandler<PositionEventArgs> PositionChanged;
public event EventHandler<PositionEventArgs> HeadingChanged;
public double DesiredAccuracy
{
get;
set;
}
public bool IsListening
{
get { return this.isListening; }
}
public bool SupportsHeading
{
get { return CLLocationManager.HeadingAvailable; }
}
public bool IsGeolocationAvailable
{
get { return true; } // all iOS devices support at least wifi geolocation
}
public bool IsGeolocationEnabled
{
get { return CLLocationManager.Status == CLAuthorizationStatus.Authorized; }
}
public Position LastKnownPosition
{
get {
return _position;
}
}
public Task<Position> GetPositionAsync (int timeout)
{
return GetPositionAsync (timeout, CancellationToken.None, false);
}
public Task<Position> GetPositionAsync (int timeout, bool includeHeading)
{
return GetPositionAsync (timeout, CancellationToken.None, includeHeading);
}
public Task<Position> GetPositionAsync (CancellationToken cancelToken)
{
return GetPositionAsync (Timeout.Infinite, cancelToken, false);
}
public Task<Position> GetPositionAsync (CancellationToken cancelToken, bool includeHeading)
{
return GetPositionAsync (Timeout.Infinite, cancelToken, includeHeading);
}
public Task<Position> GetPositionAsync (int timeout, CancellationToken cancelToken)
{
return GetPositionAsync (timeout, cancelToken, false);
}
public Task<Position> GetPositionAsync (int timeout, CancellationToken cancelToken, bool includeHeading)
{
if (timeout <= 0 && timeout != Timeout.Infinite)
throw new ArgumentOutOfRangeException ("timeout", "Timeout must be positive or Timeout.Infinite");
TaskCompletionSource<Position> tcs;
if (!IsListening)
{
var m = GetManager();
tcs = new TaskCompletionSource<Position> (m);
var singleListener = new GeolocationSingleUpdateDelegate (m, DesiredAccuracy, includeHeading, timeout, cancelToken);
m.Delegate = singleListener;
m.StartUpdatingLocation ();
if (includeHeading && SupportsHeading)
m.StartUpdatingHeading ();
return singleListener.Task;
}
else
{
tcs = new TaskCompletionSource<Position>();
if (this._position == null)
{
EventHandler<PositionErrorEventArgs> gotError = null;
gotError = (s,e) =>
{
tcs.TrySetException (new GeolocationException (e.Error));
PositionError -= gotError;
};
PositionError += gotError;
EventHandler<PositionEventArgs> gotPosition = null;
gotPosition = (s, e) =>
{
tcs.TrySetResult (e.Position);
PositionChanged -= gotPosition;
};
PositionChanged += gotPosition;
}
else
tcs.SetResult (this._position);
}
return tcs.Task;
}
/// <summary>
/// Starts the update process of the Geolocator.
/// </summary>
/// <param name="minTime">Minimum time in milliseconds.</param>
/// <param name="minDistance">Minimum distance in meters.</param>
public void StartListening (uint minTime, double minDistance)
{
StartListening (minTime, minDistance, false);
}
/// <summary>
/// Starts the update process of the Geolocator.
/// </summary>
/// <param name="minTime">Minimum time in milliseconds.</param>
/// <param name="minDistance">Minimum distance in meters.</param>
/// <param name="includeHeading">Should the Geolocator update process update heading too.</param>
public void StartListening (uint minTime, double minDistance, bool includeHeading)
{
// Get last known position from settings
_position = _position ?? new Position();
_position.Latitude = Settings.Current.GetValueOrDefault<double>(Settings.LastKnownPositionLatitudeKey);
_position.Longitude = Settings.Current.GetValueOrDefault<double>(Settings.LastKnownPositionLongitudeKey);
_position.Altitude = Settings.Current.GetValueOrDefault<double>(Settings.LastKnownPositionAltitudeKey);
if (minTime < 0)
throw new ArgumentOutOfRangeException ("minTime");
if (minDistance < 0)
throw new ArgumentOutOfRangeException ("minDistance");
if (this.isListening)
throw new InvalidOperationException ("Already listening");
if(!CLLocationManager.LocationServicesEnabled || !(CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways || CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse))
{
return;
throw new NotImplementedException ("GPS not existing or not authorized");
}
this.isListening = true;
this.manager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
this.manager.DistanceFilter = minDistance;
this.manager.StartUpdatingLocation ();
if (includeHeading && CLLocationManager.HeadingAvailable) {
this.manager.HeadingFilter = 1;
this.manager.StartUpdatingHeading ();
}
UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
_observer = NSNotificationCenter.DefaultCenter.AddObserver (UIDevice.OrientationDidChangeNotification, OnDidRotate);
}
/// <summary>
/// Stops the update process of the Geolocator.
/// </summary>
public void StopListening ()
{
if (!this.isListening)
return;
this.isListening = false;
if (CLLocationManager.HeadingAvailable)
this.manager.StopUpdatingHeading ();
this.manager.StopUpdatingLocation ();
// Save last known position for later
if (this._position != null)
{
Settings.Current.AddOrUpdateValue(Settings.LastKnownPositionLatitudeKey, this._position.Latitude);
Settings.Current.AddOrUpdateValue(Settings.LastKnownPositionLongitudeKey, this._position.Longitude);
Settings.Current.AddOrUpdateValue(Settings.LastKnownPositionAltitudeKey, this._position.Altitude);
}
this._position = null;
NSNotificationCenter.DefaultCenter.RemoveObserver (_observer);
UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications();
_observer.Dispose();
}
private readonly CLLocationManager manager;
private bool isListening;
private Position _position;
private CLLocationManager GetManager()
{
CLLocationManager m = null;
new NSObject().InvokeOnMainThread (() => m = new CLLocationManager());
if (m.RespondsToSelector (new ObjCRuntime.Selector("requestWhenInUseAuthorization")))
{
m.RequestWhenInUseAuthorization ();
}
return m;
}
/// <summary>
/// Raises the did rotate event.
/// </summary>
/// <remarks>
/// Had to do this, because didn't find a property where to get the actual orientation.
/// Seems to be the easies method.
/// </remarks>
/// <param name="notice">Notice.</param>
private void OnDidRotate(NSNotification notice)
{
UIDevice device = (UIDevice)notice.Object;
if (device.Orientation != UIDeviceOrientation.FaceUp && device.Orientation != UIDeviceOrientation.FaceDown && device.Orientation != UIDeviceOrientation.Unknown)
_orientation = device.Orientation;
}
private void OnUpdatedHeading (object sender, CLHeadingUpdatedEventArgs e)
{
if (e.NewHeading.MagneticHeading == -1)
return;
Position p = (this._position == null) ? new Position () : new Position (this._position);
// If HeadingAccuracy is below 0, than the heading is invalid
if (e.NewHeading.HeadingAccuracy < 0)
return;
var newHeading = e.NewHeading.MagneticHeading;
p.Heading = CheckDeviceOrientationForHeading(newHeading);
this._position = p;
OnHeadingChanged (new PositionEventArgs (p));
}
private void OnLocationsUpdated (object sender, CLLocationsUpdatedEventArgs e)
{
foreach (CLLocation location in e.Locations)
UpdatePosition (location);
}
private void OnUpdatedLocation (object sender, CLLocationUpdatedEventArgs e)
{
UpdatePosition (e.NewLocation);
}
private void UpdatePosition (CLLocation location)
{
Position p = (this._position == null) ? new Position () : new Position (this._position);
if (location.HorizontalAccuracy > -1)
{
p.Accuracy = location.HorizontalAccuracy;
p.Latitude = location.Coordinate.Latitude;
p.Longitude = location.Coordinate.Longitude;
}
if (location.VerticalAccuracy > -1)
{
p.Altitude = location.Altitude;
p.AltitudeAccuracy = location.VerticalAccuracy;
}
if (location.Speed > -1)
p.Speed = location.Speed;
p.Timestamp = new DateTimeOffset (location.Timestamp.ToDateTime());
this._position = p;
OnPositionChanged (new PositionEventArgs (p));
location.Dispose();
}
private void OnFailed (object sender, Foundation.NSErrorEventArgs e)
{
if ((CLError)(int)e.Error.Code == CLError.Network)
OnPositionError (new PositionErrorEventArgs (GeolocationError.PositionUnavailable));
}
private void OnAuthorizationChanged (object sender, CLAuthorizationChangedEventArgs e)
{
if (e.Status == CLAuthorizationStatus.Denied || e.Status == CLAuthorizationStatus.Restricted)
OnPositionError (new PositionErrorEventArgs (GeolocationError.Unauthorized));
}
private void OnPositionChanged (PositionEventArgs e)
{
var changed = PositionChanged;
if (changed != null)
changed (this, e);
}
private void OnHeadingChanged (PositionEventArgs e)
{
var changed = HeadingChanged;
if (changed != null)
changed (this, e);
}
private void OnPositionError (PositionErrorEventArgs e)
{
StopListening();
var error = PositionError;
if (error != null)
error (this, e);
}
double CheckDeviceOrientationForHeading(double heading)
{
double realHeading = heading;
// Don't do this, because device orientation is set to portrait,
// but device orientation changes when rotating device.
// switch (_orientation) {
// case UIDeviceOrientation.Portrait:
// break;
// case UIDeviceOrientation.PortraitUpsideDown:
// realHeading = realHeading + 180.0f;
// break;
// case UIDeviceOrientation.LandscapeLeft:
// realHeading = realHeading + 90.0f;
// break;
// case UIDeviceOrientation.LandscapeRight:
// realHeading = realHeading - 90.0f;
// break;
// default:
// break;
// }
while (realHeading < 0)
realHeading += 360.0;
realHeading = realHeading % 360;
return realHeading;
}
}
} | WFoundation/WF.Player | WF.Player.iOS/Services/Geolocation/Geolocator.cs | C# | lgpl-3.0 | 11,735 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2014, Arnaud Roques
*
* Project Info: http://plantuml.sourceforge.net
*
* This file is part of PlantUML.
*
* PlantUML 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.
*
* PlantUML 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.posimo;
public class Mirror {
private final double max;
public Mirror(double max) {
this.max = max;
}
public double getMirrored(double v) {
if (v < 0 || v > max) {
throw new IllegalArgumentException();
}
//return v;
return max - v;
}
}
| mar9000/plantuml | src/net/sourceforge/plantuml/posimo/Mirror.java | Java | lgpl-3.0 | 1,402 |
<?php
/**
# Copyright Rakesh Shrestha (rakesh.shrestha@gmail.com)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions must retain the above copyright notice.
*/
final class Csv
{
private $enclosure;
private $delimiter;
private $rows;
private $numfields;
public function __construct()
{
$this->enclosure = "\"";
$this->delimiter = ",";
$this->rows = array();
$this->numfields = 0;
}
public function load($file, $headersonly = false)
{
$ext = mb_strtolower(mb_strrchr($file, '.'));
if ($ext == '.csv' || $ext == '.txt') {
$row = 1;
$handle = fopen($file, 'r');
if ($ext == '.txt')
$this->delimiter = "\t";
while (($data = fgetcsv($handle, 1000, $this->delimiter, $this->enclosure)) !== FALSE) {
if ($row == 1) {
foreach ($data as $key => $val)
$headingTexts[] = mb_strtolower(mb_trim($val));
$this->numfields = count($headingTexts);
}
if ($this->numfields < 2) {
fclose($handle);
return 0;
}
if ($headersonly) {
fclose($handle);
return $headingTexts;
}
if ($row > 1) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[mb_strtolower($headingTexts[$key])] = $value;
}
$this->rows[] = $data;
}
$row ++;
}
fclose($handle);
}
return $this->rows;
}
public function write($csv_delimiter, array $csv_headers_array, array $csv_write_res)
{
if (! isset($csv_delimiter)) {
$csv_delimiter = $this->delimiter;
}
$data = "";
$data_temp = '';
foreach ($csv_headers_array as $val) {
$data_temp .= $this->enclosure . mb_strtolower($val) . $this->enclosure . $csv_delimiter;
}
$data .= rtrim($data_temp, $csv_delimiter) . "\r\n";
echo $data;
$data = "";
$data_temp = '';
foreach ($csv_write_res as $val) {
$data_temp = '';
foreach ($val as $val2) {
$data_temp .= $this->enclosure . $val2 . $this->enclosure . $csv_delimiter;
}
$data .= rtrim($data_temp, $csv_delimiter) . "\r\n";
}
echo $data;
}
}
| RakeshShrestha/Php-Web-Objects | admin/app/libraries/Csv.php | PHP | lgpl-3.0 | 2,754 |
#include "turnnotescontroller.h"
#include "../models/talentdata.h"
#include "../models/talentfile.h"
#include "../models/turn.h"
#include <QTextEdit>
TurnNotesController::TurnNotesController(QObject* parent) : Controller(parent)
{
notes = "";
}
void TurnNotesController::setWidgets(QTextEdit* turnNotes)
{
uiNotes = turnNotes;
view.append(uiNotes);
connect(uiNotes, SIGNAL(textChanged()), this, SLOT(on_viewUpdate()));
}
void TurnNotesController::toView()
{
uiNotes->setText(notes);
}
void TurnNotesController::toModel()
{
TalentData::lockTalentFile()->currentTurn()->setNotes(notes);
TalentData::unlockTalentFile();
}
void TurnNotesController::fromModel()
{
notes = TalentData::lockTalentFile()->currentTurn()->getNotes();
TalentData::unlockTalentFile();
}
void TurnNotesController::fromView()
{
notes = uiNotes->toPlainText();
}
| jaluk8/talented-gm | src/controllers/turnnotescontroller.cpp | C++ | lgpl-3.0 | 879 |
/* $Id: rpsblast_local.cpp 448376 2014-10-06 09:52:42Z mcelhany $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Amelia Fong
*
*/
/** @file rpsblast_local.cpp
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbifile.hpp>
#include <corelib/ncbiapp.hpp>
#include <algo/blast/api/local_blast.hpp>
#include <algo/blast/api/objmgr_query_data.hpp>
#include <corelib/ncbithr.hpp>
#include <corelib/ncbitime.hpp>
#include <corelib/ncbimtx.hpp>
#include <corelib/ncbiexpt.hpp>
#include <algo/blast/api/rpsblast_local.hpp>
#include <objtools/blast/seqdb_reader/seqdb.hpp>
#include <algo/blast/api/blast_rps_options.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(blast)
static const char delimiter[] = "#rps#";
static const size_t delimiter_len = sizeof(delimiter) - 1; // exclude \0
static void s_ConvertConcatStringToVectorOfString(const string & s, vector<string> & v)
{
int pos_start = 0;
while(1)
{
size_t pos_find = s.find(delimiter, pos_start);
if(pos_find == string::npos)
break;
TSeqPos length = pos_find - pos_start;
v.push_back(s.substr(pos_start, length));
pos_start = pos_find + delimiter_len;
}
v.push_back(s.substr(pos_start, s.size() - pos_start ));
}
static void s_MergeAlignSet(CSeq_align_set & final_set, const CSeq_align_set & input_set)
{
CSeq_align_set::Tdata & final_list = final_set.Set();
const CSeq_align_set::Tdata & input_list = input_set.Get();
CSeq_align_set::Tdata::const_iterator input_it = input_list.begin();
CSeq_align_set::Tdata::iterator final_it = final_list.begin();
while(input_it != input_list.end())
{
double final_evalue;
double input_evalue;
(*final_it)->GetNamedScore(CSeq_align::eScore_EValue, final_evalue);
(*input_it)->GetNamedScore(CSeq_align::eScore_EValue, input_evalue);
if(input_evalue == final_evalue)
{
//Pulling a trick here to keep the program flow simple
//Replace the final evalue with input bitscore and vice versa
(*final_it)->GetNamedScore(CSeq_align::eScore_BitScore, input_evalue);
(*input_it)->GetNamedScore(CSeq_align::eScore_BitScore, final_evalue);
}
if(input_evalue < final_evalue)
{
CSeq_align_set::Tdata::const_iterator start_input_it = input_it;
while(1)
{
const CSeq_id & id_prev = (*input_it)->GetSeq_id(1);
input_it++;
if(input_it == input_list.end())
{
break;
}
if(! id_prev.Match((*input_it)->GetSeq_id(1)))
{
break;
}
}
final_list.insert(final_it, start_input_it, input_it);
}
else
{
while(1)
{
const CSeq_id & id_prev = (*final_it)->GetSeq_id(1);
final_it++;
if(final_it == final_list.end())
{
break;
}
if(! id_prev.Match((*final_it)->GetSeq_id(1)))
{
break;
}
}
if(final_it == final_list.end())
{
final_list.insert(final_it, input_it, input_list.end());
break;
}
}
}
}
static CRef<CSearchResultSet> s_CombineSearchSets(vector<CRef<CSearchResultSet> > & t, unsigned int num_of_threads)
{
CRef<CSearchResultSet> aggregate_search_result_set (new CSearchResultSet());
aggregate_search_result_set->clear();
for(unsigned int i=0; i < t[0]->GetNumQueries(); i++)
{
vector< CRef<CSearchResults> > thread_results;
thread_results.push_back (CRef<CSearchResults> (&((*(t[0]))[i])));
const CSeq_id & id = *(thread_results[0]->GetSeqId());
for(unsigned int d=1; d < num_of_threads; d++)
{
thread_results.push_back ((*(t[d]))[id]);
}
CRef<CSeq_align_set> align_set(new CSeq_align_set);
TQueryMessages aggregate_messages;
for(unsigned int d=0; d< num_of_threads; d++)
{
if(thread_results[d]->HasAlignments())
{
CConstRef<CSeq_align_set> thread_align_set = thread_results[d]->GetSeqAlign();
if(align_set->IsEmpty())
{
align_set->Set().insert(align_set->Set().begin(),
thread_align_set->Get().begin(),
thread_align_set->Get().end());
}
else
{
s_MergeAlignSet(*align_set, *thread_align_set);
}
}
aggregate_messages.Combine(thread_results[d]->GetErrors());
}
TMaskedQueryRegions query_mask;
thread_results[0]->GetMaskedQueryRegions(query_mask);
CRef<CSearchResults> aggregate_search_results (new CSearchResults(thread_results[0]->GetSeqId(),
align_set,
aggregate_messages,
thread_results[0]->GetAncillaryData(),
&query_mask,
thread_results[0]->GetRID()));
aggregate_search_result_set->push_back(aggregate_search_results);
}
return aggregate_search_result_set;
}
static void s_ModifyVolumePaths(vector<string> & rps_database)
{
for(unsigned int i=0; i < rps_database.size(); i++)
{
size_t found = rps_database[i].find(".pal");
if(string::npos != found)
rps_database[i]= rps_database[i].substr(0, found);
}
}
static bool s_SortDbSize(const pair<string, Int8> & a, const pair<string, Int8> & b)
{
return(a.second > b.second);
}
static void s_MapDbToThread(vector<string> & db, unsigned int num_of_threads)
{
unsigned int db_size = db.size();
vector <pair <string, Int8> > p;
for(unsigned int i=0; i < db_size; i++)
{
vector<string> path;
CSeqDB::FindVolumePaths(db[i], CSeqDB::eProtein, path, NULL, true);
_ASSERT(path.size() == 1);
CFile f(path[0]+".loo");
Int8 length = f.GetLength();
_ASSERT(length > 0 );
//Scale down, just in case
p.push_back(make_pair(db[i], length/1000));
}
sort(p.begin(), p.end(),s_SortDbSize);
db.resize(num_of_threads);
vector<Int8> acc_size(num_of_threads, 0);
for(unsigned char i=0; i < num_of_threads; i++)
{
db[i] = p[i].first;
acc_size[i] = p[i].second;
}
for(unsigned int i= num_of_threads; i < db_size; i++)
{
unsigned int min_index = 0;
for(unsigned int j=1; j<num_of_threads; j++)
{
if(acc_size[j] < acc_size[min_index])
min_index = j;
}
acc_size[min_index] += p[i].second;
db[min_index] = db[min_index] + delimiter + p[i].first;
}
}
CRef<CSearchResultSet> s_RunLocalRpsSearch(const string & db,
CBlastQueryVector & query_vector,
CRef<CBlastOptionsHandle> opt_handle)
{
CSearchDatabase search_db(db, CSearchDatabase::eBlastDbIsProtein);
CRef<CLocalDbAdapter> db_adapter(new CLocalDbAdapter(search_db));
CRef<IQueryFactory> queries(new CObjMgr_QueryFactory(query_vector));
CLocalBlast lcl_blast(queries, opt_handle, db_adapter);
CRef<CSearchResultSet> results = lcl_blast.Run();
return results;
}
class CRPSThread : public CThread
{
public:
CRPSThread(CRef<CBlastQueryVector> query_vector,
const string & db,
CRef<CBlastOptions> options);
void * Main(void);
private:
CRef<CSearchResultSet> RunTandemSearches(void);
CRPSThread(const CRPSThread &);
CRPSThread & operator=(const CRPSThread &);
vector<string> m_db;
CRef<CBlastOptionsHandle> m_opt_handle;
CRef<CBlastQueryVector> m_query_vector;
};
/* CRPSThread */
CRPSThread::CRPSThread(CRef<CBlastQueryVector> query_vector,
const string & db,
CRef<CBlastOptions> options):
m_query_vector(query_vector)
{
m_opt_handle.Reset(new CBlastRPSOptionsHandle(options));
s_ConvertConcatStringToVectorOfString(db, m_db);
}
void* CRPSThread::Main(void)
{
CRef<CSearchResultSet> * result = new (CRef<CSearchResultSet>);
if(m_db.size() == 1)
{
*result = s_RunLocalRpsSearch(m_db[0],
*m_query_vector,
m_opt_handle);
}
else
{
*result = RunTandemSearches();
}
return result;
}
CRef<CSearchResultSet> CRPSThread::RunTandemSearches(void)
{
unsigned int num_of_db = m_db.size();
vector<CRef<CSearchResultSet> > results;
for(unsigned int i=0; i < num_of_db; i++)
{
results.push_back(s_RunLocalRpsSearch(m_db[i],
*m_query_vector,
m_opt_handle));
}
return s_CombineSearchSets(results, num_of_db);
}
/* CThreadedRpsBlast */
CLocalRPSBlast::CLocalRPSBlast(CRef<CBlastQueryVector> query_vector,
const string & db,
CRef<CBlastOptionsHandle> options,
unsigned int num_of_threads):
m_num_of_threads(num_of_threads),
m_db_name(db),
m_opt_handle(options),
m_query_vector(query_vector),
m_num_of_dbs(0)
{
CSeqDB::FindVolumePaths(db, CSeqDB::eProtein, m_rps_databases, NULL, false);
m_num_of_dbs = m_rps_databases.size();
if( 1 == m_num_of_dbs)
{
m_num_of_threads = kDisableThreadedSearch;
}
}
void CLocalRPSBlast::x_AdjustDbSize(void)
{
if(m_opt_handle->GetOptions().GetEffectiveSearchSpace()!= 0)
return;
if(m_opt_handle->GetOptions().GetDbLength()!= 0)
return;
CSeqDB db(m_db_name, CSeqDB::eProtein);
Uint8 db_size = db.GetTotalLengthStats();
int num_seq = db.GetNumSeqsStats();
if(0 == db_size)
db_size = db.GetTotalLength();
if(0 == num_seq)
num_seq = db.GetNumSeqs();
m_opt_handle->SetOptions().SetDbLength(db_size);
m_opt_handle->SetOptions().SetDbSeqNum(num_seq);
return;
}
CRef<CSearchResultSet> CLocalRPSBlast::Run(void)
{
if(1 != m_num_of_dbs)
{
x_AdjustDbSize();
}
if(kDisableThreadedSearch == m_num_of_threads)
{
if(1 == m_num_of_dbs)
{
return s_RunLocalRpsSearch(m_db_name, *m_query_vector, m_opt_handle);
}
else
{
s_ModifyVolumePaths(m_rps_databases);
vector<CRef<CSearchResultSet> > results;
for(unsigned int i=0; i < m_num_of_dbs; i++)
{
results.push_back(s_RunLocalRpsSearch(m_rps_databases[i],
*m_query_vector,
m_opt_handle));
}
return s_CombineSearchSets(results, m_num_of_dbs);
}
}
else
{
return RunThreadedSearch();
}
}
CRef<CSearchResultSet> CLocalRPSBlast::RunThreadedSearch(void)
{
s_ModifyVolumePaths(m_rps_databases);
if((kAutoThreadedSearch == m_num_of_threads) ||
(m_num_of_threads > m_rps_databases.size()))
{
//Default num of thread : a thread for each db
m_num_of_threads = m_rps_databases.size();
}
else if(m_num_of_threads < m_rps_databases.size())
{
// Combine databases, modified the size of rps_database
s_MapDbToThread(m_rps_databases, m_num_of_threads);
}
vector<CRef<CSearchResultSet> * > thread_results(m_num_of_threads, NULL);
vector <CRPSThread* > thread(m_num_of_threads, NULL);
vector<CRef<CSearchResultSet> > results;
for(unsigned int t=0; t < m_num_of_threads; t++)
{
// CThread destructor is protected, all threads destory themselves when terminated
thread[t] = (new CRPSThread(m_query_vector, m_rps_databases[t], m_opt_handle->SetOptions().Clone()));
thread[t]->Run();
}
for(unsigned int t=0; t < m_num_of_threads; t++)
{
thread[t]->Join(reinterpret_cast<void**> (&thread_results[t]));
}
for(unsigned int t=0; t < m_num_of_threads; t++)
{
results.push_back(*(thread_results[t]));
}
CRef<CBlastRPSInfo> rpsInfo = CSetupFactory::CreateRpsStructures(m_db_name,
CRef<CBlastOptions> (&(m_opt_handle->SetOptions())));
return s_CombineSearchSets(results, m_num_of_threads);
}
END_SCOPE(blast)
END_NCBI_SCOPE
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/algo/blast/api/rpsblast_local.cpp | C++ | lgpl-3.0 | 12,514 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.modelinglab.ocl.core.ast.types;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.modelinglab.ocl.core.ast.utils.ClassifierVisitor;
import org.modelinglab.ocl.core.ast.utils.OclVisitor;
/**
*
* @author Gonzalo Ortiz Jaureguizar (gortiz at software.imdea.org)
*/
public class CollectionType extends DataType {
private static final long serialVersionUID = 1L;
Classifier elementType;
private static CollectionType genericInstance = null;
public CollectionType() {
}
public CollectionType(Classifier elementType) {
Preconditions.checkArgument(elementType != null, "Element type of collection types must be "
+ "different than (java) null.");
this.elementType = elementType;
}
protected CollectionType(CollectionType other) {
super(other);
elementType = other.elementType.clone();
}
public static CollectionType getGenericInstance() {
if (genericInstance == null) {
genericInstance = new CollectionType();
genericInstance.setElementType(TemplateParameterType.getGenericCollectionElement());
}
return genericInstance;
}
public Classifier getElementType() {
return elementType;
}
public void setElementType(Classifier elementType) {
this.elementType = elementType;
}
public boolean isOrdered() {
switch (getCollectionKind()) {
case BAG:
case SET:
return false;
case ORDERED_SET:
case SEQUENCE:
return true;
default:
throw new IllegalStateException("This function has no sense in abstract collections");
}
}
public boolean isUnique() {
switch (getCollectionKind()) {
case BAG:
return false;
case SEQUENCE:
case ORDERED_SET:
case SET:
return true;
default:
throw new IllegalStateException("This function has no sense in abstract collections");
}
}
public static CollectionType newCollection(CollectionKind kind) {
CollectionType result;
switch (kind) {
case BAG:
result = new BagType();
break;
case COLLECTION:
result = new CollectionType();
break;
case ORDERED_SET:
result = new OrderedSetType();
break;
case SEQUENCE:
result = new SequenceType();
break;
case SET:
result = new SetType();
break;
default:
throw new AssertionError();
}
return result;
}
@Override
public void fixTemplates(TemplateRestrictions restrictions) {
super.fixTemplates(restrictions);
restrictions.instantiate("T", elementType, true);
}
@Override
public List<Classifier> getSuperClassifiers() {
assert getElementType() != null;
List<Classifier> elementSuperClassifiers;
elementSuperClassifiers = getElementType().getSuperClassifiers();
List<Classifier> result;
CollectionType ct;
if (getCollectionKind() != CollectionKind.COLLECTION) {
/*
* Result will have a collection foreach element in elementSuperClassifiers, a specific
* collection type foreach element in elementSuperClassifiers, the AnyType, and a collection
* and a specific collection type of elementType
*/
result = new ArrayList<Classifier>(elementSuperClassifiers.size() * 2 + 1 + 2);
CollectionKind collectionKind = getCollectionKind();
ct = CollectionType.newCollection(collectionKind);
ct.setElementType(getElementType());
result.add(ct);
for (Classifier superElement : elementSuperClassifiers) {
ct = CollectionType.newCollection(collectionKind);
ct.setElementType(superElement);
result.add(ct);
}
ct = new CollectionType();
ct.setElementType(getElementType());
result.add(ct);
} else {
result = new ArrayList<Classifier>(elementSuperClassifiers.size() + 1);
}
for (Classifier superElement : elementSuperClassifiers) {
ct = new CollectionType();
ct.setElementType(superElement);
result.add(ct);
}
result.add(AnyType.getInstance());
return result;
}
@Override
public CollectionType getRestrictedType(TemplateRestrictions restrictions) {
if (getElementType() instanceof TemplateParameterType) {
TemplateParameterType template = (TemplateParameterType) getElementType();
Classifier newElement = restrictions.getInstance(template.getSpecification());
if (newElement != null) {
CollectionType result = CollectionType.newCollection(getCollectionKind());
result.setElementType(newElement);
return result;
} else { //restrictions does not contains elementType
return this;
}
} else { //elementType is not a tempate
return this;
}
}
@Override
protected void conformsPreconditions(Classifier otherClassifier) {
super.conformsPreconditions(otherClassifier);
Preconditions.checkState(elementType != null,
"To evaluate conforms with CollectionType#getElementType() must not be null");
}
@Override
protected boolean conformsToProtected(Classifier conformsTarget, TemplateRestrictions instanciatedTemplates) {
if (!(conformsTarget instanceof CollectionType)) {
return false;
}
final CollectionType otherCollection = (CollectionType) conformsTarget;
if (!elementType.conformsTo(otherCollection.getElementType(), instanciatedTemplates)) {
return false;
}
return otherCollection.getCollectionKind() == this.getCollectionKind()
|| otherCollection.getCollectionKind() == CollectionKind.COLLECTION;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CollectionType other = (CollectionType) obj;
if (this.elementType != other.elementType && (this.elementType == null || !this.elementType.equals(other.elementType))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 29 * hash + (this.elementType != null ? this.elementType.hashCode() : 0);
return hash;
}
@Override
public CollectionType clone() {
return new CollectionType(this);
}
@Override
public String getName() {
return getCollectionKind().toString() + "(" + elementType + ')';
}
@Override
public ClassifierType getClassifierType() {
return new ClassifierType(this);
}
public CollectionKind getCollectionKind() {
return CollectionKind.COLLECTION;
}
@Override
public <Result, Arg> Result accept(ClassifierVisitor<Result, Arg> visitor, Arg arguments) {
return visitor.visit(this, arguments);
}
public <Result, Arg> Result accept(OclVisitor<Result, Arg> visitor, Arg arguments) {
return visitor.visit(this, arguments);
}
public static enum CollectionKind {
COLLECTION, BAG, SET, ORDERED_SET, SEQUENCE;
@Override
public String toString() {
switch (this) {
case COLLECTION:
return "Collection";
case BAG:
return "Bag";
case SET:
return "Set";
case ORDERED_SET:
return "OrderedSet";
case SEQUENCE:
return "Sequence";
default:
throw new AssertionError();
}
}
}
}
| modelinglab/ocl | core/src/main/java/org/modelinglab/ocl/core/ast/types/CollectionType.java | Java | lgpl-3.0 | 8,485 |
#ifndef BOOST_MPL_ITERATOR_TAG_HPP_INCLUDED
#define BOOST_MPL_ITERATOR_TAG_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /cvsroot/boost/boost/boost/mpl/iterator_tags.hpp,v $
// $Date: 2004/12/01 02:44:52 $
// $Revision: 1.3.2.1 $
#include <boost/mpl/int.hpp>
namespace boost { namespace mpl {
struct forward_iterator_tag : int_<0> { typedef forward_iterator_tag type; };
struct bidirectional_iterator_tag : int_<1> { typedef bidirectional_iterator_tag type; };
struct random_access_iterator_tag : int_<2> { typedef random_access_iterator_tag type; };
}}
#endif // BOOST_MPL_ITERATOR_TAG_HPP_INCLUDED
| pixelspark/corespark | Libraries/Spirit/boost/miniboost/boost/mpl/iterator_tags.hpp | C++ | lgpl-3.0 | 880 |
/*
* 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.es.request;
import javax.annotation.ParametersAreNonnullByDefault;
| lbndev/sonarqube | server/sonar-server/src/main/java/org/sonar/server/es/request/package-info.java | Java | lgpl-3.0 | 967 |
/*
* jndn-management
* Copyright (c) 2016, Regents of the University of California.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 3, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.intel.jndn.management.types;
import com.intel.jndn.management.enums.NfdTlv;
import com.intel.jndn.management.helpers.EncodingHelper;
import net.named_data.jndn.encoding.EncodingException;
import net.named_data.jndn.encoding.tlv.TlvDecoder;
import net.named_data.jndn.encoding.tlv.TlvEncoder;
import net.named_data.jndn.util.Blob;
import java.nio.ByteBuffer;
/**
* Represent a ChannelStatus object.
*
* @see <a href="http://redmine.named-data.net/projects/nfd/wiki/FaceMgmt#Channel-Dataset">Face Management</a>
*/
public class ChannelStatus implements Decodable {
private String localUri = "";
/////////////////////////////////////////////////////////////////////////////
/**
* Default constructor.
*/
public ChannelStatus() {
// nothing to do
}
/**
* Constructor from wire format.
*
* @param input wire format
* @throws EncodingException when decoding fails
*/
public ChannelStatus(final ByteBuffer input) throws EncodingException {
wireDecode(input);
}
/**
* Encode using a new TLV encoder.
*
* @return The encoded buffer
*/
public final Blob wireEncode() {
TlvEncoder encoder = new TlvEncoder();
wireEncode(encoder);
return new Blob(encoder.getOutput(), false);
}
/**
* Encode as part of an existing encode context.
*
* @param encoder TlvEncoder instance
*/
public final void wireEncode(final TlvEncoder encoder) {
int saveLength = encoder.getLength();
encoder.writeBlobTlv(NfdTlv.LocalUri, new Blob(localUri).buf());
encoder.writeTypeAndLength(NfdTlv.ChannelStatus, encoder.getLength() - saveLength);
}
/**
* Decode the input from its TLV format.
*
* @param input The input buffer to decode. This reads from position() to
* limit(), but does not change the position.
* @throws EncodingException when decoding fails
*/
public final void wireDecode(final ByteBuffer input) throws EncodingException {
TlvDecoder decoder = new TlvDecoder(input);
wireDecode(decoder);
}
/**
* {@inheritDoc}
*/
@Override
public void wireDecode(final TlvDecoder decoder) throws EncodingException {
int endOffset = decoder.readNestedTlvsStart(NfdTlv.ChannelStatus);
this.localUri = EncodingHelper.toString(decoder.readBlobTlv(NfdTlv.LocalUri));
decoder.finishNestedTlvs(endOffset);
}
/**
* @return channel URI
*/
public String getLocalUri() {
return localUri;
}
/**
* Set channel URI.
*
* @param localUri channel URI
* @return this
*/
public ChannelStatus setLocalUri(final String localUri) {
this.localUri = localUri;
return this;
}
@Override
public String toString() {
return "ChannelStatus(" + getLocalUri() + ")";
}
}
| 01org/jndn-management | src/main/java/com/intel/jndn/management/types/ChannelStatus.java | Java | lgpl-3.0 | 3,314 |
/*
* (C) Copyright Boris Litvin 2014, 2015
* This file is part of FSM4Java library.
*
* FSM4Java 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.
*
* FSM4Java 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 FSM4Java If not, see <http://www.gnu.org/licenses/>.
*/
package org.blitvin.statemachine;
public class InvalidFactoryImplementation extends Exception {
private static final long serialVersionUID = -5234585034138276392L;
public InvalidFactoryImplementation(String message , Throwable cause) {
super(message, cause);
}
public InvalidFactoryImplementation(String message){
super(message);
}
} | blitvin/fsm4java | src/main/java/org/blitvin/statemachine/InvalidFactoryImplementation.java | Java | lgpl-3.0 | 1,094 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jams.server.client.sync;
import jams.JAMS;
import jams.server.client.Controller;
import jams.server.entities.Workspace;
import jams.tools.StringTools;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
/**
*
* @author christian
*/
public class SyncTable extends JTable {
Component tableSyncModeCells[];
Font defaultFont = new Font("Times New Roman", Font.PLAIN, 10);
File localWorkspace = null;
Workspace serverWorkspace = null;
Controller ctrl = null;
final int COLUMN_COUNT = 5;
final int COLUMN_SIZE[] = {25, 365, 75, 90, 50};
final String COLUMN_NAMES[] = {"", JAMS.i18n("Path"), JAMS.i18n("Extension"), JAMS.i18n("Operation"), JAMS.i18n("SIZE")};
final Class COLUMN_CLASSES[] = {Boolean.class, String.class, String.class, FileSync.SyncMode.class, Long.class};
final int SYNCMODE_COLUMN = 3;
/**
*
* @param ctrl
* @param defaultFont
*/
public SyncTable(Controller ctrl, Font defaultFont) {
super(10, 5);
this.ctrl = ctrl;
if (defaultFont != null) {
this.defaultFont = defaultFont;
}
}
/**
*
* @param localWorkspace
*/
public void setLocalWorkspace(File localWorkspace) {
this.localWorkspace = localWorkspace;
initModel();
}
/**
*
* @return
*/
public File getLocalWorkspace() {
return this.localWorkspace;
}
/**
*
* @param serverWorkspace
*/
public void setServerWorkspace(Workspace serverWorkspace) {
this.serverWorkspace = serverWorkspace;
initModel();
}
/**
*
* @return
*/
public Workspace getServerWorkspace() {
return this.serverWorkspace;
}
private void initModel() {
SyncTableModel syncTableModel = new SyncTableModel(ctrl, localWorkspace, serverWorkspace);
setModel(syncTableModel);
SyncWorkspaceTableRenderer renderer
= new SyncWorkspaceTableRenderer(syncTableModel.getSyncList());
setDefaultRenderer(String.class, renderer);
setDefaultRenderer(Long.class, renderer);
getColumnModel().getColumn(SYNCMODE_COLUMN).setCellRenderer(renderer);
getColumnModel().getColumn(SYNCMODE_COLUMN).setCellEditor(new SyncModeEditor());
setShowHorizontalLines(false);
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i < COLUMN_COUNT; i++) {
getColumnModel().getColumn(i).setPreferredWidth(COLUMN_SIZE[i]);
}
}
@Override
public SyncTableModel getModel() {
if (super.getModel() instanceof SyncTableModel) {
return (SyncTableModel) super.getModel();
} else {
return null;
}
}
/**
*
*/
public class SyncTableModel extends AbstractTableModel {
ArrayList<FileSync> syncList = null;
/**
*
* @param ctrl
* @param localWsDirectory
* @param remoteWs
*/
public SyncTableModel(Controller ctrl, File localWsDirectory, Workspace remoteWs) {
if (ctrl == null
|| localWsDirectory == null
|| remoteWs == null) {
syncList = new ArrayList<>();
} else {
syncList = ctrl.workspaces()
.getSynchronizationList(localWsDirectory, remoteWs)
.getList(null);
}
}
/**
*
* @return
*/
public List<FileSync> getSyncList() {
return syncList;
}
/**
*
* @return
*/
public FileSync getRoot() {
if (syncList == null || syncList.isEmpty()) {
return null;
}
return syncList.get(0).getRoot();
}
@Override
public int getRowCount() {
return syncList.size();
}
@Override
public int getColumnCount() {
return COLUMN_COUNT;
}
@Override
public String getColumnName(int columnIndex) {
return COLUMN_NAMES[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return COLUMN_CLASSES[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 0
|| (columnIndex == SYNCMODE_COLUMN && tableSyncModeCells[rowIndex] instanceof JComboBox);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
FileSync fs = syncList.get(rowIndex);
switch (columnIndex) {
case 0:
return fs.isDoSync();
case 1:
if (fs.getLocalFile() != null) {
return fs.getLocalFile().getPath();
}
return null;
case 2: {
String name = syncList.get(rowIndex).getLocalFile().getName();
int lastIndex = name.lastIndexOf(".");
if (lastIndex == -1) {
return "";
} else {
return name.substring(lastIndex, name.length());
}
}
case 3:
return syncList.get(rowIndex).getSyncMode();
case 4:
if (fs.getServerFile() != null) {
return fs.getServerFile().getFile().getFileSize();
} else {
return 0;
}
}
return null;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (columnIndex == 0) {
syncList.get(rowIndex).setDoSync((Boolean) aValue, true);
//generateTableCells();
fireTableDataChanged();
}
if (columnIndex == 3) {
syncList.get(rowIndex).setSyncMode((FileSync.SyncMode) aValue);
generateTableCells(syncList);
fireTableDataChanged();
}
}
}
private class SyncModeEditor extends AbstractCellEditor
implements TableCellEditor,
ActionListener {
JComboBox currentBox = null;
public SyncModeEditor() {
}
@Override
public void actionPerformed(ActionEvent e) {
}
//Implement the one CellEditor method that AbstractCellEditor doesn't.
@Override
public Object getCellEditorValue() {
if (currentBox != null) {
return currentBox.getSelectedItem();
}
return null;
}
//Implement the one method defined by TableCellEditor.
@Override
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
if (tableSyncModeCells[row] instanceof JComboBox) {
return currentBox = (JComboBox) tableSyncModeCells[row];
} else {
return currentBox = null;
}
}
}
private class SyncWorkspaceTableRenderer extends JLabel implements TableCellRenderer {
List<FileSync> syncList = null;
public SyncWorkspaceTableRenderer(List<FileSync> syncList) {
this.syncList = syncList;
generateTableCells(syncList);
setOpaque(true); //MUST do this for background to show up.
}
@Override
public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
//special handling of column 3
if (column == SYNCMODE_COLUMN) {
return tableSyncModeCells[row];
}
setBackground(Color.WHITE);
setForeground(Color.BLACK);
if (value instanceof Long) {
setText(StringTools.humanReadableByteCount((Long) value, false));
setHorizontalAlignment(JLabel.RIGHT);
} else if (value instanceof Integer) {
setText(StringTools.humanReadableByteCount((Integer) value, false));
setHorizontalAlignment(JLabel.RIGHT);
} else {
setText(value.toString());
setHorizontalAlignment(JLabel.LEFT);
}
FileSync fs = syncList.get(row);
if (!fs.isExisting()) {
setBackground(Color.green);
} else if (fs.isModified()) {
setBackground(Color.red);
}
if (fs instanceof DirectorySync) {
setBackground(Color.darkGray);
setForeground(Color.white);
}
setFont(defaultFont);
return this;
}
}
private void generateTableCells(List<FileSync> syncList) {
tableSyncModeCells = new Component[syncList.size()];
for (int i = 0; i < syncList.size(); i++) {
FileSync fs = syncList.get(i);
if (fs.getSyncOptions().length == 1) {
tableSyncModeCells[i] = new JLabel(
fs.getSyncOptions()[0].toString(),
JLabel.CENTER);
tableSyncModeCells[i].setBackground(Color.WHITE);
tableSyncModeCells[i].setForeground(Color.BLACK);
if (!syncList.get(i).isExisting()) {
tableSyncModeCells[i].setBackground(Color.green);
} else if (syncList.get(i).isModified()) {
tableSyncModeCells[i].setBackground(Color.red);
}
if (syncList.get(i) instanceof DirectorySync) {
tableSyncModeCells[i].setBackground(Color.darkGray);
tableSyncModeCells[i].setForeground(Color.white);
}
((JLabel) tableSyncModeCells[i]).setOpaque(true);
} else {
JComboBox box = new JComboBox(fs.getSyncOptions());
box.putClientProperty("row", new Integer(i));
box.setSelectedItem(fs.getSyncMode());
box.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox src = (JComboBox) e.getSource();
int row = (Integer) src.getClientProperty("row");
((SyncTableModel) getModel()).setValueAt(src.getSelectedItem(), row, 3);
}
});
tableSyncModeCells[i] = box;
tableSyncModeCells[i].setBackground(Color.WHITE);
tableSyncModeCells[i].setForeground(Color.BLACK);
}
tableSyncModeCells[i].setFont(defaultFont);
}
}
}
| kralisch/jams | JAMSCloudClient/src/jams/server/client/sync/SyncTable.java | Java | lgpl-3.0 | 12,177 |
<?php
namespace Google\AdsApi\Dfp\v201708;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class ActivityError extends \Google\AdsApi\Dfp\v201708\ApiError
{
/**
* @var string $reason
*/
protected $reason = null;
/**
* @param string $fieldPath
* @param \Google\AdsApi\Dfp\v201708\FieldPathElement[] $fieldPathElements
* @param string $trigger
* @param string $errorString
* @param string $reason
*/
public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null)
{
parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString);
$this->reason = $reason;
}
/**
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* @param string $reason
* @return \Google\AdsApi\Dfp\v201708\ActivityError
*/
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
}
| advanced-online-marketing/AOM | vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201708/ActivityError.php | PHP | lgpl-3.0 | 1,048 |
/*
* Copyright (C) 2017 Premium Minds.
*
* This file is part of billy GIN.
*
* billy GIN 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.
*
* billy GIN 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 billy GIN. If not, see <http://www.gnu.org/licenses/>.
*/
package com.premiumminds.billy.gin.services.export;
import java.io.InputStream;
public interface BillyTemplateBundle {
/**
* returns the path to the image file to be used as a logo
*
* @return The path of the logo image file
*/
public String getLogoImagePath();
/**
* returns the path to the xslt file to be used as the pdf template
* generator
*
* @return The path of the xslt template file.
*/
public InputStream getXSLTFileStream();
public String getPaymentMechanismTranslation(Enum<?> pmc);
}
| premium-minds/billy | billy-gin/src/main/java/com/premiumminds/billy/gin/services/export/BillyTemplateBundle.java | Java | lgpl-3.0 | 1,309 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\network\mcpe\protocol;
use pocketmine\utils\Binary;
use pocketmine\network\mcpe\NetworkSession;
class CommandBlockUpdatePacket extends DataPacket{
const NETWORK_ID = ProtocolInfo::COMMAND_BLOCK_UPDATE_PACKET;
/** @var bool */
public $isBlock;
/** @var int */
public $x;
/** @var int */
public $y;
/** @var int */
public $z;
/** @var int */
public $commandBlockMode;
/** @var bool */
public $isRedstoneMode;
/** @var bool */
public $isConditional;
/** @var int */
public $minecartEid;
/** @var string */
public $command;
/** @var string */
public $lastOutput;
/** @var string */
public $name;
/** @var bool */
public $shouldTrackOutput;
protected function decodePayload(){
$this->isBlock = (($this->get(1) !== "\x00"));
if($this->isBlock){
$this->getBlockPosition($this->x, $this->y, $this->z);
$this->commandBlockMode = $this->getUnsignedVarInt();
$this->isRedstoneMode = (($this->get(1) !== "\x00"));
$this->isConditional = (($this->get(1) !== "\x00"));
}else{
//Minecart with command block
$this->minecartEid = $this->getEntityRuntimeId();
}
$this->command = $this->getString();
$this->lastOutput = $this->getString();
$this->name = $this->getString();
$this->shouldTrackOutput = (($this->get(1) !== "\x00"));
}
protected function encodePayload(){
($this->buffer .= ($this->isBlock ? "\x01" : "\x00"));
if($this->isBlock){
$this->putBlockPosition($this->x, $this->y, $this->z);
$this->putUnsignedVarInt($this->commandBlockMode);
($this->buffer .= ($this->isRedstoneMode ? "\x01" : "\x00"));
($this->buffer .= ($this->isConditional ? "\x01" : "\x00"));
}else{
$this->putEntityRuntimeId($this->minecartEid);
}
$this->putString($this->command);
$this->putString($this->lastOutput);
$this->putString($this->name);
($this->buffer .= ($this->shouldTrackOutput ? "\x01" : "\x00"));
}
public function handle(NetworkSession $session) : bool{
return $session->handleCommandBlockUpdate($this);
}
}
| DualNova-Team/DualNova | src/pocketmine/network/mcpe/protocol/CommandBlockUpdatePacket.php | PHP | lgpl-3.0 | 2,760 |
<?php
/*
* This file is part of the Virtual-Identity Youtube package.
*
* (c) Virtual-Identity <dev.saga@virtual-identity.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace VirtualIdentity\YoutubeBundle\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;
use VirtualIdentity\YoutubeBundle\Interfaces\YoutubeEntityInterface;
class YoutubeChangedEvent extends Event
{
/**
* The youtube that changed
*
* @var YoutubeEntityInterface
*/
protected $youtube;
public function __construct(YoutubeEntityInterface $youtube)
{
$this->youtube = $youtube;
}
/**
* Returns the changed youtube
*
* @return YoutubeEntityInterface
*/
public function getYoutube()
{
return $this->youtube;
}
} | virtualidentityag/hydra-youtube | src/VirtualIdentity/YoutubeBundle/EventDispatcher/YoutubeChangedEvent.php | PHP | lgpl-3.0 | 882 |
<?php
/*
* Copyright (c) 2012-2016, Hofmänner New Media.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of the N2N FRAMEWORK.
*
* The N2N FRAMEWORK 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.
*
* N2N 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: http://www.gnu.org/licenses/
*
* The following people participated in this project:
*
* Andreas von Burg.....: Architect, Lead Developer
* Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
* Thomas Günther.......: Developer, Hangar
*/
namespace n2n\web\dispatch\map\val;
use n2n\web\dispatch\map\PropertyPathPart;
use n2n\util\type\ArgUtils;
abstract class SimplePropertyValidator extends SinglePropertyValidator {
private $pathPart;
protected function validateProperty($mapValue) {
$managedProperty = $this->getManagedProperty();
if (!$managedProperty->isArray()) {
$this->pathPart = new PropertyPathPart($managedProperty->getName());
$this->validateValue($mapValue);
$this->pathPart = null;
return;
}
ArgUtils::valArrayLike($mapValue);
foreach ($mapValue as $aKey => $aValue) {
$this->pathPart = new PropertyPathPart($managedProperty->getName(), true, $aKey);
if ($this->getBindingErrors()->hasErrors($this->pathPart)) {
continue;
}
$this->validateValue($aValue, $this->pathPart, $this->getBindingErrors());
$this->pathPart = null;
}
}
protected function getPathPart() {
return $this->pathPart;
}
protected abstract function validateValue($mapValue);
}
| n2n/n2n-web | src/app/n2n/web/dispatch/map/val/SimplePropertyValidator.php | PHP | lgpl-3.0 | 1,990 |
/*
* AUTHOR : Emmanuel Pietriga (emmanuel.pietriga@inria.fr)
* Copyright (c) INRIA, 2008-2010. All Rights Reserved
* Licensed under the GNU LGPL. For full terms see the file COPYING.
*
* $Id: PieMenuR.java 4280 2011-02-28 15:36:54Z rprimet $
*/
package fr.inria.zvtm.widgets;
import fr.inria.zvtm.animation.Animation;
import fr.inria.zvtm.animation.interpolation.IdentityInterpolator;
import fr.inria.zvtm.engine.Utils;
import fr.inria.zvtm.engine.VirtualSpaceManager;
import fr.inria.zvtm.glyphs.VCircle;
import fr.inria.zvtm.glyphs.VRing;
import fr.inria.zvtm.glyphs.VText;
import fr.inria.zvtm.glyphs.VTextOr;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.Point2D;
/**
* Circular pie menu with dead zone at its center.
*/
public class PieMenuR extends PieMenu {
public static final int animStartSize = 5;
/**
* Pie Menu constructor - should not be used directly
*
* @param stringLabels text label of each menu item
* @param menuCenterCoordinates (mouse cursor's coordinates in virtual space as a Point2D.Double)
* @param vsName name of the virtual space in which to create the pie menu
* @param vsm instance of VirtualSpaceManager
* @param radius radius of pie menu
* @param irr Inner ring boundary radius as a percentage of outer ring boundary radius
* @param startAngle first menu item will have an offset of startAngle interpreted relative to the X horizontal axis (counter clockwise)
* @param fillColors menu items' fill colors (this array should have the same length as the stringLabels array)
* @param borderColors menu items' border colors (this array should have the same length as the stringLabels array)
* @param fillSColors menu items' fill colors, when selected (this array should have the same length as the stringLabels array)<br>elements can be null if color should not change
* @param borderSColors menu items' border colors, when selected (this array should have the same length as the stringLabels array)<br>elements can be null if color should not change
* @param alphaT menu items' translucency value: between 0 (transparent) and 1.0 (opaque)
* @param animDuration duration in ms of animation creating the menu (expansion) - 0 for instantaneous display
* @param sensitRadius sensitivity radius (as a percentage of the menu's actual radius)
* @param font font used for menu labels
* @param labelOffsets x,y offset of each menu label w.r.t their default posisition, in virtual space units<br>(this array should have the same length as the labels array)
*/
public PieMenuR(String[] stringLabels, Point2D.Double menuCenterCoordinates,
String vsName, VirtualSpaceManager vsm,
double radius, float irr, double startAngle, double angleWidth,
Color[] fillColors, Color[] borderColors, Color[] fillSColors, Color[] borderSColors, Color[] labelColors, float alphaT,
int animDuration, double sensitRadius, Font font, Point2D.Double[] labelOffsets) {
this.vs = vsm.getVirtualSpace(vsName);
double vx = menuCenterCoordinates.x;
double vy = menuCenterCoordinates.y;
items = new VRing[stringLabels.length];
labels = new VTextOr[stringLabels.length];
double angle = startAngle;
double angleDelta = angleWidth / ((double)stringLabels.length);
double pieMenuRadius = radius;
double textAngle;
for (int i = 0; i < labels.length; i++) {
angle += angleDelta;
items[i] = new VRing(vx, vy, 0, (animDuration > 0) ? animStartSize : pieMenuRadius, angleDelta, irr, angle, fillColors[i], borderColors[i], alphaT);
items[i].setCursorInsideFillColor(fillSColors[i]);
items[i].setCursorInsideHighlightColor(borderSColors[i]);
vs.addGlyph(items[i], false, false);
if (stringLabels[i] != null && stringLabels[i].length() > 0) {
if (orientText) {
textAngle = angle;
if (angle > Utils.HALF_PI) {
if (angle > Math.PI) {
if (angle < Utils.THREE_HALF_PI) {
textAngle -= Math.PI;
}
} else {
textAngle += Math.PI;
}
}
labels[i] = new VTextOr(vx + Math.cos(angle) * pieMenuRadius / 2 + labelOffsets[i].x,
vy + Math.sin(angle) * pieMenuRadius / 2 + labelOffsets[i].y,
0, labelColors[i], stringLabels[i], textAngle, VText.TEXT_ANCHOR_MIDDLE);
} else {
labels[i] = new VTextOr(vx + Math.cos(angle) * pieMenuRadius / 2 + labelOffsets[i].x,
vy + Math.sin(angle) * pieMenuRadius / 2 + labelOffsets[i].y,
0, labelColors[i], stringLabels[i], 0, VText.TEXT_ANCHOR_MIDDLE);
}
labels[i].setBorderColor(borderColors[i]);
labels[i].setFont(font);
labels[i].setSensitivity(false);
vs.addGlyph(labels[i]);
}
}
if (animDuration > 0) {
for (int i = 0; i < items.length; i++) {
Animation sizeAnim = vsm.getAnimationManager().getAnimationFactory().createGlyphSizeAnim(animDuration, items[i],
(float)pieMenuRadius,
false,
IdentityInterpolator.getInstance(),
null);
vsm.getAnimationManager().startAnimation(sizeAnim, false);
}
}
boundary = new VCircle(vx, vy, 0, pieMenuRadius * sensitRadius * 2, Color.white);
boundary.setVisible(false);
vs.addGlyph(boundary);
vs.atBottom(boundary);
}
}
| sharwell/zgrnbviewer | org-tvl-netbeans-zgrviewer/src/fr/inria/zvtm/widgets/PieMenuR.java | Java | lgpl-3.0 | 6,530 |
package de.synesthesy.music.key.nn;
import org.encog.neural.networks.BasicNetwork;
import de.synesthesy.csv.CSVTestSetInOutput;
public interface IMusicKeyNN {
public BasicNetwork getNetwork();
public int getIns();
public int getOuts();
public int[] getHiddenNeurons();
public double[] compute(double[] input);
public void train(CSVTestSetInOutput testSet);
} | synesthesy/synesthesy-core | src/main/java/de/synesthesy/music/key/nn/IMusicKeyNN.java | Java | lgpl-3.0 | 369 |
(function (window, $, undefined) {
$.infinitescroll = function infscr(options, callback, element) {
this.element = $(element);
this._create(options, callback);
};
$.infinitescroll.defaults = {
loading: {
finished: undefined,
finishedMsg: "",
img: "http://www.infinite-scroll.com/loading.gif",
msg: null,
msgText: "<em>Loading the next set of posts...</em>",
selector: null,
speed: 'fast',
start: undefined
},
state: {
isDuringAjax: false,
isInvalidPage: false,
isDestroyed: false,
isDone: false,
isPaused: false,
currPage: 1
},
callback: undefined,
debug: false,
behavior: undefined,
binder: $(window),
nextSelector: "div.navigation a:first",
navSelector: "div.navigation",
contentSelector: null,
extraScrollPx: 150,
itemSelector: "div.post",
animate: false,
pathParse: undefined,
dataType: 'html',
appendCallback: true,
bufferPx: 40,
errorCallback: function () { },
infid: 0,
pixelsFromNavToBottom: undefined,
path: undefined
};
$.infinitescroll.prototype = {
_binding: function infscr_binding(binding) {
var instance = this,
opts = instance.options;
if (!!opts.behavior && this['_binding_' + opts.behavior] !== undefined) {
this['_binding_' + opts.behavior].call(this);
return;
}
if (binding !== 'bind' && binding !== 'unbind') {
this._debug('Binding value ' + binding + ' not valid')
return false;
}
if (binding == 'unbind') {
(this.options.binder).unbind('smartscroll.infscr.' + instance.options.infid);
} else {
(this.options.binder)[binding]('smartscroll.infscr.' + instance.options.infid,
function () {
instance.scroll();
});
};
this._debug('Binding', binding);
},
//2013-2-5 15:52:02 ÐÞ¸ÄÆÙ²¼Á÷µÚÒ»´Î¼ÓÔØµÄʱºò¿ÉÄÜ»á³öÏÖÊý¾Ý²»¹»µÄÇé¿ö
loadDataOnCreat: function () {
var _this = this;
setTimeout(function () {
if ($(document).height() - $(window).height() < 20) {
_this.scroll();
_this.loadDataOnCreat();
}
}, 3000);
},
_create: function infscr_create(options, callback) {
if (!this._validate(options)) {
return false;
}
var opts = this.options = $.extend(true, {},
$.infinitescroll.defaults, options),
relurl = /(.*?\/\/).*?(\/.*)/,
path = $(opts.nextSelector).attr('href');
opts.contentSelector = opts.contentSelector || this.element;
opts.loading.selector = opts.loading.selector || opts.contentSelector;
if (!path) {
this._debug('Navigation selector not found');
return;
}
opts.path = this._determinepath(path);
opts.loading.msg = $('<div id="infscr-loading" class="tn-loading"></div>'); (new Image()).src = opts.loading.img;
opts.pixelsFromNavToBottom = $(document).height() - $(opts.navSelector).offset().top;
opts.loading.start = opts.loading.start ||
function () {
$(opts.navSelector).hide();
opts.loading.msg.appendTo(opts.loading.selector).show(opts.loading.speed,
function () {
beginAjax(opts);
});
};
opts.loading.finished = opts.loading.finished ||
function () {
opts.loading.msg.fadeOut('normal');
};
opts.callback = function (instance, data) {
if (!!opts.behavior && instance['_callback_' + opts.behavior] !== undefined) {
instance['_callback_' + opts.behavior].call($(opts.contentSelector)[0], data);
}
if (callback) {
callback.call($(opts.contentSelector)[0], data);
}
};
this._setup();
//2013-2-5 15:52:02 ÐÞ¸ÄÆÙ²¼Á÷µÚÒ»´Î¼ÓÔØµÄʱºò¿ÉÄÜ»á³öÏÖÊý¾Ý²»¹»µÄÇé¿ö
this.loadDataOnCreat();
},
_debug: function infscr_debug() {
if (this.options.debug) {
return window.console && console.log.call(console, arguments);
}
},
_determinepath: function infscr_determinepath(path) {
var opts = this.options;
if (!!opts.behavior && this['_determinepath_' + opts.behavior] !== undefined) {
this['_determinepath_' + opts.behavior].call(this, path);
return;
}
if (!!opts.pathParse) {
this._debug('pathParse manual');
return opts.pathParse;
} else if (path.match(/^(.*?)\b2\b(.*?$)/)) {
path = path.match(/^(.*?)\b2\b(.*?$)/).slice(1);
} else if (path.match(/^(.*?)2(.*?$)/)) {
if (path.match(/^(.*?page=)2(\/.*|$)/)) {
path = path.match(/^(.*?page=)2(\/.*|$)/).slice(1);
return path;
}
path = path.match(/^(.*?)2(.*?$)/).slice(1);
} else {
if (path.match(/^(.*?page=)1(\/.*|$)/)) {
path = path.match(/^(.*?page=)1(\/.*|$)/).slice(1);
return path;
} else {
this._debug('Sorry, we couldn\'t parse your Next (Previous Posts) URL. Verify your the css selector points to the correct A tag. If you still get this error: yell, scream, and kindly ask for help at infinite-scroll.com.');
opts.state.isInvalidPage = true;
}
}
this._debug('determinePath', path);
return path;
},
_error: function infscr_error(xhr) {
var opts = this.options;
if (!!opts.behavior && this['_error_' + opts.behavior] !== undefined) {
this['_error_' + opts.behavior].call(this, xhr);
return;
}
if (xhr !== 'destroy' && xhr !== 'end') {
xhr = 'unknown';
}
this._debug('Error', xhr);
if (xhr == 'end') {
this._showdonemsg();
}
opts.state.isDone = true;
opts.state.currPage = 1;
opts.state.isPaused = false;
this._binding('unbind');
},
_loadcallback: function infscr_loadcallback(box, data) {
var opts = this.options,
callback = this.options.callback,
result = (opts.state.isDone) ? 'done' : (!opts.appendCallback) ? 'no-append' : 'append',
frag;
if (!!opts.behavior && this['_loadcallback_' + opts.behavior] !== undefined) {
this['_loadcallback_' + opts.behavior].call(this, box, data);
return;
}
switch (result) {
case 'done':
this._showdonemsg();
return false;
break;
case 'no-append':
if (opts.dataType == 'html') {
data = '<div>' + data + '</div>';
data = $(data).find(opts.itemSelector);
};
break;
case 'append':
var children = box.children();
if (children.length == 0) {
return this._error('end');
}
frag = document.createDocumentFragment();
while (box[0].firstChild) {
frag.appendChild(box[0].firstChild);
}
this._debug('contentSelector', $(opts.contentSelector)[0])
$(opts.contentSelector)[0].appendChild(frag);
data = children.get();
break;
}
opts.loading.finished.call($(opts.contentSelector)[0], opts)
if (opts.animate) {
var scrollTo = $(window).scrollTop() + $('#infscr-loading').height() + opts.extraScrollPx + 'px';
$('html,body').animate({
scrollTop: scrollTo
},
800,
function () {
opts.state.isDuringAjax = false;
});
}
if (!opts.animate) opts.state.isDuringAjax = false;
callback(this, data);
},
_nearbottom: function infscr_nearbottom() {
var opts = this.options,
pixelsFromWindowBottomToBottom = 0 + $(document).height() - (opts.binder.scrollTop()) - $(window).height();
if (!!opts.behavior && this['_nearbottom_' + opts.behavior] !== undefined) {
this['_nearbottom_' + opts.behavior].call(this);
return;
}
this._debug('math:', pixelsFromWindowBottomToBottom, opts.pixelsFromNavToBottom);
return (pixelsFromWindowBottomToBottom - opts.bufferPx < opts.pixelsFromNavToBottom);
},
_pausing: function infscr_pausing(pause) {
var opts = this.options;
if (!!opts.behavior && this['_pausing_' + opts.behavior] !== undefined) {
this['_pausing_' + opts.behavior].call(this, pause);
return;
}
if (pause !== 'pause' && pause !== 'resume' && pause !== null) {
this._debug('Invalid argument. Toggling pause value instead');
};
pause = (pause && (pause == 'pause' || pause == 'resume')) ? pause : 'toggle';
switch (pause) {
case 'pause':
opts.state.isPaused = true;
break;
case 'resume':
opts.state.isPaused = false;
break;
case 'toggle':
opts.state.isPaused = !opts.state.isPaused;
break;
}
this._debug('Paused', opts.state.isPaused);
return false;
},
_setup: function infscr_setup() {
var opts = this.options;
if (!!opts.behavior && this['_setup_' + opts.behavior] !== undefined) {
this['_setup_' + opts.behavior].call(this);
return;
}
this._binding('bind');
return false;
},
_showdonemsg: function infscr_showdonemsg() {
var opts = this.options;
if (!!opts.behavior && this['_showdonemsg_' + opts.behavior] !== undefined) {
this['_showdonemsg_' + opts.behavior].call(this);
return;
}
opts.loading.msg.find('img').hide().parent().find('div').html(opts.loading.finishedMsg).animate({
opacity: 1
},
2000,
function () {
$(this).parent().fadeOut('normal');
});
$('#infscr-loading').hide();
opts.errorCallback.call($(opts.contentSelector)[0], 'done');
},
_validate: function infscr_validate(opts) {
for (var key in opts) {
if (key.indexOf && key.indexOf('Selector') > -1 && $(opts[key]).length === 0) {
this._debug('Your ' + key + ' found no elements.');
return false;
}
return true;
}
},
bind: function infscr_bind() {
this._binding('bind');
},
destroy: function infscr_destroy() {
this.options.state.isDestroyed = true;
return this._error('destroy');
},
pause: function infscr_pause() {
this._pausing('pause');
},
resume: function infscr_resume() {
this._pausing('resume');
},
retrieve: function infscr_retrieve(pageNum) {
var instance = this,
opts = instance.options,
path = opts.path,
box,
frag,
desturl,
method,
condition,
pageNum = pageNum || null,
getPage = (!!pageNum) ? pageNum : opts.state.currPage;
beginAjax = function infscr_ajax(opts) {
opts.state.currPage++;
instance._debug('heading into ajax', path);
box = $(opts.contentSelector).is('table') ? $('<tbody/>') : $('<div/>');
desturl = path.join(opts.state.currPage);
method = (opts.dataType == 'html' || opts.dataType == 'json') ? opts.dataType : 'html+callback';
if (opts.appendCallback && opts.dataType == 'html') method += '+callback'
switch (method) {
case 'html+callback':
instance._debug('Using HTML via .load() method');
box.load(desturl + ' ' + opts.itemSelector, null,
function infscr_ajax_callback(responseText) {
instance._loadcallback(box, responseText);
});
break;
case 'html':
case 'json':
instance._debug('Using ' + (method.toUpperCase()) + ' via $.ajax() method');
$.ajax({
url: desturl,
dataType: opts.dataType,
complete: function infscr_ajax_callback(jqXHR, textStatus) {
condition = (typeof (jqXHR.isResolved) !== 'undefined') ? (jqXHR.isResolved()) : (textStatus === "success" || textStatus === "notmodified"); (condition) ? instance._loadcallback(box, jqXHR.responseText) : instance._error('end');
}
});
break;
}
};
if (!!opts.behavior && this['retrieve_' + opts.behavior] !== undefined) {
this['retrieve_' + opts.behavior].call(this, pageNum);
return;
}
if (opts.state.isDestroyed) {
this._debug('Instance is destroyed');
return false;
};
opts.state.isDuringAjax = true;
opts.loading.start.call($(opts.contentSelector)[0], opts);
},
scroll: function infscr_scroll() {
var opts = this.options,
state = opts.state;
if (!!opts.behavior && this['scroll_' + opts.behavior] !== undefined) {
this['scroll_' + opts.behavior].call(this);
return;
}
if (state.isDuringAjax || state.isInvalidPage || state.isDone || state.isDestroyed || state.isPaused) return;
if (!this._nearbottom()) return;
this.retrieve();
},
toggle: function infscr_toggle() {
this._pausing();
},
unbind: function infscr_unbind() {
this._binding('unbind');
},
update: function infscr_options(key) {
if ($.isPlainObject(key)) {
this.options = $.extend(true, this.options, key);
}
}
}
$.fn.infinitescroll = function infscr_init(options, callback) {
var thisCall = typeof options;
switch (thisCall) {
case 'string':
var args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
var instance = $.data(this, 'infinitescroll');
if (!instance) {
return false;
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
return false;
}
instance[options].apply(instance, args);
});
break;
case 'object':
this.each(function () {
var instance = $.data(this, 'infinitescroll');
if (instance) {
instance.update(options);
} else {
$.data(this, 'infinitescroll', new $.infinitescroll(options, callback, this));
}
});
break;
}
return this;
};
var event = $.event,
scrollTimeout;
event.special.smartscroll = {
setup: function () {
$(this).bind("scroll", event.special.smartscroll.handler);
},
teardown: function () {
$(this).unbind("scroll", event.special.smartscroll.handler);
},
handler: function (event, execAsap) {
var context = this,
args = arguments;
event.type = "smartscroll";
if (scrollTimeout) {
clearTimeout(scrollTimeout);
}
scrollTimeout = setTimeout(function () {
$.event.handle.apply(context, args);
},
execAsap === "execAsap" ? 0 : 100);
}
};
$.fn.smartscroll = function (fn) {
return fn ? this.bind("smartscroll", fn) : this.trigger("smartscroll", ["execAsap"]);
};
})(window, jQuery); | yesan/Spacebuilder | Web/Scripts/jquery/masonry/jquery.infinitescroll.js | JavaScript | lgpl-3.0 | 17,301 |
/*
* @BEGIN LICENSE
*
* Forte: an open-source plugin to Psi4 (https://github.com/psi4/psi4)
* t hat implements a variety of quantum chemistry methods for strongly
* correlated electrons.
*
* Copyright (c) 2012-2022 by its authors (see LICENSE, AUTHORS).
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* @END LICENSE
*/
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include "helpers/helpers.h"
#include "base_classes/rdms.h"
namespace py = pybind11;
using namespace pybind11::literals;
namespace forte {
/// Export the RDMs class
void export_RDMs(py::module& m) {
py::class_<RDMs>(m, "RDMs")
.def("max_rdm_level", &RDMs::max_rdm_level, "Return the max RDM level")
.def("ms_avg", &RDMs::ms_avg, "Return if RDMs setup is Ms-averaged")
.def(
"g1a", [](RDMs& rdm) { return ambit_to_np(rdm.g1a()); },
"Return the alpha 1RDM as a numpy array")
.def(
"g1b", [](RDMs& rdm) { return ambit_to_np(rdm.g1b()); },
"Return the beta 1RDM as a numpy array")
.def(
"g2aa", [](RDMs& rdm) { return ambit_to_np(rdm.g2aa()); },
"Return the alpha-alpha 2RDM as a numpy array")
.def(
"g2ab", [](RDMs& rdm) { return ambit_to_np(rdm.g2ab()); },
"Return the alpha-beta 2RDM as a numpy array")
.def(
"g2bb", [](RDMs& rdm) { return ambit_to_np(rdm.g2bb()); },
"Return the beta-beta 2RDM as a numpy array")
.def(
"g3aaa", [](RDMs& rdm) { return ambit_to_np(rdm.g3aaa()); },
"Return the alpha-alpha-alpha 3RDM as a numpy array")
.def(
"g3aab", [](RDMs& rdm) { return ambit_to_np(rdm.g3aab()); },
"Return the alpha-alpha-beta 3RDM as a numpy array")
.def(
"g3abb", [](RDMs& rdm) { return ambit_to_np(rdm.g3abb()); },
"Return the alpha-beta-beta 3RDM as a numpy array")
.def(
"g3bbb", [](RDMs& rdm) { return ambit_to_np(rdm.g3bbb()); },
"Return the beta-beta-beta 3RDM as a numpy array")
.def(
"L2aa", [](RDMs& rdm) { return ambit_to_np(rdm.L2aa()); },
"Return the alpha-alpha 2-cumulant as a numpy array")
.def(
"L2ab", [](RDMs& rdm) { return ambit_to_np(rdm.L2ab()); },
"Return the alpha-beta 2-cumulant as a numpy array")
.def(
"L2bb", [](RDMs& rdm) { return ambit_to_np(rdm.L2bb()); },
"Return the beta-beta 2-cumulant as a numpy array")
.def(
"L3aaa", [](RDMs& rdm) { return ambit_to_np(rdm.L3aaa()); },
"Return the alpha-alpha-alpha 3-cumulant as a numpy array")
.def(
"L3aab", [](RDMs& rdm) { return ambit_to_np(rdm.L3aab()); },
"Return the alpha-alpha-beta 3-cumulant as a numpy array")
.def(
"L3abb", [](RDMs& rdm) { return ambit_to_np(rdm.L3abb()); },
"Return the alpha-beta-beta 3-cumulant as a numpy array")
.def(
"L3bbb", [](RDMs& rdm) { return ambit_to_np(rdm.L3bbb()); },
"Return the beta-beta-beta 3-cumulant as a numpy array")
.def("SF_G1mat", py::overload_cast<>(&RDMs::SF_G1mat),
"Return the spin-free 1RDM as a Psi4 Matrix without symmetry")
.def("SF_G1mat", py::overload_cast<const psi::Dimension&>(&RDMs::SF_G1mat),
"Return the spin-free 1RDM as a Psi4 Matrix with symmetry given by input")
.def(
"SF_G1", [](RDMs& rdm) { return ambit_to_np(rdm.SF_G1()); },
"Return the spin-free 1RDM as a numpy array")
.def(
"SF_G2", [](RDMs& rdm) { return ambit_to_np(rdm.SF_G2()); },
"Return the spin-free 2RDM as a numpy array")
.def(
"SF_L1", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L1()); },
"Return the spin-free 1RDM as a numpy array")
.def(
"SF_L2", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L2()); },
"Return the spin-free (Ms-averaged) 2-cumulant as a numpy array")
.def(
"SF_L3", [](RDMs& rdm) { return ambit_to_np(rdm.SF_L3()); },
"Return the spin-free (Ms-averaged) 2-cumulant as a numpy array")
.def("rotate", &RDMs::rotate, "Ua"_a, "Ub"_a,
"Rotate RDMs using the input unitary matrices");
}
} // namespace forte
| evangelistalab/forte | forte/api/rdms_api.cc | C++ | lgpl-3.0 | 5,090 |
/*
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 "deletefunctiondefinitionrequest.h"
#include "deletefunctiondefinitionrequest_p.h"
#include "deletefunctiondefinitionresponse.h"
#include "greengrassrequest_p.h"
namespace QtAws {
namespace Greengrass {
/*!
* \class QtAws::Greengrass::DeleteFunctionDefinitionRequest
* \brief The DeleteFunctionDefinitionRequest class provides an interface for Greengrass DeleteFunctionDefinition requests.
*
* \inmodule QtAwsGreengrass
*
* AWS IoT Greengrass seamlessly extends AWS onto physical devices so they can act locally on the data they generate, while
* still using the cloud for management, analytics, and durable storage. AWS IoT Greengrass ensures your devices can
* respond quickly to local events and operate with intermittent connectivity. AWS IoT Greengrass minimizes the cost of
*
* \sa GreengrassClient::deleteFunctionDefinition
*/
/*!
* Constructs a copy of \a other.
*/
DeleteFunctionDefinitionRequest::DeleteFunctionDefinitionRequest(const DeleteFunctionDefinitionRequest &other)
: GreengrassRequest(new DeleteFunctionDefinitionRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a DeleteFunctionDefinitionRequest object.
*/
DeleteFunctionDefinitionRequest::DeleteFunctionDefinitionRequest()
: GreengrassRequest(new DeleteFunctionDefinitionRequestPrivate(GreengrassRequest::DeleteFunctionDefinitionAction, this))
{
}
/*!
* \reimp
*/
bool DeleteFunctionDefinitionRequest::isValid() const
{
return false;
}
/*!
* Returns a DeleteFunctionDefinitionResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * DeleteFunctionDefinitionRequest::response(QNetworkReply * const reply) const
{
return new DeleteFunctionDefinitionResponse(*this, reply);
}
/*!
* \class QtAws::Greengrass::DeleteFunctionDefinitionRequestPrivate
* \brief The DeleteFunctionDefinitionRequestPrivate class provides private implementation for DeleteFunctionDefinitionRequest.
* \internal
*
* \inmodule QtAwsGreengrass
*/
/*!
* Constructs a DeleteFunctionDefinitionRequestPrivate object for Greengrass \a action,
* with public implementation \a q.
*/
DeleteFunctionDefinitionRequestPrivate::DeleteFunctionDefinitionRequestPrivate(
const GreengrassRequest::Action action, DeleteFunctionDefinitionRequest * const q)
: GreengrassRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the DeleteFunctionDefinitionRequest
* class' copy constructor.
*/
DeleteFunctionDefinitionRequestPrivate::DeleteFunctionDefinitionRequestPrivate(
const DeleteFunctionDefinitionRequestPrivate &other, DeleteFunctionDefinitionRequest * const q)
: GreengrassRequestPrivate(other, q)
{
}
} // namespace Greengrass
} // namespace QtAws
| pcolby/libqtaws | src/greengrass/deletefunctiondefinitionrequest.cpp | C++ | lgpl-3.0 | 3,578 |
/**
* This file is part of topicmodeling.io.
*
* topicmodeling.io 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.
*
* topicmodeling.io 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 topicmodeling.io. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dice_research.topicmodeling.io.xml;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import org.dice_research.topicmodeling.utils.doc.Document;
import org.dice_research.topicmodeling.utils.doc.DocumentMultipleCategories;
import org.dice_research.topicmodeling.utils.doc.DocumentText;
import org.dice_research.topicmodeling.utils.doc.ParseableDocumentProperty;
import org.dice_research.topicmodeling.utils.doc.ner.NamedEntitiesInText;
import org.dice_research.topicmodeling.utils.doc.ner.NamedEntityInText;
import org.dice_research.topicmodeling.utils.doc.ner.SignedNamedEntityInText;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractDocumentXmlReader implements XMLParserObserver {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDocumentXmlReader.class);
private Document currentDocument;
private NamedEntityInText currentNamedEntity;
private List<NamedEntityInText> namedEntities = new ArrayList<NamedEntityInText>();
private List<String> categories = new ArrayList<String>();
private StringBuilder textBuffer = new StringBuilder();
private String data;
public AbstractDocumentXmlReader() {
}
@Override
public void handleOpeningTag(String tagString) {
// SHOULDN'T THIS METHOD SET data=""? Otherwise it is possible that a
// closing tag gets data that was set
// before its starting tag has been seen (in most cases this is "\n").
data = "";
// Ok, this is done and the JUnit test is green. This comment will
// remain here if another problem should
// arose.
int pos = tagString.indexOf(' ');
String tagName;
if (pos == -1) {
tagName = tagString;
} else {
tagName = tagString.substring(0, pos);
}
if (tagName.equals(CorpusXmlTagHelper.DOCUMENT_TAG_NAME)) {
currentDocument = new Document();
pos = tagString.indexOf(" id=\"");
if (pos > 0) {
pos += 5;
int tmp = tagString.indexOf('"', pos + 1);
if (tmp > 0) {
try {
tmp = Integer.parseInt(tagString.substring(pos, tmp));
currentDocument.setDocumentId(tmp);
} catch (NumberFormatException e) {
LOGGER.warn("Coudln't parse the document id from the document tag.", e);
}
} else {
LOGGER.warn("Found a document tag without a document id attribute.");
}
}
} else if (tagName.equals(CorpusXmlTagHelper.NAMED_ENTITY_IN_TEXT_TAG_NAME)
|| tagName.equals(CorpusXmlTagHelper.SIGNED_NAMED_ENTITY_IN_TEXT_TAG_NAME)) {
currentNamedEntity = parseNamedEntityInText(tagString);
currentNamedEntity.setStartPos(textBuffer.length());
}
}
@Override
public void handleClosingTag(String tagString) {
if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_TAG_NAME)) {
finishedDocument(currentDocument);
currentDocument = null;
} else
if (tagString.equals(CorpusXmlTagHelper.TEXT_WITH_NAMED_ENTITIES_TAG_NAME) && (currentDocument != null)) {
currentDocument.addProperty(new DocumentText(textBuffer.toString()));
textBuffer.delete(0, textBuffer.length());
NamedEntitiesInText nes = new NamedEntitiesInText(namedEntities);
currentDocument.addProperty(nes);
namedEntities.clear();
} else if (tagString.equals(CorpusXmlTagHelper.TEXT_PART_TAG_NAME)) {
textBuffer.append(data);
data = "";
} else if (tagString.equals(CorpusXmlTagHelper.NAMED_ENTITY_IN_TEXT_TAG_NAME)
|| tagString.equals(CorpusXmlTagHelper.SIGNED_NAMED_ENTITY_IN_TEXT_TAG_NAME)) {
if (currentNamedEntity != null) {
currentNamedEntity.setLength(data.length());
namedEntities.add(currentNamedEntity);
textBuffer.append(data);
currentNamedEntity = null;
data = "";
}
} else if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_CATEGORIES_TAG_NAME)) {
currentDocument
.addProperty(new DocumentMultipleCategories(categories.toArray(new String[categories.size()])));
categories.clear();
} else if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_CATEGORIES_SINGLE_CATEGORY_TAG_NAME)) {
categories.add(data);
data = "";
} else {
if (currentDocument != null) {
Class<? extends ParseableDocumentProperty> propertyClazz = CorpusXmlTagHelper
.getParseableDocumentPropertyClassForTagName(tagString);
if (propertyClazz != null) {
try {
ParseableDocumentProperty property;
Constructor<? extends ParseableDocumentProperty> constructor;
try {
constructor = propertyClazz.getConstructor(String.class);
property = constructor.newInstance(data);
} catch (NoSuchMethodException e) {
// Couldn't get a constructor accepting a single
// String. Lets try the normal constructor.
constructor = propertyClazz.getConstructor();
property = constructor.newInstance();
property.parseValue(data);
}
currentDocument.addProperty(property);
} catch (Exception e) {
LOGGER.error("Couldn't parse property " + propertyClazz + " from the String \"" + data + "\".",
e);
}
}
data = "";
}
}
}
@Override
public void handleData(String data) {
this.data = data;
}
@Override
public void handleEmptyTag(String tagString) {
// nothing to do
}
protected NamedEntityInText parseNamedEntityInText(String tag) {
String namedEntityUri = null;
String namedEntitySource = null;
int startPos = -1;
int length = -1;
int start = 0, end = 0;
try {
start = tag.indexOf(' ') + 1;
end = tag.indexOf('=', start);
String key, value;
while (end > 0) {
key = tag.substring(start, end).trim();
end = tag.indexOf('"', end);
start = tag.indexOf('"', end + 1);
value = tag.substring(end + 1, start);
if (key.equals(CorpusXmlTagHelper.URI_ATTRIBUTE_NAME)) {
namedEntityUri = value;
} else if (key.equals(CorpusXmlTagHelper.SOURCE_ATTRIBUTE_NAME)) {
namedEntitySource = value;
}
/*
* else if (key.equals("start")) { startPos =
* Integer.parseInt(value); } else if (key.equals("length")) {
* length = Integer.parseInt(value); }
*/
++start;
end = tag.indexOf('=', start);
}
if (namedEntitySource != null) {
return new SignedNamedEntityInText(startPos, length, namedEntityUri, namedEntitySource);
} else {
return new NamedEntityInText(startPos, length, namedEntityUri);
}
} catch (Exception e) {
LOGGER.error("Couldn't parse NamedEntityInText tag (" + tag + "). Returning null.", e);
}
return null;
}
public static void registerParseableDocumentProperty(Class<? extends ParseableDocumentProperty> clazz) {
CorpusXmlTagHelper.registerParseableDocumentProperty(clazz);
}
protected abstract void finishedDocument(Document document);
}
| AKSW/topicmodeling | topicmodeling.io/src/main/java/org/dice_research/topicmodeling/io/xml/AbstractDocumentXmlReader.java | Java | lgpl-3.0 | 9,108 |
/*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.components.chart.property.widget;
import java.util.List;
import net.sf.jasperreports.charts.JRDataRange;
import net.sf.jasperreports.charts.design.JRDesignDataRange;
import net.sf.jasperreports.charts.util.JRMeterInterval;
import net.sf.jasperreports.eclipse.ui.util.UIUtils;
import net.sf.jasperreports.engine.JRExpression;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import com.jaspersoft.studio.components.chart.messages.Messages;
import com.jaspersoft.studio.editor.expression.ExpressionContext;
import com.jaspersoft.studio.model.APropertyNode;
import com.jaspersoft.studio.property.descriptor.NullEnum;
import com.jaspersoft.studio.property.descriptor.color.ColorCellEditor;
import com.jaspersoft.studio.property.descriptor.color.ColorLabelProvider;
import com.jaspersoft.studio.property.descriptor.expression.JRExpressionCellEditor;
import com.jaspersoft.studio.property.section.AbstractSection;
import com.jaspersoft.studio.swt.widgets.table.DeleteButton;
import com.jaspersoft.studio.swt.widgets.table.INewElement;
import com.jaspersoft.studio.swt.widgets.table.ListContentProvider;
import com.jaspersoft.studio.swt.widgets.table.ListOrderButtons;
import com.jaspersoft.studio.swt.widgets.table.NewButton;
import com.jaspersoft.studio.utils.AlfaRGB;
import com.jaspersoft.studio.utils.Colors;
import com.jaspersoft.studio.utils.Misc;
/**
* Dialog with a table that show all the meter intervals defined, and allow to edit, move
* delete and add them
*
* @author Orlandin Marco
*
*/
public class MeterIntervalsDialog extends Dialog {
/**
* Section used to get the selected element
*/
private AbstractSection section;
/**
* Descriptor of the property
*/
private IPropertyDescriptor pDescriptor;
/**
* List of the intervals actually shown in the table
*/
private List<JRMeterInterval> intervalsList;
/**
* Table where the intervals are shown
*/
private Table table;
/**
* Table viewer
*/
private TableViewer tableViewer;
/**
* Composite where the table is placed
*/
private Composite sectioncmp;
/**
* Cell editor for the low expression
*/
private JRExpressionCellEditor lowExp;
/**
* Cell editor for the high expression
*/
private JRExpressionCellEditor highExp;
/**
* Create the dialog
*
* @param parentShell parent shell
* @param section section of the element
* @param pDescriptor descriptor of the intervals property
* @param intervalsList list of the intervals already inside the meter chart
*/
public MeterIntervalsDialog(Shell parentShell, AbstractSection section, IPropertyDescriptor pDescriptor, List<JRMeterInterval> intervalsList) {
super(parentShell);
this.pDescriptor = pDescriptor;
this.intervalsList = intervalsList;
this.section = section;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.MeterIntervalsDialog_dialogTitle);
}
/**
*
* Custom label provider for the table
*
*/
private final class TLabelProvider extends LabelProvider implements ITableLabelProvider {
private ColorLabelProvider colorLabel = new ColorLabelProvider(NullEnum.NULL);
/**
* Return an image only on the second column of the table, the one with the color. The
* image show a sample of the color
*/
public Image getColumnImage(Object element, int columnIndex) {
JRMeterInterval mi = (JRMeterInterval) element;
switch (columnIndex) {
case 1:
AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor());
Double alfa = mi.getAlphaDouble();
color.setAlfa(alfa != null ? alfa : 1.0d);
return colorLabel.getImage(color);
}
return null;
}
/**
* Return an appropriate string for every column of the table
*/
public String getColumnText(Object element, int columnIndex) {
JRMeterInterval mi = (JRMeterInterval) element;
JRDataRange dataRange = mi.getDataRange();
switch (columnIndex) {
case 0:
return Misc.nvl(mi.getLabel(), ""); //$NON-NLS-1$
case 1:
AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor());
Double alfa = mi.getAlphaDouble();
color.setAlfa(alfa != null ? alfa : 1.0d);
RGB rgb = color.getRgb();
return "RGBA (" + rgb.red + "," + rgb.green + "," + rgb.blue + "," + color.getAlfa()+")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
case 2:
if (dataRange != null) {
JRExpression lowe = dataRange.getLowExpression();
return lowe != null ? lowe.getText() : ""; //$NON-NLS-1$
}
break;
case 3:
if (dataRange != null) {
JRExpression highe = dataRange.getHighExpression();
return highe != null ? highe.getText() : ""; //$NON-NLS-1$
}
break;
}
return ""; //$NON-NLS-1$
}
}
@Override
protected Control createDialogArea(Composite parent) {
sectioncmp = (Composite)super.createDialogArea(parent);
sectioncmp = new Composite(sectioncmp, SWT.NONE);
sectioncmp.setLayout(new GridLayout(2,false));
sectioncmp.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite bGroup = new Composite(sectioncmp, SWT.NONE);
bGroup.setLayout(new GridLayout(1, false));
bGroup.setLayoutData(new GridData(GridData.FILL_VERTICAL));
buildTable(sectioncmp);
new NewButton().createNewButtons(bGroup, tableViewer, new INewElement() {
public Object newElement(List<?> input, int pos) {
NewMeterIntervalWizard wizard = new NewMeterIntervalWizard();
WizardDialog dialog = new WizardDialog(UIUtils.getShell(), wizard);
if (dialog.open() == WizardDialog.OK){
return wizard.getMeterInterval();
} else return null;
}
});
new DeleteButton().createDeleteButton(bGroup, tableViewer);
new ListOrderButtons().createOrderButtons(bGroup, tableViewer);
table.setToolTipText(pDescriptor.getDescription());
//Set the content of the table
APropertyNode selctedNode = section.getElement();
if (selctedNode != null) {
ExpressionContext expContext = new ExpressionContext(selctedNode.getJasperConfiguration());
lowExp.setExpressionContext(expContext);
highExp.setExpressionContext(expContext);
}
tableViewer.setInput(intervalsList);
return sectioncmp;
}
/**
* Create the table element with all the cell editors
*
* @param composite parent of the table
*/
private void buildTable(Composite composite) {
table = new Table(composite, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.heightHint = 200;
gd.widthHint = 580;
table.setLayoutData(gd);
table.setHeaderVisible(true);
table.setLinesVisible(true);
tableViewer = new TableViewer(table);
tableViewer.setContentProvider(new ListContentProvider());
tableViewer.setLabelProvider(new TLabelProvider());
attachCellEditors(tableViewer, table);
TableLayout tlayout = new TableLayout();
tlayout.addColumnData(new ColumnWeightData(25));
tlayout.addColumnData(new ColumnWeightData(25));
tlayout.addColumnData(new ColumnWeightData(25));
tlayout.addColumnData(new ColumnWeightData(25));
table.setLayout(tlayout);
TableColumn[] column = new TableColumn[4];
column[0] = new TableColumn(table, SWT.NONE);
column[0].setText(Messages.MeterIntervalsDialog_label);
column[1] = new TableColumn(table, SWT.NONE);
column[1].setText(Messages.MeterIntervalsDialog_background);
column[2] = new TableColumn(table, SWT.NONE);
column[2].setText(Messages.MeterIntervalsDialog_lowExpression);
column[3] = new TableColumn(table, SWT.NONE);
column[3].setText(Messages.MeterIntervalsDialog_highExpression);
for (int i = 0, n = column.length; i < n; i++)
column[i].pack();
}
/**
* Attach the cell editor to the table
*
* @param viewer viewer of the table
* @param parent the table
*/
private void attachCellEditors(final TableViewer viewer, Composite parent) {
viewer.setCellModifier(new ICellModifier() {
//Every column can be modfied
public boolean canModify(Object element, String property) {
if (property.equals("LABEL")) //$NON-NLS-1$
return true;
if (property.equals("COLOR")) //$NON-NLS-1$
return true;
if (property.equals("HIGH")) //$NON-NLS-1$
return true;
if (property.equals("LOW")) //$NON-NLS-1$
return true;
return false;
}
public Object getValue(Object element, String property) {
JRMeterInterval mi = (JRMeterInterval) element;
if (property.equals("LABEL"))//$NON-NLS-1$
return mi.getLabel();
if (property.equals("COLOR")){//$NON-NLS-1$
AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor());
Double alfa = mi.getAlphaDouble();
color.setAlfa(alfa != null ? alfa : 1.0d);
return color;
}
if (property.equals("HIGH"))//$NON-NLS-1$
return mi.getDataRange().getHighExpression();
if (property.equals("LOW"))//$NON-NLS-1$
return mi.getDataRange().getLowExpression();
return null;
}
public void modify(Object element, String property, Object value) {
TableItem ti = (TableItem) element;
JRMeterInterval mi = (JRMeterInterval) ti.getData();
if (property.equals("LABEL")) {//$NON-NLS-1$
mi.setLabel((String) value);
}
if (property.equals("COLOR")) {//$NON-NLS-1$
AlfaRGB argb = (AlfaRGB) value;
mi.setBackgroundColor(Colors.getAWT4SWTRGBColor(argb));
mi.setAlpha(argb.getAlfa() / 255.0d);
}
if (property.equals("HIGH")) {//$NON-NLS-1$
((JRDesignDataRange) mi.getDataRange()).setHighExpression((JRExpression) value);
}
if (property.equals("LOW")) {//$NON-NLS-1$
((JRDesignDataRange) mi.getDataRange()).setLowExpression((JRExpression) value);
}
tableViewer.update(element, new String[] { property });
tableViewer.refresh();
propertyChange();
}
});
lowExp = new JRExpressionCellEditor(parent, null);
highExp = new JRExpressionCellEditor(parent, null);
ColorCellEditor argbColor = new ColorCellEditor(parent){
@Override
protected void updateContents(Object value) {
AlfaRGB argb = (AlfaRGB) value;
if (argb == null) {
rgbLabel.setText(""); //$NON-NLS-1$
} else {
RGB rgb = argb.getRgb();
rgbLabel.setText("RGBA (" + rgb.red + "," + rgb.green + "," + rgb.blue + "," + argb.getAlfa()+")");//$NON-NLS-4$ //$NON-NLS-5$//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$
}
}
};
viewer.setCellEditors(new CellEditor[] { new TextCellEditor(parent), argbColor, lowExp, highExp });
viewer.setColumnProperties(new String[] { "LABEL", "COLOR", "LOW", "HIGH" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
}
/**
* When something in the table change, the list of the element inside the table is update as well
*/
@SuppressWarnings("unchecked")
private void propertyChange() {
intervalsList = (List<JRMeterInterval>)tableViewer.getInput();
}
/**
* Return the list of the intervals actually shown in the table
*
* @return a list of intervals, can be null
*/
public List<JRMeterInterval> getIntervalsList(){
return intervalsList;
}
}
| OpenSoftwareSolutions/PDFReporter-Studio | com.jaspersoft.studio.components/src/com/jaspersoft/studio/components/chart/property/widget/MeterIntervalsDialog.java | Java | lgpl-3.0 | 12,609 |
//
// This file is part of the Tioga software library
//
// Tioga is a tool for overset grid assembly on parallel distributed systems
// Copyright (C) 2015 Jay Sitaraman
//
// This library is TIOGA_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
#include "codetypes.h"
#include "MeshBlock.h"
#include <cstring>
#include <stdexcept>
extern "C" {
void findOBB(double *x,double xc[3],double dxc[3],double vec[3][3],int nnodes);
double computeCellVolume(double xv[8][3],int nvert);
void deallocateLinkList(DONORLIST *temp);
void deallocateLinkList2(INTEGERLIST *temp);
double tdot_product(double a[3],double b[3],double c[3]);
void getobbcoords(double xc[3],double dxc[3],double vec[3][3],double xv[8][3]);
void transform2OBB(double xv[3],double xc[3],double vec[3][3],double xd[3]);
void writebbox(OBB *obb,int bid);
void writebboxdiv(OBB *obb,int bid);
}
void MeshBlock::setData(int btag,int nnodesi,double *xyzi, int *ibli,int nwbci, int nobci,
int *wbcnodei,int *obcnodei,
int ntypesi,int *nvi,int *nci,int **vconni,
uint64_t* cell_gid, uint64_t* node_gid)
{
int i;
//
// set internal pointers
//
meshtag=btag;
nnodes=nnodesi;
x=xyzi;
iblank=ibli;
nwbc=nwbci;
nobc=nobci;
wbcnode=wbcnodei;
obcnode=obcnodei;
//
ntypes=ntypesi;
//
nv=nvi;
nc=nci;
vconn=vconni;
cellGID = cell_gid;
nodeGID = node_gid;
//
//TRACEI(nnodes);
//for(i=0;i<ntypes;i++) TRACEI(nc[i]);
ncells=0;
for(i=0;i<ntypes;i++) ncells+=nc[i];
#ifdef TIOGA_HAS_NODEGID
if (nodeGID == NULL)
throw std::runtime_error("#tioga: global IDs for nodes not provided");
#endif
}
void MeshBlock::preprocess(void)
{
int i;
//
// set all iblanks = 1
//
for(i=0;i<nnodes;i++) iblank[i]=1;
//
// find oriented bounding boxes
//
if (check_uniform_hex_flag) {
check_for_uniform_hex();
if (uniform_hex) create_hex_cell_map();
}
if (obb) TIOGA_FREE(obb);
obb=(OBB *) malloc(sizeof(OBB));
findOBB(x,obb->xc,obb->dxc,obb->vec,nnodes);
tagBoundary();
}
void MeshBlock::tagBoundary(void)
{
int i,j,k,n,m,ii;
int itag;
int inode[8];
double xv[8][3];
double vol;
int *iflag;
int nvert,i3;
FILE *fp;
char intstring[7];
char fname[80];
int *iextmp,*iextmp1;
int iex;
//
// do this only once
// i.e. when the meshblock is first
// initialized, cellRes would be NULL in this case
//
if(cellRes) TIOGA_FREE(cellRes);
if(nodeRes) TIOGA_FREE(nodeRes);
//
cellRes=(double *) malloc(sizeof(double)*ncells);
nodeRes=(double *) malloc(sizeof(double)*nnodes);
//
// this is a local array
//
iflag=(int *)malloc(sizeof(int)*nnodes);
iextmp=(int *) malloc(sizeof(double)*nnodes);
iextmp1=(int *) malloc(sizeof(double)*nnodes);
//
for(i=0;i<nnodes;i++) iflag[i]=0;
//
if (userSpecifiedNodeRes ==NULL && userSpecifiedCellRes ==NULL)
{
for(i=0;i<nnodes;i++) iflag[i]=0;
for(i=0;i<nnodes;i++) nodeRes[i]=0.0;
//
k=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
for(m=0;m<nvert;m++)
{
inode[m]=vconn[n][nvert*i+m]-BASE;
i3=3*inode[m];
for(j=0;j<3;j++)
xv[m][j]=x[i3+j];
}
vol=computeCellVolume(xv,nvert);
cellRes[k++]=(vol*resolutionScale);
for(m=0;m<nvert;m++)
{
iflag[inode[m]]++;
nodeRes[inode[m]]+=(vol*resolutionScale);
}
}
}
}
else
{
k=0;
for(n=0;n<ntypes;n++)
{
for(i=0;i<nc[n];i++)
{
cellRes[k]=userSpecifiedCellRes[k];
k++;
}
}
for(k=0;k<nnodes;k++) nodeRes[k]=userSpecifiedNodeRes[k];
}
for(int j=0;j<3;j++)
{
mapdims[j]=10;
mapdx[j]=2*obb->dxc[j]/mapdims[j];
}
//
// compute nodal resolution as the average of
// all the cells associated with it. This takes care
// of partition boundaries as well.
//
// Also create the inverse map of nodes
//
if (icft) TIOGA_FREE(icft);
icft=(int *)malloc(sizeof(int)*(mapdims[2]*mapdims[1]*mapdims[0]+1));
if (invmap) TIOGA_FREE(invmap);
invmap=(int *)malloc(sizeof(int)*nnodes);
for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0]+1;i++) icft[i]=-1;
icft[0]=0;
int *iptr;
iptr=(int *)malloc(sizeof(int)*nnodes);
//
for(i=0;i<nnodes;i++)
{
double xd[3];
int idx[3];
if (iflag[i]!=0) nodeRes[i]/=iflag[i];
iflag[i]=0;
iextmp[i]=iextmp1[i]=0;
for(int j=0;j<3;j++)
{
xd[j]=obb->dxc[j];
for(int k=0;k<3;k++)
xd[j]+=(x[3*i+k]-obb->xc[k])*obb->vec[j][k];
idx[j]=xd[j]/mapdx[j];
}
int indx=idx[2]*mapdims[1]*mapdims[0]+idx[1]*mapdims[0]+idx[0];
iptr[i]=icft[indx+1];
icft[indx+1]=i;
}
int kc=0;
for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0];i++)
{
int ip=icft[i+1];
int m=0;
while(ip != -1)
{
invmap[kc++]=ip;
ip=iptr[ip];
m++;
}
icft[i+1]=icft[i]+m;
}
TIOGA_FREE(iptr);
//
// now tag the boundary nodes
// reuse the iflag array
//
//TRACEI(nobc);
for(i=0;i<nobc;i++)
{
ii=(obcnode[i]-BASE);
iflag[(obcnode[i]-BASE)]=1;
}
//
// now tag all the nodes of boundary cells
// to be mandatory receptors
// also make the inverse map mask
if (mapmask) TIOGA_FREE(mapmask);
mapmask=(int *)malloc(sizeof(int)*mapdims[2]*mapdims[1]*mapdims[0]);
for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0];i++) mapmask[i]=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
double xd[3],xc[3],xmin[3],xmax[3];
int idx[3];
itag=0;
for(int j=0;j<3;j++) { xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;}
for(m=0;m<nvert;m++)
{
inode[m]=vconn[n][nvert*i+m]-BASE;
if (iflag[inode[m]]) itag=1;
for(int j=0;j<3;j++)
{
xd[j]=obb->dxc[j];
for(int k=0;k<3;k++)
xd[j]+=(x[3*inode[m]+k]-obb->xc[k])*obb->vec[j][k];
xmin[j]=TIOGA_MIN(xd[j],xmin[j]);
xmax[j]=TIOGA_MAX(xd[j],xmax[j]);
}
}
for(int j=0;j<3;j++) { xmin[j]-=TOL; xmax[j]+=TOL;}
for(int j=xmin[0]/mapdx[0];j<=xmax[0]/mapdx[0];j++)
for(int k=xmin[1]/mapdx[1];k<=xmax[1]/mapdx[1];k++)
for(int l=xmin[2]/mapdx[2];l<=xmax[2]/mapdx[2];l++)
{
idx[0]=TIOGA_MAX(TIOGA_MIN(j,mapdims[0]-1),0);
idx[1]=TIOGA_MAX(TIOGA_MIN(k,mapdims[1]-1),0);
idx[2]=TIOGA_MAX(TIOGA_MIN(l,mapdims[2]-1),0);
mapmask[idx[2]*mapdims[1]*mapdims[0]+idx[1]*mapdims[0]+idx[0]]=1;
}
if (itag)
{
for(m=0;m<nvert;m++)
{
//iflag[inode[m]]=1;
nodeRes[inode[m]]=BIGVALUE;
iextmp[inode[m]]=iextmp1[inode[m]]=1;
}
}
}
}
/*
sprintf(intstring,"%d",100000+myid);
sprintf(fname,"nodeRes%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
for(i=0;i<nnodes;i++)
{
if (nodeRes[i]==BIGVALUE) {
fprintf(fp,"%e %e %e\n",x[3*i],x[3*i+1],x[3*i+2]);
}
}
fclose(fp);
*/
//
// now tag all the cells which have
// mandatory receptors as nodes as not acceptable
// donors
//
for(iex=0;iex<mexclude;iex++)
{
k=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
for(m=0;m<nvert;m++)
{
inode[m]=vconn[n][nvert*i+m]-BASE;
if (iextmp[inode[m]]==1) //(iflag[inode[m]])
{
cellRes[k]=BIGVALUE;
break;
}
}
if (cellRes[k]==BIGVALUE)
{
for(m=0;m<nvert;m++) {
inode[m]=vconn[n][nvert*i+m]-BASE;
if (iextmp[inode[m]]!=1) iextmp1[inode[m]]=1;
}
}
k++;
}
}
for(i=0;i<nnodes;i++) iextmp[i]=iextmp1[i];
}
TIOGA_FREE(iflag);
TIOGA_FREE(iextmp);
TIOGA_FREE(iextmp1);
}
void MeshBlock::writeGridFile(int bid)
{
char fname[80];
char intstring[7];
char hash,c;
int i,n,j;
int bodytag;
FILE *fp;
int ba;
int nvert;
sprintf(intstring,"%d",100000+bid);
sprintf(fname,"part%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
fprintf(fp,"TITLE =\"Tioga output\"\n");
fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\",\"IBLANK\"\n");
fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",nnodes,
ncells);
for(i=0;i<nnodes;i++)
{
fprintf(fp,"%.14e %.14e %.14e %d\n",x[3*i],x[3*i+1],x[3*i+2],iblank[i]);
}
ba=1-BASE;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
if (nvert==4)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba);
}
else if (nvert==5)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba);
}
else if (nvert==6)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+5]+ba);
}
else if (nvert==8)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+6]+ba,
vconn[n][nvert*i+7]+ba);
}
}
}
fclose(fp);
return;
}
void MeshBlock::writeCellFile(int bid)
{
char fname[80];
char qstr[3];
char intstring[7];
char hash,c;
int i,n,j;
int bodytag;
FILE *fp;
int ba;
int nvert;
sprintf(intstring,"%d",100000+bid);
sprintf(fname,"cell%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
fprintf(fp, "TITLE =\"Tioga output\"\n");
fprintf(fp, "VARIABLES = \"X\"\n");
fprintf(fp, "\"Y\"\n");
fprintf(fp, "\"Z\"\n");
fprintf(fp, "\"IBLANK\"\n");
fprintf(fp, "\"IBLANK_CELL\"\n");
fprintf(fp, "ZONE T=\"VOL_MIXED\"\n");
fprintf(fp, " Nodes=%d, Elements=%d, ZONETYPE=FEBrick\n", nnodes, ncells);
fprintf(fp, " DATAPACKING=BLOCK\n");
fprintf(fp, " VARLOCATION=([5]=CELLCENTERED)\n");
fprintf(fp, " DT=(SINGLE SINGLE SINGLE SINGLE SINGLE)\n");
for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i]);
for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i+1]);
for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i+2]);
for(i=0;i<nnodes;i++) fprintf(fp,"%d.0\n",iblank[i]);
for(i=0;i<ncells;i++) fprintf(fp,"%d.0\n",iblank_cell[i]);
ba=1-BASE;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
if (nvert==4)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba);
}
else if (nvert==5)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba);
}
else if (nvert==6)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+5]+ba);
}
else if (nvert==8)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+6]+ba,
vconn[n][nvert*i+7]+ba);
}
}
}
fclose(fp);
return;
}
void MeshBlock::writeFlowFile(int bid,double *q,int nvar,int type)
{
char fname[80];
char qstr[3];
char intstring[7];
char hash,c;
int i,n,j;
int bodytag;
FILE *fp;
int ba;
int nvert;
int *ibl;
//
// if fringes were reduced use
// iblank_reduced
//
if (iblank_reduced)
{
ibl=iblank_reduced;
}
else
{
ibl=iblank;
}
//
sprintf(intstring,"%d",100000+bid);
sprintf(fname,"flow%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
fprintf(fp,"TITLE =\"Tioga output\"\n");
fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\",\"IBLANK\",\"BTAG\" ");
for(i=0;i<nvar;i++)
{
sprintf(qstr,"Q%d",i);
fprintf(fp,"\"%s\",",qstr);
}
fprintf(fp,"\n");
fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",nnodes,
ncells);
if (type==0)
{
for(i=0;i<nnodes;i++)
{
fprintf(fp,"%lf %lf %lf %d %d ",x[3*i],x[3*i+1],x[3*i+2],ibl[i],meshtag);
for(j=0;j<nvar;j++)
fprintf(fp,"%lf ",q[i*nvar+j]);
//for(j=0;j<nvar;j++)
// fprintf(fp,"%lf ", x[3*i]+x[3*i+1]+x[3*i+2]);
fprintf(fp,"\n");
}
}
else
{
for(i=0;i<nnodes;i++)
{
fprintf(fp,"%lf %lf %lf %d %d ",x[3*i],x[3*i+1],x[3*i+2],ibl[i],meshtag);
for(j=0;j<nvar;j++)
fprintf(fp,"%lf ",q[j*nnodes+i]);
fprintf(fp,"\n");
}
}
ba=1-BASE;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
if (nvert==4)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba);
}
else if (nvert==5)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba);
}
else if (nvert==6)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+5]+ba);
}
else if (nvert==8)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+6]+ba,
vconn[n][nvert*i+7]+ba);
}
}
}
fprintf(fp,"%d\n",nwbc);
for(i=0;i<nwbc;i++)
fprintf(fp,"%d\n",wbcnode[i]);
fprintf(fp,"%d\n",nobc);
for(i=0;i<nobc;i++)
fprintf(fp,"%d\n",obcnode[i]);
fclose(fp);
return;
}
void MeshBlock::getWallBounds(int *mtag,int *existWall, double wbox[6])
{
int i,j,i3;
int inode;
*mtag=meshtag+(1-BASE);
if (nwbc <=0) {
*existWall=0;
for(i=0;i<6;i++) wbox[i]=0;
return;
}
*existWall=1;
wbox[0]=wbox[1]=wbox[2]=BIGVALUE;
wbox[3]=wbox[4]=wbox[5]=-BIGVALUE;
for(i=0;i<nwbc;i++)
{
inode=wbcnode[i]-BASE;
i3=3*inode;
for(j=0;j<3;j++)
{
wbox[j]=TIOGA_MIN(wbox[j],x[i3+j]);
wbox[j+3]=TIOGA_MAX(wbox[j+3],x[i3+j]);
}
}
}
void MeshBlock::markWallBoundary(int *sam,int nx[3],double extents[6])
{
int i,j,k,m,n;
int nvert;
int ii,jj,kk,mm;
int i3,iv;
int *iflag;
int *inode;
char intstring[7];
char fname[80];
double ds[3];
double xv;
int imin[3];
int imax[3];
FILE *fp;
//
iflag=(int *)malloc(sizeof(int)*ncells);
inode=(int *) malloc(sizeof(int)*nnodes);
///
//sprintf(intstring,"%d",100000+myid);
//sprintf(fname,"wbc%s.dat",&(intstring[1]));
//fp=fopen(fname,"w");
for(i=0;i<ncells;i++) iflag[i]=0;
for(i=0;i<nnodes;i++) inode[i]=0;
//
for(i=0;i<nwbc;i++)
{
ii=wbcnode[i]-BASE;
//fprintf(fp,"%e %e %e\n",x[3*ii],x[3*ii+1],x[3*ii+2]);
inode[ii]=1;
}
//fclose(fp);
//
// mark wall boundary cells
//
m=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
for(j=0;j<nvert;j++)
{
ii=vconn[n][nvert*i+j]-BASE;
if (inode[ii]==1)
{
iflag[m]=1;
break;
}
}
m++;
}
}
//
// find delta's in each directions
//
for(k=0;k<3;k++) ds[k]=(extents[k+3]-extents[k])/nx[k];
//
// mark sam cells with wall boundary cells now
//
m=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
if (iflag[m]==1)
{
//
// find the index bounds of each wall boundary cell
// bounding box
//
imin[0]=imin[1]=imin[2]=BIGINT;
imax[0]=imax[1]=imax[2]=-BIGINT;
for(j=0;j<nvert;j++)
{
i3=3*(vconn[n][nvert*i+j]-BASE);
for(k=0;k<3;k++)
{
xv=x[i3+k];
iv=floor((xv-extents[k])/ds[k]);
imin[k]=TIOGA_MIN(imin[k],iv);
imax[k]=TIOGA_MAX(imax[k],iv);
}
}
for(j=0;j<3;j++)
{
imin[j]=TIOGA_MAX(imin[j],0);
imax[j]=TIOGA_MIN(imax[j],nx[j]-1);
}
//
// mark sam to 1
//
for(kk=imin[2];kk<imax[2]+1;kk++)
for(jj=imin[1];jj<imax[1]+1;jj++)
for (ii=imin[0];ii<imax[0]+1;ii++)
{
mm=kk*nx[1]*nx[0]+jj*nx[0]+ii;
sam[mm]=2;
}
}
m++;
}
}
TIOGA_FREE(iflag);
TIOGA_FREE(inode);
}
void MeshBlock::getReducedOBB(OBB *obc,double *realData)
{
int i,j,k,m,n,i3;
int nvert;
bool iflag;
double bbox[6],xd[3];
/*
for(j=0;j<3;j++)
{
realData[j]=obb->xc[j];
realData[j+3]=obb->dxc[j];
}
return;
*/
for(j=0;j<3;j++)
{
realData[j]=BIGVALUE;
realData[j+3]=-BIGVALUE;
}
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
bbox[0]=bbox[1]=bbox[2]=BIGVALUE;
bbox[3]=bbox[4]=bbox[5]=-BIGVALUE;
for(m=0;m<nvert;m++)
{
i3=3*(vconn[n][nvert*i+m]-BASE);
for(j=0;j<3;j++) xd[j]=0;
for(j=0;j<3;j++)
for(k=0;k<3;k++)
xd[j]+=(x[i3+k]-obc->xc[k])*obc->vec[j][k];
for(j=0;j<3;j++) bbox[j]=TIOGA_MIN(bbox[j],xd[j]);
for(j=0;j<3;j++) bbox[j+3]=TIOGA_MAX(bbox[j+3],xd[j]);
}
iflag=0;
for(j=0;j<3;j++) iflag=(iflag || (bbox[j] > obc->dxc[j]));
if (iflag) continue;
iflag=0;
for(j=0;j<3;j++) iflag=(iflag || (bbox[j+3] < -obc->dxc[j]));
if (iflag) continue;
for (m=0;m<nvert;m++)
{
i3=3*(vconn[n][nvert*i+m]-BASE);
for(j=0;j<3;j++) xd[j]=0;
for(j=0;j<3;j++)
for(k=0;k<3;k++)
xd[j]+=(x[i3+k]-obb->xc[k])*obb->vec[j][k];
for(j=0;j<3;j++) realData[j]=TIOGA_MIN(realData[j],xd[j]);
for(j=0;j<3;j++) realData[j+3]=TIOGA_MAX(realData[j+3],xd[j]);
}
}
}
for(j=0;j<6;j++) bbox[j]=realData[j];
for(j=0;j<3;j++)
{
realData[j]=obb->xc[j];
for(k=0;k<3;k++)
realData[j]+=((bbox[k]+bbox[k+3])*0.5)*obb->vec[k][j];
realData[j+3]=(bbox[j+3]-bbox[j])*0.51;
}
return;
}
void MeshBlock::getReducedOBB2(OBB *obc,double *realData)
{
int i,j,k,l,m,n,i3,jmin,kmin,lmin,jmax,kmax,lmax,indx;
double bbox[6],xd[3];
double xmin[3],xmax[3],xv[8][3];
double delta;
int imin[3],imax[3];
getobbcoords(obc->xc,obc->dxc,obc->vec,xv);
for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;};
for(n=0;n<8;n++)
{
transform2OBB(xv[n],obb->xc,obb->vec,xd);
for(j=0;j<3;j++)
{
xmin[j]=TIOGA_MIN(xmin[j],xd[j]+obb->dxc[j]);
xmax[j]=TIOGA_MAX(xmax[j],xd[j]+obb->dxc[j]);
}
}
for(j=0;j<3;j++)
{
delta=0.01*(xmax[j]-xmin[j]);
xmin[j]-=delta;
xmax[j]+=delta;
imin[j]=TIOGA_MAX(xmin[j]/mapdx[j],0);
imax[j]=TIOGA_MIN(xmax[j]/mapdx[j],mapdims[j]-1);
}
lmin=mapdims[2]-1;
kmin=mapdims[1]-1;
jmin=mapdims[0]-1;
lmax=kmax=jmax=0;
for(l=imin[2];l<=imax[2];l++)
for(k=imin[1];k<=imax[1];k++)
for(j=imin[0];j<=imax[0];j++)
{
indx=l*mapdims[1]*mapdims[0]+k*mapdims[0]+j;
if (mapmask[indx]) {
lmin=TIOGA_MIN(lmin,l);
kmin=TIOGA_MIN(kmin,k);
jmin=TIOGA_MIN(jmin,j);
lmax=TIOGA_MAX(lmax,l);
kmax=TIOGA_MAX(kmax,k);
jmax=TIOGA_MAX(jmax,j);
}
}
bbox[0]=-obb->dxc[0]+jmin*mapdx[0];
bbox[1]=-obb->dxc[1]+kmin*mapdx[1];
bbox[2]=-obb->dxc[2]+lmin*mapdx[2];
bbox[3]=-obb->dxc[0]+(jmax+1)*mapdx[0];
bbox[4]=-obb->dxc[1]+(kmax+1)*mapdx[1];
bbox[5]=-obb->dxc[2]+(lmax+1)*mapdx[2];
for(j=0;j<3;j++)
{
realData[j]=obb->xc[j];
for(k=0;k<3;k++)
realData[j]+=((bbox[k]+bbox[k+3])*0.5)*obb->vec[k][j];
realData[j+3]=(bbox[j+3]-bbox[j])*0.5;
}
return;
}
void MeshBlock::getQueryPoints(OBB *obc,
int *nints,int **intData,
int *nreals, double **realData)
{
int i,j,k;
int i3;
double xd[3];
int *inode;
int iptr;
int m;
inode=(int *)malloc(sizeof(int)*nnodes);
*nints=*nreals=0;
for(i=0;i<nnodes;i++)
{
i3=3*i;
for(j=0;j<3;j++) xd[j]=0;
for(j=0;j<3;j++)
for(k=0;k<3;k++)
xd[j]+=(x[i3+k]-obc->xc[k])*obc->vec[j][k];
if (fabs(xd[0]) <= obc->dxc[0] &&
fabs(xd[1]) <= obc->dxc[1] &&
fabs(xd[2]) <= obc->dxc[2])
{
inode[*nints]=i;
(*nints)++;
(*nreals)+=4;
}
}
if (myid==0 && meshtag==1) {TRACEI(*nints);}
(*intData)=(int *)malloc(sizeof(int)*(*nints));
(*realData)=(double *)malloc(sizeof(double)*(*nreals));
//
m=0;
for(i=0;i<*nints;i++)
{
i3=3*inode[i];
(*intData)[i]=inode[i];
(*realData)[m++]=x[i3];
(*realData)[m++]=x[i3+1];
(*realData)[m++]=x[i3+2];
(*realData)[m++]=nodeRes[inode[i]];
}
//
TIOGA_FREE(inode);
}
void MeshBlock::getQueryPoints2(OBB *obc,
int *nints,int **intData,
int *nreals, double **realData)
{
int i,j,k,l,il,ik,ij,n,m,i3,iflag;
int indx,iptr;
int *inode;
double delta;
double xv[8][3],mdx[3],xd[3],xc[3];
double xmax[3],xmin[3];
int imin[3],imax[3];
//
inode=(int *)malloc(sizeof(int)*nnodes);
*nints=*nreals=0;
getobbcoords(obc->xc,obc->dxc,obc->vec,xv);
for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;};
//writebbox(obc,1);
//writebbox(obb,2);
//writebboxdiv(obb,1);
//
for(n=0;n<8;n++)
{
transform2OBB(xv[n],obb->xc,obb->vec,xd);
for(j=0;j<3;j++)
{
xmin[j]=TIOGA_MIN(xmin[j],xd[j]+obb->dxc[j]);
xmax[j]=TIOGA_MAX(xmax[j],xd[j]+obb->dxc[j]);
}
}
for(j=0;j<3;j++)
{
delta=0.01*(xmax[j]-xmin[j]);
xmin[j]-=delta;
xmax[j]+=delta;
imin[j]=TIOGA_MAX(xmin[j]/mapdx[j],0);
imax[j]=TIOGA_MIN(xmax[j]/mapdx[j],mapdims[j]-1);
mdx[j]=0.5*mapdx[j];
}
//
// find min/max extends of a single sub-block
// in OBC axes
//
getobbcoords(obc->xc,mdx,obb->vec,xv);
for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;}
for(m=0;m<8;m++)
{
transform2OBB(xv[m],obc->xc,obc->vec,xd);
for(j=0;j<3;j++)
{
xmin[j]=TIOGA_MIN(xmin[j],xd[j]);
xmax[j]=TIOGA_MAX(xmax[j],xd[j]);
}
}
//printf("xmin :%f %f %f\n",xmin[0],xmin[1],xmin[2]);
//printf("xmax :%f %f %f\n",xmax[0],xmax[1],xmax[2]);
//
// now find the actual number of points
// that are within OBC using only the
// sub-blocks with potential bbox overlap
//
//FILE *fp,*fp2,*fp3,*fp4;
//fp=fopen("v.dat","w");
//fp2=fopen("v2.dat","w");
//fp3=fopen("v3.dat","w");
//fp4=fopen("v4.dat","w");
for(l=imin[2];l<=imax[2];l++)
for(k=imin[1];k<=imax[1];k++)
for(j=imin[0];j<=imax[0];j++)
{
//
// centroid of each sub-block
// in OBC axes
//
xd[0]=-obb->dxc[0]+j*mapdx[0]+mapdx[0]*0.5;
xd[1]=-obb->dxc[1]+k*mapdx[1]+mapdx[1]*0.5;
xd[2]=-obb->dxc[2]+l*mapdx[2]+mapdx[2]*0.5;
for(n=0;n<3;n++)
{
xc[n]=obb->xc[n];
for(ij=0;ij<3;ij++)
xc[n]+=(xd[ij]*obb->vec[ij][n]);
}
//if (j==0 && k==0 & l==0) {
//printf("%f %f %f\n",obc->vec[0][0],obc->vec[1][0],obc->vec[2][0]);
//printf("%f %f %f\n",obc->vec[0][1],obc->vec[1][1],obc->vec[2][1]);
//printf("%f %f %f\n",obc->vec[0][2],obc->vec[1][2],obc->vec[2][2]);
//printf("%f %f %f\n",obc->xc[0],obc->xc[1],obc->xc[2]);
//}
//fprintf(fp,"%f %f %f\n",xc[0],xc[1],xc[2]);
transform2OBB(xc,obc->xc,obc->vec,xd);
//fprintf(fp2,"%f %f %f\n",xd[0],xd[1],xd[2]);
//if (fabs(xd[0]) <= obc->dxc[0] &&
// fabs(xd[1]) <= obc->dxc[1] &&
// fabs(xd[2]) <= obc->dxc[2])
// {
// fprintf(fp3,"%f %f %f\n",xc[0],xc[1],xc[2]);
// }
//
// check if this sub-block overlaps OBC
//
iflag=0;
for(ij=0;ij<3 && !iflag;ij++) iflag=(iflag || (xmin[ij]+xd[ij] > obc->dxc[ij]));
if (iflag) continue;
iflag=0;
for(ij=0;ij<3 && !iflag;ij++) iflag=(iflag || (xmax[ij]+xd[ij] < -obc->dxc[ij]));
if (iflag) continue;
//fprintf(fp4,"%f %f %f\n",xc[0],xc[1],xc[2]);
//
// if there overlap
// go through points within the sub-block
// to figure out what needs to be send
//
indx=l*mapdims[1]*mapdims[0]+k*mapdims[0]+j;
for(m=icft[indx];m<icft[indx+1];m++)
{
i3=3*invmap[m];
for(ik=0;ik<3;ik++) xc[ik]=x[i3+ik];
transform2OBB(xc,obc->xc,obc->vec,xd);
if (fabs(xd[0]) <= obc->dxc[0] &&
fabs(xd[1]) <= obc->dxc[1] &&
fabs(xd[2]) <= obc->dxc[2])
{
inode[*nints]=invmap[m];
(*nints)++;
(*nreals)+=4;
}
}
}
// TRACEI(*nints);
// fclose(fp);
// fclose(fp2);
// fclose(fp3);
// fclose(fp4);
// int ierr;
// MPI_Abort(MPI_COMM_WORLD,ierr);
//
#ifdef TIOGA_HAS_NODEGID
int nintsPerNode = 3;
#else
int nintsPerNode = 1;
#endif
(*intData)=(int *)malloc(sizeof(int)*(*nints) * nintsPerNode);
(*realData)=(double *)malloc(sizeof(double)*(*nreals));
//
m=0;
int iidx = 0;
for(i=0;i<*nints;i++) {
i3=3*inode[i];
(*intData)[iidx++]=inode[i];
#ifdef TIOGA_HAS_NODEGID
std::memcpy(&(*intData)[iidx],&nodeGID[inode[i]], sizeof(uint64_t));
iidx += 2;
#endif
(*realData)[m++]=x[i3];
(*realData)[m++]=x[i3+1];
(*realData)[m++]=x[i3+2];
(*realData)[m++]=nodeRes[inode[i]];
}
// Adjust nints to the proper array size
*nints *= nintsPerNode;
//
TIOGA_FREE(inode);
}
void MeshBlock::writeOBB(int bid)
{
FILE *fp;
char intstring[7];
char fname[80];
int l,k,j,m,il,ik,ij;
REAL xx[3];
sprintf(intstring,"%d",100000+bid);
sprintf(fname,"box%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
fprintf(fp,"TITLE =\"Box file\"\n");
fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\"\n");
fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",8,
1);
for(l=0;l<2;l++)
{
il=2*(l%2)-1;
for(k=0;k<2;k++)
{
ik=2*(k%2)-1;
for(j=0;j<2;j++)
{
ij=2*(j%2)-1;
xx[0]=xx[1]=xx[2]=0;
for(m=0;m<3;m++)
xx[m]=obb->xc[m]+ij*obb->vec[0][m]*obb->dxc[0]
+ik*obb->vec[1][m]*obb->dxc[1]
+il*obb->vec[2][m]*obb->dxc[2];
fprintf(fp,"%f %f %f\n",xx[0],xx[1],xx[2]);
}
}
}
fprintf(fp,"1 2 4 3 5 6 8 7\n");
fprintf(fp,"%e %e %e\n",obb->xc[0],obb->xc[1],obb->xc[2]);
for(k=0;k<3;k++)
fprintf(fp,"%e %e %e\n",obb->vec[0][k],obb->vec[1][k],obb->vec[2][k]);
fprintf(fp,"%e %e %e\n",obb->dxc[0],obb->dxc[1],obb->dxc[2]);
fclose(fp);
}
//
// destructor that deallocates all the
// the dynamic objects inside
//
MeshBlock::~MeshBlock()
{
int i;
//
// TIOGA_FREE all data that is owned by this MeshBlock
// i.e not the pointers of the external code.
//
if (cellRes) TIOGA_FREE(cellRes);
if (nodeRes) TIOGA_FREE(nodeRes);
if (elementBbox) TIOGA_FREE(elementBbox);
if (elementList) TIOGA_FREE(elementList);
if (adt) delete[] adt;
if (donorList) {
for(i=0;i<nnodes;i++) deallocateLinkList(donorList[i]);
TIOGA_FREE(donorList);
}
if (interpList) {
for(i=0;i<interpListSize;i++)
{
if (interpList[i].inode) TIOGA_FREE(interpList[i].inode);
if (interpList[i].weights) TIOGA_FREE(interpList[i].weights);
}
TIOGA_FREE(interpList);
}
if (interpList2) {
for(i=0;i<interp2ListSize;i++)
{
if (interpList2[i].inode) TIOGA_FREE(interpList2[i].inode);
if (interpList2[i].weights) TIOGA_FREE(interpList2[i].weights);
}
TIOGA_FREE(interpList2);
}
if (interpListCart) {
for(i=0;i<interpListCartSize;i++)
{
if (interpListCart[i].inode) TIOGA_FREE(interpListCart[i].inode);
if (interpListCart[i].weights) TIOGA_FREE(interpListCart[i].weights);
}
TIOGA_FREE(interpListCart);
}
// For nalu-wind API the iblank_cell array is managed on the nalu side
// if (!ihigh) {
// if (iblank_cell) TIOGA_FREE(iblank_cell);
// }
if (obb) TIOGA_FREE(obb);
if (obh) TIOGA_FREE(obh);
if (isearch) TIOGA_FREE(isearch);
if (xsearch) TIOGA_FREE(xsearch);
if (res_search) TIOGA_FREE(res_search);
if (xtag) TIOGA_FREE(xtag);
if (rst) TIOGA_FREE(rst);
if (interp2donor) TIOGA_FREE(interp2donor);
if (cancelList) deallocateLinkList2(cancelList);
if (ctag) TIOGA_FREE(ctag);
if (pointsPerCell) TIOGA_FREE(pointsPerCell);
if (rxyz) TIOGA_FREE(rxyz);
if (picked) TIOGA_FREE(picked);
if (rxyzCart) TIOGA_FREE(rxyzCart);
if (donorIdCart) TIOGA_FREE(donorIdCart);
if (pickedCart) TIOGA_FREE(pickedCart);
if (ctag_cart) TIOGA_FREE(ctag_cart);
if (tagsearch) TIOGA_FREE(tagsearch);
if (donorId) TIOGA_FREE(donorId);
if (receptorIdCart) TIOGA_FREE(receptorIdCart);
if (icft) TIOGA_FREE(icft);
if (mapmask) TIOGA_FREE(mapmask);
if (uindx) TIOGA_FREE(uindx);
if (invmap) TIOGA_FREE(invmap);
// need to add code here for other objects as and
// when they become part of MeshBlock object
};
//
// set user specified node and cell resolutions
//
void MeshBlock::setResolutions(double *nres,double *cres)
{
userSpecifiedNodeRes=nres;
userSpecifiedCellRes=cres;
}
//
// detect if a given meshblock is a uniform hex
// and create a data structure that will enable faster
// searching
//
void MeshBlock::check_for_uniform_hex(void)
{
double xv[8][3];
int hex_present=0;
if (ntypes > 1) return;
for(int n=0;n<ntypes;n++)
{
int nvert=nv[n];
if (nvert==8) {
hex_present=1;
for(int i=0;i<nc[n];i++)
{
int vold=-1;
for(int m=0;m<nvert;m++)
{
if (vconn[n][nvert*i+m]==vold) return; // degenerated hex are not uniform
vold=vconn[n][nvert*i+m];
int i3=3*(vconn[n][nvert*i+m]-BASE);
for(int k=0;k<3;k++)
xv[m][k]=x[i3+k];
}
//
// check angles to see if sides are
// rectangles
//
// z=0 side
//
if (fabs(tdot_product(xv[1],xv[3],xv[0])) > TOL) return;
if (fabs(tdot_product(xv[1],xv[3],xv[2])) > TOL) return;
//
// x=0 side
//
if (fabs(tdot_product(xv[3],xv[4],xv[0])) > TOL) return;
if (fabs(tdot_product(xv[3],xv[4],xv[7])) > TOL) return;
//
// y=0 side
//
if (fabs(tdot_product(xv[4],xv[1],xv[0])) > TOL) return;
if (fabs(tdot_product(xv[4],xv[1],xv[5])) > TOL) return;
//
// need to check just one more angle on
// on the corner against 0 (6)
//
if (fabs(tdot_product(xv[5],xv[7],xv[6])) > TOL) return;
//
// so this is a hex
// check if it has the same size as the previous hex
// if not return
//
if (i==0){
dx[0]=tdot_product(xv[1],xv[1],xv[0]);
dx[1]=tdot_product(xv[3],xv[3],xv[0]);
dx[2]=tdot_product(xv[4],xv[4],xv[0]);
}
else {
if (fabs(dx[0]-tdot_product(xv[1],xv[1],xv[0])) > TOL) return;
if (fabs(dx[1]-tdot_product(xv[3],xv[3],xv[0])) > TOL) return;
if (fabs(dx[2]-tdot_product(xv[4],xv[4],xv[0])) > TOL) return;
}
}
}
}
if (hex_present) {
for(int j=0;j<3;j++) dx[j]=sqrt(dx[j]);
uniform_hex=1;
if (obh) TIOGA_FREE(obh);
obh=(OBB *) malloc(sizeof(OBB));
for(int j=0;j<3;j++)
for(int k=0;k<3;k++)
obh->vec[j][k]=0;
for(int k=0;k<3;k++)
obh->vec[0][k]=(xv[1][k]-xv[0][k])/dx[0];
for(int k=0;k<3;k++)
obh->vec[1][k]=(xv[3][k]-xv[0][k])/dx[1];
for(int k=0;k<3;k++)
obh->vec[2][k]=(xv[4][k]-xv[0][k])/dx[2];
//obh->vec[0][0]=obh->vec[1][1]=obh->vec[2][2]=1;
//
double xd[3];
double xmax[3];
double xmin[3];
xmax[0]=xmax[1]=xmax[2]=-BIGVALUE;
xmin[0]=xmin[1]=xmin[2]=BIGVALUE;
//
for(int i=0;i<nnodes;i++)
{
int i3=3*i;
for(int j=0;j<3;j++) xd[j]=0;
//
for(int j=0;j<3;j++)
for(int k=0;k<3;k++)
xd[j]+=x[i3+k]*obh->vec[j][k];
//
for(int j=0;j<3;j++)
{
xmax[j]=TIOGA_MAX(xmax[j],xd[j]);
xmin[j]=TIOGA_MIN(xmin[j],xd[j]);
}
}
//
// find the extents of the box
// and coordinates of the center w.r.t. xc
// increase extents by 1% for tolerance
//
for(int j=0;j<3;j++)
{
xmax[j]+=TOL;
xmin[j]-=TOL;
obh->dxc[j]=(xmax[j]-xmin[j])*0.5;
xd[j]=(xmax[j]+xmin[j])*0.5;
}
//
// find the center of the box in
// actual cartesian coordinates
//
for(int j=0;j<3;j++)
{
obh->xc[j]=0.0;
for(int k=0;k<3;k++)
obh->xc[j]+=(xd[k]*obh->vec[k][j]);
}
}
return;
}
void MeshBlock::create_hex_cell_map(void)
{
for(int j=0;j<3;j++)
{
xlow[j]=obh->xc[j];
for (int k=0;k<3;k++)
xlow[j]-=(obh->dxc[k]*obh->vec[k][j]);
idims[j]=round(2*obh->dxc[j]/dx[j]);
dx[j]=(2*obh->dxc[j])/idims[j];
}
//
if (uindx) TIOGA_FREE(uindx);
uindx=(int *)malloc(sizeof(int)*idims[0]*idims[1]*idims[2]);
for(int i=0;i<idims[0]*idims[1]*idims[2];uindx[i++]=-1);
//
for(int i=0;i<nc[0];i++)
{
double xc[3];
double xd[3];
int idx[3];
for(int j=0;j<3;j++)
{
int lnode=vconn[0][8*i]-BASE;
int tnode=vconn[0][8*i+6]-BASE;
xc[j]=0.5*(x[3*lnode+j]+x[3*tnode+j]);
}
for(int j=0;j<3;j++)
{
xd[j]=0;
for(int k=0;k<3;k++)
xd[j]+=(xc[k]-xlow[k])*obh->vec[j][k];
idx[j]=xd[j]/dx[j];
}
uindx[idx[2]*idims[1]*idims[0]+idx[1]*idims[0]+idx[0]]=i;
}
}
| jsitaraman/tioga | src/MeshBlock.C | C++ | lgpl-3.0 | 35,409 |
#include <algorithm>
#include <descriptor.hpp>
namespace gemini
{
descriptor::
descriptor(unsigned short bus,
unsigned short port,
unsigned short product_id,
unsigned short vendor_id,
unsigned short interface_class) :
info_(std::array<unsigned short,DESCRIPTOR_SIZE>
{bus,port,vendor_id,product_id,interface_class})
{}
descriptor::
descriptor(std::array<unsigned short,DESCRIPTOR_SIZE> const& info) :
info_(info)
{}
bool descriptor::relevant(descriptor const& descriptor) const
{
bool relevant = true;
for(unsigned short index = BUS ; index != UNDEFINED ; ++index)
{
if(info_[index] != MASKED && info_[index] != descriptor[index])
{
relevant = false;
}
}
return relevant;
}
void descriptor::
read_device_address(libusb_device * device)
{
info_[BUS] = libusb_get_bus_number(device);
info_[PORT] = libusb_get_port_number(device);
}
void descriptor::
read_device_descriptor(libusb_device_descriptor const& dev_desc)
{
info_[VENDOR_ID] = dev_desc.idVendor;
info_[PRODUCT_ID] = dev_desc.idProduct;
}
void descriptor::
read_interface_descriptor(libusb_interface_descriptor const& intf_desc)
{
info_[INTERFACE_CLASS] = intf_desc.bInterfaceClass;
}
std::string const descriptor::info(bool readable) const
{
std::string descriptor_info;
for(unsigned short index = BUS ; index != UNDEFINED ; ++index)
{
if(index > 0) descriptor_info += " ";
if(readable)
{
switch(index)
{
case BUS : descriptor_info += "[BUS:"; break;
case PORT : descriptor_info += "[PORT:"; break;
case VENDOR_ID : descriptor_info += "[VENDOR ID:"; break;
case PRODUCT_ID : descriptor_info += "[PRODUCT ID:"; break;
case INTERFACE_CLASS : descriptor_info += "[INTERFACE CLASS:"; break;
}
}
descriptor_info += std::to_string(info_[index])
+ "]";
}
return descriptor_info;
}
std::string const descriptor::device_info() const
{
std::string device_info;
for(unsigned short index = BUS ; index != INTERFACE_CLASS ; ++index)
{
device_info += " ";
device_info += std::to_string(info_[index]);
}
return device_info;
}
unsigned short descriptor::operator [] (unsigned short index) const
{
return info_[index];
}
unsigned short & descriptor::operator [] (unsigned short index)
{
return info_[index];
}
bool operator == (descriptor const& i1,descriptor const& i2)
{
bool equal = true;
for(unsigned short index = BUS ; index != UNDEFINED ; ++index)
{
if(i1[index] != i2[index]) equal = false;
}
return equal;
}
// stream operator
std::ostream & operator << (std::ostream & out,descriptor const& intf_info)
{
// write descriptor informations readable in stream
out << intf_info.info(true);
return out;
}
} // end namespace gemini
| tgrochow/gemini | daemon/descriptor.cpp | C++ | lgpl-3.0 | 2,965 |
#!/usr/bin/env python
# -*- coding: utf-8 -*
import clutter
from clutter import cogl
import math
class Clock(clutter.Actor):
__gtype_name__ = 'Clock'
"""
A clock widget
"""
def __init__(self, date=None, texture=None):
clutter.Actor.__init__(self)
self._date = date
self._texture = texture
self._color = clutter.color_from_string('Black')
def set_color(self, color):
self._color = clutter.color_from_string(color)
self.queue_redraw()
def set_texture(self, texture):
self._texture = texture
self.queue_redraw()
def set_date(self, date=None):
self._date = date
if date is not None:
self.queue_redraw()
def do_paint(self):
#clutter.Texture.do_paint(self)
(x1, y1, x2, y2) = self.get_allocation_box()
width = x2 - x1
height = y2 - y1
hw = width / 2
hh = height / 2
center_x = hw
center_y = hh
# texture
if self._texture is not None:
cogl.path_rectangle(0, 0, width, height)
cogl.path_close()
cogl.set_source_texture(self._texture)
cogl.path_fill()
# clock hands
if self._date is not None:
hour = self._date.hour
minute = self._date.minute
# hour
angle = (60 * hour + minute) / 2 + 270
left = angle - 14
right = angle + 14
angle = angle * (math.pi / 180)
left = left * (math.pi / 180)
right = right * (math.pi / 180)
cogl.path_move_to(center_x, center_y)
cogl.path_line_to(center_x + (hw/4) * math.cos(left), center_y + (hh/4) * math.sin(left))
cogl.path_line_to(center_x + (2*hw/3) * math.cos(angle), center_y + (2*hh/3) * math.sin(angle))
cogl.path_line_to(center_x + (hw/4) * math.cos(right), center_y + (hh/4) * math.sin(right))
cogl.path_line_to(center_x, center_y)
cogl.path_close()
cogl.set_source_color(self._color)
cogl.path_fill()
# minute
angle = 6 * minute + 270
left = angle - 10
right = angle + 10
angle = angle * (math.pi / 180)
left = left * (math.pi / 180)
right = right * (math.pi / 180)
cogl.path_move_to(center_x, center_y)
cogl.path_line_to(center_x + (hw/3) * math.cos(left), center_y + (hh/3) * math.sin(left))
cogl.path_line_to(center_x + hw * math.cos(angle), center_y + hh * math.sin(angle))
cogl.path_line_to(center_x + (hw/3) * math.cos(right), center_y + (hh/3) * math.sin(right))
cogl.path_line_to(center_x, center_y)
cogl.path_close()
cogl.set_source_color(self._color)
cogl.path_fill()
#main to test
if __name__ == '__main__':
stage = clutter.Stage()
stage.connect('destroy',clutter.main_quit)
import gobject, datetime
t = cogl.texture_new_from_file('clock.png', clutter.cogl.TEXTURE_NO_SLICING, clutter.cogl.PIXEL_FORMAT_ANY)
c = Clock()
c.set_texture(t)
c.set_size(400, 400)
c.set_position(50, 50)
stage.add(c)
def update():
today = datetime.datetime.today()
#self.actor.set_text(today.strftime('%H:%M\n%d / %m'))
c.set_date(today)
return True
gobject.timeout_add_seconds(60, update)
stage.show()
clutter.main()
| UbiCastTeam/candies | candies2/clock.py | Python | lgpl-3.0 | 3,642 |
#ifndef QACCESSIBLEBRIDGE
#define QACCESSIBLEBRIDGE
class DummyQAccessibleBridge {
// Q_OBJECT;
public:
knh_RawPtr_t *self;
std::map<std::string, knh_Func_t *> *event_map;
std::map<std::string, knh_Func_t *> *slot_map;
DummyQAccessibleBridge();
virtual ~DummyQAccessibleBridge();
void setSelf(knh_RawPtr_t *ptr);
bool eventDispatcher(QEvent *event);
bool addEvent(knh_Func_t *callback_func, std::string str);
bool signalConnect(knh_Func_t *callback_func, std::string str);
knh_Object_t** reftrace(CTX ctx, knh_RawPtr_t *p FTRARG);
void connection(QObject *o);
};
class KQAccessibleBridge : public QAccessibleBridge {
// Q_OBJECT;
public:
int magic_num;
knh_RawPtr_t *self;
DummyQAccessibleBridge *dummy;
~KQAccessibleBridge();
void setSelf(knh_RawPtr_t *ptr);
};
#endif //QACCESSIBLEBRIDGE
| imasahiro/konohascript | package/konoha.qt4/include/KQAccessibleBridge.hpp | C++ | lgpl-3.0 | 810 |
package org.onebeartoe.filesystem;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* @author Roberto Marquez
*/
public class FileSystemSearcher
{
File dir;
List<FileType> targets;
FileType type;
boolean recursive;
public FileSystemSearcher(File dir, List<FileType> targets)
{
this(dir, targets, false);
}
public FileSystemSearcher(File dir, List<FileType> targets, boolean recursive)
{
if (dir == null)
{
throw new NullPointerException("search directory can't have a null value");
}
if (targets == null)
{
throw new NullPointerException("target list can't have a null value");
}
this.dir = dir;
this.targets = targets;
this.recursive = recursive;
}
public List<File> findTargetDirectories()
{
ArrayList<File> targetDirs = new ArrayList<File>();
Vector<File> directories = new Vector<File>();
directories.add(dir);
while (!directories.isEmpty())
{
File currentDir = directories.remove(0);
boolean currentContainsTargets = findTargetDirectoriesOneLevel(currentDir, directories);
if (currentContainsTargets)
{
targetDirs.add(currentDir);
}
}
return targetDirs;
}
private boolean findTargetDirectoriesOneLevel(File currentDir, Vector<File> directories)
{
boolean currentContainsTargets = false;
File[] dirContents = currentDir.listFiles();
if (dirContents != null)
{
currentContainsTargets = findTargetDirectoriesOneLevelExecute(dirContents, directories);
}
return currentContainsTargets;
}
private boolean findTargetDirectoriesOneLevelExecute(File[] dirContents, Vector<File> directories)
{
boolean currentContainsTargets = false;
boolean targetNotFoundYet = true;
for (File file : dirContents)
{
if (file.isDirectory() && recursive)
{
directories.add(file);
}
else
{
if (targetNotFoundYet)
{
// Only come here if a target has not been found.
FileType type = determinFileType(file);
if (targets.contains(type))
{
currentContainsTargets = true;
// If a target has been found in the current dir, we can skip the next file check
targetNotFoundYet = false;
}
}
}
}
return currentContainsTargets;
}
public List<File> findTargetFiles()
{
List<File> targetFiles = new ArrayList<File>();
Vector<File> directories = new Vector<File>();
directories.add(dir);
while (!directories.isEmpty())
{
findTargetFilesOneLevel(directories, targetFiles);
}
return targetFiles;
}
private void findTargetFilesOneLevel(Vector<File> directories, List<File> targetFiles)
{
File currentDir = directories.remove(0);
File[] dirContents = currentDir.listFiles();
if (dirContents != null)
{
for (File file : dirContents)
{
if (file.isDirectory() && recursive)
{
directories.add(file);
}
else
{
FileType type = determinFileType(file);
if (targets.contains(type))
{
targetFiles.add(file);
}
}
}
}
}
private FileType determinFileType(File file)
{
FileType type = FileType.UNKNOWN;
String name = file.getName();
if (FileHelper.isAudioFile(name))
{
type = FileType.AUDIO;
}
if (FileHelper.isZipFormatFile(name))
{
type = FileType.ZIP;
}
if (FileHelper.isMultimediaFile(name))
{
type = FileType.MULTIMEDIA;
}
if (FileHelper.isImageFile(name))
{
type = FileType.IMAGE;
}
if (FileHelper.isTextFile(name))
{
type = FileType.TEXT;
}
return type;
}
}
| onebeartoe/java-libraries | system/src/main/java/org/onebeartoe/filesystem/FileSystemSearcher.java | Java | lgpl-3.0 | 4,892 |
/**********
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. (See <http://www.gnu.org/copyleft/lesser.html>.)
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
**********/
// "liveMedia"
// Copyright (c) 1996-2021 Live Networks, Inc. All rights reserved.
// A filter that breaks up a H.265 Video Elementary Stream into NAL units.
// C++ header
#ifndef _H265_VIDEO_STREAM_FRAMER_HH
#define _H265_VIDEO_STREAM_FRAMER_HH
#ifndef _H264_OR_5_VIDEO_STREAM_FRAMER_HH
#include "H264or5VideoStreamFramer.hh"
#endif
class H265VideoStreamFramer: public H264or5VideoStreamFramer {
public:
static H265VideoStreamFramer* createNew(UsageEnvironment& env, FramedSource* inputSource,
Boolean includeStartCodeInOutput = False,
Boolean insertAccessUnitDelimiters = False);
protected:
H265VideoStreamFramer(UsageEnvironment& env, FramedSource* inputSource,
Boolean createParser,
Boolean includeStartCodeInOutput, Boolean insertAccessUnitDelimiters);
// called only by "createNew()"
virtual ~H265VideoStreamFramer();
// redefined virtual functions:
virtual Boolean isH265VideoStreamFramer() const;
};
#endif
| k0zmo/live555 | liveMedia/include/H265VideoStreamFramer.hh | C++ | lgpl-3.0 | 1,732 |
/*
* 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.process;
import java.io.FilePermission;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.PropertyPermission;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class PluginFileWriteRuleTest {
private final Path home = Paths.get("/path/to/home");
private final Path tmp = Paths.get("/path/to/home/tmp");
private final PluginFileWriteRule rule = new PluginFileWriteRule(home, tmp);
@Test
public void policy_restricts_modifying_home() {
assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "write"))).isFalse();
assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "execute"))).isFalse();
assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "delete"))).isFalse();
assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "read"))).isTrue();
assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/file").toAbsolutePath().toString(), "readlink"))).isTrue();
assertThat(rule.implies(new FilePermission(Paths.get("/path/to/home/extensions/file").toAbsolutePath().toString(), "write"))).isFalse();
assertThat(rule.implies(new FilePermission(Paths.get("/path/to/").toAbsolutePath().toString(), "write"))).isTrue();
}
@Test
public void policy_implies_other_permissions() {
assertThat(rule.implies(new PropertyPermission(Paths.get("/path/to/").toAbsolutePath().toString(), "write"))).isTrue();
}
}
| SonarSource/sonarqube | server/sonar-process/src/test/java/org/sonar/process/PluginFileWriteRuleTest.java | Java | lgpl-3.0 | 2,479 |
/*
Copyright 2007-2011 B3Partners BV.
This program is distributed under the terms
of the GNU General Public License.
You should have received a copy of the GNU General Public License
along with this software. If not, see http://www.gnu.org/licenses/gpl.html
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
/*Hulp functions*/
//contains on array function
function arrayContains(array,element) {
for (var i = 0; i < array.length; i++) {
if (array[i] == element) {
return true;
}
}
return false;
}
// jQuery gives problems with DWR - util.js, so noConflict mode. Usage for jQuery selecter becomes $j() instead of $()
$j = jQuery.noConflict();
// Trim polyfill
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
attachOnload = function(onloadfunction) {
if(typeof(onloadfunction) == 'function') {
var oldonload=window.onload;
if(typeof(oldonload) == 'function') {
window.onload = function() {
oldonload();
onloadfunction();
}
} else {
window.onload = function() {
onloadfunction();
}
}
}
}
var resizeFunctions = new Array();
resizeFunction = function() {
for(i in resizeFunctions) {
resizeFunctions[i]();
}
}
window.onresize = resizeFunction;
attachOnresize = function(onresizefunction) {
if(typeof(onresizefunction) == 'function') {
resizeFunctions[resizeFunctions.length] = onresizefunction;
}
}
checkLocation = function() {
if (top.location != self.location)
top.location = self.location;
}
checkLocationPopup = function() {
if(!usePopup) {
if (top.location == self.location) {
top.location = '/gisviewerconfig/index.do';
}
}
}
getIEVersionNumber = function() {
var ua = navigator.userAgent;
var MSIEOffset = ua.indexOf("MSIE ");
if (MSIEOffset == -1) {
return -1;
} else {
return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
}
}
var ieVersion = getIEVersionNumber();
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return [curleft,curtop];
}
function showHelpDialog(divid) {
$j("#" + divid).dialog({
resizable: true,
draggable: true,
show: 'slide',
hide: 'slide',
autoOpen: false
});
$j("#" + divid).dialog('open');
return false;
}
(function(B3PConfig) {
B3PConfig.cookie = {
createCookie: function(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
readCookie: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
eraseCookie: function(name) {
this.createCookie(name,"",-1);
}
};
})(window.B3PConfig || (window.B3PConfig = {}));
(function(B3PConfig, $) {
B3PConfig.advancedToggle = {
config: {
advancedclass: '.configadvanced',
advancedtoggle: '#advancedToggle',
cookiename: 'advancedtoggle'
},
advancedToggle: null,
advancedItems: [],
init: function() {
var me = this, useAdvancedToggle = false;
me.advancedToggle = $(me.config.advancedtoggle);
me.advancedItems = $(me.config.advancedclass);
me.advancedItems.each(function() {
if($(this).html().trim() !== '') useAdvancedToggle = true;
});
if(B3PConfig.cookie.readCookie(me.getCookiename()) !== null) {
me.advancedToggle[0].checked = B3PConfig.cookie.readCookie(me.getCookiename()) === 'on';
}
if(useAdvancedToggle) {
me.advancedToggle.click(function(){
me.showHideAdvanced();
});
me.showHideAdvanced();
} else {
me.advancedToggle.parent().hide();
}
},
showHideAdvanced: function () {
var showAdvancedOptions = this.advancedToggle.is(':checked');
B3PConfig.cookie.createCookie(this.getCookiename(), showAdvancedOptions ? 'on' : 'off', 7);
showAdvancedOptions ? this.advancedItems.show() : this.advancedItems.hide();
},
getCookiename: function() {
return this.config.cookiename + (this.advancedToggle.data('cookie-key') ? '-' + this.advancedToggle.data('cookie-key') : '');
}
};
})(window.B3PConfig || (window.B3PConfig = {}), jQuery);
var prevTab = null;
var fbLbl;
function labelClick($lbl) {
if(prevTab != null) prevTab.hide();
prevTab = $j(".content_"+$lbl.attr("id").replace("label_", ""));
prevTab.show();
$j(".tablabel").removeClass("active");
$lbl.addClass("active");
}
var showAdvancedOptions = false;
var contentMinHeight = 300;
$j(document).ready(function() {
contentMinHeight = $j(".tablabels").outerHeight(true)+20;
if($j("#treedivContainer").length > 0) contentMinHeight = $j("#treedivContainer").outerHeight(true)+20;
$j(".tabcontent").each(function (){
var counter = 0;
$j(this).find(".configrow").each(function() {
var $this = $j(this);
if(counter%2==1) $this.addClass("odd");
counter++;
$this.find(".helpLink").each(function (){
if($j(this).attr("id") && $j(this).attr("id") != 'undefined')
{
var $helpContentDiv = $j("#" + $j(this).attr("id").replace("helpLink_", ""));
var helpContent = $helpContentDiv.html();
var helpTitle = $helpContentDiv.attr("title");
$j(this).qtip({
content: {
text: helpContent,
title: helpTitle
},
hide: {
event: 'mouseout'
},
show: {
event: 'click mouseenter'
},
position: {
my: 'right top',
at: 'left middle',
target: $j(this),
viewport: $j(window),
adjust: {
x: -10
}
}
});
}
});
});
if(!$j(this).hasClass("defaulttab")) $j(this).hide();
});
$j(".tablabel").each(function() {
$j(this).click(function() {
labelClick($j(this));
});
});
B3PConfig.advancedToggle.init();
$j(".tabcontent").css("min-height", contentMinHeight);
if($j(".tablabel").length != 0) labelClick($j(".tablabel").first());
// Datatables
var tables = [];
jQuery('.dataTable').each(function() {
tables.push(new B3PDataTable(this));
});
jQuery('.postCheckboxTable').click(function() {
for(var x in tables) {
tables[x].showAllRows();
}
});
});
/**
* B3P wrapper for the jQuery DataTables plugin
* @requires jQuery
* @requires jQuery.dataTables
* @param {HTMLElement} table
* @returns {B3PDataTable}
*/
function B3PDataTable(table) {
/**
* Setting to preserve table height even when there are less items
* @type boolean
*/
this.preserveHeight = true;
/**
* The jQuery object of the table
* @type jQuery
*/
this.table = jQuery(table);
/**
* Container for the creation of the DataTable object
* @type DataTable
*/
this.dataTableObj = null;
/**
* Container for the column settings
* @type Array
*/
this.columnSettings = [];
/**
* Widths for each column
* @type Array
*/
this.columnWidths = [];
/**
* Header row to hold the filters
* @type jQuery
*/
this.filters = jQuery('<tr class="filter"></tr>');
/**
* The selected row object
* @type jQuery
*/
this.selectedRow = this.table.find('.row_selected');
/**
* Container for the DataTable settings
* @type Object
*/
this.tableSettings = null;
/**
* Initializes a B3PDataTable object to create a sortable, filterable DataTable
* @returns {Boolean}
*/
this.init = function() {
// We compute the column widths as soon as possible
this.columnWidths = this.getColumnWidths();
var filterCount = this.initHeaders();
if(this.preserveHeight) var tableHeight = this.calculatePageHeight(filterCount);
var tableSettings = this.initDataTable();
// If there is no saved state (first time view) go to selected row
if(tableSettings.oLoadedState === null) {
this.showSelectedRow();
}
this.appendSelectedRowButton();
if(filterCount !== 0) {
this.appendFilters();
}
this.initRowClick();
if(this.preserveHeight) this.setWrapperHeight(tableHeight);
this.showTable();
return true;
};
/**
* Calculate the height of the table header and first 10 rows (first page)
* @param {int} number of filters
* @returns {int}
*/
this.calculatePageHeight = function(filterCount) {
// Border margin of table
var borderMargin = 2;
// Calc header height
var headerHeight = this.table.find('thead').outerHeight(true) + borderMargin;
// If there are filters, multiply headerheight by 2
if(filterCount !== 0) headerHeight = headerHeight * 2;
// Calc content height
var contentHeight = 0;
// Use first 10 rows
var count = 1;
this.table.find('tbody').children().slice(0, 10).each(function() {
contentHeight += jQuery(this).outerHeight(true) + borderMargin;
});
var tableHeight = headerHeight + contentHeight + 16; // margin;
return tableHeight;
};
/**
* Sets the minimum height of the wrapper, causing the table to preserve height
* @param {int} tableHeight
* @returns {Boolean}
*/
this.setWrapperHeight = function(tableHeight) {
var wrapper = this.table.parent();
// Calculate height of search box and pagination
var childHeight = 0;
wrapper.find('.dataTables_filter, .dataTables_paginate').each(function() {
childHeight += jQuery(this).outerHeight(true);
});
// Move info and pagination to the bottom
jQuery('.dataTables_info, .dataTables_paginate').each(function() {
var obj = jQuery(this);
obj.css({
'position': 'absolute',
'bottom': '0px'
});
if(obj.hasClass('dataTables_paginate')) obj.css('right', '15px');
});
// Set wrapper min-height
wrapper.css({
'min-height': (childHeight + tableHeight - 19 + 'px') // Subtract 19 pixels for wrapper margin
});
return true;
};
/**
* Initializes the headers: create column settings and append a filter.
* Returns the amount of filters created.
* @returns {int}
*/
this.initHeaders = function() {
var me = this, filterCount = 0;
this.table.find('thead tr').first().find('th').each(function(index) {
me.columnSettings.push(me.getColumnSettings(this));
var hasFilter = me.createFilter(this, index);
if(hasFilter) filterCount++;
});
return filterCount;
};
/**
* Creates a DataTables column settings object based on some options
* @param {type} the table header object
* @returns {Object}
*/
this.getColumnSettings = function(column) {
var colSetting = {};
var sortType = "string";
if(column.className.match(/sorter\:[ ]?[']?digit[']?/)) {
sortType = "numeric";
}
if(column.className.match(/sorter\:[ ]?[']?dutchdates[']?/)) {
sortType = "dutchdates";
}
if(column.className.match(/sorter\:[ ]?[']?false[']?/)) {
colSetting.bSortable = false;
}
colSetting.sType = sortType;
colSetting.mRender = function(content, type) {
if(type === 'filter') {
// Remove all HTML tags from content to improve filtering
return content.replace(/<\/?[^>]+>/g, '').trim();
}
return content;
};
return colSetting;
};
/**
* Compute the default width of all columns in the table
* @returns {Object}
*/
this.getColumnWidths = function() {
var i = 0, me = this, columnWidths = [];
// Wrap all td's in the body in a .tablespan class (taking care of text-overflow and set width to 1px)
// So we can use the percentages set for the columns as widths
this.table.find('tbody td').wrapInner(jQuery('<span class="tablespan" style="width: 1px;"></span>'));
// Set the table to the maximum width (wrapper - 30px padding)
this.table.css('width', this.table.parent().width() - 30);
// Loop over first row and add width of each td to array
this.table.find('tbody tr:first-child td').each(function() {
columnWidths[i++] = jQuery(this).width();
});
// Reset width of table
this.table.css('width', 'auto');
// Return array with column widths
return columnWidths;
};
/**
* Sets width on each column to prevent large texts from pushing table off screen
* @returns {Boolean}
*/
this.setTablecellWidth = function() {
var me = this;
// Loop over all rows
this.table.find('tbody tr').each(function() {
// Set index var
var i = 0;
// Loop over all cells
jQuery(this).find('td').each(function() {
var td = jQuery(this);
// Add tablespan container when td is empty so widths are consistant
if(td.is(':empty')) {
td.append('<span class="tablespan"></span>');
}
// Set the max width
td.find('.tablespan').css('width', me.columnWidths[i++]);
});
});
return true;
};
/**
* Creates a filter box for a column. Returns true if a filter is created
* @param {type} the table header object
* @param {type} the column index
* @returns {Boolean}
*/
this.createFilter = function(column, index) {
var me = this, col = jQuery(column);
if(col.hasClass('no-filter')) {
// Column has no-filter class, so create empty header
this.filters.append('<th> </th>');
return false;
} else {
var filter = jQuery('<input type="text" name="filter" title="' + col.text() + '" value="" />').keyup(function(e) {
me.filterColumn(this.value, index);
});
var header = jQuery('<th></th>').append(filter);
this.filters.append(header);
}
return true;
};
/**
* Initializes the DataTables plugin and returns the creation settings
* @returns {Object}
*/
this.initDataTable = function() {
var me = this;
this.dataTableObj = this.table.dataTable({
"iDisplayLength": 10,
"bSortClasses": false,
"aoColumns": this.columnSettings,
"aaSorting": [],
"bStateSave": true,
"sPaginationType": "full_numbers",
"oLanguage": {
"sLengthMenu": "_MENU_ items per pagina",
"sSearch": "Zoeken:",
"oPaginate": {
"sFirst": "Begin",
"sNext": "Volgende",
"sPrevious": "Vorige",
"sLast": "Einde"
},
"sInfo": "Items _START_ tot _END_ van _TOTAL_ getoond",
"sInfoEmpty": "Geen items gevonden",
"sInfoFiltered": " - gefilterd (in totaal _MAX_ items)",
"sEmptyTable": "Geen items gevonden",
"sZeroRecords": "Geen items gevonden"
},
"fnDrawCallback": function() {
me.setTablecellWidth();
}
});
this.tableSettings = this.dataTableObj.fnSettings();
return this.tableSettings;
};
/**
* Append the button to go to the selected row to the paginiation
* @returns {Boolean}
*/
this.appendSelectedRowButton = function() {
var me = this;
me.table.parent().find('.dataTables_paginate').append(jQuery('<a>Geselecteerd</a>').addClass('paginate_button').click(function(e){
e.preventDefault();
me.showSelectedRow();
}));
return true;
};
/**
* Append the filter boxes to the table header
* @returns {Boolean}
*/
this.appendFilters = function() {
var me = this;
// Get saved searches to repopulate field with search value
me.filters.find('th').each(function(index) {
var searchCol = me.tableSettings.aoPreSearchCols[index];
if(searchCol.hasOwnProperty('sSearch') && searchCol.sSearch.length !== 0) {
jQuery('input', this).val(searchCol.sSearch);
}
});
// Add filters to table
me.table.find('thead').append(me.filters);
return true;
};
/**
* Attach handlers for clicking a row in the table
* @returns {Boolean}
*/
this.initRowClick = function() {
this.table.find('tbody').delegate("td", "click", function() {
var row = jQuery(this);
// Check if there is a link or input (button, checkbox, etc.) present
if(row.find('a, input').length === 0) {
// No link or input so navigate to the attached URL
var link = row.parent().attr('data-link');
if(link) window.location.href = link;
}
});
return true;
};
/**
* Search a single column for a string
* @param {String} the string to search on
* @param {int} the index of the columns that needs to be filtered
* @returns {Boolean}
*/
this.filterColumn = function(filter, colindex) {
if(this.dataTableObj === null) return;
this.dataTableObj.fnFilter( filter, colindex );
return true;
};
/**
* Shows the currently selected row
* @returns {Boolean}
*/
this.showSelectedRow = function() {
if(this.dataTableObj === null) return false;
this.dataTableObj.fnDisplayRow( this.selectedRow[0] );
return true;
};
/**
* Makes the table visible (table is hidden using CSS and positioning to prevent flicker)
* @returns {Boolean}
*/
this.showTable = function() {
this.table.css({
'position': 'static',
'left': '0px'
});
return true;
};
/**
* Function to show all rows (remove pagination).
* This is mainly used to post all input fields in a tables
* @returns {Boolean}
*/
this.showAllRows = function() {
var wrapper = this.table.parent(), wrapperHeight = wrapper.height();
wrapper.css({
'height': wrapperHeight + 'px',
'overflow': 'hidden'
});
this.table.css({
'position': 'absolute',
'left': '-99999px'
});
jQuery('<div>Bezig met opslaan...</div>')
.css({ 'clear': 'both', 'margin-top': '15px;' })
.insertAfter(jQuery('.dataTables_filter', wrapper));
jQuery('tbody', this.table).append( this.dataTableObj.fnGetHiddenNodes() );
};
/**
* Install dataTable extensions, needed for some functionality
*/
(function() {
if(typeof jQuery.fn.dataTableExt.oSort['dutchdates-asc'] === "undefined") {
/**
* Extension to support sorting of dutch formatted dates (dd-mm-yyyy)
*/
jQuery.fn.dataTableExt.oSort['dutchdates-asc'] = function(a,b) {
var x = parseDutchDate(jQuery(a)), y = parseDutchDate(jQuery(b));
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['dutchdates-desc'] = function(a,b) {
var x = parseDutchDate(jQuery(a)), y = parseDutchDate(jQuery(b));
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
var parseDutchDate = function(obj) {
var s = obj.text();
var hit = s.match(/(\d{2})-(\d{2})-(\d{4})/);
if (hit && hit.length === 4) return new Date(hit[3], hit[2], hit[1]);
return new Date(s);
};
}
if(typeof jQuery.fn.dataTableExt.oApi.fnDisplayRow === "undefined") {
/**
* Extension to go to the page containing a specific row
* We use this extension to go to the selected row
*/
jQuery.fn.dataTableExt.oApi.fnDisplayRow = function ( oSettings, nRow ) {
// Account for the "display" all case - row is already displayed
if ( oSettings._iDisplayLength === -1 ) return;
// Find the node in the table
var iPos = -1, iLen=oSettings.aiDisplay.length;
for( var i=0; i < iLen; i++ ) {
if( oSettings.aoData[ oSettings.aiDisplay[i] ].nTr === nRow ) {
iPos = i;
break;
}
}
// Alter the start point of the paging display
if( iPos >= 0 ) {
oSettings._iDisplayStart = ( Math.floor(i / oSettings._iDisplayLength) ) * oSettings._iDisplayLength;
this.oApi._fnCalculateEnd( oSettings );
}
this.oApi._fnDraw( oSettings );
};
}
if(typeof jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes === "undefined") {
jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes = function ( oSettings ) {
/* Note the use of a DataTables 'private' function thought the 'oApi' object */
var anNodes = this.oApi._fnGetTrNodes( oSettings );
var anDisplay = jQuery('tbody tr', oSettings.nTable);
/* Remove nodes which are being displayed */
for ( var i=0 ; i<anDisplay.length ; i++ )
{
var iIndex = jQuery.inArray( anDisplay[i], anNodes );
if ( iIndex != -1 )
{
anNodes.splice( iIndex, 1 );
}
}
/* Fire back the array to the caller */
return anNodes;
};
}
})();
/**
* Execute initialize function
*/
this.init();
} | B3Partners/gisviewerConfig | src/main/webapp/scripts/commonfunctions.js | JavaScript | lgpl-3.0 | 24,486 |
/**
* Copyright (C) 2010-2016 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite 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.
*
* EvoSuite 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.graphs.ccfg;
public class CCFGFrameEdge extends CCFGEdge {
private static final long serialVersionUID = 8223049010545407697L;
/** {@inheritDoc} */
@Override
public String toString() {
return "";
}
}
| claudejin/evosuite | client/src/main/java/org/evosuite/graphs/ccfg/CCFGFrameEdge.java | Java | lgpl-3.0 | 1,011 |
/*
This file is part of Advanced Input.
Advanced Input 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.
Advanced Input 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 Advanced Input. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace AdvancedInput.ButtonBindings {
public class AI_BB_TranslateBack: IButtonBinding
{
public string name { get { return "TranslateBack"; } }
public ControlTypes lockMask { get { return ControlTypes.LINEAR; } }
public bool locked { get; set; }
public void Update (int state, bool edge)
{
if (state > 0) {
FlightInputHandler.state.Z = 1;
}
}
public AI_BB_TranslateBack (ConfigNode node)
{
}
}
}
| taniwha/AdvancedInput | Source/ButtonBindings/TranslateBack.cs | C# | lgpl-3.0 | 1,131 |
import { ipcRenderer } from 'electron';
import * as normalizeUrl from 'normalize-url';
$(document).ready(() => {
ipcRenderer.send('ready');
});
ipcRenderer.on('open-url', (e: any, msg: any) => {
const url = normalizeUrl(msg);
(document.querySelector('webview.active') as any).loadURL(url);
}); | Perolize/MyBrowser | app/src/js/urlLoad.ts | TypeScript | lgpl-3.0 | 307 |
########################################################################
# File:: presenters.rb
# (C):: Loyalty New Zealand 2014
#
# Purpose:: Include the schema based data validation and rendering code.
# ----------------------------------------------------------------------
# 26-Jan-2015 (ADH): Split from top-level inclusion file.
########################################################################
module Hoodoo
# Module providing a namespace for schema-based data rendering and
# validation code.
#
module Presenters
end
end
# Dependencies
require 'hoodoo/utilities'
# Presenters
require 'hoodoo/presenters/base'
require 'hoodoo/presenters/base_dsl'
require 'hoodoo/presenters/embedding'
require 'hoodoo/presenters/types/field'
require 'hoodoo/presenters/types/object'
require 'hoodoo/presenters/types/array'
require 'hoodoo/presenters/types/hash'
require 'hoodoo/presenters/types/string'
require 'hoodoo/presenters/types/text'
require 'hoodoo/presenters/types/enum'
require 'hoodoo/presenters/types/boolean'
require 'hoodoo/presenters/types/float'
require 'hoodoo/presenters/types/integer'
require 'hoodoo/presenters/types/decimal'
require 'hoodoo/presenters/types/date'
require 'hoodoo/presenters/types/date_time'
require 'hoodoo/presenters/types/tags'
require 'hoodoo/presenters/types/uuid'
require 'hoodoo/presenters/common_resource_fields'
| LoyaltyNZ/hoodoo | lib/hoodoo/presenters.rb | Ruby | lgpl-3.0 | 1,391 |
import itertools
import re
import random
import time
import urllib2
from bs4 import BeautifulSoup
import csv
import os
import os.path
import string
import pg
from collections import OrderedDict
import tweepy
import sys
# lint_ignore=E302,E501
_dir = os.path.dirname(os.path.abspath(__file__))
_cur = pg.connect(host="127.0.0.1")
_topHashtagsDir = "%s/dissertationData/topHashtags" % (_dir)
def getTweepyAPI():
consumer_key = "vKbz24SqytZnYO33FNkR7w"
consumer_secret = "jjobro8Chy9aKMzo8szYMz9tHftONLRkjNnrxk0"
access_key = "363361813-FKSdmwSbzuUzHWg326fTGJM7Bu2hTviqEetjMgu8"
access_secret = "VKgzDnTvDUWR1csliUR3BiMOI2oqO9NzocNKX1jPd4"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
return tweepy.API(auth)
_api = getTweepyAPI()
def isRetweet(tweet):
return hasattr(tweet, 'retweeted_status')
def write2csv(res, file):
print "writing %s results to file: %s" % (len(res), file)
with open(file, 'wb') as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerows(res)
def myQuery(query):
print "running query: %s" % (query)
res = _cur.query(query)
print "finished running query"
return(res)
def getTweetObj(tweet):
tweetObj = [tweet.id_str, tweet.user.id, tweet.user.screen_name.lower(), tweet.created_at, isRetweet(tweet), tweet.in_reply_to_status_id_str,
tweet.lang, tweet.truncated, tweet.text.encode("utf-8")]
return tweetObj
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, group):
self.group = group
self.curTweets = []
# http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods
super(CustomStreamListener, self).__init__()
def addTweet(self, tweet):
tweetObj = getTweetObj(tweet)
tweetObj.append(self.group)
self.curTweets.append(tweetObj)
if len(self.curTweets) == 1000:
self.saveResults()
self.curTweets = []
def saveResults(self):
sys.stdout.write('\n')
file = '/tmp/topHashtags.csv' % ()
ids = [tweet[0] for tweet in self.curTweets]
ids = list(OrderedDict.fromkeys(ids))
ids = [[id] for id in ids]
myQuery('truncate temp_tweets_id')
write2csv(ids, file)
myQuery("copy temp_tweets_id (id) from '%s' delimiters ',' csv" % (file))
newIds = myQuery("select id from temp_tweets_id as t where t.id not in (select id from top_hashtag_tweets where top_hashtag_tweets.id >= (select min(id) from temp_tweets_id))").getresult()
newIds = [id[0] for id in newIds]
newIds = [str(id) for id in newIds]
newTweets = [tweet for tweet in self.curTweets if tweet[0] in newIds]
newTweets = dict((tweet[0], tweet) for tweet in newTweets).values()
write2csv(newTweets, file)
myQuery("copy top_hashtag_tweets (id, user_id, user_screen_name, created_at, retweeted, in_reply_to_status_id, lang, truncated, text, hashtag_group) from '%s' delimiters ',' csv" % (file))
def on_status(self, status):
sys.stdout.write('.')
sys.stdout.flush()
self.addTweet(status)
def on_error(self, status_code):
print >> sys.stderr, 'error: %s' % (repr(status_code))
return True
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True
def scrapeTrendsmap():
baseUrl = 'http://trendsmap.com'
url = baseUrl + '/local'
soup = BeautifulSoup(urllib2.urlopen(url).read())
#res = soup.findAll('div', {'class': 'location'})
res = soup.findAll('a', {'href': re.compile('^\/local\/us')})
cityUrls = [baseUrl + item['href'] for item in res]
allHashtags = []
for rank, url in enumerate(cityUrls):
print "working url %s, %s/%s" % (url, rank, len(cityUrls))
soup = BeautifulSoup(urllib2.urlopen(url).read())
res = soup.findAll('a', {'class': 'obscure-text', 'title': re.compile('^#')})
hashtags = [item['title'].encode('utf-8') for item in res]
allHashtags.extend(hashtags)
time.sleep(2 + random.random())
allHashtags = list(OrderedDict.fromkeys(allHashtags))
random.shuffle(allHashtags)
return allHashtags
def generateTopHashtagsTrendsmap():
res = scrapeTrendsmap()
return res
def scrapeStatweestics():
url = 'http://statweestics.com/stats/hashtags/day'
soup = BeautifulSoup(urllib2.urlopen(url).read())
res = []
for hrefEl in soup.findAll('a', {'href': re.compile('^\/stats\/show')}):
res.append(hrefEl.contents[0].encode('utf-8'))
return res
def generateTopHashtagsStatweestics():
res = scrapeStatweestics()
return res
def generateTopHashtagsCSV(scrapeFun, group):
res = []
for rank, item in enumerate(scrapeFun()):
res.append([item, rank, group])
file = "%s/%s.csv" % (_topHashtagsDir, group)
write2csv(res, file)
def storeTopHashtags(topHashtagsFile):
cmd = "copy top_hashtag_hashtags (hashtag, rank, hashtag_group) from '%s/%s.csv' delimiters ',' csv" % (_topHashtagsDir, topHashtagsFile)
myQuery(cmd)
def generateTopHashtags(scrapeFun=generateTopHashtagsTrendsmap, groupID='trendsmap'):
hashtagGroup = '%s %s' % (time.strftime("%Y-%m-%d %H:%M:%S"), groupID)
generateTopHashtagsCSV(scrapeFun, hashtagGroup)
storeTopHashtags(hashtagGroup)
def getHashtagsFrom(group):
res = myQuery("select hashtag from top_hashtag_hashtags where hashtag_group = '%s' order by rank asc" % (group)).getresult()
res = [item[0] for item in res]
res = [hashtag for hashtag in res if sys.getsizeof(hashtag) <= 60]
res = res[-400:]
return res
def streamHashtags(hashtagGroup):
while True:
try:
sapi = tweepy.streaming.Stream(_api.auth, CustomStreamListener(hashtagGroup))
sapi.filter(languages=['en'], track=getHashtagsFrom('%s' % (hashtagGroup)))
except Exception as e:
print "couldn't do it for %s:" % (e)
time.sleep(1)
pass
def streamHashtagsCurrent():
#hashtagGroup = '2014-02-27 17:13:30 initial'
#hashtagGroup = '2014-03-17 11:28:15 trendsmap'
#hashtagGroup = '2014-03-24 13:06:19 trendsmap'
hashtagGroup = '2014-04-04 15:03:59 trendsmap'
streamHashtags(hashtagGroup)
def scrape_socialbakers(url):
soup = BeautifulSoup(urllib2.urlopen(url).read())
res = []
for div in soup.findAll('div', {'id': 'snippet-bookmarkToggle-bookmarkToggle'}):
res.append(div.findAll('div')[0]['id'].split('-')[-1])
print "grabbed %s results from url %s" % (len(res), url)
return res
def scrape_twitaholic(url):
soup = BeautifulSoup(urllib2.urlopen(url).read())
res = []
for tr in soup.findAll('tr', {'style': 'border-top:1px solid black;'}):
temp = tr.find('td', {'class': 'statcol_name'})
res.append(temp.a['title'].split('(')[1][4:-1])
return res
def generateTopUsersTwitaholic():
res = []
for i in range(10):
i = i + 1
url = 'http://twitaholic.com/top' + str(i) + '00/followers/'
res.append(scrape_twitaholic(url))
return res
def generateTopUsersSocialBakers(numUsers=10000):
res = []
for i in range(numUsers / 50):
url = 'http://socialbakers.com/twitter/page-' + str(i + 1) + '/'
res.append(scrape_socialbakers(url))
return res
_topUsersDir = "%s/dissertationData/topRankedUsers" % (_dir)
def generateTopUsersCSV(scrapeFun, topUsersFile):
res = scrapeFun()
res = list(itertools.chain(*res))
res = [x.lower() for x in res]
res = OrderedDict.fromkeys(res)
res = filter(None, res)
with open("%s/%s" % (_topUsersDir, topUsersFile), 'wb') as csvfile:
csvWriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
rank = 0
for item in res:
rank = rank + 1
csvWriter.writerow([item, rank])
def storeTopUsers(topUsersFile):
topUsersDir = _topUsersDir
cmd = "copy topUsers (user_screen_name, rank) from '${topUsersDir}/${topUsersFile}' delimiters ',' csv"
cmd = string.Template(cmd).substitute(locals())
myQuery(cmd)
def generateTopUsers(scrapeFun=generateTopUsersTwitaholic, topUsersFile='top1000Twitaholic.csv'):
generateTopUsersCSV(scrapeFun=scrapeFun, topUsersFile=topUsersFile)
storeTopUsers(topUsersFile=topUsersFile)
def storeTagSynonyms(synonymsFile):
cmd = "copy tag_synonyms (%s) from '%s/dissertationData/tagSynonyms/%s' delimiters ',' csv header" % (
"id, Source_Tag_Name, Target_Tag_Name, Creation_Date, Owner_User_Id, Auto_Rename_Count, Last_Auto_Rename, Score, Approved_By_User_Id, Approval_Date",
_dir, synonymsFile)
myQuery(cmd)
def storeCurTagSynonyms():
storeTagSynonyms('synonyms-2014-01-30.csv')
def backupTables(tableNames=['topUsers', 'tweets', 'top_hashtag_hashtags', 'top_hashtag_tweets', 'post_subsets', 'top_hashtag_subsets',
'post_tokenized', 'top_hashtag_tokenized', 'post_filtered', 'twitter_users', 'tag_synonyms', 'users', 'posts',
'post_tokenized_type_types', 'top_hashtag_tokenized_type_types', 'post_tokenized_chunk_types', 'top_hashtag_tokenized_chunk_types',
'tweets_tokenized', 'tweets_tokenized_chunk_types', 'tweets_tokenized_type_types']):
for tableName in tableNames:
file = "%s/dissertationData/tables/%s.csv" % (_dir, tableName)
cmd = string.Template("copy ${tableName} to '${file}' delimiter ',' csv header").substitute(locals())
myQuery(cmd)
def getRemainingHitsUserTimeline():
stat = _api.rate_limit_status()
return stat['resources']['statuses']['/statuses/user_timeline']['remaining']
def getRemainingHitsGetUser():
stat = _api.rate_limit_status()
return stat['resources']['users']['/users/lookup']['remaining']
def getTweets(screen_name, **kwargs):
# w.r.t include_rts: ref: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
# When set to false, the timeline will strip any native retweets (though they
# will still count toward both the maximal length of the timeline and the slice
# selected by the count parameter).
return _api.user_timeline(screen_name=screen_name, include_rts=True, **kwargs)
def getInfoForUser(screenNames):
users = _api.lookup_users(screen_names=screenNames)
res = [[user.id, user.created_at, user.description.encode('utf-8'), user.followers_count, user.friends_count,
user.lang, user.location.encode('utf-8'), user.name.encode('utf-8'), user.screen_name.lower(), user.verified, user.statuses_count] for user in users]
file = '/tmp/%s..%s_user.csv' % (screenNames[0], screenNames[-1])
write2csv(res, file)
myQuery("copy twitter_users (id,created_at,description,followers_count,friends_count,lang,location,name,user_screen_name,verified,statuses_count) from '%s' delimiters ',' csv" % (file))
def getAllTweets(screenNames):
def getTweetsBetween(greaterThanID, lessThanID):
alltweets = []
while True:
print "getting tweets from %s that are later than %s but before %s" % (screen_name, greaterThanID, lessThanID)
newTweets = getTweets(screen_name, count=200, max_id=lessThanID - 1, since_id=greaterThanID + 1)
if len(newTweets) == 0:
break
alltweets.extend(newTweets)
lessThanID = alltweets[-1].id
print "...%s tweets downloaded so far" % (len(alltweets))
return alltweets
assert len(screenNames) == 1, "Passed more than one screen name into function"
screen_name = screenNames[0]
print "getting tweets for %s" % (screen_name)
alltweets = []
lessThanID = getTweets(screen_name, count=1)[-1].id + 1
cmd = string.Template("select id from tweets where user_screen_name = '${screen_name}' order by id desc").substitute(locals())
res = myQuery(cmd).getresult()
if len(res) == 0:
newestGrabbed = 0
else:
newestGrabbed = int(res[0][0])
res = getTweetsBetween(newestGrabbed, lessThanID)
alltweets.extend(res)
cmd = string.Template("select id from tweets where user_screen_name = '${screen_name}' order by id asc").substitute(locals())
res = myQuery(cmd).getresult()
if len(res) == 0:
lessThanID = 0
else:
lessThanID = int(res[0][0])
alltweets.extend(getTweetsBetween(0, lessThanID))
outTweets = [getTweetObj(tweet) for tweet in alltweets]
file = '/tmp/%s_tweets.csv' % screen_name
write2csv(outTweets, file)
myQuery("copy tweets (id, user_id, user_screen_name, created_at, retweeted, in_reply_to_status_id, lang, truncated,text) from '%s' delimiters ',' csv" % (file))
def userAlreadyCollected(user_screen_name):
res = myQuery(string.Template("select * from tweets where user_screen_name='${user_screen_name}' limit 1").substitute(locals())).getresult()
return len(res) > 0
def userInfoAlreadyCollected(user_screen_name):
res = myQuery(string.Template("select * from twitter_users where user_screen_name='${user_screen_name}' limit 1").substitute(locals())).getresult()
return len(res) > 0
# ref: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks/434411#434411
def chunker(seq, size):
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
def getForTopUsers(alreadyCollectedFun, getForUserFun, getRemainingHitsFun, hitsAlwaysGreaterThan, userQuery, groupFun=lambda x: chunker(x, 1)):
res = myQuery(userQuery).getresult()
screenNames = [[user[0]] for user in res]
screenNames = list(itertools.chain(*screenNames))
print "getting tweets for %s users" % len(screenNames)
screenNameGroups = groupFun(screenNames)
for screenNameGroup in screenNameGroups:
newScreenNames = []
for screenName in screenNameGroup:
if alreadyCollectedFun(screenName):
print "already collected tweets for %s; moving to next user" % (screenName)
continue
newScreenNames.append(screenName)
if len(newScreenNames) == 0:
continue
try:
while True:
remainingHits = getRemainingHitsFun()
if remainingHits > hitsAlwaysGreaterThan:
break
print "only %s remaining hits; waiting until greater than %s" % (remainingHits, hitsAlwaysGreaterThan)
time.sleep(60)
print "calling %s with %s at %s remaining hits" % (getForUserFun, newScreenNames, remainingHits)
getForUserFun(newScreenNames)
except Exception as e:
print "couldn't do it for %s: %s" % (newScreenNames, e)
time.sleep(1)
pass
def getAllTweetsDefault(userQuery):
return getForTopUsers(alreadyCollectedFun=userAlreadyCollected, getForUserFun=getAllTweets, getRemainingHitsFun=getRemainingHitsUserTimeline, hitsAlwaysGreaterThan=30, userQuery=userQuery)
def makeUserQuery(val, col):
return 'select user_screen_name from twitter_users where %s > %d order by %s asc limit 1000' % (col, val, col)
def makeUserQueryFollowers(val):
return makeUserQuery(val, 'followers_count')
def makeUserQueryTweets(val):
return makeUserQuery(val, 'statuses_count')
def getAllTweetsFor10MUsers():
return getAllTweetsDefault(makeUserQueryFollowers(10000000))
def getAllTweetsFor1MUsers():
return getAllTweetsDefault(makeUserQueryFollowers(1000000))
def getAllTweetsFor100kUsers():
return getAllTweetsDefault(makeUserQueryFollowers(100000))
def getAllTweetsFor10kUsers():
return getAllTweetsDefault(makeUserQueryFollowers(10000))
def getAllTweetsFor5kUsers():
return getAllTweetsDefault(makeUserQueryFollowers(5000))
def getAllTweetsFor1kUsers():
return getAllTweetsDefault(makeUserQueryFollowers(1000))
def getAllTweetsForS1e2Users():
return getAllTweetsDefault(makeUserQueryTweets(100))
def getAllTweetsForS5e2Users():
return getAllTweetsDefault(makeUserQueryTweets(500))
def getAllTweetsForS1e3Users():
return getAllTweetsDefault(makeUserQueryTweets(1000))
def getAllTweetsForS5e3Users():
return getAllTweetsDefault(makeUserQueryTweets(5000))
def getAllTweetsForS1e4Users():
return getAllTweetsDefault(makeUserQueryTweets(10000))
def getAllTweetsForS5e4Users():
return getAllTweetsDefault(makeUserQueryTweets(50000))
def getAllTweetsForTopUsersByFollowers():
getAllTweetsFor10MUsers()
getAllTweetsFor1MUsers()
getAllTweetsFor100kUsers()
getAllTweetsFor10kUsers()
getAllTweetsFor1kUsers()
getAllTweetsFor5kUsers()
def getAllTweetsForTopUsersByTweets():
getAllTweetsForS1e2Users()
getAllTweetsForS5e2Users()
getAllTweetsForS1e3Users()
getAllTweetsForS5e3Users()
getAllTweetsForS1e4Users()
getAllTweetsForS5e4Users()
def getUserInfoForTopUsers():
getForTopUsers(alreadyCollectedFun=userInfoAlreadyCollected, getForUserFun=getInfoForUser, getRemainingHitsFun=getRemainingHitsGetUser, hitsAlwaysGreaterThan=30, groupFun=lambda x: chunker(x, 100),
userQuery='select (user_screen_name) from topUsers order by rank asc limit 100000')
def generateTopUsers100k():
generateTopUsers(scrapeFun=lambda: generateTopUsersSocialBakers(numUsers=100000), topUsersFile='top100000SocialBakers.csv')
def backupTopHashtags():
backupTables(tableNames=['top_hashtag_hashtags',
'top_hashtag_subsets',
'top_hashtag_tokenized',
'top_hashtag_tokenized_chunk_types',
'top_hashtag_tokenized_type_types',
'top_hashtag_tweets'])
def backupTweets():
backupTables(tableNames=['tweets',
'tweets_tokenized',
'tweets_tokenized_chunk_types',
'tweets_tokenized_type_types'])
# Current run selections
#generateTopUsers100k()
#getAllTweetsForTopUsersByFollowers()
#getAllTweetsForTopUsersByTweets()
#getUserInfoForTopUsers()
#storeCurTagSynonyms()
#backupTopHashtags()
#backupTables()
#generateTopHashtags()
#streamHashtagsCurrent()
if __name__ == "__main__":
command = " ".join(sys.argv[1:])
print('running command %s') % (command)
eval(command)
| claytontstanley/dissertation | dissProject/scrapeUsers.py | Python | lgpl-3.0 | 18,399 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package parallelismanalysis.util;
/*************************************************************************
* Compilation: javac Permutations.java
* Execution: java Permutations N
*
* Enumerates all permutations on N elements.
*
* % java Permutations 3
* bca
* cba
* cab
* acb
* bac
* abc
*
* % java Permutations 3 | sort
* abc
* acb
* bac
* bca
* cab
* cba
*
* http://www.comscigate.com/cs/IntroSedgewick/20elements/27recursion/Permutations.java
*************************************************************************/
public class Permutations {
// swap the characters at indices i and j
public static void swap(char[] a, int i, int j) {
char c;
c = a[i];
a[i] = a[j];
a[j] = c;
}
// print n! permutation of the characters of a
public static void enumerate(char[] a, int n) {
if (n == 1) {
System.out.println(a);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n - 1);
enumerate(a, n - 1);
swap(a, i, n - 1);
}
}
public static void main(String[] args) {
int N = 6; // Integer.parseInt(args[0]);
String elements = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// initialize a[i] to ith letter, starting at 'a'
char[] a = new char[N];
for (int i = 0; i < N; i++) {
a[i] = elements.charAt(i);
}
enumerate(a, N);
}
}
| parmerasa-uau/parallelism-optimization | ParallelismAnalysisJMetal/src/parallelismanalysis/util/Permutations.java | Java | lgpl-3.0 | 1,677 |
namespace StockSharp.Algo.Testing
{
using System;
using Ecng.Common;
using StockSharp.Messages;
/// <summary>
/// Адаптер, исполняющий сообщения в <see cref="IMarketEmulator"/>.
/// </summary>
public class EmulationMessageAdapter : MessageAdapter<IMessageSessionHolder>
{
/// <summary>
/// Создать <see cref="EmulationMessageAdapter"/>.
/// </summary>
/// <param name="sessionHolder">Контейнер для сессии.</param>
public EmulationMessageAdapter(IMessageSessionHolder sessionHolder)
: this(new MarketEmulator(), sessionHolder)
{
}
/// <summary>
/// Создать <see cref="EmulationMessageAdapter"/>.
/// </summary>
/// <param name="emulator">Эмулятор торгов.</param>
/// <param name="sessionHolder">Контейнер для сессии.</param>
public EmulationMessageAdapter(IMarketEmulator emulator, IMessageSessionHolder sessionHolder)
: base(MessageAdapterTypes.Transaction, sessionHolder)
{
Emulator = emulator;
}
private IMarketEmulator _emulator;
/// <summary>
/// Эмулятор торгов.
/// </summary>
public IMarketEmulator Emulator
{
get { return _emulator; }
set
{
if (value == null)
throw new ArgumentNullException("value");
if (value == _emulator)
return;
if (_emulator != null)
{
_emulator.NewOutMessage -= SendOutMessage;
_emulator.Parent = null;
}
_emulator = value;
_emulator.Parent = SessionHolder;
_emulator.NewOutMessage += SendOutMessage;
}
}
/// <summary>
/// Запустить таймер генерации с интервалом <see cref="MessageSessionHolder.MarketTimeChangedInterval"/> сообщений <see cref="TimeMessage"/>.
/// </summary>
protected override void StartMarketTimer()
{
}
/// <summary>
/// Отправить сообщение.
/// </summary>
/// <param name="message">Сообщение.</param>
protected override void OnSendInMessage(Message message)
{
SessionHolder.DoIf<IMessageSessionHolder, HistorySessionHolder>(s => s.UpdateCurrentTime(message.GetServerTime()));
switch (message.Type)
{
case MessageTypes.Connect:
_emulator.SendInMessage(new ResetMessage());
SendOutMessage(new ConnectMessage());
return;
case MessageTypes.Disconnect:
SendOutMessage(new DisconnectMessage());
return;
case ExtendedMessageTypes.EmulationState:
SendOutMessage(message.Clone());
return;
}
_emulator.SendInMessage(message);
}
}
} | Enterprize-1701/robot | Algo/Testing/EmulationMessageAdapter.cs | C# | lgpl-3.0 | 2,581 |
<?php
/*
* This file is part of facturacion_base
* Copyright (C) 2013-2017 Carlos Garcia Gomez neorazorx@gmail.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, see <http://www.gnu.org/licenses/>.
*/
namespace FacturaScripts\model;
require_model('asiento.php');
require_model('ejercicio.php');
require_model('linea_iva_factura_proveedor.php');
require_model('linea_factura_proveedor.php');
require_model('regularizacion_iva.php');
require_model('secuencia.php');
require_model('serie.php');
/**
* Factura de un proveedor.
*
* @author Carlos García Gómez <neorazorx@gmail.com>
*/
class factura_proveedor extends \fs_model
{
/**
* Clave primaria.
* @var type
*/
public $idfactura;
/**
* ID de la factura a la que rectifica.
* @var type
*/
public $idfacturarect;
/**
* ID del asiento relacionado, si lo hay.
* @var type
*/
public $idasiento;
/**
* ID del asiento de pago relacionado, si lo hay.
* @var type
*/
public $idasientop;
public $cifnif;
/**
* Empleado que ha creado la factura.
* Modelo agente.
* @var type
*/
public $codagente;
/**
* Almacén en el que entra la mercancía.
* @var type
*/
public $codalmacen;
/**
* Divisa de la factura.
* @var type
*/
public $coddivisa;
/**
* Ejercicio relacionado. El que corresponde a la fecha.
* @var type
*/
public $codejercicio;
/**
* Código único de la factura. Para humanos.
* @var type
*/
public $codigo;
/**
* Código de la factura a la que rectifica.
* @var type
*/
public $codigorect;
/**
* Forma d epago usada.
* @var type
*/
public $codpago;
/**
* Proveedor de la factura.
* @var type
*/
public $codproveedor;
/**
* Serie de la factura.
* @var type
*/
public $codserie;
public $fecha;
public $hora;
/**
* % de retención IRPF de la factura.
* Cada línea puede tener uno distinto.
* @var type
*/
public $irpf;
/**
* Suma total antes de impuestos.
* @var type
*/
public $neto;
/**
* Nombre del proveedor.
* @var type
*/
public $nombre;
/**
* Número de la factura.
* Único dentro de serie+ejercicio.
* @var type
*/
public $numero;
/**
* Número de factura del proveedor, si lo hay.
* @var type
*/
public $numproveedor;
public $observaciones;
public $pagada;
/**
* Tasa de conversión a Euros de la divisa de la factura.
* @var type
*/
public $tasaconv;
/**
* Importe total de la factura, con impuestos.
* @var type
*/
public $total;
/**
* Total expresado en euros, por si no fuese la divisa de la factura.
* totaleuros = total/tasaconv
* No hace falta rellenarlo, al hacer save() se calcula el valor.
* @var type
*/
public $totaleuros;
/**
* Suma total de retenciones IRPF de las líneas.
* @var type
*/
public $totalirpf;
/**
* Suma total del IVA de las líneas.
* @var type
*/
public $totaliva;
/**
* Suma del recargo de equivalencia de las líneas.
* @var type
*/
public $totalrecargo;
public $anulada;
/**
* Número de documentos adjuntos.
* @var integer
*/
public $numdocs;
public function __construct($f = FALSE)
{
parent::__construct('facturasprov');
if($f)
{
$this->anulada = $this->str2bool($f['anulada']);
$this->cifnif = $f['cifnif'];
$this->codagente = $f['codagente'];
$this->codalmacen = $f['codalmacen'];
$this->coddivisa = $f['coddivisa'];
$this->codejercicio = $f['codejercicio'];
$this->codigo = $f['codigo'];
$this->codigorect = $f['codigorect'];
$this->codpago = $f['codpago'];
$this->codproveedor = $f['codproveedor'];
$this->codserie = $f['codserie'];
$this->fecha = Date('d-m-Y', strtotime($f['fecha']));
$this->hora = '00:00:00';
if( !is_null($f['hora']) )
{
$this->hora = date('H:i:s', strtotime($f['hora']));
}
$this->idasiento = $this->intval($f['idasiento']);
$this->idasientop = $this->intval($f['idasientop']);
$this->idfactura = $this->intval($f['idfactura']);
$this->idfacturarect = $this->intval($f['idfacturarect']);
$this->irpf = floatval($f['irpf']);
$this->neto = floatval($f['neto']);
$this->nombre = $f['nombre'];
$this->numero = $f['numero'];
$this->numproveedor = $f['numproveedor'];
$this->observaciones = $this->no_html($f['observaciones']);
$this->pagada = $this->str2bool($f['pagada']);
$this->tasaconv = floatval($f['tasaconv']);
$this->total = floatval($f['total']);
$this->totaleuros = floatval($f['totaleuros']);
$this->totalirpf = floatval($f['totalirpf']);
$this->totaliva = floatval($f['totaliva']);
$this->totalrecargo = floatval($f['totalrecargo']);
$this->numdocs = intval($f['numdocs']);
}
else
{
$this->anulada = FALSE;
$this->cifnif = '';
$this->codagente = NULL;
$this->codalmacen = $this->default_items->codalmacen();
$this->coddivisa = NULL;
$this->codejercicio = NULL;
$this->codigo = NULL;
$this->codigorect = NULL;
$this->codpago = $this->default_items->codpago();
$this->codproveedor = NULL;
$this->codserie = $this->default_items->codserie();
$this->fecha = Date('d-m-Y');
$this->hora = Date('H:i:s');
$this->idasiento = NULL;
$this->idasientop = NULL;
$this->idfactura = NULL;
$this->idfacturarect = NULL;
$this->irpf = 0;
$this->neto = 0;
$this->nombre = '';
$this->numero = NULL;
$this->numproveedor = NULL;
$this->observaciones = NULL;
$this->pagada = FALSE;
$this->tasaconv = 1;
$this->total = 0;
$this->totaleuros = 0;
$this->totalirpf = 0;
$this->totaliva = 0;
$this->totalrecargo = 0;
$this->numdocs = 0;
}
}
protected function install()
{
new \serie();
new \asiento();
return '';
}
public function observaciones_resume()
{
if($this->observaciones == '')
{
return '-';
}
else if( strlen($this->observaciones) < 60 )
{
return $this->observaciones;
}
else
return substr($this->observaciones, 0, 50).'...';
}
/**
* Establece la fecha y la hora, pero respetando el ejercicio y las
* regularizaciones de IVA.
* Devuelve TRUE si se asigna una fecha u hora distinta a los solicitados.
* @param type $fecha
* @param type $hora
* @return boolean
*/
public function set_fecha_hora($fecha, $hora)
{
$cambio = FALSE;
if( is_null($this->numero) ) /// nueva factura
{
$this->fecha = $fecha;
$this->hora = $hora;
}
else if($fecha != $this->fecha) /// factura existente y cambiamos fecha
{
$cambio = TRUE;
$eje0 = new \ejercicio();
$ejercicio = $eje0->get($this->codejercicio);
if($ejercicio)
{
/// ¿El ejercicio actual está abierto?
if( $ejercicio->abierto() )
{
$eje2 = $eje0->get_by_fecha($fecha);
if($eje2)
{
if( $eje2->abierto() )
{
/// ¿La factura está dentro de alguna regularización?
$regiva0 = new \regularizacion_iva();
if( $regiva0->get_fecha_inside($this->fecha) )
{
$this->new_error_msg('La factura se encuentra dentro de una regularización de '
.FS_IVA.'. No se puede modificar la fecha.');
}
else if( $regiva0->get_fecha_inside($fecha) )
{
$this->new_error_msg('No se puede asignar la fecha '.$fecha.' porque ya hay'
. ' una regularización de '.FS_IVA.' para ese periodo.');
}
else
{
$cambio = FALSE;
$this->fecha = $fecha;
$this->hora = $hora;
/// ¿El ejercicio es distinto?
if($this->codejercicio != $eje2->codejercicio)
{
$this->codejercicio = $eje2->codejercicio;
$this->new_codigo();
}
}
}
else
{
$this->new_error_msg('El ejercicio '.$eje2->nombre.' está cerrado. No se puede modificar la fecha.');
}
}
}
else
{
$this->new_error_msg('El ejercicio '.$ejercicio->nombre.' está cerrado. No se puede modificar la fecha.');
}
}
else
{
$this->new_error_msg('Ejercicio no encontrado.');
}
}
else if($hora != $this->hora) /// factura existente y cambiamos hora
{
$this->hora = $hora;
}
return $cambio;
}
public function url()
{
if( is_null($this->idfactura) )
{
return 'index.php?page=compras_facturas';
}
else
return 'index.php?page=compras_factura&id='.$this->idfactura;
}
public function asiento_url()
{
if( is_null($this->idasiento) )
{
return 'index.php?page=contabilidad_asientos';
}
else
return 'index.php?page=contabilidad_asiento&id='.$this->idasiento;
}
public function asiento_pago_url()
{
if( is_null($this->idasientop) )
{
return 'index.php?page=contabilidad_asientos';
}
else
return 'index.php?page=contabilidad_asiento&id='.$this->idasientop;
}
public function agente_url()
{
if( is_null($this->codagente) )
{
return "index.php?page=admin_agentes";
}
else
return "index.php?page=admin_agente&cod=".$this->codagente;
}
public function proveedor_url()
{
if( is_null($this->codproveedor) )
{
return "index.php?page=compras_proveedores";
}
else
return "index.php?page=compras_proveedor&cod=".$this->codproveedor;
}
/**
* Devuelve las líneas de la factura.
* @return line_factura_proveedor
*/
public function get_lineas()
{
$linea = new \linea_factura_proveedor();
return $linea->all_from_factura($this->idfactura);
}
/**
* Devuelve las líneas de IVA de la factura.
* Si no hay, las crea.
* @return \linea_iva_factura_proveedor
*/
public function get_lineas_iva()
{
$linea_iva = new \linea_iva_factura_proveedor();
$lineasi = $linea_iva->all_from_factura($this->idfactura);
/// si no hay lineas de IVA las generamos
if( !$lineasi )
{
$lineas = $this->get_lineas();
if($lineas)
{
foreach($lineas as $l)
{
$i = 0;
$encontrada = FALSE;
while($i < count($lineasi))
{
if($l->iva == $lineasi[$i]->iva AND $l->recargo == $lineasi[$i]->recargo)
{
$encontrada = TRUE;
$lineasi[$i]->neto += $l->pvptotal;
$lineasi[$i]->totaliva += ($l->pvptotal*$l->iva)/100;
$lineasi[$i]->totalrecargo += ($l->pvptotal*$l->recargo)/100;
}
$i++;
}
if( !$encontrada )
{
$lineasi[$i] = new \linea_iva_factura_proveedor();
$lineasi[$i]->idfactura = $this->idfactura;
$lineasi[$i]->codimpuesto = $l->codimpuesto;
$lineasi[$i]->iva = $l->iva;
$lineasi[$i]->recargo = $l->recargo;
$lineasi[$i]->neto = $l->pvptotal;
$lineasi[$i]->totaliva = ($l->pvptotal*$l->iva)/100;
$lineasi[$i]->totalrecargo = ($l->pvptotal*$l->recargo)/100;
}
}
/// redondeamos y guardamos
if( count($lineasi) == 1 )
{
$lineasi[0]->neto = round($lineasi[0]->neto, FS_NF0);
$lineasi[0]->totaliva = round($lineasi[0]->totaliva, FS_NF0);
$lineasi[0]->totalrecargo = round($lineasi[0]->totalrecargo, FS_NF0);
$lineasi[0]->totallinea = $lineasi[0]->neto + $lineasi[0]->totaliva + $lineasi[0]->totalrecargo;
$lineasi[0]->save();
}
else
{
/*
* Como el neto y el iva se redondean en la factura, al dividirlo
* en líneas de iva podemos encontrarnos con un descuadre que
* hay que calcular y solucionar.
*/
$t_neto = 0;
$t_iva = 0;
foreach($lineasi as $li)
{
$li->neto = bround($li->neto, FS_NF0);
$li->totaliva = bround($li->totaliva, FS_NF0);
$li->totallinea = $li->neto + $li->totaliva + $li->totalrecargo;
$t_neto += $li->neto;
$t_iva += $li->totaliva;
}
if( !$this->floatcmp($this->neto, $t_neto) )
{
/*
* Sumamos o restamos un céntimo a los netos más altos
* hasta que desaparezca el descuadre
*/
$diferencia = round( ($this->neto-$t_neto) * 100 );
usort($lineasi, function($a, $b) {
if($a->totallinea == $b->totallinea)
{
return 0;
}
else if($this->total < 0)
{
return ($a->totallinea < $b->totallinea) ? -1 : 1;
}
else
{
return ($a->totallinea < $b->totallinea) ? 1 : -1;
}
});
foreach($lineasi as $i => $value)
{
if($diferencia > 0)
{
$lineasi[$i]->neto += .01;
$diferencia--;
}
else if($diferencia < 0)
{
$lineasi[$i]->neto -= .01;
$diferencia++;
}
else
break;
}
}
if( !$this->floatcmp($this->totaliva, $t_iva) )
{
/*
* Sumamos o restamos un céntimo a los importes más altos
* hasta que desaparezca el descuadre
*/
$diferencia = round( ($this->totaliva-$t_iva) * 100 );
usort($lineasi, function($a, $b) {
if($a->totaliva == $b->totaliva)
{
return 0;
}
else if($this->total < 0)
{
return ($a->totaliva < $b->totaliva) ? -1 : 1;
}
else
{
return ($a->totaliva < $b->totaliva) ? 1 : -1;
}
});
foreach($lineasi as $i => $value)
{
if($diferencia > 0)
{
$lineasi[$i]->totaliva += .01;
$diferencia--;
}
else if($diferencia < 0)
{
$lineasi[$i]->totaliva -= .01;
$diferencia++;
}
else
break;
}
}
foreach($lineasi as $i => $value)
{
$lineasi[$i]->totallinea = $value->neto + $value->totaliva + $value->totalrecargo;
$lineasi[$i]->save();
}
}
}
}
return $lineasi;
}
public function get_asiento()
{
$asiento = new \asiento();
return $asiento->get($this->idasiento);
}
public function get_asiento_pago()
{
$asiento = new \asiento();
return $asiento->get($this->idasientop);
}
/**
* Devuelve un array con todas las facturas rectificativas de esta factura.
* @return \factura_proveedor
*/
public function get_rectificativas()
{
$devoluciones = array();
$data = $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfacturarect = ".$this->var2str($this->idfactura).";");
if($data)
{
foreach($data as $d)
{
$devoluciones[] = new \factura_proveedor($d);
}
}
return $devoluciones;
}
/**
* Devuelve la factura de compra con el id proporcionado.
* @param type $id
* @return boolean|\factura_proveedor
*/
public function get($id)
{
$fact = $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($id).";");
if($fact)
{
return new \factura_proveedor($fact[0]);
}
else
return FALSE;
}
public function get_by_codigo($cod)
{
$fact = $this->db->select("SELECT * FROM ".$this->table_name." WHERE codigo = ".$this->var2str($cod).";");
if($fact)
{
return new \factura_proveedor($fact[0]);
}
else
return FALSE;
}
public function exists()
{
if( is_null($this->idfactura) )
{
return FALSE;
}
else
return $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($this->idfactura).";");
}
/**
* Genera el número y código de la factura.
*/
public function new_codigo()
{
/// buscamos un hueco o el siguiente número disponible
$encontrado = FALSE;
$num = 1;
$sql = "SELECT ".$this->db->sql_to_int('numero')." as numero,fecha,hora FROM ".$this->table_name
." WHERE codejercicio = ".$this->var2str($this->codejercicio)
." AND codserie = ".$this->var2str($this->codserie)
." ORDER BY numero ASC;";
$data = $this->db->select($sql);
if($data)
{
foreach($data as $d)
{
if( intval($d['numero']) < $num )
{
/**
* El número de la factura es menor que el inicial.
* El usuario ha cambiado el número inicial después de hacer
* facturas.
*/
}
else if( intval($d['numero']) == $num )
{
/// el número es correcto, avanzamos
$num++;
}
else
{
/// Hemos encontrado un hueco
$encontrado = TRUE;
break;
}
}
}
if($encontrado)
{
$this->numero = $num;
}
else
{
$this->numero = $num;
/// nos guardamos la secuencia para abanq/eneboo
$sec = new \secuencia();
$sec = $sec->get_by_params2($this->codejercicio, $this->codserie, 'nfacturaprov');
if($sec)
{
if($sec->valorout <= $this->numero)
{
$sec->valorout = 1 + $this->numero;
$sec->save();
}
}
}
if(FS_NEW_CODIGO == 'eneboo')
{
$this->codigo = $this->codejercicio.sprintf('%02s', $this->codserie).sprintf('%06s', $this->numero);
}
else
{
$this->codigo = 'FAC'.$this->codejercicio.$this->codserie.$this->numero.'C';
}
}
/**
* Comprueba los datos de la factura, devuelve TRUE si está todo correcto
* @return boolean
*/
public function test()
{
$this->nombre = $this->no_html($this->nombre);
if($this->nombre == '')
{
$this->nombre = '-';
}
$this->numproveedor = $this->no_html($this->numproveedor);
$this->observaciones = $this->no_html($this->observaciones);
/**
* Usamos el euro como divisa puente a la hora de sumar, comparar
* o convertir cantidades en varias divisas. Por este motivo necesimos
* muchos decimales.
*/
$this->totaleuros = round($this->total / $this->tasaconv, 5);
if( $this->floatcmp($this->total, $this->neto+$this->totaliva-$this->totalirpf+$this->totalrecargo, FS_NF0, TRUE) )
{
return TRUE;
}
else
{
$this->new_error_msg("Error grave: El total está mal calculado. ¡Informa del error!");
return FALSE;
}
}
public function full_test($duplicados = TRUE)
{
$status = TRUE;
/// comprobamos la fecha de la factura
$ejercicio = new \ejercicio();
$eje0 = $ejercicio->get($this->codejercicio);
if($eje0)
{
if( strtotime($this->fecha) < strtotime($eje0->fechainicio) OR strtotime($this->fecha) > strtotime($eje0->fechafin) )
{
$status = FALSE;
$this->new_error_msg("La fecha de esta factura está fuera del rango del"
. " <a target='_blank' href='".$eje0->url()."'>ejercicio</a>.");
}
}
/// comprobamos las líneas
$neto = 0;
$iva = 0;
$irpf = 0;
$recargo = 0;
foreach($this->get_lineas() as $l)
{
if( !$l->test() )
{
$status = FALSE;
}
$neto += $l->pvptotal;
$iva += $l->pvptotal * $l->iva / 100;
$irpf += $l->pvptotal * $l->irpf / 100;
$recargo += $l->pvptotal * $l->recargo / 100;
}
$neto = round($neto, FS_NF0);
$iva = round($iva, FS_NF0);
$irpf = round($irpf, FS_NF0);
$recargo = round($recargo, FS_NF0);
$total = $neto + $iva - $irpf + $recargo;
if( !$this->floatcmp($this->neto, $neto, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor neto de la factura ".$this->codigo." incorrecto. Valor correcto: ".$neto);
$status = FALSE;
}
else if( !$this->floatcmp($this->totaliva, $iva, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor totaliva de la factura ".$this->codigo." incorrecto. Valor correcto: ".$iva);
$status = FALSE;
}
else if( !$this->floatcmp($this->totalirpf, $irpf, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor totalirpf de la factura ".$this->codigo." incorrecto. Valor correcto: ".$irpf);
$status = FALSE;
}
else if( !$this->floatcmp($this->totalrecargo, $recargo, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor totalrecargo de la factura ".$this->codigo." incorrecto. Valor correcto: ".$recargo);
$status = FALSE;
}
else if( !$this->floatcmp($this->total, $total, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor total de la factura ".$this->codigo." incorrecto. Valor correcto: ".$total);
$status = FALSE;
}
/// comprobamos las líneas de IVA
$this->get_lineas_iva();
$linea_iva = new \linea_iva_factura_proveedor();
if( !$linea_iva->factura_test($this->idfactura, $neto, $iva, $recargo) )
{
$status = FALSE;
}
/// comprobamos el asiento
if( isset($this->idasiento) )
{
$asiento = $this->get_asiento();
if($asiento)
{
if($asiento->tipodocumento != 'Factura de proveedor' OR $asiento->documento != $this->codigo)
{
$this->new_error_msg("Esta factura apunta a un <a href='".$this->asiento_url()."'>asiento incorrecto</a>.");
$status = FALSE;
}
else if($this->coddivisa == $this->default_items->coddivisa() AND (abs($asiento->importe) - abs($this->total+$this->totalirpf) >= .02) )
{
$this->new_error_msg("El importe del asiento es distinto al de la factura.");
$status = FALSE;
}
else
{
$asientop = $this->get_asiento_pago();
if($asientop)
{
if($this->totalirpf != 0)
{
/// excluimos la comprobación si la factura tiene IRPF
}
else if( !$this->floatcmp($asiento->importe, $asientop->importe) )
{
$this->new_error_msg('No coinciden los importes de los asientos.');
$status = FALSE;
}
}
}
}
else
{
$this->new_error_msg("Asiento no encontrado.");
$status = FALSE;
}
}
if($status AND $duplicados)
{
/// comprobamos si es un duplicado
$facturas = $this->db->select("SELECT * FROM ".$this->table_name." WHERE fecha = ".$this->var2str($this->fecha)
." AND codproveedor = ".$this->var2str($this->codproveedor)
." AND total = ".$this->var2str($this->total)
." AND codagente = ".$this->var2str($this->codagente)
." AND numproveedor = ".$this->var2str($this->numproveedor)
." AND observaciones = ".$this->var2str($this->observaciones)
." AND idfactura != ".$this->var2str($this->idfactura).";");
if($facturas)
{
foreach($facturas as $fac)
{
/// comprobamos las líneas
$aux = $this->db->select("SELECT referencia FROM lineasfacturasprov WHERE
idfactura = ".$this->var2str($this->idfactura)."
AND referencia NOT IN (SELECT referencia FROM lineasfacturasprov
WHERE idfactura = ".$this->var2str($fac['idfactura']).");");
if( !$aux )
{
$this->new_error_msg("Esta factura es un posible duplicado de
<a href='index.php?page=compras_factura&id=".$fac['idfactura']."'>esta otra</a>.
Si no lo es, para evitar este mensaje, simplemente modifica las observaciones.");
$status = FALSE;
}
}
}
}
return $status;
}
public function save()
{
if( $this->test() )
{
if( $this->exists() )
{
$sql = "UPDATE ".$this->table_name." SET codigo = ".$this->var2str($this->codigo)
.", total = ".$this->var2str($this->total)
.", neto = ".$this->var2str($this->neto)
.", cifnif = ".$this->var2str($this->cifnif)
.", pagada = ".$this->var2str($this->pagada)
.", anulada = ".$this->var2str($this->anulada)
.", observaciones = ".$this->var2str($this->observaciones)
.", codagente = ".$this->var2str($this->codagente)
.", codalmacen = ".$this->var2str($this->codalmacen)
.", irpf = ".$this->var2str($this->irpf)
.", totaleuros = ".$this->var2str($this->totaleuros)
.", nombre = ".$this->var2str($this->nombre)
.", codpago = ".$this->var2str($this->codpago)
.", codproveedor = ".$this->var2str($this->codproveedor)
.", idfacturarect = ".$this->var2str($this->idfacturarect)
.", numproveedor = ".$this->var2str($this->numproveedor)
.", codigorect = ".$this->var2str($this->codigorect)
.", codserie = ".$this->var2str($this->codserie)
.", idasiento = ".$this->var2str($this->idasiento)
.", idasientop = ".$this->var2str($this->idasientop)
.", totalirpf = ".$this->var2str($this->totalirpf)
.", totaliva = ".$this->var2str($this->totaliva)
.", coddivisa = ".$this->var2str($this->coddivisa)
.", numero = ".$this->var2str($this->numero)
.", codejercicio = ".$this->var2str($this->codejercicio)
.", tasaconv = ".$this->var2str($this->tasaconv)
.", totalrecargo = ".$this->var2str($this->totalrecargo)
.", fecha = ".$this->var2str($this->fecha)
.", hora = ".$this->var2str($this->hora)
.", numdocs = ".$this->var2str($this->numdocs)
." WHERE idfactura = ".$this->var2str($this->idfactura).";";
return $this->db->exec($sql);
}
else
{
$this->new_codigo();
$sql = "INSERT INTO ".$this->table_name." (codigo,total,neto,cifnif,pagada,anulada,observaciones,
codagente,codalmacen,irpf,totaleuros,nombre,codpago,codproveedor,idfacturarect,numproveedor,
codigorect,codserie,idasiento,idasientop,totalirpf,totaliva,coddivisa,numero,codejercicio,tasaconv,
totalrecargo,fecha,hora,numdocs) VALUES (".$this->var2str($this->codigo)
.",".$this->var2str($this->total)
.",".$this->var2str($this->neto)
.",".$this->var2str($this->cifnif)
.",".$this->var2str($this->pagada)
.",".$this->var2str($this->anulada)
.",".$this->var2str($this->observaciones)
.",".$this->var2str($this->codagente)
.",".$this->var2str($this->codalmacen)
.",".$this->var2str($this->irpf)
.",".$this->var2str($this->totaleuros)
.",".$this->var2str($this->nombre)
.",".$this->var2str($this->codpago)
.",".$this->var2str($this->codproveedor)
.",".$this->var2str($this->idfacturarect)
.",".$this->var2str($this->numproveedor)
.",".$this->var2str($this->codigorect)
.",".$this->var2str($this->codserie)
.",".$this->var2str($this->idasiento)
.",".$this->var2str($this->idasientop)
.",".$this->var2str($this->totalirpf)
.",".$this->var2str($this->totaliva)
.",".$this->var2str($this->coddivisa)
.",".$this->var2str($this->numero)
.",".$this->var2str($this->codejercicio)
.",".$this->var2str($this->tasaconv)
.",".$this->var2str($this->totalrecargo)
.",".$this->var2str($this->fecha)
.",".$this->var2str($this->hora)
.",".$this->var2str($this->numdocs).");";
if( $this->db->exec($sql) )
{
$this->idfactura = $this->db->lastval();
return TRUE;
}
else
return FALSE;
}
}
else
return FALSE;
}
/**
* Elimina la factura de la base de datos.
* @return boolean
*/
public function delete()
{
$bloquear = FALSE;
$eje0 = new \ejercicio();
$ejercicio = $eje0->get($this->codejercicio);
if($ejercicio)
{
if( $ejercicio->abierto() )
{
$reg0 = new \regularizacion_iva();
if( $reg0->get_fecha_inside($this->fecha) )
{
$this->new_error_msg('La factura se encuentra dentro de una regularización de '
.FS_IVA.'. No se puede eliminar.');
$bloquear = TRUE;
}
else
{
foreach($this->get_rectificativas() as $rect)
{
$this->new_error_msg('La factura ya tiene una rectificativa. No se puede eliminar.');
$bloquear = TRUE;
break;
}
}
}
else
{
$this->new_error_msg('El ejercicio '.$ejercicio->nombre.' está cerrado.');
$bloquear = TRUE;
}
}
/// desvincular albaranes asociados y eliminar factura
$sql = "UPDATE albaranesprov SET idfactura = NULL, ptefactura = TRUE WHERE idfactura = ".$this->var2str($this->idfactura).";"
. "DELETE FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($this->idfactura).";";
if($bloquear)
{
return FALSE;
}
else if( $this->db->exec($sql) )
{
if($this->idasiento)
{
/**
* Delegamos la eliminación del asiento en la clase correspondiente.
*/
$asiento = new \asiento();
$asi0 = $asiento->get($this->idasiento);
if($asi0)
{
$asi0->delete();
}
$asi1 = $asiento->get($this->idasientop);
if($asi1)
{
$asi1->delete();
}
}
$this->new_message(ucfirst(FS_FACTURA)." de compra ".$this->codigo." eliminada correctamente.");
return TRUE;
}
else
return FALSE;
}
/**
* Devuelve un array con las últimas facturas
* @param type $offset
* @param type $limit
* @param type $order
* @return \factura_proveedor
*/
public function all($offset = 0, $limit = FS_ITEM_LIMIT, $order = 'fecha DESC, codigo DESC')
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name." ORDER BY ".$order;
$data = $this->db->select_limit($sql, $limit, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas sin pagar.
* @param type $offset
* @param type $limit
* @param type $order
* @return \factura_proveedor
*/
public function all_sin_pagar($offset = 0, $limit = FS_ITEM_LIMIT, $order = 'fecha ASC, codigo ASC')
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name." WHERE pagada = false ORDER BY ".$order;
$data = $this->db->select_limit($sql, $limit, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas del agente/empleado
* @param type $codagente
* @param type $offset
* @return \factura_proveedor
*/
public function all_from_agente($codagente, $offset = 0)
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name.
" WHERE codagente = ".$this->var2str($codagente).
" ORDER BY fecha DESC, codigo DESC";
$data = $this->db->select_limit($sql, FS_ITEM_LIMIT, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas del proveedor
* @param type $codproveedor
* @param type $offset
* @return \factura_proveedor
*/
public function all_from_proveedor($codproveedor, $offset = 0)
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name.
" WHERE codproveedor = ".$this->var2str($codproveedor).
" ORDER BY fecha DESC, codigo DESC";
$data = $this->db->select_limit($sql, FS_ITEM_LIMIT, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas comprendidas entre $desde y $hasta
* @param type $desde
* @param type $hasta
* @param type $codserie
* @param type $codagente
* @param type $codproveedor
* @param type $estado
* @return \factura_proveedor
*/
public function all_desde($desde, $hasta, $codserie = FALSE, $codagente = FALSE, $codproveedor = FALSE, $estado = FALSE, $forma_pago = FALSE)
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name." WHERE fecha >= ".$this->var2str($desde)." AND fecha <= ".$this->var2str($hasta);
if($codserie)
{
$sql .= " AND codserie = ".$this->var2str($codserie);
}
if($codagente)
{
$sql .= " AND codagente = ".$this->var2str($codagente);
}
if($codproveedor)
{
$sql .= " AND codproveedor = ".$this->var2str($codproveedor);
}
if($estado)
{
if($estado == 'pagada')
{
$sql .= " AND pagada = true";
}
else
{
$sql .= " AND pagada = false";
}
}
if($forma_pago)
{
$sql .= " AND codpago = ".$this->var2str($forma_pago);
}
$sql .= " ORDER BY fecha ASC, codigo ASC;";
$data = $this->db->select($sql);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas coincidentes con $query
* @param type $query
* @param type $offset
* @return \factura_proveedor
*/
public function search($query, $offset = 0)
{
$faclist = array();
$query = mb_strtolower( $this->no_html($query), 'UTF8' );
$consulta = "SELECT * FROM ".$this->table_name." WHERE ";
if( is_numeric($query) )
{
$consulta .= "codigo LIKE '%".$query."%' OR numproveedor LIKE '%".$query
."%' OR observaciones LIKE '%".$query."%'";
}
else
{
$consulta .= "lower(codigo) LIKE '%".$query."%' OR lower(numproveedor) LIKE '%".$query."%' "
. "OR lower(observaciones) LIKE '%".str_replace(' ', '%', $query)."%'";
}
$consulta .= " ORDER BY fecha DESC, codigo DESC";
$data = $this->db->select_limit($consulta, FS_ITEM_LIMIT, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
public function cron_job()
{
}
}
| KalimochoAz/facturacion_base | model/core/factura_proveedor.php | PHP | lgpl-3.0 | 40,486 |
//QPen QPen.new();
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
KQPen *ret_v = new KQPen();
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
/*
//QPen QPen.new(int style);
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[1]);
KQPen *ret_v = new KQPen(style);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
*/
/*
//QPen QPen.new(QColor color);
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
const QColor color = *RawPtr_to(const QColor *, sfp[1]);
KQPen *ret_v = new KQPen(color);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
*/
/*
//QPen QPen.new(QBrush brush, float width, int style, int cap, int join);
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
const QBrush brush = *RawPtr_to(const QBrush *, sfp[1]);
qreal width = Float_to(qreal, sfp[2]);
Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[3]);
Qt::PenCapStyle cap = Int_to(Qt::PenCapStyle, sfp[4]);
Qt::PenJoinStyle join = Int_to(Qt::PenJoinStyle, sfp[5]);
KQPen *ret_v = new KQPen(brush, width, style, cap, join);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
*/
/*
//QPen QPen.new(QPen pen);
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
const QPen pen = *RawPtr_to(const QPen *, sfp[1]);
KQPen *ret_v = new KQPen(pen);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
*/
//QBrush QPen.getBrush();
KMETHOD QPen_getBrush(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
QBrush ret_v = qp->brush();
QBrush *ret_v_ = new QBrush(ret_v);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL);
RETURN_(rptr);
} else {
RETURN_(KNH_NULL);
}
}
//int QPen.getCapStyle();
KMETHOD QPen_getCapStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenCapStyle ret_v = qp->capStyle();
RETURNi_(ret_v);
} else {
RETURNi_(0);
}
}
//QColor QPen.getColor();
KMETHOD QPen_getColor(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
QColor ret_v = qp->color();
QColor *ret_v_ = new QColor(ret_v);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL);
RETURN_(rptr);
} else {
RETURN_(KNH_NULL);
}
}
//float QPen.dashOffset();
KMETHOD QPen_dashOffset(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal ret_v = qp->dashOffset();
RETURNf_(ret_v);
} else {
RETURNf_(0.0f);
}
}
//boolean QPen.isCosmetic();
KMETHOD QPen_isCosmetic(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
bool ret_v = qp->isCosmetic();
RETURNb_(ret_v);
} else {
RETURNb_(false);
}
}
//boolean QPen.isSolid();
KMETHOD QPen_isSolid(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
bool ret_v = qp->isSolid();
RETURNb_(ret_v);
} else {
RETURNb_(false);
}
}
//int QPen.getJoinStyle();
KMETHOD QPen_getJoinStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenJoinStyle ret_v = qp->joinStyle();
RETURNi_(ret_v);
} else {
RETURNi_(0);
}
}
//float QPen.getMiterLimit();
KMETHOD QPen_getMiterLimit(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal ret_v = qp->miterLimit();
RETURNf_(ret_v);
} else {
RETURNf_(0.0f);
}
}
//void QPen.setBrush(QBrush brush);
KMETHOD QPen_setBrush(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
const QBrush brush = *RawPtr_to(const QBrush *, sfp[1]);
qp->setBrush(brush);
}
RETURNvoid_();
}
//void QPen.setCapStyle(int style);
KMETHOD QPen_setCapStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenCapStyle style = Int_to(Qt::PenCapStyle, sfp[1]);
qp->setCapStyle(style);
}
RETURNvoid_();
}
//void QPen.setColor(QColor color);
KMETHOD QPen_setColor(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
const QColor color = *RawPtr_to(const QColor *, sfp[1]);
qp->setColor(color);
}
RETURNvoid_();
}
//void QPen.setCosmetic(boolean cosmetic);
KMETHOD QPen_setCosmetic(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
bool cosmetic = Boolean_to(bool, sfp[1]);
qp->setCosmetic(cosmetic);
}
RETURNvoid_();
}
//void QPen.setDashOffset(float offset);
KMETHOD QPen_setDashOffset(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal offset = Float_to(qreal, sfp[1]);
qp->setDashOffset(offset);
}
RETURNvoid_();
}
//void QPen.setJoinStyle(int style);
KMETHOD QPen_setJoinStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenJoinStyle style = Int_to(Qt::PenJoinStyle, sfp[1]);
qp->setJoinStyle(style);
}
RETURNvoid_();
}
//void QPen.setMiterLimit(float limit);
KMETHOD QPen_setMiterLimit(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal limit = Float_to(qreal, sfp[1]);
qp->setMiterLimit(limit);
}
RETURNvoid_();
}
//void QPen.setStyle(int style);
KMETHOD QPen_setStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[1]);
qp->setStyle(style);
}
RETURNvoid_();
}
//void QPen.setWidth(int width);
KMETHOD QPen_setWidth(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
int width = Int_to(int, sfp[1]);
qp->setWidth(width);
}
RETURNvoid_();
}
//void QPen.setWidthF(float width);
KMETHOD QPen_setWidthF(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal width = Float_to(qreal, sfp[1]);
qp->setWidthF(width);
}
RETURNvoid_();
}
//int QPen.getStyle();
KMETHOD QPen_getStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenStyle ret_v = qp->style();
RETURNi_(ret_v);
} else {
RETURNi_(0);
}
}
//int QPen.getWidth();
KMETHOD QPen_getWidth(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
int ret_v = qp->width();
RETURNi_(ret_v);
} else {
RETURNi_(0);
}
}
//float QPen.getWidthF();
KMETHOD QPen_getWidthF(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal ret_v = qp->widthF();
RETURNf_(ret_v);
} else {
RETURNf_(0.0f);
}
}
//Array<String> QPen.parents();
KMETHOD QPen_parents(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen *qp = RawPtr_to(QPen*, sfp[0]);
if (qp != NULL) {
int size = 10;
knh_Array_t *a = new_Array0(ctx, size);
const knh_ClassTBL_t *ct = sfp[0].p->h.cTBL;
while(ct->supcid != CLASS_Object) {
ct = ct->supTBL;
knh_Array_add(ctx, a, (knh_Object_t *)ct->lname);
}
RETURN_(a);
} else {
RETURN_(KNH_NULL);
}
}
DummyQPen::DummyQPen()
{
CTX lctx = knh_getCurrentContext();
(void)lctx;
self = NULL;
event_map = new map<string, knh_Func_t *>();
slot_map = new map<string, knh_Func_t *>();
}
DummyQPen::~DummyQPen()
{
delete event_map;
delete slot_map;
event_map = NULL;
slot_map = NULL;
}
void DummyQPen::setSelf(knh_RawPtr_t *ptr)
{
DummyQPen::self = ptr;
}
bool DummyQPen::eventDispatcher(QEvent *event)
{
bool ret = true;
switch (event->type()) {
default:
ret = false;
break;
}
return ret;
}
bool DummyQPen::addEvent(knh_Func_t *callback_func, string str)
{
std::map<string, knh_Func_t*>::iterator itr;// = DummyQPen::event_map->bigin();
if ((itr = DummyQPen::event_map->find(str)) == DummyQPen::event_map->end()) {
bool ret = false;
return ret;
} else {
KNH_INITv((*event_map)[str], callback_func);
return true;
}
}
bool DummyQPen::signalConnect(knh_Func_t *callback_func, string str)
{
std::map<string, knh_Func_t*>::iterator itr;// = DummyQPen::slot_map->bigin();
if ((itr = DummyQPen::slot_map->find(str)) == DummyQPen::slot_map->end()) {
bool ret = false;
return ret;
} else {
KNH_INITv((*slot_map)[str], callback_func);
return true;
}
}
knh_Object_t** DummyQPen::reftrace(CTX ctx, knh_RawPtr_t *p FTRARG)
{
(void)ctx; (void)p; (void)tail_;
// fprintf(stderr, "DummyQPen::reftrace p->rawptr=[%p]\n", p->rawptr);
return tail_;
}
void DummyQPen::connection(QObject *o)
{
QPen *p = dynamic_cast<QPen*>(o);
if (p != NULL) {
}
}
KQPen::KQPen() : QPen()
{
magic_num = G_MAGIC_NUM;
self = NULL;
dummy = new DummyQPen();
}
KQPen::~KQPen()
{
delete dummy;
dummy = NULL;
}
KMETHOD QPen_addEvent(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
KQPen *qp = RawPtr_to(KQPen *, sfp[0]);
const char *event_name = String_to(const char *, sfp[1]);
knh_Func_t *callback_func = sfp[2].fo;
if (qp != NULL) {
// if (qp->event_map->find(event_name) == qp->event_map->end()) {
// fprintf(stderr, "WARNING:[QPen]unknown event name [%s]\n", event_name);
// return;
// }
string str = string(event_name);
// KNH_INITv((*(qp->event_map))[event_name], callback_func);
if (!qp->dummy->addEvent(callback_func, str)) {
fprintf(stderr, "WARNING:[QPen]unknown event name [%s]\n", event_name);
return;
}
}
RETURNvoid_();
}
KMETHOD QPen_signalConnect(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
KQPen *qp = RawPtr_to(KQPen *, sfp[0]);
const char *signal_name = String_to(const char *, sfp[1]);
knh_Func_t *callback_func = sfp[2].fo;
if (qp != NULL) {
// if (qp->slot_map->find(signal_name) == qp->slot_map->end()) {
// fprintf(stderr, "WARNING:[QPen]unknown signal name [%s]\n", signal_name);
// return;
// }
string str = string(signal_name);
// KNH_INITv((*(qp->slot_map))[signal_name], callback_func);
if (!qp->dummy->signalConnect(callback_func, str)) {
fprintf(stderr, "WARNING:[QPen]unknown signal name [%s]\n", signal_name);
return;
}
}
RETURNvoid_();
}
static void QPen_free(CTX ctx, knh_RawPtr_t *p)
{
(void)ctx;
if (!exec_flag) return;
if (p->rawptr != NULL) {
KQPen *qp = (KQPen *)p->rawptr;
if (qp->magic_num == G_MAGIC_NUM) {
delete qp;
p->rawptr = NULL;
} else {
delete (QPen*)qp;
p->rawptr = NULL;
}
}
}
static void QPen_reftrace(CTX ctx, knh_RawPtr_t *p FTRARG)
{
if (p->rawptr != NULL) {
// KQPen *qp = (KQPen *)p->rawptr;
KQPen *qp = static_cast<KQPen*>(p->rawptr);
qp->dummy->reftrace(ctx, p, tail_);
}
}
static int QPen_compareTo(knh_RawPtr_t *p1, knh_RawPtr_t *p2)
{
return (*static_cast<QPen*>(p1->rawptr) == *static_cast<QPen*>(p2->rawptr) ? 0 : 1);
}
void KQPen::setSelf(knh_RawPtr_t *ptr)
{
self = ptr;
dummy->setSelf(ptr);
}
DEFAPI(void) defQPen(CTX ctx, knh_class_t cid, knh_ClassDef_t *cdef)
{
(void)ctx; (void) cid;
cdef->name = "QPen";
cdef->free = QPen_free;
cdef->reftrace = QPen_reftrace;
cdef->compareTo = QPen_compareTo;
}
| imasahiro/konohascript | package/konoha.qt4/src/KQPen.cpp | C++ | lgpl-3.0 | 11,262 |
namespace TireDataAnalyzer.UserControls.FittingWizard
{
partial class FittingWizard
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// FittingWizard
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1023, 684);
this.Name = "FittingWizard";
this.Text = "FittingWizard";
this.Load += new System.EventHandler(this.FittingWizard_Load);
this.ResumeLayout(false);
}
#endregion
}
} | GRAM-shuzo/TireDataAnalyzer | TireDataAnalyzer/TireDataAnalyzer/UserControls/FittingWizard/FittingWizard.Designer.cs | C# | lgpl-3.0 | 1,503 |
/*
* HA-JDBC: High-Availability JDBC
* Copyright (C) 2013 Paul Ferraro
*
* 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 net.sf.hajdbc.sql;
import java.sql.Ref;
import java.sql.SQLException;
import java.util.Map;
import net.sf.hajdbc.Database;
import net.sf.hajdbc.invocation.Invoker;
/**
*
* @author Paul Ferraro
*/
public class RefProxyFactoryFactory<Z, D extends Database<Z>, P> implements ProxyFactoryFactory<Z, D, P, SQLException, Ref, SQLException>
{
private final boolean locatorsUpdateCopy;
public RefProxyFactoryFactory(boolean locatorsUpdateCopy)
{
this.locatorsUpdateCopy = locatorsUpdateCopy;
}
@Override
public ProxyFactory<Z, D, Ref, SQLException> createProxyFactory(P parentProxy, ProxyFactory<Z, D, P, SQLException> parent, Invoker<Z, D, P, Ref, SQLException> invoker, Map<D, Ref> structs)
{
return new RefProxyFactory<>(parentProxy, parent, invoker, structs, this.locatorsUpdateCopy);
}
}
| ha-jdbc/ha-jdbc | core/src/main/java/net/sf/hajdbc/sql/RefProxyFactoryFactory.java | Java | lgpl-3.0 | 1,563 |
<?php
namespace Polygen\Grammar;
use Polygen\Grammar\Interfaces\DeclarationInterface;
use Polygen\Grammar\Interfaces\Node;
use Polygen\Language\AbstractSyntaxWalker;
use Webmozart\Assert\Assert;
/**
* Definition Polygen node
*/
class Definition implements DeclarationInterface, Node
{
/**
* @var string
*/
private $name;
/**
* @var ProductionCollection
*/
private $productions;
/**
* @param string $name
*/
public function __construct($name, ProductionCollection $productions)
{
Assert::string($name);
$this->name = $name;
$this->productions = $productions;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Allows a node to pass itself back to the walker using the method most appropriate to walk on it.
*
* @param mixed|null $context Data that you want to be passed back to the walker.
* @return mixed|null
*/
public function traverse(AbstractSyntaxWalker $walker, $context = null)
{
return $walker->walkDefinition($this, $context);
}
/**
* @deprecated
* @return Production[]
*/
public function getProductions()
{
return $this->productions->getProductions();
}
/**
* @return \Polygen\Grammar\ProductionCollection
*/
public function getProductionSet()
{
return $this->productions;
}
/**
* Returns a new instance of this object with the same properties, but with the specified productions.
*
* @return static
*/
public function withProductions(ProductionCollection $productions)
{
return new static($this->name, $productions);
}
}
| RBastianini/polygen-php | src/Grammar/Definition.php | PHP | lgpl-3.0 | 1,761 |
#!/usr/bin/env python
#
# Copyright (C) 2015 Jonathan Racicot
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http:#www.gnu.org/licenses/>.
#
# You are free to use and modify this code for your own software
# as long as you retain information about the original author
# in your code as shown below.
#
# <author>Jonathan Racicot</author>
# <email>infectedpacket@gmail.com</email>
# <date>2015-03-26</date>
# <url>https://github.com/infectedpacket</url>
#//////////////////////////////////////////////////////////
# Program Information
#
PROGRAM_NAME = "vmfcat"
PROGRAM_DESC = ""
PROGRAM_USAGE = "%(prog)s [-i] [-h|--help] (OPTIONS)"
__version_info__ = ('0','1','0')
__version__ = '.'.join(__version_info__)
#//////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////
# Imports Statements
import re
import sys
import json
import argparse
import traceback
from Factory import *
from Logger import *
from bitstring import *
#//////////////////////////////////////////////////////////
# =============================================================================
# Parameter information
class Params:
parameters = {
"debug" : {
"cmd" : "debug",
"help" : "Enables debug mode.",
"choices" : [True, False]
},
"data" : {
"cmd" : "data",
"help" : "Specifies a file containing data to be included in the VMF message.",
"choices" : []
},
"vmfversion" : {
"cmd" : "vmfversion",
"help" :
"""Field representing the version of the MIL-STD-2045-47001 header being used for the message.""",
"choices" : ["std47001", "std47001b","std47001c","std47001d","std47001d_change"]
},
"compress" : {
"cmd" : "compress",
"help" :
"""This field represents whether the message or messages contained in the User Data portion of the Application PDU have been UNIX compressed or compressed using GZIP.""",
"choices" : ["unix", "gzip"]
},
"headersize" : {
"cmd" : "headersize",
"help" :
"""Indicates the size in octets of the header""",
"choices" : []
},
"originator_urn" : {
"cmd" : "originator_urn",
"help" : """24-bit code used to uniquely identify friendly military units, broadcast networks and multicast groups.""",
"choices" : []
},
"originator_unitname" : {
"cmd" : "originator_unitname",
"help" : """Specify the name of the unit sending the message.""",
"choices" : []
},
"rcpt_urns" : {
"cmd" : "rcpt_urns",
"help" : """List of 24-bit codes used to uniquely identify friendly units.""",
"choices" : []
},
"rcpt_unitnames" : {
"cmd" : "rcpt_unitnames",
"help" : """ List of variable size fields of character-coded identifiers for friendly units. """,
"choices" : []
},
"info_urns" : {
"cmd" : "info_urns",
"help" : """List of 24-bit codes used to uniquely identify friendly units.""",
"choices" : []
},
"info_unitnames" : {
"cmd" : "info_unitnames",
"help" : """ List of variable size fields of character-coded identifiers for friendly units. """,
"choices" : []
},
"umf" : {
"cmd" : "umf",
"choices" : ["link16", "binary", "vmf", "nitfs", "rdm", "usmtf", "doi103", "xml-mtf", "xml-vmf"],
"help" : """ Indicates the format of the message contained in the user data field."""
},
"messagevers" : {
"cmd" : "messagevers",
"choices" : [],
"help" : """Represents the version of the message standard contained in the user data field."""
},
"fad" : {
"cmd" : "fad",
"choices" : ["netcon", "geninfo", "firesp", "airops", "intops", "landops","marops", "css", "specialops", "jtfopsctl", "airdef"],
"help" : "Identifies the functional area of a specific VMF message using code words."
},
"msgnumber" : {
"cmd" : "msgnumber",
"choices" : [],
"help" : """Represents the number that identifies a specific VMF message within a functional area."""
},
"msgsubtype" : {
"cmd" : "msgsubtype",
"choices" : [],
"help" : """Represents a specific case within a VMF message, which depends on the UMF, FAD and message number."""
},
"filename" : {
"cmd" : "filename",
"choices" : [],
"help" : """Indicates the name of the computer file or data block contained in the User Data portion of the application PDU."""
},
"msgsize" : {
"cmd" : "msgsize",
"choices" : [],
"help" : """Indicates the size(in bytes) of the associated message within the User Data field."""
},
"opind" : {
"cmd" : "opind",
"choices" : ["op", "ex", "sim", "test"],
"help" : "Indicates the operational function of the message."
},
"retransmission" : {
"cmd" : "retransmission",
"choices" : [1, 0],
"help" : """Indicates whether a message is a retransmission."""
},
"msgprecedence" : {
"cmd" : "msgprecedence",
"choices" : ["reserved", "critic", "flashover", "flash", "imm", "pri", "routine"],
"help" : """Indicates relative precedence of a message."""
},
"classification" : {
"cmd" : "classification",
"choices" : ["unclass", "conf", "secret", "topsecret"],
"help" : """Security classification of the message."""
},
"releasemark" : {
"cmd" : "releasemark",
"choices" : [],
"help" : """Support the exchange of a list of up to 16 country codes with which the message can be release."""
},
"originatordtg" : {
"cmd" : "originatordtg",
"choices" : [],
"help" : """ Contains the date and time in Zulu Time that the message was prepared."""
},
"perishdtg" : {
"cmd" : "perishdtg",
"choices" : [],
"help" : """Provides the latest time the message is still of value."""
},
"ackmachine" : {
"cmd" : "ackmachine",
"choices" : [1, 0],
"help" : """Indicates whether the originator of a machine requires a machine acknowledgement for the message."""
},
"ackop" : {
"cmd" : "ackop",
"choices" : [1, 0],
"help" : """Indicates whether the originator of the message requires an acknowledgement for the message from the recipient."""
},
"ackdtg" : {
"cmd" : "ackdtg",
"choices" : [],
"help" : """Provides the date and time of the original message that is being acknowledged."""
},
"rc" : {
"cmd" : "rc",
"choices" : ["mr", "cantpro", "oprack", "wilco", "havco", "cantco", "undef"],
"help" : """Codeword representing the Receipt/Compliance answer to the acknowledgement request."""
},
"cantpro" : {
"cmd" : "cantpro",
"choices" : [],
"help" : """Indicates the reason that a particular message cannot be processed by a recipient or information address."""
},
"reply" : {
"cmd" : "reply",
"choices" : [1, 0],
"help" : """Indicates whether the originator of the message requires an operator reply to the message."""
},
"cantco" : {
"cmd" : "cantco",
"choices" : ["comm", "ammo", "pers", "fuel", "env", "equip", "tac", "other"],
"help" : """Indicates the reason that a particular recipient cannot comply with a particular message."""
},
"replyamp" : {
"cmd" : "replyamp",
"choices" : [],
"help" : """Provide textual data an amplification of the recipient's reply to a message."""
},
"ref_urn" : {
"cmd" : "ref_urn",
"choices" : [],
"help" : """URN of the reference message."""
},
"ref_unitname" : {
"cmd" : "ref_unitname",
"choices" : [],
"help" : """Name of the unit of the reference message."""
},
"refdtg" : {
"cmd" : "refdtg",
"choices" : [],
"help" : """Date time group of the reference message."""
},
"secparam" : {
"cmd" : "secparam",
"choices" : ['auth', 'undef'],
"help" : """Indicate the identities of the parameters and algorithms that enable security processing."""
},
"keymatlen" : {
"cmd" : "keymatlen",
"choices" : [],
"help" : """Defines the size in octets of the Keying Material ID field."""
},
"keymatid" : {
"cmd" : "keymatid",
"choices" : [],
"help" : """Identifies the key which was used for encryption."""
},
"crypto_init_len" : {
"cmd" : "crypto_init_len",
"choices" : [],
"help" : """Defines the size, in 64-bit blocks, of the Crypto Initialization field."""
},
"crypto_init" : {
"cmd" : "crypto_init",
"choices" : [],
"help" : """Sequence of bits used by the originator and recipient to initialize the encryption/decryption process."""
},
"keytok_len" : {
"cmd" : "keytok_len",
"choices" : [],
"help" : """Defines the size, in 64-bit blocks, of the Key Token field."""
},
"keytok" : {
"cmd" : "keytok",
"choices" : [],
"help" : """Contains information enabling each member of each address group to decrypt the user data associated with this message header."""
},
"autha-len" : {
"cmd" : "autha-len",
"choices" : [],
"help" : """Defines the size, in 64-bit blocks, of the Authentification Data (A) field."""
},
"authb-len" : {
"cmd" : "authb-len",
"choices" : [],
"help" : """Defines the size, in 64-bit blocks, of the Authentification Data (B) field."""
},
"autha" : {
"cmd" : "autha",
"choices" : [],
"help" : """Data created by the originator to provide both connectionless integrity and data origin authentication (A)."""
},
"authb" : {
"cmd" : "authb",
"choices" : [],
"help" : """Data created by the originator to provide both connectionless integrity and data origin authentication (B)."""
},
"acksigned" : {
"cmd" : "acksigned",
"choices" : [],
"help" : """Indicates whether the originator of a message requires a signed response from the recipient."""
},
"pad_len" : {
"cmd" : "pad_len",
"choices" : [],
"help" : """Defines the size, in octets, of the message security padding field."""
},
"padding" : {
"cmd" : "padding",
"choices" : [],
"help" : """Necessary for a block encryption algorithm so the content of the message is a multiple of the encryption block length."""
},
}
#//////////////////////////////////////////////////////////////////////////////
# Argument Parser Declaration
#
usage = "%(prog)s [options] data"
parser = argparse.ArgumentParser(usage=usage,
prog="vmfcat",
version="%(prog)s "+__version__,
description="Allows crafting of Variable Message Format (VMF) messages.")
io_options = parser.add_argument_group(
"Input/Output Options", "Types of I/O supported.")
io_options.add_argument("-d", "--debug",
dest=Params.parameters['debug']['cmd'],
action="store_true",
help=Params.parameters['debug']['help'])
io_options.add_argument("-i", "--interactive",
dest="interactive",
action="store_true",
help="Create and send VMF messages interactively.")
io_options.add_argument("-of", "--ofile",
dest="outputfile",
nargs="?",
type=argparse.FileType('w'),
default=sys.stdout,
help="File to output the results. STDOUT by default.")
io_options.add_argument("--data",
dest=Params.parameters['data']['cmd'],
help=Params.parameters['data']['help'])
# =============================================================================
# Application Header Arguments
header_options = parser.add_argument_group(
"Application Header", "Flags and Fields of the application header.")
header_options.add_argument("--vmf-version",
dest=Params.parameters["vmfversion"]["cmd"],
action="store",
choices=Params.parameters["vmfversion"]["choices"],
default="std47001c",
help=Params.parameters["vmfversion"]["help"])
header_options.add_argument("--compress",
dest=Params.parameters["compress"]["cmd"],
action="store",
choices=Params.parameters["compress"]["choices"],
help=Params.parameters["compress"]["help"])
header_options.add_argument("--header-size",
dest=Params.parameters["headersize"]["cmd"],
action="store",
type=int,
help=Params.parameters["headersize"]["help"])
# =============================================================================
# Originator Address Group Arguments
orig_addr_options = parser.add_argument_group(
"Originator Address Group", "Fields of the originator address group.")
orig_addr_options.add_argument("--orig-urn",
dest=Params.parameters["originator_urn"]["cmd"],
metavar="URN",
type=int,
action="store",
help=Params.parameters["originator_urn"]["help"])
orig_addr_options.add_argument("--orig-unit",
dest=Params.parameters["originator_unitname"]["cmd"],
metavar="STRING",
action="store",
help=Params.parameters["originator_unitname"]["help"])
# =============================================================================
# =============================================================================
# Recipient Address Group Arguments
recp_addr_options = parser.add_argument_group(
"Recipient Address Group", "Fields of the recipient address group.")
recp_addr_options.add_argument("--rcpt-urns",
nargs="+",
dest=Params.parameters['rcpt_urns']['cmd'],
metavar="URNs",
help=Params.parameters['rcpt_urns']['help'])
recp_addr_options.add_argument("--rcpt-unitnames",
nargs="+",
dest=Params.parameters['rcpt_unitnames']['cmd'],
metavar="UNITNAMES",
help=Params.parameters['rcpt_unitnames']['help'])
# =============================================================================
# =============================================================================
# Information Address Group Arguments
info_addr_options = parser.add_argument_group(
"Information Address Group", "Fields of the information address group.")
info_addr_options.add_argument("--info-urns",
dest=Params.parameters["info_urns"]["cmd"],
metavar="URNs",
nargs="+",
action="store",
help=Params.parameters["info_urns"]["help"])
info_addr_options.add_argument("--info-units",
dest="info_unitnames",
metavar="UNITNAMES",
action="store",
help="Specify the name of the unit of the reference message.")
# =============================================================================
# =============================================================================
# Message Handling Group Arguments
msg_handling_options = parser.add_argument_group(
"Message Handling Group", "Fields of the message handling group.")
msg_handling_options.add_argument("--umf",
dest=Params.parameters["umf"]["cmd"],
action="store",
choices=Params.parameters["umf"]["choices"],
help=Params.parameters["umf"]["help"])
msg_handling_options.add_argument("--msg-version",
dest=Params.parameters["messagevers"]["cmd"],
action="store",
metavar="VERSION",
type=int,
help=Params.parameters["messagevers"]["help"])
msg_handling_options.add_argument("--fad",
dest=Params.parameters["fad"]["cmd"],
action="store",
choices=Params.parameters["fad"]["choices"],
help=Params.parameters["fad"]["help"])
msg_handling_options.add_argument("--msg-number",
dest=Params.parameters["msgnumber"]["cmd"],
action="store",
type=int,
metavar="1-127",
help=Params.parameters["msgnumber"]["help"])
msg_handling_options.add_argument("--msg-subtype",
dest=Params.parameters["msgsubtype"]["cmd"],
action="store",
type=int,
metavar="1-127",
help=Params.parameters["msgsubtype"]["help"])
msg_handling_options.add_argument("--filename",
dest=Params.parameters["filename"]["cmd"],
action="store",
help=Params.parameters["filename"]["help"])
msg_handling_options.add_argument("--msg-size",
dest=Params.parameters["msgsize"]["cmd"],
action="store",
type=int,
metavar="SIZE",
help=Params.parameters["msgsize"]["help"])
msg_handling_options.add_argument("--opind",
dest=Params.parameters["opind"]["cmd"],
action="store",
choices=Params.parameters["opind"]["choices"],
help=Params.parameters["opind"]["help"])
msg_handling_options.add_argument("--retrans",
dest=Params.parameters["retransmission"]["cmd"],
action="store_true",
help=Params.parameters["retransmission"]["help"])
msg_handling_options.add_argument("--msg-prec",
dest=Params.parameters["msgprecedence"]["cmd"],
action="store",
choices=Params.parameters["msgprecedence"]["choices"],
help=Params.parameters["msgprecedence"]["help"])
msg_handling_options.add_argument("--class",
dest=Params.parameters["classification"]["cmd"],
action="store",
nargs="+",
choices=Params.parameters["classification"]["choices"],
help=Params.parameters["classification"]["cmd"])
msg_handling_options.add_argument("--release",
dest=Params.parameters["releasemark"]["cmd"],
action="store",
metavar="COUNTRIES",
help=Params.parameters["releasemark"]["help"])
msg_handling_options.add_argument("--orig-dtg",
dest=Params.parameters["originatordtg"]["cmd"],
action="store",
metavar="YYYY-MM-DD HH:mm[:ss] [extension]",
help=Params.parameters["originatordtg"]["cmd"])
msg_handling_options.add_argument("--perish-dtg",
dest=Params.parameters["perishdtg"]["cmd"],
action="store",
metavar="YYYY-MM-DD HH:mm[:ss]",
help=Params.parameters["perishdtg"]["cmd"])
# =====================================================================================
# =====================================================================================
# Acknowledge Request Group Arguments
ack_options = parser.add_argument_group(
"Acknowledgement Request Group", "Options to request acknowledgement and replies.")
ack_options.add_argument("--ack-machine",
dest=Params.parameters["ackmachine"]["cmd"],
action="store_true",
help=Params.parameters["ackmachine"]["help"])
ack_options.add_argument("--ack-op",
dest=Params.parameters["ackop"]["cmd"],
action="store_true",
help=Params.parameters["ackop"]["help"])
ack_options.add_argument("--reply",
dest=Params.parameters["reply"]["cmd"],
action="store_true",
help=Params.parameters["reply"]["help"])
# =====================================================================================
# =====================================================================================
# Response Data Group Arguments
#
resp_options = parser.add_argument_group(
"Response Data Options", "Fields for the response data group.")
resp_options.add_argument("--ack-dtg",
dest=Params.parameters["ackdtg"]["cmd"],
help=Params.parameters["ackdtg"]["help"],
action="store",
metavar="YYYY-MM-DD HH:mm[:ss] [extension]")
resp_options.add_argument("--rc",
dest=Params.parameters["rc"]["cmd"],
help=Params.parameters["rc"]["help"],
choices=Params.parameters["rc"]["choices"],
action="store")
resp_options.add_argument("--cantpro",
dest=Params.parameters["cantpro"]["cmd"],
help=Params.parameters["cantpro"]["help"],
action="store",
type=int,
metavar="1-32")
resp_options.add_argument("--cantco",
dest=Params.parameters["cantco"]["cmd"],
help=Params.parameters["cantco"]["help"],
choices=Params.parameters["cantco"]["choices"],
action="store")
resp_options.add_argument("--reply-amp",
dest=Params.parameters["replyamp"]["cmd"],
help=Params.parameters["replyamp"]["help"],
action="store")
# =====================================================================================
# =====================================================================================
# Reference Message Data Group Arguments
#
ref_msg_options = parser.add_argument_group(
"Reference Message Data Group", "Fields of the reference message data group.")
ref_msg_options.add_argument("--ref-urn",
dest=Params.parameters["ref_urn"]["cmd"],
help=Params.parameters["ref_urn"]["help"],
metavar="URN",
action="store")
ref_msg_options.add_argument("--ref-unit",
dest=Params.parameters["ref_unitname"]["cmd"],
help=Params.parameters["ref_unitname"]["help"],
metavar="STRING",
action="store")
ref_msg_options.add_argument("--ref-dtg",
dest=Params.parameters["refdtg"]["cmd"],
help=Params.parameters["refdtg"]["help"],
action="store",
metavar="YYYY-MM-DD HH:mm[:ss] [extension]")
# =====================================================================================
# =====================================================================================
# Message Security Data Group Arguments
#
msg_sec_grp = parser.add_argument_group(
"Message Security Group", "Fields of the message security group.")
msg_sec_grp.add_argument("--sec-param",
dest=Params.parameters["secparam"]["cmd"],
help=Params.parameters["secparam"]["help"],
choices=Params.parameters["secparam"]["choices"],
action="store")
msg_sec_grp.add_argument("--keymat-len",
dest=Params.parameters["keymatlen"]["cmd"],
help=Params.parameters["keymatlen"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--keymat-id",
dest=Params.parameters["keymatid"]["cmd"],
help=Params.parameters["keymatid"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--crypto-init-len",
dest=Params.parameters["crypto_init_len"]["cmd"],
help=Params.parameters["crypto_init_len"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--crypto-init",
dest=Params.parameters["crypto_init"]["cmd"],
help=Params.parameters["crypto_init"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--keytok-len",
dest=Params.parameters["keytok_len"]["cmd"],
help=Params.parameters["keytok_len"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--keytok",
dest=Params.parameters["keytok"]["cmd"],
help=Params.parameters["keytok"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--autha-len",
dest=Params.parameters["autha-len"]["cmd"],
help=Params.parameters["autha-len"]["help"],
action="store",
type=int,
metavar="LENGTH")
msg_sec_grp.add_argument("--authb-len",
dest=Params.parameters["authb-len"]["cmd"],
help=Params.parameters["authb-len"]["help"],
action="store",
type=int,
metavar="LENGTH")
msg_sec_grp.add_argument("--autha",
dest=Params.parameters["autha"]["cmd"],
help=Params.parameters["autha"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--authb",
dest=Params.parameters["authb"]["cmd"],
help=Params.parameters["authb"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--ack-signed",
dest=Params.parameters["acksigned"]["cmd"],
help=Params.parameters["acksigned"]["help"],
action="store_true")
msg_sec_grp.add_argument("--pad-len",
dest=Params.parameters["pad_len"]["cmd"],
help=Params.parameters["pad_len"]["help"],
action="store",
type=int,
metavar="LENGTH")
msg_sec_grp.add_argument("--padding",
dest=Params.parameters["padding"]["cmd"],
help=Params.parameters["padding"]["help"],
action="store",
type=int)
# =============================================================================
#//////////////////////////////////////////////////////////////////////////////
class VmfShell(object):
"""
Interative shell to Vmfcat. The shell can be use to build a VMF message.
"""
CMD_SAVE = 'save'
CMD_LOAD = 'load'
CMD_SEARCH = 'search'
CMD_SET = 'set'
CMD_SHOW = 'show'
CMD_HEADER = 'header'
CMD_HELP = 'help'
CMD_QUIT = 'quit'
PROMPT = "<<< "
def __init__(self, _output=sys.stdout):
"""
Initializes the user interface by defining a Logger object
and defining the standard output.
"""
self.output = _output
self.logger = Logger(_output, _debug=True)
def start(self):
"""
Starts the main loop of the interactive shell.
"""
# Command entered by the user
cmd = ""
self.logger.print_info("Type 'help' to show a list of available commands.")
while (cmd.lower() != VmfShell.CMD_QUIT):
try:
self.output.write(VmfShell.PROMPT)
user_input = sys.stdin.readline()
tokens = user_input.rstrip().split()
cmd = tokens[0]
if (cmd.lower() == VmfShell.CMD_QUIT):
pass
elif (cmd.lower() == VmfShell.CMD_HELP):
if (len(tokens) == 1):
self.logger.print_info("{:s} <field>|all".format(VmfShell.CMD_SHOW))
self.logger.print_info("{:s} <field> <value>".format(VmfShell.CMD_SET))
self.logger.print_info("{:s} [field] {{bin, hex}}".format(VmfShell.CMD_HEADER))
self.logger.print_info("{:s} <field>".format(VmfShell.CMD_HELP))
self.logger.print_info("{:s} <field>".format(VmfShell.CMD_SEARCH))
self.logger.print_info("{:s} <file>".format(VmfShell.CMD_SAVE))
self.logger.print_info("{:s} <file>".format(VmfShell.CMD_LOAD))
self.logger.print_info("{:s}".format(VmfShell.CMD_QUIT))
else:
param = tokens[1]
if (param in Params.__dict__.keys()):
help_msg = Params.parameters[param]['help']
self.logger.print_info(help_msg)
if (len(Params.parameters[param]['choices']) > 0):
choices_msg = ', '.join([ choice for choice in Params.parameters[param]['choices']])
self.logger.print_info("Available values: {:s}".format(choices_msg))
else:
self.logger.print_error("Unknown parameter/option: {:s}.".format(param))
elif (cmd.lower() == VmfShell.CMD_SHOW):
#
# Displays the value of the given field
#
if (len(tokens) == 2):
param = tokens[1]
if (param in Params.parameters.keys()):
value = Params.__dict__[param]
if (isinstance(value, int)):
value = "0x{:02x}".format(value)
self.logger.print_info("{} = {}".format(param, value))
elif param.lower() == "all":
for p in Params.parameters.keys():
value = Params.__dict__[p]
self.logger.print_info("{} = {}".format(p, value))
else:
self.logger.print_error("Unknown parameter/option {:s}.".format(param))
else:
self.logger.print_error("Usage: {s} <field>".format(VmfShell.CMD_SHOW))
elif (cmd.lower() == VmfShell.CMD_SET):
#
# Sets a field with the given value
#
# TODO: Issues with parameters with boolean values
if (len(tokens) >= 3):
param = tokens[1]
value = ' '.join(tokens[2:])
if (param in Params.__dict__.keys()):
if (Params.parameters[param]["choices"]):
if (value in Params.parameters[param]["choices"]):
Params.__dict__[param] = value
new_value = Params.__dict__[param]
self.logger.print_success("{:s} = {:s}".format(param, new_value))
else:
self.logger.print_error("Invalid value ({:s}) for field {:s}.".format(value, param))
self.logger.print_info("Values for field are : {:s}.".format(','.join(str(Params.parameters[param]["choices"]))))
else:
Params.__dict__[param] = value
new_value = Params.__dict__[param]
self.logger.print_success("{:s} = {:s}".format(param, new_value))
else:
self.logger.print_error("Unknown parameter {:s}.".format(param))
else:
self.logger.print_error("Usage: {:s} <field> <value>".format(VmfShell.CMD_SET))
elif (cmd.lower() == VmfShell.CMD_HEADER):
field = "vmfversion"
fmt = "bin"
if (len(tokens) >= 2):
field = tokens[1]
if (len(tokens) == 3):
fmt = tokens[2]
vmf_factory = Factory(_logger=self.logger)
vmf_message = vmf_factory.new_message(Params)
vmf_elem = vmf_message.header.elements[field]
if (isinstance(vmf_elem, Field)):
vmf_value = vmf_elem.value
elif (isinstance(vmf_elem, Group)):
vmf_value = "n/a"
else:
raise Exception("Unknown type for element '{:s}'.".format(field))
vmf_bits = vmf_elem.get_bit_array()
output = vmf_bits
if (fmt == "bin"):
output = vmf_bits.bin
if (fmt == "hex"):
output = vmf_bits.hex
self.logger.print_success("{}\t{}\t{}".format(field, vmf_value, output))
elif (cmd.lower() == VmfShell.CMD_SEARCH):
keyword = ' '.join(tokens[1:]).lower()
for p in Params.parameters.keys():
help = Params.parameters[p]['help']
if (p.lower() == keyword or keyword in help.lower()):
self.logger.print_success("{:s}: {:s}".format(p, help))
elif (cmd.lower() == VmfShell.CMD_SAVE):
if len(tokens) == 2:
file = tokens[1]
tmpdict = {}
for param in Params.parameters.keys():
value = Params.__dict__[param]
tmpdict[param] = value
with open(file, 'w') as f:
json.dump(tmpdict, f)
self.logger.print_success("Saved VMF message to {:s}.".format(file))
else:
self.logger.print_error("Specify a file to save the configuration to.")
elif (cmd.lower() == "test"):
if (len(tokens) == 2):
vmf_params = tokens[1]
else:
vmf_params = '0x4023'
s = BitStream(vmf_params)
bstream = BitStream('0x4023')
vmf_factory = Factory(_logger=self.logger)
vmf_message = vmf_factory.read_message(bstream)
elif (cmd.lower() == VmfShell.CMD_LOAD):
if len(tokens) == 2:
file = tokens[1]
with open(file, 'r') as f:
param_dict = json.load(f)
for (param, value) in param_dict.iteritems():
Params.__dict__[param] = value
self.logger.print_success("Loaded VMF message from {:s}.".format(file))
else:
self.logger.print_error("Specify a file to load the configuration from.")
else:
self.logger.print_error("Unknown command {:s}.".format(cmd))
except Exception as e:
self.logger.print_error("An exception as occured: {:s}".format(e.message))
traceback.print_exc(file=sys.stdout)
| InfectedPacket/TerrorCat | UI.py | Python | lgpl-3.0 | 32,143 |
/*
* Copyright (c) 2011 for Jacek Bzdak
*
* This file is part of query builder.
*
* Query builder 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.
*
* Query builder 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 Query builder. If not, see <http://www.gnu.org/licenses/>.
*/
package cx.ath.jbzdak.sqlbuilder.expression;
import fakeEnum.FakeEnum;
import java.util.Collection;
/**
* Created by: Jacek Bzdak
*/
public class BinaryExpressionType {
public static final String LIKE = "LIKE";
public static final String EQUALS = "=";
public static final String NE = "<>";
public static final String LT = "<";
public static final String GT = ">";
public static final String LTE = "<=";
public static final String GTE = ">=";
public static final String IN = "IN";
public static final String MINUS = "-";
public static final String DIVIDE = "/";
public static final FakeEnum<String> FAKE_ENUM = new FakeEnum<String>(BinaryExpressionType.class, String.class);
public static String nameOf(String value) {
return FAKE_ENUM.nameOf(value);
}
public static Collection<? extends String> values() {
return FAKE_ENUM.values();
}
public static String valueOf(String s) {
return FAKE_ENUM.valueOf(s);
}
}
| jbzdak/query-builder | sql-builder-api/src/main/java/cx/ath/jbzdak/sqlbuilder/expression/BinaryExpressionType.java | Java | lgpl-3.0 | 1,760 |
// 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; version 3 of the License.
//
// 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
using NUnit.Framework;
using System.Web.Security;
using System.Collections.Specialized;
using System.Data;
using System;
using System.Configuration.Provider;
using MariaDB.Web.Security;
using MariaDB.Data.MySqlClient;
namespace MariaDB.Web.Tests
{
[TestFixture]
public class UserManagement : BaseWebTest
{
private MySQLMembershipProvider provider;
[SetUp]
public override void Setup()
{
base.Setup();
execSQL("DROP TABLE IF EXISTS mysql_membership");
}
private void CreateUserWithFormat(MembershipPasswordFormat format)
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", format.ToString());
provider.Initialize(null, config);
// create the user
MembershipCreateStatus status;
provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
// verify that the password format is hashed.
DataTable table = FillTable("SELECT * FROM my_aspnet_Membership");
MembershipPasswordFormat rowFormat =
(MembershipPasswordFormat)Convert.ToInt32(table.Rows[0]["PasswordFormat"]);
Assert.AreEqual(format, rowFormat);
// then attempt to verify the user
Assert.IsTrue(provider.ValidateUser("foo", "barbar!"));
}
[Test]
public void CreateUserWithHashedPassword()
{
CreateUserWithFormat(MembershipPasswordFormat.Hashed);
}
[Test]
public void CreateUserWithEncryptedPasswordWithAutoGenKeys()
{
try
{
CreateUserWithFormat(MembershipPasswordFormat.Encrypted);
}
catch (ProviderException)
{
}
}
[Test]
public void CreateUserWithClearPassword()
{
CreateUserWithFormat(MembershipPasswordFormat.Clear);
}
/// <summary>
/// Bug #34792 New User/Changing Password Validation Not working.
/// </summary>
[Test]
public void ChangePassword()
{
CreateUserWithHashedPassword();
try
{
provider.ChangePassword("foo", "barbar!", "bar2");
Assert.Fail();
}
catch (ArgumentException ae1)
{
Assert.AreEqual("newPassword", ae1.ParamName);
Assert.IsTrue(ae1.Message.Contains("length of parameter"));
}
try
{
provider.ChangePassword("foo", "barbar!", "barbar2");
Assert.Fail();
}
catch (ArgumentException ae1)
{
Assert.AreEqual("newPassword", ae1.ParamName);
Assert.IsTrue(ae1.Message.Contains("alpha numeric"));
}
// now test regex strength testing
bool result = provider.ChangePassword("foo", "barbar!", "zzzxxx!");
Assert.IsFalse(result);
// now do one that should work
result = provider.ChangePassword("foo", "barbar!", "barfoo!");
Assert.IsTrue(result);
provider.ValidateUser("foo", "barfoo!");
}
/// <summary>
/// Bug #34792 New User/Changing Password Validation Not working.
/// </summary>
[Test]
public void CreateUserWithErrors()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Hashed");
provider.Initialize(null, config);
// first try to create a user with a password not long enough
MembershipCreateStatus status;
MembershipUser user = provider.CreateUser("foo", "xyz",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now with not enough non-alphas
user = provider.CreateUser("foo", "xyz1234",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now one that doesn't pass the regex test
user = provider.CreateUser("foo", "xyzxyz!",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now one that works
user = provider.CreateUser("foo", "barbar!",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
Assert.AreEqual(MembershipCreateStatus.Success, status);
}
[Test]
public void DeleteUser()
{
CreateUserWithHashedPassword();
Assert.IsTrue(provider.DeleteUser("foo", true));
DataTable table = FillTable("SELECT * FROM my_aspnet_Membership");
Assert.AreEqual(0, table.Rows.Count);
table = FillTable("SELECT * FROM my_aspnet_Users");
Assert.AreEqual(0, table.Rows.Count);
CreateUserWithHashedPassword();
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
provider.Initialize(null, config);
Assert.IsTrue(Membership.DeleteUser("foo", false));
table = FillTable("SELECT * FROM my_aspnet_Membership");
Assert.AreEqual(0, table.Rows.Count);
table = FillTable("SELECT * FROM my_aspnet_Users");
Assert.AreEqual(1, table.Rows.Count);
}
[Test]
public void FindUsersByName()
{
CreateUserWithHashedPassword();
int records;
MembershipUserCollection users = provider.FindUsersByName("F%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
}
[Test]
public void FindUsersByEmail()
{
CreateUserWithHashedPassword();
int records;
MembershipUserCollection users = provider.FindUsersByEmail("foo@bar.com", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
}
[Test]
public void TestCreateUserOverrides()
{
try
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
int records;
MembershipUserCollection users = Membership.FindUsersByName("F%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
Membership.CreateUser("test", "barbar!", "myemail@host.com",
"question", "answer", true, out status);
users = Membership.FindUsersByName("T%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("test", users["test"].UserName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void NumberOfUsersOnline()
{
int numOnline = Membership.GetNumberOfUsersOnline();
Assert.AreEqual(0, numOnline);
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
Membership.CreateUser("foo2", "barbar!", null, "question", "answer", true, out status);
numOnline = Membership.GetNumberOfUsersOnline();
Assert.AreEqual(2, numOnline);
}
[Test]
public void UnlockUser()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
Assert.IsFalse(Membership.ValidateUser("foo", "bar2"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
// the user should be locked now so the right password should fail
Assert.IsFalse(Membership.ValidateUser("foo", "barbar!"));
MembershipUser user = Membership.GetUser("foo");
Assert.IsTrue(user.IsLockedOut);
Assert.IsTrue(user.UnlockUser());
user = Membership.GetUser("foo");
Assert.IsFalse(user.IsLockedOut);
Assert.IsTrue(Membership.ValidateUser("foo", "barbar!"));
}
[Test]
public void GetUsernameByEmail()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "question", "answer", true, out status);
string username = Membership.GetUserNameByEmail("foo@bar.com");
Assert.AreEqual("foo", username);
username = Membership.GetUserNameByEmail("foo@b.com");
Assert.IsNull(username);
username = Membership.GetUserNameByEmail(" foo@bar.com ");
Assert.AreEqual("foo", username);
}
[Test]
public void UpdateUser()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
MembershipUser user = Membership.GetUser("foo");
user.Comment = "my comment";
user.Email = "my email";
user.IsApproved = false;
user.LastActivityDate = new DateTime(2008, 1, 1);
user.LastLoginDate = new DateTime(2008, 2, 1);
Membership.UpdateUser(user);
MembershipUser newUser = Membership.GetUser("foo");
Assert.AreEqual(user.Comment, newUser.Comment);
Assert.AreEqual(user.Email, newUser.Email);
Assert.AreEqual(user.IsApproved, newUser.IsApproved);
Assert.AreEqual(user.LastActivityDate, newUser.LastActivityDate);
Assert.AreEqual(user.LastLoginDate, newUser.LastLoginDate);
}
private void ChangePasswordQAHelper(MembershipUser user, string pw, string newQ, string newA)
{
try
{
user.ChangePasswordQuestionAndAnswer(pw, newQ, newA);
Assert.Fail("This should not work.");
}
catch (ArgumentNullException ane)
{
Assert.AreEqual("password", ane.ParamName);
}
catch (ArgumentException)
{
Assert.IsNotNull(pw);
}
}
[Test]
public void ChangePasswordQuestionAndAnswer()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
MembershipUser user = Membership.GetUser("foo");
ChangePasswordQAHelper(user, "", "newQ", "newA");
ChangePasswordQAHelper(user, "barbar!", "", "newA");
ChangePasswordQAHelper(user, "barbar!", "newQ", "");
ChangePasswordQAHelper(user, null, "newQ", "newA");
bool result = user.ChangePasswordQuestionAndAnswer("barbar!", "newQ", "newA");
Assert.IsTrue(result);
user = Membership.GetUser("foo");
Assert.AreEqual("newQ", user.PasswordQuestion);
}
[Test]
public void GetAllUsers()
{
MembershipCreateStatus status;
// first create a bunch of users
for (int i=0; i < 100; i++)
Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null,
"question", "answer", true, out status);
MembershipUserCollection users = Membership.GetAllUsers();
Assert.AreEqual(100, users.Count);
int index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo{0}", index++), user.UserName);
int total;
users = Membership.GetAllUsers(2, 10, out total);
Assert.AreEqual(10, users.Count);
Assert.AreEqual(100, total);
index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName);
}
private void GetPasswordHelper(bool requireQA, bool enablePasswordRetrieval, string answer)
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", requireQA ? "true" : "false");
config.Add("enablePasswordRetrieval", enablePasswordRetrieval ? "true" : "false");
config.Add("passwordFormat", "clear");
config.Add("applicationName", "/");
config.Add("writeExceptionsToEventLog", "false");
provider.Initialize(null, config);
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, null, out status);
try
{
string password = provider.GetPassword("foo", answer);
if (!enablePasswordRetrieval)
Assert.Fail("This should have thrown an exception");
Assert.AreEqual("barbar!", password);
}
catch (MembershipPasswordException)
{
if (requireQA && answer != null)
Assert.Fail("This should not have thrown an exception");
}
catch (ProviderException)
{
if (requireQA && answer != null)
Assert.Fail("This should not have thrown an exception");
}
}
[Test]
public void GetPassword()
{
GetPasswordHelper(false, false, null);
GetPasswordHelper(false, true, null);
GetPasswordHelper(true, true, null);
GetPasswordHelper(true, true, "blue");
}
/// <summary>
/// Bug #38939 MembershipUser.GetPassword(string answer) fails when incorrect answer is passed.
/// </summary>
[Test]
public void GetPasswordWithWrongAnswer()
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", "true");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "Encrypted");
config.Add("applicationName", "/");
provider.Initialize(null, config);
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, null, out status);
MySQLMembershipProvider provider2 = new MySQLMembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", "LocalMySqlServer");
config2.Add("requiresQuestionAndAnswer", "true");
config2.Add("enablePasswordRetrieval", "true");
config2.Add("passwordFormat", "Encrypted");
config2.Add("applicationName", "/");
provider2.Initialize(null, config2);
try
{
string pw = provider2.GetPassword("foo", "wrong");
Assert.Fail("Should have failed");
}
catch (MembershipPasswordException)
{
}
}
[Test]
public void GetUser()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
MembershipUser user = Membership.GetUser(1);
Assert.AreEqual("foo", user.UserName);
// now move the activity date back outside the login
// window
user.LastActivityDate = new DateTime(2008, 1, 1);
Membership.UpdateUser(user);
user = Membership.GetUser("foo");
Assert.IsFalse(user.IsOnline);
user = Membership.GetUser("foo", true);
Assert.IsTrue(user.IsOnline);
// now move the activity date back outside the login
// window again
user.LastActivityDate = new DateTime(2008, 1, 1);
Membership.UpdateUser(user);
user = Membership.GetUser(1);
Assert.IsFalse(user.IsOnline);
user = Membership.GetUser(1, true);
Assert.IsTrue(user.IsOnline);
}
[Test]
public void FindUsers()
{
MembershipCreateStatus status;
for (int i=0; i < 100; i++)
Membership.CreateUser(String.Format("boo{0}", i), "barbar!", null,
"question", "answer", true, out status);
for (int i=0; i < 100; i++)
Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null,
"question", "answer", true, out status);
for (int i=0; i < 100; i++)
Membership.CreateUser(String.Format("schmoo{0}", i), "barbar!", null,
"question", "answer", true, out status);
MembershipUserCollection users = Membership.FindUsersByName("fo%");
Assert.AreEqual(100, users.Count);
int total;
users = Membership.FindUsersByName("fo%", 2, 10, out total);
Assert.AreEqual(10, users.Count);
Assert.AreEqual(100, total);
int index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName);
}
[Test]
public void CreateUserWithNoQA()
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", "true");
config.Add("passwordFormat", "clear");
config.Add("applicationName", "/");
provider.Initialize(null, config);
try
{
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", null, true, null, out status);
Assert.Fail();
}
catch (Exception ex)
{
Assert.IsTrue(ex.Message.StartsWith("Password answer supplied is invalid"));
}
try
{
provider.CreateUser("foo", "barbar!", "foo@bar.com", "", "blue", true, null, out status);
Assert.Fail();
}
catch (Exception ex)
{
Assert.IsTrue(ex.Message.StartsWith("Password question supplied is invalid"));
}
}
[Test]
public void MinRequiredAlpha()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("minRequiredNonalphanumericCharacters", "3");
provider.Initialize(null, config);
MembershipCreateStatus status;
MembershipUser user = provider.CreateUser("foo", "pw!pass", "email", null, null, true, null, out status);
Assert.IsNull(user);
user = provider.CreateUser("foo", "pw!pa!!", "email", null, null, true, null, out status);
Assert.IsNotNull(user);
}
/// <summary>
/// Bug #35332 GetPassword() don't working (when PasswordAnswer is NULL)
/// </summary>
[Test]
public void GetPasswordWithNullValues()
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "clear");
config.Add("applicationName", "/");
provider.Initialize(null, config);
MembershipUser user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
string pw = provider.GetPassword("foo", null);
Assert.AreEqual("barbar!", pw);
}
/// <summary>
/// Bug #35336 GetPassword() return wrong password (when format is encrypted)
/// </summary>
[Test]
public void GetEncryptedPassword()
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "encrypted");
config.Add("applicationName", "/");
provider.Initialize(null, config);
MembershipUser user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
string pw = provider.GetPassword("foo", null);
Assert.AreEqual("barbar!", pw);
}
/// <summary>
/// Bug #42574 ValidateUser does not use the application id, allowing cross application login
/// </summary>
[Test]
public void CrossAppLogin()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status);
MySQLMembershipProvider provider2 = new MySQLMembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", "LocalMySqlServer");
config2.Add("applicationName", "/myapp");
config2.Add("passwordStrengthRegularExpression", ".*");
config2.Add("passwordFormat", "Clear");
provider2.Initialize(null, config2);
bool worked = provider2.ValidateUser("foo", "bar!bar");
Assert.AreEqual(false, worked);
}
/// <summary>
/// Bug #41408 PasswordReset not possible when requiresQuestionAndAnswer="false"
/// </summary>
[Test]
public void ResetPassword()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
config.Add("requiresQuestionAndAnswer", "false");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status);
MembershipUser u = provider.GetUser("foo", false);
string newpw = provider.ResetPassword("foo", null);
}
/// <summary>
/// Bug #59438 setting Membership.ApplicationName has no effect
/// </summary>
[Test]
public void ChangeAppName()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status);
Assert.IsTrue(status == MembershipCreateStatus.Success);
MySQLMembershipProvider provider2 = new MySQLMembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", "LocalMySqlServer");
config2.Add("applicationName", "/myapp");
config2.Add("passwordStrengthRegularExpression", "foo.*");
config2.Add("passwordFormat", "Clear");
provider2.Initialize(null, config2);
provider2.CreateUser("foo2", "foo!foo", null, null, null, true, null, out status);
Assert.IsTrue(status == MembershipCreateStatus.Success);
provider.ApplicationName = "/myapp";
Assert.IsFalse(provider.ValidateUser("foo", "bar!bar"));
Assert.IsTrue(provider.ValidateUser("foo2", "foo!foo"));
}
[Test]
public void GetUserLooksForExactUsername()
{
MembershipCreateStatus status;
Membership.CreateUser("code", "thecode!", null, "question", "answer", true, out status);
MembershipUser user = Membership.GetUser("code");
Assert.AreEqual("code", user.UserName);
user = Membership.GetUser("co_e");
Assert.IsNull(user);
}
[Test]
public void GetUserNameByEmailLooksForExactEmail()
{
MembershipCreateStatus status;
Membership.CreateUser("code", "thecode!", "code@mysql.com", "question", "answer", true, out status);
string username = Membership.GetUserNameByEmail("code@mysql.com");
Assert.AreEqual("code", username);
username = Membership.GetUserNameByEmail("co_e@mysql.com");
Assert.IsNull(username);
}
}
}
| noahvans/mariadb-connector-net | Legacy/Tests/MariaDB.Web.Tests/UserManagement.cs | C# | lgpl-3.0 | 23,494 |
package com.sirma.itt.seip.definition;
import java.lang.invoke.MethodHandles;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.enterprise.context.ContextNotActiveException;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sirma.itt.seip.domain.definition.DefinitionModel;
import com.sirma.itt.seip.domain.definition.PropertyDefinition;
import com.sirma.itt.seip.domain.instance.Instance;
import com.sirma.itt.seip.domain.instance.InstancePropertyNameResolver;
/**
* Default implementation of the {@link InstancePropertyNameResolver} that uses a request scoped cache to store already
* resolved definitions for an instance in order to provide better performance. If request context is not available
* then the resolver will fall back to on demand definition lookup.
*
* @author <a href="mailto:borislav.bonev@sirma.bg">Borislav Bonev</a>
* @since 19/07/2018
*/
public class InstancePropertyNameResolverImpl implements InstancePropertyNameResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@Inject
private DefinitionService definitionService;
@Inject
private InstancePropertyNameResolverCache cache;
@Override
public String resolve(Instance instance, String fieldUri) {
return getOrResolveModel(instance)
.getField(fieldUri)
.map(PropertyDefinition::getName)
.orElse(fieldUri);
}
private DefinitionModel getOrResolveModel(Instance instance) {
try {
return cache.getOrResolveModel(instance.getId(), resolveDefinition(instance));
} catch (ContextNotActiveException e) {
// for the cases when this is used outside of a transaction like parallel stream processing
return resolveDefinition(instance).get();
}
}
@Override
public Function<String, String> resolverFor(Instance instance) {
DefinitionModel model = getOrResolveModel(instance);
return property -> model.getField(property)
.map(PropertyDefinition::getName)
.orElse(property);
}
private Supplier<DefinitionModel> resolveDefinition(Instance instance) {
return () -> {
LOGGER.trace("Resolving model for {}", instance.getId());
return definitionService.getInstanceDefinition(instance);
};
}
}
| SirmaITT/conservation-space-1.7.0 | docker/sirma-platform/platform/seip-parent/model-management/definition-core/src/main/java/com/sirma/itt/seip/definition/InstancePropertyNameResolverImpl.java | Java | lgpl-3.0 | 2,269 |
/**
* \file components/gpp/stack/CoordinatorMobility/CoordinatorMobilityComponent.cpp
* \version 1.0
*
* \section COPYRIGHT
*
* Copyright 2012 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 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 General Public License for more details.
*
* A copy of the GNU 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 a mobility protocol that has a coordinator that
* determines a backup channel for a set of follower nodes.
*
*/
#include "irisapi/LibraryDefs.h"
#include "irisapi/Version.h"
#include "CoordinatorMobilityComponent.h"
using namespace std;
using namespace boost;
namespace iris
{
// export library symbols
IRIS_COMPONENT_EXPORTS(StackComponent, CoordinatorMobilityComponent);
CoordinatorMobilityComponent::CoordinatorMobilityComponent(std::string name)
: FllStackComponent(name,
"coordinatorcstackcomponent",
"A very simple mobility protocol with coordinator/follower roles",
"Andre Puschmann",
"0.1")
{
//Format: registerParameter(name, description, default, dynamic?, parameter, allowed values);
registerParameter("role", "Role of node", "coordinator", false, role_x);
registerParameter("updateinterval", "Interval between BC updates", "1000", true, updateInterval_x);
registerParameter("querydrm", "Whether to use DRM to determine backupchannel", "false", true, queryDrm_x);
//Format: registerEvent(name, description, data type);
registerEvent("EvGetAvailableChannelsRequest", "Retrieve list of available channels from FllController", TypeInfo< int32_t >::identifier);
registerEvent("EvGetOperatingChannelRequest", "Retrieve current operating channel from FllController", TypeInfo< int32_t >::identifier);
registerEvent("EvUpdateBackupChannel", "Set new backup channel", TypeInfo< int32_t >::identifier);
}
CoordinatorMobilityComponent::~CoordinatorMobilityComponent()
{
}
void CoordinatorMobilityComponent::initialize()
{
// turn off logging to file, system will take care of closing file handle
//LoggingPolicy::getPolicyInstance()->setFileStream(NULL);
}
void CoordinatorMobilityComponent::processMessageFromAbove(boost::shared_ptr<StackDataSet> incomingFrame)
{
//StackHelper::printDataset(incomingFrame, "vanilla from above");
}
void CoordinatorMobilityComponent::processMessageFromBelow(boost::shared_ptr<StackDataSet> incomingFrame)
{
//StackHelper::printDataset(incomingFrame, "vanilla from below");
MobilityPacket updatePacket;
StackHelper::deserializeAndStripDataset(incomingFrame, updatePacket);
switch(updatePacket.type()) {
case MobilityPacket::UPDATE_BC:
{
if (updatePacket.source() == MobilityPacket::COORDINATOR) {
// take first channel in update packet as backup channel
if (updatePacket.channelmap_size() > 0) {
MobilityChannel *mobilityChannel = updatePacket.mutable_channelmap(0);
FllChannel fllChannel = MobilityChannelToFllChannel(mobilityChannel);
LOG(LINFO) << "Received new backup channel from coordinator: " << fllChannel.getFreq() << "Hz.";
setBackupChannel(fllChannel);
}
}
break;
}
default:
LOG(LERROR) << "Undefined packet type.";
break;
} // switch
}
void CoordinatorMobilityComponent::start()
{
// start beaconing thread in coordinator mode
LOG(LINFO) << "I am a " << role_x << " node.";
if (role_x == "coordinator") {
LOG(LINFO) << "Start beaconing thread ..";
beaconingThread_.reset(new boost::thread(boost::bind( &CoordinatorMobilityComponent::beaconingThreadFunction, this)));
} else
if (role_x == "follower") {
LOG(LINFO) << "I am waiting for beacons ..";
} else {
LOG(LERROR) << "Mode is not defined: " << role_x;
}
FllChannelVector channels = getAvailableChannels();
LOG(LINFO) << "No of channels: " << channels.size();
}
void CoordinatorMobilityComponent::stop()
{
// stop threads
if (beaconingThread_) {
beaconingThread_->interrupt();
beaconingThread_->join();
}
}
void CoordinatorMobilityComponent::beaconingThreadFunction()
{
boost::this_thread::sleep(boost::posix_time::seconds(1));
LOG(LINFO) << "Beaconing thread started.";
try
{
while(true)
{
boost::this_thread::interruption_point();
// determine backup channel and transmit beacon
FllChannel bc;
if (findBackupChannel(bc) == true) {
setBackupChannel(bc);
sendUpdateBackupChannelPacket(bc);
}
// sleep until next beacon
boost::this_thread::sleep(boost::posix_time::milliseconds(updateInterval_x));
} // while
}
catch(IrisException& ex)
{
LOG(LFATAL) << "Error in CoordinatorMobility component: " << ex.what() << " - Beaconing thread exiting.";
}
catch(boost::thread_interrupted)
{
LOG(LINFO) << "Thread " << boost::this_thread::get_id() << " in stack component interrupted.";
}
}
void CoordinatorMobilityComponent::sendUpdateBackupChannelPacket(FllChannel backupChannel)
{
MobilityPacket updatePacket;
updatePacket.set_source(MobilityPacket::COORDINATOR);
updatePacket.set_destination(MobilityPacket::FOLLOWER);
updatePacket.set_type(MobilityPacket::UPDATE_BC);
MobilityChannel *channel = updatePacket.add_channelmap();
FllChannelToMobilityChannel(backupChannel, channel);
shared_ptr<StackDataSet> buffer(new StackDataSet);
StackHelper::mergeAndSerializeDataset(buffer, updatePacket);
//StackHelper::printDataset(buffer, "UpdateBC packet Tx");
sendDownwards(buffer);
LOG(LINFO) << "Tx UpdateBC packet ";
}
void CoordinatorMobilityComponent::FllChannelToMobilityChannel(const FllChannel fllchannel, MobilityChannel *mobilityChannel)
{
mobilityChannel->set_f_center(fllchannel.getFreq());
mobilityChannel->set_bandwidth(fllchannel.getBandwidth());
switch (fllchannel.getState()) {
case FREE: mobilityChannel->set_status(MobilityChannel_Status_FREE); break;
case BUSY_SU: mobilityChannel->set_status(MobilityChannel_Status_BUSY_SU); break;
case BUSY_PU: mobilityChannel->set_status(MobilityChannel_Status_BUSY_PU); break;
default: LOG(LERROR) << "Unknown channel state.";
}
}
FllChannel CoordinatorMobilityComponent::MobilityChannelToFllChannel(MobilityChannel *mobilityChannel)
{
FllChannel channel;
channel.setFreq(mobilityChannel->f_center());
channel.setBandwidth(mobilityChannel->bandwidth());
switch (mobilityChannel->status()) {
case MobilityChannel_Status_FREE: channel.setState(FREE); break;
case MobilityChannel_Status_BUSY_SU: channel.setState(BUSY_SU); break;
case MobilityChannel_Status_BUSY_PU: channel.setState(BUSY_PU); break;
default: LOG(LERROR) << "Unknown channel state.";
}
return channel;
}
bool CoordinatorMobilityComponent::findBackupChannel(FllChannel& bc)
{
FllChannelVector channels = getAvailableChannels();
FllChannel operatingChannel = getOperatingChannel(0); // get operating channel of primary receiver, i.e. trx 0
#if OSPECORR
if (queryDrm_x) {
bool ret = FllDrmHelper::getChannel(bc);
if (ret == true && bc != operatingChannel) {
// success, got valid backup channel from DRM
LOG(LINFO) << "Got backup channel at " << bc.getFreq() << " from DRM.";
return true;
} else {
return false;
}
}
#endif
// find free channel other than operating channel in set of available channels
FllChannelVector::iterator it;
bool channelFound = false;
for (it = channels.begin(); it != channels.end(); ++it) {
if (it->getState() == FREE && *it != operatingChannel) {
LOG(LINFO) << "Free channel found: " << it->getFreq() << "Hz.";
bc = *it;
channelFound = true;
break;
}
}
if (not channelFound) {
LOG(LERROR) << "No free backup channel found. Skip update.";
}
return channelFound;
}
} /* namespace iris */
| andrepuschmann/iris_fll_modules | components/gpp/stack/CoordinatorMobility/CoordinatorMobilityComponent.cpp | C++ | lgpl-3.0 | 9,079 |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Plot cost evolution
@author: verlaanm
"""
# ex1
#load numpy and matplotlib if needed
import matplotlib.pyplot as plt
#load data
import dud_results as dud
# create plot of cost and parameter
plt.close("all")
f,ax = plt.subplots(2,1)
ax[0].plot(dud.costTotal);
ax[0].set_xlabel("model run");
ax[0].set_ylabel("cost function");
ax[1].plot(dud.evaluatedParameters);
ax[1].set_xlabel('model run');
ax[1].set_ylabel('change of reaction\_time [seconds]');
| OpenDA-Association/OpenDA | course/exercise_black_box_calibration_polution_NOT_WORKING/plot_cost.py | Python | lgpl-3.0 | 504 |
// Copyright 2019 The Swarm Authors
// This file is part of the Swarm library.
//
// The Swarm 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 Swarm 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 Swarm library. If not, see <http://www.gnu.org/licenses/>.
package stream
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"runtime"
"sync"
"testing"
"time"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethersphere/swarm/chunk"
"github.com/ethersphere/swarm/log"
"github.com/ethersphere/swarm/network"
"github.com/ethersphere/swarm/network/simulation"
"github.com/ethersphere/swarm/p2p/protocols"
"github.com/ethersphere/swarm/pot"
"github.com/ethersphere/swarm/storage"
"github.com/ethersphere/swarm/storage/localstore"
"github.com/ethersphere/swarm/testutil"
)
var timeout = 90 * time.Second
// TestTwoNodesSyncWithGaps tests that syncing works with gaps in the localstore intervals
func TestTwoNodesSyncWithGaps(t *testing.T) {
// construct a pauser before simulation is started and reset it to nil after all streams are closed
// to avoid the need for protecting handleMsgPauser with a lock in production code.
handleMsgPauser = new(syncPauser)
defer func() { handleMsgPauser = nil }()
removeChunks := func(t *testing.T, ctx context.Context, store chunk.Store, gaps [][2]uint64, chunks []chunk.Address) (removedCount uint64) {
t.Helper()
for _, gap := range gaps {
for i := gap[0]; i < gap[1]; i++ {
c := chunks[i]
if err := store.Set(ctx, chunk.ModeSetRemove, c); err != nil {
t.Fatal(err)
}
removedCount++
}
}
return removedCount
}
for _, tc := range []struct {
name string
chunkCount uint64
gaps [][2]uint64
liveChunkCount uint64
liveGaps [][2]uint64
}{
{
name: "no gaps",
chunkCount: 100,
gaps: nil,
},
{
name: "first chunk removed",
chunkCount: 100,
gaps: [][2]uint64{{0, 1}},
},
{
name: "one chunk removed",
chunkCount: 100,
gaps: [][2]uint64{{60, 61}},
},
{
name: "single gap at start",
chunkCount: 100,
gaps: [][2]uint64{{0, 5}},
},
{
name: "single gap",
chunkCount: 100,
gaps: [][2]uint64{{5, 10}},
},
{
name: "multiple gaps",
chunkCount: 100,
gaps: [][2]uint64{{0, 1}, {10, 21}},
},
{
name: "big gaps",
chunkCount: 100,
gaps: [][2]uint64{{0, 1}, {10, 21}, {50, 91}},
},
{
name: "remove all",
chunkCount: 100,
gaps: [][2]uint64{{0, 100}},
},
{
name: "large db",
chunkCount: 4000,
},
{
name: "large db with gap",
chunkCount: 4000,
gaps: [][2]uint64{{1000, 3000}},
},
{
name: "live",
liveChunkCount: 100,
},
{
name: "live and history",
chunkCount: 100,
liveChunkCount: 100,
},
{
name: "live and history with history gap",
chunkCount: 100,
gaps: [][2]uint64{{5, 10}},
liveChunkCount: 100,
},
{
name: "live and history with live gap",
chunkCount: 100,
liveChunkCount: 100,
liveGaps: [][2]uint64{{105, 110}},
},
{
name: "live and history with gaps",
chunkCount: 100,
gaps: [][2]uint64{{5, 10}},
liveChunkCount: 100,
liveGaps: [][2]uint64{{105, 110}},
},
} {
t.Run(tc.name, func(t *testing.T) {
sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}),
}, false)
defer sim.Close()
defer catchDuplicateChunkSync(t)()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
uploadNode, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
uploadStore := sim.MustNodeItem(uploadNode, bucketKeyFileStore).(chunk.Store)
chunks := mustUploadChunks(ctx, t, uploadStore, tc.chunkCount)
totalChunkCount, err := getChunkCount(uploadStore)
if err != nil {
t.Fatal(err)
}
if totalChunkCount != tc.chunkCount {
t.Errorf("uploaded %v chunks, want %v", totalChunkCount, tc.chunkCount)
}
removedCount := removeChunks(t, ctx, uploadStore, tc.gaps, chunks)
syncNode, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
err = sim.Net.Connect(uploadNode, syncNode)
if err != nil {
t.Fatal(err)
}
syncStore := sim.MustNodeItem(syncNode, bucketKeyFileStore).(chunk.Store)
err = waitChunks(syncStore, totalChunkCount-removedCount, 10*time.Second)
if err != nil {
t.Fatal(err)
}
if tc.liveChunkCount > 0 {
// pause syncing so that the chunks in the live gap
// are not synced before they are removed
handleMsgPauser.Pause()
chunks = append(chunks, mustUploadChunks(ctx, t, uploadStore, tc.liveChunkCount)...)
removedCount += removeChunks(t, ctx, uploadStore, tc.liveGaps, chunks)
// resume syncing
handleMsgPauser.Resume()
err = waitChunks(syncStore, tc.chunkCount+tc.liveChunkCount-removedCount, time.Minute)
if err != nil {
t.Fatal(err)
}
}
})
}
}
// TestTheeNodesUnionHistoricalSync brings up three nodes, uploads content too all of them and then
// asserts that all of them have the union of all 3 local stores (depth is assumed to be 0)
func TestThreeNodesUnionHistoricalSync(t *testing.T) {
nodes := 3
chunkCount := 1000
sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}),
}, false)
defer sim.Close()
union := make(map[string]struct{})
nodeIDs := []enode.ID{}
for i := 0; i < nodes; i++ {
node, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
nodeIDs = append(nodeIDs, node)
nodeStore := sim.MustNodeItem(node, bucketKeyFileStore).(*storage.FileStore)
mustUploadChunks(context.Background(), t, nodeStore, uint64(chunkCount))
uploadedChunks, err := getChunks(nodeStore.ChunkStore)
if err != nil {
t.Fatal(err)
}
for k := range uploadedChunks {
if _, ok := union[k]; ok {
t.Fatal("chunk already exists in union")
}
union[k] = struct{}{}
}
}
err := sim.Net.ConnectNodesFull(nodeIDs)
if err != nil {
t.Fatal(err)
}
for _, n := range nodeIDs {
nodeStore := sim.MustNodeItem(n, bucketKeyFileStore).(*storage.FileStore)
if err := waitChunks(nodeStore, uint64(len(union)), 10*time.Second); err != nil {
t.Fatal(err)
}
}
}
// TestFullSync performs a series of subtests where a number of nodes are
// connected to the single (chunk uploading) node.
func TestFullSync(t *testing.T) {
for _, tc := range []struct {
name string
chunkCount uint64
syncNodeCount int
history bool
live bool
}{
{
name: "sync to two nodes history",
chunkCount: 5000,
syncNodeCount: 2,
history: true,
},
{
name: "sync to two nodes live",
chunkCount: 5000,
syncNodeCount: 2,
live: true,
},
{
name: "sync to two nodes history and live",
chunkCount: 2500,
syncNodeCount: 2,
history: true,
live: true,
},
{
name: "sync to 50 nodes history",
chunkCount: 500,
syncNodeCount: 50,
history: true,
},
{
name: "sync to 50 nodes live",
chunkCount: 500,
syncNodeCount: 50,
live: true,
},
{
name: "sync to 50 nodes history and live",
chunkCount: 250,
syncNodeCount: 50,
history: true,
live: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
if tc.syncNodeCount > 2 && runtime.GOARCH == "386" {
t.Skip("skipping larger simulation on low memory architecture")
}
sim := simulation.NewInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}),
})
defer sim.Close()
defer catchDuplicateChunkSync(t)()
uploaderNode, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
uploaderNodeStore := sim.MustNodeItem(uploaderNode, bucketKeyFileStore).(*storage.FileStore)
if tc.history {
mustUploadChunks(context.Background(), t, uploaderNodeStore, tc.chunkCount)
}
// add nodes to sync to
ids, err := sim.AddNodes(tc.syncNodeCount)
if err != nil {
t.Fatal(err)
}
// connect every new node to the uploading one, so
// every node will have depth 0 as only uploading node
// will be in their kademlia tables
err = sim.Net.ConnectNodesStar(ids, uploaderNode)
if err != nil {
t.Fatal(err)
}
// count the content in the bins again
uploadedChunks, err := getChunks(uploaderNodeStore.ChunkStore)
if err != nil {
t.Fatal(err)
}
if tc.history && len(uploadedChunks) == 0 {
t.Errorf("got empty uploader chunk store")
}
if !tc.history && len(uploadedChunks) != 0 {
t.Errorf("got non empty uploader chunk store")
}
historicalChunks := make(map[enode.ID]map[string]struct{})
for _, id := range ids {
wantChunks := make(map[string]struct{}, len(uploadedChunks))
for k, v := range uploadedChunks {
wantChunks[k] = v
}
// wait for all chunks to be synced
store := sim.MustNodeItem(id, bucketKeyFileStore).(chunk.Store)
if err := waitChunks(store, uint64(len(wantChunks)), 10*time.Second); err != nil {
t.Fatal(err)
}
// validate that all and only all chunks are synced
syncedChunks, err := getChunks(store)
if err != nil {
t.Fatal(err)
}
historicalChunks[id] = make(map[string]struct{})
for c := range wantChunks {
if _, ok := syncedChunks[c]; !ok {
t.Errorf("missing chunk %v", c)
}
delete(wantChunks, c)
delete(syncedChunks, c)
historicalChunks[id][c] = struct{}{}
}
if len(wantChunks) != 0 {
t.Errorf("some of the uploaded chunks are not synced")
}
if len(syncedChunks) != 0 {
t.Errorf("some of the synced chunks are not of uploaded ones")
}
}
if tc.live {
mustUploadChunks(context.Background(), t, uploaderNodeStore, tc.chunkCount)
}
uploadedChunks, err = getChunks(uploaderNodeStore.ChunkStore)
if err != nil {
t.Fatal(err)
}
for _, id := range ids {
wantChunks := make(map[string]struct{}, len(uploadedChunks))
for k, v := range uploadedChunks {
wantChunks[k] = v
}
store := sim.MustNodeItem(id, bucketKeyFileStore).(chunk.Store)
// wait for all chunks to be synced
if err := waitChunks(store, uint64(len(wantChunks)), 10*time.Second); err != nil {
t.Fatal(err)
}
// get all chunks from the syncing node
syncedChunks, err := getChunks(store)
if err != nil {
t.Fatal(err)
}
// remove historical chunks from total uploaded and synced chunks
for c := range historicalChunks[id] {
if _, ok := wantChunks[c]; !ok {
t.Errorf("missing uploaded historical chunk: %s", c)
}
delete(wantChunks, c)
if _, ok := syncedChunks[c]; !ok {
t.Errorf("missing synced historical chunk: %s", c)
}
delete(syncedChunks, c)
}
// validate that all and only all live chunks are synced
for c := range wantChunks {
if _, ok := syncedChunks[c]; !ok {
t.Errorf("missing chunk %v", c)
}
delete(wantChunks, c)
delete(syncedChunks, c)
}
if len(wantChunks) != 0 {
t.Errorf("some of the uploaded live chunks are not synced")
}
if len(syncedChunks) != 0 {
t.Errorf("some of the synced live chunks are not of uploaded ones")
}
}
})
}
}
func waitChunks(store chunk.Store, want uint64, staledTimeout time.Duration) (err error) {
start := time.Now()
var (
count uint64 // total number of chunks
prev uint64 // total number of chunks in previous check
sleep time.Duration // duration until the next check
staled time.Duration // duration for when the number of chunks is the same
)
for staled < staledTimeout { // wait for some time while staled
count, err = getChunkCount(store)
if err != nil {
return err
}
if count >= want {
break
}
if count == prev {
staled += sleep
} else {
staled = 0
}
prev = count
if count > 0 {
// Calculate sleep time only if there is at least 1% of chunks available,
// less may produce unreliable result.
if count > want/100 {
// Calculate the time required to pass for missing chunks to be available,
// and divide it by half to perform a check earlier.
sleep = time.Duration(float64(time.Since(start)) * float64(want-count) / float64(count) / 2)
log.Debug("expecting all chunks", "in", sleep*2, "want", want, "have", count)
}
}
switch {
case sleep > time.Minute:
// next check and speed calculation in some shorter time
sleep = 500 * time.Millisecond
case sleep > 5*time.Second:
// upper limit for the check, do not check too slow
sleep = 5 * time.Second
case sleep < 50*time.Millisecond:
// lower limit for the check, do not check too frequently
sleep = 50 * time.Millisecond
if staled > 0 {
// slow down if chunks are stuck near the want value
sleep *= 10
}
}
time.Sleep(sleep)
}
if count != want {
return fmt.Errorf("got synced chunks %d, want %d", count, want)
}
return nil
}
func getChunkCount(store chunk.Store) (c uint64, err error) {
for po := 0; po <= chunk.MaxPO; po++ {
last, err := store.LastPullSubscriptionBinID(uint8(po))
if err != nil {
return 0, err
}
c += last
}
return c, nil
}
func getChunks(store chunk.Store) (chunks map[string]struct{}, err error) {
chunks = make(map[string]struct{})
for po := uint8(0); po <= chunk.MaxPO; po++ {
last, err := store.LastPullSubscriptionBinID(po)
if err != nil {
return nil, err
}
if last == 0 {
continue
}
ch, _ := store.SubscribePull(context.Background(), po, 0, last)
for c := range ch {
addr := c.Address.Hex()
if _, ok := chunks[addr]; ok {
return nil, fmt.Errorf("duplicate chunk %s", addr)
}
chunks[addr] = struct{}{}
}
}
return chunks, nil
}
/*
BenchmarkHistoricalStream measures syncing time after two nodes connect.
go test -v github.com/ethersphere/swarm/network/stream/v2 -run="^$" -bench BenchmarkHistoricalStream -benchmem -loglevel 0
goos: darwin
goarch: amd64
pkg: github.com/ethersphere/swarm/network/stream/v2
BenchmarkHistoricalStream/1000-chunks-8 10 133564663 ns/op 148289188 B/op 233646 allocs/op
BenchmarkHistoricalStream/2000-chunks-8 5 290056259 ns/op 316599452 B/op 541507 allocs/op
BenchmarkHistoricalStream/10000-chunks-8 1 1714618578 ns/op 1791108672 B/op 4133564 allocs/op
BenchmarkHistoricalStream/20000-chunks-8 1 4724760666 ns/op 4133092720 B/op 11347504 allocs/op
PASS
*/
func BenchmarkHistoricalStream(b *testing.B) {
for _, c := range []uint64{
1000,
2000,
10000,
20000,
} {
b.Run(fmt.Sprintf("%v-chunks", c), func(b *testing.B) {
benchmarkHistoricalStream(b, c)
})
}
}
func benchmarkHistoricalStream(b *testing.B, chunks uint64) {
b.StopTimer()
for i := 0; i < b.N; i++ {
sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}),
}, false)
uploaderNode, err := sim.AddNode()
if err != nil {
b.Fatal(err)
}
uploaderNodeStore := nodeFileStore(sim, uploaderNode)
mustUploadChunks(context.Background(), b, uploaderNodeStore, chunks)
uploadedChunks, err := getChunks(uploaderNodeStore.ChunkStore)
if err != nil {
b.Fatal(err)
}
syncingNode, err := sim.AddNode()
if err != nil {
b.Fatal(err)
}
b.StartTimer()
err = sim.Net.Connect(syncingNode, uploaderNode)
if err != nil {
b.Fatal(err)
}
syncingNodeStore := sim.MustNodeItem(syncingNode, bucketKeyFileStore).(chunk.Store)
if err := waitChunks(syncingNodeStore, uint64(len(uploadedChunks)), 10*time.Second); err != nil {
b.Fatal(err)
}
b.StopTimer()
err = sim.Net.Stop(syncingNode)
if err != nil {
b.Fatal(err)
}
sim.Close()
}
}
// Function that uses putSeenTestHook to record and report
// if there were duplicate chunk synced between Node id
func catchDuplicateChunkSync(t *testing.T) (validate func()) {
m := make(map[enode.ID]map[string]int)
var mu sync.Mutex
putSeenTestHook = func(addr chunk.Address, id enode.ID) {
mu.Lock()
defer mu.Unlock()
if _, ok := m[id]; !ok {
m[id] = make(map[string]int)
}
m[id][addr.Hex()]++
}
return func() {
// reset the test hook
putSeenTestHook = nil
// do the validation
mu.Lock()
defer mu.Unlock()
for nodeID, addrs := range m {
for addr, count := range addrs {
t.Errorf("chunk synced %v times to node %s: %v", count, nodeID, addr)
}
}
}
}
// TestStarNetworkSyncWithBogusNodes ests that syncing works on a more elaborate network topology
// the test creates three real nodes in a star topology, then adds bogus nodes to the pivot (instead of using real nodes
// this is in order to make the simulation be more CI friendly)
// the pivot node will have neighbourhood depth > 0, which in turn means that from each
// connected node, the pivot node should have only part of its chunks
// The test checks that EVERY chunk that exists a node which is not the pivot, according to
// its PO, and kademlia table of the pivot - exists on the pivot node and does not exist on other nodes
func TestStarNetworkSyncWithBogusNodes(t *testing.T) {
var (
chunkCount = 500
nodeCount = 12
minPivotDepth = 1
chunkSize = 4096
simTimeout = 60 * time.Second
syncTime = 4 * time.Second
filesize = chunkCount * chunkSize
opts = &SyncSimServiceOptions{SyncOnlyWithinDepth: false, Autostart: true}
)
sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(opts),
}, false)
defer sim.Close()
ctx, cancel := context.WithTimeout(context.Background(), simTimeout)
defer cancel()
pivot, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
pivotKad := sim.MustNodeItem(pivot, simulation.BucketKeyKademlia).(*network.Kademlia)
pivotBase := pivotKad.BaseAddr()
log.Debug("started pivot node", "addr", hex.EncodeToString(pivotBase))
newNode, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
err = sim.Net.Connect(pivot, newNode)
if err != nil {
t.Fatal(err)
}
newNode2, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
err = sim.Net.Connect(pivot, newNode2)
if err != nil {
t.Fatal(err)
}
time.Sleep(50 * time.Millisecond)
log.Trace(sim.MustNodeItem(newNode, simulation.BucketKeyKademlia).(*network.Kademlia).String())
pivotKad = sim.MustNodeItem(pivot, simulation.BucketKeyKademlia).(*network.Kademlia)
pivotAddr := pot.NewAddressFromBytes(pivotBase)
// add a few fictional nodes at higher POs to uploader so that uploader depth goes > 0
for i := 0; i < nodeCount; i++ {
rw := &p2p.MsgPipeRW{}
ptpPeer := p2p.NewPeer(enode.ID{}, "im just a lazy hobo", []p2p.Cap{})
protoPeer := protocols.NewPeer(ptpPeer, rw, &protocols.Spec{})
peerAddr := pot.RandomAddressAt(pivotAddr, i)
bzzPeer := &network.BzzPeer{
Peer: protoPeer,
BzzAddr: network.NewBzzAddr(peerAddr.Bytes(), nil),
}
peer := network.NewPeer(bzzPeer, pivotKad)
pivotKad.On(peer)
}
time.Sleep(50 * time.Millisecond)
log.Trace(pivotKad.String())
if d := pivotKad.NeighbourhoodDepth(); d < minPivotDepth {
t.Skipf("too shallow. depth %d want %d", d, minPivotDepth)
}
pivotDepth := pivotKad.NeighbourhoodDepth()
chunkProx := make(map[string]chunkProxData)
result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) (err error) {
nodeIDs := sim.UpNodeIDs()
for _, node := range nodeIDs {
node := node
if bytes.Equal(pivot.Bytes(), node.Bytes()) {
continue
}
nodeKad := sim.MustNodeItem(node, simulation.BucketKeyKademlia).(*network.Kademlia)
nodePo := chunk.Proximity(nodeKad.BaseAddr(), pivotKad.BaseAddr())
seed := int(time.Now().UnixNano())
randomBytes := testutil.RandomBytes(seed, filesize)
log.Debug("putting chunks to ephemeral localstore")
chunkAddrs, err := getAllRefs(randomBytes[:])
if err != nil {
return err
}
log.Debug("done getting all refs")
for _, c := range chunkAddrs {
proxData := chunkProxData{
addr: c,
uploaderNodeToPivotNodePO: nodePo,
chunkToUploaderPO: chunk.Proximity(nodeKad.BaseAddr(), c),
pivotPO: chunk.Proximity(c, pivotKad.BaseAddr()),
uploaderNode: node,
}
log.Debug("test putting chunk", "node", node, "addr", hex.EncodeToString(c), "uploaderToPivotPO", proxData.uploaderNodeToPivotNodePO, "c2uploaderPO", proxData.chunkToUploaderPO, "pivotDepth", pivotDepth)
if _, ok := chunkProx[hex.EncodeToString(c)]; ok {
return fmt.Errorf("chunk already found on another node %s", hex.EncodeToString(c))
}
chunkProx[hex.EncodeToString(c)] = proxData
}
fs := sim.MustNodeItem(node, bucketKeyFileStore).(*storage.FileStore)
reader := bytes.NewReader(randomBytes[:])
_, wait1, err := fs.Store(ctx, reader, int64(len(randomBytes)), false)
if err != nil {
return fmt.Errorf("fileStore.Store: %v", err)
}
if err := wait1(ctx); err != nil {
return err
}
}
//according to old pull sync - if the node is outside of depth - it should have all chunks where po(chunk)==po(node)
time.Sleep(syncTime)
pivotLs := sim.MustNodeItem(pivot, bucketKeyLocalStore).(*localstore.DB)
verifyCorrectChunksOnPivot(t, chunkProx, pivotDepth, pivotLs)
return nil
})
if result.Error != nil {
t.Fatal(result.Error)
}
}
// verifyCorrectChunksOnPivot checks which chunks should be present on the
// pivot node from the perspective of the pivot node. All streams established
// should be presumed from the point of view of the pivot and presence of
// chunks should be assumed by po(chunk,uploader)
// for example, if the pivot has depth==1 and the po(pivot,uploader)==1, then
// all chunks that have po(chunk,uploader)==1 should be synced to the pivot
func verifyCorrectChunksOnPivot(t *testing.T, chunkProx map[string]chunkProxData, pivotDepth int, pivotLs *localstore.DB) {
t.Helper()
for _, v := range chunkProx {
// outside of depth
if v.uploaderNodeToPivotNodePO < pivotDepth {
// chunk PO to uploader == uploader node PO to pivot (i.e. chunk should be synced) - inclusive test
if v.chunkToUploaderPO == v.uploaderNodeToPivotNodePO {
//check that the chunk exists on the pivot when the chunkPo == uploaderPo
_, err := pivotLs.Get(context.Background(), chunk.ModeGetRequest, v.addr)
if err != nil {
t.Errorf("chunk errored. err %v uploaderNode %s poUploader %d uploaderToPivotPo %d chunk %s", err, v.uploaderNode.String(), v.chunkToUploaderPO, v.uploaderNodeToPivotNodePO, hex.EncodeToString(v.addr))
}
} else {
//chunk should not be synced - exclusion test
_, err := pivotLs.Get(context.Background(), chunk.ModeGetRequest, v.addr)
if err == nil {
t.Errorf("chunk did not error but should have. uploaderNode %s poUploader %d uploaderToPivotPo %d chunk %s", v.uploaderNode.String(), v.chunkToUploaderPO, v.uploaderNodeToPivotNodePO, hex.EncodeToString(v.addr))
}
}
}
}
}
type chunkProxData struct {
addr chunk.Address
uploaderNodeToPivotNodePO int
chunkToUploaderPO int
uploaderNode enode.ID
pivotPO int
}
func getAllRefs(testData []byte) (storage.AddressCollection, error) {
datadir, err := ioutil.TempDir("", "chunk-debug")
if err != nil {
return nil, fmt.Errorf("unable to create temp dir: %v", err)
}
defer os.RemoveAll(datadir)
fileStore, cleanup, err := storage.NewLocalFileStore(datadir, make([]byte, 32), chunk.NewTags())
if err != nil {
return nil, err
}
defer cleanup()
reader := bytes.NewReader(testData)
return fileStore.GetAllReferences(context.Background(), reader)
}
| ethersphere/go-ethereum | network/stream/syncing_test.go | GO | lgpl-3.0 | 24,602 |
<?php
/**
* @copyright Copyright (c) Metaways Infosystems GmbH, 2011
* @license LGPLv3, http://www.arcavias.com/en/license
* @package MShop
* @subpackage Order
*/
/**
* Default Manager Order service
*
* @package MShop
* @subpackage Order
*/
class MShop_Order_Manager_Base_Service_Default
extends MShop_Common_Manager_Abstract
implements MShop_Order_Manager_Base_Service_Interface
{
private $_searchConfig = array(
'order.base.service.id' => array(
'code' => 'order.base.service.id',
'internalcode' => 'mordbase."id"',
'internaldeps' => array( 'LEFT JOIN "mshop_order_base_service" AS mordbase ON ( mordba."id" = mordbase."baseid" )' ),
'label' => 'Order base service ID',
'type' => 'integer',
'internaltype' => MW_DB_Statement_Abstract::PARAM_INT,
'public' => false,
),
'order.base.service.siteid' => array(
'code' => 'order.base.service.siteid',
'internalcode' => 'mordbase."siteid"',
'label' => 'Order base service site ID',
'type' => 'integer',
'internaltype' => MW_DB_Statement_Abstract::PARAM_INT,
'public' => false,
),
'order.base.service.baseid' => array(
'code' => 'order.base.service.baseid',
'internalcode' => 'mordbase."baseid"',
'label' => 'Order base ID',
'type' => 'integer',
'internaltype' => MW_DB_Statement_Abstract::PARAM_INT,
'public' => false,
),
'order.base.service.serviceid' => array(
'code' => 'order.base.service.serviceid',
'internalcode' => 'mordbase."servid"',
'label' => 'Order base service original service ID',
'type' => 'string',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.type' => array(
'code' => 'order.base.service.type',
'internalcode' => 'mordbase."type"',
'label' => 'Order base service type',
'type' => 'string',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.code' => array(
'code' => 'order.base.service.code',
'internalcode' => 'mordbase."code"',
'label' => 'Order base service code',
'type' => 'string',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.name' => array(
'code' => 'order.base.service.name',
'internalcode' => 'mordbase."name"',
'label' => 'Order base service name',
'type' => 'string',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.mediaurl' => array(
'code'=>'order.base.service.mediaurl',
'internalcode'=>'mordbase."mediaurl"',
'label'=>'Order base service media url',
'type'=> 'string',
'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.price' => array(
'code' => 'order.base.service.price',
'internalcode' => 'mordbase."price"',
'label' => 'Order base service price',
'type' => 'decimal',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.costs' => array(
'code' => 'order.base.service.costs',
'internalcode' => 'mordbase."costs"',
'label' => 'Order base service shipping',
'type' => 'decimal',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.rebate' => array(
'code' => 'order.base.service.rebate',
'internalcode' => 'mordbase."rebate"',
'label' => 'Order base service rebate',
'type' => 'decimal',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.taxrate' => array(
'code' => 'order.base.service.taxrate',
'internalcode' => 'mordbase."taxrate"',
'label' => 'Order base service taxrate',
'type' => 'decimal',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.mtime' => array(
'code' => 'order.base.service.mtime',
'internalcode' => 'mordbase."mtime"',
'label' => 'Order base service modification time',
'type' => 'datetime',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.ctime'=> array(
'code'=>'order.base.service.ctime',
'internalcode'=>'mordbase."ctime"',
'label'=>'Order base service create date/time',
'type'=> 'datetime',
'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR
),
'order.base.service.editor'=> array(
'code'=>'order.base.service.editor',
'internalcode'=>'mordbase."editor"',
'label'=>'Order base service editor',
'type'=> 'string',
'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR
),
);
/**
* Initializes the object.
*
* @param MShop_Context_Item_Interface $context Context object
*/
public function __construct( MShop_Context_Item_Interface $context )
{
parent::__construct( $context );
$this->_setResourceName( 'db-order' );
}
/**
* Removes old entries from the storage.
*
* @param integer[] $siteids List of IDs for sites whose entries should be deleted
*/
public function cleanup( array $siteids )
{
$path = 'classes/order/manager/base/service/submanagers';
foreach( $this->_getContext()->getConfig()->get( $path, array( 'attribute' ) ) as $domain ) {
$this->getSubManager( $domain )->cleanup( $siteids );
}
$this->_cleanup( $siteids, 'mshop/order/manager/base/service/default/item/delete' );
}
/**
* Creates new order service item object.
*
* @return MShop_Order_Item_Base_Service_Interface New object
*/
public function createItem()
{
$context = $this->_getContext();
$priceManager = MShop_Factory::createManager( $context, 'price' );
$values = array( 'siteid'=> $context->getLocale()->getSiteId() );
return $this->_createItem( $priceManager->createItem(), $values );
}
/**
* Adds or updates an order base service item to the storage.
*
* @param MShop_Common_Item_Interface $item Order base service object
* @param boolean $fetch True if the new ID should be returned in the item
*/
public function saveItem( MShop_Common_Item_Interface $item, $fetch = true )
{
$iface = 'MShop_Order_Item_Base_Service_Interface';
if( !( $item instanceof $iface ) ) {
throw new MShop_Order_Exception( sprintf( 'Object is not of required type "%1$s"', $iface ) );
}
if( !$item->isModified() ) { return; }
$context = $this->_getContext();
$dbm = $context->getDatabaseManager();
$dbname = $this->_getResourceName();
$conn = $dbm->acquire( $dbname );
try
{
$id = $item->getId();
$price = $item->getPrice();
$path = 'mshop/order/manager/base/service/default/item/';
$path .= ( $id === null ) ? 'insert' : 'update';
$stmt = $this->_getCachedStatement( $conn, $path );
$stmt->bind(1, $item->getBaseId(), MW_DB_Statement_Abstract::PARAM_INT);
$stmt->bind(2, $context->getLocale()->getSiteId(), MW_DB_Statement_Abstract::PARAM_INT);
$stmt->bind(3, $item->getServiceId(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(4, $item->getType(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(5, $item->getCode(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(6, $item->getName(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(7, $item->getMediaUrl(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(8, $price->getValue(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(9, $price->getCosts(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(10, $price->getRebate(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(11, $price->getTaxRate(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(12, date('Y-m-d H:i:s', time()), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(13, $context->getEditor() );
if ( $id !== null ) {
$stmt->bind(14, $id, MW_DB_Statement_Abstract::PARAM_INT);
} else {
$stmt->bind(14, date( 'Y-m-d H:i:s', time() ), MW_DB_Statement_Abstract::PARAM_STR );// ctime
}
$stmt->execute()->finish();
if( $fetch === true )
{
if( $id === null ) {
$path = 'mshop/order/manager/base/service/default/item/newid';
$item->setId( $this->_newId( $conn, $context->getConfig()->get( $path, $path ) ) );
} else {
$item->setId($id);
}
}
$dbm->release( $conn, $dbname );
}
catch ( Exception $e )
{
$dbm->release( $conn, $dbname );
throw $e;
}
}
/**
* Removes multiple items specified by ids in the array.
*
* @param array $ids List of IDs
*/
public function deleteItems( array $ids )
{
$path = 'mshop/order/manager/base/service/default/item/delete';
$this->_deleteItems( $ids, $this->_getContext()->getConfig()->get( $path, $path ) );
}
/**
* Returns the order service item object for the given ID.
*
* @param integer $id Order service ID
* @param array $ref List of domains to fetch list items and referenced items for
* @return MShop_Order_Item_Base_Service_Interface Returns order base service item of the given id
* @throws MShop_Exception If item couldn't be found
*/
public function getItem( $id, array $ref = array() )
{
return $this->_getItem( 'order.base.service.id', $id, $ref );
}
/**
* Searches for order service items based on the given criteria.
*
* @param MW_Common_Criteria_Interface $search Search object containing the conditions
* @param array $ref Not used
* @param integer &$total Number of items that are available in total
* @return array List of items implementing MShop_Order_Item_Base_Service_Interface
*/
public function searchItems(MW_Common_Criteria_Interface $search, array $ref = array(), &$total = null)
{
$items = array();
$context = $this->_getContext();
$priceManager = MShop_Factory::createManager( $context, 'price' );
$dbm = $context->getDatabaseManager();
$dbname = $this->_getResourceName();
$conn = $dbm->acquire( $dbname );
try
{
$sitelevel = MShop_Locale_Manager_Abstract::SITE_SUBTREE;
$cfgPathSearch = 'mshop/order/manager/base/service/default/item/search';
$cfgPathCount = 'mshop/order/manager/base/service/default/item/count';
$required = array( 'order.base.service' );
$results = $this->_searchItems( $conn, $search, $cfgPathSearch, $cfgPathCount,
$required, $total, $sitelevel );
try
{
while( ( $row = $results->fetch() ) !== false )
{
$price = $priceManager->createItem();
$price->setValue($row['price']);
$price->setRebate($row['rebate']);
$price->setCosts($row['costs']);
$price->setTaxRate($row['taxrate']);
$items[ $row['id'] ] = array( 'price' => $price, 'item' => $row );
}
}
catch( Exception $e )
{
$results->finish();
throw $e;
}
$dbm->release( $conn, $dbname );
}
catch( Exception $e )
{
$dbm->release( $conn, $dbname );
throw $e;
}
$result = array();
$attributes = $this->_getAttributeItems( array_keys( $items ) );
foreach ( $items as $id => $row )
{
$attrList = array();
if( isset( $attributes[$id] ) ) {
$attrList = $attributes[$id];
}
$result[ $id ] = $this->_createItem( $row['price'], $row['item'], $attrList );
}
return $result;
}
/**
* Returns the search attributes that can be used for searching.
*
* @param boolean $withsub Return also attributes of sub-managers if true
* @return array List of attributes implementing MW_Common_Criteria_Attribute_Interface
*/
public function getSearchAttributes($withsub = true)
{
/** classes/order/manager/base/service/submanagers
* List of manager names that can be instantiated by the order base service manager
*
* Managers provide a generic interface to the underlying storage.
* Each manager has or can have sub-managers caring about particular
* aspects. Each of these sub-managers can be instantiated by its
* parent manager using the getSubManager() method.
*
* The search keys from sub-managers can be normally used in the
* manager as well. It allows you to search for items of the manager
* using the search keys of the sub-managers to further limit the
* retrieved list of items.
*
* @param array List of sub-manager names
* @since 2014.03
* @category Developer
*/
$path = 'classes/order/manager/base/service/submanagers';
return $this->_getSearchAttributes( $this->_searchConfig, $path, array( 'attribute' ), $withsub );
}
/**
* Returns a new manager for order service extensions.
*
* @param string $manager Name of the sub manager type in lower case
* @param string|null $name Name of the implementation (from configuration or "Default" if null)
* @return MShop_Common_Manager_Interface Manager for different extensions, e.g attribute
*/
public function getSubManager($manager, $name = null)
{
/** classes/order/manager/base/service/name
* Class name of the used order base service manager implementation
*
* Each default order base service manager can be replaced by an alternative imlementation.
* To use this implementation, you have to set the last part of the class
* name as configuration value so the manager factory knows which class it
* has to instantiate.
*
* For example, if the name of the default class is
*
* MShop_Order_Manager_Base_Service_Default
*
* and you want to replace it with your own version named
*
* MShop_Order_Manager_Base_Service_Myservice
*
* then you have to set the this configuration option:
*
* classes/order/manager/base/service/name = Myservice
*
* The value is the last part of your own class name and it's case sensitive,
* so take care that the configuration value is exactly named like the last
* part of the class name.
*
* The allowed characters of the class name are A-Z, a-z and 0-9. No other
* characters are possible! You should always start the last part of the class
* name with an upper case character and continue only with lower case characters
* or numbers. Avoid chamel case names like "MyService"!
*
* @param string Last part of the class name
* @since 2014.03
* @category Developer
*/
/** mshop/order/manager/base/service/decorators/excludes
* Excludes decorators added by the "common" option from the order base service manager
*
* Decorators extend the functionality of a class by adding new aspects
* (e.g. log what is currently done), executing the methods of the underlying
* class only in certain conditions (e.g. only for logged in users) or
* modify what is returned to the caller.
*
* This option allows you to remove a decorator added via
* "mshop/common/manager/decorators/default" before they are wrapped
* around the order base service manager.
*
* mshop/order/manager/base/service/decorators/excludes = array( 'decorator1' )
*
* This would remove the decorator named "decorator1" from the list of
* common decorators ("MShop_Common_Manager_Decorator_*") added via
* "mshop/common/manager/decorators/default" for the order base service manager.
*
* @param array List of decorator names
* @since 2014.03
* @category Developer
* @see mshop/common/manager/decorators/default
* @see mshop/order/manager/base/service/decorators/global
* @see mshop/order/manager/base/service/decorators/local
*/
/** mshop/order/manager/base/service/decorators/global
* Adds a list of globally available decorators only to the order base service manager
*
* Decorators extend the functionality of a class by adding new aspects
* (e.g. log what is currently done), executing the methods of the underlying
* class only in certain conditions (e.g. only for logged in users) or
* modify what is returned to the caller.
*
* This option allows you to wrap global decorators
* ("MShop_Common_Manager_Decorator_*") around the order base service manager.
*
* mshop/order/manager/base/service/decorators/global = array( 'decorator1' )
*
* This would add the decorator named "decorator1" defined by
* "MShop_Common_Manager_Decorator_Decorator1" only to the order controller.
*
* @param array List of decorator names
* @since 2014.03
* @category Developer
* @see mshop/common/manager/decorators/default
* @see mshop/order/manager/base/service/decorators/excludes
* @see mshop/order/manager/base/service/decorators/local
*/
/** mshop/order/manager/base/service/decorators/local
* Adds a list of local decorators only to the order base service manager
*
* Decorators extend the functionality of a class by adding new aspects
* (e.g. log what is currently done), executing the methods of the underlying
* class only in certain conditions (e.g. only for logged in users) or
* modify what is returned to the caller.
*
* This option allows you to wrap local decorators
* ("MShop_Common_Manager_Decorator_*") around the order base service manager.
*
* mshop/order/manager/base/service/decorators/local = array( 'decorator2' )
*
* This would add the decorator named "decorator2" defined by
* "MShop_Common_Manager_Decorator_Decorator2" only to the order
* controller.
*
* @param array List of decorator names
* @since 2014.03
* @category Developer
* @see mshop/common/manager/decorators/default
* @see mshop/order/manager/base/service/decorators/excludes
* @see mshop/order/manager/base/service/decorators/global
*/
return $this->_getSubManager( 'order', 'base/service/' . $manager, $name );
}
/**
* Creates a new order service item object initialized with given parameters.
*
* @param MShop_Price_Item_Interface $price Price object
* @param array $values Associative list of values from the database
* @param array $attributes List of order service attribute items
* @return MShop_Order_Item_Base_Service_Interface Order item service object
*/
protected function _createItem( MShop_Price_Item_Interface $price,
array $values = array(), array $attributes = array() )
{
return new MShop_Order_Item_Base_Service_Default( $price, $values, $attributes );
}
/**
* Searches for attribute items connected with order service item.
*
* @param string[] $ids List of order service item IDs
* @return array List of items implementing MShop_Order_Item_Base_Service_Attribute_Interface
*/
protected function _getAttributeItems( $ids )
{
$manager = $this->getSubManager( 'attribute' );
$search = $manager->createSearch();
$search->setConditions( $search->compare( '==', 'order.base.service.attribute.serviceid', $ids ) );
$search->setSortations( array( $search->sort( '+', 'order.base.service.attribute.code' ) ) );
$search->setSlice( 0, 0x7fffffff );
$result = array();
foreach ($manager->searchItems( $search ) as $item) {
$result[ $item->getServiceId() ][ $item->getId() ] = $item;
}
return $result;
}
}
| Arcavias/arcavias-core | lib/mshoplib/src/MShop/Order/Manager/Base/Service/Default.php | PHP | lgpl-3.0 | 18,575 |
//+======================================================================
// $Source$
//
// Project: Tango
//
// Description: java source code for the TANGO client/server API.
//
// $Author: pascal_verdier $
//
// Copyright (C) : 2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,
// European Synchrotron Radiation Facility
// BP 220, Grenoble 38043
// FRANCE
//
// This file is part of Tango.
//
// Tango 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.
//
// Tango 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 Tango. If not, see <http://www.gnu.org/licenses/>.
//
// $Revision: 25297 $
//
//-======================================================================
package fr.esrf.TangoApi;
import fr.esrf.Tango.DevCmdInfo;
import fr.esrf.Tango.DevFailed;
import fr.esrf.TangoDs.Except;
public class DevVarCmdArray
{
/**
* manage an array of CommandInfo objects.
*/
protected CommandInfo[] cmd_info;
/**
* The device name
*/
protected String devname;
//======================================================
//======================================================
public DevVarCmdArray(String devname, DevCmdInfo[] info)
{
this.devname = devname;
cmd_info = new CommandInfo[info.length];
for (int i=0 ; i<info.length ; i++)
cmd_info[i] = new CommandInfo(info[i]);
}
//======================================================
//======================================================
public DevVarCmdArray(String devname, CommandInfo[] info)
{
this.devname = devname;
this.cmd_info = info;
}
//======================================================
//======================================================
public int size()
{
return cmd_info.length;
}
//======================================================
//======================================================
public CommandInfo elementAt(int i)
{
return cmd_info[i];
}
//======================================================
//======================================================
public CommandInfo[] getInfoArray()
{
return cmd_info;
}
//======================================================
//======================================================
public int argoutType(String cmdname) throws DevFailed
{
for (CommandInfo info : cmd_info)
if (cmdname.equals(info.cmd_name))
return info.out_type;
Except.throw_non_supported_exception("TACO_CMD_UNAVAILABLE",
cmdname + " command unknown for device " + devname,
"DevVarCmdArray.argoutType()");
return -1;
}
//======================================================
//======================================================
public int arginType(String cmdname) throws DevFailed
{
for (CommandInfo info : cmd_info)
if (cmdname.equals(info.cmd_name))
return info.in_type;
Except.throw_non_supported_exception("TACO_CMD_UNAVAILABLE",
cmdname + " command unknown for device " + devname,
"DevVarCmdArray.arginType()");
return -1;
}
//======================================================
//======================================================
public String toString()
{
StringBuffer sb = new StringBuffer();
for (CommandInfo info : cmd_info)
{
sb.append(info.cmd_name);
sb.append("(").append(info.in_type);
sb.append(", ").append(info.out_type).append(")\n");
}
return sb.toString();
}
}
| tango-controls/JTango | dao/src/main/java/fr/esrf/TangoApi/DevVarCmdArray.java | Java | lgpl-3.0 | 3,880 |
/*
* SonarLint for Visual Studio
* Copyright (C) 2016-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.
*/
using System;
using System.Collections.Generic;
using EnvDTE;
using FluentAssertions;
using VsShell = Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SonarLint.VisualStudio.CFamily.Analysis;
using SonarLint.VisualStudio.Core;
using SonarLint.VisualStudio.Core.CFamily;
using SonarLint.VisualStudio.Integration.Vsix.CFamily;
using SonarLint.VisualStudio.Integration.Vsix.CFamily.VcxProject;
using static SonarLint.VisualStudio.Integration.Vsix.CFamily.UnitTests.CFamilyTestUtility;
using System.Threading.Tasks;
using EnvDTE80;
using Microsoft.VisualStudio.Shell.Interop;
namespace SonarLint.VisualStudio.Integration.UnitTests.CFamily
{
[TestClass]
public class VcxRequestFactoryTests
{
private static ProjectItem DummyProjectItem = Mock.Of<ProjectItem>();
private static CFamilyAnalyzerOptions DummyAnalyzerOptions = new CFamilyAnalyzerOptions();
[TestMethod]
public void MefCtor_CheckIsExported()
{
MefTestHelpers.CheckTypeCanBeImported<VcxRequestFactory, IRequestFactory>(null, new[]
{
MefTestHelpers.CreateExport<VsShell.SVsServiceProvider>(Mock.Of<IServiceProvider>()),
MefTestHelpers.CreateExport<ICFamilyRulesConfigProvider>(Mock.Of<ICFamilyRulesConfigProvider>()),
MefTestHelpers.CreateExport<ILogger>(Mock.Of<ILogger>())
});
}
[TestMethod]
public async Task TryGet_RunsOnUIThread()
{
var fileConfigProvider = new Mock<IFileConfigProvider>();
var threadHandling = new Mock<IThreadHandling>();
threadHandling.Setup(x => x.RunOnUIThread(It.IsAny<Action>()))
.Callback<Action>(op =>
{
// Try to check that the product code is executed inside the "RunOnUIThread" call
fileConfigProvider.Invocations.Count.Should().Be(0);
op();
fileConfigProvider.Invocations.Count.Should().Be(1);
});
var testSubject = CreateTestSubject(projectItem: DummyProjectItem,
threadHandling: threadHandling.Object,
fileConfigProvider: fileConfigProvider.Object);
var request = await testSubject.TryCreateAsync("any", new CFamilyAnalyzerOptions());
threadHandling.Verify(x => x.RunOnUIThread(It.IsAny<Action>()), Times.Once);
threadHandling.Verify(x => x.ThrowIfNotOnUIThread(), Times.Once);
}
[TestMethod]
public async Task TryGet_NoProjectItem_Null()
{
var testSubject = CreateTestSubject(projectItem: null);
var request = await testSubject.TryCreateAsync("path", new CFamilyAnalyzerOptions());
request.Should().BeNull();
}
[TestMethod]
public async Task TryGet_NoFileConfig_Null()
{
const string analyzedFilePath = "path";
var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, null);
var testSubject = CreateTestSubject(DummyProjectItem, fileConfigProvider: fileConfigProvider.Object);
var request = await testSubject.TryCreateAsync("path", DummyAnalyzerOptions);
request.Should().BeNull();
fileConfigProvider.Verify(x=> x.Get(DummyProjectItem, analyzedFilePath, DummyAnalyzerOptions), Times.Once);
}
[TestMethod]
public async Task TryGet_RequestCreatedWithNoDetectedLanguage_Null()
{
const string analyzedFilePath = "c:\\notCFamilyFile.txt";
var fileConfig = CreateDummyFileConfig(analyzedFilePath);
var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object);
var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>();
var testSubject = CreateTestSubject(DummyProjectItem,
fileConfigProvider: fileConfigProvider.Object,
cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object);
var request = await testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions);
request.Should().BeNull();
fileConfig.VerifyGet(x => x.AbsoluteFilePath, Times.Once);
cFamilyRulesConfigProvider.Invocations.Count.Should().Be(0);
}
[TestMethod]
public async Task TryGet_FailureParsing_NonCriticialException_Null()
{
const string analyzedFilePath = "c:\\test.cpp";
var fileConfig = CreateDummyFileConfig(analyzedFilePath);
var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object);
var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>();
cFamilyRulesConfigProvider
.Setup(x => x.GetRulesConfiguration(SonarLanguageKeys.CPlusPlus))
.Throws<NotImplementedException>();
var logger = new TestLogger();
var testSubject = CreateTestSubject(DummyProjectItem,
fileConfigProvider: fileConfigProvider.Object,
cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object,
logger: logger);
var request = await testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions);
request.Should().BeNull();
logger.AssertPartialOutputStringExists(nameof(NotImplementedException));
}
[TestMethod]
public void TryGet_FailureParsing_CriticalException_ExceptionThrown()
{
const string analyzedFilePath = "c:\\test.cpp";
var fileConfig = CreateDummyFileConfig(analyzedFilePath);
var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object);
var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>();
cFamilyRulesConfigProvider
.Setup(x => x.GetRulesConfiguration(SonarLanguageKeys.CPlusPlus))
.Throws<StackOverflowException>();
var testSubject = CreateTestSubject(DummyProjectItem,
fileConfigProvider: fileConfigProvider.Object,
cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object);
Func<Task> act = () => testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions);
act.Should().ThrowExactly<StackOverflowException>();
}
[TestMethod]
public async Task TryGet_IRequestPropertiesAreSet()
{
var analyzerOptions = new CFamilyAnalyzerOptions();
var rulesConfig = Mock.Of<ICFamilyRulesConfig>();
var request = await GetSuccessfulRequest(analyzerOptions, "d:\\xxx\\fileToAnalyze.cpp", rulesConfig);
request.Should().NotBeNull();
request.Context.File.Should().Be("d:\\xxx\\fileToAnalyze.cpp");
request.Context.PchFile.Should().Be(SubProcessFilePaths.PchFilePath);
request.Context.AnalyzerOptions.Should().BeSameAs(analyzerOptions);
request.Context.RulesConfiguration.Should().BeSameAs(rulesConfig);
}
[TestMethod]
public async Task TryGet_FileConfigIsSet()
{
var request = await GetSuccessfulRequest();
request.Should().NotBeNull();
request.FileConfig.Should().NotBeNull();
}
[TestMethod]
public async Task TryGet_NonHeaderFile_IsSupported()
{
var request = await GetSuccessfulRequest();
request.Should().NotBeNull();
(request.Flags & Request.MainFileIsHeader).Should().Be(0);
}
[TestMethod]
public async Task TryGet_HeaderFile_IsSupported()
{
var projectItemConfig = new ProjectItemConfig { ItemType = "ClInclude" };
var projectItemMock = CreateMockProjectItem("c:\\foo\\xxx.vcxproj", projectItemConfig);
var fileConfig = CreateDummyFileConfig("c:\\dummy\\file.h");
fileConfig.Setup(x => x.CompileAs).Returns("CompileAsCpp");
fileConfig.Setup(x => x.ItemType).Returns("ClInclude");
var request = await GetSuccessfulRequest(fileToAnalyze: "c:\\dummy\\file.h", projectItem: projectItemMock.Object, fileConfig: fileConfig);
request.Should().NotBeNull();
(request.Flags & Request.MainFileIsHeader).Should().NotBe(0);
}
[TestMethod]
public async Task TryGet_NoAnalyzerOptions_RequestCreatedWithoutOptions()
{
var request = await GetSuccessfulRequest(analyzerOptions: null);
request.Should().NotBeNull();
(request.Flags & Request.CreateReproducer).Should().Be(0);
(request.Flags & Request.BuildPreamble).Should().Be(0);
request.Context.AnalyzerOptions.Should().BeNull();
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithReproducerEnabled_RequestCreatedWithReproducerFlag()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreateReproducer = true });
request.Should().NotBeNull();
(request.Flags & Request.CreateReproducer).Should().NotBe(0);
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithoutReproducerEnabled_RequestCreatedWithoutReproducerFlag()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreateReproducer = false });
request.Should().NotBeNull();
(request.Flags & Request.CreateReproducer).Should().Be(0);
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithPCH_RequestCreatedWithPCHFlag()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = true });
request.Should().NotBeNull();
(request.Flags & Request.BuildPreamble).Should().NotBe(0);
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithoutPCH_RequestCreatedWithoutPCHFlag()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = false });
request.Should().NotBeNull();
(request.Flags & Request.BuildPreamble).Should().Be(0);
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithPCH_RequestOptionsNotSet()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = true });
request.Should().NotBeNull();
request.Context.RulesConfiguration.Should().BeNull();
request.Options.Should().BeEmpty();
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithoutPCH_RequestOptionsAreSet()
{
var rulesProtocolFormat = new RuleConfigProtocolFormat("some profile", new Dictionary<string, string>
{
{"rule1", "param1"},
{"rule2", "param2"}
});
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = false }, protocolFormat: rulesProtocolFormat);
request.Should().NotBeNull();
request.Context.RulesConfiguration.Should().NotBeNull();
request.Options.Should().BeEquivalentTo(
"internal.qualityProfile=some profile",
"rule1=param1",
"rule2=param2");
}
private static Mock<IFileConfigProvider> SetupFileConfigProvider(ProjectItem projectItem,
CFamilyAnalyzerOptions analyzerOptions,
string analyzedFilePath,
IFileConfig fileConfigToReturn)
{
var fileConfigProvider = new Mock<IFileConfigProvider>();
fileConfigProvider
.Setup(x => x.Get(projectItem, analyzedFilePath, analyzerOptions))
.Returns(fileConfigToReturn);
return fileConfigProvider;
}
private VcxRequestFactory CreateTestSubject(ProjectItem projectItem,
ICFamilyRulesConfigProvider cFamilyRulesConfigProvider = null,
IFileConfigProvider fileConfigProvider = null,
IRulesConfigProtocolFormatter rulesConfigProtocolFormatter = null,
IThreadHandling threadHandling = null,
ILogger logger = null)
{
var serviceProvider = CreateServiceProviderReturningProjectItem(projectItem);
cFamilyRulesConfigProvider ??= Mock.Of<ICFamilyRulesConfigProvider>();
rulesConfigProtocolFormatter ??= Mock.Of<IRulesConfigProtocolFormatter>();
fileConfigProvider ??= Mock.Of<IFileConfigProvider>();
threadHandling ??= new NoOpThreadHandler();
logger ??= Mock.Of<ILogger>();
return new VcxRequestFactory(serviceProvider.Object,
cFamilyRulesConfigProvider,
rulesConfigProtocolFormatter,
fileConfigProvider,
logger,
threadHandling);
}
private static Mock<IServiceProvider> CreateServiceProviderReturningProjectItem(ProjectItem projectItemToReturn)
{
var mockSolution = new Mock<Solution>();
mockSolution.Setup(s => s.FindProjectItem(It.IsAny<string>())).Returns(projectItemToReturn);
var mockDTE = new Mock<DTE2>();
mockDTE.Setup(d => d.Solution).Returns(mockSolution.Object);
var mockServiceProvider = new Mock<IServiceProvider>();
mockServiceProvider.Setup(s => s.GetService(typeof(SDTE))).Returns(mockDTE.Object);
return mockServiceProvider;
}
private async Task<Request> GetSuccessfulRequest(CFamilyAnalyzerOptions analyzerOptions = null,
string fileToAnalyze = "c:\\foo\\file.cpp",
ICFamilyRulesConfig rulesConfig = null,
ProjectItem projectItem = null,
Mock<IFileConfig> fileConfig = null,
RuleConfigProtocolFormat protocolFormat = null)
{
rulesConfig ??= Mock.Of<ICFamilyRulesConfig>();
var rulesConfigProviderMock = new Mock<ICFamilyRulesConfigProvider>();
rulesConfigProviderMock
.Setup(x => x.GetRulesConfiguration(It.IsAny<string>()))
.Returns(rulesConfig);
projectItem ??= Mock.Of<ProjectItem>();
fileConfig ??= CreateDummyFileConfig(fileToAnalyze);
var fileConfigProvider = SetupFileConfigProvider(projectItem, analyzerOptions, fileToAnalyze, fileConfig.Object);
protocolFormat ??= new RuleConfigProtocolFormat("qp", new Dictionary<string, string>());
var rulesConfigProtocolFormatter = new Mock<IRulesConfigProtocolFormatter>();
rulesConfigProtocolFormatter
.Setup(x => x.Format(rulesConfig))
.Returns(protocolFormat);
var testSubject = CreateTestSubject(projectItem,
rulesConfigProviderMock.Object,
fileConfigProvider.Object,
rulesConfigProtocolFormatter.Object);
return await testSubject.TryCreateAsync(fileToAnalyze, analyzerOptions) as Request;
}
private Mock<IFileConfig> CreateDummyFileConfig(string filePath)
{
var fileConfig = new Mock<IFileConfig>();
fileConfig.SetupGet(x => x.PlatformName).Returns("Win32");
fileConfig.SetupGet(x => x.AdditionalIncludeDirectories).Returns("");
fileConfig.SetupGet(x => x.ForcedIncludeFiles).Returns("");
fileConfig.SetupGet(x => x.PrecompiledHeader).Returns("");
fileConfig.SetupGet(x => x.UndefinePreprocessorDefinitions).Returns("");
fileConfig.SetupGet(x => x.PreprocessorDefinitions).Returns("");
fileConfig.SetupGet(x => x.CompileAs).Returns("");
fileConfig.SetupGet(x => x.CompileAsManaged).Returns("");
fileConfig.SetupGet(x => x.RuntimeLibrary).Returns("");
fileConfig.SetupGet(x => x.ExceptionHandling).Returns("");
fileConfig.SetupGet(x => x.EnableEnhancedInstructionSet).Returns("");
fileConfig.SetupGet(x => x.BasicRuntimeChecks).Returns("");
fileConfig.SetupGet(x => x.LanguageStandard).Returns("");
fileConfig.SetupGet(x => x.AdditionalOptions).Returns("");
fileConfig.SetupGet(x => x.CompilerVersion).Returns("1.2.3.4");
fileConfig.SetupGet(x => x.AbsoluteProjectPath).Returns("c:\\test.vcxproj");
fileConfig.SetupGet(x => x.AbsoluteFilePath).Returns(filePath);
return fileConfig;
}
}
}
| SonarSource/sonarlint-visualstudio | src/Integration.Vsix.UnitTests/CFamily/VcxRequestFactoryTests.cs | C# | lgpl-3.0 | 17,901 |
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2019 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* 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/>.
* #L%
*/
package org.alfresco.util;
import java.io.IOException;
import java.io.LineNumberReader;
import org.springframework.core.io.support.EncodedResource;
public abstract class DBScriptUtil
{
private static final String DEFAULT_SCRIPT_COMMENT_PREFIX = "--";
/**
* Read a script from the provided EncodedResource and build a String containing
* the lines.
*
* @param resource
* the resource (potentially associated with a specific encoding) to
* load the SQL script from
* @return a String containing the script lines
*/
public static String readScript(EncodedResource resource) throws IOException
{
return readScript(resource, DEFAULT_SCRIPT_COMMENT_PREFIX);
}
/**
* Read a script from the provided EncodedResource, using the supplied line
* comment prefix, and build a String containing the lines.
*
* @param resource
* the resource (potentially associated with a specific encoding) to
* load the SQL script from
* @param lineCommentPrefix
* the prefix that identifies comments in the SQL script (typically
* "--")
* @return a String containing the script lines
*/
private static String readScript(EncodedResource resource, String lineCommentPrefix) throws IOException
{
LineNumberReader lineNumberReader = new LineNumberReader(resource.getReader());
try
{
return readScript(lineNumberReader, lineCommentPrefix);
}
finally
{
lineNumberReader.close();
}
}
/**
* Read a script from the provided LineNumberReader, using the supplied line
* comment prefix, and build a String containing the lines.
*
* @param lineNumberReader
* the LineNumberReader containing the script to be processed
* @param lineCommentPrefix
* the prefix that identifies comments in the SQL script (typically
* "--")
* @return a String containing the script lines
*/
private static String readScript(LineNumberReader lineNumberReader, String lineCommentPrefix) throws IOException
{
String statement = lineNumberReader.readLine();
StringBuilder scriptBuilder = new StringBuilder();
while (statement != null)
{
if (lineCommentPrefix != null && !statement.startsWith(lineCommentPrefix))
{
if (scriptBuilder.length() > 0)
{
scriptBuilder.append('\n');
}
scriptBuilder.append(statement);
}
statement = lineNumberReader.readLine();
}
return scriptBuilder.toString();
}
}
| Alfresco/alfresco-repository | src/main/java/org/alfresco/util/DBScriptUtil.java | Java | lgpl-3.0 | 3,822 |
#!/usr/bin/env python
from string import punctuation
import argparse
import fnmatch
import os
import shutil
import sys
import json
sys.path.insert(1, '/var/www/bedrock/')
sys.path.insert(0, '/var/www/bedrock/src/')
import analytics.utils
import dataloader.utils
import visualization.utils
from multiprocessing import Queue
#function to determine if the file being checked has the appropriate imports
def find_imports(fileToCheck, desiredInterface):
importedList = []
asterikFound = False
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
newFront = line.find("import") #finds the first occurence of the word import on the line
if newFront != -1: #an occurence of import has been found
line = line[newFront + 7:] #sets line to now start at the word after import
possibleAs = line.find(" as") #used to find import states that have the structure (from x import y as z)
if possibleAs != -1:
line = line[possibleAs + 4:]
if line.find("*") != -1 and len(line) == 2: #if the import is just the *
importedList.extend(line)
asterikFound = True
line =[word.strip(punctuation) for word in line.split()] #correctly splits the inputs based on puncuation
importedList.extend(line) #creates a single list of all the imports
if desiredInterface == 1:
if "Algorithm" not in importedList:
return "Missing the Algorithm input, can be fixed using 'from ..analytics import Algorithm'.\n"
else:
return ""
elif desiredInterface == 2:
if "*" not in importedList:
return "Missing the * input, can be fixed using 'from visualization.utils import *'.\n"
else:
return ""
elif desiredInterface == 3:
if "*" not in importedList:
return "Missing the * input, can be fixed using 'from dataloader.utils import *'.\n"
else:
return ""
elif desiredInterface == 4:
if "*" not in importedList:
return "Missing the * input, can be fixed using 'from dataloader.utils import *'\n"
else:
return ""
def find_class(fileToCheck, desiredInterface):
classesList = []
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
newFront = line.find("class")
newEnd = line.find(")")
if newFront == 0:
line = line[newFront + 6: newEnd + 1]
line.split()
classesList.append(line)
return classesList
def find_functions(fileToCheck, desiredInterface):
functionsList_with_inputs = []
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
newFront = line.find("def")
newEnd = line.find(")")
if newFront != -1:
line = line[newFront + 3: newEnd + 1]
line.split()
functionsList_with_inputs.append(line)
return functionsList_with_inputs
def compare_fuctions(fileToCheck, desiredInterface):
fList = find_functions(fileToCheck, desiredInterface)
if desiredInterface == 1:
if " __init__(self)" not in fList or " compute(self, filepath, **kwargs)" not in fList:
return "Function/s and/or specific input/s missing in this file.\n"
else:
return ""
elif desiredInterface == 2:
if " __init__(self)" not in fList or " initialize(self, inputs)" not in fList or " create(self)" not in fList:
return "Function/s and/or specific inputs/s missing in this file.\n"
else:
return ""
elif desiredInterface == 3:
if " __init__(self)" not in fList or " explore(self, filepath)" not in fList or " ingest(self, posted_data, src)" not in fList:
return "Function/s and/or specific input/s missing in this file.\n"
else:
return ""
elif desiredInterface == 4:
if " __init__(self)" not in fList or (" check(self, name, sample)" not in fList and " check(self, name, col)" not in fList) or " apply(self, conf)" not in fList:
return "Function/s and/or specific input/s missing in this file.\n"
else:
return ""
def inheritance_check(fileToCheck, desiredInterface):
class_name_list = find_class(fileToCheck, desiredInterface)
inhertiance_name = ""
if (len(class_name_list) > 0):
if (desiredInterface == 1 and len(class_name_list) > 1):
inhertiance_name = class_name_list[0]
elif (len(class_name_list) > 1):
inhertiance_name = class_name_list[len(class_name_list) - 1]
else:
inhertiance_name = class_name_list[0]
newFront = inhertiance_name.find("(")
newEnd = inhertiance_name.find(")")
inhertiance_name = inhertiance_name[newFront + 1:newEnd]
if desiredInterface == 1:
if inhertiance_name != "Algorithm":
return "Class must inherit from the Algorithm super class.\n"
else:
return ""
elif desiredInterface == 2:
if inhertiance_name != "Visualization":
return "Class must inherit from the Visualization super class.\n"
else:
return ""
elif desiredInterface == 3:
if inhertiance_name != "Ingest":
return "Class must inherit from the Ingest super class.\n"
else:
return ""
elif desiredInterface == 4:
if inhertiance_name != "Filter":
return "Class must inherit from the Filter super class.\n"
else:
return ""
else:
return "There are no classes in this file.\n"
def validate_file_name(fileToCheck, desiredInterface):
class_name_list = find_class(fileToCheck, desiredInterface)
class_name = ""
if (len(class_name_list) > 0):
if (desiredInterface == 1 and len(class_name_list) > 1):
class_name = class_name_list[0]
elif (len(class_name_list) > 1):
class_name = class_name_list[len(class_name_list) - 1]
else:
class_name = class_name_list[0]
trim = class_name.find("(")
class_name = class_name[:trim]
returnsList = list_returns(fileToCheck, desiredInterface)
superStament = []
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
newFront = line.find("super")
if newFront != -1:
trimFront = line.find("(")
trimBack = line.find(",")
line = line[trimFront + 1: trimBack]
superStament.append(line)
if class_name not in superStament:
return "File name does not match Class name\n"
else:
return ""
def list_returns(fileToCheck, desiredInterface):
returnsList = []
newLine = ""
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
if line.find("#") == -1:
newFront = line.find("return")
if newFront != -1:
possibleErrorMessageCheck1 = line.find("'")
bracketBefore = line.find("{")
lastBracket = line.find("}")
newLine = line[possibleErrorMessageCheck1:]
possibleErrorMessageCheck2 = newLine.find(" ")
if possibleErrorMessageCheck2 == -1:
line = line[newFront + 7:]
line.split()
line = [word.strip(punctuation) for word in line.split()]
returnsList.extend(line)
elif possibleErrorMessageCheck1 == bracketBefore + 1:
line = line[newFront + 7:lastBracket + 1]
line.split()
returnsList.append(line)
return returnsList
def check_return_values(fileToCheck, desiredInterface):
listOfReturns = list_returns(fileToCheck, desiredInterface)
listOfClasses = find_class(fileToCheck, desiredInterface)
firstElement = listOfClasses[0]
for elem in listOfClasses:
cutOff = elem.find("(")
if cutOff != -1:
elem = elem[:cutOff]
firstElement = elem
listOfClasses[0] = firstElement
if desiredInterface == 1:
listOfFunctions = find_functions(fileToCheck, desiredInterface)
if len(listOfFunctions) == 2 and len(listOfReturns) > 0:
return "Too many return values in this file.\n"
else:
return ""
elif desiredInterface == 2:
if len(listOfReturns) > 1:
if listOfClasses[0] not in listOfReturns or listOfReturns[1].find("data") == -1 or listOfReturns[1].find("type") == -1 or listOfReturns[1].find("id") == -1:
return "Missing or incorrectly named return values.\n"
else:
return ""
elif listOfReturns[0].find("data") == -1 or listOfReturns[0].find("type") == -1 or listOfReturns[0].find("id") == -1:
return "Missing or incorrectly named return values.\n"
else:
return ""
elif desiredInterface == 3:
if ("schema" not in listOfReturns and "schemas" not in listOfReturns and "collection:ret" not in listOfReturns) or "error" not in listOfReturns or "matrices" not in listOfReturns:
return "Missing or incorrectly named return values.\n"
else:
return ""
elif desiredInterface == 4:
if ("True" not in listOfReturns and "False" not in listOfReturns) or ("matrix" not in listOfReturns and "None" not in listOfReturns):
return "Missing or incorrectly named return values"
else:
return ""
def hard_type_check_return(fileToCheck, desiredInterface, my_dir, output_directory, filter_specs):
specificErrorMessage = ""
queue = Queue()
lastOccurence = fileToCheck.rfind("/")
file_name = fileToCheck[lastOccurence + 1:len(fileToCheck) - 3]
print filter_specs
if desiredInterface == 1:
file_metaData = analytics.utils.get_metadata(file_name)
elif desiredInterface == 2:
file_metaData = visualization.utils.get_metadata(file_name)
elif desiredInterface == 3:
file_metaData = dataloader.utils.get_metadata(file_name, "ingest")
elif desiredInterface == 4:
file_metaData = dataloader.utils.get_metadata(file_name, "filters")
inputList = []
if desiredInterface != 3 and desiredInterface != 4:
for elem in file_metaData['inputs']:
inputList.append(elem)
inputDict = create_input_dict(my_dir, inputList)
if desiredInterface == 1:
count = 0
computeResult = analytics.utils.run_analysis(queue, file_name, file_metaData['parameters'], inputDict, output_directory, "Result")
for file in os.listdir(my_dir):
if fnmatch.fnmatch(file, "*.csv") or fnmatch.fnmatch(file, ".json"):
count += 1
if (count < 1):
specificErrorMessage += "Missing .csv or .json file, the compute function must create a new .csv or .json file."
for file_name in os.listdir(output_directory):
os.remove(os.path.join(output_directory, file_name))
elif desiredInterface == 2:
createResult = visualization.utils.generate_vis(file_name, inputDict, file_metaData['parameters'])
if (type(createResult) != dict):
specificErrorMessage += "Missing a dict return, create function must return a dict item."
elif desiredInterface == 3:
filter_specs_dict = json.loads(str(filter_specs))
exploreResult = dataloader.utils.explore(file_name, my_dir, [])
exploreResultList = list(exploreResult)
count = 0
typeOfMatrix = []
matrix = ""
nameOfSource = ""
filterOfMatrix = []
for elem in exploreResult:
if type(elem) == dict:
for key in elem.keys():
nameOfSource = str(key)
if len(elem.values()) == 1:
for value in elem.values():
while count < len(value):
for item in value[count].keys():
if item == "type":
matrix = str(value[count]['type'])
matrix = matrix[2:len(matrix) - 2]
typeOfMatrix.append(matrix)
if item == "key_usr":
filterOfMatrix.append(str(value[count]['key_usr']))
count += 1
typeListExplore = []
posted_data = {
'matrixFilters':{},
'matrixFeatures':[],
'matrixFeaturesOriginal':[],
'matrixName':"test",
'sourceName':nameOfSource,
'matrixTypes':[]
}
# posted_data['matrixFilters'].update({filterOfMatrix[0]:{"classname":"DocumentLEAN","filter_id":"DocumentLEAN","parameters":[],"stage":"before","type":"extract"}}) #for Text
# posted_data['matrixFilters'].update({filterOfMatrix[0]:{"classname":"TweetDocumentLEAN","filter_id":"TweetDocumentLEAN","parameters":[{"attrname":"include","name":"Include the following keywords","type":"input","value":""},{"attrname":"sent","value":"No"},{"attrname":"exclude","name":"Exclude the following keywords","type":"input","value":""},{"attrname":"lang","name":"Language","type":"input","value":""},{"attrname":"limit","name":"Limit","type":"input","value":"10"},{"attrname":"start","name":"Start time","type":"input","value":""},{"attrname":"end","name":"End time","type":"input","value":""},{"attrname":"geo","name":"Geo","type":"input","value":""}],"stage":"before","type":"extract"}}) #for Mongo
posted_data['matrixFilters'].update({filterOfMatrix[0]:filter_specs_dict})
# posted_data['matrixFilters'].update({filterOfMatrix[0]:{}}) #for spreadsheet
posted_data['matrixFeatures'].append(filterOfMatrix[0])
posted_data['matrixFeaturesOriginal'].append(filterOfMatrix[0])
posted_data['matrixTypes'].append(typeOfMatrix[0])
secondToLastOccurence = my_dir.rfind("/", 0, my_dir.rfind("/"))
my_dir = my_dir[:secondToLastOccurence + 1]
src = {
'created':dataloader.utils.getCurrentTime(),
'host': "127.0.1.1",
'ingest_id':file_name,
'matrices':[],
'name': nameOfSource,
'rootdir':my_dir,
'src_id': "test_files",
'src_type':"file"
}
ingestResult = dataloader.utils.ingest(posted_data, src)
ingestResultList = list(ingestResult)
typeListIngest = []
for i in range(len(exploreResultList)):
typeListExplore.append(type(exploreResultList[i]))
for i in range(len(ingestResultList)):
typeListIngest.append(type(ingestResultList[i]))
for file in os.listdir(my_dir):
if os.path.isdir(my_dir + file) and len(file) > 15:
shutil.rmtree(my_dir + file + "/")
if file.startswith("reduced_"):
os.remove(os.path.join(my_dir, file))
if dict in typeListExplore and int not in typeListExplore:
specificErrorMessage += "Missing a int, explore function must return both a dict and a int."
elif dict not in typeListExplore and int in typeListExplore:
specificErrorMessage += "Missing a dict, explore function must return both a dict and a int."
elif dict not in typeListExplore and int not in typeListExplore:
specificErrorMessage += "Missing a dict and int, explore function must return both a dict and a int."
if bool in typeListIngest and list not in typeListIngest:
specificErrorMessage += " Missing a list, ingest function must return both a boolean and a list."
elif bool not in typeListIngest and list in typeListIngest:
specificErrorMessage += " Missing a boolean value, ingest function must return both a boolean and a list."
elif bool not in typeListIngest and list not in typeListIngest:
specificErrorMessage += " Missing a boolean value and list, ingest function must return both a boolean and a list."
elif desiredInterface == 4:
conf = {
'mat_id':'27651d66d4cf4375a75208d3482476ac',
'storepath':'/home/vagrant/bedrock/bedrock-core/caa1a3105a22477f8f9b4a3124cd41b6/source/',
'src_id':'caa1a3105a22477f8f9b4a3124cd41b6',
'name':'iris'
}
checkResult = dataloader.utils.check(file_name, file_metaData['name'], conf)
if type(checkResult) != bool:
specificErrorMessage += "Missing boolean value, check funtion must return a boolean value."
applyResult = dataloader.utils.apply(file_name, file_metaData['parameters'], conf)
if type(applyResult) != dict:
specificErrorMessage += " Missing a dict object, apply function must return a dict object."
return specificErrorMessage
def create_input_dict(my_dir, inputList):
returnDict = {}
i = 0
j = 1
length = len(inputList)
for file in os.listdir(my_dir):
if file in inputList:
if length == 1 or (length > 1 and file != inputList[length - 1]) or (length > 1 and inputList[i] != inputList[i + 1]):
returnDict.update({file:{'rootdir':my_dir}})
elif length > 1 and inputList[i] == inputList[i + 1]:
firstNewFile = file + "_" + str(j)
j += 1
returnDict.update({firstNewFile:{'rootdir':my_dir}})
if j > 1:
secondNewFile = file + "_" + str(j)
returnDict.update({secondNewFile:{'rootdir':my_dir}})
i += 1
length -= 1
return returnDict
parser = argparse.ArgumentParser(description="Validate files being added to system.")
parser.add_argument('--api', help="The API where the file is trying to be inserted.", action='store', required=True, metavar='api')
parser.add_argument('--filename', help="Name of file inlcuding entire file path.", action='store', required=True, metavar='filename')
parser.add_argument('--input_directory', help="Directory where necessary inputs are stored", action='store', required=True, metavar='input_directory')
parser.add_argument('--filter_specs', help="Specifications for a used filter.", action='store', required=True, metavar='filter_specs')
parser.add_argument('--output_directory', help='Directory where outputs are stored (type NA if there will be no outputs).', action='store', required=True, metavar='output_directory')
args = parser.parse_args()
desiredInterface = 0
fileToCheck = args.filename
if args.api.lower() == "analytics":
desiredInterface = 1
elif args.api.lower() == "visualization":
desiredInterface = 2
elif args.api.lower() == "ingest":
desiredInterface = 3
elif args.api.lower() == "filter":
desiredInterface = 4
my_dir = args.input_directory
output_directory = args.output_directory
filter_specs = args.filter_specs
errorMessage = ""
errorMessage += str(find_imports(fileToCheck, desiredInterface))
errorMessage += str(compare_fuctions(fileToCheck, desiredInterface))
errorMessage += str(inheritance_check(fileToCheck, desiredInterface))
errorMessage += str(validate_file_name(fileToCheck, desiredInterface))
errorMessage += str(check_return_values(fileToCheck, desiredInterface))
if len(errorMessage) == 0:
print("File has been validated and is ready for input")
else:
print("Error Log: ")
print(errorMessage)
print(hard_type_check_return(fileToCheck, desiredInterface, my_dir, output_directory, filter_specs))
| Bedrock-py/bedrock-core | validation/validationScript.py | Python | lgpl-3.0 | 17,191 |
<?php
namespace Google\AdsApi\Dfp\v201711;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class PackageActionError extends \Google\AdsApi\Dfp\v201711\ApiError
{
/**
* @var string $reason
*/
protected $reason = null;
/**
* @param string $fieldPath
* @param \Google\AdsApi\Dfp\v201711\FieldPathElement[] $fieldPathElements
* @param string $trigger
* @param string $errorString
* @param string $reason
*/
public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null)
{
parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString);
$this->reason = $reason;
}
/**
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* @param string $reason
* @return \Google\AdsApi\Dfp\v201711\PackageActionError
*/
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
}
| advanced-online-marketing/AOM | vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201711/PackageActionError.php | PHP | lgpl-3.0 | 1,058 |
/**************************************************************************************************
// file: Engine\Math\CShape.cpp
// A2DE
// Copyright (c) 2013 Blisspoint Softworks and Casey Ugone. All rights reserved.
// Contact cugone@gmail.com for questions or support.
// summary: Implements the shape class
**************************************************************************************************/
#include "CShape.h"
#include "CPoint.h"
#include "CLine.h"
#include "CRectangle.h"
#include "CCircle.h"
#include "CEllipse.h"
#include "CTriangle.h"
#include "CArc.h"
#include "CPolygon.h"
#include "CSpline.h"
#include "CSector.h"
A2DE_BEGIN
Shape::Shape() :
_position(0.0, 0.0),
_half_extents(0.0, 0.0),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(double x, double y) :
_position(x, y),
_half_extents(0.0, 0.0),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(const Vector2D& position) :
_position(position),
_half_extents(0.0, 0.0),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(double x, double y, double half_width, double half_height) :
_position(x, y),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(const Vector2D& position, double half_width, double half_height) :
_position(position),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(double x, double y, const Vector2D& half_extents) :
_position(x, y),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(const Vector2D& position, const Vector2D& half_extents) :
_position(position),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(double x, double y, double half_width, double half_height, const ALLEGRO_COLOR& color) :
_position(x, y),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(false) { }
Shape::Shape(const Vector2D& position, double half_width, double half_height, const ALLEGRO_COLOR& color) :
_position(position),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(false) { }
Shape::Shape(double x, double y, const Vector2D& half_extents, const ALLEGRO_COLOR& color) :
_position(x, y),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(false) { }
Shape::Shape(const Vector2D& position, const Vector2D& half_extents, const ALLEGRO_COLOR& color) :
_position(position),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(false) { }
Shape::Shape(double x, double y, double half_width, double half_height, const ALLEGRO_COLOR& color, bool filled) :
_position(x, y),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(filled) { }
Shape::Shape(const Vector2D& position, double half_width, double half_height, const ALLEGRO_COLOR& color, bool filled) :
_position(position),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(filled) { }
Shape::Shape(double x, double y, const Vector2D& half_extents, const ALLEGRO_COLOR& color, bool filled) :
_position(x, y),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(filled) { }
Shape::Shape(const Vector2D& position, const Vector2D& half_extents, const ALLEGRO_COLOR& color, bool filled) :
_position(position),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(filled) { }
Shape::Shape(const Shape& shape) :
_position(shape._position),
_half_extents(shape._half_extents),
_area(shape._area),
_type(Shape::SHAPETYPE_SHAPE),
_color(shape._color),
_filled(shape._filled) { }
Shape& Shape::operator=(const Shape& rhs) {
if(this == &rhs) return *this;
this->_position = rhs._position;
this->_half_extents = rhs._half_extents;
this->_area = rhs._area;
this->_type = rhs._type;
this->_color = rhs._color;
this->_filled = rhs._filled;
return *this;
}
Shape::~Shape() {
}
const ALLEGRO_COLOR& Shape::GetColor() const {
return _color;
}
ALLEGRO_COLOR& Shape::GetColor() {
return const_cast<ALLEGRO_COLOR&>(static_cast<const Shape&>(*this).GetColor());
}
bool Shape::IsFilled() const {
return _filled;
}
void Shape::SetColor(const ALLEGRO_COLOR& color) {
_color = color;
}
void Shape::SetFill(bool filled) {
_filled = filled;
}
double Shape::GetHalfWidth() const {
return _half_extents.GetX();
}
double Shape::GetHalfWidth(){
return static_cast<const Shape&>(*this).GetHalfWidth();
}
double Shape::GetHalfHeight() const {
return _half_extents.GetY();
}
double Shape::GetHalfHeight() {
return static_cast<const Shape&>(*this).GetHalfHeight();
}
const Vector2D& Shape::GetHalfExtents() const {
return _half_extents;
}
Vector2D& Shape::GetHalfExtents() {
return const_cast<a2de::Vector2D&>(static_cast<const Shape&>(*this).GetHalfExtents());
}
const Vector2D& Shape::GetPosition() const {
return _position;
}
Vector2D& Shape::GetPosition() {
return const_cast<a2de::Vector2D&>(static_cast<const Shape&>(*this).GetPosition());
}
double Shape::GetArea() const {
return _area;
}
double Shape::GetArea() {
return static_cast<const Shape&>(*this).GetArea();
}
double Shape::GetX() const {
return _position.GetX();
}
double Shape::GetX() {
return static_cast<const Shape&>(*this).GetX();
}
double Shape::GetY() const {
return _position.GetY();
}
double Shape::GetY() {
return static_cast<const Shape&>(*this).GetY();
}
void Shape::SetX(double x) {
SetPosition(x, GetY());
}
void Shape::SetY(double y) {
SetPosition(GetX(), y);
}
void Shape::SetPosition(double x, double y) {
SetPosition(Vector2D(x, y));
}
void Shape::SetPosition(const Vector2D& position) {
_position = position;
}
void Shape::SetHalfWidth(double width) {
SetHalfExtents(width, GetHalfHeight());
}
void Shape::SetHalfHeight(double height) {
SetHalfExtents(GetHalfWidth(), height);
}
void Shape::SetHalfExtents(double width, double height) {
SetHalfExtents(Vector2D(width, height));
}
void Shape::SetHalfExtents(const Vector2D& dimensions) {
_half_extents = dimensions;
}
const Shape::SHAPE_TYPE& Shape::GetShapeType() const {
return _type;
}
Shape::SHAPE_TYPE& Shape::GetShapeType() {
return const_cast<Shape::SHAPE_TYPE&>(static_cast<const Shape&>(*this).GetShapeType());
}
Shape* Shape::Clone(Shape* shape) {
if(shape == nullptr) return nullptr;
Shape::SHAPE_TYPE type = shape->GetShapeType();
switch(type) {
case Shape::SHAPETYPE_POINT:
return new Point(*dynamic_cast<Point*>(shape));
case Shape::SHAPETYPE_LINE:
return new Line(*dynamic_cast<Line*>(shape));
case Shape::SHAPETYPE_RECTANGLE:
return new Rectangle(*dynamic_cast<Rectangle*>(shape));
case Shape::SHAPETYPE_CIRCLE:
return new Circle(*dynamic_cast<Circle*>(shape));
case Shape::SHAPETYPE_ELLIPSE:
return new Ellipse(*dynamic_cast<Ellipse*>(shape));
case Shape::SHAPETYPE_TRIANGLE:
return new Triangle(*dynamic_cast<Triangle*>(shape));
case Shape::SHAPETYPE_ARC:
return new Arc(*dynamic_cast<Arc*>(shape));
case Shape::SHAPETYPE_POLYGON:
return new Polygon(*dynamic_cast<Polygon*>(shape));
case Shape::SHAPETYPE_SPLINE:
return new Spline(*dynamic_cast<Spline*>(shape));
case Shape::SHAPETYPE_SECTOR:
return new Sector(*dynamic_cast<Sector*>(shape));
default:
return nullptr;
}
}
bool Shape::Contains(const Shape& shape) const {
Shape::SHAPE_TYPE type = shape.GetShapeType();
switch(type) {
case Shape::SHAPETYPE_POINT:
return this->Contains(dynamic_cast<const Point&>(shape));
case Shape::SHAPETYPE_LINE:
return this->Contains(dynamic_cast<const Line&>(shape));
case Shape::SHAPETYPE_RECTANGLE:
return this->Contains(dynamic_cast<const Rectangle&>(shape));
case Shape::SHAPETYPE_CIRCLE:
return this->Contains(dynamic_cast<const Circle&>(shape));
case Shape::SHAPETYPE_ELLIPSE:
return this->Contains(dynamic_cast<const Ellipse&>(shape));
case Shape::SHAPETYPE_TRIANGLE:
return this->Contains(dynamic_cast<const Triangle&>(shape));
case Shape::SHAPETYPE_ARC:
return this->Contains(dynamic_cast<const Arc&>(shape));
case Shape::SHAPETYPE_POLYGON:
return this->Contains(dynamic_cast<const Polygon&>(shape));
case Shape::SHAPETYPE_SPLINE:
return this->Contains(dynamic_cast<const Spline&>(shape));
case Shape::SHAPETYPE_SECTOR:
return this->Contains(dynamic_cast<const Sector&>(shape));
default:
return false;
}
}
bool Shape::Contains(const Point& point) const {
return this->Intersects(point);
}
bool Shape::Contains(const Line& line) const {
return this->Intersects(line.GetPointOne()) && this->Intersects(line.GetPointTwo());
}
bool Shape::Contains(const Rectangle& rectangle) const {
double rleft = rectangle.GetX();
double rtop = rectangle.GetY();
double rright = rleft + rectangle.GetHalfWidth();
double rbottom = rtop + rectangle.GetHalfHeight();
double tleft = this->GetX();
double ttop = this->GetY();
double tright = tleft + this->GetHalfWidth();
double tbottom = ttop + this->GetHalfHeight();
bool is_exact = a2de::Math::IsEqual(rtop, ttop) && a2de::Math::IsEqual(rleft, tleft) && a2de::Math::IsEqual(rbottom, tbottom) && a2de::Math::IsEqual(rright, tright);
bool is_smaller = (rtop > ttop && rleft > tleft && rbottom < tbottom && rright < tright);
return (is_exact || is_smaller);
}
bool Shape::Contains(const Circle& circle) const {
double cdiameter = circle.GetDiameter();
double twidth = this->GetHalfWidth();
double theight = this->GetHalfHeight();
bool diameter_equal_to_width = a2de::Math::IsEqual(cdiameter, twidth);
bool diameter_equal_to_height = a2de::Math::IsEqual(cdiameter, theight);
bool diameter_less_than_width = cdiameter < twidth;
bool diameter_less_than_height = cdiameter < theight;
bool diameter_less_equal_width = diameter_less_than_width || diameter_equal_to_width;
bool diameter_less_equal_height = diameter_less_than_height || diameter_equal_to_height;
bool center_inside_shape = this->Intersects(Point(circle.GetPosition()));
bool contains = center_inside_shape && diameter_less_equal_width && diameter_less_equal_height;
return contains;
}
bool Shape::Contains(const Ellipse& ellipse) const {
return this->Intersects(Point(ellipse.GetPosition())) && ellipse.GetHalfWidth() <= this->GetHalfWidth() && ellipse.GetHalfHeight() <= this->GetHalfHeight();
}
bool Shape::Contains(const Triangle& triangle) const {
return this->Intersects(Point(triangle.GetPointA())) && this->Intersects(Point(triangle.GetPointB())) && this->Intersects(Point(triangle.GetPointC()));
}
bool Shape::Contains(const Arc& arc) const {
return this->Intersects(arc.GetStartPoint()) && this->Intersects(arc.GetEndPoint());
}
bool Shape::Contains(const Polygon& polygon) const {
int total_points = polygon.GetNumVertices();
for(int i = 0; i < total_points; ++i) {
if(this->Intersects(polygon.GetVertices()[i])) continue;
return false;
}
return true;
}
bool Shape::Contains(const Spline& /*spline*/) const {
return false;
}
bool Shape::Contains(const Sector& sector) const {
return this->Intersects(sector.GetStartPoint()) && this->Intersects(sector.GetEndPoint()) && this->Intersects(Point(sector.GetPosition()));
}
void Shape::Draw(ALLEGRO_BITMAP* dest) {
this->Draw(dest, _color, _filled);
}
A2DE_END | cugone/Abrams2012 | Allegro2DEngine/Engine/Math/CShape.cpp | C++ | lgpl-3.0 | 12,152 |
<?php
/**
* Venne:CMS (version 2.0-dev released on $WCDATE$)
*
* Copyright (c) 2011 Josef Kříž pepakriz@gmail.com
*
* For the full copyright and license information, please view
* the file license.txt that was distributed with this source code.
*/
namespace App\SecurityModule\AdminModule;
/**
* @author Josef Kříž
* @resource AdminModule\SecurityModule\Security
*/
class DefaultPresenter extends BasePresenter
{
public function renderDefault()
{
}
}
| Venne/Venne-CMS-old | App/SecurityModule/AdminModule/presenters/DefaultPresenter.php | PHP | lgpl-3.0 | 477 |
/**
\author Shestakov Mikhail aka MIKE
\date 12.12.2012 (c)Andrey Korotkov
This file is a part of DGLE project and is distributed
under the terms of the GNU Lesser General Public License.
See "DGLE.h" for more details.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Gtk;
namespace Packer
{
public static class TreeViewExtensions
{
public static IEnumerable<TreeIter> GetSelected(this TreeView tree)
{
return tree.Selection.GetSelectedRows().ToList().Select(path =>
{
TreeIter selectedIter;
if (tree.Model.GetIter(out selectedIter, path))
return selectedIter;
return TreeIter.Zero;
});
}
public static void SelectAndFocus(this TreeView tree, TreeIter iter)
{
tree.Selection.SelectIter(iter);
tree.GrabFocus();
}
public static void SelectAndFocus(this TreeView tree, TreePath path)
{
tree.Selection.SelectPath(path);
tree.GrabFocus();
}
}
}
| DGLE-HQ/DGLE | src/tools/packer/TreeViewExtensions.cs | C# | lgpl-3.0 | 940 |
<?php declare(strict_types=1);
namespace ju1ius\Pegasus\Parser\Exception;
class ParseError extends \RuntimeException {}
| ju1ius/pegasus | src/Parser/Exception/ParseError.php | PHP | lgpl-3.0 | 122 |
<?php
require_once('lib/Stats.php');
require_once('lib/ProbabilityDistribution/ProbabilityDistribution.php');
require_once('lib/ProbabilityDistribution/Weibull.php');
require_once('lib/StatisticalTests.php');
use \PHPStats\ProbabilityDistribution\Weibull as Weibull;
class WeibullTest extends PHPUnit_Framework_TestCase {
private $testObject;
public function __construct() {
$this->testObject = new Weibull(5, 1);
}
public function test_rvs() {
$variates = array();
for ($i = 0; $i < 10000; $i++) $variates[] = $this->testObject->rvs();
$this->assertGreaterThanOrEqual(0.01, \PHPStats\StatisticalTests::kolmogorovSmirnov($variates, $this->testObject));
$this->assertLessThanOrEqual(0.99, \PHPStats\StatisticalTests::kolmogorovSmirnov($variates, $this->testObject));
}
public function test_pdf() {
$this->assertEquals(0.2, round($this->testObject->pdf(0), 5));
$this->assertEquals(0.14523, round($this->testObject->pdf(1.6), 5));
}
public function test_cdf() {
$this->assertEquals(0.5, round($this->testObject->cdf(3.46574), 5));
$this->assertEquals(0.9, round($this->testObject->cdf(11.5129), 5));
}
public function test_sf() {
$this->assertEquals(0.5, round($this->testObject->sf(3.46574), 5));
$this->assertEquals(0.1, round($this->testObject->sf(11.5129), 5));
}
public function test_ppf() {
$this->assertEquals(3.46574, round($this->testObject->ppf(0.5), 5));
$this->assertEquals(11.5129, round($this->testObject->ppf(0.9), 4));
}
public function test_isf() {
$this->assertEquals(3.46574, round($this->testObject->isf(0.5), 5));
$this->assertEquals(11.5129, round($this->testObject->isf(0.1), 4));
}
public function test_stats() {
$summaryStats = $this->testObject->stats('mvsk');
$this->assertEquals(5, round($summaryStats['mean'], 3));
$this->assertEquals(25, round($summaryStats['variance'], 2));
$this->assertEquals(2, round($summaryStats['skew'], 3));
$this->assertEquals(6, round($summaryStats['kurtosis'], 3));
}
}
?>
| bunnyinc/phpstats | tests/ProbabilityDistribution/WeibullTest.php | PHP | lgpl-3.0 | 1,997 |
package broad.core.siphy;
public class UnableToFitException extends Exception {
private static final long serialVersionUID = 285381715807645775L;
public UnableToFitException(String msg) {
super(msg);
}
}
| mgarber/scriptureV2 | src/java/broad/core/siphy/UnableToFitException.java | Java | lgpl-3.0 | 214 |
package org.javlo.component.social;
public class FacebookFriend {
private String name;
private String image;
public FacebookFriend(String name, String image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
} | Javlo/javlo | src/main/java/org/javlo/component/social/FacebookFriend.java | Java | lgpl-3.0 | 427 |
if (typeof ui == 'undefined') var ui = {};
ui.Template = {
reg_vaild_preceding_chars: '(?:[^-\\/"\':!=a-zA-Z0-9_]|^)',
reg_url_path_chars_1: '[a-zA-Z0-9!\\*\';:=\\+\\$/%#\\[\\]\\?\\-_,~\\(\\)&\\.`@]',
reg_url_path_chars_2: '[a-zA-Z0-9!\':=\\+\\$/%#~\\(\\)&`@]',
reg_url_proto_chars: '([a-zA-Z]+:\\/\\/|www\\.)',
reg_user_name_chars: '[@@]([a-zA-Z0-9_]{1,20})',
reg_list_name_template: '[@@]([a-zA-Z0-9_]{1,20}/[a-zA-Z][a-zA-Z0-9_\\-\u0080-\u00ff]{0,24})',
// from https://si0.twimg.com/c/phoenix/en/bundle/t1-hogan-core.f760c184d1eaaf1cf27535473a7306ef.js
reg_hash_tag_latin_chars: '\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u024f\u0253-\u0254\u0256-\u0257\u0259\u025b\u0263\u0268\u026f\u0272\u0289\u028b\u02bb\u1e00-\u1eff',
reg_hash_tag_nonlatin_chars: '\u0400-\u04ff\u0500-\u0527\u2de0-\u2dff\ua640-\ua69f\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\ufb12-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4f\u0610-\u061a\u0620-\u065f\u066e-\u06d3\u06d5-\u06dc\u06de-\u06e8\u06ea-\u06ef\u06fa-\u06fc\u06ff\u0750-\u077f\u08a0\u08a2-\u08ac\u08e4-\u08fe\ufb50-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\u200c\u0e01-\u0e3a\u0e40-\u0e4e\u1100-\u11ff\u3130-\u3185\ua960-\ua97f\uac00-\ud7af\ud7b0-\ud7ff\uffa1-\uffdc\u30a1-\u30fa\u30fc-\u30fe\uff66-\uff9f\uff70\uff10-\uff19\uff21-\uff3a\uff41-\uff5a\u3041-\u3096\u3099-\u309e\u3400-\u4dbf\u4e00-\u9fff\ua700-\ub73f\ub740-\ub81f\uf800-\ufa1f\u3003\u3005\u303b',
reg_hash_tag_template: '(^|\\s)[##]([a-z0-9_{%LATIN_CHARS%}{%NONLATIN_CHARS%}]*)',
reg_hash_tag: null,
reg_is_rtl: new RegExp('[\u0600-\u06ff]|[\ufe70-\ufeff]|[\ufb50-\ufdff]|[\u0590-\u05ff]'),
tweet_t:
'<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%} {%FAV_CLASS%}" type="tweet" retweet_id="{%RETWEET_ID%}" reply_id="{%REPLY_ID%}" in_thread="{%IN_THREAD%}" reply_name="{%REPLY_NAME%}" screen_name="{%SCREEN_NAME%}" retweetable="{%RETWEETABLE%}" deletable="{%DELETABLE%}" link="{%LINK%}" style="font-family: {%TWEET_FONT%};">\
<div class="tweet_color_label" style="background-color:{%COLOR_LABEL%}"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="tweet_fav_indicator"></div>\
<div class="deleted_mark"></div>\
<div class="tweet_retweet_indicator"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}\n\n{%DESCRIPTION%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\
</li>\
</ul>\
<div class="card_body">\
<div class="who {%RETWEET_MARK%}">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}\n\n{%DESCRIPTION%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" alt="{%ALT%}" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\
<div class="tweet_meta">\
<div class="tweet_thread_info" style="display:{%IN_REPLY%}">\
<a class="btn_tweet_thread" href="#"></a>\
{%REPLY_TEXT%}\
</div>\
<div class="tweet_source"> \
{%RETWEET_TEXT%} \
<span class="tweet_timestamp">\
<a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\
</span>\
{%TRANS_via%}: {%SOURCE%}</div>\
<div class="status_bar">{%STATUS_INDICATOR%}</div>\
</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
<div class="tweet_thread_wrapper">\
<div class="tweet_thread_hint">{%TRANS_Loading%}</div>\
<ul class="tweet_thread"></ul>\
<a class="btn_tweet_thread_more">{%TRANS_View_more_conversation%}</a>\
</div>\
</li>',
trending_topic_t:
'<li id="{%ID%}" class="card" type="trending_topic">\
<div class="profile_img_wrapper trend_topic_number">#{%ID%}</div>\
<div class="card_body keep_height">\
<a class="hash_href trending_topic" href="{%NAME%}">{%NAME%}</a>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
retweeted_by_t:
'<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%} {%FAV_CLASS%}" type="tweet" retweet_id="{%RETWEET_ID%}" reply_id="{%REPLY_ID%}" reply_name="{%REPLY_NAME%}" screen_name="{%SCREEN_NAME%}" retweetable="{%RETWEETABLE%}" deletable="{%DELETABLE%}" style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="deleted_mark"></div>\
<div class="tweet_fav_indicator"></div>\
<div class="tweet_retweet_indicator"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\
</li>\
</ul>\
<div class="card_body">\
<div class="who {%RETWEET_MARK%}">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" alt="{%ALT%}" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\
<div class="tweet_meta">\
<div class="tweet_thread_info" style="display:{%IN_REPLY%}">\
<a class="btn_tweet_thread" href="#"></a>\
{%REPLY_TEXT%}\
</div>\
<div class="tweet_source"> \
{%RETWEET_TEXT%} \
<span class="tweet_timestamp">\
<a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\
</span>\
{%TRANS_via%}: {%SOURCE%}\
{%TRANS_Retweeted_by%}: <a class="show" href="#" title="{%TRANS_Click_to_show_retweeters%}" tweet_id="{%TWEET_ID%}">{%TRANS_Show_retweeters%}</a>\
</div>\
<div class="tweet_retweeters" tweet_id="{%TWEET_ID%}"></div>\
<div class="status_bar">{%STATUS_INDICATOR%}</div>\
</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
<div class="tweet_thread_wrapper">\
<div class="tweet_thread_hint">{%TRANS_Loading%}</div>\
<ul class="tweet_thread"></ul>\
<a class="btn_tweet_thread_more">{%TRANS_View_more_conversation%}</a>\
</div>\
</li>',
message_t:
'<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%}" type="message" sender_screen_name="{%SCREEN_NAME%}" style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}\n\n{%DESCRIPTION%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn tweet_dm_reply_btn" title="Reply them" href="#reply_dm" data-i18n-title="reply"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\
</li>\
</ul>\
<div class="card_body">\
<div class="who">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}\n\n{%DESCRIPTION%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">@<a class="who_href" href="#{%RECIPIENT_SCREEN_NAME%}">{%RECIPIENT_SCREEN_NAME%}</a> {%TEXT%}</div>\
<div class="tweet_meta">\
<div class="tweet_source"> \
<span class="tweet_timestamp tweet_update_timestamp" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</span>\
</div>\
</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
search_t:
'<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%}" type="search" screen_name="{%SCREEN_NAME%}" link="{%LINK%}" style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="deleted_mark"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\
</li>\
</ul>\
<div class="card_body">\
<div class="who">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\
<div class="tweet_meta">\
<div class="tweet_source"> \
<span class="tweet_timestamp">\
<a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\
</span>\
{%TRANS_via%}: {%SOURCE%}</div>\
</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
people_t:
'<li id="{%USER_ID%}" class="people_card card normal" type="people" following={%FOLLOWING%} screen_name={%SCREEN_NAME%} style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li style="display:none;">\
<a class="tweet_bar_btn add_to_list_btn" title="Add to list" href="#follow" data-i18n-title="add_to_list"></a>\
</li><li>\
<a class="tweet_bar_btn follow_btn" title="Follow them" href="#follow" data-i18n-title="follow"></a>\
</li><li>\
<a class="tweet_bar_btn unfollow_btn" title="Unfollow them" href="#unfollow" data-i18n-title="unfollow"></a>\
</li>\
</ul>\
<div class="card_body">\
<div id="{%USER_ID%}" class="who">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" style="font-style:italic font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%DESCRIPTION%}</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
people_vcard_t_orig:
'<div class="header_frame">\
<div class="people_vcard vcard">\
<a target="_blank" class="profile_img_wrapper"></a>\
<div class="vcard_body">\
<center>\
<ul class="people_vcard_radio_group mochi_button_group"> \
<li><a class="mochi_button_group_item selected" href="#people_vcard_info_page" name="">{%TRANS_info%}</a> \
</li><li><a class="mochi_button_group_item" href="#people_vcard_stat_page">{%TRANS_stat%}</a> \
</li></ul>\
</center>\
<div class="vcard_tabs_pages">\
<table class="people_vcard_info_page vcard_tabs_page radio_group_page" border="0" cellpadding="0" cellspacing="0"> \
<tr><td>{%TRANS_name%}: </td><td> \
<a class="screen_name" target="_blank" href="#"></a> \
(<span class="name"></span>) </td> \
</tr> \
<tr><td>{%TRANS_bio%}: </td> \
<td><span class="bio"></span></td> \
</tr> \
<tr><td>{%TRANS_web%}: </td> \
<td><a class="web" target="_blank" href="#" class="link"></a></td> \
</tr> \
<tr><td>{%TRANS_location%}: </td> \
<td><span class="location"></span></td> \
</tr> \
</table> \
<table class="people_vcard_stat_page vcard_tabs_page radio_group_page"> \
<tr><td>{%TRANS_join%}: </td> \
<td><span class="join"></span></td> \
</tr> \
<tr><td>{%TRANS_tweet_cnt%}: </td> \
<td><span class="tweet_cnt"></span> \
(<span class="tweet_per_day_cnt"></span> per day)</td> \
</tr> \
<tr><td>{%TRANS_follower_cnt%}: </td> \
<td><span class="follower_cnt"></span></td> \
</tr> \
<tr><td>{%TRANS_friend_cnt%}: </td> \
<td><span class="friend_cnt"></span></td> \
</tr> \
<tr><td>{%TRANS_listed_cnt%}: </td> \
<td><span class="listed_cnt"></span></td> \
</tr> \
<tr><td>{%TRANS_relation%}: </td> \
<td><span class="relation"></span></td> \
</tr> \
</table> \
</div><!-- vcard tabs pages --> \
</div> <!-- vcard body --> \
<div class="vcard_ctrl"> \
<ul class="vcard_action_btns"> \
<li><a class="vcard_follow mochi_button blue" \
href="#" >{%TRANS_follow%}</a> \
</li><li> \
<a class="vcard_edit mochi_button" \
href="#" style="display:none;">{%TRANS_edit%}</a>\
</li><li class="people_action_more_trigger"> \
<a class="vcard_more mochi_button" \
href="#">{%TRANS_more_actions%} ▾</a> \
<ul class="people_action_more_memu hotot_menu">\
<li><a class="mention_menu_item" \
title="Mention them"\
href="#">{%TRANS_mention_them%}</a>\
</li><li><a class="message_menu_item" \
title="Send Message to them"\
href="#">{%TRANS_message_them%}</a>\
</li><li><a class="add_to_list_menu_item" \
title="Add them to a list"\
href="#">{%TRANS_add_to_list%}</a>\
</li><li class="separator"><span></span>\
</li><li><a class="block_menu_item" \
title="Block"\
href="#">{%TRANS_block%}</a>\
</li><li><a class="unblock_menu_item"\
href="#" \
title="Unblock">{%TRANS_unblock%}</a>\
</li><li><a class="report_spam_menu_item" \
href="#" \
title="Report Spam">{%TRANS_report_spam%}</a>\
</li>\
</ul>\
</li> \
</ul> \
</div><!-- #people_vcard_ctrl --> \
</div> <!-- vcard --> \
<div class="expand_wrapper"><a href="#" class="expand">…</a></div>\
<div class="people_view_toggle"> \
<ol class="people_view_toggle_btns mochi_button_group"> \
<li><a class="people_view_tweet_btn mochi_button_group_item selected" href="#tweet">{%TRANS_tweets%}</a> \
</li><li> \
<a class="people_view_fav_btn mochi_button_group_item" href="#fav">{%TRANS_favs%}</a> \
</li><li class="people_view_people_trigger"> \
<a class="people_view_people_btn mochi_button_group_item" href="#people">{%TRANS_fellowship%} ▾</a> \
<ul class="people_menu hotot_menu">\
<li><a class="followers_menu_item" \
title="People who follow them."\
href="#">{%TRANS_followers%}</a>\
</li><li><a class="friends_menu_item"\
href="People them is following" \
title="All Lists following Them">{%TRANS_friends%}</a>\
</li>\
</ul>\
</li><li class="people_view_list_trigger"> \
<a class="people_view_list_btn mochi_button_group_item" href="#list">{%TRANS_lists%} ▾\
</a> \
<ul class="lists_menu hotot_menu">\
<li><a class="user_lists_menu_item" \
title="Lists of Them"\
href="#">{%TRANS_lists_of_them%}</a>\
</li><li><a class="listed_lists_menu_item"\
href="#" \
title="All Lists following Them">{%TRANS_lists_following_them%}</a>\
</li><li><a class="create_list_menu_item" \
href="#" \
title="Create A List">{%TRANS_create_a_list%}</a>\
</li>\
</ul>\
</li> \
</ol> \
</div> \
<div class="people_request_hint"> \
<h1 data-i18n-text="he_she_has_protexted_his_her_tweets">He/She has protected his/her tweets.</span></h1> \
<p data-i18n-text="you_need_to_go_to_twitter_com_to_send_a_request_before_you_can_start_following_this_persion">You need to go to twitter.com to send a request before you can start following this person...</p> \
<div style="text-align:center;"> \
<a class="people_request_btn mochi_button" href="#" target="_blank" data-i18n-text="send_request">Send Request</a> \
</div> \
</div></div>',
list_t:
'<li id="{%LIST_ID%}" class="list_card card normal" type="list" following={%FOLLOWING%} screen_name={%SCREEN_NAME%} slug={%SLUG%} style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="profile_img_wrapper" title="@{%USER_NAME%}/{%SLUG%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn follow_btn" title="Follow them" href="#follow" data-i18n-title="follow"></a>\
</li><li>\
<a class="tweet_bar_btn unfollow_btn" title="Unfollow them" href="#unfollow" data-i18n-title="unfollow"></a>\
</li>\
</ul>\
<div class="card_body">\
<div id="{%USER_ID%}" class="who">\
<a class="list_href" href="#{%SCREEN_NAME%}/{%SLUG%}" title="{%USER_NAME%}/{%SLUG%}">\
@{%SCREEN_NAME%}/{%SLUG%}\
</a>\
</div>\
<div class="text" style="font-style:italic font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%DESCRIPTION%}</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
list_vcard_t:
'<div class="header_frame"><div class="list_vcard vcard">\
<a target="_blank" class="profile_img_wrapper"></a>\
<div class="vcard_body">\
<div class="vcard_tabs_pages">\
<table border="0" cellpadding="0" cellspacing="0" class="vcard_tabs_page" style="display:block;"> \
<tr><td data-i18n-text="name">Name: </td><td> \
<a class="name" target="_blank" href="#"></a></td> \
</tr> \
<tr><td>Owner: </td> \
<td><a class="owner" target="_blank" href="#" data-i18n-text="owner"></a></td> \
</tr> \
<tr><td data-i18n-text="description">Description: </td> \
<td><span class="description"></span></td> \
</tr> \
</table> \
</div>\
</div> <!-- vcard body --> \
<div class="vcard_ctrl"> \
<ul class="vcard_action_btns"> \
<li><a class="vcard_follow mochi_button blue" \
href="#" data-i18n-text="follow">Follow</a> \
</li><li> \
<a class="vcard_delete mochi_button red" \
href="#" data-i18n-text="delete">Delete</a> \
</li><li> \
<a class="vcard_edit mochi_button" \
href="#" style="display:none;" data-i18n-text="edit">Edit</a>\
</li> \
</ul> \
</div><!-- #list_vcard_ctrl --> \
</div> <!-- vcard --> \
<div class="expand_wrapper"><a href="#" class="expand">…</a></div>\
<div class="list_view_toggle"> \
<ol class="list_view_toggle_btns mochi_button_group"> \
<li><a class="list_view_tweet_btn mochi_button_group_item selected" href="#tweet" data-i18n-text="tweets">Tweets</a> \
</li><li> \
<a class="list_view_follower_btn mochi_button_group_item" href="#follower" data-i18n-text="followers">Followers</a> \
</li><li> \
<a class="list_view_following_btn mochi_button_group_item" href="#following" data-i18n-text="following">Following</a> \
</li> \
</ol> \
</div> \
<div class="list_lock_hint"> \
<h1 data-i18n-text="he_she_has_protected_his_her_list">He/She has protected his/her list.</span></h1> \
<p data-i18n-text="only_the_owner_can_access_this_list">Only the owner can access this list.</p> \
</div></div>',
search_header_t:
'<div class="header_frame"> \
<div class="search_box"> \
<input class="search_entry mochi_entry" type="text" placeholder="Type and press enter to search." data-i18n-placeholder="type_and_press_enter_to_search"/> \
<a href="#" class="search_entry_clear_btn"></a>\
<div class="search_people_result"> \
<span data-i18n-text="one_user_matched">One user matched: </span> <span class="search_people_inner"></span>\
</div>\
<div class="saved_searches">\
<a id="create_saved_search_btn" class="mochi_button" \
href="#" title="Detach" data-i18n-title="detach"> +\
</a>\
<div id="saved_searches_more_trigger" style="display:none;">\
<a id="saved_searches_btn" class="vcard_more mochi_button" \
href="#"> ▾</a> \
<ul id="saved_searches_more_menu" class="hotot_menu">\
<li><a class="" \
title="Clear ALL"\
href="#" data-i18n-title="clear_all" data-i18n-text="clear_all">Clear All</a>\
</li><li class="separator"><span></span>\
</li><li>\
<a class="saved_search_item" href="#">a</a>\
</li>\
</ul>\
</div>\
</div>\
<div class="search_view_toggle">\
<ol class="search_view_toggle_btns mochi_button_group">\
<li><a class="search_tweet mochi_button_group_item selected" \
href="#tweet" data-i18n-text="tweets">Tweet</a>\
</li><li> \
<a class="search_people mochi_button_group_item"\
href="#people" data-i18n-text="people">People</a>\
</li> \
</ol> \
</div> \
<div class="search_no_result_hint"> \
<p><span data-i18n-text="your_search">Your search</span> - <label class="keywords"></label> - <span data-i18n-text="did_not_match_any_result">did not match any result.</span></p> \
<p><span data-i18n-text="suggestions">Suggestions</span>: <br/> \
- <span data-i18n-text="make_sure_all_words_are_spelled_correctly">Make sure all words are spelled correctly.</span><br/> \
- <span data-i18n-text="try_different_keywords">Try different keywords.</span><br/> \
- <span data-i18n-text="try_more_general_keywords">Try more general keywords.</span><br/></p> \
</div> \
</div> \
</div>',
retweets_header_t:
'<div class="header_frame"><div class="retweets_view_toggle"> \
<ol class="retweets_view_toggle_btns radio_group">\
<li><a class="btn_retweeted_to_me radio_group_btn selected" \
href="#retweeted_to_me" data-i18n-text="by_others">By Others</a>\
</li><li> \
<a class="btn_retweeted_by_me radio_group_btn"\
href="#retweeted_by_me" data-i18n-text="by_me">By Me</a>\
</li><li> \
<a class="btn_retweets_of_me radio_group_btn" \
href="#retweets_of_me" data-i18n-text="my_tweets_retweeted">My Tweets, Retweeted</a> \
</li> \
</ol> \
</div></div>',
common_column_header_t:
'<div class="column_settings"> \
<ul class="mochi_list dark">\
<li class="mochi_list_item dark"> \
<input type="checkbox" href="#use_auto_update" class="mochi_toggle dark widget"/>\
<label class="label" data-i18n-text="auto_update">Auto Update</label>\
</li>\
<li class="mochi_list_item dark"> \
<input type="checkbox" href="#use_notify" class="mochi_toggle dark widget"/>\
<label class="label" data-i18n-text="notify">Notify</label>\
</li>\
<li class="mochi_list_item dark"> \
<input type="checkbox" href="#use_notify_sound" class="mochi_toggle dark widget"/>\
<label class="label" data-i18n-text="sound">Sound</label>\
</li>\
</ul>\
</div>\
',
view_t:
'<div id="{%ID%}" \
name="{%NAME%}" class="listview scrollbar_container {%CLASS%} {%ROLE%}"> \
<div class="scrollbar_track">\
<div class="scrollbar_slot">\
<div class="scrollbar_handle"></div>\
</div>\
</div>\
<div class="scrollbar_content listview_content">\
<div class="listview_header"><div class="header_content">{%HEADER%}</div></div> \
<ul class="listview_body"></ul> \
<div class="listview_footer"> \
<div class="load_more_info"><img src="image/ani_loading_bar.gif"/></div> \
</div> \
</div> \
</div>',
indicator_t:
'<div class="{%STICK%} {%ROLE%}" name="{%TARGET%}" draggable="true"><a class="indicator_btn" href="#{%TARGET%}" title="{%TITLE%}"><img class="icon" src="{%ICON%}"/><div class="icon_alt" style="background-image: url({%ICON%})"></div></a><span class="shape"></span></div>',
kismet_rule_t:
'<li><a class="kismet_rule" name="{%NAME%}" type="{%TYPE%}" method="{%METHOD%}"\
disabled="{%DISABLED%}" field="{%FIELD%}" pattern="{%PATTERN%}" \
actions="{%ACTIONS%}" {%ADDITION%} href="#">{%NAME%}</a></li>',
status_draft_t:
'<li mode="{%MODE%}" reply_to_id="{%REPLY_TO_ID%}" reply_text="{%REPLY_TEXT%}" recipient="{%RECIPIENT%}"><a class="text">{%TEXT%}</a><a class="btn_draft_clear" href="#"></a></li>',
preview_link_reg: {
'img.ly': {
reg: new RegExp('http:\\/\\/img.ly\\/([a-zA-Z0-9_\\-]+)','g'),
base: 'http://img.ly/show/thumb/',
direct_base: 'http://img.ly/show/full/'
},
'twitpic.com': {
reg: new RegExp('http:\\/\\/twitpic.com\\/([a-zA-Z0-9_\\-]+)','g'),
base: 'http://twitpic.com/show/thumb/'
},
'twitgoo.com': {
reg: new RegExp('http:\\/\\/twitgoo.com\\/([a-zA-Z0-9_\\-]+)','g'),
base: 'http://twitgoo.com/show/thumb/',
direct_base: 'http://twitgoo.com/show/img/'
},
'yfrog.com': {
reg: new RegExp('http:\\/\\/yfrog.com\\/([a-zA-Z0-9_\\-]+)','g'),
tail: '.th.jpg'
},
'moby.to': {
reg: new RegExp('http:\\/\\/moby.to\\/([a-zA-Z0-9_\\-]+)','g'),
tail: ':thumbnail'
},
'instagr.am': {
reg: new RegExp('http:\\/\\/instagr.am\\/p\\/([a-zA-Z0-9_\\-]+)\\/?','g'),
tail: 'media?size=m',
direct_tail: 'media?size=l'
},
'plixi.com': {
reg: new RegExp('http:\\/\\/plixi.com\\/p\\/([a-zA-Z0-9_\\-]+)','g'),
base: 'http://api.plixi.com/api/tpapi.svc/imagefromurl?size=thumbnail&url='
},
'picplz.com': {
reg: new RegExp('http:\\/\\/picplz.com\\/([a-zA-Z0-9_\\-]+)','g'),
tail: '/thumb/'
},
'raw': {
reg: new RegExp('[a-zA-Z0-9]+:\\/\\/.+\\/.+\\.(jpg|jpeg|jpe|png|gif)', 'gi')
},
'youtube.com': {
reg: new RegExp('href="(http:\\/\\/(www.)?youtube.com\\/watch\\?v\\=([A-Za-z0-9_\\-]+))','g'),
base: 'http://img.youtube.com/vi/',
tail: '/default.jpg',
}
},
init:
function init() {
ui.Template.reg_url = ''//ui.Template.reg_vaild_preceding_chars
+ '('
+ ui.Template.reg_url_proto_chars
+ ui.Template.reg_url_path_chars_1
+ '*'
+ ui.Template.reg_url_path_chars_2
+ '+)';
ui.Template.reg_user = new RegExp('(^|[^a-zA-Z0-9_!#$%&*@@])'
+ ui.Template.reg_user_name_chars, 'g');
ui.Template.reg_list = new RegExp('(^|[^a-zA-Z0-9_!#$%&*@@])'
+ ui.Template.reg_list_name_template, 'ig');
ui.Template.reg_link = new RegExp(ui.Template.reg_url);
ui.Template.reg_link_g = new RegExp(ui.Template.reg_url, 'g');
ui.Template.reg_hash_tag = new RegExp(ui.Template.reg_hash_tag_template
.replace(new RegExp('{%LATIN_CHARS%}', 'g'), ui.Template.reg_hash_tag_latin_chars)
.replace(new RegExp('{%NONLATIN_CHARS%}', 'g'), ui.Template.reg_hash_tag_nonlatin_chars)
, 'ig');
ui.Template.tweet_m = {
ID:'', TWEET_ID:'', RETWEET_ID:''
, REPLY_ID:'',SCREEN_NAME:'',REPLY_NAME:'', USER_NAME:''
, PROFILE_IMG:'', TEXT:'', SOURCE:'', SCHEME:''
, IN_REPLY:'', RETWEETABLE:'', REPLY_TEXT:'', RETWEET_TEXT:''
, RETWEET_MARK:'', SHORT_TIMESTAMP:'', TIMESTAMP:'', FAV_CLASS:''
, DELETABLE:'', TWEET_FONT_SIZE:'', TWEET_FONT: ''
, TWEET_LINE_HEIGHT:''
, STATUS_INDICATOR:'', TRANS_Delete:''
, TRANS_Official_retweet_this_tweet:'', TRANS_Reply_All:''
, TRANS_Reply_this_tweet:'', TRANS_RT_this_tweet:''
, TRANS_Send_Message:'', TRANS_Send_Message_to_them:''
, TRANS_via:'', TRANS_View_more_conversation:''
, TWEET_BASE_URL: '', IN_THREAD: ''
, COLOR_LABEL: ''
};
ui.Template.trending_topic_m = {
ID:'', NAME:''
};
ui.Template.retweeted_by_m = {
ID:'', TWEET_ID:'', RETWEET_ID:''
, REPLY_ID:'',SCREEN_NAME:'',REPLY_NAME:'', USER_NAME:''
, PROFILE_IMG:'', TEXT:'', SOURCE:'', SCHEME:''
, IN_REPLY:'', RETWEETABLE:'', REPLY_TEXT:'', RETWEET_TEXT:''
, RETWEET_MARK:'', SHORT_TIMESTAMP:'', TIMESTAMP:'', FAV_CLASS:''
, DELETABLE:'', TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
, STATUS_INDICATOR:'', TRANS_Delete:''
, TRANS_Official_retweet_this_tweet:'', TRANS_Reply_All:''
, TRANS_Reply_this_tweet:'', TRANS_RT_this_tweet:''
, TRANS_Send_Message:'', TRANS_Send_Message_to_them:''
, TRANS_via:'', TRANS_View_more_conversation:''
, TRANS_retweeted_by:'', TRANS_Show_retweeters:''
, TRANS_Click_to_show_retweeters:''
, TWEET_BASE_URL: ''
};
ui.Template.message_m = {
ID:'', TWEET_ID:'', SCREEN_NAME:'', RECIPIENT_SCREEN_NAME:''
, USER_NAME:'', PROFILE_IMG:'', TEXT:''
, SCHEME:'', TIMESTAMP:''
, TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
, TRANS_Reply_Them:''
};
ui.Template.search_m = {
ID:'', TWEET_ID:'', SCREEN_NAME:''
, USER_NAME:'', PROFILE_IMG:'', TEXT:'', SOURCE:''
, SCHEME:'', SHORT_TIMESTAMP:'', TIMESTAMP:''
, TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
, TRANS_via:''
, TWEET_BASE_URL: ''
};
ui.Template.people_m = {
USER_ID:'', SCREEN_NAME:'', USER_NAME:'', DESCRIPTION:''
, PROFILE_IMG:'', FOLLOWING:'', TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
};
ui.Template.list_m = {
LIST_ID:'', SCREEN_NAME:'', SLUG:'', NAME:'', MODE:''
, DESCRIPTION:'', PROFILE_IMG:'', FOLLOWING:''
, TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
};
ui.Template.view_m = {
ID:'', CLASS:'tweetview', NAME: '', CAN_CLOSE: '', ROLE: ''
};
ui.Template.indicator_m = {
TARGET: '', TITLE: '', ICON: '', ROLE: ''
};
ui.Template.kismet_rule_m = {
TYPE:'', DISABLED:'', FIELD:'', PATTERN:''
, METHOD:'', ACTIONS: '', ADDITION: '', NAME: ''
};
ui.Template.status_draft_m = {
MODE:'', TEXT:'', REPLY_TO_ID: '', REPLY_TEXT: ''
, RECIPIENT: ''
};
ui.Template.update_trans();
},
update_trans:
function update_trans() {
ui.Template.people_vcard_m = {
TRANS_info: _('info'), TRANS_stat: _('stat')
, TRANS_name: _('name'), TRANS_bio: _('bio')
, TRANS_web: _('web'), TRANS_location: _('location')
, TRANS_join: _('join'), TRANS_tweet_cnt: _('tweet_cnt')
, TRANS_tweet_cnt: _('tweet_cnt')
, TRANS_follower_cnt: _('follower_cnt')
, TRANS_friend_cnt: _('friend_cnt')
, TRANS_listed_cnt: _('listed_cnt')
, TRANS_relation: _('relation')
, TRANS_edit: _('edit')
, TRANS_follow: _('follow'), TRANS_more_actions: _('more_actions')
, TRANS_mention_them: _('mention_them')
, TRANS_message_them: _('send_message_to_them')
, TRANS_add_to_list: _('add_to_list')
, TRANS_block: _('block')
, TRANS_unblock: _('unblock')
, TRANS_report_spam: _('report_spam')
, TRANS_tweets: _('tweets'), TRANS_favs: _('favs')
, TRANS_followers: _('followers'), TRANS_friends: _('friends')
, TRANS_fellowship: _('fellowship')
, TRANS_lists: _('lists'), TRANS_lists_of_them: _('lists_of_them')
, TRANS_lists_following_them: _('lists_following_them')
, TRANS_create_a_list: _('create_a_list')
}
ui.Template.people_vcard_t = ui.Template.render(ui.Template.people_vcard_t_orig, ui.Template.people_vcard_m);
},
form_dm:
function form_dm(dm_obj, pagename) {
var timestamp = Date.parse(dm_obj.created_at);
var created_at = new Date();
created_at.setTime(timestamp);
var created_at_str = ui.Template.to_long_time_string(created_at);
var created_at_short_str = ui.Template.to_short_time_string(created_at);
var text = ui.Template.form_text(dm_obj);
var m = ui.Template.message_m;
m.ID = pagename + '-' + dm_obj.id_str;
m.TWEET_ID = dm_obj.id_str;
m.SCREEN_NAME = dm_obj.sender.screen_name;
m.RECIPIENT_SCREEN_NAME = dm_obj.recipient.screen_name;
m.USER_NAME = dm_obj.sender.name;
m.DESCRIPTION = dm_obj.sender.description;
m.PROFILE_IMG = util.big_avatar(dm_obj.sender.profile_image_url_https);
m.TEXT = text;
m.SCHEME = 'message';
m.TIMESTAMP = created_at_str;
m.SHORT_TIMESTAMP = created_at_short_str;
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
m.TWEET_FONT = globals.tweet_font;
m.TRANS_Reply_Them = "Reply Them";
return ui.Template.render(ui.Template.message_t, m);
},
// This function returns the html for the given tweet_obj.
form_tweet:
function form_tweet (tweet_obj, pagename, in_thread) {
var retweet_name = '';
var retweet_str = '';
var retweet_id = '';
var id = tweet_obj.id_str;
if (tweet_obj.hasOwnProperty('retweeted_status')) {
retweet_name = tweet_obj['user']['screen_name'];
tweet_obj['retweeted_status'].favorited = tweet_obj.favorited; // The favorite status of the embedded tweet is not reliable, use outer one.
tweet_obj = tweet_obj['retweeted_status'];
retweet_id = tweet_obj.id_str;
}
var reply_name = tweet_obj.in_reply_to_screen_name;
var reply_id = tweet_obj.hasOwnProperty('in_reply_to_status_id_str')
? tweet_obj.in_reply_to_status_id_str:tweet_obj.in_reply_to_status_id;
var reply_str = (reply_id != null) ?
_('reply_to') + ' <a class="who_href" href="#'
+ reply_name + '">'
+ reply_name + '</a>'
: '';
var in_thread = in_thread == true ? true: false;
var timestamp = Date.parse(tweet_obj.created_at);
var created_at = new Date();
created_at.setTime(timestamp);
var created_at_str = ui.Template.to_long_time_string(created_at);
var created_at_short_str = ui.Template.to_short_time_string(created_at);
// choose color scheme
var scheme = 'normal';
if (tweet_obj.entities && tweet_obj.entities.user_mentions) {
for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1)
{
if (tweet_obj.entities.user_mentions[i].screen_name
== globals.myself.screen_name)
{
scheme = 'mention';
}
}
}
if (tweet_obj.user.screen_name == globals.myself.screen_name) {
scheme = 'me';
}
if (retweet_name != '') {
retweet_str = _('retweeted_by') + ' <a class="who_href" href="#'
+ retweet_name + '">'
+ retweet_name + '</a>, ';
}
var alt_text = tweet_obj.text;
var link = '';
if (tweet_obj.entities && tweet_obj.entities.urls) {
var urls = null;
if (tweet_obj.entities.media) {
urls = tweet_obj.entities.urls.concat(tweet_obj.entities.media);
} else {
urls = tweet_obj.entities.urls;
}
for (var i = 0, l = urls.length; i < l; i += 1) {
var url = urls[i];
if (url.url && url.expanded_url) {
tweet_obj.text = tweet_obj.text.replace(url.url, url.expanded_url);
}
}
if (tweet_obj.entities.urls.length > 0) {
link = tweet_obj.entities.urls[0].expanded_url;
}
}
var text = ui.Template.form_text(tweet_obj);
// if the tweet contains user_mentions (which are provided by the Twitter
// API, not by the StatusNet API), it will here replace the
// contents of the 'who_ref'-a-tag by the full name of this user.
if (tweet_obj.entities && tweet_obj.entities.user_mentions) {
for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1)
{
// hotot_log('form_tweet', 'user mention: ' + tweet_obj.entities.user_mentions[i].screen_name);
var screen_name = tweet_obj.entities.user_mentions[i].screen_name;
var name = tweet_obj.entities.user_mentions[i].name.replace(/"/g, '"');
var reg_ulink = new RegExp('>(' + screen_name + ')<', 'ig');
text = text.replace(reg_ulink, ' title="' + name + '">$1<')
}
// If we get here, and there are still <a who_href="...">-tags
// without title attribute, the user name was probably misspelled.
// If I then remove the tag, the incorrect user name is not
// highlighted any more, which fixes #415 for twitter.
// (It does not work for identi.ca, because the identi.ca API
// does not provide user_mentions.)
var re = /\<a class=\"who_href\" href=\"[^"]*\"\>([^<]*)\<\/a\>/gi
text = text.replace(re, '$1');
// hotot_log('form_tweet', 'resulting text: ' + text);
}
var m = ui.Template.tweet_m;
m.ID = pagename+'-'+id;
m.TWEET_ID = id;
m.RETWEET_ID = retweet_id;
m.REPLY_ID = reply_id != null? reply_id:'';
m.IN_THREAD = in_thread;
m.SCREEN_NAME = tweet_obj.user.screen_name;
m.REPLY_NAME = reply_id != null? reply_name: '';
m.USER_NAME = tweet_obj.user.name;
m.DESCRIPTION = tweet_obj.user.description;
m.PROFILE_IMG = util.big_avatar(tweet_obj.user.profile_image_url_https);
m.TEXT = text;
m.ALT = ui.Template.convert_chars(alt_text);
m.SOURCE = tweet_obj.source.replace('href', 'target="_blank" href');
m.SCHEME = scheme;
m.IN_REPLY = (reply_id != null && !in_thread) ? 'block' : 'none';
m.RETWEETABLE = (tweet_obj.user.protected || scheme == 'me' )? 'false':'true';
m.COLOR_LABEL = kismet.get_user_color(tweet_obj.user.screen_name);
m.REPLY_TEXT = reply_str;
m.RETWEET_TEXT = retweet_str;
m.RETWEET_MARK = retweet_name != ''? 'retweet_mark': '';
m.SHORT_TIMESTAMP = created_at_short_str;
m.TIMESTAMP = created_at_str;
m.FAV_CLASS = tweet_obj.favorited? 'faved': '';
m.DELETABLE = scheme == 'me'? 'true': 'false';
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
m.STATUS_INDICATOR = ui.Template.form_status_indicators(tweet_obj);
m.TRANS_Delete = _('delete');
m.TRANS_Delete_this_tweet = _('delete_this_tweet');
m.TRANS_Loading = _('loading_dots');
m.TRANS_Official_retweet_this_tweet = _('official_retweet_this_tweet');
m.TRANS_Reply_All = _('reply_all');
m.TRANS_Reply_this_tweet = _('reply_this_tweet');
m.TRANS_RT_this_tweet = _('rt_this_tweet');
m.TRANS_Send_Message = _('send_message');
m.TRANS_Send_Message_to_them = _('send_message_to_them');
m.TRANS_via = _('via');
m.TRANS_View_more_conversation = _('view_more_conversation');
m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.user.screen_name + '/status':'https://identi.ca/notice';
m.LINK = link;
return ui.Template.render(ui.Template.tweet_t, m);
},
form_retweeted_by:
function form_retweeted_by(tweet_obj, pagename) {
var retweet_name = '';
var retweet_str = '';
var retweet_id = '';
var id = tweet_obj.id_str;
if (tweet_obj.hasOwnProperty('retweeted_status')) {
retweet_name = tweet_obj['user']['screen_name'];
tweet_obj['retweeted_status'].favorited = tweet_obj.favorited; // The favorite status of the embedded tweet is not reliable, use outer one.
tweet_obj = tweet_obj['retweeted_status'];
retweet_id = tweet_obj.id_str;
}
var reply_name = tweet_obj.in_reply_to_screen_name;
var reply_id = tweet_obj.hasOwnProperty('in_reply_to_status_id_str')
? tweet_obj.in_reply_to_status_id_str:tweet_obj.in_reply_to_status_id;
var reply_str = (reply_id != null) ?
_('Reply to @') + ' <a class="who_href" href="#'
+ reply_name + '">'
+ reply_name + '</a>: '
: '';
var timestamp = Date.parse(tweet_obj.created_at);
var created_at = new Date();
created_at.setTime(timestamp);
var created_at_str = ui.Template.to_long_time_string(created_at);
var created_at_short_str = ui.Template.to_short_time_string(created_at);
// choose color scheme
var scheme = 'normal';
if (tweet_obj.entities && tweet_obj.entities.user_mentions) {
for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1)
{
if (tweet_obj.entities.user_mentions[i].screen_name
== globals.myself.screen_name)
{
scheme = 'mention';
}
}
}
if (tweet_obj.user.screen_name == globals.myself.screen_name) {
scheme = 'me';
}
if (retweet_name != '') {
retweet_str = _('retweeted_by') + ' <a class="who_href" href="#'
+ retweet_name + '">'
+ retweet_name + '</a>, ';
}
var m = ui.Template.retweeted_by_m;
m.ID = pagename+'-'+id;
m.TWEET_ID = id;
m.RETWEET_ID = retweet_id;
m.REPLY_ID = reply_id != null? reply_id:'';
m.SCREEN_NAME = tweet_obj.user.screen_name;
m.REPLY_NAME = reply_id != null? reply_name: '';
m.USER_NAME = tweet_obj.user.name;
m.PROFILE_IMG = util.big_avatar(tweet_obj.user.profile_image_url_https);
m.TEXT = ui.Template.form_text(tweet_obj);
m.SOURCE = tweet_obj.source.replace('href', 'target="_blank" href');
m.SCHEME = scheme;
m.IN_REPLY = (reply_id != null && pagename.split('-').length < 2) ? 'block' : 'none';
m.RETWEETABLE = (tweet_obj.user.protected || scheme == 'me' )? 'false':'true';
m.REPLY_TEXT = reply_str;
m.RETWEET_TEXT = retweet_str;
m.RETWEET_MARK = retweet_name != ''? 'retweet_mark': '';
m.SHORT_TIMESTAMP = created_at_short_str;
m.TIMESTAMP = created_at_str;
m.FAV_CLASS = tweet_obj.favorited? 'faved': '';
m.DELETABLE = scheme == 'me'? 'true': 'false';
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
m.STATUS_INDICATOR = ui.Template.form_status_indicators(tweet_obj);
m.TRANS_Delete = _('delete');
m.TRANS_Delete_this_tweet = _('delete_this_tweet');
m.TRANS_Loading = _('loading_dots');
m.TRANS_Official_retweet_this_tweet = _('official_retweet_this_tweet');
m.TRANS_Reply_All = _('reply_All');
m.TRANS_Reply_this_tweet = _('reply_this_tweet');
m.TRANS_RT_this_tweet = _('rt_this_tweet');
m.TRANS_Send_Message = _('send_message');
m.TRANS_Send_Message_to_them = _('send_message_to_them');
m.TRANS_via = _('via');
m.TRANS_View_more_conversation = _('view_more_conversation');
m.TRANS_Retweeted_by = _('retweeted_by');
m.TRANS_Show_retweeters = _('click_to_show');
m.TRANS_Click_to_show_retweeters = _('click_to_show_retweeters');
m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.user.screen_name + '/status':'https://identi.ca/notice';
return ui.Template.render(ui.Template.retweeted_by_t, m);
},
form_search:
function form_search(tweet_obj, pagename) {
if (tweet_obj.user != undefined) {
// use phoenix_search ... well, in fact, the original parser is totally useless.
return ui.Template.form_tweet(tweet_obj, pagename);
}
var id = tweet_obj.id_str;
var source = tweet_obj.source.replace(/>/g, '>').replace(/</g, '<').replace(/"/g, '');
var timestamp = Date.parse(tweet_obj.created_at);
var created_at = new Date();
created_at.setTime(timestamp);
var created_at_str = ui.Template.to_long_time_string(created_at);
var created_at_short_str = ui.Template.to_short_time_string(created_at);
var text = ui.Template.form_text(tweet_obj);
// choose color scheme
var scheme = 'normal';
if (text.indexOf(globals.myself.screen_name) != -1) {
scheme = 'mention';
}
if (tweet_obj.from_user == globals.myself.screen_name) {
scheme = 'me';
}
var link = '';
if (tweet_obj.entities.urls.length > 0) {
link = tweet_obj.entities.urls[0].expanded_url;
}
var m = ui.Template.search_m;
m.ID = pagename + '-' + id;
m.TWEET_ID = id;
m.SCREEN_NAME = tweet_obj.from_user;
m.USER_NAME = tweet_obj.from_user_name;
m.PROFILE_IMG = util.big_avatar(tweet_obj.profile_image_url_https);
m.TEXT = text;
m.SOURCE = source.replace('href', 'target="_blank" href');
m.SCHEME = scheme;
m.SHORT_TIMESTAMP = created_at_short_str;
m.TIMESTAMP = created_at_str;
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
m.TRANS_via = _('via');
m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.from_user + '/status':'https://identi.ca/notice';
m.LINK = link;
return ui.Template.render(ui.Template.search_t, m);
},
form_people:
function form_people(user_obj, pagename) {
var m = ui.Template.people_m;
m.USER_ID = pagename + '-' + user_obj.id_str;
m.SCREEN_NAME = user_obj.screen_name;
m.USER_NAME = user_obj.name;
m.DESCRIPTION = user_obj.description;
m.PROFILE_IMG = util.big_avatar(user_obj.profile_image_url_https);
m.FOLLOWING = user_obj.following;
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
return ui.Template.render(ui.Template.people_t, m);
},
form_list:
function form_people(list_obj, pagename) {
var m = ui.Template.list_m;
m.LIST_ID = pagename + '-' + list_obj.id_str;
m.SCREEN_NAME = list_obj.user.screen_name;
m.SLUG = list_obj.slug;
m.NAME = list_obj.name;
m.MODE = list_obj.mode;
m.DESCRIPTION = list_obj.description;
m.PROFILE_IMG = util.big_avatar(list_obj.user.profile_image_url_https);
m.FOLLOWING = list_obj.following;
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
return ui.Template.render(ui.Template.list_t, m);
},
form_view:
function form_view(name, title, cls) {
var m = ui.Template.view_m;
m.ID = name + '_tweetview';
m.NAME = name;
m.CLASS = cls;
if (name == 'home') {
m.CAN_CLOSE = 'none';
} else {
m.CAN_CLOSE = 'block';
}
if (ui.Slider.system_views.hasOwnProperty(name)) {
m.ROLE = 'system_view';
} else {
m.ROLE = 'custom_view';
}
return ui.Template.render(ui.Template.view_t, m);
},
form_indicator:
function form_indicator(target, title, icon) {
var m = ui.Template.indicator_m;
m.TARGET = target
m.TITLE = title;
m.ICON = icon;
if (ui.Slider.system_views.hasOwnProperty(target)) {
m.ROLE = 'system_view';
} else {
m.ROLE = 'custom_view';
}
return ui.Template.render(ui.Template.indicator_t, m);
},
form_kismet_rule:
function form_kismet_rule(rule) {
var m = ui.Template.kismet_rule_m;
m.NAME = rule.name;
m.TYPE = rule.type;
m.METHOD = rule.method;
m.PATTERN = rule.pattern;
m.ACTIONS = rule.actions.join(':');
m.ADDITION = rule.actions.indexOf(3)!=-1?'archive_name="'+rule.archive_name+'"':'archive_name=""';
m.FIELD = rule.field;
m.DISABLED = rule.disabled;
return ui.Template.render(ui.Template.kismet_rule_t, m);
},
form_status_draft:
function form_status_draft(draft) {
var m = ui.Template.status_draft_m;
m.MODE = draft.mode;
m.TEXT = draft.text.replace(/</g, "<").replace(/>/g,">");
if (m.MODE == ui.StatusBox.MODE_REPLY) {
m.REPLY_TO_ID = draft.reply_to_id;
m.REPLY_TEXT = draft.reply_text
} else if (m.MODE == ui.StatusBox.MODE_DM) {
m.RECIPIENT = draft.recipient;
} else if (m.MODE == ui.StatusBox.MODE_IMG) {
}
return ui.Template.render(ui.Template.status_draft_t, m);
},
fill_people_vcard:
function fill_people_vcard(user_obj, vcard_container) {
var created_at = new Date(Date.parse(user_obj.created_at));
var now = new Date();
var differ = Math.floor((now-created_at)/(1000 * 60 * 60 * 24));
var created_at_str = ui.Template.to_long_time_string(created_at);
vcard_container.find('.profile_img_wrapper')
.attr('href', user_obj.profile_image_url_https.replace(/_normal/, ''))
.attr('style', 'background-image:url('+util.big_avatar(user_obj.profile_image_url_https)+');');
vcard_container.find('.screen_name')
.attr('href', conf.get_current_profile().preferences.base_url + user_obj.screen_name)
.text(user_obj.screen_name);
vcard_container.find('.name').text(user_obj.name);
vcard_container.find('.tweet_cnt').text(user_obj.statuses_count);
vcard_container.find('.tweet_per_day_cnt').text(
Math.round(user_obj.statuses_count / differ * 100)/ 100);
vcard_container.find('.follower_cnt').text(user_obj.followers_count);
vcard_container.find('.friend_cnt').text(user_obj.friends_count);
vcard_container.find('.listed_cnt').text(user_obj.listed_count);
vcard_container.find('.bio').unbind().empty().html(
ui.Template.form_text_raw(user_obj.description));
ui.Main.bind_tweet_text_action(vcard_container.find('.bio'));
vcard_container.find('.location').text('').text(user_obj.location);
vcard_container.find('.join').text(created_at_str);
if (user_obj.url) {
vcard_container.find('.web').text(user_obj.url)
vcard_container.find('.web').attr('href', user_obj.url);
} else {
vcard_container.find('.web').text('')
vcard_container.find('.web').attr('href', '#');
}
vcard_container.find('.people_vcard_radio_group .mochi_button_group_item').attr('name', 'people_'+user_obj.screen_name+'_vcard')
vcard_container.find('.people_view_toggle .mochi_button_group_item').attr('name', 'people_'+user_obj.screen_name+'_views')
},
fill_list_vcard:
function fill_list_vcard(view, list_obj) {
var vcard_container = view._header;
vcard_container.find('.profile_img_wrapper')
.attr('style', 'background-image:url('
+ util.big_avatar(list_obj.user.profile_image_url_https) + ');');
vcard_container.find('.name')
.attr('href', conf.get_current_profile().preferences.base_url + list_obj.user.screen_name + '/' + list_obj.slug)
.text(list_obj.full_name);
vcard_container.find('.owner')
.attr('href', conf.get_current_profile().preferences.base_url + list_obj.user.screen_name)
.text(list_obj.user.screen_name);
vcard_container.find('.description').text(list_obj.description);
},
convert_chars:
function convert_chars(text) {
text = text.replace(/"/g, '"');
text = text.replace(/'/g, ''');
text = text.replace(/\$/g, '$');
return text;
},
// This function applies some basic replacements to tweet.text, and returns
// the resulting string.
// This is not the final text that will appear in the UI, form_tweet will also do
// some modifications. from_tweet will search for the a-tags added in this
// function, to do the modifications.
form_text:
function form_text(tweet) {
//hotot_log('form_text in', tweet.text);
var text = ui.Template.convert_chars(tweet.text);
text = text.replace(ui.Template.reg_link_g, function replace_url(url) {
if (url.length > 51) url_short = url.substring(0,48) + '...';
else url_short = url;
return ' <a href="'+url+'" target="_blank">' + url_short + '</a>';
});
text = text.replace(/href="www/g, 'href="http://www');
text = text.replace(ui.Template.reg_list
, '$1@<a class="list_href" href="#$2">$2</a>');
text = text.replace(ui.Template.reg_user
, '$1@<a class="who_href" href="#$2">$2</a>');
text = text.replace(ui.Template.reg_hash_tag
, '$1<a class="hash_href" href="#$2">#$2</a>');
text = text.replace(/href="(http:\/\/hotot.in\/(\d+))"/g
, 'full_text_id="$2" href="$1"');
text = text.replace(/[\r\n]\s+[\r\n]/g, '\n\n');
text = text.replace(/\n/g, '<br/>');
if (ui.Template.reg_is_rtl.test(text)) {
text = '<div class="text_inner" align="right" dir="rtl">' + text + '</div>';
} else {
text = '<div class="text_inner">' + text + '</div>';
}
if (conf.get_current_profile().preferences.use_media_preview) {
text += '<div class="preview">'
+ ui.Template.form_preview(tweet)
+ '</div>';
}
//hotot_log('form_text out', text);
return text;
},
form_text_raw:
function form_text_raw(raw_text) {
var text = raw_text;
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(ui.Template.reg_link_g, ' <a href="$1" target="_blank">$1</a>');
text = text.replace(/href="www/g, 'href="http://www');
text = text.replace(ui.Template.reg_list
, '$1@<a class="list_href" href="#$2">$2</a>');
text = text.replace(ui.Template.reg_user
, '$1@<a class="who_href" href="#$2">$2</a>');
text = text.replace(ui.Template.reg_hash_tag
, '$1<a class="hash_href" href="#$2">#$2</a>');
text = text.replace(/href="(http:\/\/hotot.in\/(\d+))"/g
, 'full_text_id="$2" href="$1"');
text = text.replace(/[\r\n]\s+[\r\n]/g, '\n\n');
text = text.replace(/\n/g, '<br/>');
return text;
},
form_media:
function form_media(href, src, direct_url) {
if (direct_url != undefined) {
return '<a direct_url="'+direct_url+'" href="'+href+'"><img src="'+ src +'" /></a>';
} else {
return '<a href="'+href+'" target="_blank"><img src="'+ src +'" /></a>';
}
},
form_preview:
function form_preview(tweet) {
var html_arr = [];
var link_reg = ui.Template.preview_link_reg;
for (var pvd_name in link_reg) {
var match = link_reg[pvd_name].reg.exec(tweet.text);
while (match != null) {
switch (pvd_name) {
case 'img.ly':
case 'twitgoo.com':
html_arr.push(
ui.Template.form_media(
match[0], link_reg[pvd_name].base + match[1],
link_reg[pvd_name].direct_base + match[1]));
break;
case 'twitpic.com':
html_arr.push(
ui.Template.form_media(
match[0], link_reg[pvd_name].base + match[1]));
break;
case 'instagr.am':
html_arr.push(
ui.Template.form_media(
match[0], match[0] + link_reg[pvd_name].tail,
match[0] + link_reg[pvd_name].direct_tail));
break;
case 'yfrog.com':
case 'moby.to':
case 'picplz.com':
html_arr.push(
ui.Template.form_media(
match[0], match[0] + link_reg[pvd_name].tail));
break;
case 'plixi.com':
html_arr.push(
ui.Template.form_media(
match[0], link_reg[pvd_name].base +match[0]));
break;
case 'raw':
html_arr.push(
ui.Template.form_media(
match[0], match[0], match[0]));
break;
case 'youtube.com':
html_arr.push(
ui.Template.form_media(
match[0], link_reg[pvd_name].base + match[2] + link_reg[pvd_name].tail));
break;
}
match = link_reg[pvd_name].reg.exec(tweet.text);
}
}
// twitter official picture service
if (tweet.entities && tweet.entities.media) {
for (var i = 0; i < tweet.entities.media.length; i += 1) {
var media = tweet.entities.media[i];
if (media.expanded_url && media.media_url) {
html_arr.push(
ui.Template.form_media(
tweet.entities.media[i].expanded_url,
tweet.entities.media[i].media_url + ':thumb',
tweet.entities.media[i].media_url + ':large'
));
}
}
}
if (conf.get_current_profile().preferences.filter_nsfw_media && tweet.text.match(/nsfw/ig))
html_arr = ['<i>NSFW image hidden</i>'];
if (html_arr.length != 0) {
return '<p class="media_preview">'+ html_arr.join('')+'</p>';
}
return '';
},
form_status_indicators:
function form_status_indicators(tweet) {
},
render:
function render(tpl, map) {
var text = tpl
var replace = false;
for (var k in map) {
replace = typeof map[k] == 'string' ? map[k] : '';
text = text.replace(new RegExp('{%'+k+'%}', 'g'), replace);
}
return text;
},
to_long_time_string:
function (datetime) {
return moment(datetime).toLocaleString();
},
to_short_time_string:
function (dataObj) {
var is_human = conf.get_current_profile().preferences.show_relative_timestamp,
now = moment(),
mobj = moment(dataObj),
time_str;
if (is_human) {
try {
mobj.lang(i18n.current);
mobj.lang();
} catch (e) {
mobj.lang(false);
}
if(now.diff(mobj, 'hours', true) > 6) {
time_str = mobj.calendar();
} else {
time_str = mobj.fromNow();
}
} else {
if(now.diff(mobj, 'days', true) > 1) {
time_str = mobj.format('YYYY-MM-DD HH:mm:ss');
} else {
time_str = mobj.format('YYYY-MM-DD HH:mm:ss');
}
}
return time_str;
}
}
| AshKyd/Hotot | data/js/ui.template.js | JavaScript | lgpl-3.0 | 59,989 |
/*
* logic2j - "Bring Logic to your Java" - Copyright (c) 2017 Laurent.Tettoni@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.logic2j.core.impl;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.logic2j.core.ExtractingSolutionListener;
import org.logic2j.core.PrologTestBase;
import org.logic2j.engine.solver.holder.GoalHolder;
/**
* Lowest-level tests of the Solver: check core primitives: true, fail, cut, and, or. Check basic unification.
* See other test classes for testing the solver against theories.
*/
public class SolverTest extends PrologTestBase {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SolverTest.class);
// ---------------------------------------------------------------------------
// Simplest primitives and undefined goal
// ---------------------------------------------------------------------------
@Test
public void primitiveFail() {
final Object goal = unmarshall("fail");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(0);
}
@Test
public void primitiveTrue() {
final Object goal = unmarshall("true");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(1);
}
@Test
public void primitiveCut() {
final Object goal = unmarshall("!");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(1);
}
@Test
public void atomUndefined() {
final Object goal = unmarshall("undefined_atom");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(0);
}
@Test
public void primitiveTrueAndTrue() {
final Object goal = unmarshall("true,true");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(1);
}
@Test
public void primitiveTrueOrTrue() {
final Object goal = unmarshall("true;true");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(2);
}
@Test
public void corePrimitivesThatYieldUniqueSolution() {
final String[] SINGLE_SOLUTION_GOALS = new String[]{ //
"true", //
"true, true", //
"true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true", //
"!", //
"!, !", //
};
countOneSolution(SINGLE_SOLUTION_GOALS);
}
@Test
public void corePrimitivesThatYieldNoSolution() {
final String[] NO_SOLUTION_GOALS = new String[]{ //
"fail", //
"fail, fail", //
"fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail, fail", //
"true, fail", //
"fail, true", //
"true, true, fail", //
"true, fail, !", //
};
countNoSolution(NO_SOLUTION_GOALS);
}
/**
* This is a special feature of logic2j: AND with any arity
*/
@Test
public void nonBinaryAnd() {
loadTheoryFromTestResourcesDir("test-functional.pro");
final String[] SINGLE_SOLUTION_GOALS = new String[]{ //
"','(true)", //
"','(true, true)", //
"','(true, !, true)", //
};
countOneSolution(SINGLE_SOLUTION_GOALS);
}
@Test
public void or() {
loadTheoryFromTestResourcesDir("test-functional.pro");
countNSolutions(2, "';'(true, true)");
countNSolutions(2, "true; true");
//
countNSolutions(3, "true; true; true");
//
GoalHolder solutions;
solutions = this.prolog.solve("X=a; X=b; X=c");
assertThat(solutions.var("X").list().toString()).isEqualTo("[a, b, c]");
}
/**
* This is a special feature of logic2j: OR with any arity
*/
@Test
public void nonBinaryOr() {
loadTheoryFromTestResourcesDir("test-functional.pro");
countNSolutions(2, "';'(true, true)");
// if (Solver.INTERNAL_OR) {
// countNSolutions(1, "';'(true)");
// countNSolutions(3, "';'(true, true, true)");
// }
countNSolutions(1, "true");
countNSolutions(3, "true; true; true");
}
@Test
public void orWithVars() {
GoalHolder solutions;
solutions = this.prolog.solve("X=1; Y=2");
final String actual = solutions.vars().list().toString();
assertThat("[{Y=Y, X=1}, {Y=2, X=X}]".equals(actual) || "[{X=1, Y=Y}, {X=X, Y=2}]".equals(actual)).isTrue();
}
@Test
public void orWithClause() {
loadTheoryFromTestResourcesDir("test-functional.pro");
GoalHolder solutions;
solutions = this.prolog.solve("or3(X)");
assertThat(solutions.var("X").list().toString()).isEqualTo("[a, b, c]");
}
@Test
public void not() {
// Surprisingly enough, the operator \+ means "not provable".
uniqueSolution("not(fail)", "\\+(fail)");
nSolutions(0, "not(true)", "\\+(true)");
}
// ---------------------------------------------------------------------------
// Basic unification
// ---------------------------------------------------------------------------
@Test
public void unifyLiteralsNoSolution() {
final Object goal = unmarshall("a=b");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(0);
}
@Test
public void unifyLiteralsOneSolution() {
final Object goal = unmarshall("c=c");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(1);
}
@Test
public void unifyAnonymousToAnonymous() {
final Object goal = unmarshall("_=_");
final int nbSolutions = solveWithExtractingListener(goal).count();
assertThat(nbSolutions).isEqualTo(1);
}
@Test
public void unifyVarToLiteral() {
final Object goal = unmarshall("Q=d");
final ExtractingSolutionListener listener = solveWithExtractingListener(goal);
assertThat(listener.count()).isEqualTo(1);
assertThat(listener.getVariables().toString()).isEqualTo("[Q]");
assertThat(marshall(listener.getValues("."))).isEqualTo("[d = d]");
assertThat(marshall(listener.getValues("Q"))).isEqualTo("[d]");
}
@Test
public void unifyVarToAnonymous() {
final Object goal = unmarshall("Q=_");
final ExtractingSolutionListener listener = solveWithExtractingListener(goal);
assertThat(listener.count()).isEqualTo(1);
assertThat(listener.getVariables().toString()).isEqualTo("[Q]");
assertThat(marshall(listener.getValues("."))).isEqualTo("[Q = _]");
assertThat(marshall(listener.getValues("Q"))).isEqualTo("[Q]");
}
@Test
public void unifyVarToVar() {
final Object goal = unmarshall("Q=Z");
final ExtractingSolutionListener listener = solveWithExtractingListener(goal);
assertThat(listener.count()).isEqualTo(1);
assertThat(listener.getVarNames().toString()).isEqualTo("[., Q, Z]");
assertThat(marshall(listener.getValues("."))).isEqualTo("[Q = Q]");
assertThat(marshall(listener.getValues("Q"))).isEqualTo("[Q]");
assertThat(marshall(listener.getValues("Z"))).isEqualTo("[Q]");
}
}
| ltettoni/logic2j | src/test/java/org/logic2j/core/impl/SolverTest.java | Java | lgpl-3.0 | 7,797 |
package org.openbase.jul.processing;
/*
* #%L
* JUL Processing Default
* %%
* Copyright (C) 2015 - 2021 openbase.org
* %%
* 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 General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openbase.jps.core.JPService;
import org.openbase.jps.exception.JPServiceException;
import org.openbase.jul.exception.MultiException;
/**
*
* * @author Divine <a href="mailto:DivineThreepwood@gmail.com">Divine Threepwood</a>
*/
public class VariableProcessorTest {
private TestVariableProvider provider;
public VariableProcessorTest() {
provider = new TestVariableProvider();
}
@BeforeClass
public static void setUpClass() throws JPServiceException {
JPService.setupJUnitTestMode();
}
/**
* Test of resolveVariables method, of class VariableProcessor.
*/
@Test(timeout = 5000)
public void testResolveVariables() throws Exception {
System.out.println("testResolveVariables");
String context = "${VAR_A} : Hey Mr ${VAR_B} is happy today because of Mrs ${VAR_C}. ${VAR_W}${VAR_O}${VAR_W}";
boolean throwOnError = true;
String expResult = "A : Hey Mr B is happy today because of Mrs C. WOW";
String result = VariableProcessor.resolveVariables(context, throwOnError, provider);
assertEquals(expResult, result);
}
/**
* Test of resolveVariables method, of class VariableProcessor.
*/
@Test(timeout = 5000)
public void testResolveVariablesErrorCase() throws Exception {
System.out.println("testResolveVariablesErrorCase");
String context = "${VAR_A} : Hey Mr ${VAR_D} is happy today because of Mrs ${VAR_C}. ${VAR_W}${VAR_Y}${VAR_W}";
boolean throwOnError = true;
String expResult = "A : Hey Mr is happy today because of Mrs C. WW";
try {
VariableProcessor.resolveVariables(context, throwOnError, provider);
fail("No exception is thrown in error case!");
} catch (MultiException ex) {
}
String result = VariableProcessor.resolveVariables(context, false, provider);
assertEquals(expResult, result);
}
public class TestVariableProvider extends VariableStore {
public TestVariableProvider() {
super("TestVarPro");
store("VAR_A", "A");
store("VAR_B", "B");
store("VAR_C", "C");
store("VAR_W", "W");
store("VAR_O", "O");
}
}
}
| DivineCooperation/jul | processing/default/src/test/java/org/openbase/jul/processing/VariableProcessorTest.java | Java | lgpl-3.0 | 3,307 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\network\mcpe\protocol\types;
class EntityLink{
public const TYPE_REMOVE = 0;
public const TYPE_RIDER = 1;
public const TYPE_PASSENGER = 2;
/** @var int */
public $fromEntityUniqueId;
/** @var int */
public $toEntityUniqueId;
/** @var int */
public $type;
/** @var bool */
public $immediate; //for dismounting on mount death
public function __construct(int $fromEntityUniqueId = null, int $toEntityUniqueId = null, int $type = null, bool $immediate = false){
$this->fromEntityUniqueId = $fromEntityUniqueId;
$this->toEntityUniqueId = $toEntityUniqueId;
$this->type = $type;
$this->immediate = $immediate;
}
}
| kabluinc/PocketMine-MP | src/pocketmine/network/mcpe/protocol/types/EntityLink.php | PHP | lgpl-3.0 | 1,388 |