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 |
|---|---|---|---|---|---|
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.util;
import android.content.Context;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import java.lang.reflect.Method;
public class WindowUtils {
private static final String LOGTAG = "Gecko" + WindowUtils.class.getSimpleName();
private WindowUtils() { /* To prevent instantiation */ }
/**
* Returns the best-guess physical device dimensions, including the system status bars. Note
* that DisplayMetrics.height/widthPixels does not include the system bars.
*
* via http://stackoverflow.com/a/23861333
*
* @param context the calling Activity's Context
* @return The number of pixels of the device's largest dimension, ignoring software status bars
*/
public static int getLargestDimension(final Context context) {
final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (Build.VERSION.SDK_INT >= 17) {
final DisplayMetrics realMetrics = new DisplayMetrics();
display.getRealMetrics(realMetrics);
return Math.max(realMetrics.widthPixels, realMetrics.heightPixels);
} else {
int tempWidth;
int tempHeight;
try {
final Method getRawH = Display.class.getMethod("getRawHeight");
final Method getRawW = Display.class.getMethod("getRawWidth");
tempWidth = (Integer) getRawW.invoke(display);
tempHeight = (Integer) getRawH.invoke(display);
} catch (Exception e) {
// This is the best we can do.
tempWidth = display.getWidth();
tempHeight = display.getHeight();
Log.w(LOGTAG, "Couldn't use reflection to get the real display metrics.");
}
return Math.max(tempWidth, tempHeight);
}
}
}
| Yukarumya/Yukarum-Redfoxes | mobile/android/geckoview/src/main/java/org/mozilla/gecko/util/WindowUtils.java | Java | mpl-2.0 | 2,284 |
/*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ScriptEngine.HostedScript.Library.Binary;
using ScriptEngine.Machine;
using ScriptEngine.Machine.Contexts;
/// <summary>
///
/// Коллекция байтов фиксированного размера с возможностью произвольного доступа и изменения по месту.
/// Размер буфера формально не ограничен, но поскольку все данные буфера полностью находятся в оперативной памяти, при попытке создать буфер слишком большого размера доступной памяти может оказаться недостаточно, в результате чего будет вызвано исключение. Поэтому при работе с буферами двоичных данных необходимо соотносить их размер с доступным объемом оперативной памяти.
/// При создании буфера можно указать порядок байтов, который будет использован для операций с целыми числами. При этом если буфер не создан явно, а получен с помощью вызова метода другого объекта, то порядок байтов в полученном буфере будет унаследован от порядка байтов, заданного для того объекта, метод которого вызывается.
/// Например, если буфер получен с помощью вызова метода ПрочитатьВБуферДвоичныхДанных, то порядок байтов в полученном буфере будет равен значению свойства ПорядокБайтов.
/// Возможен также более сложный случай наследования порядка байтов. Если буфер получен с помощью вызова метода ПолучитьБуферДвоичныхДанных, то порядок байтов у полученного буфера будет выбираться из объекта ЧтениеДанных, из которого был получен объект РезультатЧтенияДанных.
/// Порядок байтов, заданный для объекта ЧтениеДанных, будет использован во всех объектах, полученных на его основании.
/// </summary>
[ContextClass("БуферДвоичныхДанных", "BinaryDataBuffer")]
public class BinaryDataBuffer : AutoContext<BinaryDataBuffer>, ICollectionContext
{
private bool _readOnly;
private readonly byte[] _buffer;
public BinaryDataBuffer(byte[] buffer, ByteOrderEnum byteOrder = ByteOrderEnum.LittleEndian)
{
_buffer = buffer;
ByteOrder = byteOrder;
Converter = new EndianBitConverter();
Converter.IsLittleEndian = byteOrder == ByteOrderEnum.LittleEndian;
}
private EndianBitConverter Converter { get; }
// для операций с содержимым буфера внутри 1Script
//
public byte[] Bytes
{
get { return _buffer; }
}
/// <param name="size">
/// Размер буфера в байтах. </param>
/// <param name="byteOrder">
/// Порядок байтов.
/// Значение по умолчанию: LittleEndian. </param>
///
[ScriptConstructor]
public static BinaryDataBuffer Constructor(IValue size, IValue byteOrder = null)
{
var orderValue = byteOrder == null ? ByteOrderEnum.LittleEndian : ContextValuesMarshaller.ConvertParam<ByteOrderEnum>(byteOrder);
return new BinaryDataBuffer(
new byte[ContextValuesMarshaller.ConvertParam<int>(size)],
orderValue);
}
public override IValue GetIndexedValue(IValue index)
{
return ValueFactory.Create(Get((int) index.AsNumber()));
}
public override void SetIndexedValue(IValue index, IValue val)
{
ThrowIfReadonly();
int value = (int)val.AsNumber();
if (value < byte.MinValue || value > byte.MaxValue)
throw RuntimeException.InvalidArgumentValue();
var idx = (int)index.AsNumber();
_buffer[idx] = (byte) value;
}
/// <summary>
///
/// Текущий порядок байтов. Влияет на операции чтения и записи целых чисел в буфер.
/// </summary>
/// <value>ПорядокБайтов (ByteOrder)</value>
[ContextProperty("ПорядокБайтов", "ByteOrder")]
public ByteOrderEnum ByteOrder { get; set; }
/// <summary>
///
/// Размер буфера в байтах.
/// </summary>
/// <value>Число (Number)</value>
[ContextProperty("Размер", "Size")]
public long Size => _buffer.LongLength;
/// <summary>
///
/// Значение Истина указывает, что данный буфер предназначен только для чтения.
/// </summary>
/// <value>Булево (Boolean)</value>
[ContextProperty("ТолькоЧтение", "ReadOnly")]
public bool ReadOnly
{
get { return _readOnly; }
}
/// <summary>
///
/// Заменить значения, начиная с заданной позиции, значениями из заданного буфера.
/// </summary>
///
/// <param name="position">
/// Позиция, начиная с которой требуется записать содержимое буфера. </param>
/// <param name="bytes">
/// Байты, которыми нужно заполнить часть буфера. </param>
/// <param name="number">
/// Количество байт, которые требуется заменить. </param>
///
[ContextMethod("Записать", "Write")]
public void Write(int position, BinaryDataBuffer bytes, int number = 0)
{
ThrowIfReadonly();
if (number == 0)
Array.Copy(bytes._buffer, _buffer, bytes._buffer.Length);
else
Array.Copy(bytes._buffer, _buffer, number);
}
private byte[] GetBytes<T>(Converter<T, byte[]> converterOverload, T value, IValue byteOrder = null)
{
byte[] bytes;
if (byteOrder == null)
bytes = converterOverload(value);
else
{
try
{
var order = (ByteOrderEnum)(object)byteOrder.GetRawValue();
Converter.IsLittleEndian = order == ByteOrderEnum.LittleEndian;
bytes = converterOverload(value);
}
catch (InvalidCastException)
{
throw RuntimeException.InvalidArgumentType();
}
}
return bytes;
}
private void CopyBytes(int position, byte[] bytes)
{
for (int i = 0; i < bytes.Length; i++)
{
_buffer[position + i] = bytes[i];
}
}
/// <summary>
///
/// Записать целое 16-битное положительное число в заданную позицию.
/// </summary>
///
/// <param name="position">
/// Позиция, на которой требуется записать число. </param>
/// <param name="value">
/// Число, которое требуется записать.
/// Если значение не помещается в 16 бит, будет вызвано исключение. </param>
/// <param name="byteOrder">
/// Порядок байтов, который будет использован для кодировки числа при записи в буфер. Если не установлен, то будет использован порядок байтов, заданный для текущего экземпляра БуферДвоичныхДанных.
/// Значение по умолчанию: Неопределено. </param>
///
///
[ContextMethod("ЗаписатьЦелое16", "WriteInt16")]
public void WriteInt16(int position, int value, IValue byteOrder = null)
{
ThrowIfReadonly();
if (value < short.MinValue || value > short.MaxValue)
throw RuntimeException.InvalidArgumentValue();
var bytes = GetBytes(Converter.GetBytes, value, byteOrder);
CopyBytes(position, bytes);
}
/// <summary>
///
/// Записать целое 32-битное положительное число в заданную позицию.
/// </summary>
///
/// <param name="position">
/// Позиция, на которой требуется записать число. </param>
/// <param name="value">
/// Число, которое требуется записать.
/// Если значение не помещается в 32 бита, будет вызван исключение. </param>
/// <param name="byteOrder">
/// Порядок байтов, который будет использован для кодировки числа при записи в буфер. Если не установлен, то будет использован порядок байтов, заданный для текущего экземпляра БуферДвоичныхДанных.
/// Значение по умолчанию: Неопределено. </param>
[ContextMethod("ЗаписатьЦелое32", "WriteInt32")]
public void WriteInt32(int position, int value, IValue byteOrder = null)
{
ThrowIfReadonly();
var bytes = GetBytes(Converter.GetBytes, value, byteOrder);
CopyBytes(position, bytes);
}
/// <summary>
///
/// Записать целое 64-битное положительное число в заданную позицию.
/// </summary>
///
/// <param name="position">
/// Позиция, на которой требуется записать число. </param>
/// <param name="value">
/// Число, которое требуется записать.
/// Если значение не помещается в 64 бита, будет вызвано исключение. </param>
/// <param name="byteOrder">
/// Порядок байтов, который будет использован для кодировки числа при записи в буфер. Если не установлен, то используется порядок байтов, заданный для текущего экземпляра БуферДвоичныхДанных.
/// Значение по умолчанию: Неопределено. </param>
///
///
[ContextMethod("ЗаписатьЦелое64", "WriteInt64")]
public void WriteInt64(int position, long value, IValue byteOrder = null)
{
ThrowIfReadonly();
var bytes = GetBytes(Converter.GetBytes, value, byteOrder);
CopyBytes(position, bytes);
}
/// <summary>
///
/// Создает новый буфер, содержащий элементы текущего буфера в противоположном порядке.
/// </summary>
///
///
/// <returns name="BinaryDataBuffer"/>
///
[ContextMethod("Перевернуть", "Reverse")]
public BinaryDataBuffer Reverse()
{
var bytes = _buffer.Reverse().ToArray();
return new BinaryDataBuffer(bytes, ByteOrder);
}
/// <summary>
///
/// Получает значение элемента на указанной позиции.
/// </summary>
///
/// <param name="position">
/// Позиция элемента в буфере. Нумерация начинается с 0. </param>
///
/// <returns name="Number">
/// Числовым типом может быть представлено любое десятичное число. Над данными числового типа определены основные арифметические операции: сложение, вычитание, умножение и деление. Максимально допустимая разрядность числа 38 знаков.</returns>
///
[ContextMethod("Получить", "Get")]
public int Get(int position)
{
return _buffer[position];
}
/// <summary>
/// Создает новый буфер, использующий заданное количество байтов из исходного буфера, начиная с заданной позиции (нумерация с 0). Если количество не задано, то новый буфер является представлением элементов текущего буфера, начиная с заданного индекса и до конца.
///
/// НЕ РЕАЛИЗОВАН
/// </summary>
///
/// <param name="position">
/// Позиция, начиная с которой будет создан новый буфер. </param>
/// <param name="number">
/// Количество байтов, которые требуется отобразить в срезе. Если на задано, то отображаются все байты от начала среза до конца исходного буфера.
/// Значение по умолчанию: Неопределено. </param>
///
/// <returns name="BinaryDataBuffer">
/// </returns>
///
[ContextMethod("ПолучитьСрез", "GetSlice")]
public BinaryDataBuffer GetSlice(int position, IValue number = null)
{
throw new NotImplementedException();
}
/// <summary>
///
/// Выполняет чтение байтов из буфера и помещает их в новый буфер.
/// </summary>
///
/// <param name="position">
/// Позиция, начиная с которой требуется прочитать байты. </param>
/// <param name="number">
/// Количество байтов, которое требуется прочитать. </param>
///
/// <returns name="BinaryDataBuffer"/>
///
[ContextMethod("Прочитать", "Read")]
public BinaryDataBuffer Read(int position, int number)
{
var data = new byte[number];
Array.Copy(_buffer, position, data, 0, number);
return new BinaryDataBuffer(data, ByteOrder);
}
private T FromBytes<T>(Func<byte[],int,T> converterOverload, int position, IValue byteOrder = null) where T : struct
{
ByteOrderEnum order = ByteOrder;
if (byteOrder != null)
order = ((CLREnumValueWrapper<ByteOrderEnum>)byteOrder.GetRawValue()).UnderlyingValue;
Converter.IsLittleEndian = order == ByteOrderEnum.LittleEndian;
return converterOverload(_buffer, position);
}
/// <summary>
///
/// Выполняет чтение целого 16-битного положительного числа на заданной позиции.
/// </summary>
///
/// <param name="position">
/// Позиция, на которой требуется прочитать число. </param>
/// <param name="byteOrder">
/// Порядок байтов, используемый при чтении числа.
/// Если не задан, используется порядок, определенный для текущего экземпляра ЧтениеДанных.
/// Значение по умолчанию: Неопределено. </param>
///
/// <returns name="Number"/>
///
[ContextMethod("ПрочитатьЦелое16", "ReadInt16")]
public int ReadInt16(int position, IValue byteOrder = null)
{
return FromBytes(Converter.ToInt16, position, byteOrder);
}
/// <summary>
///
/// Прочитать целое 32-битное положительное число на заданной позиции.
/// </summary>
///
/// <param name="position">
/// Позиция, на которой требуется прочитать число. </param>
/// <param name="byteOrder">
/// Порядок байтов, используемый при чтении числа.
/// Если не задан, используется порядок, определенный для текущего экземпляра ЧтениеДанных.
/// Значение по умолчанию: Неопределено. </param>
///
/// <returns name="Number">
/// Числовым типом может быть представлено любое десятичное число. Над данными числового типа определены основные арифметические операции: сложение, вычитание, умножение и деление. Максимально допустимая разрядность числа 38 знаков.</returns>
///
[ContextMethod("ПрочитатьЦелое32", "ReadInt32")]
public uint ReadInt32(int position, IValue byteOrder = null)
{
return FromBytes(Converter.ToUInt32, position, byteOrder);
}
/// <summary>
///
/// Выполняет чтение целого 64-битного положительного числа на заданной позиции.
/// </summary>
///
/// <param name="position">
/// Позиция, на которой требуется прочитать число. </param>
/// <param name="byteOrder">
/// Порядок байтов, используемый при чтении числа.
/// Если не задан, используется порядок, определенный для текущего экземпляра ЧтениеДанных.
/// Значение по умолчанию: Неопределено. </param>
///
/// <returns name="Number">
/// Числовым типом может быть представлено любое десятичное число. Над данными числового типа определены основные арифметические операции: сложение, вычитание, умножение и деление. Максимально допустимая разрядность числа 38 знаков.</returns>
///
[ContextMethod("ПрочитатьЦелое64", "ReadInt64")]
public ulong ReadInt64(int position, IValue byteOrder = null)
{
return FromBytes(Converter.ToUInt64, position, byteOrder);
}
/// <summary>
/// Разделить буфер на части по заданному разделителю.
///
/// НЕ РЕАЛИЗОВАН
/// </summary>
///
/// <remarks>
///
/// По двоичному буферу
/// </remarks>
///
/// <param name="separator">
/// Разделитель. </param>
///
/// <returns name="Array"/>
///
[ContextMethod("Разделить", "Split")]
public IValue Split(IValue separator)
{
throw new NotImplementedException();
}
/// <summary>
///
/// Создает копию массива.
/// </summary>
///
///
/// <returns name="BinaryDataBuffer"/>
///
[ContextMethod("Скопировать", "Copy")]
public BinaryDataBuffer Copy()
{
byte[] copy = new byte[_buffer.Length];
Array.Copy(_buffer, copy, _buffer.Length);
return new BinaryDataBuffer(copy, ByteOrder);
}
/// <summary>
///
/// Создает новый буфер, содержащий элементы текущего буфера и, за ними, элементы заданного буфера.
/// </summary>
///
/// <param name="buffer">
/// Буфер, который будет соединен с исходным. </param>
///
/// <returns name="BinaryDataBuffer"/>
///
[ContextMethod("Соединить", "Concat")]
public BinaryDataBuffer Concat(BinaryDataBuffer buffer)
{
var source = buffer._buffer;
var totalLength = _buffer.Length + source.Length;
var joinedArray = new byte[totalLength];
Array.Copy(_buffer, joinedArray, _buffer.Length);
Array.Copy(source, 0, joinedArray, _buffer.Length, source.Length);
return new BinaryDataBuffer(joinedArray, ByteOrder);
}
/// <summary>
///
/// Устанавливает значение элемента на заданной позиции (нумерация начинается с 0).
/// </summary>
///
/// <param name="position">
/// Позиция, на которую требуется поместить новое значение. </param>
/// <param name="value">
/// Значение, которое требуется установить в заданную позицию буфера.
/// Если значение больше 255 или меньше 0, будет выдана ошибка о неверном значении параметра. </param>
[ContextMethod("Установить", "Set")]
public void Set(int position, int value)
{
ThrowIfReadonly();
if (value < byte.MinValue || value > byte.MaxValue)
throw RuntimeException.InvalidArgumentValue();
_buffer[position] = (byte)value;
}
/// <summary>
///
/// Переводит текущий буфер в режим "только для чтения".
/// Попытка изменить состояние буфера приведет к вызову исключения.
/// </summary>
///
///
///
[ContextMethod("УстановитьТолькоЧтение", "SetReadOnly")]
public void SetReadOnly()
{
_readOnly = true;
}
public int Count()
{
return _buffer.Length;
}
public CollectionEnumerator GetManagedIterator()
{
return new CollectionEnumerator(GetEnumerator());
}
private IEnumerator<IValue> GetEnumerator()
{
for (long i = 0; i < _buffer.LongLength; i++)
{
yield return ValueFactory.Create(_buffer[i]);
}
}
public void ThrowIfReadonly()
{
if (_readOnly)
throw new RuntimeException("Буфер находится в режиме \"Только чтение\"");
}
}
| svgorbunov/OneScript | src/ScriptEngine.HostedScript/Library/Binary/BinaryDataBuffer.cs | C# | mpl-2.0 | 23,502 |
#include "plastiqmethod.h"
#include "plastiqqvideosurfaceformat.h"
#include <QVideoSurfaceFormat>
#include <QSize>
#include <QVariant>
#include <QRect>
QHash<QByteArray, PlastiQMethod> PlastiQQVideoSurfaceFormat::plastiqConstructors = {
{ "QVideoSurfaceFormat()", { "QVideoSurfaceFormat", "", "QVideoSurfaceFormat*", 0, PlastiQMethod::Public, PlastiQMethod::Constructor } },
{ "QVideoSurfaceFormat(QSize&,enum)", { "QVideoSurfaceFormat", "QSize&,QVideoFrame::PixelFormat", "QVideoSurfaceFormat*", 1, PlastiQMethod::Public, PlastiQMethod::Constructor } },
{ "QVideoSurfaceFormat(QSize&,enum,enum)", { "QVideoSurfaceFormat", "QSize&,QVideoFrame::PixelFormat,QAbstractVideoBuffer::HandleType", "QVideoSurfaceFormat*", 2, PlastiQMethod::Public, PlastiQMethod::Constructor } },
{ "QVideoSurfaceFormat(QVideoSurfaceFormat&)", { "QVideoSurfaceFormat", "QVideoSurfaceFormat&", "QVideoSurfaceFormat*", 3, PlastiQMethod::Public, PlastiQMethod::Constructor } },
};
QHash<QByteArray, PlastiQMethod> PlastiQQVideoSurfaceFormat::plastiqMethods = {
{ "frameHeight()", { "frameHeight", "", "int", 0, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "frameRate()", { "frameRate", "", "qreal", 1, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "frameSize()", { "frameSize", "", "QSize", 2, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "frameWidth()", { "frameWidth", "", "int", 3, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "handleType()", { "handleType", "", "QAbstractVideoBuffer::HandleType", 4, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "isValid()", { "isValid", "", "bool", 5, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "pixelAspectRatio()", { "pixelAspectRatio", "", "QSize", 6, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "pixelFormat()", { "pixelFormat", "", "QVideoFrame::PixelFormat", 7, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "property(const char*)", { "property", "char*", "QVariant", 8, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "scanLineDirection()", { "scanLineDirection", "", "Direction", 9, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setFrameRate(double)", { "setFrameRate", "qreal", "void", 10, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setFrameSize(QSize&)", { "setFrameSize", "QSize&", "void", 11, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setFrameSize(int,int)", { "setFrameSize", "int,int", "void", 12, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setPixelAspectRatio(QSize&)", { "setPixelAspectRatio", "QSize&", "void", 13, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setPixelAspectRatio(int,int)", { "setPixelAspectRatio", "int,int", "void", 14, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setProperty(const char*,QVariant)", { "setProperty", "char*,QVariant&", "void", 15, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setScanLineDirection(enum)", { "setScanLineDirection", "Direction", "void", 16, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setViewport(QRect&)", { "setViewport", "QRect&", "void", 17, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "setYCbCrColorSpace(enum)", { "setYCbCrColorSpace", "YCbCrColorSpace", "void", 18, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "sizeHint()", { "sizeHint", "", "QSize", 19, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "viewport()", { "viewport", "", "QRect", 20, PlastiQMethod::Public, PlastiQMethod::Method } },
{ "yCbCrColorSpace()", { "yCbCrColorSpace", "", "YCbCrColorSpace", 21, PlastiQMethod::Public, PlastiQMethod::Method } },
};
QHash<QByteArray, PlastiQMethod> PlastiQQVideoSurfaceFormat::plastiqSignals = {
};
QHash<QByteArray, PlastiQProperty> PlastiQQVideoSurfaceFormat::plastiqProperties = {
};
QHash<QByteArray, long> PlastiQQVideoSurfaceFormat::plastiqConstants = {
/* QVideoSurfaceFormat::Direction */
{ "TopToBottom", QVideoSurfaceFormat::TopToBottom },
{ "BottomToTop", QVideoSurfaceFormat::BottomToTop },
/* QVideoSurfaceFormat::YCbCrColorSpace */
{ "YCbCr_Undefined", QVideoSurfaceFormat::YCbCr_Undefined },
{ "YCbCr_BT601", QVideoSurfaceFormat::YCbCr_BT601 },
{ "YCbCr_BT709", QVideoSurfaceFormat::YCbCr_BT709 },
{ "YCbCr_xvYCC601", QVideoSurfaceFormat::YCbCr_xvYCC601 },
{ "YCbCr_xvYCC709", QVideoSurfaceFormat::YCbCr_xvYCC709 },
{ "YCbCr_JPEG", QVideoSurfaceFormat::YCbCr_JPEG },
};
QVector<PlastiQMetaObject*> PlastiQQVideoSurfaceFormat::plastiqInherits = { };
const PlastiQ::ObjectType PlastiQQVideoSurfaceFormat::plastiq_static_objectType = PlastiQ::IsQtObject;
PlastiQMetaObject PlastiQQVideoSurfaceFormat::plastiq_static_metaObject = {
{ Q_NULLPTR, &plastiqInherits, "QVideoSurfaceFormat", &plastiq_static_objectType,
&plastiqConstructors,
&plastiqMethods,
&plastiqSignals,
&plastiqProperties,
&plastiqConstants,
plastiq_static_metacall
}
};
const PlastiQMetaObject *PlastiQQVideoSurfaceFormat::plastiq_metaObject() const {
return &plastiq_static_metaObject;
}
void PlastiQQVideoSurfaceFormat::plastiq_static_metacall(PlastiQObject *object, PlastiQMetaObject::Call call, int id, const PMOGStack &stack) {
if(call == PlastiQMetaObject::CreateInstance) {
QVideoSurfaceFormat *o = Q_NULLPTR;
switch(id) {
case 0: o = new QVideoSurfaceFormat(); break;
case 1: o = new QVideoSurfaceFormat((*reinterpret_cast< QSize(*) >(stack[1].s_voidp)),
QVideoFrame::PixelFormat(stack[2].s_int64)); break;
case 2: o = new QVideoSurfaceFormat((*reinterpret_cast< QSize(*) >(stack[1].s_voidp)),
QVideoFrame::PixelFormat(stack[2].s_int64),
QAbstractVideoBuffer::HandleType(stack[3].s_int64)); break;
case 3: o = new QVideoSurfaceFormat((*reinterpret_cast< QVideoSurfaceFormat(*) >(stack[1].s_voidp))); break;
default: ;
}
/*%UPDATEWRAPPER%*/ PlastiQQVideoSurfaceFormat *p = new PlastiQQVideoSurfaceFormat();
p->plastiq_setData(reinterpret_cast<void*>(o), p);
PlastiQObject *po = static_cast<PlastiQObject*>(p);
*reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = po;
}
else if(call == PlastiQMetaObject::CreateDataInstance) {
PlastiQQVideoSurfaceFormat *p = new PlastiQQVideoSurfaceFormat();
p->plastiq_setData(stack[1].s_voidp, p);
*reinterpret_cast<PlastiQObject**>(stack[0].s_voidpp) = p;
}
else if(call == PlastiQMetaObject::InvokeMethod || call == PlastiQMetaObject::InvokeStaticMember) {
if(id >= 22) {
id -= 22;
return;
}
bool sc = call == PlastiQMetaObject::InvokeStaticMember;
bool isWrapper = sc ? false : object->isWrapper();
QVideoSurfaceFormat *o = sc ? Q_NULLPTR : reinterpret_cast<QVideoSurfaceFormat*>(object->plastiq_data());
switch(id) {
case 0: { int _r = o->frameHeight();
stack[0].s_int = _r; stack[0].type = PlastiQ::Int; } break;
case 1: { double _r = o->frameRate();
stack[0].s_double = _r; stack[0].type = PlastiQ::Double; } break;
case 2: { /* COPY OBJECT */
QSize *_r = new QSize(o->frameSize());
reinterpret_cast<void*>(stack[0].s_voidp) = _r;
stack[0].name = "QSize";
stack[0].type = PlastiQ::QtObject;
} break;
case 3: { int _r = o->frameWidth();
stack[0].s_int = _r; stack[0].type = PlastiQ::Int; } break;
case 4: { qint64 _r = o->handleType(); // HACK for QAbstractVideoBuffer::HandleType
stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break;
case 5: { bool _r = o->isValid();
stack[0].s_bool = _r; stack[0].type = PlastiQ::Bool; } break;
case 6: { /* COPY OBJECT */
QSize *_r = new QSize(o->pixelAspectRatio());
reinterpret_cast<void*>(stack[0].s_voidp) = _r;
stack[0].name = "QSize";
stack[0].type = PlastiQ::QtObject;
} break;
case 7: { qint64 _r = o->pixelFormat(); // HACK for QVideoFrame::PixelFormat
stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break;
case 8: { /* COPY OBJECT */
QVariant *_r = new QVariant(o->property(reinterpret_cast<const char*>(stack[1].s_voidp)));
reinterpret_cast<void*>(stack[0].s_voidp) = _r;
stack[0].name = "QVariant";
stack[0].type = PlastiQ::QtObject;
} break;
case 9: { qint64 _r = o->scanLineDirection(); // HACK for Direction
stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break;
case 10: o->setFrameRate(stack[1].s_double);
stack[0].type = PlastiQ::Void; break;
case 11: o->setFrameSize((*reinterpret_cast< QSize(*) >(stack[1].s_voidp)));
stack[0].type = PlastiQ::Void; break;
case 12: o->setFrameSize(stack[1].s_int,
stack[2].s_int);
stack[0].type = PlastiQ::Void; break;
case 13: o->setPixelAspectRatio((*reinterpret_cast< QSize(*) >(stack[1].s_voidp)));
stack[0].type = PlastiQ::Void; break;
case 14: o->setPixelAspectRatio(stack[1].s_int,
stack[2].s_int);
stack[0].type = PlastiQ::Void; break;
case 15: o->setProperty(reinterpret_cast<const char*>(stack[1].s_voidp),
stack[2].s_variant);
stack[0].type = PlastiQ::Void; break;
case 16: o->setScanLineDirection(QVideoSurfaceFormat::Direction(stack[1].s_int64));
stack[0].type = PlastiQ::Void; break;
case 17: o->setViewport((*reinterpret_cast< QRect(*) >(stack[1].s_voidp)));
stack[0].type = PlastiQ::Void; break;
case 18: o->setYCbCrColorSpace(QVideoSurfaceFormat::YCbCrColorSpace(stack[1].s_int64));
stack[0].type = PlastiQ::Void; break;
case 19: { /* COPY OBJECT */
QSize *_r = new QSize(o->sizeHint());
reinterpret_cast<void*>(stack[0].s_voidp) = _r;
stack[0].name = "QSize";
stack[0].type = PlastiQ::QtObject;
} break;
case 20: { /* COPY OBJECT */
QRect *_r = new QRect(o->viewport());
reinterpret_cast<void*>(stack[0].s_voidp) = _r;
stack[0].name = "QRect";
stack[0].type = PlastiQ::QtObject;
} break;
case 21: { qint64 _r = o->yCbCrColorSpace(); // HACK for YCbCrColorSpace
stack[0].s_int64 = _r; stack[0].type = PlastiQ::Enum; } break;
default: ;
}
}
else if(call == PlastiQMetaObject::ToQObject) {
}
else if(call == PlastiQMetaObject::HaveParent) {
stack[0].s_bool = false;
}
else if(call == PlastiQMetaObject::DownCast) {
QByteArray className = stack[1].s_bytearray;
QVideoSurfaceFormat *o = reinterpret_cast<QVideoSurfaceFormat*>(object->plastiq_data());
stack[0].s_voidp = Q_NULLPTR;
stack[0].name = "Q_NULLPTR";
}
}
PlastiQQVideoSurfaceFormat::~PlastiQQVideoSurfaceFormat() {
QVideoSurfaceFormat* o = reinterpret_cast<QVideoSurfaceFormat*>(plastiq_data());
if(o != Q_NULLPTR) {
delete o;
}
o = Q_NULLPTR;
plastiq_setData(Q_NULLPTR, Q_NULLPTR);
}
| ArtMares/PQStudio | Builder/plastiq/include/multimedia/PlastiQQVideoSurfaceFormat/plastiqqvideosurfaceformat.cpp | C++ | mpl-2.0 | 11,450 |
/**
* Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.seed.core.utils;
import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matcher;
import org.seedstack.seed.core.api.Ignore;
import org.seedstack.seed.core.api.Install;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.kametic.specifications.Specification;
import org.seedstack.seed.core.fixtures.DummyService1;
import org.seedstack.seed.core.fixtures.DummyService2;
import java.lang.annotation.*;
/**
* SeedReflectionUtilsTest
*
* @author redouane.loulou@ext.mpsa.com
*/
public class SeedReflectionUtilsTest {
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
@Ignore
@interface AnnotationTest {
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@Inherited
@Ignore
@interface AnnotationAllTest {
}
@Install
public static class TestModule1 extends AbstractModule {
@AnnotationAllTest
public String foo;
@AnnotationAllTest
@Override
protected void configure() {
}
public void bar(){}
}
// not automatically installed
public static class TestModule2 extends AbstractModule {
@Override
protected void configure() {
}
}
@AnnotationTest
public static class TestModule3 extends AbstractModule {
@Override
protected void configure() {
}
}
@Test
public void ancestorMetaAnnotatedWithTest() {
Matcher matcher = SeedMatchers.ancestorMetaAnnotatedWith(Install.class);
Assertions.assertThat(matcher).isNotNull();
Assertions.assertThat(matcher.matches(null)).isFalse();
Assertions.assertThat(matcher.matches(TestModule1.class)).isTrue();
}
@Test
public void classMetaAnnotatedWithTest() {
Specification specification = SeedSpecifications.classMetaAnnotatedWith(Install.class);
Assertions.assertThat(specification.isSatisfiedBy(TestModule1.class)).isTrue();
Assertions.assertThat(specification.isSatisfiedBy(TestModule2.class)).isFalse();
Assertions.assertThat(specification.isSatisfiedBy(null)).isFalse();
}
@Test
public void getAllInterfacesAndClassesTest() {
Class[] hierarchies = SeedReflectionUtils.getAllInterfacesAndClasses(DummyService1.class);
Assertions.assertThat(hierarchies).isNotNull().isNotEmpty().hasSize(3);
}
@Test
public void getAllInterfacesAndClassesTest2() {
Class[] hierarchies = SeedReflectionUtils.getAllInterfacesAndClasses(new Class[]{Object.class});
Assertions.assertThat(hierarchies).isNotNull().isNotEmpty().hasSize(1);
hierarchies = SeedReflectionUtils.getAllInterfacesAndClasses(new Class[]{DummyService1.class, DummyService2.class});
Assertions.assertThat(hierarchies).isNotNull().isNotEmpty().hasSize(6);
}
@Test
public void getAnnotationDeepTest() {
Annotation anno = SeedReflectionUtils.getAnnotationDeep(TestModule1.class.getAnnotation(Install.class), Target.class);
Assertions.assertThat(anno).isNull();
anno = SeedReflectionUtils.getAnnotationDeep(TestModule3.class.getAnnotation(AnnotationTest.class), Ignore.class);
Assertions.assertThat(anno).isNotNull();
anno = SeedReflectionUtils.getAnnotationDeep(TestModule1.class.getAnnotation(Install.class), Install.class);
Assertions.assertThat(anno).isEqualTo(TestModule1.class.getAnnotation(Install.class));
}
@Test
public void getMetaAnnotationFromAncestorsTest() {
Install install = SeedReflectionUtils.getMetaAnnotationFromAncestors(TestModule1.class, Install.class);
Assertions.assertThat(install).isNotNull();
}
@Test
public void getMethodOrAncestorMetaAnnotatedWith() throws NoSuchMethodException, NoSuchFieldException {
// Get annotation from declaring class
Install install0 = SeedReflectionUtils.getMethodOrAncestorMetaAnnotatedWith(TestModule1.class.getDeclaredField("foo"), Install.class);
Assertions.assertThat(install0).isNotNull();
// Get annotation from current field
AnnotationAllTest annotationFieldTest = SeedReflectionUtils.getMethodOrAncestorMetaAnnotatedWith(TestModule1.class.getDeclaredField("foo"), AnnotationAllTest.class);
Assertions.assertThat(annotationFieldTest).isNotNull();
// Get annotation from declaring class
Install install = SeedReflectionUtils.getMethodOrAncestorMetaAnnotatedWith(TestModule1.class.getDeclaredMethod("configure"), Install.class);
Assertions.assertThat(install).isNotNull();
// Get annotation from current method
AnnotationAllTest override = SeedReflectionUtils.getMethodOrAncestorMetaAnnotatedWith(TestModule1.class.getDeclaredMethod("configure"), AnnotationAllTest.class);
Assertions.assertThat(override).isNotNull();
AnnotationAllTest result = SeedReflectionUtils.getMethodOrAncestorMetaAnnotatedWith(TestModule1.class.getDeclaredMethod("bar"), AnnotationAllTest.class);
Assertions.assertThat(result).isNull();
// Get annotation from current class
Install install3 = SeedReflectionUtils.getMethodOrAncestorMetaAnnotatedWith(TestModule1.class, Install.class);
Assertions.assertThat(install3).isNotNull();
}
@Test
public void findCallerTest() {
StackTraceElement caller = new CallerTestFixture().findCaller();
Assertions.assertThat(caller).isNotNull();
Assertions.assertThat(caller.getClassName()).isEqualTo(SeedReflectionUtilsTest.class.getCanonicalName());
Assertions.assertThat(caller.getMethodName()).isEqualTo("findCallerTest");
}
}
| tbouvet/seed | core/src/test/java/org/seedstack/seed/core/utils/SeedReflectionUtilsTest.java | Java | mpl-2.0 | 6,034 |
/**
* Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package eu.itesla_project.offline.db.mmap;
import com.powsybl.commons.config.ModuleConfig;
import com.powsybl.commons.config.PlatformConfig;
import java.nio.file.Path;
import java.util.Objects;
/**
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com>
*/
public class MMapOfflineDbConfig {
private static final int DEFAULT_SAMPLE_CHUNK_SIZE = 1000;
private static final int DEFAULT_MAX_SECURITY_INDEXES_COUNT = 1000;
private static final int DEFAULT_MAX_NETWORK_ATTRIBUTES_COUNT = 40000;
private Path directory;
private int sampleChunkSize;
private int maxSecurityIndexesCount;
private int maxNetworkAttributesCount;
public static MMapOfflineDbConfig load() {
ModuleConfig config = PlatformConfig.defaultConfig().getModuleConfig("mmap-offlinedb");
Path directory = config.getPathProperty("directory");
int sampleChunkSize = config.getIntProperty("sampleChunkSize", DEFAULT_SAMPLE_CHUNK_SIZE);
int maxSecurityIndexesCount = config.getIntProperty("maxSecurityIndexesCount", DEFAULT_MAX_SECURITY_INDEXES_COUNT);
int maxNetworkAttributesCount = config.getIntProperty("maxNetworkAttributesCount", DEFAULT_MAX_NETWORK_ATTRIBUTES_COUNT);
return new MMapOfflineDbConfig(directory, sampleChunkSize, maxSecurityIndexesCount, maxNetworkAttributesCount);
}
public MMapOfflineDbConfig(Path directory, int sampleChunkSize, int maxSecurityIndexesCount, int maxNetworkAttributesCount) {
this.directory = Objects.requireNonNull(directory);
this.sampleChunkSize = sampleChunkSize;
this.maxSecurityIndexesCount = maxSecurityIndexesCount;
this.maxNetworkAttributesCount = maxNetworkAttributesCount;
}
public MMapOfflineDbConfig(Path directory) {
this(directory, DEFAULT_SAMPLE_CHUNK_SIZE, DEFAULT_MAX_SECURITY_INDEXES_COUNT, DEFAULT_MAX_NETWORK_ATTRIBUTES_COUNT);
}
public Path getDirectory() {
return directory;
}
public void setDirectory(Path directory) {
this.directory = directory;
}
public int getSampleChunkSize() {
return sampleChunkSize;
}
public void setSampleChunkSize(int sampleChunkSize) {
this.sampleChunkSize = sampleChunkSize;
}
public int getMaxSecurityIndexesCount() {
return maxSecurityIndexesCount;
}
public void setMaxSecurityIndexesCount(int maxSecurityIndexesCount) {
this.maxSecurityIndexesCount = maxSecurityIndexesCount;
}
public int getMaxNetworkAttributesCount() {
return maxNetworkAttributesCount;
}
public void setMaxNetworkAttributesCount(int maxNetworkAttributesCount) {
this.maxNetworkAttributesCount = maxNetworkAttributesCount;
}
}
| itesla/ipst | mmap-offline-db/src/main/java/eu/itesla_project/offline/db/mmap/MMapOfflineDbConfig.java | Java | mpl-2.0 | 3,061 |
/**
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* The Original Code is OpenELIS code.
*
* Copyright (C) The Minnesota Department of Health. All Rights Reserved.
*/
package us.mn.state.health.lims.testmanagement.action;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;
import us.mn.state.health.lims.action.dao.ActionDAO;
import us.mn.state.health.lims.action.daoimpl.ActionDAOImpl;
import us.mn.state.health.lims.action.valueholder.Action;
import us.mn.state.health.lims.analysis.dao.AnalysisDAO;
import us.mn.state.health.lims.analysis.daoimpl.AnalysisDAOImpl;
import us.mn.state.health.lims.analysis.valueholder.Analysis;
import us.mn.state.health.lims.analysisqaevent.dao.AnalysisQaEventDAO;
import us.mn.state.health.lims.analysisqaevent.daoimpl.AnalysisQaEventDAOImpl;
import us.mn.state.health.lims.analysisqaevent.valueholder.AnalysisQaEvent;
import us.mn.state.health.lims.analysisqaeventaction.dao.AnalysisQaEventActionDAO;
import us.mn.state.health.lims.analysisqaeventaction.daoimpl.AnalysisQaEventActionDAOImpl;
import us.mn.state.health.lims.analysisqaeventaction.valueholder.AnalysisQaEventAction;
import us.mn.state.health.lims.common.action.BaseAction;
import us.mn.state.health.lims.common.action.BaseActionForm;
import us.mn.state.health.lims.common.exception.LIMSRuntimeException;
import us.mn.state.health.lims.common.log.LogEvent;
import us.mn.state.health.lims.common.provider.validation.*;
import us.mn.state.health.lims.common.util.DateUtil;
import us.mn.state.health.lims.common.util.StringUtil;
import us.mn.state.health.lims.common.util.SystemConfiguration;
import us.mn.state.health.lims.common.util.validator.ActionError;
import us.mn.state.health.lims.hibernate.HibernateUtil;
import us.mn.state.health.lims.login.valueholder.UserSessionData;
import us.mn.state.health.lims.organization.dao.OrganizationDAO;
import us.mn.state.health.lims.organization.daoimpl.OrganizationDAOImpl;
import us.mn.state.health.lims.organization.valueholder.Organization;
import us.mn.state.health.lims.patient.dao.PatientDAO;
import us.mn.state.health.lims.patient.daoimpl.PatientDAOImpl;
import us.mn.state.health.lims.patient.valueholder.Patient;
import us.mn.state.health.lims.person.dao.PersonDAO;
import us.mn.state.health.lims.person.daoimpl.PersonDAOImpl;
import us.mn.state.health.lims.person.valueholder.Person;
import us.mn.state.health.lims.project.dao.ProjectDAO;
import us.mn.state.health.lims.project.daoimpl.ProjectDAOImpl;
import us.mn.state.health.lims.project.valueholder.Project;
import us.mn.state.health.lims.provider.dao.ProviderDAO;
import us.mn.state.health.lims.provider.daoimpl.ProviderDAOImpl;
import us.mn.state.health.lims.provider.valueholder.Provider;
import us.mn.state.health.lims.qaevent.dao.QaEventDAO;
import us.mn.state.health.lims.qaevent.daoimpl.QaEventDAOImpl;
import us.mn.state.health.lims.qaevent.valueholder.QaEvent;
import us.mn.state.health.lims.sample.dao.SampleDAO;
import us.mn.state.health.lims.sample.daoimpl.SampleDAOImpl;
import us.mn.state.health.lims.sample.valueholder.Sample;
import us.mn.state.health.lims.samplehuman.dao.SampleHumanDAO;
import us.mn.state.health.lims.samplehuman.daoimpl.SampleHumanDAOImpl;
import us.mn.state.health.lims.samplehuman.valueholder.SampleHuman;
import us.mn.state.health.lims.sampleitem.dao.SampleItemDAO;
import us.mn.state.health.lims.sampleitem.daoimpl.SampleItemDAOImpl;
import us.mn.state.health.lims.sampleitem.valueholder.SampleItem;
import us.mn.state.health.lims.sampleorganization.dao.SampleOrganizationDAO;
import us.mn.state.health.lims.sampleorganization.daoimpl.SampleOrganizationDAOImpl;
import us.mn.state.health.lims.sampleorganization.valueholder.SampleOrganization;
import us.mn.state.health.lims.sampleproject.dao.SampleProjectDAO;
import us.mn.state.health.lims.sampleproject.daoimpl.SampleProjectDAOImpl;
import us.mn.state.health.lims.sampleproject.valueholder.SampleProject;
import us.mn.state.health.lims.sourceofsample.dao.SourceOfSampleDAO;
import us.mn.state.health.lims.sourceofsample.daoimpl.SourceOfSampleDAOImpl;
import us.mn.state.health.lims.sourceofsample.valueholder.SourceOfSample;
import us.mn.state.health.lims.systemuser.dao.SystemUserDAO;
import us.mn.state.health.lims.systemuser.daoimpl.SystemUserDAOImpl;
import us.mn.state.health.lims.systemuser.valueholder.SystemUser;
import us.mn.state.health.lims.typeofsample.dao.TypeOfSampleDAO;
import us.mn.state.health.lims.typeofsample.daoimpl.TypeOfSampleDAOImpl;
import us.mn.state.health.lims.typeofsample.valueholder.TypeOfSample;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.*;
/**
* @author aiswarya raman
*
* To change this generated comment edit the template variable "typecomment":
* Window>Preferences>Java>Templates. To enable and disable the creation of type
* comments go to Window>Preferences>Java>Code Generation.
*/
public class SampleDemographicsUpdateAction extends BaseAction {
protected ActionForward performAction(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
//System.out.println("I am in SampleDemographicsUpdateAction ");
String forward = FWD_SUCCESS;
request.setAttribute(ALLOW_EDITS_KEY, "true");
BaseActionForm testManagementForm = (BaseActionForm) form;
// server-side validation (validation.xml)
ActionMessages errors = testManagementForm.validate(mapping, request);
try {
errors = validateAll(request, errors, testManagementForm);
} catch (Exception e) {
//bugzilla 2154
LogEvent.logError("SampleDemographicsUpdateAction","performAction()",e.toString());
ActionError error = new ActionError("errors.ValidationException",
null, null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
// end of zip/city combination check
if (errors != null && errors.size() > 0) {
saveErrors(request, errors);
// since we forward to jsp - not Action we don't need to repopulate
// the lists here
return mapping.findForward(FWD_FAIL);
}
String accessionNumber = (String) testManagementForm
.get("accessionNumber");
String typeOfSample = (String) testManagementForm
.get("typeOfSampleDesc");
String sourceOfSample = (String) testManagementForm
.get("sourceOfSampleDesc");
List typeOfSamples = new ArrayList();
List sourceOfSamples = new ArrayList();
if (testManagementForm.get("typeOfSamples") != null) {
typeOfSamples = (List) testManagementForm.get("typeOfSamples");
} else {
TypeOfSampleDAO typeOfSampleDAO = new TypeOfSampleDAOImpl();
typeOfSamples = typeOfSampleDAO.getAllTypeOfSamples();
}
if (testManagementForm.get("sourceOfSamples") != null) {
sourceOfSamples = (List) testManagementForm.get("sourceOfSamples");
} else {
SourceOfSampleDAO sourceOfSampleDAO = new SourceOfSampleDAOImpl();
sourceOfSamples = sourceOfSampleDAO.getAllSourceOfSamples();
}
String projectIdOrName = (String) testManagementForm
.get("projectIdOrName");
String project2IdOrName = (String) testManagementForm
.get("project2IdOrName");
String projectNameOrId = (String) testManagementForm
.get("projectNameOrId");
String project2NameOrId = (String) testManagementForm
.get("project2NameOrId");
String projectId = null;
String project2Id = null;
if (projectIdOrName != null && projectNameOrId != null) {
try {
Integer i = Integer.valueOf(projectIdOrName);
projectId = projectIdOrName;
} catch (NumberFormatException nfe) {
//bugzilla 2154
LogEvent.logError("SampleDemographicsUpdateAction","performAction()",nfe.toString());
projectId = projectNameOrId;
}
}
if (project2IdOrName != null && project2NameOrId != null) {
try {
Integer i = Integer.valueOf(project2IdOrName);
project2Id = project2IdOrName;
} catch (NumberFormatException nfe) {
//bugzilla 2154
LogEvent.logError("SampleDemographicsUpdateAction","performAction()",nfe.toString());
project2Id = project2NameOrId;
}
}
// set current date for validation of dates
Date today = Calendar.getInstance().getTime();
String dateAsText = DateUtil.formatDateAsText(today);
PersonDAO personDAO = new PersonDAOImpl();
PatientDAO patientDAO = new PatientDAOImpl();
ProviderDAO providerDAO = new ProviderDAOImpl();
SampleDAO sampleDAO = new SampleDAOImpl();
SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
AnalysisDAO analysisDAO = new AnalysisDAOImpl();
SampleProjectDAO sampleProjectDAO = new SampleProjectDAOImpl();
ProjectDAO projectDAO = new ProjectDAOImpl();
AnalysisQaEventDAO analysisQaEventDAO = new AnalysisQaEventDAOImpl();
AnalysisQaEventActionDAO analysisQaEventActionDAO = new AnalysisQaEventActionDAOImpl();
QaEventDAO qaEventDAO = new QaEventDAOImpl();
ActionDAO actionDAO = new ActionDAOImpl();
Patient patient = new Patient();
Person person = new Person();
Provider provider = new Provider();
Person providerPerson = new Person();
Sample sample = new Sample();
SampleHuman sampleHuman = new SampleHuman();
SampleOrganization sampleOrganization = new SampleOrganization();
List oldSampleProjects = new ArrayList();
List newSampleProjects = new ArrayList();
SampleItem sampleItem = new SampleItem();
List analyses = new ArrayList();
// GET ORIGINAL DATA
try {
sample.setAccessionNumber(accessionNumber);
sampleDAO.getSampleByAccessionNumber(sample);
if (!StringUtil.isNullorNill(sample.getId())) {
sampleHuman.setSampleId(sample.getId());
sampleHumanDAO.getDataBySample(sampleHuman);
sampleOrganization.setSampleId(sample.getId());
sampleOrganizationDAO.getDataBySample(sampleOrganization);
// bugzilla 1773 need to store sample not sampleId for use in
// sorting
sampleItem.setSample(sample);
sampleItemDAO.getDataBySample(sampleItem);
patient.setId(sampleHuman.getPatientId());
patientDAO.getData(patient);
person = patient.getPerson();
personDAO.getData(person);
provider.setId(sampleHuman.getProviderId());
providerDAO.getData(provider);
providerPerson = provider.getPerson();
personDAO.getData(providerPerson);
//bugzilla 2227
analyses = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);
oldSampleProjects = sample.getSampleProjects();
}
} catch (LIMSRuntimeException lre) {
// if error then forward to fail and don't update to blank page
// = false
//bugzilla 2154
LogEvent.logError("SampleDemographicsUpdateAction","performAction()",lre.toString());
errors = new ActionMessages();
ActionError error = null;
error = new ActionError("errors.GetException", null, null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
request.setAttribute(ALLOW_EDITS_KEY, "false");
return mapping.findForward(FWD_FAIL);
}
// UPDATE DATA FROM FORM
// populate valueholder from form
PropertyUtils.copyProperties(sample, testManagementForm);
PropertyUtils.copyProperties(person, testManagementForm);
PropertyUtils.copyProperties(patient, testManagementForm);
PropertyUtils.copyProperties(provider, testManagementForm);
PropertyUtils.copyProperties(sampleHuman, testManagementForm);
PropertyUtils.copyProperties(sampleOrganization, testManagementForm);
PropertyUtils.copyProperties(sampleItem, testManagementForm);
TypeOfSample typeOfSamp = null;
// get the right typeOfSamp to update sampleitem with
for (int i = 0; i < typeOfSamples.size(); i++) {
TypeOfSample s = (TypeOfSample) typeOfSamples.get(i);
if (s.getDescription().equalsIgnoreCase(typeOfSample)) {
typeOfSamp = s;
break;
}
}
SourceOfSample sourceOfSamp = null;
// get the right sourceOfSamp to update sampleitem with
for (int i = 0; i < sourceOfSamples.size(); i++) {
SourceOfSample s = (SourceOfSample) sourceOfSamples.get(i);
if (s.getDescription().equalsIgnoreCase(sourceOfSample)) {
sourceOfSamp = s;
break;
}
}
Organization org = new Organization();
//bugzilla 2069
org.setOrganizationLocalAbbreviation((String) testManagementForm.get("organizationLocalAbbreviation"));
OrganizationDAO organizationDAO = new OrganizationDAOImpl();
org = organizationDAO.getOrganizationByLocalAbbreviation(org, true);
sampleOrganization.setOrganization(org);
// if there was a first sampleProject id entered
// ****Added a Try catch block to validate integer because..
// ****When a project is deleted, the name of the project is passed in
// as its id which causes error
try {
Integer i = Integer.valueOf(projectId);
if (!StringUtil.isNullorNill(projectId)) {
SampleProject sampleProject = new SampleProject();
Project p = new Project();
//bugzilla 2438
p.setLocalAbbreviation(projectId);
p = projectDAO.getProjectByLocalAbbreviation(p, true);
sampleProject.setProject(p);
sampleProject.setSample(sample);
sampleProject.setIsPermanent(NO);
newSampleProjects.add(sampleProject);
}
} catch (NumberFormatException nfe) {
//bugzilla 2154
LogEvent.logError("SampleDemographicsUpdateAction","performAction()",nfe.toString());
}
// in case there was a second sampleProject id entered
try {
Integer i = Integer.valueOf(project2Id);
if (!StringUtil.isNullorNill(project2Id)) {
SampleProject sampleProject2 = new SampleProject();
Project p2 = new Project();
//bugzilla 2438
p2.setLocalAbbreviation(project2Id);
p2 = projectDAO.getProjectByLocalAbbreviation(p2, true);
sampleProject2.setProject(p2);
sampleProject2.setSample(sample);
sampleProject2.setIsPermanent(NO);
newSampleProjects.add(sampleProject2);
}
} catch (NumberFormatException nfe) {
//bugzilla 2154
LogEvent.logError("SampleDemographicsUpdateAction","performAction()",nfe.toString());
}
// set the provider person manually as we have two Person
// valueholders
// to populate and copyProperties() can only handle one per form
providerPerson.setFirstName((String) testManagementForm
.get("providerFirstName"));
providerPerson.setLastName((String) testManagementForm
.get("providerLastName"));
// format workPhone for storage
String workPhone = (String) testManagementForm.get("providerWorkPhone");
String ext = (String) testManagementForm
.get("providerWorkPhoneExtension");
String formattedPhone = StringUtil.formatPhone(workPhone, ext);
// phone is stored as 999/999-9999.9999
// area code/phone - number.extension
providerPerson.setWorkPhone(formattedPhone);
String date = (String) testManagementForm
.get("collectionDateForDisplay");
if (!StringUtil.isNullorNill(date)) {
//System.out.println("I am here");
// set collection time
String time = (String) testManagementForm
.get("collectionTimeForDisplay");
if (StringUtil.isNullorNill(time)) {
time = "00:00";
}
sample.setCollectionTimeForDisplay(time);
sample.setCollectionDateForDisplay(date);
Timestamp d = sample.getCollectionDate();
if (time.indexOf(":") > 0) {
// bugzilla 1857 deprecated stuff
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(
time.substring(0, 2)).intValue());
cal.set(Calendar.MINUTE, Integer.valueOf(time.substring(3, 5))
.intValue());
// d.setHours(Integer.valueOf(time.substring(0, 2)).intValue());
// d.setMinutes(Integer.valueOf(time.substring(3,
// 5)).intValue());
d = new Timestamp(cal.getTimeInMillis());
sample.setCollectionDate(d);
}
}
// sampleItem
sampleItem.setSortOrder("1");
// set the typeOfSample
sampleItem.setTypeOfSample(typeOfSamp);
// set the sourceOfSample
sampleItem.setSourceOfSample(sourceOfSamp);
sample.setSampleProjects(newSampleProjects);
// get sysUserId from login module
UserSessionData usd = (UserSessionData)request.getSession().getAttribute(USER_SESSION_DATA);
String sysUserId = String.valueOf(usd.getSystemUserId());
org.hibernate.Transaction tx = HibernateUtil.getSession()
.beginTransaction();
//bugzilla 2481, 2496 Action Owner
SystemUser systemUser = new SystemUser();
systemUser.setId(sysUserId);
SystemUserDAO systemUserDAO = new SystemUserDAOImpl();
systemUserDAO.getData(systemUser);
List newIds = new ArrayList();
List oldIds = new ArrayList();
if (newSampleProjects != null) {
for (int i = 0; i < newSampleProjects.size(); i++) {
SampleProject sp = (SampleProject) newSampleProjects.get(i);
newIds.add(sp.getId());
}
}
if (oldSampleProjects != null) {
List listOfOldOnesToRemove = new ArrayList();
for (int i = 0; i < oldSampleProjects.size(); i++) {
SampleProject sp = (SampleProject) oldSampleProjects.get(i);
oldIds.add(sp.getId());
if (!newIds.contains(sp.getId())) {
// remove ones that are to be deleted
listOfOldOnesToRemove.add(new Integer(i));
}
}
int decreaseOSPIndexBy = 0;
int decreaseOIIndexBy = 0;
List listOfSampleProjectObjectsToDelete = new ArrayList();
for (int i = 0; i < listOfOldOnesToRemove.size(); i++) {
SampleProject sp = (SampleProject) oldSampleProjects
.remove(((Integer) listOfOldOnesToRemove.get(i))
.intValue()
- decreaseOSPIndexBy++);
//bugzilla 1926
sp.setSysUserId(sysUserId);
listOfSampleProjectObjectsToDelete.add(sp);
oldIds.remove(((Integer) listOfOldOnesToRemove.get(i))
.intValue()
- decreaseOIIndexBy++);
}
sampleProjectDAO.deleteData(listOfSampleProjectObjectsToDelete);
}
if (newSampleProjects != null) {
for (int j = 0; j < newSampleProjects.size(); j++) {
SampleProject saPr = (SampleProject) newSampleProjects.get(j);
int index = oldIds.indexOf(saPr.getId());
if (index >= 0) {
SampleProject sampleProjectClone = (SampleProject) oldSampleProjects
.get(index);
PropertyUtils.copyProperties(sampleProjectClone, saPr);
Sample smplClone = (Sample) sampleProjectClone.getSample();
sampleProjectClone.setSample(smplClone);
Project pClone = (Project) sampleProjectClone.getProject();
sampleProjectClone.setProject(pClone);
PropertyUtils.setProperty(sampleProjectClone,
"lastupdated", (Timestamp) testManagementForm
.get("sampleProject1Lastupdated"));
sampleProjectClone.setSysUserId(sysUserId);
sampleProjectDAO.updateData(sampleProjectClone);
oldSampleProjects.set(index, sampleProjectClone);
} else {
SampleProject sampleProjectClone = new SampleProject();
PropertyUtils.copyProperties(sampleProjectClone, saPr);
Sample smplClone = (Sample) sampleProjectClone.getSample();
sampleProjectClone.setSample(smplClone);
Project pClone = (Project) sampleProjectClone.getProject();
sampleProjectClone.setProject(pClone);
PropertyUtils.setProperty(sampleProjectClone,
"lastupdated", (Timestamp) testManagementForm
.get("sampleProject2Lastupdated"));
//bugzilla 1926
sampleProjectClone.setSysUserId(sysUserId);
sampleProjectDAO.insertData(sampleProjectClone);
oldSampleProjects.add(sampleProjectClone);
}
}
}
sample.setSampleProjects(oldSampleProjects);
// END DIANE
try {
// set last updated from form
PropertyUtils.setProperty(person, "lastupdated",
(Timestamp) testManagementForm.get("personLastupdated"));
PropertyUtils.setProperty(patient, "lastupdated",
(Timestamp) testManagementForm.get("patientLastupdated"));
PropertyUtils.setProperty(sample, "lastupdated",
(Timestamp) testManagementForm.get("lastupdated"));
PropertyUtils.setProperty(providerPerson, "lastupdated",
(Timestamp) testManagementForm
.get("providerPersonLastupdated"));
PropertyUtils.setProperty(provider, "lastupdated",
(Timestamp) testManagementForm.get("providerLastupdated"));
PropertyUtils
.setProperty(sampleItem, "lastupdated",
(Timestamp) testManagementForm
.get("sampleItemLastupdated"));
PropertyUtils.setProperty(sampleHuman, "lastupdated",
(Timestamp) testManagementForm
.get("sampleHumanLastupdated"));
PropertyUtils.setProperty(sampleOrganization, "lastupdated",
(Timestamp) testManagementForm
.get("sampleOrganizationLastupdated"));
person.setSysUserId(sysUserId);
patient.setSysUserId(sysUserId);
providerPerson.setSysUserId(sysUserId);
provider.setSysUserId(sysUserId);
sample.setSysUserId(sysUserId);
sampleHuman.setSysUserId(sysUserId);
sampleOrganization.setSysUserId(sysUserId);
sampleItem.setSysUserId(sysUserId);
personDAO.updateData(person);
patient.setPerson(person);
patientDAO.updateData(patient);
personDAO.updateData(providerPerson);
provider.setPerson(providerPerson);
providerDAO.updateData(provider);
sampleDAO.updateData(sample);
sampleHuman.setSampleId(sample.getId());
sampleHuman.setPatientId(patient.getId());
sampleHuman.setProviderId(provider.getId());
sampleHumanDAO.updateData(sampleHuman);
sampleOrganization.setSampleId(sample.getId());
sampleOrganization.setSample(sample);
sampleOrganizationDAO.updateData(sampleOrganization);
// bugzilla 1773 need to store sample not sampleId for use in
// sorting
sampleItem.setSample(sample);
sampleItemDAO.updateData(sampleItem);
// Analysis table
for (int i = 0; i < analyses.size(); i++) {
Analysis analysis = (Analysis) analyses.get(i);
analysis.setSampleItem(sampleItem);
analysis.setSysUserId(sysUserId);
analysisDAO.updateData(analysis);
}
// bugzilla 3032/2028 qa event logic needs to be executed for new and
// existing analyses for this sample
// ADDITIONAL REQUIREMENT ADDED 8/30: only for HSE2 Completed Status (see bugzilla 2032)
boolean isSampleStatusReadyForQaEvent = false;
if (!StringUtil.isNullorNill(sample.getStatus()) && (sample.getStatus().equals(SystemConfiguration.getInstance().getSampleStatusReleased()))
|| sample.getStatus().equals(SystemConfiguration.getInstance().getSampleStatusEntry2Complete())) {
isSampleStatusReadyForQaEvent = true;
}
if (isSampleStatusReadyForQaEvent) {
// bugzilla 2028 need additional information for qa events
typeOfSamp = sampleItem.getTypeOfSample();
sampleOrganization.setSampleId(sample.getId());
sampleOrganizationDAO.getDataBySample(sampleOrganization);
//bugzilla 2589
String submitterNumber = "";
if (sampleOrganization != null && sampleOrganization.getOrganization() != null) {
submitterNumber = sampleOrganization.getOrganization()
.getId();
}
//bugzilla 2227
List allAnalysesForSample = analysisDAO
.getMaxRevisionAnalysesBySample(sampleItem);
// bugzilla 2028 get the possible qa events
QaEvent qaEventForNoCollectionDate = new QaEvent();
qaEventForNoCollectionDate.setQaEventName(SystemConfiguration
.getInstance().getQaEventCodeForRequestNoCollectionDate());
qaEventForNoCollectionDate = qaEventDAO
.getQaEventByName(qaEventForNoCollectionDate);
QaEvent qaEventForNoSampleType = new QaEvent();
qaEventForNoSampleType.setQaEventName(SystemConfiguration
.getInstance().getQaEventCodeForRequestNoSampleType());
qaEventForNoSampleType = qaEventDAO
.getQaEventByName(qaEventForNoSampleType);
QaEvent qaEventForUnknownSubmitter = new QaEvent();
qaEventForUnknownSubmitter.setQaEventName(SystemConfiguration
.getInstance().getQaEventCodeForRequestUnknownSubmitter());
qaEventForUnknownSubmitter = qaEventDAO
.getQaEventByName(qaEventForUnknownSubmitter);
// end bugzilla 2028
// bugzilla 2028 get the possible qa event actions
Action actionForNoCollectionDate = new Action();
actionForNoCollectionDate.setCode(SystemConfiguration.getInstance()
.getQaEventActionCodeForRequestNoCollectionDate());
actionForNoCollectionDate = actionDAO
.getActionByCode(actionForNoCollectionDate);
Action actionForNoSampleType = new Action();
actionForNoSampleType.setCode(SystemConfiguration.getInstance()
.getQaEventActionCodeForRequestNoSampleType());
actionForNoSampleType = actionDAO
.getActionByCode(actionForNoSampleType);
Action actionForUnknownSubmitter = new Action();
actionForUnknownSubmitter.setCode(SystemConfiguration.getInstance()
.getQaEventActionCodeForRequestUnknownSubmitter());
actionForUnknownSubmitter = actionDAO
.getActionByCode(actionForUnknownSubmitter);
// end bugzilla 2028
for (int i = 0; i < allAnalysesForSample.size(); i++) {
Analysis analysis = (Analysis) allAnalysesForSample.get(i);
// bugzilla 2028 QA_EVENT COLLECTIONDATE
if (sample.getCollectionDate() == null) {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
if (analysisQaEvent == null) {
analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.insertData(analysisQaEvent);
} else {
if (analysisQaEvent.getCompletedDate() != null) {
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
} else {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
// if we don't find a record in ANALYSIS_QAEVENT (or
// completed date is not null) then this is already
// fixed
if (analysisQaEvent != null
&& analysisQaEvent.getCompletedDate() == null) {
AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
analysisQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analysisQaEventAction
.setAction(actionForNoCollectionDate);
analysisQaEventAction = analysisQaEventActionDAO
.getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);
// if we found a record in ANALYSIS_QAEVENT_ACTION
// then this has been fixed
if (analysisQaEventAction == null) {
// insert a record in ANALYSIS_QAEVENT_ACTION
AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
analQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analQaEventAction
.setAction(actionForNoCollectionDate);
analQaEventAction
.setCreatedDateForDisplay(dateAsText);
analQaEventAction.setSysUserId(sysUserId);
//bugzilla 2496
analQaEventAction.setSystemUser(systemUser);
analysisQaEventActionDAO
.insertData(analQaEventAction);
}
// update the found
// ANALYSIS_QAEVENT.COMPLETED_DATE with current
// date stamp
analysisQaEvent
.setCompletedDateForDisplay(dateAsText);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
// bugzilla 2028 QA_EVENT SAMPLETYPE
if (typeOfSamp.getDescription().equals(SAMPLE_TYPE_NOT_GIVEN)) {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoSampleType);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
if (analysisQaEvent == null) {
analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoSampleType);
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.insertData(analysisQaEvent);
} else {
if (analysisQaEvent.getCompletedDate() != null) {
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
} else {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoSampleType);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
// if we don't find a record in ANALYSIS_QAEVENT (or
// completed date is not null) then this is already
// fixed
if (analysisQaEvent != null
&& analysisQaEvent.getCompletedDate() == null) {
AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
analysisQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analysisQaEventAction
.setAction(actionForNoSampleType);
analysisQaEventAction = analysisQaEventActionDAO
.getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);
// if we found a record in ANALYSIS_QAEVENT_ACTION
// then this has been fixed
if (analysisQaEventAction == null) {
// insert a record in ANALYSIS_QAEVENT_ACTION
AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
analQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analQaEventAction
.setAction(actionForNoSampleType);
analQaEventAction
.setCreatedDateForDisplay(dateAsText);
analQaEventAction.setSysUserId(sysUserId);
//bugzilla 2496
analQaEventAction.setSystemUser(systemUser);
analysisQaEventActionDAO
.insertData(analQaEventAction);
}
// update the found
// ANALYSIS_QAEVENT.COMPLETED_DATE with current
// date stamp
analysisQaEvent
.setCompletedDateForDisplay(dateAsText);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
// bugzilla 2028 QA_EVENT UNKNOWN SUBMITTER
//bugzilla 2589
if (submitterNumber.equals(SystemConfiguration.getInstance()
.getUnknownSubmitterNumberForQaEvent())) {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
if (analysisQaEvent == null) {
analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.insertData(analysisQaEvent);
} else {
if (analysisQaEvent.getCompletedDate() != null) {
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
} else {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
// if we don't find a record in ANALYSIS_QAEVENT (or
// completed date is not null) then this is already
// fixed
if (analysisQaEvent != null
&& analysisQaEvent.getCompletedDate() == null) {
AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
analysisQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analysisQaEventAction
.setAction(actionForUnknownSubmitter);
analysisQaEventAction = analysisQaEventActionDAO
.getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);
// if we found a record in ANALYSIS_QAEVENT_ACTION
// then this has been fixed
if (analysisQaEventAction == null) {
// insert a record in ANALYSIS_QAEVENT_ACTION
AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
analQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analQaEventAction
.setAction(actionForUnknownSubmitter);
analQaEventAction
.setCreatedDateForDisplay(dateAsText);
analQaEventAction.setSysUserId(sysUserId);
//bugzilla 2496
analQaEventAction.setSystemUser(systemUser);
analysisQaEventActionDAO
.insertData(analQaEventAction);
}
// update the found
// ANALYSIS_QAEVENT.COMPLETED_DATE with current
// date stamp
analysisQaEvent
.setCompletedDateForDisplay(dateAsText);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
}
}
tx.commit();
// done updating return to menu
forward = FWD_CLOSE;
} catch (LIMSRuntimeException lre) {
//bugzilla 2154
LogEvent.logError("SampleDemographicsUpdateAction","performAction()",lre.toString());
tx.rollback();
// if error then forward to fail and don't update to blank page
// = false
errors = new ActionMessages();
ActionError error = null;
if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {
// how can I get popup instead of struts error at the top of
// page?
// ActionMessages errors = testManagementForm.validate(mapping,
// request);
error = new ActionError("errors.OptimisticLockException", null,
null);
} else {
error = new ActionError("errors.UpdateException", null, null);
}
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
request.setAttribute(ALLOW_EDITS_KEY, "false");
forward = FWD_FAIL;
} finally {
HibernateUtil.closeSession();
}
if (forward.equals(FWD_FAIL))
return mapping.findForward(FWD_FAIL);
if ("true".equalsIgnoreCase(request.getParameter("close"))) {
forward = FWD_CLOSE;
}
if (sample.getId() != null && !sample.getId().equals("0")) {
request.setAttribute(ID, sample.getId());
}
if (forward.equals(FWD_SUCCESS)) {
request.setAttribute("menuDefinition", "default");
}
return mapping.findForward(forward);
}
protected String getPageTitleKey() {
return "testmanagement.sampledemographics.title";
}
protected String getPageSubtitleKey() {
return "testmanagement.sampledemographics.subtitle";
}
//bugzilla 1765 changes to city state zip validation
protected ActionMessages validateAll(HttpServletRequest request,
ActionMessages errors, BaseActionForm dynaForm) throws Exception {
String result;
String messageKey;
//bugzilla 1978: changed to use Basic Provider which allows active and inactive projs
BasicProjectIdOrNameValidationProvider projIdOrNameValidator = new BasicProjectIdOrNameValidationProvider();
String projNum = (String) dynaForm.get("projectIdOrName");
if (!StringUtil.isNullorNill(projNum)) {
// project ID validation against database (reusing ajax
// validation logic)
result = projIdOrNameValidator.validate((String) dynaForm
.get("projectIdOrName"));
messageKey = "humansampleone.projectNumber";
if (result.startsWith("valid")) {
result = projIdOrNameValidator.validate((String) dynaForm
.get("projectNameOrId"));
if (result.equals("invalid")) {
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
} else {
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
}
String proj2Num = (String) dynaForm.get("project2IdOrName");
if (!StringUtil.isNullorNill(proj2Num)) {
result = projIdOrNameValidator.validate((String) dynaForm
.get("project2IdOrName"));
messageKey = "humansampleone.project2Number";
if (result.startsWith("valid")) {
result = projIdOrNameValidator.validate((String) dynaForm
.get("project2NameOrId"));
if (result.equals("invalid")) {
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
} else {
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
}
// organization ID (submitter) validation against database (reusing ajax
// validation logic)
//bugzilla 2069
//bugzilla 2531
OrganizationLocalAbbreviationValidationProvider organizationLocalAbbreviationValidator = new OrganizationLocalAbbreviationValidationProvider();
result = organizationLocalAbbreviationValidator.validate((String) dynaForm
.get("organizationLocalAbbreviation"),null);
messageKey = "humansampleone.provider.organization.localAbbreviation";
if (result.equals("invalid")) {
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
boolean cityValid = true;
boolean zipValid = true;
boolean stateValid = true;
// state validation against database (reusing ajax validation logic
StateValidationProvider stateValidator = new StateValidationProvider();
result = stateValidator.validate((String) dynaForm.get("state"));
messageKey = "person.state";
if (result.equals("invalid")) {
stateValid = false;
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
// city validation against database (reusing ajax validation logic
CityValidationProvider cityValidator = new CityValidationProvider();
result = cityValidator.validate((String) dynaForm.get("city"));
messageKey = "person.city";
if (result.equals("invalid")) {
cityValid = false;
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
// zip validation against database (reusing ajax validation logic
ZipValidationProvider zipValidator = new ZipValidationProvider();
result = zipValidator.validate((String) dynaForm.get("zipCode"));
messageKey = "person.zipCode";
if (result.equals("invalid")) {
zipValid = false;
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
if (cityValid && stateValid && zipValid) {
String messageKey1 = "person.city";
String messageKey2 = "person.zipCode";
String messageKey3 = "person.state";
// city validation against database (reusing ajax validation logic
CityStateZipComboValidationProvider cityStateZipComboValidator = new CityStateZipComboValidationProvider();
result = cityStateZipComboValidator.validate((String) dynaForm
.get("city"), (String) dynaForm.get("state"),
(String) dynaForm.get("zipCode"));
// combination is invalid if result is invalid
if ("invalid".equals(result)) {
ActionError error = new ActionError("errors.combo.3.invalid",
getMessageForKey(messageKey1),
getMessageForKey(messageKey2),
getMessageForKey(messageKey3), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
}
// sample type validation against database (reusing ajax validation
// logic
// do this "invalid" only when filled in. otherwise, "required" error
String typeOfSample = (String) dynaForm.get("typeOfSampleDesc");
if (!StringUtil.isNullorNill(typeOfSample)) {
HumanSampleTypeValidationProvider typeValidator = new HumanSampleTypeValidationProvider();
result = typeValidator.validate((String) dynaForm
.get("typeOfSampleDesc"));
messageKey = "sampleitem.typeOfSample";
if (result.equals("invalid")) {
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
} else {
ActionError error = new ActionError("errors.required",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
// sample source validation against database (reusing ajax validation
// logic
HumanSampleSourceValidationProvider sourceValidator = new HumanSampleSourceValidationProvider();
result = sourceValidator.validate((String) dynaForm
.get("sourceOfSampleDesc"));
messageKey = "sampleitem.sourceOfSample";
if (result.equals("invalid")) {
ActionError error = new ActionError("errors.invalid",
getMessageForKey(messageKey), null);
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
}
return errors;
}
} | kalwar/openelisglobal-core | app/src/us/mn/state/health/lims/testmanagement/action/SampleDemographicsUpdateAction.java | Java | mpl-2.0 | 42,396 |
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// API covering the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services. Use this API
// to manage resources such as virtual cloud networks (VCNs), compute instances, and
// block storage volumes.
//
package core
import (
"github.com/oracle/oci-go-sdk/v46/common"
)
// UpdateBootVolumeKmsKeyDetails The representation of UpdateBootVolumeKmsKeyDetails
type UpdateBootVolumeKmsKeyDetails struct {
// The OCID of the new Key Management key to assign to protect the specified volume.
// This key has to be a valid Key Management key, and policies must exist to allow the user and the Block Volume service to access this key.
// If you specify the same OCID as the previous key's OCID, the Block Volume service will use it to regenerate a volume encryption key.
KmsKeyId *string `mandatory:"false" json:"kmsKeyId"`
}
func (m UpdateBootVolumeKmsKeyDetails) String() string {
return common.PointerString(m)
}
| oracle/terraform-provider-baremetal | vendor/github.com/oracle/oci-go-sdk/v46/core/update_boot_volume_kms_key_details.go | GO | mpl-2.0 | 1,535 |
package ca.rbon.iostream.channel;
import ca.rbon.iostream.channel.part.CharIn;
import ca.rbon.iostream.channel.part.CharOut;
/**
* A char-oriented stream builder that can be used for output only.
*
* @author fralalonde
* @param <T> The backing resource type
*/
public interface CharBiChannel<T> extends CharIn<T>, CharOut<T> {
}
| fralalonde/iostream | src/main/java/ca/rbon/iostream/channel/CharBiChannel.java | Java | mpl-2.0 | 336 |
package org.openlca.app.collaboration.navigation;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.openlca.app.collaboration.util.ObjectIds;
import org.openlca.app.db.Cache;
import org.openlca.app.db.Database;
import org.openlca.app.db.Repository;
import org.openlca.app.navigation.elements.CategoryElement;
import org.openlca.app.navigation.elements.DatabaseElement;
import org.openlca.app.navigation.elements.GroupElement;
import org.openlca.app.navigation.elements.INavigationElement;
import org.openlca.app.navigation.elements.ModelElement;
import org.openlca.app.navigation.elements.ModelTypeElement;
import org.openlca.app.navigation.elements.NavigationRoot;
import org.openlca.app.rcp.images.Images;
import org.openlca.app.rcp.images.Overlay;
import org.openlca.core.database.config.DatabaseConfig;
import org.openlca.git.util.Constants;
/**
* known limitations: if a new model is created, the parent categories will be
* marked as changed (correctly), if the new model is deleted the parent
* categories will still be marked as changed (incorrectly), because we
* invalidated the categories and dont calculate new tree ids
*/
public class RepositoryLabel {
public static final String CHANGED_STATE = "> ";
public static Image getWithOverlay(INavigationElement<?> elem) {
if (!Repository.isConnected())
return null;
if (elem instanceof CategoryElement e && isZero(getRepositoryId(e)))
return Images.getForCategory(e.getContent().modelType, Overlay.ADDED);
if (elem instanceof ModelElement e && isZero(getRepositoryId(e)))
return Images.get(e.getContent().type, Overlay.ADDED);
return null;
}
private static ObjectId getRepositoryId(INavigationElement<?> elem) {
if (elem instanceof DatabaseElement)
return Repository.get().ids.get("");
if (elem instanceof ModelTypeElement e)
return Repository.get().ids.get(e.getContent().name());
if (elem instanceof CategoryElement e) {
var path = Repository.get().workspaceIds.getPath(e.getContent());
return Repository.get().ids.get(path);
}
if (elem instanceof ModelElement e) {
var path = Repository.get().workspaceIds.getPath(Cache.getPathCache(), e.getContent());
return Repository.get().ids.get(path);
}
return null;
}
private static ObjectId getWorkspaceId(INavigationElement<?> elem) {
if (elem instanceof DatabaseElement)
return Repository.get().workspaceIds.get("");
if (elem instanceof ModelTypeElement e)
return Repository.get().workspaceIds.get(e.getContent());
if (elem instanceof CategoryElement e)
return Repository.get().workspaceIds.get(e.getContent());
if (elem instanceof ModelElement e)
return Repository.get().workspaceIds.get(Cache.getPathCache(), e.getContent());
return null;
}
private static boolean isZero(ObjectId id) {
return ObjectIds.nullOrZero(id);
}
public static String getRepositoryText(DatabaseConfig dbConfig) {
if (!Database.isActive(dbConfig))
return null;
if (!Repository.isConnected())
return null;
var config = Repository.get().config;
var commits = Repository.get().commits;
var localCommitId = commits.resolve(Constants.LOCAL_BRANCH);
var remoteCommitId = commits.resolve(Constants.REMOTE_BRANCH);
var ahead = commits.find()
.after(remoteCommitId)
.until(localCommitId)
.all().size();
var behind = commits.find()
.after(localCommitId)
.until(remoteCommitId)
.all().size();
var text = " [" + config.url();
if (ahead > 0) {
text += " ↑" + ahead;
}
if (behind > 0) {
text += " ↓" + behind;
}
return text + "]";
}
public static String getStateIndicator(INavigationElement<?> elem) {
if (indicateChangedState(elem))
return CHANGED_STATE;
return null;
}
private static boolean indicateChangedState(INavigationElement<?> elem) {
if (!Repository.isConnected())
return false;
if (elem instanceof NavigationRoot)
return false;
if (elem instanceof DatabaseElement e) {
if (!Database.isActive(e.getContent()))
return false;
for (var child : elem.getChildren())
if (indicateChangedState(child))
return true;
return false;
}
if (elem instanceof GroupElement) {
for (var child : elem.getChildren())
if (indicateChangedState(child))
return true;
return false;
}
var repositoryId = getRepositoryId(elem);
var workspaceId = getWorkspaceId(elem);
var isNew = isZero(repositoryId);
if (elem instanceof ModelTypeElement) {
if (isNew != elem.getChildren().isEmpty())
return true;
for (var child : elem.getChildren())
if (indicateChangedState(child))
return true;
var isChanged = !repositoryId.equals(workspaceId);
return isChanged;
}
var isChanged = !isNew && !repositoryId.equals(workspaceId);
if (elem instanceof CategoryElement) {
if (isNew != elem.getChildren().isEmpty())
return true;
for (var child : elem.getChildren())
if (indicateChangedState(child))
return true;
return isChanged;
}
return isChanged;
}
public static Font getFont(INavigationElement<?> elem) {
// if (!isTracked(elem))
// return UI.italicFont();
return null;
}
public static Color getForeground(INavigationElement<?> elem) {
// if (!isTracked(elem))
// return Colors.get(85, 85, 85);
return null;
}
}
| GreenDelta/olca-app | olca-app/src/org/openlca/app/collaboration/navigation/RepositoryLabel.java | Java | mpl-2.0 | 5,376 |
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { csetWithCcovData } from '../utils/data';
import hash from '../utils/hash';
import * as FetchAPI from '../utils/fetch_data';
const parse = require('parse-diff');
/* DiffViewer loads a raw diff from Mozilla's hg-web and code coverage from
* shiptit-uplift to show a diff with code coverage information for added
* lines.
*/
export default class DiffViewerContainer extends Component {
constructor(props) {
super(props);
this.state = {
appError: undefined,
csetMeta: {
coverage: undefined,
},
parsedDiff: [],
};
}
componentDidMount() {
const { changeset } = this.props;
Promise.all([this.fetchSetCoverageData(changeset), this.fetchSetDiff(changeset)]);
}
async fetchSetCoverageData(changeset) {
try {
this.setState({ csetMeta: await csetWithCcovData({ node: changeset }) });
} catch (error) {
console.error(error);
this.setState({
appError: 'There was an error fetching the code coverage data.',
});
}
}
async fetchSetDiff(changeset) {
try {
const text = await (await FetchAPI.getDiff(changeset)).text();
this.setState({ parsedDiff: parse(text) });
} catch (error) {
console.error(error);
this.setState({
appError: 'We did not manage to parse the diff correctly.',
});
}
}
render() {
const { appError, csetMeta, parsedDiff } = this.state;
return (
<DiffViewer
{...csetMeta}
appError={appError}
parsedDiff={parsedDiff}
/>
);
}
}
const DiffViewer = ({ appError, coverage, node, parsedDiff, summary }) => (
<div className="codecoverage-diffviewer">
<div className="return-home"><Link to="/">Return to main page</Link></div>
{(coverage) &&
<CoverageMeta
{...coverage.parentMeta(coverage)}
{...coverage.diffMeta(node)}
coverage={coverage}
node={node}
summary={summary}
/>}
<span className="error_message">{appError}</span>
{parsedDiff.map(diffBlock =>
// We only push down the subset of code coverage data
// applicable to a file
(
<DiffFile
key={diffBlock.from}
diffBlock={diffBlock}
fileCoverageDiffs={(coverage) ?
coverage.diffs[diffBlock.from] : undefined}
/>
))}
</div>
);
const CoverageMeta = ({ ccovBackend, codecov, coverage, gh, hgRev, pushlog, summary }) => (
<div className="coverage-meta">
<div className="coverage-meta-row">
<span className="meta parent-meta-subtitle">Parent meta</span>
<span className="meta">
{`Current coverage: ${coverage.overall_cur.substring(0, 4)}%`}
</span>
<span className="meta meta-right">
<a href={pushlog} target="_blank">Push log</a>
<a href={gh} target="_blank">GitHub</a>
<a href={codecov} target="_blank">Codecov</a>
</span>
</div>
<div className="coverage-meta-row">
<span className="meta parent-meta-subtitle">Changeset meta</span>
<span className="meta">{summary}</span>
<span className="meta meta-right">
<a href={hgRev} target="_blank">Hg diff</a>
<a href={ccovBackend} target="_blank">Coverage backend</a>
</span>
</div>
</div>
);
/* A DiffLine contains all diff changes for a specific file */
const DiffFile = ({ fileCoverageDiffs, diffBlock }) => (
<div className="diff-file">
<div className="file-summary">
<div className="file-path">{diffBlock.from}</div>
</div>
{diffBlock.chunks.map(block => (
<DiffBlock
key={block.content}
filePath={diffBlock.from}
block={block}
fileDiffs={fileCoverageDiffs}
/>
))}
</div>
);
const uniqueLineId = (filePath, change) => {
let lineNumber;
if (change.ln) {
lineNumber = change.ln;
} else if (change.ln2) {
lineNumber = change.ln2;
} else {
lineNumber = change.ln1;
}
return `${hash(filePath)}-${change.type}-${lineNumber}`;
};
/* A DiffBlock is *one* of the blocks changed for a specific file */
const DiffBlock = ({ filePath, block, fileDiffs }) => (
<div>
<div className="diff-line-at">{block.content}</div>
<div className="diff-block">
<table className="diff-block-table">
<tbody>
{block.changes.map((change) => {
const uid = uniqueLineId(filePath, change);
return (<DiffLine
key={uid}
id={uid}
change={change}
fileDiffs={fileDiffs}
/>);
})}
</tbody>
</table>
</div>
</div>
);
/* A DiffLine contains metadata about a line in a DiffBlock */
const DiffLine = ({ change, fileDiffs, id }) => {
const c = change; // Information about the line itself
const changeType = change.type; // Added, deleted or unchanged line
let rowClass = 'nolinechange'; // CSS tr and td classes
const rowId = id;
let [oldLineNumber, newLineNumber] = ['', '']; // Cell contents
if (changeType === 'add') {
// Added line - <blank> | <new line number>
if (fileDiffs) {
try {
const coverage = fileDiffs[c.ln];
if (coverage === 'Y') {
rowClass = 'hit';
} else if (coverage === '?') {
rowClass = 'nolinechange';
} else {
rowClass = 'miss';
}
} catch (e) {
console.log(e);
rowClass = 'miss';
}
}
newLineNumber = c.ln;
} else if (changeType === 'del') {
// Removed line - <old line number> | <blank>
oldLineNumber = c.ln;
} else {
// Unchanged line - <old line number> | <blank>
oldLineNumber = c.ln1;
if (oldLineNumber !== c.ln2) {
newLineNumber = c.ln2;
}
}
return (
<tr id={rowId} className={`${rowClass} diff-row`}>
<td className="old-line-number diff-cell">{oldLineNumber}</td>
<td className="new-line-number diff-cell">{newLineNumber}</td>
<td className="line-content diff-cell">
<pre>{c.content}</pre>
</td>
</tr>
);
};
| LinkaiQi/firefox-code-coverage-frontend | src/components/diffviewer.js | JavaScript | mpl-2.0 | 6,160 |
//
// gomanta - Go library to interact with Joyent Manta
//
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2016 Joyent Inc.
//
// Written by Daniele Stroppa <daniele.stroppa@joyent.com>
//
package manta_test
import (
"flag"
"github.com/joyent/gocommon/jpc"
gc "launchpad.net/gocheck"
"testing"
)
var live = flag.Bool("live", false, "Include live Manta tests")
var keyName = flag.String("key.name", "", "Specify the full path to the private key, defaults to ~/.ssh/id_rsa")
func Test(t *testing.T) {
if *live {
creds, err := jpc.CompleteCredentialsFromEnv(*keyName)
if err != nil {
t.Fatalf("Error setting up test suite: %s", err.Error())
}
registerMantaTests(creds)
}
registerLocalTests(*keyName)
gc.TestingT(t)
}
| joyent/gomanta | manta/manta_test.go | GO | mpl-2.0 | 915 |
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :menu_pages, :current_path
def menu_pages
{
hunts: "/hunts",
properties: "/properties",
streets: "/streets"}
end
def current_path
request.env["PATH_INFO"]
end
end
| ralphreid/bird_dog | app/controllers/application_controller.rb | Ruby | mpl-2.0 | 291 |
<?php
declare(strict_types=1);
use ParagonIE\Halite\Alerts as CryptoException;
use ParagonIE\Halite\Alerts\InvalidType;
use ParagonIE\Halite\KeyFactory;
use ParagonIE\Halite\Asymmetric\Crypto as Asymmetric;
use ParagonIE\Halite\Asymmetric\EncryptionPublicKey;
use ParagonIE\Halite\Asymmetric\SignaturePublicKey;
use ParagonIE\Halite\Asymmetric\SignatureSecretKey;
use ParagonIE\HiddenString\HiddenString;
use PHPUnit\Framework\TestCase;
/**
* @backupGlobals disabled
* @backupStaticAttributes disabled
*/
class KeyTest extends TestCase
{
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
*/
public function testDerive()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$key = KeyFactory::deriveEncryptionKey(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
KeyFactory::INTERACTIVE
);
$this->assertSame(
$key->getRawKeyMaterial(),
"\x3a\x16\x68\xc1\x45\x8a\x4f\x59\x9c\x36\x4e\xa4\x7f\xae\xfa\xe1" .
"\xee\xa3\xa6\xd0\x34\x26\x35\xc9\xb4\x79\xee\xab\xf4\x71\x86\xaa"
);
$salt = sodium_hex2bin(
'762ce4cabd543065172236de1027536a'
);
// Issue #10
$enc_secret = KeyFactory::deriveEncryptionKey(
new HiddenString('correct horse battery staple'),
$salt
);
$this->assertTrue(
$enc_secret->isEncryptionKey()
);
$key = KeyFactory::deriveAuthenticationKey(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
KeyFactory::INTERACTIVE
);
$this->assertSame(
$key->getRawKeyMaterial(),
"\x3a\x16\x68\xc1\x45\x8a\x4f\x59\x9c\x36\x4e\xa4\x7f\xae\xfa\xe1" .
"\xee\xa3\xa6\xd0\x34\x26\x35\xc9\xb4\x79\xee\xab\xf4\x71\x86\xaa"
);
}
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
*/
public function testDeriveOldArgon2i()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$key = KeyFactory::deriveEncryptionKey(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
KeyFactory::INTERACTIVE,
SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13
);
$this->assertSame(
$key->getRawKeyMaterial(),
"\x79\x12\x36\xc1\xf0\x6b\x73\xbd\xaa\x88\x89\x80\xe3\x2c\x4b\xdb".
"\x25\xd1\xf9\x39\xe5\xf7\x13\x30\x5c\xd8\x4c\x50\x22\xcc\x96\x6e"
);
$salt = sodium_hex2bin(
'762ce4cabd543065172236de1027536a'
);
// Issue #10
$enc_secret = KeyFactory::deriveEncryptionKey(
new HiddenString('correct horse battery staple'),
$salt
);
$this->assertTrue(
$enc_secret->isEncryptionKey()
);
}
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
* @throws CryptoException\InvalidSignature
*/
public function testDeriveSigningKey()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$keypair = KeyFactory::deriveSignatureKeyPair(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
);
$sign_secret = $keypair->getSecretKey();
$sign_public = $keypair->getPublicKey();
$this->assertTrue($sign_secret instanceof SignatureSecretKey);
$this->assertTrue($sign_public instanceof SignaturePublicKey);
// Can this be used?
$message = 'This is a test message';
$signed = Asymmetric::sign(
$message,
$sign_secret
);
$this->assertTrue(
Asymmetric::verify($message, $sign_public, $signed)
);
$this->assertSame(
$sign_public->getRawKeyMaterial(),
"\x9a\xce\x92\x8f\x6a\x27\x93\x8e\x87\xac\x9b\x97\xfb\xe2\x50\x6b" .
"\x67\xd5\x8b\x68\xeb\x37\xc2\x2d\x31\xdb\xcf\x7e\x8d\xa0\xcb\x17"
);
}
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
* @throws CryptoException\InvalidSignature
*/
public function testDeriveSigningKeyOldArgon2i()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$keypair = KeyFactory::deriveSignatureKeyPair(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
KeyFactory::INTERACTIVE,
SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13
);
$sign_secret = $keypair->getSecretKey();
$sign_public = $keypair->getPublicKey();
$this->assertTrue($sign_secret instanceof SignatureSecretKey);
$this->assertTrue($sign_public instanceof SignaturePublicKey);
// Can this be used?
$message = 'This is a test message';
$signed = Asymmetric::sign(
$message,
$sign_secret
);
$this->assertTrue(
Asymmetric::verify($message, $sign_public, $signed)
);
$this->assertSame(
$sign_public->getRawKeyMaterial(),
"\x88\x9c\xc0\x7a\x90\xb8\x98\xf4\x6b\x47\xfe\xcc\x91\x42\x58\x45".
"\x41\xcf\x4b\x5c\x6a\x82\x2d\xdc\xc6\x8b\x87\xbc\x08\x2f\xfe\x95"
);
}
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\CannotPerformOperation
* @throws CryptoException\InvalidKey
*/
public function testImport()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$key = KeyFactory::generateAuthenticationKey();
$export = KeyFactory::export($key);
$import = KeyFactory::importAuthenticationKey($export);
$this->assertSame(
bin2hex($key->getRawKeyMaterial()),
bin2hex($import->getRawKeyMaterial())
);
$key = KeyFactory::generateEncryptionKey();
$export = KeyFactory::export($key);
$import = KeyFactory::importEncryptionKey($export);
$this->assertSame(
bin2hex($key->getRawKeyMaterial()),
bin2hex($import->getRawKeyMaterial())
);
$signKeypair = KeyFactory::generateSignatureKeyPair();
$export = KeyFactory::export($signKeypair);
$import = KeyFactory::importSignatureKeyPair($export);
$this->assertSame(
bin2hex($signKeypair->getSecretKey()->getRawKeyMaterial()),
bin2hex($import->getSecretKey()->getRawKeyMaterial())
);
$this->assertSame(
bin2hex($signKeypair->getPublicKey()->getRawKeyMaterial()),
bin2hex($import->getPublicKey()->getRawKeyMaterial())
);
$export = KeyFactory::export($signKeypair->getSecretKey());
$import = KeyFactory::importSignatureSecretKey($export);
$this->assertSame(
bin2hex($signKeypair->getSecretKey()->getRawKeyMaterial()),
bin2hex($import->getRawKeyMaterial())
);
$export = KeyFactory::export($signKeypair->getPublicKey());
$import = KeyFactory::importSignaturePublicKey($export);
$this->assertSame(
bin2hex($signKeypair->getPublicKey()->getRawKeyMaterial()),
bin2hex($import->getRawKeyMaterial())
);
$encKeypair = KeyFactory::generateEncryptionKeyPair();
$export = KeyFactory::export($encKeypair);
$import = KeyFactory::importEncryptionKeyPair($export);
$this->assertSame(
bin2hex($encKeypair->getSecretKey()->getRawKeyMaterial()),
bin2hex($import->getSecretKey()->getRawKeyMaterial())
);
$this->assertSame(
bin2hex($encKeypair->getPublicKey()->getRawKeyMaterial()),
bin2hex($import->getPublicKey()->getRawKeyMaterial())
);
$export = KeyFactory::export($encKeypair->getSecretKey());
$import = KeyFactory::importEncryptionSecretKey($export);
$this->assertSame(
bin2hex($encKeypair->getSecretKey()->getRawKeyMaterial()),
bin2hex($import->getRawKeyMaterial())
);
$export = KeyFactory::export($encKeypair->getPublicKey());
$import = KeyFactory::importEncryptionPublicKey($export);
$this->assertSame(
bin2hex($encKeypair->getPublicKey()->getRawKeyMaterial()),
bin2hex($import->getRawKeyMaterial())
);
try {
KeyFactory::export(new stdClass());
$this->fail('Expected a TypeError to be raised');
} catch (TypeError $ex) {
}
}
/**
* @throws TypeError
* @throws CryptoException\CannotPerformOperation
* @throws CryptoException\InvalidKey
*/
public function testKeyTypes()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$key = KeyFactory::generateAuthenticationKey();
$this->assertFalse($key->isAsymmetricKey());
$this->assertFalse($key->isEncryptionKey());
$this->assertTrue($key->isSecretKey());
$this->assertTrue($key->isSigningKey());
$this->assertFalse($key->isPublicKey());
$key = KeyFactory::generateEncryptionKey();
$this->assertFalse($key->isAsymmetricKey());
$this->assertTrue($key->isEncryptionKey());
$this->assertTrue($key->isSecretKey());
$this->assertFalse($key->isSigningKey());
$this->assertFalse($key->isPublicKey());
$keypair = KeyFactory::generateEncryptionKeyPair();
$enc_secret = $keypair->getSecretKey();
$enc_public = $keypair->getPublicKey();
$this->assertTrue($enc_secret->isAsymmetricKey());
$this->assertTrue($enc_secret->isEncryptionKey());
$this->assertTrue($enc_secret->isSecretKey());
$this->assertFalse($enc_secret->isSigningKey());
$this->assertFalse($enc_secret->isPublicKey());
$this->assertTrue($enc_public->isAsymmetricKey());
$this->assertTrue($enc_public->isEncryptionKey());
$this->assertFalse($enc_public->isSecretKey());
$this->assertFalse($enc_public->isSigningKey());
$this->assertTrue($enc_public->isPublicKey());
$keypair = KeyFactory::generateSignatureKeyPair();
$sign_secret = $keypair->getSecretKey();
$sign_public = $keypair->getPublicKey();
$this->assertTrue($sign_secret->isAsymmetricKey());
$this->assertFalse($sign_secret->isEncryptionKey());
$this->assertTrue($sign_secret->isSecretKey());
$this->assertTrue($sign_public->isSigningKey());
$this->assertFalse($sign_secret->isPublicKey());
$this->assertTrue($sign_public->isAsymmetricKey());
$this->assertFalse($sign_public->isEncryptionKey());
$this->assertFalse($sign_public->isSecretKey());
$this->assertTrue($sign_public->isSigningKey());
$this->assertTrue($sign_public->isPublicKey());
}
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\CannotPerformOperation
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
*/
public function testEncKeyStorage()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$enc_keypair = KeyFactory::deriveEncryptionKeyPair(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
);
$enc_secret = $enc_keypair->getSecretKey();
$enc_public = $enc_keypair->getPublicKey();
$file_secret = \tempnam(__DIR__.'/tmp', 'key');
$file_public = \tempnam(__DIR__.'/tmp', 'key');
$this->assertTrue(
KeyFactory::save($enc_secret, $file_secret) !== false
);
$this->assertTrue(
KeyFactory::save($enc_public, $file_public) !== false
);
$load_public = KeyFactory::loadEncryptionPublicKey($file_public);
$this->assertTrue(
$load_public instanceof EncryptionPublicKey
);
$this->assertTrue(
\hash_equals($enc_public->getRawKeyMaterial(), $load_public->getRawKeyMaterial())
);
$encoded = KeyFactory::export($enc_secret);
$imported = KeyFactory::importEncryptionSecretKey($encoded);
$this->assertSame(
$enc_secret->getRawKeyMaterial(),
$imported->getRawKeyMaterial()
);
\unlink($file_secret);
\unlink($file_public);
}
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\CannotPerformOperation
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
*/
public function testSignKeyStorage()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$sign_keypair = KeyFactory::deriveSignatureKeyPair(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
);
$sign_secret = $sign_keypair->getSecretKey();
$sign_public = $sign_keypair->getPublicKey();
$file_secret = \tempnam(__DIR__.'/tmp', 'key');
$file_public = \tempnam(__DIR__.'/tmp', 'key');
$this->assertTrue(
KeyFactory::save($sign_secret, $file_secret) !== false
);
$this->assertTrue(
KeyFactory::save($sign_public, $file_public) !== false
);
$load_public = KeyFactory::loadSignaturePublicKey($file_public);
$this->assertTrue(
$load_public instanceof SignaturePublicKey
);
$this->assertTrue(
\hash_equals($sign_public->getRawKeyMaterial(), $load_public->getRawKeyMaterial())
);
$encoded = KeyFactory::export($sign_secret);
$imported = KeyFactory::importSignatureSecretKey($encoded);
$this->assertSame(
$sign_secret->getRawKeyMaterial(),
$imported->getRawKeyMaterial()
);
\unlink($file_secret);
\unlink($file_public);
}
/**
* @throws TypeError
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
*/
public function testInvalidKeyLevels()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
try {
KeyFactory::deriveEncryptionKey(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
'INVALID SECURITY LEVEL IDENTIFIER SHOULD HAVE USED A CONSTANT INSTEAD'
);
$this->fail('Argon2 should fail on invalid');
} catch (InvalidType $ex) {
$this->assertSame(
'Invalid security level for Argon2i',
$ex->getMessage()
);
}
}
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
*/
public function testKeyLevels()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$key = KeyFactory::deriveEncryptionKey(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
KeyFactory::MODERATE
);
$this->assertSame(
'b5b21bb729b14cecca8e9d8e5811a09f0b4cb3fd4271ebf6f416ec855b6cd286',
sodium_bin2hex($key->getRawKeyMaterial())
);
$key = KeyFactory::deriveEncryptionKey(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
KeyFactory::SENSITIVE
);
$this->assertSame(
'd2d76bb8f27dadcc2820515dee41e2e3946f489e5e0635c987815c06c3baee95',
sodium_bin2hex($key->getRawKeyMaterial())
);
}
/**
* @throws InvalidType
* @throws TypeError
* @throws CryptoException\InvalidKey
* @throws CryptoException\InvalidSalt
*/
public function testKeyLevelsOldArgon2i()
{
if (!\extension_loaded('sodium')) {
$this->markTestSkipped('Libsodium not installed');
}
$key = KeyFactory::deriveEncryptionKey(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
KeyFactory::MODERATE,
SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13
);
$this->assertSame(
'227817a188e55a679ddc8b1ca51f7aba4d1086f0512f9e3eb547c2392d49bde9',
sodium_bin2hex($key->getRawKeyMaterial())
);
$key = KeyFactory::deriveEncryptionKey(
new HiddenString('apple'),
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
KeyFactory::SENSITIVE
);
$this->assertSame(
'd2d76bb8f27dadcc2820515dee41e2e3946f489e5e0635c987815c06c3baee95',
sodium_bin2hex($key->getRawKeyMaterial())
);
}
/**
* @throws TypeError
*/
public function testInvalidSizes()
{
try {
new \ParagonIE\Halite\Symmetric\AuthenticationKey(new HiddenString(''));
$this->fail('Invalid key size accepted');
} catch (\ParagonIE\Halite\Alerts\InvalidKey $ex) {
$this->assertSame('Authentication key must be CRYPTO_AUTH_KEYBYTES (32) bytes long', $ex->getMessage());
}
try {
new \ParagonIE\Halite\Symmetric\EncryptionKey(new HiddenString(''));
$this->fail('Invalid key size accepted');
} catch (\ParagonIE\Halite\Alerts\InvalidKey $ex) {
$this->assertSame('Encryption key must be CRYPTO_STREAM_KEYBYTES (32) bytes long', $ex->getMessage());
}
try {
new \ParagonIE\Halite\Asymmetric\EncryptionSecretKey(new HiddenString(''));
$this->fail('Invalid key size accepted');
} catch (\ParagonIE\Halite\Alerts\InvalidKey $ex) {
$this->assertSame('Encryption secret key must be CRYPTO_BOX_SECRETKEYBYTES (32) bytes long', $ex->getMessage());
}
try {
new \ParagonIE\Halite\Asymmetric\EncryptionPublicKey(new HiddenString(''));
$this->fail('Invalid key size accepted');
} catch (\ParagonIE\Halite\Alerts\InvalidKey $ex) {
$this->assertSame('Encryption public key must be CRYPTO_BOX_PUBLICKEYBYTES (32) bytes long', $ex->getMessage());
}
try {
new \ParagonIE\Halite\Asymmetric\SignatureSecretKey(new HiddenString(''));
$this->fail('Invalid key size accepted');
} catch (\ParagonIE\Halite\Alerts\InvalidKey $ex) {
$this->assertSame('Signature secret key must be CRYPTO_SIGN_SECRETKEYBYTES (64) bytes long', $ex->getMessage());
}
try {
new \ParagonIE\Halite\Asymmetric\SignaturePublicKey(new HiddenString(''));
$this->fail('Invalid key size accepted');
} catch (\ParagonIE\Halite\Alerts\InvalidKey $ex) {
$this->assertSame('Signature public key must be CRYPTO_SIGN_PUBLICKEYBYTES (32) bytes long', $ex->getMessage());
}
}
}
| paragonie/halite | test/unit/KeyTest.php | PHP | mpl-2.0 | 20,415 |
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
package syncthing
import (
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/pkg/errors"
"github.com/syncthing/syncthing/lib/config"
"github.com/syncthing/syncthing/lib/db/backend"
"github.com/syncthing/syncthing/lib/events"
"github.com/syncthing/syncthing/lib/fs"
"github.com/syncthing/syncthing/lib/locations"
"github.com/syncthing/syncthing/lib/protocol"
"github.com/syncthing/syncthing/lib/tlsutil"
)
func LoadOrGenerateCertificate(certFile, keyFile string) (tls.Certificate, error) {
cert, err := tls.LoadX509KeyPair(
locations.Get(locations.CertFile),
locations.Get(locations.KeyFile),
)
if err != nil {
l.Infof("Generating ECDSA key and certificate for %s...", tlsDefaultCommonName)
return tlsutil.NewCertificate(
locations.Get(locations.CertFile),
locations.Get(locations.KeyFile),
tlsDefaultCommonName,
deviceCertLifetimeDays,
)
}
return cert, nil
}
func DefaultConfig(path string, myID protocol.DeviceID, evLogger events.Logger, noDefaultFolder bool) (config.Wrapper, error) {
newCfg, err := config.NewWithFreePorts(myID)
if err != nil {
return nil, err
}
if noDefaultFolder {
l.Infoln("We will skip creation of a default folder on first start")
return config.Wrap(path, newCfg, evLogger), nil
}
newCfg.Folders = append(newCfg.Folders, config.NewFolderConfiguration(myID, "default", "Default Folder", fs.FilesystemTypeBasic, locations.Get(locations.DefFolder)))
l.Infoln("Default folder created and/or linked to new config")
return config.Wrap(path, newCfg, evLogger), nil
}
// LoadConfigAtStartup loads an existing config. If it doesn't yet exist, it
// creates a default one, without the default folder if noDefaultFolder is ture.
// Otherwise it checks the version, and archives and upgrades the config if
// necessary or returns an error, if the version isn't compatible.
func LoadConfigAtStartup(path string, cert tls.Certificate, evLogger events.Logger, allowNewerConfig, noDefaultFolder bool) (config.Wrapper, error) {
myID := protocol.NewDeviceID(cert.Certificate[0])
cfg, err := config.Load(path, myID, evLogger)
if fs.IsNotExist(err) {
cfg, err = DefaultConfig(path, myID, evLogger, noDefaultFolder)
if err != nil {
return nil, errors.Wrap(err, "failed to generate default config")
}
err = cfg.Save()
if err != nil {
return nil, errors.Wrap(err, "failed to save default config")
}
l.Infof("Default config saved. Edit %s to taste (with Syncthing stopped) or use the GUI", cfg.ConfigPath())
} else if err == io.EOF {
return nil, errors.New("failed to load config: unexpected end of file. Truncated or empty configuration?")
} else if err != nil {
return nil, errors.Wrap(err, "failed to load config")
}
if cfg.RawCopy().OriginalVersion != config.CurrentVersion {
if cfg.RawCopy().OriginalVersion == config.CurrentVersion+1101 {
l.Infof("Now, THAT's what we call a config from the future! Don't worry. As long as you hit that wire with the connecting hook at precisely eighty-eight miles per hour the instant the lightning strikes the tower... everything will be fine.")
}
if cfg.RawCopy().OriginalVersion > config.CurrentVersion && !allowNewerConfig {
return nil, fmt.Errorf("config file version (%d) is newer than supported version (%d). If this is expected, use -allow-newer-config to override.", cfg.RawCopy().OriginalVersion, config.CurrentVersion)
}
err = archiveAndSaveConfig(cfg)
if err != nil {
return nil, errors.Wrap(err, "config archive")
}
}
return cfg, nil
}
func archiveAndSaveConfig(cfg config.Wrapper) error {
// Copy the existing config to an archive copy
archivePath := cfg.ConfigPath() + fmt.Sprintf(".v%d", cfg.RawCopy().OriginalVersion)
l.Infoln("Archiving a copy of old config file format at:", archivePath)
if err := copyFile(cfg.ConfigPath(), archivePath); err != nil {
return err
}
// Do a regular atomic config sve
return cfg.Save()
}
func copyFile(src, dst string) error {
bs, err := ioutil.ReadFile(src)
if err != nil {
return err
}
if err := ioutil.WriteFile(dst, bs, 0600); err != nil {
// Attempt to clean up
os.Remove(dst)
return err
}
return nil
}
func OpenDBBackend(path string, tuning config.Tuning) (backend.Backend, error) {
return backend.Open(path, backend.Tuning(tuning))
}
| AudriusButkevicius/syncthing | lib/syncthing/utils.go | GO | mpl-2.0 | 4,537 |
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
// Core Services API
//
// API covering the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm),
// Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and
// Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services. Use this API
// to manage resources such as virtual cloud networks (VCNs), compute instances, and
// block storage volumes.
//
package core
import (
"github.com/oracle/oci-go-sdk/v46/common"
)
// CpeDeviceShapeDetail The detailed information about a particular CPE device type. Compare with
// CpeDeviceShapeSummary.
type CpeDeviceShapeDetail struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the CPE device shape.
// This value uniquely identifies the type of CPE device.
CpeDeviceShapeId *string `mandatory:"false" json:"cpeDeviceShapeId"`
CpeDeviceInfo *CpeDeviceInfo `mandatory:"false" json:"cpeDeviceInfo"`
// For certain CPE devices types, the customer can provide answers to
// questions that are specific to the device type. This attribute contains
// a list of those questions. The Networking service merges the answers with
// other information and renders a set of CPE configuration content. To
// provide the answers, use
// UpdateTunnelCpeDeviceConfig.
Parameters []CpeDeviceConfigQuestion `mandatory:"false" json:"parameters"`
// A template of CPE device configuration information that will be merged with the customer's
// answers to the questions to render the final CPE device configuration content. Also see:
// * GetCpeDeviceConfigContent
// * GetIpsecCpeDeviceConfigContent
// * GetTunnelCpeDeviceConfigContent
Template *string `mandatory:"false" json:"template"`
}
func (m CpeDeviceShapeDetail) String() string {
return common.PointerString(m)
}
| oracle/terraform-provider-baremetal | vendor/github.com/oracle/oci-go-sdk/v46/core/cpe_device_shape_detail.go | GO | mpl-2.0 | 2,247 |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
from __future__ import unicode_literals
from .models import Tree, Repository, Locale, Forest
from django.contrib import admin
class RepositoryAdmin(admin.ModelAdmin):
list_display = ('name', 'id',)
exclude = ('changesets',)
search_fields = ('name',)
admin.site.register(Locale)
admin.site.register(Repository, RepositoryAdmin)
admin.site.register(Tree)
admin.site.register(Forest)
| mozilla/elmo | apps/life/admin.py | Python | mpl-2.0 | 636 |
package minejava.material;
import minejava.reg.util.EnumSet;
import minejava.reg.util.Set;
import minejava.Material;
import minejava.areg.lang.Validate;
import minejava.block.BlockFace;
public class Mushroom extends MaterialData{
private static final byte SHROOM_NONE = 0;
private static final byte SHROOM_STEM = 10;
private static final byte NORTH_LIMIT = 4;
private static final byte SOUTH_LIMIT = 6;
private static final byte EAST_WEST_LIMIT = 3;
private static final byte EAST_REMAINDER = 0;
private static final byte WEST_REMAINDER = 1;
private static final byte NORTH_SOUTH_MOD = 3;
private static final byte EAST_WEST_MOD = 1;
public Mushroom(Material shroom){
super(shroom);
Validate.isTrue(shroom == Material.HUGE_RED_MUSHROOM || shroom == Material.HUGE_BROWN_MUSHROOM, "Not a mushroom!");
}
public Mushroom(Material shroom, byte data){
super(shroom, data);
Validate.isTrue(shroom == Material.HUGE_RED_MUSHROOM || shroom == Material.HUGE_BROWN_MUSHROOM, "Not a mushroom!");
}
public Mushroom(int type, byte data){
super(type, data);
Validate.isTrue(type == Material.HUGE_RED_MUSHROOM.getId() || type == Material.HUGE_BROWN_MUSHROOM.getId(), "Not a mushroom!");
}
public boolean isStem(){
return getData() == SHROOM_STEM;
}
public void setStem(){
setData((byte) 10);
}
public boolean isFacePainted(BlockFace face){
byte data = getData();
if (data == SHROOM_NONE || data == SHROOM_STEM){
return false;
}
switch (face){
case WEST:
return data < NORTH_LIMIT;
case EAST:
return data > SOUTH_LIMIT;
case NORTH:
return data % EAST_WEST_LIMIT == EAST_REMAINDER;
case SOUTH:
return data % EAST_WEST_LIMIT == WEST_REMAINDER;
case UP:
return true;
default:
return false;
}
}
public void setFacePainted(BlockFace face, boolean painted){
if (painted == isFacePainted(face)){
return;
}
byte data = getData();
if (data == SHROOM_STEM){
data = 5;
}
switch (face){
case WEST:
if (painted){
data -= NORTH_SOUTH_MOD;
}else{
data += NORTH_SOUTH_MOD;
}
break;
case EAST:
if (painted){
data += NORTH_SOUTH_MOD;
}else{
data -= NORTH_SOUTH_MOD;
}
break;
case NORTH:
if (painted){
data += EAST_WEST_MOD;
}else{
data -= EAST_WEST_MOD;
}
break;
case SOUTH:
if (painted){
data -= EAST_WEST_MOD;
}else{
data += EAST_WEST_MOD;
}
break;
case UP:
if (!painted){
data = 0;
}
break;
default:
throw new IllegalArgumentException("Can't paint that face of a mushroom!");
}
setData(data);
}
public Set<BlockFace> getPaintedFaces(){
EnumSet<BlockFace> faces = EnumSet.noneOf(BlockFace.class);
if (isFacePainted(BlockFace.WEST)){
faces.add(BlockFace.WEST);
}
if (isFacePainted(BlockFace.NORTH)){
faces.add(BlockFace.NORTH);
}
if (isFacePainted(BlockFace.SOUTH)){
faces.add(BlockFace.SOUTH);
}
if (isFacePainted(BlockFace.EAST)){
faces.add(BlockFace.EAST);
}
if (isFacePainted(BlockFace.UP)){
faces.add(BlockFace.UP);
}
return faces;
}
@Override
public String toString(){
return Material.getMaterial(getItemTypeId()).toString() + (isStem() ? "{STEM}" : getPaintedFaces());
}
@Override
public Mushroom clone() throws CloneNotSupportedException{
return (Mushroom) super.clone();
}
} | cFerg/MineJava | src/main/java/minejava/material/Mushroom.java | Java | mpl-2.0 | 4,554 |
/*
This file is part of the MinSG library extension MixedExtVisibility.
Copyright (C) 2015 Claudius Jähn <claudius@uni-paderborn.de>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_MIXED_EXTERN_VISIBILITY
#include "Preprocessor.h"
#include "../../Core/FrameContext.h"
#include "../../Helper/StdNodeVisitors.h"
#include <Rendering/RenderingContext/RenderingContext.h>
#include <Rendering/RenderingContext/RenderingParameters.h>
#include <Rendering/OcclusionQuery.h>
#include <Util/Graphics/Color.h>
#include <algorithm>
struct KeyHash {
size_t operator()(const Util::Reference<MinSG::Node>& a) const
{
std::hash<MinSG::Node*> hash_fn;
return hash_fn(a.get());
}
};
std::vector<Util::Reference<MinSG::Node>> MinSG::MixedExtVisibility::
filterAndSortNodesByExtVisibility(FrameContext & context,
const std::vector<Util::Reference<Node>>& nodes,
const std::vector<Util::Reference<AbstractCameraNode>>& cameras,
size_t polygonLimit){
context.pushCamera();
std::unordered_map<Util::Reference<MinSG::Node>,uint32_t,KeyHash> nodeVisibilities; // node -> max visible pixels
for(const auto& node: nodes)
nodeVisibilities[node] = 0;
RenderParam param(USE_WORLD_MATRIX);
param.setRenderingLayers(1);
for(const auto& camera : cameras){
context.setCamera(camera.get());
// first pass
context.getRenderingContext().clearScreen(Util::Color4f(0,0,0,0));
for(const auto & node : nodes)
context.displayNode(node.get(), param);
context.getRenderingContext().pushAndSetDepthBuffer(Rendering::DepthBufferParameters(true, true, Rendering::Comparison::EQUAL));
std::vector<Rendering::OcclusionQuery> queries(nodeVisibilities.size());
size_t i = 0;
Rendering::OcclusionQuery::enableTestMode(context.getRenderingContext());
for(const auto & node : nodes) {
queries[i].begin();
context.displayNode(node.get(), param);
queries[i].end();
++i;
}
Rendering::OcclusionQuery::disableTestMode(context.getRenderingContext());
i=0;
for(const auto & node : nodes){
nodeVisibilities[node] = std::max(queries[i].getResult(),nodeVisibilities[node]);
++i;
}
context.getRenderingContext().popDepthBuffer();
}
context.popCamera();
std::vector<std::pair<Util::Reference<Node>,uint32_t>> sortedNodes;
for(const auto& nodeVis : nodeVisibilities)
sortedNodes.emplace_back(nodeVis.first,nodeVis.second);
std::sort(sortedNodes.begin(),sortedNodes.end(),
[](const std::pair<Util::Reference<Node>,uint32_t>&a,const std::pair<Util::Reference<Node>,uint32_t>&b){return a.second>b.second;});
for(const auto& nodeVis : sortedNodes)
std::cout << " "<<nodeVis.second<<" ";
std::vector<Util::Reference<Node>> collectedNodes;
size_t pCounter = 0;
for(auto& entry : sortedNodes){
if(entry.second==0)
break;
pCounter += countTriangles(entry.first.get());
if(polygonLimit>0 && pCounter>polygonLimit)
break;
collectedNodes.emplace_back(std::move(entry.first));
}
return collectedNodes;
}
#endif /* MINSG_EXT_MIXED_EXTERN_VISIBILITY */
| PADrend/MinSG | Ext/MixedExtVisibility/Preprocessor.cpp | C++ | mpl-2.0 | 3,236 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("11.-12.PolinomialsOperations")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("11.-12.PolinomialsOperations")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e7452e98-1832-44fb-b83f-de81fcfcfaa1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| emilVenkov12/TelerikCourses | Programing/02.CSharpPart2Winter2013-2014/03.Methods/03.Methods-HW/11.-12.PolinomialsOperations/Properties/AssemblyInfo.cs | C# | mpl-2.0 | 1,432 |
(function(global, _) {
var Dataset = global.Miso.Dataset;
Dataset.typeOf = function(value, options) {
var types = _.keys(Dataset.types),
chosenType;
//move string and mixed to the end
types.push(types.splice(_.indexOf(types, 'string'), 1)[0]);
types.push(types.splice(_.indexOf(types, 'mixed'), 1)[0]);
chosenType = _.find(types, function(type) {
return Dataset.types[type].test(value, options);
});
chosenType = _.isUndefined(chosenType) ? 'string' : chosenType;
return chosenType;
};
Dataset.types = {
mixed : {
name : 'mixed',
coerce : function(v) {
if (_.isNull(v) || typeof v === "undefined" || _.isNaN(v)) {
return null;
}
return v;
},
test : function() {
return true;
},
compare : function(s1, s2) {
if ( _.isEqual(s1, s2) ) { return 0; }
if (s1 < s2) { return -1;}
if (s1 > s2) { return 1; }
},
numeric : function(v) {
return v === null || _.isNaN(+v) ? null : +v;
}
},
string : {
name : "string",
coerce : function(v) {
if (_.isNaN(v) || v === null || typeof v === "undefined") {
return null;
}
return v.toString();
},
test : function(v) {
return (v === null || typeof v === "undefined" || typeof v === 'string');
},
compare : function(s1, s2) {
if (s1 == null && s2 != null) { return -1; }
if (s1 != null && s2 == null) { return 1; }
if (s1 < s2) { return -1; }
if (s1 > s2) { return 1; }
return 0;
},
numeric : function(value) {
if (_.isNaN(+value) || value === null) {
return null;
} else if (_.isNumber(+value)) {
return +value;
} else {
return null;
}
}
},
"boolean" : {
name : "boolean",
regexp : /^(true|false)$/,
coerce : function(v) {
if (_.isNaN(v) || v === null || typeof v === "undefined") {
return null;
}
if (v === 'false') { return false; }
return Boolean(v);
},
test : function(v) {
if (v === null || typeof v === "undefined" || typeof v === 'boolean' || this.regexp.test( v ) ) {
return true;
} else {
return false;
}
},
compare : function(n1, n2) {
if (n1 == null && n2 != null) { return -1; }
if (n1 != null && n2 == null) { return 1; }
if (n1 == null && n2 == null) { return 0; }
if (n1 === n2) { return 0; }
return (n1 < n2 ? -1 : 1);
},
numeric : function(value) {
if (value === null || _.isNaN(value)) {
return null;
} else {
return (value) ? 1 : 0;
}
}
},
number : {
name : "number",
regexp : /^\s*[\-\.]?[0-9]+([\.][0-9]+)?\s*$/,
coerce : function(v) {
var cv = +v;
if (_.isNull(v) || typeof v === "undefined" || _.isNaN(cv)) {
return null;
}
return cv;
},
test : function(v) {
if (v === null || typeof v === "undefined" || typeof v === 'number' || this.regexp.test( v ) ) {
return true;
} else {
return false;
}
},
compare : function(n1, n2) {
if (n1 == null && n2 != null) { return -1; }
if (n1 != null && n2 == null) { return 1; }
if (n1 == null && n2 == null) { return 0; }
if (n1 === n2) { return 0; }
return (n1 < n2 ? -1 : 1);
},
numeric : function(value) {
if (_.isNaN(value) || value === null) {
return null;
}
return value;
}
},
time : {
name : "time",
format : "DD/MM/YYYY",
_formatLookup : [
['DD', "\\d{2}"],
['D' , "\\d{1}|\\d{2}"],
['MM', "\\d{2}"],
['M' , "\\d{1}|\\d{2}"],
['YYYY', "\\d{4}"],
['YY', "\\d{2}"],
['A', "[AM|PM]"],
['hh', "\\d{2}"],
['h', "\\d{1}|\\d{2}"],
['mm', "\\d{2}"],
['m', "\\d{1}|\\d{2}"],
['ss', "\\d{2}"],
['s', "\\d{1}|\\d{2}"],
['ZZ',"[-|+]\\d{4}"],
['Z', "[-|+]\\d{2}:\\d{2}"]
],
_regexpTable : {},
_regexp: function(format) {
//memoise
if (this._regexpTable[format]) {
return new RegExp(this._regexpTable[format], 'g');
}
//build the regexp for substitutions
var regexp = format;
_.each(this._formatLookup, function(pair) {
regexp = regexp.replace(pair[0], pair[1]);
}, this);
// escape all forward slashes
regexp = regexp.split("/").join("\\/");
// save the string of the regexp, NOT the regexp itself.
// For some reason, this resulted in inconsistant behavior
this._regexpTable[format] = regexp;
return new RegExp(this._regexpTable[format], 'g');
},
coerce : function(v, options) {
options = options || {};
if (_.isNull(v) || typeof v === "undefined" || _.isNaN(v)) {
return null;
}
// if string, then parse as a time
if (_.isString(v)) {
var format = options.format || this.format;
return moment(v, format);
} else if (_.isNumber(v)) {
return moment(v);
} else {
return v;
}
},
test : function(v, options) {
options = options || {};
if (v === null || typeof v === "undefined") {
return true;
}
if (_.isString(v) ) {
var format = options.format || this.format,
regex = this._regexp(format);
return regex.test(v);
} else {
//any number or moment obj basically
return true;
}
},
compare : function(d1, d2) {
if (d1 < d2) {return -1;}
if (d1 > d2) {return 1;}
return 0;
},
numeric : function( value ) {
if (_.isNaN(value) || value === null) {
return null;
}
return value.valueOf();
}
}
};
}(this, _));
| bwinton/d3Experiments | bower_components/miso.dataset/src/types.js | JavaScript | mpl-2.0 | 6,215 |
using System;
using System.Collections.Concurrent;
using System.Numerics;
using MiNET.Net;
using MiNET.Utils;
namespace MiNET.Worlds
{
internal class ExperimentalWorldProvider : IWorldProvider
{
public ExperimentalWorldProvider()
{
IsCaching = true;
}
private readonly ConcurrentDictionary<ChunkCoordinates, ChunkColumn> _chunkCache = new ConcurrentDictionary<ChunkCoordinates, ChunkColumn>();
public bool IsCaching { get; private set; }
public void Initialize()
{
}
public ChunkColumn GenerateChunkColumn(ChunkCoordinates chunkCoordinates)
{
ChunkColumn cachedChunk;
if (_chunkCache.TryGetValue(chunkCoordinates, out cachedChunk)) return cachedChunk;
ChunkColumn chunk = new ChunkColumn();
chunk.x = chunkCoordinates.X;
chunk.z = chunkCoordinates.Z;
PopulateChunk(chunk);
_chunkCache[chunkCoordinates] = chunk;
return chunk;
}
public Vector3 GetSpawnPoint()
{
return new Vector3(50, 10, 50);
}
public long GetTime()
{
return 0;
}
public int SaveChunks()
{
return 0;
}
private float stoneBaseHeight = 0;
private float stoneBaseNoise = 0.05f;
private float stoneBaseNoiseHeight = 4;
private float stoneMountainHeight = 48;
private float stoneMountainFrequency = 0.008f;
private float stoneMinHeight = 0;
private float dirtBaseHeight = 1;
private float dirtNoise = 0.004f;
private float dirtNoiseHeight = 3;
private int waterLevel = 25;
private void PopulateChunk(ChunkColumn chunk)
{
int trees = new Random().Next(0, 10);
int[,] treeBasePositions = new int[trees, 2];
for (int t = 0; t < trees; t++)
{
int x = new Random().Next(1, 16);
int z = new Random().Next(1, 16);
treeBasePositions[t, 0] = x;
treeBasePositions[t, 1] = z;
}
for (int x = 0; x < 16; x++)
{
for (int z = 0; z < 16; z++)
{
int stoneHeight = (int) Math.Floor(stoneBaseHeight);
stoneHeight += GetNoise(chunk.x*16 + x, chunk.z*16 + z, stoneMountainFrequency, (int) Math.Floor(stoneMountainHeight));
if (stoneHeight < stoneMinHeight)
stoneHeight = (int) Math.Floor(stoneMinHeight);
stoneHeight += GetNoise(chunk.x*16 + x, chunk.z*16 + z, stoneBaseNoise, (int) Math.Floor(stoneBaseNoiseHeight));
int dirtHeight = stoneHeight + (int) Math.Floor(dirtBaseHeight);
dirtHeight += GetNoise(chunk.x*16 + x, chunk.z*16 + z, dirtNoise, (int) Math.Floor(dirtNoiseHeight));
for (int y = 0; y < 256; y++)
{
//float y2 = Get3DNoise(chunk.X*16, y, chunk.Z*16, stoneBaseNoise, (int) Math.Floor(stoneBaseNoiseHeight));
if (y <= stoneHeight)
{
chunk.SetBlock(x, y, z, 1);
//Diamond ore
if (GetRandomNumber(0, 2500) < 5)
{
chunk.SetBlock(x, y, z, 56);
}
//Coal Ore
if (GetRandomNumber(0, 1500) < 50)
{
chunk.SetBlock(x, y, z, 16);
}
//Iron Ore
if (GetRandomNumber(0, 2500) < 30)
{
chunk.SetBlock(x, y, z, 15);
}
//Gold Ore
if (GetRandomNumber(0, 2500) < 20)
{
chunk.SetBlock(x, y, z, 14);
}
}
if (y < waterLevel) //FlowingWater :)
{
if (chunk.GetBlock(x, y, z) == 2 || chunk.GetBlock(x, y, z) == 3) //Grass or Dirt?
{
if (GetRandomNumber(1, 40) == 5 && y < waterLevel - 4)
chunk.SetBlock(x, y, z, 82); //Clay
else
chunk.SetBlock(x, y, z, 12); //Sand
}
if (y < waterLevel - 3)
chunk.SetBlock(x, y + 1, z, 8); //FlowingWater
}
if (y <= dirtHeight && y >= stoneHeight)
{
chunk.SetBlock(x, y, z, 3); //Dirt
chunk.SetBlock(x, y + 1, z, 2); //Grass Block
if (y > waterLevel)
{
//Grass
if (GetRandomNumber(0, 5) == 2)
{
chunk.SetBlock(x, y + 2, z, 31);
chunk.SetMetadata(x, y + 2, z, 1);
}
//flower
if (GetRandomNumber(0, 65) == 8)
{
int meta = GetRandomNumber(0, 8);
chunk.SetBlock(x, y + 2, z, 38);
chunk.SetMetadata(x, y + 2, z, (byte) meta);
}
for (int pos = 0; pos < trees; pos++)
{
if (treeBasePositions[pos, 0] < 14 && treeBasePositions[pos, 0] > 4 && treeBasePositions[pos, 1] < 14 &&
treeBasePositions[pos, 1] > 4)
{
if (y < waterLevel + 2)
break;
if (chunk.GetBlock(treeBasePositions[pos, 0], y + 1, treeBasePositions[pos, 1]) == 2)
{
if (y == dirtHeight)
GenerateTree(chunk, treeBasePositions[pos, 0], y + 1, treeBasePositions[pos, 1]);
}
}
}
}
}
if (y == 0)
{
chunk.SetBlock(x, y, z, 7);
}
}
}
}
}
private void GenerateTree(ChunkColumn chunk, int x, int treebase, int z)
{
int treeheight = GetRandomNumber(4, 5);
chunk.SetBlock(x, treebase + treeheight + 2, z, 18); //Top leave
chunk.SetBlock(x, treebase + treeheight + 1, z + 1, 18);
chunk.SetBlock(x, treebase + treeheight + 1, z - 1, 18);
chunk.SetBlock(x + 1, treebase + treeheight + 1, z, 18);
chunk.SetBlock(x - 1, treebase + treeheight + 1, z, 18);
chunk.SetBlock(x, treebase + treeheight, z + 1, 18);
chunk.SetBlock(x, treebase + treeheight, z - 1, 18);
chunk.SetBlock(x + 1, treebase + treeheight, z, 18);
chunk.SetBlock(x - 1, treebase + treeheight, z, 18);
chunk.SetBlock(x + 1, treebase + treeheight, z + 1, 18);
chunk.SetBlock(x - 1, treebase + treeheight, z - 1, 18);
chunk.SetBlock(x + 1, treebase + treeheight, z - 1, 18);
chunk.SetBlock(x - 1, treebase + treeheight, z + 1, 18);
for (int i = 0; i <= treeheight; i++)
{
chunk.SetBlock(x, treebase + i, z, 17);
}
}
private static readonly Random getrandom = new Random();
private static readonly object syncLock = new object();
private static int GetRandomNumber(int min, int max)
{
lock (syncLock)
{
// synchronize
return getrandom.Next(min, max);
}
}
private static readonly OpenSimplexNoise OpenNoise = new OpenSimplexNoise("a-seed".GetHashCode());
public static int GetNoise(int x, int z, float scale, int max)
{
return (int) Math.Floor((OpenNoise.Evaluate(x*scale, z*scale) + 1f)*(max/2f));
}
}
} | MiPE-JP/RaNET | src/MiNET/MiNET/Worlds/ExperimentalWorldProvider.cs | C# | mpl-2.0 | 6,304 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("04.CalcSurfaceOfTriangle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04.CalcSurfaceOfTriangle")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1777a19c-d2df-40f9-a162-d115725ccdea")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| emilVenkov12/TelerikCourses | Programing/02.CSharpPart2Winter2013-2014/05.Using-Classes-and-Objects/05.Using-Classes-and-ObjectsHW/04.CalcSurfaceOfTriangle/Properties/AssemblyInfo.cs | C# | mpl-2.0 | 1,424 |
from Tkinter import *
class Interface:
def __init__(self, contenedor):
self.textoE3 = StringVar()
self.e1 = Label(contenedor, text = "Convertir Celsius a Farenheit", fg = "black")
self.e2 = Label(contenedor, text = "Celsius", fg = "black")
self.e3 = Label(contenedor, text = "Farenheit", fg = "black")
self.e4 = Button(contenedor, text = "Convertir", fg = "black", bg = "cyan", command=self.hacerConversion)
self.e5 = Entry(contenedor, fg = "black", bg = "white")
self.e6 = Label(contenedor, text ="", fg = "black", textvariable=self.textoE3)
self.e1.grid(column=0,row=0,columnspan=2)
self.e2.grid(column=0,row=1)
self.e3.grid(column=0,row=2)
self.e4.grid(column=1,row=3,columnspan=2)
self.e5.grid(column=1,row=1)
self.e6.grid(column=1,row=2)
def hacerConversion(self):
cel = float(self.e5.get())
far = (cel*1.8)+32
self.textoE3.set(far)
ventana = Tk()
miInterface = Interface(ventana)
ventana.mainloop()
| heliogabalo/The-side-of-the-source | Codigo/Python/ventana5.py | Python | mpl-2.0 | 1,053 |
from __future__ import unicode_literals
import pytest
from django.core.exceptions import MiddlewareNotUsed
from django.http import HttpResponse
from django.test import RequestFactory
from mock import MagicMock, patch
from ..middleware import (
ForceAnonymousSessionMiddleware,
RestrictedEndpointsMiddleware,
RestrictedWhiteNoiseMiddleware,
SetRemoteAddrFromForwardedFor,
WaffleWithCookieDomainMiddleware,
WhiteNoiseMiddleware,
)
@pytest.mark.parametrize('path', ('/missing_url', '/missing_url/'))
def test_slash_middleware_keep_404(client, db, path):
'''The SlashMiddleware retains 404s.'''
response = client.get(path)
assert response.status_code == 404
def test_slash_middleware_removes_slash(client, db):
'''The SlashMiddleware fixes a URL that shouldn't have a trailing slash.'''
response = client.get('/contribute.json/')
assert response.status_code == 301
assert response['Location'].endswith('/contribute.json')
@pytest.mark.parametrize('path', ('/admin', '/en-US'))
def test_slash_middleware_adds_slash(path, client, db):
'''The SlashMiddleware fixes a URL that should have a trailing slash.'''
response = client.get(path)
assert response.status_code == 301
assert response['Location'].endswith(path + '/')
def test_slash_middleware_retains_querystring(client, db):
'''The SlashMiddleware handles encoded querystrings.'''
response = client.get('/contribute.json/?xxx=%C3%83')
assert response.status_code == 301
assert response['Location'].endswith('/contribute.json?xxx=%C3%83')
@pytest.mark.parametrize(
'forwarded_for,remote_addr',
(('1.1.1.1', '1.1.1.1'),
('2.2.2.2', '2.2.2.2'),
('3.3.3.3, 4.4.4.4', '3.3.3.3')))
def test_set_remote_addr_from_forwarded_for(rf, forwarded_for, remote_addr):
'''SetRemoteAddrFromForwardedFor parses the X-Forwarded-For Header.'''
rf = RequestFactory()
middleware = SetRemoteAddrFromForwardedFor(lambda req: None)
request = rf.get('/', HTTP_X_FORWARDED_FOR=forwarded_for)
middleware(request)
assert request.META['REMOTE_ADDR'] == remote_addr
def test_force_anonymous_session_middleware(rf, settings):
request = rf.get('/foo')
request.COOKIES[settings.SESSION_COOKIE_NAME] = 'totallyfake'
mock_response = MagicMock()
middleware = ForceAnonymousSessionMiddleware(lambda req: mock_response)
response = middleware(request)
assert request.session
assert request.session.session_key is None
assert not response.method_calls
@pytest.mark.parametrize(
'host,key,expected',
(('beta', 'BETA_HOST', 'kuma.urls_beta'),
('beta-origin', 'BETA_ORIGIN', 'kuma.urls_beta'),
('demos', 'ATTACHMENT_HOST', 'kuma.urls_untrusted'),
('demos-origin', 'ATTACHMENT_ORIGIN', 'kuma.urls_untrusted')),
ids=('beta', 'beta-origin', 'attachment', 'attachment-origin')
)
def test_restricted_endpoints_middleware(rf, settings, host, key, expected):
setattr(settings, key, host)
settings.ENABLE_RESTRICTIONS_BY_HOST = True
settings.ALLOWED_HOSTS.append(host)
middleware = RestrictedEndpointsMiddleware(lambda req: None)
request = rf.get('/foo', HTTP_HOST=host)
middleware(request)
assert request.urlconf == expected
request = rf.get('/foo', HTTP_HOST='testserver')
middleware(request)
assert not hasattr(request, 'urlconf')
def test_restricted_endpoints_middleware_when_disabled(settings):
settings.ENABLE_RESTRICTIONS_BY_HOST = False
with pytest.raises(MiddlewareNotUsed):
RestrictedEndpointsMiddleware(lambda req: None)
def test_restricted_whitenoise_middleware(rf, settings):
settings.ATTACHMENT_HOST = 'demos'
settings.ENABLE_RESTRICTIONS_BY_HOST = True
settings.ALLOWED_HOSTS.append('demos')
middleware = RestrictedWhiteNoiseMiddleware(lambda req: None)
sentinel = object()
with patch.object(WhiteNoiseMiddleware, 'process_request',
return_value=sentinel):
request = rf.get('/foo', HTTP_HOST='demos')
assert middleware(request) is None
request = rf.get('/foo', HTTP_HOST='testserver')
assert middleware(request) is sentinel
settings.ENABLE_RESTRICTIONS_BY_HOST = False
request = rf.get('/foo', HTTP_HOST='demos')
assert middleware(request) is sentinel
def test_waffle_cookie_domain_middleware(rf, settings):
settings.WAFFLE_COOKIE = 'dwf_%s'
settings.WAFFLE_COOKIE_DOMAIN = 'mdn.dev'
resp = HttpResponse()
resp.set_cookie('some_key', 'some_value', domain=None)
resp.set_cookie('another_key', 'another_value', domain='another.domain')
middleware = WaffleWithCookieDomainMiddleware(lambda req: resp)
request = rf.get('/foo')
request.waffles = {
'contrib_beta': (True, False),
'developer_needs': (True, False),
}
response = middleware(request)
assert response.cookies['some_key']['domain'] == ''
assert response.cookies['another_key']['domain'] == 'another.domain'
assert response.cookies['dwf_contrib_beta']['domain'] == 'mdn.dev'
assert response.cookies['dwf_developer_needs']['domain'] == 'mdn.dev'
| SphinxKnight/kuma | kuma/core/tests/test_middleware.py | Python | mpl-2.0 | 5,154 |
package com.servinglynk.hmis.warehouse.core.model;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.servinglynk.hmis.warehouse.PaginatedModel;
@JsonRootName("trustedApps")
public class TrustedApps extends PaginatedModel {
@JsonProperty("trustedApp")
private List<TrustedApp> trustedApps;
public List<TrustedApp> getTrustedApps() {
return trustedApps;
}
public void setTrustedApps(List<TrustedApp> trustedApps) {
this.trustedApps = trustedApps;
}
public void addTrustedApp(TrustedApp trustedApp) {
if(this.trustedApps==null) trustedApps = new ArrayList<TrustedApp>();
this.trustedApps.add(trustedApp);
}
}
| servinglynk/servinglynk-hmis | base-serialize/src/main/java/com/servinglynk/hmis/warehouse/core/model/TrustedApps.java | Java | mpl-2.0 | 754 |
#include "demod_iq_time_plot.h"
DemodIQTimePlot::DemodIQTimePlot(Session *session, QWidget *parent) :
GLSubView(session, parent),
textFont(14),
divFont(12),
traceVBO(0),
yScale(0.0)
{
makeCurrent();
glShadeModel(GL_SMOOTH);
glClearDepth(1.0);
glDepthFunc(GL_LEQUAL);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
context()->format().setDoubleBuffer(true);
glGenBuffers(1, &traceVBO);
doneCurrent();
}
DemodIQTimePlot::~DemodIQTimePlot()
{
makeCurrent();
glDeleteBuffers(1, &traceVBO);
doneCurrent();
}
void DemodIQTimePlot::resizeEvent(QResizeEvent *)
{
SetGraticuleDimensions(QPoint(60, 50),
QPoint(width() - 80, height() - 100));
}
void DemodIQTimePlot::paintEvent(QPaintEvent *)
{
makeCurrent();
glQClearColor(GetSession()->colors.background);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glViewport(0, 0, width(), height());
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(grat_sz.x() >= 600) {
textFont = GLFont(14);
} else if(grat_sz.x() <= 350) {
textFont = GLFont(8);
} else {
int mod = (600 - grat_sz.x()) / 50;
textFont = GLFont(13 - mod);
}
int textHeight = textFont.GetTextHeight() + 2;
SetGraticuleDimensions(QPoint(60, textHeight*2),
QPoint(width() - 80, height() - textHeight*4));
DrawGraticule();
DrawIQLines();
glDisable(GL_DEPTH_TEST);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, width(), 0, height(), -1, 1);
glPushAttrib(GL_ALL_ATTRIB_BITS);
QPainter p(this);
p.setRenderHint(QPainter::TextAntialiasing);
p.setRenderHint(QPainter::Antialiasing);
p.translate(0.0, height());
p.setPen(QPen(GetSession()->colors.text));
p.setFont(textFont.Font());
DrawPlotText(p);
p.end();
glPopAttrib();
doneCurrent();
swapBuffers();
}
void DemodIQTimePlot::DrawIQLines()
{
traces[0].clear();
traces[1].clear();
const IQSweep &sweep = GetSession()->iq_capture;
const std::vector<complex_f> &iq = sweep.iq;
if(sweep.sweepLen <= 4) return;
if(sweep.iq.size() <= 4) return;
glColor3f(1.0, 0.0, 0.0);
for(int i = 0; i < sweep.sweepLen; i++) {
traces[0].push_back(i);
traces[0].push_back(iq[i].re);
traces[1].push_back(i);
traces[1].push_back(iq[i].im);
}
float max = 0.0;
for(int i = 0; i < sweep.sweepLen; i++) {
max = bb_lib::max2(max, iq[i].re);
max = bb_lib::max2(max, iq[i].im);
}
yScale = bb_lib::next_multiple_of(0.05, max);
if(yScale - max < 0.01) yScale += 0.1;
if(yScale > 1.5) yScale = 0.75;
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(grat_ll.x(), grat_ll.y(), grat_sz.x(), grat_sz.y());
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
//glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
//glLoadIdentity();
glOrtho(0, sweep.sweepLen - 1, -yScale, yScale, -1, 1);
// Nice lines
glEnable(GL_BLEND);
glEnable(GL_LINE_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBlendEquation(GL_FUNC_ADD);
glLineWidth(GetSession()->prefs.trace_width);
qglColor(QColor(255, 0, 0));
DrawTrace(traces[0]);
qglColor(QColor(0, 255, 0));
DrawTrace(traces[1]);
// Disable nice lines
glLineWidth(1.0);
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
}
void DemodIQTimePlot::DrawTrace(const GLVector &v)
{
if(v.size() <= 4) {
return;
}
// Put the trace in the vbo
glBindBuffer(GL_ARRAY_BUFFER, traceVBO);
glBufferData(GL_ARRAY_BUFFER, v.size()*sizeof(float),
&v[0], GL_DYNAMIC_DRAW);
glVertexPointer(2, GL_FLOAT, 0, INDEX_OFFSET(0));
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawArrays(GL_LINE_STRIP, 0, v.size() / 2);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// Unbind array
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void DemodIQTimePlot::DrawPlotText(QPainter &p)
{
int ascent = textFont.FontMetrics().ascent();
int textHeight = textFont.GetTextHeight();
const IQSweep &sweep = GetSession()->iq_capture;
const DemodSettings *ds = GetSession()->demod_settings;
QString str;
p.beginNativePainting();
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0, 0, width(), height());
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, width(), 0, height(), -1, 1);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_QUADS);
glVertex2i(grat_ul.x() + 5, grat_ul.y() + 2);
glVertex2i(grat_ul.x() + 5 + ascent, grat_ul.y() + 2);
glVertex2i(grat_ul.x() + 5 + ascent, grat_ul.y() + 2 + ascent);
glVertex2i(grat_ul.x() + 5, grat_ul.y() + 2 + ascent);
glVertex2i(grat_ul.x() + 5, grat_ul.y() + 2);
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_QUADS);
glVertex2i(grat_ul.x() + 45, grat_ul.y() + 2);
glVertex2i(grat_ul.x() + 45 + ascent, grat_ul.y() + 2);
glVertex2i(grat_ul.x() + 45 + ascent, grat_ul.y() + 2 + ascent);
glVertex2i(grat_ul.x() + 45, grat_ul.y() + 2 + ascent);
glVertex2i(grat_ul.x() + 45, grat_ul.y() + 2);
glEnd();
glQColor(GetSession()->colors.text);
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glPopAttrib();
p.endNativePainting();
DrawString(p, "I", QPoint(grat_ul.x() + 25, grat_ul.y() + 2), LEFT_ALIGNED);
DrawString(p, "Q", QPoint(grat_ul.x() + 65, grat_ul.y() + 2), LEFT_ALIGNED);
str = "IF Bandwidth " + Frequency(sweep.descriptor.bandwidth).GetFreqString(3, true);
DrawString(p, str, QPoint(grat_ll.x() + 5, grat_ll.y() - textHeight), LEFT_ALIGNED);
str = "Capture Len " + ds->SweepTime().GetString();
DrawString(p, str, QPoint(grat_ll.x() + grat_sz.x() - 5, grat_ll.y() - textHeight), RIGHT_ALIGNED);
str = "Sample Rate " + getSampleRateString(sweep.descriptor.sampleRate);
DrawString(p, str, QPoint(grat_ll.x() + grat_sz.x() - 5, grat_ul.y() + 2), RIGHT_ALIGNED);
p.setFont(divFont.Font());
for(int i = 0; i <= 10; i++) {
int x_loc = grat_ul.x() - 2,
y_loc = grat_ul.y() - (i * grat_sz.y()/10.0) - 5;
str.sprintf("%.2f", yScale - (i * yScale/5.0));
DrawString(p, str, x_loc, y_loc, RIGHT_ALIGNED);
}
}
| SignalHound/BBApp | BBApp/src/views/demod_iq_time_plot.cpp | C++ | mpl-2.0 | 6,891 |
<?php
/**
* Class CRM_Mosaico_AbDemux
*
* Mosaico mailings may use an optional field, `$mailing['template_options']['variants']`
* to specify that multiple variants of the message will be sent as A/B tests.
*
* $mailing = [
* 'subject' => '',
* 'body_html' => '<p>Hello world</p>',
* 'template_options' => [
* 'variants' => [
* 0 => ['subject' => 'Greetings!']
* 1 => ['subject' => 'Greetings from the other side!']
* ]
* ]
* ]
*
* This listener modifies the behavior of `Mailing.submit` - if the `variants`
* are specified, then:
* - Split the mailing into three mailings (experiments A+B plus anticipated winner C).
* - The A+B mailings are identical, except for the variant fields.
* - Put the mailings in an A/B test
* - Submit the A/B experiment for testing.
*
* Otherwise, defer to the normal Mailing.submit API.
*/
class CRM_Mosaico_AbDemux {
const DEFAULT_AB_PERCENTAGE = 10;
protected $mandatory = [
'open_tracking' => 1,
'url_tracking' => 1,
];
const DEFAULT_WINNING_TIME = '+2 days';
/**
* List of properties that may be overriden in variants.
* To apply consistently, properties should be equally valid for Mailing DAO and Mailing API.
*
* @var array
*/
protected $variantFields = [
'subject',
'body_html',
'body_text',
'from_name',
'from_email',
'replyto_email',
'header_id',
'footer_id',
'reply_id',
'unsubscribe_id',
'resubscribe_id',
'optout_id',
];
/**
* Handle the Mailing.send_test API.
*
* If there are `template_options.variants`, then we send all the variants
* to the intended recipient.
*
* @param array $apiRequest
* The submitted API request.
* @param callable $continue
* The original/upstream implementation of Mailing.send_test API.
* @return array
* @throws \API_Exception
*/
public function onSendTestMailing($apiRequest, $continue) {
if (empty($apiRequest['params']['mailing_id'])) {
// Let upstream handle the error.
return $continue($apiRequest);
}
$id = $apiRequest['params']['mailing_id'];
$api3 = $this->makeApi3($apiRequest);
$mailing = $api3('Mailing', 'getsingle', ['id' => $id]);
if (empty($mailing['template_options']['variants'])) {
// Not one of ours!
return $continue($apiRequest);
}
$allResults = [];
foreach ($mailing['template_options']['variants'] as $variant) {
$applyVariant = function(\Civi\FlexMailer\Event\ComposeBatchEvent $e) use ($id, $variant) {
if ($e->getMailing()->id == $id) {
$this->applyVariant($e->getMailing(), $variant);
}
};
Civi::dispatcher()->addListener('civi.flexmailer.compose', $applyVariant, \Civi\FlexMailer\FlexMailer::WEIGHT_START);
try {
$result = $continue($apiRequest);
$allResults = $allResults + $result['values'];
}
finally {
Civi::dispatcher()->removeListener('civi.flexmailer.compose', $applyVariant);
}
}
return civicrm_api3_create_success($allResults);
}
/**
* Handle the Mailing.submit API.
*
* @param array $apiRequest
* The submitted API request.
* @param callable $continue
* The original/upstream implementation of Mailing.submit API.
* @return array
* @throws \API_Exception
*/
public function onSubmitMailing($apiRequest, $continue) {
civicrm_api3_verify_mandatory($apiRequest['params'], 'CRM_Mailing_DAO_Mailing', array('id'));
if (!isset($apiRequest['params']['scheduled_date']) && !isset($apiRequest['params']['approval_date'])) {
throw new API_Exception("Missing parameter scheduled_date and/or approval_date");
}
$api3 = $this->makeApi3($apiRequest);
// Ensure that mailings A, B, C exist. Lookup $variants spec.
$a = $api3('Mailing', 'getsingle', ['id' => $apiRequest['params']['id']]);
if (empty($a['template_options']['variants'])) {
// Not one of ours!
return $continue($apiRequest);
}
$b = $api3('Mailing', 'clone', [
'id' => $a['id'],
'api.Mailing.create' => [
'groups' => ['include' => [], 'exclude' => []],
'mailings' => ['include' => [], 'exclude' => []],
],
]);
$c = $api3('Mailing', 'create', ['name' => $a['name'] . ' (C)']);
$variants = $a['template_options']['variants'];
// Specify the key content of mailings A, B, C.
self::update($api3, 'Mailing', $a['id'], function ($mailing) use ($variants) {
unset($mailing['template_options']['variants']);
$mailing['name'] .= ' (A)';
$mailing['mailing_type'] = 'experiment';
return $this->applyVariant($mailing, $this->mandatory + $variants[0]);
});
self::update($api3, 'Mailing', $b['id'], function ($mailing) use ($variants) {
unset($mailing['template_options']['variants']);
$mailing['name'] .= ' (B)';
$mailing['mailing_type'] = 'experiment';
return $this->applyVariant($mailing, $this->mandatory + $variants[1]);
});
self::update($api3, 'Mailing', $c['id'], function ($mailing) use ($variants) {
$mailing['mailing_type'] = 'winner';
return $mailing;
});
// Create and submit the full A/B test record.
$ab = $api3('MailingAB', 'create', [
'name' => $a['name'],
'status' => 'Draft',
'mailing_id_a' => $a['id'],
'mailing_id_b' => $b['id'],
'mailing_id_c' => $c['id'],
'testing_criteria' => 'full_email',
'group_percentage' => CRM_Utils_Array::value('variantsPct', $a['template_options'], self::DEFAULT_AB_PERCENTAGE),
'winner_criteria' => 'open',
'declare_winning_time' => self::DEFAULT_WINNING_TIME,
]);
$submitParams = CRM_Utils_Array::subset($apiRequest['params'], array(
'scheduled_date',
'approval_date',
'approval_note',
'approval_status_id',
));
$api3('MailingAB', 'submit', $submitParams + [
'id' => $ab['id'],
'status' => 'Testing',
]);
// We should still provide a return signature for the original Mailing.submit call.
$reloadA = $api3('Mailing', 'getsingle', [
'id' => $a['id'],
'return' => [
'scheduled_id',
'scheduled_date',
'approval_date',
'approval_note',
'approval_status_id',
],
]);
return civicrm_api3_create_success([
$a['id'] => $reloadA + [
'_mailing_ab' => $ab['values'][$ab['id']],
],
]);
}
public function update($api3, $entity, $id, $callback) {
$base = ['id' => $id];
$record = $api3($entity, 'getsingle', $base);
$record = $callback($record);
return $api3($entity, 'create', $base + $record);
}
/**
* Generate an API facade which makes requests using consistent
* security context.
*
* @param array $apiRequest
* The original API request
* @return \Closure
* An API entry function which works like "civicrm_api3()`
*/
protected function makeApi3($apiRequest) {
$check = ['check_permissions' => CRM_Utils_Array::value('check_permissions', $apiRequest['params'], FALSE)];
$api3 = function ($entity, $action, $params) use ($check) {
return civicrm_api3($entity, $action, $params + $check);
};
return $api3;
}
/**
* @param array|object $mailing
* @param array $variant
* @return array|object
* @throws \API_Exception
*/
protected function applyVariant(&$mailing, $variant) {
$overrides = array_intersect(array_keys($variant), $this->variantFields);
if (is_array($mailing)) {
foreach ($overrides as $override) {
$mailing[$override] = $variant[$override];
}
}
elseif (is_object($mailing)) {
foreach ($overrides as $override) {
$mailing->{$override} = $variant[$override];
}
}
else {
throw new API_Exception("Cannot apply variant - unrecognized mailing object");
}
return $mailing;
}
}
| veda-consulting/uk.co.vedaconsulting.mosaico | CRM/Mosaico/AbDemux.php | PHP | agpl-3.0 | 7,960 |
# coding: utf-8
"""
MIT License
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import workshop._.z_2a as workshop
import workshop.fr._ as _
from workshop.fr.turtle import *
def go():
workshop.main(None, _.DEFAULT_TITLE)
| epeios-q37/epeios | other/exercises/basics/workshop/fr/z_2a.py | Python | agpl-3.0 | 1,301 |
# frozen_string_literal: true
module Settings
class PicturesController < BaseController
before_action :authenticate_user!
before_action :set_account
before_action :set_picture
def destroy
if valid_picture
account_params = {
@picture => nil,
(@picture + '_remote_url') => nil,
}
msg = UpdateAccountService.new.call(@account, account_params) ? I18n.t('generic.changes_saved_msg') : nil
redirect_to settings_profile_path, notice: msg, status: 303
else
bad_request
end
end
private
def set_account
@account = current_account
end
def set_picture
@picture = params[:id]
end
def valid_picture
@picture == 'avatar' || @picture == 'header'
end
end
end
| rainyday/mastodon | app/controllers/settings/pictures_controller.rb | Ruby | agpl-3.0 | 797 |
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.keystore;
import javax.swing.text.html.HTML;
/**
* Utility class that stores html attributes as static String
*/
public final class AttributeStore {
/**
* Returned key when an attribute requested as evidence element is missing
*/
public static final String ABSENT_ATTRIBUTE_VALUE = "attribute-absent";
public static final String ARIA_HIDDEN_ATTR = "aria-hidden";
public static final String ALT_ATTR = HTML.Attribute.ALT.toString();
public static final String CLASS_ATTR = HTML.Attribute.CLASS.toString();
public static final String CODE_ATTR = HTML.Attribute.CODE.toString();
public static final String CONTENT_ATTR = HTML.Attribute.CONTENT.toString();
public static final String DATA_ATTR = HTML.Attribute.DATA.toString();
public static final String DIR_ATTR = HTML.Attribute.DIR.toString();;
public static final String DISABLED_ATTR = "disabled";
public static final String FOR_ATTR = "for";
public static final String HREF_ATTR = HTML.Attribute.HREF.toString();
public static final String ID_ATTR = HTML.Attribute.ID.toString();
public static final String LABEL_ATTR = "label";
public static final String LANG_ATTR = HTML.Attribute.LANG.toString();
public static final String LONGDESC_ATTR = "longdesc";
public static final String NAME_ATTR = HTML.Attribute.NAME.toString();
public static final String ONKEYPRESS_ATTR = "onkeypress";
public static final String ROLE_ATTR = "role";
public static final String SRC_ATTR = HTML.Attribute.SRC.toString();
public static final String SUMMARY_ATTR = "summary";
public static final String TABINDEX_ATTR = "tabindex";
public static final String TARGET_ATTR = HTML.Attribute.TARGET.toString();
public static final String TITLE_ATTR = HTML.Attribute.TITLE.toString();
public static final String TYPE_ATTR = "type";
public static final String ARIA_LABEL_ATTR = "aria-label";
public static final String ARIA_LABELLEDBY_ATTR = "aria-labelledby";
public static final String ARIA_DESCRIBEDBY_ATTR = "aria-describedby";
public static final String USEMAP_ATTR = HTML.Attribute.USEMAP.toString();
public static final String VALUE_ATTR = HTML.Attribute.VALUE.toString();
public static final String WIDTH_ATTR = HTML.Attribute.WIDTH.toString();
public static final String HEIGHT_ATTR = HTML.Attribute.HEIGHT.toString();
public static final String XML_LANG_ATTR = "xml:lang";
/* Value linked to an attribute */
public static final String PRESENTATION_VALUE = "presentation";
/**
* Private constructor. This class handles keys and must not be instantiated
*/
private AttributeStore() {
}
}
| Asqatasun/Asqatasun | rules/rules-commons/src/main/java/org/asqatasun/rules/keystore/AttributeStore.java | Java | agpl-3.0 | 3,602 |
# require 'procedo/procedure/parameter'
module Procedo
module Engine
# A set is a couple of data: reference parameter and its associated "real" data (products)
class Set
attr_reader :parameter
delegate :name, to: :parameter, prefix: true
delegate :map, :collect, :each, :size, :count, to: :parameters
def initialize(intervention, parameter, list = nil)
raise 'Invalid intervention' unless intervention.is_a?(Procedo::Engine::Intervention)
@intervention = intervention
raise 'Invalid parameter reference' unless parameter.is_a?(Procedo::Procedure::Parameter)
@parameter = parameter
@list = list || @intervention.parameters_of_name(@parameter.name)
end
def parameters
@list
end
def build(list = nil)
sub(list)
end
def first
sub([@list.first])
end
private
def sub(items)
self.class.new(@intervention, @parameter, items)
end
end
end
end
| ekylibre/ekylibre | lib/procedo/engine/set.rb | Ruby | agpl-3.0 | 1,021 |
module LaClasse
module Helpers
module Auth
def session
return env[:session] unless env[:session].nil?
session = nil
unless cookies[:LACLASSE_AUTH].nil?
RestClient::Request.execute( method: :get,
url: "#{ANNUAIRE[:url]}/sessions/#{cookies[:LACLASSE_AUTH]}" ) do |response, _request, result|
if result.is_a?( Net::HTTPSuccess )
session = JSON.parse( response )
# put the current user in the AUTH_USER for the HTTP request logger
env['AUTH_USER'] = session['user']
end
end
end
env[:session] = session unless session.nil?
session
end
def log_exception( exception )
puts "\"#{env['REQUEST_METHOD']} #{env['REQUEST_URI']}\". Exception catched.
Message: '#{exception}'. Stack: #{exception.backtrace}"
end
def logged?
!session.nil?
end
def login!( route )
protocol = SSL ? 'https' : 'http'
service = ''
if route.empty?
service = "#{protocol}://#{env['HTTP_HOST']}#{APP_PATH}"
else
route += "?#{env['QUERY_STRING']}" unless env['QUERY_STRING'].empty?
service = "#{protocol}://#{env['HTTP_HOST']}#{route}"
end
redirect '/sso/login?ticket=false&service=' + CGI.escape(service)
end
end
end
end
| laclasse-com/service-cahiertextes | lib/helpers/auth.rb | Ruby | agpl-3.0 | 1,419 |
#!/usr/bin/env php
<?php
/*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2008, 2009, StatusNet, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
$shortoptions = 'b:g:j:n:t:u:w:x:z:';
$longoptions = array(
'subscriptions=',
'groups=',
'joins=',
'notices=',
'tags=',
'users=',
'words=',
'prefix=',
'groupprefix'
);
$helptext = <<<END_OF_CREATESIM_HELP
Creates a lot of test users and notices to (loosely) simulate a real server.
-b --subscriptions Average subscriptions per user (default no. users/20)
-g --groups Number of groups (default 20)
-j --joins Number of groups per user (default 5)
-n --notices Average notices per user (default 100)
-t --tags Number of distinct hash tags (default 10000)
-u --users Number of users (default 100)
-w --words Words file (default '/usr/share/dict/words')
-x --prefix User name prefix (default 'testuser')
-z --groupprefix Group name prefix (default 'testgroup')
END_OF_CREATESIM_HELP;
require_once INSTALLDIR.'/scripts/commandline.inc';
// XXX: make these command-line options
function newUser($i)
{
global $userprefix;
$user = User::register(array('nickname' => sprintf('%s%d', $userprefix, $i),
'password' => sprintf('password%d', $i),
'fullname' => sprintf('Test User %d', $i)));
if (!empty($user)) {
$user->free();
}
}
function newGroup($i, $j)
{
global $groupprefix;
global $userprefix;
// Pick a random user to be the admin
$n = rand(0, max($j - 1, 0));
$user = User::staticGet('nickname', sprintf('%s%d', $userprefix, $n));
$group = User_group::register(array('nickname' => sprintf('%s%d', $groupprefix, $i),
'local' => true,
'userid' => $user->id,
'fullname' => sprintf('Test Group %d', $i)));
}
function newNotice($i, $tagmax)
{
global $userprefix;
$options = array('scope' => Notice::defaultScope());
$n = rand(0, $i - 1);
$user = User::staticGet('nickname', sprintf('%s%d', $userprefix, $n));
$is_reply = rand(0, 1);
$content = testNoticeContent();
if ($is_reply == 0) {
$stream = new InboxNoticeStream($user, $user->getProfile());
$notices = $stream->getNotices(0, 20);
if ($notices->N > 0) {
$nval = rand(0, $notices->N - 1);
$notices->fetch(); // go to 0th
for ($i = 0; $i < $nval; $i++) {
$notices->fetch();
}
$options['reply_to'] = $notices->id;
$dont_use_nickname = rand(0, 2);
if ($dont_use_nickname != 0) {
$rprofile = $notices->getProfile();
$content = "@".$rprofile->nickname." ".$content;
}
$private_to_addressees = rand(0, 4);
if ($private_to_addressees == 0) {
$options['scope'] |= Notice::ADDRESSEE_SCOPE;
}
}
}
$has_hash = rand(0, 2);
if ($has_hash == 0) {
$hashcount = rand(0, 2);
for ($j = 0; $j < $hashcount; $j++) {
$h = rand(0, $tagmax);
$content .= " #tag{$h}";
}
}
$in_group = rand(0, 5);
if ($in_group == 0) {
$groups = $user->getGroups();
if ($groups->N > 0) {
$gval = rand(0, $groups->N - 1);
$groups->fetch(); // go to 0th
for ($i = 0; $i < $gval; $i++) {
$groups->fetch();
}
$options['groups'] = array($groups->id);
$content = "!".$groups->nickname." ".$content;
$private_to_group = rand(0, 2);
if ($private_to_group == 0) {
$options['scope'] |= Notice::GROUP_SCOPE;
}
}
}
$private_to_site = rand(0, 4);
if ($private_to_site == 0) {
$options['scope'] |= Notice::SITE_SCOPE;
}
$notice = Notice::saveNew($user->id, $content, 'system', $options);
}
function newSub($i)
{
global $userprefix;
$f = rand(0, $i - 1);
$fromnick = sprintf('%s%d', $userprefix, $f);
$from = User::staticGet('nickname', $fromnick);
if (empty($from)) {
throw new Exception("Can't find user '$fromnick'.");
}
$t = rand(0, $i - 1);
if ($t == $f) {
$t++;
if ($t > $i - 1) {
$t = 0;
}
}
$tunic = sprintf('%s%d', $userprefix, $t);
$to = User::staticGet('nickname', $tunic);
if (empty($to)) {
throw new Exception("Can't find user '$tunic'.");
}
subs_subscribe_to($from, $to);
$from->free();
$to->free();
}
function newJoin($u, $g)
{
global $userprefix;
global $groupprefix;
$userNumber = rand(0, $u - 1);
$userNick = sprintf('%s%d', $userprefix, $userNumber);
$user = User::staticGet('nickname', $userNick);
if (empty($user)) {
throw new Exception("Can't find user '$fromnick'.");
}
$groupNumber = rand(0, $g - 1);
$groupNick = sprintf('%s%d', $groupprefix, $groupNumber);
$group = User_group::staticGet('nickname', $groupNick);
if (empty($group)) {
throw new Exception("Can't find group '$groupNick'.");
}
if (!$user->isMember($group)) {
$user->joinGroup($group);
}
}
function testNoticeContent()
{
global $words;
if (is_null($words)) {
return "test notice content";
}
$cnt = rand(3, 8);
$ids = array_rand($words, $cnt);
foreach ($ids as $id) {
$parts[] = $words[$id];
}
$text = implode(' ', $parts);
if (mb_strlen($text) > 80) {
$text = substr($text, 0, 77) . "...";
}
return $text;
}
function main($usercount, $groupcount, $noticeavg, $subsavg, $joinsavg, $tagmax)
{
global $config;
$config['site']['dupelimit'] = -1;
$n = 0;
$g = 0;
// Make users first
$preuser = min($usercount, 5);
for ($j = 0; $j < $preuser; $j++) {
printfv("$i Creating user $n\n");
newUser($n);
$n++;
}
$pregroup = min($groupcount, 3);
for ($k = 0; $k < $pregroup; $k++) {
printfv("$i Creating group $g\n");
newGroup($g, $n);
$g++;
}
// # registrations + # notices + # subs
$events = $usercount + $groupcount + ($usercount * ($noticeavg + $subsavg + $joinsavg));
$events -= $preuser;
$events -= $pregroup;
$ut = $usercount;
$gt = $ut + $groupcount;
$nt = $gt + ($usercount * $noticeavg);
$st = $nt + ($usercount * $subsavg);
$jt = $st + ($usercount * $joinsavg);
printfv("$events events ($ut, $gt, $nt, $st, $jt)\n");
for ($i = 0; $i < $events; $i++)
{
$e = rand(0, $events);
if ($e >= 0 && $e <= $ut) {
printfv("$i Creating user $n\n");
newUser($n);
$n++;
} else if ($e > $ut && $e <= $gt) {
printfv("$i Creating group $g\n");
newGroup($g, $n);
$g++;
} else if ($e > $gt && $e <= $nt) {
printfv("$i Making a new notice\n");
newNotice($n, $tagmax);
} else if ($e > $nt && $e <= $st) {
printfv("$i Making a new subscription\n");
newSub($n);
} else if ($e > $st && $e <= $jt) {
printfv("$i Making a new group join\n");
newJoin($n, $g);
} else {
printfv("No event for $i!");
}
}
}
$defaultWordsfile = '/usr/share/dict/words';
$usercount = (have_option('u', 'users')) ? get_option_value('u', 'users') : 100;
$groupcount = (have_option('g', 'groups')) ? get_option_value('g', 'groups') : 20;
$noticeavg = (have_option('n', 'notices')) ? get_option_value('n', 'notices') : 100;
$subsavg = (have_option('b', 'subscriptions')) ? get_option_value('b', 'subscriptions') : max($usercount/20, 10);
$joinsavg = (have_option('j', 'joins')) ? get_option_value('j', 'joins') : 5;
$tagmax = (have_option('t', 'tags')) ? get_option_value('t', 'tags') : 10000;
$userprefix = (have_option('x', 'prefix')) ? get_option_value('x', 'prefix') : 'testuser';
$groupprefix = (have_option('z', 'groupprefix')) ? get_option_value('z', 'groupprefix') : 'testgroup';
$wordsfile = (have_option('w', 'words')) ? get_option_value('w', 'words') : $defaultWordsfile;
if (is_readable($wordsfile)) {
$words = file($wordsfile);
} else {
if ($wordsfile != $defaultWordsfile) {
// user specified words file couldn't be read
throw new Exception("Couldn't read words file: {$wordsfile}.");
}
$words = null;
}
try {
main($usercount, $groupcount, $noticeavg, $subsavg, $joinsavg, $tagmax);
} catch (Exception $e) {
printfv("Got an exception: ".$e->getMessage());
}
| gayathri6/stepstream_salute | scripts/createsim.php | PHP | agpl-3.0 | 9,603 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.gl.batch;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.kuali.kfs.gl.GeneralLedgerConstants;
import org.kuali.kfs.gl.businessobject.OriginEntryFull;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.context.TestUtils;
import org.kuali.kfs.sys.dataaccess.UnitTestSqlDao;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.kfs.sys.suite.AnnotationTestSuite;
import org.kuali.kfs.sys.suite.IcrEncumbranceSuite;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
/**
* This class tests posting of ICR Encumbrance entries to the general ledger table.
*/
@ConfigureContext
@AnnotationTestSuite(IcrEncumbranceSuite.class)
public class PosterIcrEncumbranceEntriesStepTest extends IcrEncumbranceStepTestBase {
// Services
private IcrEncumbranceSortStep icrEncumbranceSortStep;
private PosterIcrEncumbranceEntriesStep posterIcrEncumbranceEntriesStep;
private UnitTestSqlDao unitTestSqlDao;
/**
* This method sets up the services used during testing.
*
* @see org.kuali.kfs.gl.batch.IcrEncumbranceStepTestBase#setUp()
*/
@Override
public void setUp() throws Exception {
super.setUp();
// Init services
this.icrEncumbranceSortStep = SpringContext.getBean(IcrEncumbranceSortStep.class);
this.icrEncumbranceSortStep.setParameterService(SpringContext.getBean(ParameterService.class));
this.posterIcrEncumbranceEntriesStep = SpringContext.getBean(PosterIcrEncumbranceEntriesStep.class);
this.posterIcrEncumbranceEntriesStep.setParameterService(SpringContext.getBean(ParameterService.class));
this.unitTestSqlDao = SpringContext.getBean(UnitTestSqlDao.class);
}
/*
* Populate a list of OriginEntryFull objects from the lines
* contained in a generated feed file.
*/
private List<OriginEntryFull> getOriginEntriesFromFile(File feedFile){
List<String> lines = getLinesFromFile(feedFile);
List<OriginEntryFull> entryList = new ArrayList<OriginEntryFull>();
int lineNumber = 1;
for(String line : lines){
OriginEntryFull entry = new OriginEntryFull();
entry.setFromTextFileForBatch(line, lineNumber);
entryList.add(entry);
lineNumber++;
}
return entryList;
}
/*
* Helper method to pull lines from a file and create one
* String for each line.
*/
private List<String> getLinesFromFile(File feedFile){
Reader feedReader = null;
List<String> lines = null;
try {
feedReader = new FileReader(feedFile);
lines = IOUtils.readLines(feedReader);
}catch (Exception e) {
throw new RuntimeException(e);
}finally{
IOUtils.closeQuietly(feedReader);
}
return lines;
}
/**
* This method tests the execute() mehthod of the PosterIcrEncumbranceEntriesStep.
*
* The sequence of steps for the ICR Encumbrance posting job is:
* 1.) icrEncumbranceFeedStep
* 2.) icrEncumbranceSortStep
* 3.) posterIcrEncumbranceEntriesStep <--- This is what we are testing, stop here
* 4.) fileRenameStep
*
* @see org.kuali.kfs.gl.batch.IcrEncumbranceStepTestBase#testExecute()
*/
@Override
public void testExecute() {
TestUtils.setSystemParameter(KfsParameterConstants.GENERAL_LEDGER_BATCH.class, GeneralLedgerConstants.USE_ICR_ENCUMBRANCE_PARAM, "Y");
// Generate a feed file, (see IcrEncumbranceFeedTest for full test coverage)
File feedFile = icrEncumbranceService.buildIcrEncumbranceFeed();
// Sort file contents (see IcrEncumbranceSortStepTest for full test coverage)
this.icrEncumbranceSortStep.execute("testIcrEncumbranceSortStep", dateTimeService.getCurrentDate());
// Ensure OriginEntryFull objects can be instantiated from the generated feed
// file, and capture how many entries were generated
int originEntryCount = getOriginEntriesFromFile(feedFile).size();
assertTrue("The feed file did not produce the expected number of origin entries.", originEntryCount > 0);
// Clear the general ledger table, then ensure no records are present,
// this means any new records are from our test posting them
unitTestSqlDao.sqlCommand("DELETE FROM GL_ENTRY_T");
int glEntryTableRowCount = unitTestSqlDao.sqlSelect("SELECT UNIV_FISCAL_PRD_CD FROM GL_ENTRY_T").size();
assertTrue("The GL_ENTRY_T should be empty.", glEntryTableRowCount == 0);
// Perform posting, this step is the consumer of the feed file contents
posterIcrEncumbranceEntriesStep.execute("testPosterIcrEncumbranceEntriesStep", dateTimeService.getCurrentDate());
// Ensure the general ledger table contains twice the number of records as origin entries from the feed file
glEntryTableRowCount = unitTestSqlDao.sqlSelect("SELECT UNIV_FISCAL_PRD_CD FROM GL_ENTRY_T").size();
int expectedCount = originEntryCount * 2;
String msg = String.format("The GL_ENTRY_T should have %d records but only has %d.", expectedCount, glEntryTableRowCount);
assertTrue(msg, glEntryTableRowCount == expectedCount);
}
}
| ua-eas/ua-kfs-5.3 | test/unit/src/org/kuali/kfs/gl/batch/PosterIcrEncumbranceEntriesStepTest.java | Java | agpl-3.0 | 6,463 |
<?Php
/**
* \class User
* \brief Handles the user's login and user.
*
*/
class User {
private $xmppSession;
private $username = '';
private $password = '';
private $config = array();
/**
* Class constructor. Reloads the user's session or attempts to authenticate
* the user.
* Note that the constructor is private. This class is a singleton.
*/
function __construct()
{
if($this->isLogged()) {
global $session;
$this->username = $session['user'].'@'.$session['host'];
$this->config = $session['config'];
}
}
/**
* Checks if the user has an open session.
*/
function isLogged()
{
// User is not logged in if both the session vars and the members are unset.
global $session;
return $session['on'];
}
function desauth()
{
PresenceHandler::clearPresence();
if($this->isLogged()) {
$p = new moxl\PresenceUnavaiable();
$p->request();
}
$sess = Session::start(APP_NAME);
Session::dispose(APP_NAME);
}
function setLang($language)
{
global $sdb;
$conf = $sdb->select('ConfVar', array('login' => $this->username));
$conf[0]->set('language', $language);
$sdb->save($conf[0]);
}
function getLogin()
{
return $this->username;
}
function getPass()
{
return $this->password;
}
function setConfig(array $config)
{
global $session;
$session['config'] = $config;
$sess = Session::start(APP_NAME);
$sess->set('session', $session);
}
function getConfig($key = false)
{
if($key == false)
return $this->config;
if(isset($this->config[$key]))
return $this->config[$key];
}
}
| seemenow/bbbbbbbb | system/User.php | PHP | agpl-3.0 | 1,770 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-Today INECO LTD,. PART. (<http://www.ineco.co.th>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import product
import wizard
import sale
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| jeffery9/mixprint_addons | ineco_sale_make_purchase/__init__.py | Python | agpl-3.0 | 1,105 |
/*
Copyright (C) 2017 by TecDevsIT(www.tecdevs.cf)
Application: Text2Speech
VERSION: 1.0
FILE: Text2Speech.cs
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/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Text2Speech
{
static class Text2Speech
{
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new main());
}
}
}
| TecDevsIT/Text2Speech | Text2Speech.cs | C# | agpl-3.0 | 1,224 |
/*
* Copyright 2010 OpenHealthData, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openhealthdata.validation.result;
import java.util.List;
/**
* Interface for a Managed Validation Result
* @author swaldren
*
*/
public interface ValidationResultManager {
/**
* Return the Validation Result that is being managed
*
* @return The managed validation result
*/
public ValidationResult getResult();
/**
* Set the Validation Result to be managed
*
* @param result The managed validation result
*/
public void setResult(ValidationResult result);
/**
* Set the name of the file being tested. This is needed for non-file
* based test objects (such as DOM, String, JAXBObject)
* @param filename
*/
public void setFileTested(String filename);
/**
* Returns the name of the file being tested. This does not need to be
* a URI or findable in the filesystem
* @return
*/
public String getFileTested();
/**
* A validation result may have multiple profiles to be tested against.
* Each profile will have a unique identifier to link test results back too.
* @param schemaName The name of the syntax schema (i.e. XSD) used
* @param schemaVersion The version of the syntax schema
* @param profileName A display name for the profile
* @param profileVersion The version of the profile
* @param profileID A unique identifer for this profile
*/
public void addValidationUsed(String schemaName, String schemaVersion, String profileName, String profileVersion, String profileID);
/**
* Add a profile to validation used
*
* @param profileName
* @param profileVersion
* @param profileID
*/
public void addProfile(String profileName, String profileVersion, String profileID);
/**
* Add a profile to validation used
* @param p
*/
public void addProfile(ValidationResult.ValidationUsed.Profile p);
/**
* Each test has a unique identifier. This method retrieves the test
* based on the supplied unique identifier
* @param uid The unique identifier for a test
* @return a found test or <code>null</code> if none found
*/
public TestResultType getTest(String uid);
/**
* Adds a rule to the list of rules to be used for testing.
* This is used to list all tested rules in the validation result
* @param id The unique identifier for the rule
* @param name The name of the rule
* @param title The title for the rule
* @param packge The package the rule resides in
* @param description A description of what the rule tests against
* @param profile The profile to which the rule belongs
*/
public void addRule(String id, String name, String title, String packge, String description,
String profile, String source, String author);
/**
* Added a test to the validation result
* @param test
*/
public void addTest(TestResultType test);
/**
* Creates and adds a test to the validation result
*
* @param testUID The unique identifier for the test
* @param name The display name for the test
* @param description A short description of the test
* @param status The status as an enum (see static final strings in <code>TestResultType</code>
* @return the created test
*/
public TestResultType addTest(String testUID, String name, String description, String status);
/**
* Creates and adds a test to the validation result
*
* @param testUID The unique identifier for the test
* @param name The display name for the test
* @param description A short description of the test
* @param status The status as an enum (see static final strings in <code>TestResultType</code>
* @param profiles the unique identifiers for profiles linked to the test
* @return
*/
public TestResultType addTest(String testUID, String name, String description, String status, List<String> profiles);
/**
* Creates and adds a test to the validation result. Should also check
* for existence of profile and add stub profile if not found
*
* @param testUID The unique identifier for the test
* @param name The display name for the test
* @param description A short description of the test
* @param status The status as an enum (see static final strings in <code>TestResultType</code>
* @param profile the unique identifier for profile linked to the test
* @return
*/
public TestResultType addTest(String testUID, String name, String description, String status, String profile);
/**
* Returns a list of tests based on their status
* @param status The status as an enum (see static final strings in <code>TestResultType</code>
* @return
*/
public List<TestResultType> getTestByStatus(String status);
/**
* Adds an error to a test as identified by the test unique identifier.
* It should create a stub test if no test found by unique identifier.
* @param testUID The unique identifier of the test
* @param message The error message
* @param serverity the serverity of the error as an enum (see static final string in <code>ErrorType</code>
* @param xpath An Xpath expression of the location of the error.
*/
public void addError(String testUID, String message, String serverity, String xpath);
/**
* Adds an error to a test as identified by the test unique identifier
* @param testUID the unique identifier of the test
* @param error the error to add
*/
public void addError(String testUID, ErrorType error);
/**
* Adds multiple errors to a test as identified by the test unique identifier
* @param testUID the unique identifier of the test
* @param error the list of errors to add
*/
public void addError(String testUID, List<ErrorType> error);
/**
* Adds an error to a test as identified by the test uniqu identifier.
* @param testUID the unique identifier of the test
* @param message the error message
* @param serverity the serverity of the error as an enum (see static final string in <code>ErrorType</code>
* @param lineNumber the line number in the file where the error was found
* @param columnNumber the column number in the line where the error was found
*/
public void addError(String testUID, String message, String serverity, int lineNumber, int columnNumber);
}
| openhealthdata/CCR-Validator | src/main/java/org/openhealthdata/validation/result/ValidationResultManager.java | Java | agpl-3.0 | 7,553 |
/*
* Flexisip, a flexible SIP proxy server with media capabilities.
* Copyright (C) 2018 Belledonne Communications SARL, All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <cstring>
#include <functional>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <sofia-sip/sip_header.h>
#include <flexisip/logmanager.hh>
#include "utils/string-utils.hh"
#include "external-auth-module.hh"
using namespace std;
namespace flexisip {
ExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, int nonceExpire, bool qopAuth) : FlexisipAuthModuleBase(root, domain, nonceExpire, qopAuth) {
mEngine = nth_engine_create(root, TAG_END());
}
ExternalAuthModule::~ExternalAuthModule() {
nth_engine_destroy(mEngine);
}
void ExternalAuthModule::checkAuthHeader(FlexisipAuthStatus &as, msg_auth_t *credentials,
auth_challenger_t const *ach) {
auto ctx = make_unique<HttpRequestCtx>(*this, as, *ach, *credentials);
pendingAuthRequests.push(move(ctx));
as.status(100);
if (!mWaitingForResponse) {
popAndSendRequest();
}
}
void ExternalAuthModule::popAndSendRequest() {
auto ctx = move(pendingAuthRequests.front());
pendingAuthRequests.pop();
try {
auto &externalAs = dynamic_cast<ExternalAuthModule::Status &>(ctx->as);
auto &credentials = ctx->creds;
HttpUriFormater::TranslationFunc func = [&externalAs, &credentials](const string &key) {
return extractParameter(externalAs, credentials, key);
};
string uri = mUriFormater.format(func);
nth_client_t *request = nth_client_tcreate(mEngine,
onHttpResponseCb,
reinterpret_cast<nth_client_magic_t*>(ctx.get()),
http_method_get,
"GET",
URL_STRING_MAKE(uri.c_str()),
TAG_END()
);
if (request == nullptr) {
ostringstream os;
os << "HTTP request for '" << uri << "' has failed";
throw runtime_error{os.str()};
}
// Request successfully sent. Give the ownership of HttpRequestCtx to the HTTP client
// and swtich to waiting state.
ctx.release();
mWaitingForResponse = true;
SLOGD << "HTTP request [" << request << "] to '" << uri << "' successfully sent";
} catch (const runtime_error &e) {
SLOGE << e.what();
onError(ctx->as);
notify(ctx->as);
}
}
void ExternalAuthModule::onHttpResponse(HttpRequestCtx &ctx, nth_client_t *request, const http_t *http) {
shared_ptr<RequestSipEvent> ev;
try {
int sipCode = 0;
string phrase;
string reasonHeaderValue;
string pAssertedIdentity;
ostringstream os;
if (http == nullptr) {
os << "HTTP server responds with code " << nth_client_status(request);
throw runtime_error(os.str());
}
auto status = http->http_status->st_status;
auto httpBody = toString(http->http_payload);
SLOGD << "HTTP response received [" << status << "]: " << endl << (!httpBody.empty() ? httpBody : "<empty>") ;
if (status != 200) {
os << "unhandled HTTP status code [" << status << "]";
throw runtime_error(os.str());
}
if (httpBody.empty()) {
os << "HTTP server answered with an empty body";
throw runtime_error(os.str());
}
try {
map<string, string> kv = parseHttpBody(httpBody);
sipCode = stoi(kv["Status"]);
phrase = move(kv["Phrase"]);
reasonHeaderValue = move(kv["Reason"]);
pAssertedIdentity = move(kv["P-Asserted-Identity"]);
} catch (const logic_error &e) {
os << "error while parsing HTTP body: " << e.what();
throw runtime_error(os.str());
}
if (!validSipCode(sipCode)) {
os << "invalid SIP code";
throw runtime_error(os.str());
}
auto &httpAuthStatus = dynamic_cast<ExternalAuthModule::Status &>(ctx.as);
httpAuthStatus.status(sipCode == 200 ? 0 : sipCode);
httpAuthStatus.phrase(su_strdup(ctx.as.home(), phrase.c_str()));
httpAuthStatus.reason(reasonHeaderValue);
httpAuthStatus.pAssertedIdentity(pAssertedIdentity);
if (sipCode == 401 || sipCode == 407) challenge(ctx.as, &ctx.ach);
} catch (const runtime_error &e) {
SLOGE << "HTTP request [" << request << "]: " << e.what();
onError(ctx.as);
} catch (...) {
if (request) nth_client_destroy(request);
throw;
}
notify(ctx.as);
if (request) nth_client_destroy(request);
}
std::map<std::string, std::string> ExternalAuthModule::parseHttpBody(const std::string &body) const {
istringstream is(body);
ostringstream os;
map<string, string> result;
string line;
do {
getline(is, line);
if (line.empty()) continue;
auto column = find(line.cbegin(), line.cend(), ':');
if (column == line.cend()) {
os << "invalid line '" << line << "': missing column symbol";
throw invalid_argument(os.str());
}
string &value = result[string(line.cbegin(), column)];
auto valueStart = find_if_not(column+1, line.cend(), [](const char &c){return isspace(c) != 0;});
if (valueStart == line.cend()) {
os << "invalid line '" << line << "': missing value";
throw invalid_argument(os.str());
}
value.assign(valueStart, line.cend());
} while (!is.eof());
return result;
}
std::string ExternalAuthModule::extractParameter(const Status &as, const msg_auth_t &credentials, const std::string ¶mName) {
if (paramName.compare(0, 7, "header:") == 0) {
string headerName(paramName, 7);
if (!headerName.empty()) {
char encodedHeader[255];
msg_header_t *header = as.event()->getMsgSip()->findHeader(headerName, true);
if (header) {
cmatch m;
sip_header_e(encodedHeader, sizeof(encodedHeader), reinterpret_cast<sip_header_t *>(header), 0);
if (regex_match(encodedHeader, m, regex(".*:\\s*(.*)\r\n"))) {
return m.str(1);
}
}
}
}
for (int i = 0; credentials.au_params[i] != nullptr; i++) {
const char *param = credentials.au_params[i];
const char *equal = strchr(const_cast<char *>(param), '=');
if (paramName.compare(0, paramName.size(), param, equal-param) == 0) {
return StringUtils::strip(equal+1, '"');
}
}
if (paramName == "scheme") return StringUtils::strip(credentials.au_scheme, '"');
if (paramName == "method") return StringUtils::strip(as.method(), '"');
if (paramName == "from") return StringUtils::strip(as.fromHeader(), '"');
if (paramName == "sip-instance") return StringUtils::strip(as.sipInstance(), '"');
if (paramName == "uuid") return as.uuid();
if (paramName == "domain") return StringUtils::strip(as.domain(), '"');
return "null";
}
int ExternalAuthModule::onHttpResponseCb(nth_client_magic_t *magic, nth_client_t *request,
const http_t *http) noexcept {
// Get back the ownership to the HttpRequestCtx
unique_ptr<HttpRequestCtx> ctx{reinterpret_cast<HttpRequestCtx*>(magic)};
// The response has been received, switching back to idle state.
ctx->am.mWaitingForResponse = false;
ctx->am.onHttpResponse(*ctx, request, http);
if (!ctx->am.pendingAuthRequests.empty()) {
ctx->am.popAndSendRequest();
}
return 0;
}
std::string ExternalAuthModule::toString(const http_payload_t *httpPayload) {
if (httpPayload == nullptr || httpPayload->pl_data == nullptr || httpPayload->pl_len == 0) {
return string();
}
return string(httpPayload->pl_data, httpPayload->pl_len);
}
bool ExternalAuthModule::validSipCode(int sipCode) {
const auto it = find(sValidSipCodes.cbegin(), sValidSipCodes.cend(), sipCode);
return (it != sValidSipCodes.cend());
}
std::array<int, 4> ExternalAuthModule::sValidSipCodes{{200, 401, 407, 403}};
} // namespace flexisip
| BelledonneCommunications/flexisip | src/plugin/external-auth-plugin/external-auth-module.cc | C++ | agpl-3.0 | 7,993 |
<?php
/**
* StatusNet, the distributed open-source microblogging tool
*
* Un-block a user via the API
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category API
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @author Zach Copley <zach@status.net>
* @copyright 2009-2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
/**
* Un-blocks the user specified in the ID parameter for the authenticating user.
* Returns the un-blocked user in the requested format when successful.
*
* @category API
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @author Zach Copley <zach@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
class ApiBlockDestroyAction extends ApiAuthAction
{
protected $needPost = true;
var $other = null;
/**
* Take arguments for running
*
* @param array $args $_REQUEST args
*
* @return boolean success flag
*/
protected function prepare(array $args=array())
{
parent::prepare($args);
$this->other = $this->getTargetProfile($this->arg('id'));
return true;
}
/**
* Handle the request
*
* Save the new message
*
* @return void
*/
protected function handle()
{
parent::handle();
if (empty($this->user) || empty($this->other)) {
// TRANS: Client error when user not found for an API action to remove a block for a user.
$this->clientError(_('No such user.'), 404);
}
if ($this->user->hasBlocked($this->other)) {
if (Event::handle('StartUnblockProfile', array($this->user, $this->other))) {
$result = $this->user->unblock($this->other);
if ($result) {
Event::handle('EndUnblockProfile', array($this->user, $this->other));
}
}
}
if (!$this->user->hasBlocked($this->other)) {
$this->initDocument($this->format);
$this->showProfile($this->other, $this->format);
$this->endDocument($this->format);
} else {
// TRANS: Server error displayed when unblocking a user has failed.
$this->serverError(_('Unblock user failed.'));
}
}
}
| charlycoste/StatusNet | actions/apiblockdestroy.php | PHP | agpl-3.0 | 3,155 |
package gplx.xowa.apps.apis.xowa.html.skins; import gplx.*; import gplx.xowa.*; import gplx.xowa.apps.*; import gplx.xowa.apps.apis.*; import gplx.xowa.apps.apis.xowa.*; import gplx.xowa.apps.apis.xowa.html.*;
public class Xoapi_skin_app_base implements Gfo_invk {
public void Init_by_kit(Xoae_app app) {
}
public boolean Sidebar_home_enabled() {return sidebar_home_enabled;} public void Sidebar_home_enabled_(boolean v) {sidebar_home_enabled = v;} private boolean sidebar_home_enabled;
public Object Invk(GfsCtx ctx, int ikey, String k, GfoMsg m) {
if (ctx.Match(k, Invk_sidebar_home_enabled)) return Yn.To_str(sidebar_home_enabled);
else if (ctx.Match(k, Invk_sidebar_home_enabled_)) sidebar_home_enabled = m.ReadYn("v");
return this;
}
private static final String Invk_sidebar_home_enabled = "sidebar_home_enabled", Invk_sidebar_home_enabled_ = "sidebar_home_enabled_";
}
| gnosygnu/xowa_android | _400_xowa/src/main/java/gplx/xowa/apps/apis/xowa/html/skins/Xoapi_skin_app_base.java | Java | agpl-3.0 | 904 |
angular.module('app.preferences.email.directives').directive('sharedWith', sharedWith);
function sharedWith() {
return {
restrict: 'E',
replace: true,
templateUrl: 'preferences/email/directives/shared_with.html',
};
}
| HelloLily/hellolily | frontend/app/preferences/email/controllers/shared_with.js | JavaScript | agpl-3.0 | 251 |
# The Hazard Library
# Copyright (C) 2012-2016 GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Module :mod:`openquake.hazardlib.source.base` defines a base class for
seismic sources.
"""
import abc
from openquake.baselib.slots import with_slots
from openquake.baselib.python3compat import with_metaclass
@with_slots
class BaseSeismicSource(with_metaclass(abc.ABCMeta)):
"""
Base class representing a seismic source, that is a structure generating
earthquake ruptures.
:param source_id:
Some (numeric or literal) source identifier. Supposed to be unique
within the source model.
:param name:
String, a human-readable name of the source.
:param tectonic_region_type:
Source's tectonic regime. See :class:`openquake.hazardlib.const.TRT`.
"""
_slots_ = ['source_id', 'name', 'tectonic_region_type',
'src_group_id', 'num_ruptures', 'seed', 'id']
MODIFICATIONS = abc.abstractproperty()
RUPTURE_WEIGHT = 1. # overridden in PointSource
@property
def weight(self):
"""
Determine the source weight from the number of ruptures, by
multiplying with the scale factor RUPTURE_WEIGHT
"""
return self.num_ruptures * self.RUPTURE_WEIGHT
def __init__(self, source_id, name, tectonic_region_type):
self.source_id = source_id
self.name = name
self.tectonic_region_type = tectonic_region_type
self.src_group_id = None # set by the engine
self.num_ruptures = 0 # set by the engine
self.seed = None # set by the engine
self.id = None # set by the engine
@abc.abstractmethod
def iter_ruptures(self):
"""
Get a generator object that yields probabilistic ruptures the source
consists of.
:returns:
Generator of instances of sublclass of :class:
`~openquake.hazardlib.source.rupture.BaseProbabilisticRupture`.
"""
@abc.abstractmethod
def count_ruptures(self):
"""
Return the number of ruptures that will be generated by the source.
"""
@abc.abstractmethod
def get_min_max_mag(self):
"""
Return minimum and maximum magnitudes of the ruptures generated
by the source.
"""
@abc.abstractmethod
def get_rupture_enclosing_polygon(self, dilation=0):
"""
Get a polygon which encloses all the ruptures generated by the source.
The rupture enclosing polygon is meant to be used in all hazard
calculators to filter out sources whose ruptures the user wants
to be neglected because they are too far from the locations
of interest.
For performance reasons, the ``get_rupture_enclosing_polygon()``
should compute the polygon, without creating all the ruptures.
The rupture enclosing polygon may not be necessarily the *minimum*
enclosing polygon, but must guarantee that all ruptures are within
the polygon.
This method must be implemented by subclasses.
:param dilation:
A buffer distance in km to extend the polygon borders to.
:returns:
Instance of :class:`openquake.hazardlib.geo.polygon.Polygon`.
"""
def filter_sites_by_distance_to_source(self, integration_distance, sites):
"""
Filter out sites from the collection that are further from the source
than some arbitrary threshold.
:param integration_distance:
Distance in km representing a threshold: sites that are further
than that distance from the closest rupture produced by the source
should be excluded.
:param sites:
Instance of :class:`openquake.hazardlib.site.SiteCollection`
to filter.
:returns:
Filtered :class:`~openquake.hazardlib.site.SiteCollection`.
Method can be overridden by subclasses in order to achieve
higher performance for a specific typology. Base class method calls
:meth:`get_rupture_enclosing_polygon` with ``integration_distance``
as a dilation value and then filters site collection by checking
:meth:
`containment <openquake.hazardlib.geo.polygon.Polygon.intersects>`
of site locations.
The main criteria for this method to decide whether a site should be
filtered out or not is the minimum distance between the site and all
the ruptures produced by the source. If at least one rupture is closer
(in terms of great circle distance between surface projections) than
integration distance to a site, it should not be filtered out. However,
it is important not to make this method too computationally intensive.
If short-circuits are taken, false positives are generally better than
false negatives (it's better not to filter a site out if there is some
uncertainty about its distance).
"""
rup_enc_poly = self.get_rupture_enclosing_polygon(integration_distance)
return sites.filter(rup_enc_poly.intersects(sites.mesh))
def modify(self, modification, parameters):
"""
Apply a single modificaton to the source parameters
Reflects the modification method and calls it passing ``parameters``
as keyword arguments.
Modifications can be applied one on top of another. The logic
of stacking modifications is up to a specific source implementation.
:param modification:
String name representing the type of modification.
:param parameters:
Dictionary of parameters needed for modification.
:raises ValueError:
If ``modification`` is missing from the attribute `MODIFICATIONS`.
"""
if modification not in self.MODIFICATIONS:
raise ValueError('Modification %s is not supported by %s' %
(modification, type(self).__name__))
meth = getattr(self, 'modify_%s' % modification)
meth(**parameters)
@with_slots
class ParametricSeismicSource(with_metaclass(abc.ABCMeta, BaseSeismicSource)):
"""
Parametric Seismic Source generates earthquake ruptures from source
parameters, and associated probabilities of occurrence are defined through
a magnitude frequency distribution and a temporal occurrence model.
:param mfd:
Magnitude-Frequency distribution for the source.
See :mod:`openquake.hazardlib.mfd`.
:param rupture_mesh_spacing:
The desired distance between two adjacent points in source's
ruptures' mesh, in km. Mainly this parameter allows to balance
the trade-off between time needed to compute the :meth:`distance
<openquake.hazardlib.geo.surface.base.BaseQuadrilateralSurface.get_min_distance>`
between the rupture surface and a site and the precision of that
computation.
:param magnitude_scaling_relationship:
Instance of subclass of
:class:`openquake.hazardlib.scalerel.base.BaseMSR` to
describe how does the area of the rupture depend on magnitude and rake.
:param rupture_aspect_ratio:
Float number representing how much source's ruptures are more wide
than tall. Aspect ratio of 1 means ruptures have square shape,
value below 1 means ruptures stretch vertically more than horizontally
and vice versa.
:param temporal_occurrence_model:
Instance of
:class:`openquake.hazardlib.tom.PoissonTOM` defining temporal occurrence
model for calculating rupture occurrence probabilities
:raises ValueError:
If either rupture aspect ratio or rupture mesh spacing is not positive
(if not None).
"""
_slots_ = BaseSeismicSource._slots_ + '''mfd rupture_mesh_spacing
magnitude_scaling_relationship rupture_aspect_ratio
temporal_occurrence_model'''.split()
def __init__(self, source_id, name, tectonic_region_type, mfd,
rupture_mesh_spacing, magnitude_scaling_relationship,
rupture_aspect_ratio, temporal_occurrence_model):
super(ParametricSeismicSource, self). \
__init__(source_id, name, tectonic_region_type)
if rupture_mesh_spacing is not None and not rupture_mesh_spacing > 0:
raise ValueError('rupture mesh spacing must be positive')
if rupture_aspect_ratio is not None and not rupture_aspect_ratio > 0:
raise ValueError('rupture aspect ratio must be positive')
self.mfd = mfd
self.rupture_mesh_spacing = rupture_mesh_spacing
self.magnitude_scaling_relationship = magnitude_scaling_relationship
self.rupture_aspect_ratio = rupture_aspect_ratio
self.temporal_occurrence_model = temporal_occurrence_model
def get_annual_occurrence_rates(self, min_rate=0):
"""
Get a list of pairs "magnitude -- annual occurrence rate".
The list is taken from assigned MFD object
(see :meth:`openquake.hazardlib.mfd.base.BaseMFD.get_annual_occurrence_rates`)
with simple filtering by rate applied.
:param min_rate:
A non-negative value to filter magnitudes by minimum annual
occurrence rate. Only magnitudes with rates greater than that
are included in the result list.
:returns:
A list of two-item tuples -- magnitudes and occurrence rates.
"""
return [(mag, occ_rate)
for (mag, occ_rate) in self.mfd.get_annual_occurrence_rates()
if min_rate is None or occ_rate > min_rate]
def get_min_max_mag(self):
"""
Get the minimum and maximum magnitudes of the ruptures generated
by the source from the underlying MFD.
"""
return self.mfd.get_min_max_mag()
def __repr__(self):
"""
String representation of a source, displaying the source class name
and the source id.
"""
return '<%s %s>' % (self.__class__.__name__, self.source_id)
| vup1120/oq-hazardlib | openquake/hazardlib/source/base.py | Python | agpl-3.0 | 10,755 |
/* eslint "import/prefer-default-export": 0 */
/* eslint "new-cap": 0 */
import { toGlobalId } from "graphql-relay";
import icalendar from "icalendar";
import moment from "moment";
import Event from "./models/Event";
export function icalEvents(req, res, next) {
let query = Event.find({ "permissions.public": true });
query = query
.where({
start: {
$gte: moment()
.subtract(1, "years")
.startOf("day"),
},
})
.sort("start")
.populate("creator", "username name");
query.exec((err, events) => {
if (err) {
return next(err);
}
const ical = new icalendar.iCalendar("2.0");
ical.addProperty("VERSION", "2.0");
ical.addProperty("PRODID", "-//Nidarholm//Aktivitetskalender//");
ical.addProperty("X-WR-CALNAME", "Nidarholmkalenderen");
ical.addProperty("METHOD", "PUBLISH");
ical.addProperty("CALSCALE", "GREGORIAN");
ical.addProperty("X-ORIGINAL", "https://nidarholm.no/events/");
events.forEach((e) => {
const event = new icalendar.VEvent();
event.addProperty("UID", e.id);
if (e.modified) {
event.addProperty("DTSTAMP", e.modified);
} else {
event.addProperty("DTSTAMP", e.created);
}
event.setSummary(e.title);
event.setDate(e.start, e.end);
event.setDescription(
e.mdtext.replace(/\r/g, "").replace(/(<([^>]+)>)/gi, ""),
);
event.setLocation(e.location);
event.addProperty(
"URL",
`https://nidarholm.no/events/${toGlobalId("event", e.id)}`,
);
ical.addComponent(event);
});
res.setHeader("Filename", "nidarholm.ics");
res.setHeader("Content-Disposition", "attachment; filename=nidarholm.ics");
res.setHeader("Content-Type", "text/calendar; charset=utf-8");
res.setHeader("Cache-Control", "max-age=7200, private, must-revalidate");
res.send(ical.toString());
return res;
});
}
| strekmann/nidarholmjs | src/server/icalRoutes.js | JavaScript | agpl-3.0 | 1,934 |
/*******************************************************************************
* gvGeoportal is sponsored by the General Directorate for Information
* Technologies (DGTI) of the Regional Ministry of Finance and Public
* Administration of the Generalitat Valenciana (Valencian Community,
* Spain), managed by gvSIG Association and led by DISID Corporation.
*
* Copyright (C) 2016 DGTI - Generalitat Valenciana
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package es.gva.dgti.gvgeoportal.domain.components;
import org.junit.Test;
import org.springframework.roo.addon.test.RooIntegrationTest;
@RooIntegrationTest(entity = ConfCapasTematicas.class)
public class ConfCapasTematicasIntegrationTest {
@Test
public void testMarkerMethod() {
}
}
| gvSIGAssociation/gvsig-web | src/test/java/es/gva/dgti/gvgeoportal/domain/components/ConfCapasTematicasIntegrationTest.java | Java | agpl-3.0 | 1,470 |
/**
* Mutinack mutation detection program.
* Copyright (C) 2014-2016 Olivier Cinquin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.org.cinquin.mutinack.misc_util.exceptions;
public final class ParseRTException extends IllegalInputException {
private static final long serialVersionUID = -3713797417129778021L;
public ParseRTException(String message) {
super(message);
}
public ParseRTException(String message, Throwable cause) {
super(message, cause);
}
}
| cinquin/mutinack | src/uk/org/cinquin/mutinack/misc_util/exceptions/ParseRTException.java | Java | agpl-3.0 | 1,045 |
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-10-13 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
| Bluelytics/bluelytics_frontend | test/karma.conf.js | JavaScript | agpl-3.0 | 2,084 |
/**
* Axelor Business Solutions
*
* Copyright (C) 2016 Axelor (<http://axelor.com>).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.axelor.apps.production.report;
public interface IReport {
public static final String MANUF_ORDER = "ManufOrder.rptdesign";
public static final String OPERATION_ORDER = "OperationOrder.rptdesign";
}
| jph-axelor/axelor-business-suite | axelor-production/src/main/java/com/axelor/apps/production/report/IReport.java | Java | agpl-3.0 | 920 |
/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Don Gagne <don@thegagnes.com>
#include "PX4FirmwarePlugin.h"
#include "AutoPilotPlugins/PX4/PX4AutoPilotPlugin.h" // FIXME: Hack
#include <QDebug>
IMPLEMENT_QGC_SINGLETON(PX4FirmwarePlugin, FirmwarePlugin)
enum PX4_CUSTOM_MAIN_MODE {
PX4_CUSTOM_MAIN_MODE_MANUAL = 1,
PX4_CUSTOM_MAIN_MODE_ALTCTL,
PX4_CUSTOM_MAIN_MODE_POSCTL,
PX4_CUSTOM_MAIN_MODE_AUTO,
PX4_CUSTOM_MAIN_MODE_ACRO,
PX4_CUSTOM_MAIN_MODE_OFFBOARD,
PX4_CUSTOM_MAIN_MODE_STABILIZED,
};
enum PX4_CUSTOM_SUB_MODE_AUTO {
PX4_CUSTOM_SUB_MODE_AUTO_READY = 1,
PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF,
PX4_CUSTOM_SUB_MODE_AUTO_LOITER,
PX4_CUSTOM_SUB_MODE_AUTO_MISSION,
PX4_CUSTOM_SUB_MODE_AUTO_RTL,
PX4_CUSTOM_SUB_MODE_AUTO_LAND,
PX4_CUSTOM_SUB_MODE_AUTO_RTGS
};
union px4_custom_mode {
struct {
uint16_t reserved;
uint8_t main_mode;
uint8_t sub_mode;
};
uint32_t data;
float data_float;
};
struct Modes2Name {
uint8_t main_mode;
uint8_t sub_mode;
const char* name; ///< Name for flight mode
bool canBeSet; ///< true: Vehicle can be set to this flight mode
};
/// Tranlates from PX4 custom modes to flight mode names
// FIXME: Doens't handle fixed-wing/multi-rotor name differences
static const struct Modes2Name rgModes2Name[] = {
{ PX4_CUSTOM_MAIN_MODE_MANUAL, 0, "Manual", true },
{ PX4_CUSTOM_MAIN_MODE_ACRO, 0, "Acro", true },
{ PX4_CUSTOM_MAIN_MODE_STABILIZED, 0, "Stabilized", true },
{ PX4_CUSTOM_MAIN_MODE_ALTCTL, 0, "Altitude control", true },
{ PX4_CUSTOM_MAIN_MODE_POSCTL, 0, "Position control", true },
{ PX4_CUSTOM_MAIN_MODE_OFFBOARD, 0, "Offboard control", true },
{ PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_SUB_MODE_AUTO_READY, "Auto ready", false },
{ PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF, "Taking off", false },
{ PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_SUB_MODE_AUTO_LOITER, "Loiter", true },
{ PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_SUB_MODE_AUTO_MISSION, "Mission", true },
{ PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_SUB_MODE_AUTO_RTL, "Return to Land", true },
{ PX4_CUSTOM_MAIN_MODE_AUTO, PX4_CUSTOM_SUB_MODE_AUTO_LAND, "Landing", false },
};
PX4FirmwarePlugin::PX4FirmwarePlugin(QObject* parent)
: FirmwarePlugin(parent)
, _parameterLoader(NULL)
{
}
QList<VehicleComponent*> PX4FirmwarePlugin::componentsForVehicle(AutoPilotPlugin* vehicle)
{
Q_UNUSED(vehicle);
return QList<VehicleComponent*>();
}
QStringList PX4FirmwarePlugin::flightModes(void)
{
QStringList flightModes;
// FIXME: fixed-wing/multi-rotor differences?
for (size_t i=0; i<sizeof(rgModes2Name)/sizeof(rgModes2Name[0]); i++) {
const struct Modes2Name* pModes2Name = &rgModes2Name[i];
if (pModes2Name->canBeSet) {
flightModes += pModes2Name->name;
}
}
return flightModes;
}
QString PX4FirmwarePlugin::flightMode(uint8_t base_mode, uint32_t custom_mode)
{
QString flightMode = "Unknown";
if (base_mode & MAV_MODE_FLAG_CUSTOM_MODE_ENABLED) {
union px4_custom_mode px4_mode;
px4_mode.data = custom_mode;
// FIXME: fixed-wing/multi-rotor differences?
bool found = false;
for (size_t i=0; i<sizeof(rgModes2Name)/sizeof(rgModes2Name[0]); i++) {
const struct Modes2Name* pModes2Name = &rgModes2Name[i];
if (pModes2Name->main_mode == px4_mode.main_mode && pModes2Name->sub_mode == px4_mode.sub_mode) {
flightMode = pModes2Name->name;
found = true;
break;
}
}
if (!found) {
qWarning() << "Unknown flight mode" << custom_mode;
}
} else {
qWarning() << "PX4 Flight Stack flight mode without custom mode enabled?";
}
return flightMode;
}
bool PX4FirmwarePlugin::setFlightMode(const QString& flightMode, uint8_t* base_mode, uint32_t* custom_mode)
{
*base_mode = 0;
*custom_mode = 0;
bool found = false;
for (size_t i=0; i<sizeof(rgModes2Name)/sizeof(rgModes2Name[0]); i++) {
const struct Modes2Name* pModes2Name = &rgModes2Name[i];
if (flightMode.compare(pModes2Name->name, Qt::CaseInsensitive) == 0) {
union px4_custom_mode px4_mode;
px4_mode.data = 0;
px4_mode.main_mode = pModes2Name->main_mode;
px4_mode.sub_mode = pModes2Name->sub_mode;
*base_mode = MAV_MODE_FLAG_CUSTOM_MODE_ENABLED;
*custom_mode = px4_mode.data;
found = true;
break;
}
}
if (!found) {
qWarning() << "Unknown flight Mode" << flightMode;
}
return found;
}
int PX4FirmwarePlugin::manualControlReservedButtonCount(void)
{
return 8; // 8 buttons reserved for rc switch simulation
}
void PX4FirmwarePlugin::adjustMavlinkMessage(mavlink_message_t* message)
{
Q_UNUSED(message);
// PX4 Flight Stack plugin does no message adjustment
}
bool PX4FirmwarePlugin::isCapable(FirmwareCapabilities capabilities)
{
return (capabilities & (MavCmdPreflightStorageCapability | SetFlightModeCapability)) == capabilities;
}
void PX4FirmwarePlugin::initializeVehicle(Vehicle* vehicle)
{
Q_UNUSED(vehicle);
// PX4 Flight Stack doesn't need to do any extra work
}
bool PX4FirmwarePlugin::sendHomePositionToVehicle(void)
{
// PX4 stack does not want home position sent in the first position.
// Subsequent sequence numbers must be adjusted.
return false;
}
ParameterLoader* PX4FirmwarePlugin::getParameterLoader(AutoPilotPlugin* autopilotPlugin, Vehicle* vehicle)
{
if (!_parameterLoader) {
_parameterLoader = new PX4ParameterLoader(autopilotPlugin, vehicle, this);
Q_CHECK_PTR(_parameterLoader);
// FIXME: Why do I need SIGNAL/SLOT to make this work
connect(_parameterLoader, SIGNAL(parametersReady(bool)), autopilotPlugin, SLOT(_parametersReadyPreChecks(bool)));
connect(_parameterLoader, &PX4ParameterLoader::parameterListProgress, autopilotPlugin, &PX4AutoPilotPlugin::parameterListProgress);
_parameterLoader->loadParameterFactMetaData();
}
return _parameterLoader;
}
| dagoodma/qgroundcontrol | src/FirmwarePlugin/PX4/PX4FirmwarePlugin.cc | C++ | agpl-3.0 | 7,680 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from datetime import timedelta
from functools import partial
import psycopg2
import pytz
from odoo import api, fields, models, tools, _
from odoo.tools import float_is_zero
from odoo.exceptions import UserError
from odoo.http import request
from odoo.addons import decimal_precision as dp
_logger = logging.getLogger(__name__)
class PosOrder(models.Model):
_name = "pos.order"
_description = "Point of Sale Orders"
_order = "id desc"
@api.model
def _amount_line_tax(self, line, fiscal_position_id):
taxes = line.tax_ids.filtered(lambda t: t.company_id.id == line.order_id.company_id.id)
if fiscal_position_id:
taxes = fiscal_position_id.map_tax(taxes, line.product_id, line.order_id.partner_id)
price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
taxes = taxes.compute_all(price, line.order_id.pricelist_id.currency_id, line.qty, product=line.product_id, partner=line.order_id.partner_id or False)['taxes']
return sum(tax.get('amount', 0.0) for tax in taxes)
@api.model
def _order_fields(self, ui_order):
process_line = partial(self.env['pos.order.line']._order_line_fields, session_id=ui_order['pos_session_id'])
return {
'name': ui_order['name'],
'user_id': ui_order['user_id'] or False,
'session_id': ui_order['pos_session_id'],
'lines': [process_line(l) for l in ui_order['lines']] if ui_order['lines'] else False,
'pos_reference': ui_order['name'],
'partner_id': ui_order['partner_id'] or False,
'date_order': ui_order['creation_date'],
'fiscal_position_id': ui_order['fiscal_position_id'],
'pricelist_id': ui_order['pricelist_id'],
}
def _payment_fields(self, ui_paymentline):
payment_date = ui_paymentline['name']
payment_date = fields.Date.context_today(self, fields.Datetime.from_string(payment_date))
return {
'amount': ui_paymentline['amount'] or 0.0,
'payment_date': payment_date,
'statement_id': ui_paymentline['statement_id'],
'payment_name': ui_paymentline.get('note', False),
'journal': ui_paymentline['journal_id'],
}
# This deals with orders that belong to a closed session. In order
# to recover from this situation we create a new rescue session,
# making it obvious that something went wrong.
# A new, separate, rescue session is preferred for every such recovery,
# to avoid adding unrelated orders to live sessions.
def _get_valid_session(self, order):
PosSession = self.env['pos.session']
closed_session = PosSession.browse(order['pos_session_id'])
_logger.warning('session %s (ID: %s) was closed but received order %s (total: %s) belonging to it',
closed_session.name,
closed_session.id,
order['name'],
order['amount_total'])
rescue_session = PosSession.search([
('state', 'not in', ('closed', 'closing_control')),
('rescue', '=', True),
('config_id', '=', closed_session.config_id.id),
], limit=1)
if rescue_session:
_logger.warning('reusing recovery session %s for saving order %s', rescue_session.name, order['name'])
return rescue_session
_logger.warning('attempting to create recovery session for saving order %s', order['name'])
new_session = PosSession.create({
'config_id': closed_session.config_id.id,
'name': _('(RESCUE FOR %(session)s)') % {'session': closed_session.name},
'rescue': True, # avoid conflict with live sessions
})
# bypass opening_control (necessary when using cash control)
new_session.action_pos_session_open()
return new_session
def _match_payment_to_invoice(self, order):
pricelist_id = self.env['product.pricelist'].browse(order.get('pricelist_id'))
account_precision = pricelist_id.currency_id.decimal_places
# ignore orders with an amount_paid of 0 because those are returns through the POS
if not float_is_zero(order['amount_return'], account_precision) and not float_is_zero(order['amount_paid'], account_precision):
cur_amount_paid = 0
payments_to_keep = []
for payment in order.get('statement_ids'):
if cur_amount_paid + payment[2]['amount'] > order['amount_total']:
payment[2]['amount'] = order['amount_total'] - cur_amount_paid
payments_to_keep.append(payment)
break
cur_amount_paid += payment[2]['amount']
payments_to_keep.append(payment)
order['statement_ids'] = payments_to_keep
order['amount_return'] = 0
@api.model
def _process_order(self, pos_order):
pos_session = self.env['pos.session'].browse(pos_order['pos_session_id'])
if pos_session.state == 'closing_control' or pos_session.state == 'closed':
pos_order['pos_session_id'] = self._get_valid_session(pos_order).id
order = self.create(self._order_fields(pos_order))
prec_acc = order.pricelist_id.currency_id.decimal_places
journal_ids = set()
for payments in pos_order['statement_ids']:
if not float_is_zero(payments[2]['amount'], precision_digits=prec_acc):
order.add_payment(self._payment_fields(payments[2]))
journal_ids.add(payments[2]['journal_id'])
if pos_session.sequence_number <= pos_order['sequence_number']:
pos_session.write({'sequence_number': pos_order['sequence_number'] + 1})
pos_session.refresh()
if not float_is_zero(pos_order['amount_return'], prec_acc):
cash_journal_id = pos_session.cash_journal_id.id
if not cash_journal_id:
# Select for change one of the cash journals used in this
# payment
cash_journal = self.env['account.journal'].search([
('type', '=', 'cash'),
('id', 'in', list(journal_ids)),
], limit=1)
if not cash_journal:
# If none, select for change one of the cash journals of the POS
# This is used for example when a customer pays by credit card
# an amount higher than total amount of the order and gets cash back
cash_journal = [statement.journal_id for statement in pos_session.statement_ids if statement.journal_id.type == 'cash']
if not cash_journal:
raise UserError(_("No cash statement found for this session. Unable to record returned cash."))
cash_journal_id = cash_journal[0].id
order.add_payment({
'amount': -pos_order['amount_return'],
'payment_date': fields.Datetime.now(),
'payment_name': _('return'),
'journal': cash_journal_id,
})
return order
def _prepare_analytic_account(self, line):
'''This method is designed to be inherited in a custom module'''
return False
def _create_account_move(self, dt, ref, journal_id, company_id):
date_tz_user = fields.Datetime.context_timestamp(self, fields.Datetime.from_string(dt))
date_tz_user = fields.Date.to_string(date_tz_user)
return self.env['account.move'].sudo().create({'ref': ref, 'journal_id': journal_id, 'date': date_tz_user})
def _prepare_invoice(self):
"""
Prepare the dict of values to create the new invoice for a pos order.
"""
invoice_type = 'out_invoice' if self.amount_total >= 0 else 'out_refund'
return {
'name': self.name,
'origin': self.name,
'account_id': self.partner_id.property_account_receivable_id.id,
'journal_id': self.session_id.config_id.invoice_journal_id.id,
'company_id': self.company_id.id,
'type': invoice_type,
'reference': self.name,
'partner_id': self.partner_id.id,
'comment': self.note or '',
# considering partner's sale pricelist's currency
'currency_id': self.pricelist_id.currency_id.id,
'user_id': self.env.uid,
}
@api.model
def _get_account_move_line_group_data_type_key(self, data_type, values):
"""
Return a tuple which will be used as a key for grouping account
move lines in _create_account_move_line method.
:param data_type: 'product', 'tax', ....
:param values: account move line values
:return: tuple() representing the data_type key
"""
if data_type == 'product':
return ('product',
values['partner_id'],
(values['product_id'], tuple(values['tax_ids'][0][2]), values['name']),
values['analytic_account_id'],
values['debit'] > 0)
elif data_type == 'tax':
return ('tax',
values['partner_id'],
values['tax_line_id'],
values['debit'] > 0)
elif data_type == 'counter_part':
return ('counter_part',
values['partner_id'],
values['account_id'],
values['debit'] > 0)
return False
def _action_create_invoice_line(self, line=False, invoice_id=False):
InvoiceLine = self.env['account.invoice.line']
inv_name = line.product_id.name_get()[0][1]
inv_line = {
'invoice_id': invoice_id,
'product_id': line.product_id.id,
'quantity': line.qty if self.amount_total >= 0 else -line.qty,
'account_analytic_id': self._prepare_analytic_account(line),
'name': inv_name,
}
# Oldlin trick
invoice_line = InvoiceLine.sudo().new(inv_line)
invoice_line._onchange_product_id()
invoice_line.invoice_line_tax_ids = invoice_line.invoice_line_tax_ids.filtered(lambda t: t.company_id.id == line.order_id.company_id.id).ids
fiscal_position_id = line.order_id.fiscal_position_id
if fiscal_position_id:
invoice_line.invoice_line_tax_ids = fiscal_position_id.map_tax(invoice_line.invoice_line_tax_ids, line.product_id, line.order_id.partner_id)
invoice_line.invoice_line_tax_ids = invoice_line.invoice_line_tax_ids.ids
# We convert a new id object back to a dictionary to write to
# bridge between old and new api
inv_line = invoice_line._convert_to_write({name: invoice_line[name] for name in invoice_line._cache})
inv_line.update(price_unit=line.price_unit, discount=line.discount, name=inv_name)
return InvoiceLine.sudo().create(inv_line)
def _create_account_move_line(self, session=None, move=None):
def _flatten_tax_and_children(taxes, group_done=None):
children = self.env['account.tax']
if group_done is None:
group_done = set()
for tax in taxes.filtered(lambda t: t.amount_type == 'group'):
if tax.id not in group_done:
group_done.add(tax.id)
children |= _flatten_tax_and_children(tax.children_tax_ids, group_done)
return taxes + children
# Tricky, via the workflow, we only have one id in the ids variable
"""Create a account move line of order grouped by products or not."""
IrProperty = self.env['ir.property']
ResPartner = self.env['res.partner']
if session and not all(session.id == order.session_id.id for order in self):
raise UserError(_('Selected orders do not have the same session!'))
grouped_data = {}
have_to_group_by = session and session.config_id.group_by or False
rounding_method = session and session.config_id.company_id.tax_calculation_rounding_method
def add_anglosaxon_lines(grouped_data):
Product = self.env['product.product']
Analytic = self.env['account.analytic.account']
for product_key in list(grouped_data.keys()):
if product_key[0] == "product":
line = grouped_data[product_key][0]
product = Product.browse(line['product_id'])
# In the SO part, the entries will be inverted by function compute_invoice_totals
price_unit = self._get_pos_anglo_saxon_price_unit(product, line['partner_id'], line['quantity'])
account_analytic = Analytic.browse(line.get('analytic_account_id'))
res = Product._anglo_saxon_sale_move_lines(
line['name'], product, product.uom_id, line['quantity'], price_unit,
fiscal_position=order.fiscal_position_id,
account_analytic=account_analytic)
if res:
line1, line2 = res
line1 = Product._convert_prepared_anglosaxon_line(line1, order.partner_id)
insert_data('counter_part', {
'name': line1['name'],
'account_id': line1['account_id'],
'credit': line1['credit'] or 0.0,
'debit': line1['debit'] or 0.0,
'partner_id': line1['partner_id']
})
line2 = Product._convert_prepared_anglosaxon_line(line2, order.partner_id)
insert_data('counter_part', {
'name': line2['name'],
'account_id': line2['account_id'],
'credit': line2['credit'] or 0.0,
'debit': line2['debit'] or 0.0,
'partner_id': line2['partner_id']
})
for order in self.filtered(lambda o: not o.account_move or o.state == 'paid'):
current_company = order.sale_journal.company_id
account_def = IrProperty.get(
'property_account_receivable_id', 'res.partner')
order_account = order.partner_id.property_account_receivable_id.id or account_def and account_def.id
partner_id = ResPartner._find_accounting_partner(order.partner_id).id or False
if move is None:
# Create an entry for the sale
journal_id = self.env['ir.config_parameter'].sudo().get_param(
'pos.closing.journal_id_%s' % current_company.id, default=order.sale_journal.id)
move = self._create_account_move(
order.session_id.start_at, order.name, int(journal_id), order.company_id.id)
def insert_data(data_type, values):
# if have_to_group_by:
values.update({
'partner_id': partner_id,
'move_id': move.id,
})
key = self._get_account_move_line_group_data_type_key(data_type, values)
if not key:
return
grouped_data.setdefault(key, [])
if have_to_group_by:
if not grouped_data[key]:
grouped_data[key].append(values)
else:
current_value = grouped_data[key][0]
current_value['quantity'] = current_value.get('quantity', 0.0) + values.get('quantity', 0.0)
current_value['credit'] = current_value.get('credit', 0.0) + values.get('credit', 0.0)
current_value['debit'] = current_value.get('debit', 0.0) + values.get('debit', 0.0)
else:
grouped_data[key].append(values)
# because of the weird way the pos order is written, we need to make sure there is at least one line,
# because just after the 'for' loop there are references to 'line' and 'income_account' variables (that
# are set inside the for loop)
# TOFIX: a deep refactoring of this method (and class!) is needed
# in order to get rid of this stupid hack
assert order.lines, _('The POS order must have lines when calling this method')
# Create an move for each order line
cur = order.pricelist_id.currency_id
for line in order.lines:
amount = line.price_subtotal
# Search for the income account
if line.product_id.property_account_income_id.id:
income_account = line.product_id.property_account_income_id.id
elif line.product_id.categ_id.property_account_income_categ_id.id:
income_account = line.product_id.categ_id.property_account_income_categ_id.id
else:
raise UserError(_('Please define income '
'account for this product: "%s" (id:%d).')
% (line.product_id.name, line.product_id.id))
name = line.product_id.name
if line.notice:
# add discount reason in move
name = name + ' (' + line.notice + ')'
# Create a move for the line for the order line
# Just like for invoices, a group of taxes must be present on this base line
# As well as its children
base_line_tax_ids = _flatten_tax_and_children(line.tax_ids_after_fiscal_position).filtered(lambda tax: tax.type_tax_use in ['sale', 'none'])
insert_data('product', {
'name': name,
'quantity': line.qty,
'product_id': line.product_id.id,
'account_id': income_account,
'analytic_account_id': self._prepare_analytic_account(line),
'credit': ((amount > 0) and amount) or 0.0,
'debit': ((amount < 0) and -amount) or 0.0,
'tax_ids': [(6, 0, base_line_tax_ids.ids)],
'partner_id': partner_id
})
# Create the tax lines
taxes = line.tax_ids_after_fiscal_position.filtered(lambda t: t.company_id.id == current_company.id)
if not taxes:
continue
price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
for tax in taxes.compute_all(price, cur, line.qty)['taxes']:
insert_data('tax', {
'name': _('Tax') + ' ' + tax['name'],
'product_id': line.product_id.id,
'quantity': line.qty,
'account_id': tax['account_id'] or income_account,
'credit': ((tax['amount'] > 0) and tax['amount']) or 0.0,
'debit': ((tax['amount'] < 0) and -tax['amount']) or 0.0,
'tax_line_id': tax['id'],
'partner_id': partner_id
})
# round tax lines per order
if rounding_method == 'round_globally':
for group_key, group_value in grouped_data.items():
if group_key[0] == 'tax':
for line in group_value:
line['credit'] = cur.round(line['credit'])
line['debit'] = cur.round(line['debit'])
# counterpart
insert_data('counter_part', {
'name': _("Trade Receivables"), # order.name,
'account_id': order_account,
'credit': ((order.amount_total < 0) and -order.amount_total) or 0.0,
'debit': ((order.amount_total > 0) and order.amount_total) or 0.0,
'partner_id': partner_id
})
order.write({'state': 'done', 'account_move': move.id})
if self and order.company_id.anglo_saxon_accounting:
add_anglosaxon_lines(grouped_data)
all_lines = []
for group_key, group_data in grouped_data.items():
for value in group_data:
all_lines.append((0, 0, value),)
if move: # In case no order was changed
move.sudo().write({'line_ids': all_lines})
move.sudo().post()
return True
def _get_pos_anglo_saxon_price_unit(self, product, partner_id, quantity):
price_unit = product._get_anglo_saxon_price_unit()
if product._get_invoice_policy() == "delivery":
moves = self.filtered(lambda o: o.partner_id.id == partner_id).mapped('picking_id.move_lines').filtered(lambda m: m.product_id.id == product.id)
moves.sorted(lambda x: x.date)
average_price_unit = product._compute_average_price(0, quantity, moves)
price_unit = average_price_unit or price_unit
# In the SO part, the entries will be inverted by function compute_invoice_totals
return - price_unit
def _reconcile_payments(self):
for order in self:
aml = order.statement_ids.mapped('journal_entry_ids') | order.account_move.line_ids | order.invoice_id.move_id.line_ids
aml = aml.filtered(lambda r: not r.reconciled and r.account_id.internal_type == 'receivable' and r.partner_id == order.partner_id.commercial_partner_id)
# Reconcile returns first
# to avoid mixing up the credit of a payment and the credit of a return
# in the receivable account
aml_returns = aml.filtered(lambda l: (l.journal_id.type == 'sale' and l.credit) or (l.journal_id.type != 'sale' and l.debit))
try:
aml_returns.reconcile()
(aml - aml_returns).reconcile()
except Exception:
# There might be unexpected situations where the automatic reconciliation won't
# work. We don't want the user to be blocked because of this, since the automatic
# reconciliation is introduced for convenience, not for mandatory accounting
# reasons.
# It may be interesting to have the Traceback logged anyway
# for debugging and support purposes
_logger.exception('Reconciliation did not work for order %s', order.name)
def _default_session(self):
return self.env['pos.session'].search([('state', '=', 'opened'), ('user_id', '=', self.env.uid)], limit=1)
def _default_pricelist(self):
return self._default_session().config_id.pricelist_id
name = fields.Char(string='Order Ref', required=True, readonly=True, copy=False, default='/')
company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.user.company_id)
date_order = fields.Datetime(string='Order Date', readonly=True, index=True, default=fields.Datetime.now)
user_id = fields.Many2one(
comodel_name='res.users', string='Salesman',
help="Person who uses the cash register. It can be a reliever, a student or an interim employee.",
default=lambda self: self.env.uid,
states={'done': [('readonly', True)], 'invoiced': [('readonly', True)]},
)
amount_tax = fields.Float(compute='_compute_amount_all', string='Taxes', digits=0)
amount_total = fields.Float(compute='_compute_amount_all', string='Total', digits=0)
amount_paid = fields.Float(compute='_compute_amount_all', string='Paid', states={'draft': [('readonly', False)]}, readonly=True, digits=0)
amount_return = fields.Float(compute='_compute_amount_all', string='Returned', digits=0)
lines = fields.One2many('pos.order.line', 'order_id', string='Order Lines', states={'draft': [('readonly', False)]}, readonly=True, copy=True)
statement_ids = fields.One2many('account.bank.statement.line', 'pos_statement_id', string='Payments', states={'draft': [('readonly', False)]}, readonly=True)
pricelist_id = fields.Many2one('product.pricelist', string='Pricelist', required=True, states={
'draft': [('readonly', False)]}, readonly=True, default=_default_pricelist)
partner_id = fields.Many2one('res.partner', string='Customer', change_default=True, index=True, states={'draft': [('readonly', False)], 'paid': [('readonly', False)]})
sequence_number = fields.Integer(string='Sequence Number', help='A session-unique sequence number for the order', default=1)
session_id = fields.Many2one(
'pos.session', string='Session', required=True, index=True,
domain="[('state', '=', 'opened')]", states={'draft': [('readonly', False)]},
readonly=True, default=_default_session)
config_id = fields.Many2one('pos.config', related='session_id.config_id', string="Point of Sale")
state = fields.Selection(
[('draft', 'New'), ('cancel', 'Cancelled'), ('paid', 'Paid'), ('done', 'Posted'), ('invoiced', 'Invoiced')],
'Status', readonly=True, copy=False, default='draft')
invoice_id = fields.Many2one('account.invoice', string='Invoice', copy=False)
account_move = fields.Many2one('account.move', string='Journal Entry', readonly=True, copy=False)
picking_id = fields.Many2one('stock.picking', string='Picking', readonly=True, copy=False)
picking_type_id = fields.Many2one('stock.picking.type', related='session_id.config_id.picking_type_id', string="Operation Type")
location_id = fields.Many2one(
comodel_name='stock.location',
related='session_id.config_id.stock_location_id',
string="Location", store=True,
readonly=True,
)
note = fields.Text(string='Internal Notes')
nb_print = fields.Integer(string='Number of Print', readonly=True, copy=False, default=0)
pos_reference = fields.Char(string='Receipt Ref', readonly=True, copy=False)
sale_journal = fields.Many2one('account.journal', related='session_id.config_id.journal_id', string='Sales Journal', store=True, readonly=True)
fiscal_position_id = fields.Many2one(
comodel_name='account.fiscal.position', string='Fiscal Position',
default=lambda self: self._default_session().config_id.default_fiscal_position_id,
readonly=True,
states={'draft': [('readonly', False)]},
)
@api.depends('statement_ids', 'lines.price_subtotal_incl', 'lines.discount')
def _compute_amount_all(self):
for order in self:
order.amount_paid = order.amount_return = order.amount_tax = 0.0
currency = order.pricelist_id.currency_id
order.amount_paid = sum(payment.amount for payment in order.statement_ids)
order.amount_return = sum(payment.amount < 0 and payment.amount or 0 for payment in order.statement_ids)
order.amount_tax = currency.round(sum(self._amount_line_tax(line, order.fiscal_position_id) for line in order.lines))
amount_untaxed = currency.round(sum(line.price_subtotal for line in order.lines))
order.amount_total = order.amount_tax + amount_untaxed
@api.onchange('partner_id')
def _onchange_partner_id(self):
if self.partner_id:
self.pricelist = self.partner_id.property_product_pricelist.id
@api.multi
def write(self, vals):
res = super(PosOrder, self).write(vals)
Partner = self.env['res.partner']
# If you change the partner of the PoS order, change also the partner of the associated bank statement lines
if 'partner_id' in vals:
for order in self:
partner_id = False
if order.invoice_id:
raise UserError(_("You cannot change the partner of a POS order for which an invoice has already been issued."))
if vals['partner_id']:
partner = Partner.browse(vals['partner_id'])
partner_id = Partner._find_accounting_partner(partner).id
order.statement_ids.write({'partner_id': partner_id})
return res
@api.multi
def unlink(self):
for pos_order in self.filtered(lambda pos_order: pos_order.state not in ['draft', 'cancel']):
raise UserError(_('In order to delete a sale, it must be new or cancelled.'))
return super(PosOrder, self).unlink()
@api.model
def create(self, values):
if values.get('session_id'):
# set name based on the sequence specified on the config
session = self.env['pos.session'].browse(values['session_id'])
values['name'] = session.config_id.sequence_id._next()
values.setdefault('pricelist_id', session.config_id.pricelist_id.id)
else:
# fallback on any pos.order sequence
values['name'] = self.env['ir.sequence'].next_by_code('pos.order')
return super(PosOrder, self).create(values)
@api.multi
def action_view_invoice(self):
return {
'name': _('Customer Invoice'),
'view_mode': 'form',
'view_id': self.env.ref('account.invoice_form').id,
'res_model': 'account.invoice',
'context': "{'type':'out_invoice'}",
'type': 'ir.actions.act_window',
'res_id': self.invoice_id.id,
}
@api.multi
def action_pos_order_paid(self):
if not self.test_paid():
raise UserError(_("Order is not paid."))
self.write({'state': 'paid'})
return self.create_picking()
@api.multi
def action_pos_order_invoice(self):
Invoice = self.env['account.invoice']
for order in self:
# Force company for all SUPERUSER_ID action
local_context = dict(self.env.context, force_company=order.company_id.id, company_id=order.company_id.id)
if order.invoice_id:
Invoice += order.invoice_id
continue
if not order.partner_id:
raise UserError(_('Please provide a partner for the sale.'))
invoice = Invoice.new(order._prepare_invoice())
invoice._onchange_partner_id()
invoice.fiscal_position_id = order.fiscal_position_id
inv = invoice._convert_to_write({name: invoice[name] for name in invoice._cache})
new_invoice = Invoice.with_context(local_context).sudo().create(inv)
message = _("This invoice has been created from the point of sale session: <a href=# data-oe-model=pos.order data-oe-id=%d>%s</a>") % (order.id, order.name)
new_invoice.message_post(body=message)
order.write({'invoice_id': new_invoice.id, 'state': 'invoiced'})
Invoice += new_invoice
for line in order.lines:
self.with_context(local_context)._action_create_invoice_line(line, new_invoice.id)
new_invoice.with_context(local_context).sudo().compute_taxes()
order.sudo().write({'state': 'invoiced'})
if not Invoice:
return {}
return {
'name': _('Customer Invoice'),
'view_type': 'form',
'view_mode': 'form',
'view_id': self.env.ref('account.invoice_form').id,
'res_model': 'account.invoice',
'context': "{'type':'out_invoice'}",
'type': 'ir.actions.act_window',
'nodestroy': True,
'target': 'current',
'res_id': Invoice and Invoice.ids[0] or False,
}
# this method is unused, and so is the state 'cancel'
@api.multi
def action_pos_order_cancel(self):
return self.write({'state': 'cancel'})
@api.multi
def action_pos_order_done(self):
return self._create_account_move_line()
@api.model
def create_from_ui(self, orders):
# Keep only new orders
submitted_references = [o['data']['name'] for o in orders]
pos_order = self.search([('pos_reference', 'in', submitted_references)])
existing_orders = pos_order.read(['pos_reference'])
existing_references = set([o['pos_reference'] for o in existing_orders])
orders_to_save = [o for o in orders if o['data']['name'] not in existing_references]
order_ids = []
for tmp_order in orders_to_save:
to_invoice = tmp_order['to_invoice']
order = tmp_order['data']
if to_invoice:
self._match_payment_to_invoice(order)
pos_order = self._process_order(order)
order_ids.append(pos_order.id)
try:
pos_order.action_pos_order_paid()
except psycopg2.OperationalError:
# do not hide transactional errors, the order(s) won't be saved!
raise
except Exception as e:
_logger.error('Could not fully process the POS Order: %s', tools.ustr(e))
if to_invoice:
pos_order.action_pos_order_invoice()
pos_order.invoice_id.sudo().action_invoice_open()
pos_order.account_move = pos_order.invoice_id.move_id
return order_ids
def test_paid(self):
"""A Point of Sale is paid when the sum
@return: True
"""
for order in self:
if order.lines and not order.amount_total:
continue
if (not order.lines) or (not order.statement_ids) or (abs(order.amount_total - order.amount_paid) > 0.00001):
return False
return True
def create_picking(self):
"""Create a picking for each order and validate it."""
Picking = self.env['stock.picking']
Move = self.env['stock.move']
StockWarehouse = self.env['stock.warehouse']
for order in self:
if not order.lines.filtered(lambda l: l.product_id.type in ['product', 'consu']):
continue
address = order.partner_id.address_get(['delivery']) or {}
picking_type = order.picking_type_id
return_pick_type = order.picking_type_id.return_picking_type_id or order.picking_type_id
order_picking = Picking
return_picking = Picking
moves = Move
location_id = order.location_id.id
if order.partner_id:
destination_id = order.partner_id.property_stock_customer.id
else:
if (not picking_type) or (not picking_type.default_location_dest_id):
customerloc, supplierloc = StockWarehouse._get_partner_locations()
destination_id = customerloc.id
else:
destination_id = picking_type.default_location_dest_id.id
if picking_type:
message = _("This transfer has been created from the point of sale session: <a href=# data-oe-model=pos.order data-oe-id=%d>%s</a>") % (order.id, order.name)
picking_vals = {
'origin': order.name,
'partner_id': address.get('delivery', False),
'date_done': order.date_order,
'picking_type_id': picking_type.id,
'company_id': order.company_id.id,
'move_type': 'direct',
'note': order.note or "",
'location_id': location_id,
'location_dest_id': destination_id,
}
pos_qty = any([x.qty > 0 for x in order.lines if x.product_id.type in ['product', 'consu']])
if pos_qty:
order_picking = Picking.create(picking_vals.copy())
order_picking.message_post(body=message)
neg_qty = any([x.qty < 0 for x in order.lines if x.product_id.type in ['product', 'consu']])
if neg_qty:
return_vals = picking_vals.copy()
return_vals.update({
'location_id': destination_id,
'location_dest_id': return_pick_type != picking_type and return_pick_type.default_location_dest_id.id or location_id,
'picking_type_id': return_pick_type.id
})
return_picking = Picking.create(return_vals)
return_picking.message_post(body=message)
for line in order.lines.filtered(lambda l: l.product_id.type in ['product', 'consu'] and not float_is_zero(l.qty, precision_rounding=l.product_id.uom_id.rounding)):
moves |= Move.create({
'name': line.name,
'product_uom': line.product_id.uom_id.id,
'picking_id': order_picking.id if line.qty >= 0 else return_picking.id,
'picking_type_id': picking_type.id if line.qty >= 0 else return_pick_type.id,
'product_id': line.product_id.id,
'product_uom_qty': abs(line.qty),
'state': 'draft',
'location_id': location_id if line.qty >= 0 else destination_id,
'location_dest_id': destination_id if line.qty >= 0 else return_pick_type != picking_type and return_pick_type.default_location_dest_id.id or location_id,
})
# prefer associating the regular order picking, not the return
order.write({'picking_id': order_picking.id or return_picking.id})
if return_picking:
order._force_picking_done(return_picking)
if order_picking:
order._force_picking_done(order_picking)
# when the pos.config has no picking_type_id set only the moves will be created
if moves and not return_picking and not order_picking:
moves._action_assign()
moves.filtered(lambda m: m.state in ['confirmed', 'waiting'])._force_assign()
moves.filtered(lambda m: m.product_id.tracking == 'none')._action_done()
return True
def _force_picking_done(self, picking):
"""Force picking in order to be set as done."""
self.ensure_one()
picking.action_assign()
picking.force_assign()
wrong_lots = self.set_pack_operation_lot(picking)
if not wrong_lots:
picking.action_done()
def set_pack_operation_lot(self, picking=None):
"""Set Serial/Lot number in pack operations to mark the pack operation done."""
StockProductionLot = self.env['stock.production.lot']
PosPackOperationLot = self.env['pos.pack.operation.lot']
has_wrong_lots = False
for order in self:
for move in (picking or self.picking_id).move_lines:
picking_type = (picking or self.picking_id).picking_type_id
lots_necessary = True
if picking_type:
lots_necessary = picking_type and picking_type.use_existing_lots
qty = 0
qty_done = 0
pack_lots = []
pos_pack_lots = PosPackOperationLot.search([('order_id', '=', order.id), ('product_id', '=', move.product_id.id)])
pack_lot_names = [pos_pack.lot_name for pos_pack in pos_pack_lots]
if pack_lot_names and lots_necessary:
for lot_name in list(set(pack_lot_names)):
stock_production_lot = StockProductionLot.search([('name', '=', lot_name), ('product_id', '=', move.product_id.id)])
if stock_production_lot:
if stock_production_lot.product_id.tracking == 'lot':
# if a lot nr is set through the frontend it will refer to the full quantity
qty = move.product_uom_qty
else: # serial numbers
qty = 1.0
qty_done += qty
pack_lots.append({'lot_id': stock_production_lot.id, 'qty': qty})
else:
has_wrong_lots = True
elif move.product_id.tracking == 'none' or not lots_necessary:
qty_done = move.product_uom_qty
else:
has_wrong_lots = True
for pack_lot in pack_lots:
lot_id, qty = pack_lot['lot_id'], pack_lot['qty']
self.env['stock.move.line'].create({
'move_id': move.id,
'product_id': move.product_id.id,
'product_uom_id': move.product_uom.id,
'qty_done': qty,
'location_id': move.location_id.id,
'location_dest_id': move.location_dest_id.id,
'lot_id': lot_id,
})
if not pack_lots and not float_is_zero(qty_done, precision_rounding=move.product_uom.rounding):
move.quantity_done = qty_done
return has_wrong_lots
def _prepare_bank_statement_line_payment_values(self, data):
"""Create a new payment for the order"""
args = {
'amount': data['amount'],
'date': data.get('payment_date', fields.Date.context_today(self)),
'name': self.name + ': ' + (data.get('payment_name', '') or ''),
'partner_id': self.env["res.partner"]._find_accounting_partner(self.partner_id).id or False,
}
journal_id = data.get('journal', False)
statement_id = data.get('statement_id', False)
assert journal_id or statement_id, "No statement_id or journal_id passed to the method!"
journal = self.env['account.journal'].browse(journal_id)
# use the company of the journal and not of the current user
company_cxt = dict(self.env.context, force_company=journal.company_id.id)
account_def = self.env['ir.property'].with_context(company_cxt).get('property_account_receivable_id', 'res.partner')
args['account_id'] = (self.partner_id.property_account_receivable_id.id) or (account_def and account_def.id) or False
if not args['account_id']:
if not args['partner_id']:
msg = _('There is no receivable account defined to make payment.')
else:
msg = _('There is no receivable account defined to make payment for the partner: "%s" (id:%d).') % (
self.partner_id.name, self.partner_id.id,)
raise UserError(msg)
context = dict(self.env.context)
context.pop('pos_session_id', False)
for statement in self.session_id.statement_ids:
if statement.id == statement_id:
journal_id = statement.journal_id.id
break
elif statement.journal_id.id == journal_id:
statement_id = statement.id
break
if not statement_id:
raise UserError(_('You have to open at least one cashbox.'))
args.update({
'statement_id': statement_id,
'pos_statement_id': self.id,
'journal_id': journal_id,
'ref': self.session_id.name,
})
return args
def add_payment(self, data):
"""Create a new payment for the order"""
args = self._prepare_bank_statement_line_payment_values(data)
context = dict(self.env.context)
context.pop('pos_session_id', False)
self.env['account.bank.statement.line'].with_context(context).create(args)
return args.get('statement_id', False)
@api.multi
def refund(self):
"""Create a copy of order for refund order"""
PosOrder = self.env['pos.order']
current_session = self.env['pos.session'].search([('state', '!=', 'closed'), ('user_id', '=', self.env.uid)], limit=1)
if not current_session:
raise UserError(_('To return product(s), you need to open a session that will be used to register the refund.'))
for order in self:
clone = order.copy({
# ot used, name forced by create
'name': order.name + _(' REFUND'),
'session_id': current_session.id,
'date_order': fields.Datetime.now(),
'pos_reference': order.pos_reference,
'lines': False,
})
for line in order.lines:
clone_line = line.copy({
# required=True, copy=False
'name': line.name + _(' REFUND'),
'order_id': clone.id,
'qty': -line.qty,
})
PosOrder += clone
return {
'name': _('Return Products'),
'view_type': 'form',
'view_mode': 'form',
'res_model': 'pos.order',
'res_id': PosOrder.ids[0],
'view_id': False,
'context': self.env.context,
'type': 'ir.actions.act_window',
'target': 'current',
}
class PosOrderLine(models.Model):
_name = "pos.order.line"
_description = "Lines of Point of Sale Orders"
_rec_name = "product_id"
def _order_line_fields(self, line, session_id=None):
if line and 'name' not in line[2]:
session = self.env['pos.session'].browse(session_id).exists() if session_id else None
if session and session.config_id.sequence_line_id:
# set name based on the sequence specified on the config
line[2]['name'] = session.config_id.sequence_line_id._next()
else:
# fallback on any pos.order.line sequence
line[2]['name'] = self.env['ir.sequence'].next_by_code('pos.order.line')
if line and 'tax_ids' not in line[2]:
product = self.env['product.product'].browse(line[2]['product_id'])
line[2]['tax_ids'] = [(6, 0, [x.id for x in product.taxes_id])]
return line
company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.user.company_id)
name = fields.Char(string='Line No', required=True, copy=False)
notice = fields.Char(string='Discount Notice')
product_id = fields.Many2one('product.product', string='Product', domain=[('sale_ok', '=', True)], required=True, change_default=True)
price_unit = fields.Float(string='Unit Price', digits=0)
qty = fields.Float('Quantity', digits=dp.get_precision('Product Unit of Measure'), default=1)
price_subtotal = fields.Float(compute='_compute_amount_line_all', digits=0, string='Subtotal w/o Tax')
price_subtotal_incl = fields.Float(compute='_compute_amount_line_all', digits=0, string='Subtotal')
discount = fields.Float(string='Discount (%)', digits=0, default=0.0)
order_id = fields.Many2one('pos.order', string='Order Ref', ondelete='cascade')
create_date = fields.Datetime(string='Creation Date', readonly=True)
tax_ids = fields.Many2many('account.tax', string='Taxes', readonly=True)
tax_ids_after_fiscal_position = fields.Many2many('account.tax', compute='_get_tax_ids_after_fiscal_position', string='Taxes to Apply')
pack_lot_ids = fields.One2many('pos.pack.operation.lot', 'pos_order_line_id', string='Lot/serial Number')
@api.model
def create(self, values):
if values.get('order_id') and not values.get('name'):
# set name based on the sequence specified on the config
config_id = self.order_id.browse(values['order_id']).session_id.config_id.id
# HACK: sequence created in the same transaction as the config
# cf TODO master is pos.config create
# remove me saas-15
self.env.cr.execute("""
SELECT s.id
FROM ir_sequence s
JOIN pos_config c
ON s.create_date=c.create_date
WHERE c.id = %s
AND s.code = 'pos.order.line'
LIMIT 1
""", (config_id,))
sequence = self.env.cr.fetchone()
if sequence:
values['name'] = self.env['ir.sequence'].browse(sequence[0])._next()
if not values.get('name'):
# fallback on any pos.order sequence
values['name'] = self.env['ir.sequence'].next_by_code('pos.order.line')
return super(PosOrderLine, self).create(values)
@api.depends('price_unit', 'tax_ids', 'qty', 'discount', 'product_id')
def _compute_amount_line_all(self):
for line in self:
fpos = line.order_id.fiscal_position_id
tax_ids_after_fiscal_position = fpos.map_tax(line.tax_ids, line.product_id, line.order_id.partner_id) if fpos else line.tax_ids
price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
taxes = tax_ids_after_fiscal_position.compute_all(price, line.order_id.pricelist_id.currency_id, line.qty, product=line.product_id, partner=line.order_id.partner_id)
line.update({
'price_subtotal_incl': taxes['total_included'],
'price_subtotal': taxes['total_excluded'],
})
@api.onchange('product_id')
def _onchange_product_id(self):
if self.product_id:
if not self.order_id.pricelist_id:
raise UserError(
_('You have to select a pricelist in the sale form !\n'
'Please set one before choosing a product.'))
price = self.order_id.pricelist_id.get_product_price(
self.product_id, self.qty or 1.0, self.order_id.partner_id)
self._onchange_qty()
self.tax_ids = self.product_id.taxes_id.filtered(lambda r: not self.company_id or r.company_id == self.company_id)
fpos = self.order_id.fiscal_position_id
tax_ids_after_fiscal_position = fpos.map_tax(self.tax_ids, self.product_id, self.order_id.partner_id) if fpos else self.tax_ids
self.price_unit = self.env['account.tax']._fix_tax_included_price_company(price, self.product_id.taxes_id, tax_ids_after_fiscal_position, self.company_id)
@api.onchange('qty', 'discount', 'price_unit', 'tax_ids')
def _onchange_qty(self):
if self.product_id:
if not self.order_id.pricelist_id:
raise UserError(_('You have to select a pricelist in the sale form !'))
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
self.price_subtotal = self.price_subtotal_incl = price * self.qty
if (self.product_id.taxes_id):
taxes = self.product_id.taxes_id.compute_all(price, self.order_id.pricelist_id.currency_id, self.qty, product=self.product_id, partner=False)
self.price_subtotal = taxes['total_excluded']
self.price_subtotal_incl = taxes['total_included']
@api.multi
def _get_tax_ids_after_fiscal_position(self):
for line in self:
line.tax_ids_after_fiscal_position = line.order_id.fiscal_position_id.map_tax(line.tax_ids, line.product_id, line.order_id.partner_id)
class PosOrderLineLot(models.Model):
_name = "pos.pack.operation.lot"
_description = "Specify product lot/serial number in pos order line"
pos_order_line_id = fields.Many2one('pos.order.line')
order_id = fields.Many2one('pos.order', related="pos_order_line_id.order_id")
lot_name = fields.Char('Lot Name')
product_id = fields.Many2one('product.product', related='pos_order_line_id.product_id')
class ReportSaleDetails(models.AbstractModel):
_name = 'report.point_of_sale.report_saledetails'
@api.model
def get_sale_details(self, date_start=False, date_stop=False, configs=False):
""" Serialise the orders of the day information
params: date_start, date_stop string representing the datetime of order
"""
if not configs:
configs = self.env['pos.config'].search([])
user_tz = pytz.timezone(self.env.context.get('tz') or self.env.user.tz or 'UTC')
today = user_tz.localize(fields.Datetime.from_string(fields.Date.context_today(self)))
today = today.astimezone(pytz.timezone('UTC'))
if date_start:
date_start = fields.Datetime.from_string(date_start)
else:
# start by default today 00:00:00
date_start = today
if date_stop:
# set time to 23:59:59
date_stop = fields.Datetime.from_string(date_stop)
else:
# stop by default today 23:59:59
date_stop = today + timedelta(days=1, seconds=-1)
# avoid a date_stop smaller than date_start
date_stop = max(date_stop, date_start)
date_start = fields.Datetime.to_string(date_start)
date_stop = fields.Datetime.to_string(date_stop)
orders = self.env['pos.order'].search([
('date_order', '>=', date_start),
('date_order', '<=', date_stop),
('state', 'in', ['paid','invoiced','done']),
('config_id', 'in', configs.ids)])
user_currency = self.env.user.company_id.currency_id
total = 0.0
products_sold = {}
taxes = {}
for order in orders:
if user_currency != order.pricelist_id.currency_id:
total += order.pricelist_id.currency_id._convert(
order.amount_total, user_currency, order.company_id, order.date_order or fields.Date.today())
else:
total += order.amount_total
currency = order.session_id.currency_id
for line in order.lines:
key = (line.product_id, line.price_unit, line.discount)
products_sold.setdefault(key, 0.0)
products_sold[key] += line.qty
if line.tax_ids_after_fiscal_position:
line_taxes = line.tax_ids_after_fiscal_position.compute_all(line.price_unit * (1-(line.discount or 0.0)/100.0), currency, line.qty, product=line.product_id, partner=line.order_id.partner_id or False)
for tax in line_taxes['taxes']:
taxes.setdefault(tax['id'], {'name': tax['name'], 'tax_amount':0.0, 'base_amount':0.0})
taxes[tax['id']]['tax_amount'] += tax['amount']
taxes[tax['id']]['base_amount'] += tax['base']
else:
taxes.setdefault(0, {'name': _('No Taxes'), 'tax_amount':0.0, 'base_amount':0.0})
taxes[0]['base_amount'] += line.price_subtotal_incl
st_line_ids = self.env["account.bank.statement.line"].search([('pos_statement_id', 'in', orders.ids)]).ids
if st_line_ids:
self.env.cr.execute("""
SELECT aj.name, sum(amount) total
FROM account_bank_statement_line AS absl,
account_bank_statement AS abs,
account_journal AS aj
WHERE absl.statement_id = abs.id
AND abs.journal_id = aj.id
AND absl.id IN %s
GROUP BY aj.name
""", (tuple(st_line_ids),))
payments = self.env.cr.dictfetchall()
else:
payments = []
return {
'currency_precision': user_currency.decimal_places,
'total_paid': user_currency.round(total),
'payments': payments,
'company_name': self.env.user.company_id.name,
'taxes': list(taxes.values()),
'products': sorted([{
'product_id': product.id,
'product_name': product.name,
'code': product.default_code,
'quantity': qty,
'price_unit': price_unit,
'discount': discount,
'uom': product.uom_id.name
} for (product, price_unit, discount), qty in products_sold.items()], key=lambda l: l['product_name'])
}
@api.multi
def get_report_values(self, docids, data=None):
data = dict(data or {})
configs = self.env['pos.config'].browse(data['config_ids'])
data.update(self.get_sale_details(data['date_start'], data['date_stop'], configs))
return data
| maxive/erp | addons/point_of_sale/models/pos_order.py | Python | agpl-3.0 | 56,888 |
# frozen_string_literal: true
class CreateTagReferences < ActiveRecord::Migration[4.2]
def change
create_table :tag_references do |t|
t.references :tag, null: false
t.references :taggable, null: false, polymorphic: true
t.timestamps null: false
end
end
end
| Feuerwehrsport/wettkampf-manager | db/migrate/20160229204201_create_tag_references.rb | Ruby | agpl-3.0 | 288 |
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2014-2022 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
"""
Implements the set of tests for the Ghofrani & Atkinson (2014) Subduction
Interface GMPE
Test data are generated from tables supplied by Gail Atkinson
(2015, personal communication)
"""
from openquake.hazardlib.gsim.ghofrani_atkinson_2014 import (
GhofraniAtkinson2014,
GhofraniAtkinson2014Cascadia,
GhofraniAtkinson2014Upper,
GhofraniAtkinson2014Lower,
GhofraniAtkinson2014CascadiaUpper,
GhofraniAtkinson2014CascadiaLower)
from openquake.hazardlib.tests.gsim.utils import BaseGSIMTestCase
# Discrepency percentages to be applied to all tests
MEAN_DISCREP = 0.1
STDDEV_DISCREP = 0.1
class GhofraniAtkinson2014TestCase(BaseGSIMTestCase):
"""
Implements the test case for the Ghorfrani & Atkinson (2014) GMPE for the
default condition
"""
GSIM_CLASS = GhofraniAtkinson2014
# File for the mean results
MEAN_FILE = "GA2014/GA2014_MEAN.csv"
# File for the total standard deviation
STD_FILE = "GA2014/GA2014_TOTAL.csv"
# File for the inter-event standard deviation
INTER_FILE = "GA2014/GA2014_INTER.csv"
# File for the intra-event standard deviation
INTRA_FILE = "GA2014/GA2014_INTRA.csv"
def test_all(self):
self.check(self.MEAN_FILE,
self.STD_FILE,
self.INTER_FILE,
self.INTRA_FILE,
max_discrep_percentage=MEAN_DISCREP,
std_discrep_percentage=STDDEV_DISCREP)
class GhofraniAtkinson2014CascadiaTestCase(GhofraniAtkinson2014TestCase):
"""
Implements the test case for the Ghorfrani & Atkinson (2014) GMPE for with
the adjustment for Cascadia
"""
GSIM_CLASS = GhofraniAtkinson2014Cascadia
MEAN_FILE = "GA2014/GA2014_CASCADIA_MEAN.csv"
STD_FILE = "GA2014/GA2014_CASCADIA_TOTAL.csv"
INTER_FILE = "GA2014/GA2014_CASCADIA_INTER.csv"
INTRA_FILE = "GA2014/GA2014_CASCADIA_INTRA.csv"
class GhofraniAtkinson2014UpperTestCase(GhofraniAtkinson2014TestCase):
"""
Implements the test case for the Ghorfrani & Atkinson (2014) GMPE for the
"upper" epistemic uncertainty case
"""
GSIM_CLASS = GhofraniAtkinson2014Upper
MEAN_FILE = "GA2014/GA2014_UPPER_MEAN.csv"
STD_FILE = "GA2014/GA2014_UPPER_TOTAL.csv"
INTER_FILE = "GA2014/GA2014_UPPER_INTER.csv"
INTRA_FILE = "GA2014/GA2014_UPPER_INTRA.csv"
class GhofraniAtkinson2014LowerTestCase(GhofraniAtkinson2014TestCase):
"""
Implements the test case for the Ghorfrani & Atkinson (2014) GMPE for the
"lower" epistemic uncertainty case
"""
GSIM_CLASS = GhofraniAtkinson2014Lower
MEAN_FILE = "GA2014/GA2014_LOWER_MEAN.csv"
STD_FILE = "GA2014/GA2014_LOWER_TOTAL.csv"
INTER_FILE = "GA2014/GA2014_LOWER_INTER.csv"
INTRA_FILE = "GA2014/GA2014_LOWER_INTRA.csv"
class GhofraniAtkinson2014CascadiaUpperTestCase(GhofraniAtkinson2014TestCase):
"""
Implements the test case for the Ghorfrani & Atkinson (2014) GMPE with the
adjustment for Cascadia and the "upper" epistemic uncertainty case
"""
GSIM_CLASS = GhofraniAtkinson2014CascadiaUpper
MEAN_FILE = "GA2014/GA2014_CASCADIA_UPPER_MEAN.csv"
STD_FILE = "GA2014/GA2014_CASCADIA_UPPER_TOTAL.csv"
INTER_FILE = "GA2014/GA2014_CASCADIA_UPPER_INTER.csv"
INTRA_FILE = "GA2014/GA2014_CASCADIA_UPPER_INTRA.csv"
class GhofraniAtkinson2014CascadiaLowerTestCase(GhofraniAtkinson2014TestCase):
"""
Implements the test case for the Ghorfrani & Atkinson (2014) GMPE with the
adjustment for Cascadia and the "lower" epistemic uncertainty case
"""
GSIM_CLASS = GhofraniAtkinson2014CascadiaLower
MEAN_FILE = "GA2014/GA2014_CASCADIA_LOWER_MEAN.csv"
STD_FILE = "GA2014/GA2014_CASCADIA_LOWER_TOTAL.csv"
INTER_FILE = "GA2014/GA2014_CASCADIA_LOWER_INTER.csv"
INTRA_FILE = "GA2014/GA2014_CASCADIA_LOWER_INTRA.csv"
| gem/oq-engine | openquake/hazardlib/tests/gsim/ghofrani_atkinson_test.py | Python | agpl-3.0 | 4,595 |
# encoding: UTF-8
module MongoMapper
module Plugins
module Associations
class BelongsToProxy < Proxy
def replace(doc)
if doc
doc.save if doc.new?
id = doc.id
end
proxy_owner[association.foreign_key] = id
reload
end
protected
def find_target
return nil if proxy_owner[association.foreign_key].nil?
klass.find_by_id(proxy_owner[association.foreign_key])
end
end
end
end
end
| anuragsolanki/ofri-Haus | vendor/gems/mongo_mapper-0.8.6/lib/mongo_mapper/plugins/associations/belongs_to_proxy.rb | Ruby | agpl-3.0 | 530 |
"""add column automatic_crawling to the user table
Revision ID: 8bf5694c0b9e
Revises: 5553a6c05fa7
Create Date: 2016-10-06 13:47:32.784711
"""
# revision identifiers, used by Alembic.
revision = '8bf5694c0b9e'
down_revision = '5553a6c05fa7'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('user', sa.Column('automatic_crawling',
sa.Boolean(), default=True))
def downgrade():
op.drop_column('user', 'automatic_crawling')
| JARR/JARR | migrations/versions/8bf5694c0b9e_add_column_automatic_crawling_to_the_.py | Python | agpl-3.0 | 543 |
// Copyright (c) 2012-present The upper.io/db authors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package sqlite // import "github.com/webx-top/db/sqlite"
import (
"database/sql"
"github.com/webx-top/db"
"github.com/webx-top/db/internal/sqladapter"
"github.com/webx-top/db/lib/sqlbuilder"
)
const sqlDriver = `sqlite`
// Adapter is the public name of the adapter.
const Adapter = sqlDriver
func init() {
sqlbuilder.RegisterAdapter(Adapter, &sqlbuilder.AdapterFuncMap{
New: New,
NewTx: NewTx,
Open: Open,
})
}
// Open stablishes a new connection with the SQL server.
func Open(settings db.ConnectionURL) (sqlbuilder.Database, error) {
d := newDatabase(settings)
if err := d.Open(settings); err != nil {
return nil, err
}
return d, nil
}
// NewTx returns a transaction session.
func NewTx(sqlTx *sql.Tx) (sqlbuilder.Tx, error) {
d := newDatabase(nil)
// Binding with sqladapter's logic.
d.BaseDatabase = sqladapter.NewBaseDatabase(d)
// Binding with sqlbuilder.
d.SQLBuilder = sqlbuilder.WithSession(d.BaseDatabase, template)
if err := d.BaseDatabase.BindTx(d.Context(), sqlTx); err != nil {
return nil, err
}
newTx := sqladapter.NewDatabaseTx(d)
return &tx{DatabaseTx: newTx}, nil
}
// New wraps the given *sql.DB session and creates a new db session.
func New(sess *sql.DB) (sqlbuilder.Database, error) {
d := newDatabase(nil)
// Binding with sqladapter's logic.
d.BaseDatabase = sqladapter.NewBaseDatabase(d)
// Binding with sqlbuilder.
d.SQLBuilder = sqlbuilder.WithSession(d.BaseDatabase, template)
if err := d.BaseDatabase.BindSession(sess); err != nil {
return nil, err
}
return d, nil
}
| admpub/nging | vendor/github.com/webx-top/db/sqlite/sqlite.go | GO | agpl-3.0 | 2,795 |
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.test import override_settings
from shuup.core.models import get_person_contact, MutableAddress, OrderLineType
from shuup.core.order_creator import OrderCreator
from shuup.testing.factories import (
get_default_payment_method, get_default_product,
get_default_shipping_method, get_default_shop, get_default_supplier,
get_initial_order_status
)
from shuup_tests.utils.basketish_order_source import BasketishOrderSource
def get_order_and_source(admin_user, product, language, language_fallback):
# create original source to tamper with
contact = get_person_contact(admin_user)
contact.language = language
contact.save()
assert contact.language == language # contact language is naive
source = BasketishOrderSource(get_default_shop())
source.status = get_initial_order_status()
source.billing_address = MutableAddress.objects.create(name="Original Billing")
source.shipping_address = MutableAddress.objects.create(name="Original Shipping")
source.customer = contact
source.payment_method = get_default_payment_method()
source.shipping_method = get_default_shipping_method()
source.add_line(
type=OrderLineType.PRODUCT,
product=product,
supplier=get_default_supplier(),
quantity=1,
base_unit_price=source.create_price(10),
)
source.add_line(
type=OrderLineType.OTHER,
quantity=1,
base_unit_price=source.create_price(10),
require_verification=True,
)
assert len(source.get_lines()) == 2
source.creator = admin_user
assert not source._language # is None because it was not directly assigned
assert source.language == language_fallback
creator = OrderCreator()
order = creator.create_order(source)
assert order.language == source.language
return order, source
@pytest.mark.django_db
@pytest.mark.parametrize("lang_code", ["en", "fi", "sv", "ja", "zh-hans", "pt-br", "it"])
def test_order_language_fallbacks(rf, admin_user, lang_code):
product = get_default_product()
with override_settings(LANGUAGE_CODE=lang_code):
languages = {
0: ("en", "en"), # English
1: ("fi", "fi"), # Finnish
2: ("bew", lang_code), # Betawi
3: ("bss", lang_code), # Akoose
4: ("en_US", lang_code), # American English
5: ("is", "is"), # Icelandic
6: ("es_419", lang_code), # Latin American Spanish
7: ("nds_NL", lang_code), # Low Saxon
8: ("arn", lang_code), # Mapuche
9: ("sv", "sv") # swedish
}
for x in range(10):
language = languages[x][0]
fallback = languages[x][1]
# print(lang_code, language, fallback)
get_order_and_source(admin_user=admin_user, product=product, language=language, language_fallback=fallback)
| suutari/shoop | shuup_tests/core/test_order_languages.py | Python | agpl-3.0 | 3,168 |
/*-----------------------------------------------------------------------------
**
** -Gozer is not Zuul-
**
** Copyright 2017 by SwordLord - the coding crew - https://www.swordlord.com/
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of the GNU Affero 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 Affero General Public License for
** more details.
**
** You should have received a copy of the GNU Affero General Public License along
** with this program. If not, see <http://www.gnu.org/licenses/>.
**
**-----------------------------------------------------------------------------
**
** $Id: GGraph.java 1170 2011-10-07 16:24:10Z LordEidi $
**
-----------------------------------------------------------------------------*/
package com.swordlord.gozer.components.generic.graph;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import com.swordlord.gozer.builder.ObjectTree;
import com.swordlord.gozer.components.generic.ObjectBase;
import com.swordlord.gozer.databinding.DataBindingContext;
import com.swordlord.gozer.databinding.DataBindingManager;
import com.swordlord.gozer.databinding.DataBindingMember;
@SuppressWarnings("serial")
public class GGraph extends ObjectBase
{
private static Log _logger = LogFactory.getLog(GGraph.class);
public static String ATTRIBUTE_BINDING_MEMBER_ROWKEY = "DataBinding_rowkey";
public static String ATTRIBUTE_BINDING_MEMBER_TARGETID = "DataBinding_targetid";
public static String ATTRIBUTE_BINDING_MEMBER_VALUE = "DataBinding_value";
public static String ATTRIBUTE_BINDING_MEMBER_COLKEY = "DataBinding_colkey";
public static String ATTRIBUTE_WIDTH = "width";
public static String ATTRIBUTE_HEIGHT = "height";
public static String ATTRIBUTE_TITLE = "title";
public static String ATTRIBUTE_SUBTITLE = "subtitle";
public static String ATTRIBUTE_LEGEND = "legend";
private static String ATTRIBUTE_CLICKABLE = "clickable";
private static String ATTRIBUTE_TARGET_CHART = "target_chart";
public static String ATTRIBUTE_ORDERING = "ordering";
public static String getObjectTag()
{
return "graph";
}
public GGraph(ObjectTree root)
{
super(root);
}
public String getOrdering()
{
return getAttribute(ATTRIBUTE_ORDERING);
}
public boolean hasOrdering()
{
return getAttribute(ATTRIBUTE_ORDERING) != null;
}
// TODO: make the drawing supplier configurable from the .gozer file
public DefaultDrawingSupplier getDrawingSupplier()
{
return new BLAFDrawingSupplier();
}
public int getWidth(int nDefault)
{
return getAttributeAsInt(ATTRIBUTE_WIDTH, nDefault);
}
public int getHeight(int nDefault)
{
return getAttributeAsInt(ATTRIBUTE_HEIGHT, nDefault);
}
public PlotOrientation getAttributeAsPlotOrientation(String strAttribute, PlotOrientation nDefault)
{
String attributes = getAttribute(strAttribute);
if (attributes == null)
{
return nDefault;
} else
{
if (attributes.equals("horizontal"))
{
return PlotOrientation.HORIZONTAL;
} else if (attributes.equals("vertical"))
{
return PlotOrientation.VERTICAL;
} else
{
_logger.error("PlotOrientation not allowed, only the following values are allowed : horizontal, vertical");
return null;
}
}
}
public DataBindingMember getDataBindingMemberRowKey()
{
String strBindingMember = getAttribute(ATTRIBUTE_BINDING_MEMBER_ROWKEY);
DataBindingMember dbm = new DataBindingMember(strBindingMember);
return dbm;
}
public DataBindingMember getDataBindingMemberTargetId()
{
String strBindingMember = getAttribute(ATTRIBUTE_BINDING_MEMBER_TARGETID);
if (strBindingMember == null)
{
return null;
} else
{
DataBindingMember dbm = new DataBindingMember(strBindingMember);
return dbm;
}
}
public DataBindingMember getDataBindingMemberColKey()
{
String strBindingMember = getAttribute(ATTRIBUTE_BINDING_MEMBER_COLKEY);
DataBindingMember dbm = new DataBindingMember(strBindingMember);
return dbm;
}
public DataBindingMember getDataBindingMemberValue()
{
String strBindingMember = getAttribute(ATTRIBUTE_BINDING_MEMBER_VALUE);
DataBindingMember dbm = new DataBindingMember(strBindingMember);
return dbm;
}
public DataBindingManager getDataBindingManager()
{
DataBindingMember dataBindingMember = getDataBindingMemberRowKey();
DataBindingContext dbc = _root.getDataBindingContext();
return dbc.getDataBindingManager(dataBindingMember);
}
/**
* The chart title (null permitted).
*
* @return the chart title.
*/
public String getTitle()
{
return getAttribute(ATTRIBUTE_TITLE);
}
/**
* The chart sub-title (null permitted).
*
* @return the chart sub-title.
*/
public String getSubTitle()
{
return getAttribute(ATTRIBUTE_SUBTITLE);
}
/**
* A flag specifying whether or not a legend is required.
*
* @return a flag specifying whether or not a legend is required
*/
public boolean getLegend()
{
return getAttributeAsBoolean(ATTRIBUTE_LEGEND, true);
}
/**
* Is the chart clickable ? If yes, then you can call a target chart
*
* @return
*/
public boolean isClickable()
{
return this.getAttributeAsBoolean(ATTRIBUTE_CLICKABLE, false);
}
public String getTargetChart()
{
return getAttribute(ATTRIBUTE_TARGET_CHART);
}
}
| swordlordcodingcrew/gozer | src/main/java/com/swordlord/gozer/components/generic/graph/GGraph.java | Java | agpl-3.0 | 5,730 |
# Copyright 2012 John Sullivan
# Copyright 2012 Other contributers as noted in the CONTRIBUTERS file
#
# This file is part of Galah.
#
# Galah is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Galah is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Galah. If not, see <http://www.gnu.org/licenses/>.
# Snippet below derived from code published by Matteo Dell'Amico and published
# under the unlicense.
# see: https://gist.github.com/4451520
# If you wish to use this file in your own project, go to the link above, DO NOT
# use the code within this file verbatim unless you are prepared to work under
# the restrictions of the AGPLv3, as this file is licenced under it.
from heapq import heapify, heappush, heappop
from collections import namedtuple
PriorityValuePair = namedtuple("PriorityValuePair", ["priority", "value"])
class PriorityDict(dict):
"""Dictionary that can be used as a priority queue.
Keys of the dictionary are items to be put into the queue, and values
are their respective priorities. All dictionary methods work as expected.
The advantage over a standard heapq-based priority queue is
that priorities of items can be efficiently updated (amortized O(1))
using code as 'thedict[item] = new_priority.'
The 'smallest' method can be used to return the object with lowest
priority, and 'pop_smallest' also removes it.
The 'sorted_iter' method provides a destructive sorted iterator.
"""
def __init__(self, *args, **kwargs):
super(PriorityDict, self).__init__(*args, **kwargs)
self._rebuild_heap()
def _rebuild_heap(self):
self._heap = [(v, k) for k, v in self.iteritems()]
heapify(self._heap)
def smallest(self):
"""
Return the item with the lowest priority as a named tuple
(priority, value).
Raises IndexError if the object is empty.
"""
heap = self._heap
v, k = heap[0]
while k not in self or self[k] != v:
heappop(heap)
v, k = heap[0]
return PriorityValuePair(v, k)
def pop_smallest(self):
"""
Return the item as a named tuple (priority, value) with the lowest
priority and remove it.
Raises IndexError if the object is empty.
"""
heap = self._heap
v, k = heappop(heap)
while k not in self or self[k] != v:
v, k = heappop(heap)
del self[k]
return PriorityValuePair(v, k)
def __setitem__(self, key, val):
# We are not going to remove the previous value from the heap,
# since this would have a cost O(n).
super(PriorityDict, self).__setitem__(key, val)
if len(self._heap) < 2 * len(self):
heappush(self._heap, (val, key))
else:
# When the heap grows larger than 2 * len(self), we rebuild it
# from scratch to avoid wasting too much memory.
self._rebuild_heap()
def setdefault(self, key, val):
if key not in self:
self[key] = val
return val
return self[key]
def update(self, *args, **kwargs):
# Reimplementing dict.update is tricky -- see e.g.
# http://mail.python.org/pipermail/python-ideas/2007-May/000744.html
# We just rebuild the heap from scratch after passing to super.
super(PriorityDict, self).update(*args, **kwargs)
self._rebuild_heap()
def sorted_iter(self):
"""Sorted iterator of the priority dictionary items.
Beware: this will destroy elements as they are returned.
"""
while self:
yield self.pop_smallest() | tugluck/galah | galah/base/prioritydict.py | Python | agpl-3.0 | 4,196 |
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Joas Schilling <coding@schilljs.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Repair;
use Doctrine\DBAL\Exception\DriverException;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\ILogger;
use OCP\Migration\IOutput;
use OCP\Migration\IRepairStep;
class Collation implements IRepairStep {
/** @var IConfig */
protected $config;
/** @var ILogger */
protected $logger;
/** @var IDBConnection */
protected $connection;
/** @var bool */
protected $ignoreFailures;
/**
* @param IConfig $config
* @param ILogger $logger
* @param IDBConnection $connection
* @param bool $ignoreFailures
*/
public function __construct(IConfig $config, ILogger $logger, IDBConnection $connection, $ignoreFailures) {
$this->connection = $connection;
$this->config = $config;
$this->logger = $logger;
$this->ignoreFailures = $ignoreFailures;
}
public function getName() {
return 'Repair MySQL collation';
}
/**
* Fix mime types
*/
public function run(IOutput $output) {
if (!$this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
$output->info('Not a mysql database -> nothing to do');
return;
}
$characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
$tables = $this->getAllNonUTF8BinTables($this->connection);
foreach ($tables as $table) {
$output->info("Change row format for $table ...");
$query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT = DYNAMIC;');
try {
$query->execute();
} catch (DriverException $e) {
// Just log this
$this->logger->logException($e);
if (!$this->ignoreFailures) {
throw $e;
}
}
$output->info("Change collation for $table ...");
if ($characterSet === 'utf8mb4') {
// need to set row compression first
$query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT=COMPRESSED;');
$query->execute();
}
$query = $this->connection->prepare('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET ' . $characterSet . ' COLLATE ' . $characterSet . '_bin;');
try {
$query->execute();
} catch (DriverException $e) {
// Just log this
$this->logger->logException($e);
if (!$this->ignoreFailures) {
throw $e;
}
}
}
if (empty($tables)) {
$output->info('All tables already have the correct collation -> nothing to do');
}
}
/**
* @param IDBConnection $connection
* @return string[]
*/
protected function getAllNonUTF8BinTables(IDBConnection $connection) {
$dbName = $this->config->getSystemValue("dbname");
$characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
// fetch tables by columns
$statement = $connection->executeQuery(
"SELECT DISTINCT(TABLE_NAME) AS `table`" .
" FROM INFORMATION_SCHEMA . COLUMNS" .
" WHERE TABLE_SCHEMA = ?" .
" AND (COLLATION_NAME <> '" . $characterSet . "_bin' OR CHARACTER_SET_NAME <> '" . $characterSet . "')" .
" AND TABLE_NAME LIKE \"*PREFIX*%\"",
array($dbName)
);
$rows = $statement->fetchAll();
$result = [];
foreach ($rows as $row) {
$result[$row['table']] = true;
}
// fetch tables by collation
$statement = $connection->executeQuery(
"SELECT DISTINCT(TABLE_NAME) AS `table`" .
" FROM INFORMATION_SCHEMA . TABLES" .
" WHERE TABLE_SCHEMA = ?" .
" AND TABLE_COLLATION <> '" . $characterSet . "_bin'" .
" AND TABLE_NAME LIKE \"*PREFIX*%\"",
[$dbName]
);
$rows = $statement->fetchAll();
foreach ($rows as $row) {
$result[$row['table']] = true;
}
return array_keys($result);
}
}
| michaelletzgus/nextcloud-server | lib/private/Repair/Collation.php | PHP | agpl-3.0 | 4,464 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.krad.util.documentserializer;
import java.util.ArrayList;
import java.util.List;
/**
* This object keeps track of most of the open tags while a document is serialized. Note that instances of this class
* may not necessarily hold all open tags of a document while it is being serialized. For example, tags enclosing list elements
* and map entries are not contained within here. See DocumentSerializerServiceImpl, in krad-service-impl, to determine when
* this object's state is modified.
*
* This class's manipulators behave much like a stack, but it has random access characteristics like an array.
*/
public class SerializationState {
protected class SerializationPropertyElement {
private String elementName;
private PropertyType propertyType;
public SerializationPropertyElement(String elementName, PropertyType propertyType) {
this.elementName = elementName;
this.propertyType = propertyType;
}
public String getElementName() {
return this.elementName;
}
public PropertyType getPropertyType() {
return this.propertyType;
}
}
private List<SerializationPropertyElement> pathElements;
public SerializationState(){
pathElements = new ArrayList<SerializationPropertyElement>();
}
/**
* Creates a new SerializationState that is a copy of the given state
*
* @param stateToCopy the state to copy
*/
public SerializationState(SerializationState stateToCopy) {
this();
this.pathElements.addAll(stateToCopy.pathElements);
}
/**
* The number of property elements in this state object.
*
* @return
*/
public int numPropertyElements() {
return pathElements.size();
}
/**
* Adds an additional state element into this object.
*
* @param elementName
* @param propertyType the type of the property when it was serialized
*/
public void addSerializedProperty(String elementName, PropertyType propertyType) {
SerializationPropertyElement serializationPropertyElement = new SerializationPropertyElement(elementName, propertyType);
pathElements.add(serializationPropertyElement);
}
/**
* Removes the last added serialized property
*
*/
public void removeSerializedProperty() {
pathElements.remove(pathElements.size() - 1);
}
/**
* Retrieves the element name of the state element. A parameter value of 0 represents the first element that was added
* by calling {@link #addSerializedProperty(String, PropertyType)} that hasn't been removed, and a value of
* {@link #numPropertyElements()} - 1 represents the element last added that hasn't been removed.
*
* @param propertyIndex most be between 0 and the value returned by {@link #numPropertyElements()} - 1
* @return
*/
public String getElementName(int propertyIndex) {
return pathElements.get(propertyIndex).getElementName();
}
/**
* Retrieves the property type of the state element. A parameter value of 0 represents the first element that was added
* by calling {@link #addSerializedProperty(String, PropertyType)} that hasn't been removed, and a value of
* {@link #numPropertyElements()} - 1 represents the element last added that hasn't been removed.
*
* @param propertyIndex most be between 0 and the value returned by {@link #numPropertyElements()} - 1
* @return
*/
public PropertyType getPropertyType(int propertyIndex) {
return pathElements.get(propertyIndex).getPropertyType();
}
}
| quikkian-ua-devops/will-financials | kfs-kns/src/main/java/org/kuali/kfs/krad/util/documentserializer/SerializationState.java | Java | agpl-3.0 | 4,510 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ar.document.validation.impl;
import org.kuali.kfs.kns.document.MaintenanceDocument;
import org.kuali.kfs.kns.rules.PromptBeforeValidationBase;
import org.kuali.kfs.krad.document.Document;
import org.kuali.kfs.krad.exception.UnknownDocumentIdException;
import org.kuali.kfs.krad.service.DocumentService;
import org.kuali.kfs.krad.util.ObjectUtils;
import org.kuali.kfs.module.ar.businessobject.InvoiceRecurrence;
import org.kuali.kfs.module.ar.document.CustomerInvoiceDocument;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.util.KfsDateUtils;
import org.kuali.rice.kew.api.exception.WorkflowException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Calendar;
public class InvoiceRecurrencePreRules extends PromptBeforeValidationBase {
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(InvoiceRecurrencePreRules.class);
/**
* @see org.kuali.rice.kns.rules.PromptBeforeValidationBase#doRules(org.kuali.rice.krad.document.Document)
*/
@Override
public boolean doPrompts(Document document) {
boolean preRulesOK = true;
preRulesOK &= setCustomerNumberIfInvoiceIsEntered(document);
preRulesOK &= setEndDateIfTotalRecurrenceNumberIsEntered(document);
preRulesOK &= setTotalRecurrenceNumberIfEndDateIsEntered(document);
return preRulesOK;
}
/**
* @param document the maintenance document
* @return
*/
protected boolean setCustomerNumberIfInvoiceIsEntered(Document document) {
MaintenanceDocument maintenanceDocument = (MaintenanceDocument) document;
InvoiceRecurrence newInvoiceRecurrence = (InvoiceRecurrence) maintenanceDocument.getNewMaintainableObject().getBusinessObject();
if (ObjectUtils.isNull(newInvoiceRecurrence.getInvoiceNumber()) ||
ObjectUtils.isNotNull(newInvoiceRecurrence.getCustomerNumber())) {
return true;
}
try {
if (SpringContext.getBean(DocumentService.class).documentExists(newInvoiceRecurrence.getInvoiceNumber())) {
CustomerInvoiceDocument customerInvoiceDocument = (CustomerInvoiceDocument) SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(newInvoiceRecurrence.getInvoiceNumber());
newInvoiceRecurrence.setCustomerNumber(customerInvoiceDocument.getCustomer().getCustomerNumber());
}
} catch (WorkflowException ex) {
LOG.error("Unable to retrieve document " + newInvoiceRecurrence.getInvoiceNumber() + " from workflow.", ex);
} catch (UnknownDocumentIdException ex) {
LOG.error("Document " + newInvoiceRecurrence.getInvoiceNumber() + " does not exist.");
}
return true;
}
/**
* This method checks if there is another customer with the same name and generates yes/no question
*
* @param document the maintenance document
* @return
*/
protected boolean setEndDateIfTotalRecurrenceNumberIsEntered(Document document) {
MaintenanceDocument maintenanceDocument = (MaintenanceDocument) document;
InvoiceRecurrence newInvoiceRecurrence = (InvoiceRecurrence) maintenanceDocument.getNewMaintainableObject().getBusinessObject();
if (ObjectUtils.isNull(newInvoiceRecurrence.getDocumentTotalRecurrenceNumber())) {
return true;
}
if (ObjectUtils.isNotNull(newInvoiceRecurrence.getDocumentRecurrenceEndDate()) && ObjectUtils.isNotNull(newInvoiceRecurrence.getDocumentTotalRecurrenceNumber())) {
return true;
}
Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(new Timestamp(newInvoiceRecurrence.getDocumentRecurrenceBeginDate().getTime()));
Calendar endCalendar = Calendar.getInstance();
endCalendar = beginCalendar;
int addCounter = 0;
Integer documentTotalRecurrenceNumber = newInvoiceRecurrence.getDocumentTotalRecurrenceNumber();
String intervalCode = newInvoiceRecurrence.getDocumentRecurrenceIntervalCode();
if (intervalCode.equals("M")) {
addCounter = -1;
addCounter += documentTotalRecurrenceNumber * 1;
}
if (intervalCode.equals("Q")) {
addCounter = -3;
addCounter += documentTotalRecurrenceNumber * 3;
}
endCalendar.add(Calendar.MONTH, addCounter);
newInvoiceRecurrence.setDocumentRecurrenceEndDate(KfsDateUtils.convertToSqlDate(endCalendar.getTime()));
return true;
}
/**
* This method calculates the total number of recurrences when a begin date and end date is entered.
*
* @param document the maintenance document
* @return
*/
protected boolean setTotalRecurrenceNumberIfEndDateIsEntered(Document document) {
MaintenanceDocument maintenanceDocument = (MaintenanceDocument) document;
InvoiceRecurrence newInvoiceRecurrence = (InvoiceRecurrence) maintenanceDocument.getNewMaintainableObject().getBusinessObject();
if (ObjectUtils.isNull(newInvoiceRecurrence.getDocumentRecurrenceEndDate())) {
return true;
}
if (ObjectUtils.isNotNull(newInvoiceRecurrence.getDocumentRecurrenceEndDate()) && ObjectUtils.isNotNull(newInvoiceRecurrence.getDocumentTotalRecurrenceNumber())) {
return true;
}
Calendar beginCalendar = Calendar.getInstance();
/*
* beginCalendar.setTime(new Timestamp(newInvoiceRecurrence.getDocumentRecurrenceBeginDate().getTime()));
*/
beginCalendar.setTime(newInvoiceRecurrence.getDocumentRecurrenceBeginDate());
Date beginDate = newInvoiceRecurrence.getDocumentRecurrenceBeginDate();
Calendar endCalendar = Calendar.getInstance();
/*
* endCalendar.setTime(new Timestamp(newInvoiceRecurrence.getDocumentRecurrenceEndDate().getTime()));
*/
endCalendar.setTime(newInvoiceRecurrence.getDocumentRecurrenceEndDate());
Date endDate = newInvoiceRecurrence.getDocumentRecurrenceEndDate();
Calendar nextCalendar = Calendar.getInstance();
Date nextDate = beginDate;
int totalRecurrences = 0;
int addCounter = 0;
String intervalCode = newInvoiceRecurrence.getDocumentRecurrenceIntervalCode();
if (intervalCode.equals("M")) {
addCounter = 1;
}
if (intervalCode.equals("Q")) {
addCounter = 3;
}
/* perform this loop while begin_date is less than or equal to end_date */
while (!(beginDate.after(endDate))) {
beginCalendar.setTime(beginDate);
beginCalendar.add(Calendar.MONTH, addCounter);
beginDate = KfsDateUtils.convertToSqlDate(beginCalendar.getTime());
totalRecurrences++;
nextDate = beginDate;
nextCalendar.setTime(nextDate);
nextCalendar.add(Calendar.MONTH, addCounter);
nextDate = KfsDateUtils.convertToSqlDate(nextCalendar.getTime());
if (endDate.after(beginDate) && endDate.before(nextDate)) {
totalRecurrences++;
break;
}
}
if (totalRecurrences > 0) {
newInvoiceRecurrence.setDocumentTotalRecurrenceNumber(totalRecurrences);
}
return true;
}
}
| quikkian-ua-devops/will-financials | kfs-ar/src/main/java/org/kuali/kfs/module/ar/document/validation/impl/InvoiceRecurrencePreRules.java | Java | agpl-3.0 | 8,173 |
/* -*-mode:java; c-basic-offset:2; -*- */
/* JSchSession
* Copyright (C) 2002,2007 ymnk, JCraft,Inc.
*
* Written by: ymnk<ymnk@jcaft.com>
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library 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 Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package com.jcraft.jcterm;
import com.jcraft.jsch.*;
import java.util.concurrent.ConcurrentHashMap;
public final class JSchSession {
private static final java.util.Map pool = new ConcurrentHashMap();
private static JSch jsch = null;
private static SessionFactory sessionFactory = null;
private String key = null;
private Session session = null;
private JSchSession(Session session, String key) {
this.session = session;
this.key = key;
}
public static JSchSession getSession(String username, String password,
String hostname, int port, UserInfo userinfo, Proxy proxy)
throws JSchException {
String key = getPoolKey(username, hostname, port);
try {
JSchSession jschSession = (JSchSession) pool.get(key);
if (jschSession != null && !jschSession.getSession().isConnected()) {
pool.remove(key);
jschSession = null;
}
if (jschSession == null) {
Session session = null;
try {
session = createSession(username, password, hostname, port, userinfo,
proxy);
} catch (JSchException e) {
if (isAuthenticationFailure(e)) {
session = createSession(username, password, hostname, port, userinfo,
proxy);
} else {
throw e;
}
}
if (session == null)
throw new JSchException("The JSch service is not available");
JSchSession schSession = new JSchSession(session, key);
pool.put(key, schSession);
return schSession;
}
return jschSession;
} catch (JSchException e) {
pool.remove(key);
throw e;
}
}
private static synchronized JSch getJSch() {
if (jsch == null) {
jsch = new JSch();
}
return jsch;
}
private static Session createSession(String username, String password,
String hostname, int port, UserInfo userinfo, Proxy proxy)
throws JSchException {
Session session = null;
if (sessionFactory == null) {
session = getJSch().getSession(username, hostname, port);
} else {
session = sessionFactory.getSession(username, hostname, port);
}
session.setTimeout(60000);
if (password != null)
session.setPassword(password);
session.setUserInfo(userinfo);
if (proxy != null)
session.setProxy(proxy);
session.connect(60000);
session.setServerAliveInterval(60000);
return session;
}
private static String getPoolKey(String username, String hostname, int port) {
return username + '@' + hostname + ':' + port;
}
private static boolean isAuthenticationFailure(JSchException ee) {
return ee.getMessage().equals("Auth fail");
}
public static void setSessionFactory(SessionFactory sf) {
sessionFactory = sf;
}
static void useSSHAgent(boolean use) {
IdentityRepository ir = null;
if (use) {
try {
Class c = Class.forName("com.jcraft.jcterm.JCTermIdentityRepository");
ir = (IdentityRepository) (c.getConstructor().newInstance());
} catch (NoClassDefFoundError | Exception e) {
System.err.println(e);
}
if (ir == null) {
System.err.println("JCTermIdentityRepository is not available.");
}
}
if (ir != null)
getJSch().setIdentityRepository(ir);
}
public Session getSession() {
return session;
}
public void dispose() {
if (session.isConnected()) {
session.disconnect();
}
pool.remove(key);
}
interface SessionFactory {
Session getSession(String username, String hostname, int port)
;
}
}
| automenta/narchy | ui/src/main/java/com/jcraft/jcterm/JSchSession.java | Java | agpl-3.0 | 5,095 |
#region
using System;
using System.Collections.Generic;
using System.IO;
using common;
using Ionic.Zlib;
using wServer.realm.entities;
using wServer.realm.entities.merchant;
#endregion
namespace wServer.realm.terrain
{
public enum TileRegion : byte
{
None,
Spawn,
Realm_Portals,
Store_1,
Store_2,
Store_3,
Store_4,
Store_5,
Store_6,
Vault,
Loot,
Defender,
Hallway,
Enemy,
Hallway_1,
Hallway_2,
Hallway_3,
Store_7,
Store_8,
Store_9,
Gifting_Chest,
Store_10,
Store_11,
Store_12,
Store_13,
Store_14,
Store_15,
Store_16,
Store_17,
Store_18,
Store_19,
Store_20,
Store_21,
Store_22,
Store_23,
Store_24,
PetRegion,
Outside_Arena,
Item_Spawn_Point,
Arena_Central_Spawn,
Arena_Edge_Spawn
}
public enum WmapTerrain : byte
{
None,
Mountains,
HighSand,
HighPlains,
HighForest,
MidSand,
MidPlains,
MidForest,
LowSand,
LowPlains,
LowForest,
ShoreSand,
ShorePlains,
}
public struct WmapTile
{
public byte Elevation;
public string Name;
public int ObjId;
public ushort ObjType;
public TileRegion Region;
public WmapTerrain Terrain;
public byte TileId;
public byte UpdateCount;
public ObjectDef ToDef(int x, int y)
{
List<KeyValuePair<StatsType, object>> stats = new List<KeyValuePair<StatsType, object>>();
if (!string.IsNullOrEmpty(Name))
foreach (string item in Name.Split(';'))
{
string[] kv = item.Split(':');
switch (kv[0])
{
case "name":
stats.Add(new KeyValuePair<StatsType, object>(StatsType.Name, kv[1]));
break;
case "size":
stats.Add(new KeyValuePair<StatsType, object>(StatsType.Size, Utils.FromString(kv[1])));
break;
case "eff":
stats.Add(new KeyValuePair<StatsType, object>(StatsType.Effects, Utils.FromString(kv[1])));
break;
case "conn":
stats.Add(new KeyValuePair<StatsType, object>(StatsType.ObjectConnection,
Utils.FromString(kv[1])));
break;
case "hp":
stats.Add(new KeyValuePair<StatsType, object>(StatsType.HP, Utils.FromString(kv[1])));
break;
case "mcost":
stats.Add(new KeyValuePair<StatsType, object>(StatsType.SellablePrice,
Utils.FromString(kv[1])));
break;
case "mcur":
stats.Add(new KeyValuePair<StatsType, object>(StatsType.SellablePriceCurrency,
Utils.FromString(kv[1])));
break;
//case "mtype":
// stats.Add(new KeyValuePair<StatsType, object>(StatsType.MerchantMerchandiseType, Utils.FromString(kv[1]))); break;
//case "mcount":
// stats.Add(new KeyValuePair<StatsType, object>(StatsType.MerchantRemainingCount, Utils.FromString(kv[1]))); break;
//case "mtime":
// stats.Add(new KeyValuePair<StatsType, object>(StatsType.MerchantRemainingMinute, Utils.FromString(kv[1]))); break;
//case "nstar":
// entity.Stats[StatsType.NameChangerStar] = Utils.FromString(kv[1]); break;
}
}
return new ObjectDef
{
ObjectType = ObjType,
Stats = new ObjectStats
{
Id = ObjId,
Position = new Position
{
X = x + 0.5f,
Y = y + 0.5f
},
Stats = stats.ToArray()
}
};
}
public WmapTile Clone()
{
return new WmapTile
{
UpdateCount = (byte) (UpdateCount + 1),
TileId = TileId,
Name = Name,
ObjType = ObjType,
Terrain = Terrain,
Region = Region,
ObjId = ObjId,
};
}
}
public class Wmap
{
private readonly XmlData data;
private Tuple<IntPoint, ushort, string>[] entities;
private WmapTile[,] tiles;
public Wmap(XmlData data)
{
this.data = data;
}
public int Width { get; set; }
public int Height { get; set; }
public WmapTile this[int x, int y]
{
get { return tiles[x, y]; }
set { tiles[x, y] = value; }
}
public int Load(Stream stream, int idBase)
{
int ver = stream.ReadByte();
using (BinaryReader rdr = new BinaryReader(new ZlibStream(stream, CompressionMode.Decompress)))
{
if (ver == 0) return LoadV0(rdr, idBase);
if (ver == 1) return LoadV1(rdr, idBase);
if (ver == 2) return LoadV2(rdr, idBase);
throw new NotSupportedException("WMap version " + ver);
}
}
private int LoadV0(BinaryReader reader, int idBase)
{
List<WmapTile> dict = new List<WmapTile>();
ushort c = (ushort)reader.ReadInt16();
for (ushort i = 0; i < c; i++)
{
WmapTile tile = new WmapTile();
tile.TileId = (byte) reader.ReadInt16();
string obj = reader.ReadString();
tile.ObjType = string.IsNullOrEmpty(obj) ? (ushort) 0 : data.IdToObjectType[obj];
tile.Name = reader.ReadString();
tile.Terrain = (WmapTerrain) reader.ReadByte();
tile.Region = (TileRegion) reader.ReadByte();
dict.Add(tile);
}
Width = reader.ReadInt32();
Height = reader.ReadInt32();
tiles = new WmapTile[Width, Height];
int enCount = 0;
List<Tuple<IntPoint, ushort, string>> entities = new List<Tuple<IntPoint, ushort, string>>();
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
WmapTile tile = dict[reader.ReadInt16()];
tile.UpdateCount = 1;
ObjectDesc desc;
if (tile.ObjType != 0 &&
(!data.ObjectDescs.TryGetValue(tile.ObjType, out desc) ||
!desc.Static || desc.Enemy))
{
entities.Add(new Tuple<IntPoint, ushort, string>(new IntPoint(x, y), tile.ObjType, tile.Name));
tile.ObjType = 0;
}
if (tile.ObjType != 0)
{
enCount++;
tile.ObjId = idBase + enCount;
}
tiles[x, y] = tile;
}
this.entities = entities.ToArray();
return enCount;
}
private int LoadV1(BinaryReader reader, int idBase)
{
List<WmapTile> dict = new List<WmapTile>();
ushort c = (ushort)reader.ReadInt16();
for (ushort i = 0; i < c; i++)
{
WmapTile tile = new WmapTile();
tile.TileId = (byte) reader.ReadInt16();
string obj = reader.ReadString();
tile.ObjType = string.IsNullOrEmpty(obj) ? (ushort) 0 : data.IdToObjectType[obj];
tile.Name = reader.ReadString();
tile.Terrain = (WmapTerrain) reader.ReadByte();
tile.Region = (TileRegion) reader.ReadByte();
tile.Elevation = reader.ReadByte();
dict.Add(tile);
}
Width = reader.ReadInt32();
Height = reader.ReadInt32();
tiles = new WmapTile[Width, Height];
int enCount = 0;
List<Tuple<IntPoint, ushort, string>> entities = new List<Tuple<IntPoint, ushort, string>>();
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
WmapTile tile = dict[reader.ReadInt16()];
tile.UpdateCount = 1;
ObjectDesc desc;
if (tile.ObjType != 0 &&
(!data.ObjectDescs.TryGetValue(tile.ObjType, out desc) ||
!desc.Static || desc.Enemy))
{
entities.Add(new Tuple<IntPoint, ushort, string>(new IntPoint(x, y), tile.ObjType, tile.Name));
tile.ObjType = 0;
}
if (tile.ObjType != 0)
{
enCount++;
tile.ObjId = idBase + enCount;
}
tiles[x, y] = tile;
}
this.entities = entities.ToArray();
return enCount;
}
private int LoadV2(BinaryReader reader, int idBase)
{
List<WmapTile> dict = new List<WmapTile>();
ushort c = (ushort)reader.ReadInt16();
for (ushort i = 0; i < c; i++)
{
WmapTile tile = new WmapTile();
tile.TileId = (byte) reader.ReadInt16();
string obj = reader.ReadString();
tile.ObjType = string.IsNullOrEmpty(obj) ? (ushort) 0 : data.IdToObjectType[obj];
tile.Name = reader.ReadString();
tile.Terrain = (WmapTerrain) reader.ReadByte();
tile.Region = (TileRegion) reader.ReadByte();
dict.Add(tile);
}
Width = reader.ReadInt32();
Height = reader.ReadInt32();
tiles = new WmapTile[Width, Height];
int enCount = 0;
List<Tuple<IntPoint, ushort, string>> entities = new List<Tuple<IntPoint, ushort, string>>();
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
WmapTile tile = dict[reader.ReadInt16()];
tile.UpdateCount = 1;
tile.Elevation = reader.ReadByte();
ObjectDesc desc;
if (tile.ObjType != 0 &&
(!data.ObjectDescs.TryGetValue(tile.ObjType, out desc) ||
!desc.Static || desc.Enemy))
{
entities.Add(new Tuple<IntPoint, ushort, string>(new IntPoint(x, y), tile.ObjType, tile.Name));
tile.ObjType = 0;
}
if (tile.ObjType != 0)
{
enCount++;
tile.ObjId = idBase + enCount;
}
tiles[x, y] = tile;
}
this.entities = entities.ToArray();
return enCount;
}
public IEnumerable<Entity> InstantiateEntities(RealmManager manager)
{
foreach (Tuple<IntPoint, ushort, string> i in entities)
{
Entity entity = Entity.Resolve(manager, i.Item2);
entity.Move(i.Item1.X + 0.5f, i.Item1.Y + 0.5f);
if (i.Item3 != null)
foreach (string item in i.Item3.Split(';'))
{
string[] kv = item.Split(':');
switch (kv[0])
{
case "name":
entity.Name = kv[1];
break;
case "size":
entity.Size = Utils.FromString(kv[1]);
break;
case "eff":
entity.ConditionEffects = (ConditionEffects) Utils.FromString(kv[1]);
break;
case "conn":
(entity as ConnectedObject).Connection =
ConnectionInfo.Infos[(uint) Utils.FromString(kv[1])];
break;
case "mtype":
(entity as Merchants).Custom = true;
(entity as Merchants).MType = Utils.FromString(kv[1]);
break;
//case "mcount":
// entity.Stats[StatsType.MerchantRemainingCount] = Utils.FromString(kv[1]); break; NOT NEEDED FOR NOW
//case "mtime":
// entity.Stats[StatsType.MerchantRemainingMinute] = Utils.FromString(kv[1]); break;
case "mcost":
(entity as SellableObject).Price = Utils.FromString(kv[1]);
break;
case "mcur":
(entity as SellableObject).Currency = (CurrencyType) Utils.FromString(kv[1]);
break;
//case "nstar":
// entity.Stats[StatsType.NameChangerStar] = Utils.FromString(kv[1]); break;
}
}
yield return entity;
}
}
}
} | GhostMaree/fsod_redis | wServer/realm/terrain/Wmap.cs | C# | agpl-3.0 | 14,367 |
@nantel.java.annotations.NonNullByDefault
package nantel.java.boulder.models.matrix; | hiveship/BoulderDash | src/main/java/nantel/java/boulder/models/matrix/package-info.java | Java | agpl-3.0 | 84 |
require 'rails_helper'
describe LocalesController, type: :controller do
describe 'PUT #update' do
it 'sets the locale session if valdi' do
put :update, params: { locale: 'es' }
expect(session[:locale]).to eq('es')
expect(response).to redirect_to root_path
end
it 'does nothing if invalid locale' do
put :update, params: { locale: 'xx' }
expect(session[:locale]).to be_nil
expect(response).to redirect_to root_path
end
end
end
| Codeminer42/cm42-central | spec/controllers/locales_controller_spec.rb | Ruby | agpl-3.0 | 484 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) Open Solutions Finland 2013.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name" : "Delivery date to order line",
"version" : "1.0",
"author" : "Open Solutions Finland",
"description" : """
""",
"website" : "http://www.opensolutions.fi",
"depends" : ["base","product","sale"],
"category" : "Generic Modules",
"init_xml" : [],
"demo_xml" : [],
"data" : [
'sale_order_line_view.xml'
],
'test': [
],
'installable': True,
'active': False,
'certificate': '',
}
| OpenSolutionsFinland/deliver_date | __openerp__.py | Python | agpl-3.0 | 1,459 |
<?php
namespace NetBull\CoreBundle\Utils;
// original source: http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/
/*
The MIT License (MIT)
Copyright (c) 2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// ORIGINAL NOTES
//
// Thanks to http://www.eval.ca/articles/php-pluralize (MIT license)
// http://dev.rubyonrails.org/browser/trunk/activesupport/lib/active_support/inflections.rb (MIT license)
// http://www.fortunecity.com/bally/durrus/153/gramch13.html
// http://www2.gsu.edu/~wwwesl/egw/crump.htm
//
// Changes (12/17/07)
// Major changes
// --
// Fixed irregular noun algorithm to use regular expressions just like the original Ruby source.
// (this allows for things like fireman -> firemen
// Fixed the order of the singular array, which was backwards.
//
// Minor changes
// --
// Removed incorrect pluralization rule for /([^aeiouy]|qu)ies$/ => $1y
// Expanded on the list of exceptions for *o -> *oes, and removed rule for buffalo -> buffaloes
// Removed dangerous singularization rule for /([^f])ves$/ => $1fe
// Added more specific rules for singularizing lives, wives, knives, sheaves, loaves, and leaves and thieves
// Added exception to /(us)es$/ => $1 rule for houses => house and blouses => blouse
// Added excpetions for feet, geese and teeth
// Added rule for deer -> deer
// Changes:
// Removed rule for virus -> viri
// Added rule for potato -> potatoes
// Added rule for *us -> *uses
class Inflect
{
public static $plural = [
'/(quiz)$/i' => "$1zes",
'/^(ox)$/i' => "$1en",
'/([m|l])ouse$/i' => "$1ice",
'/(matr|vert|ind)ix|ex$/i' => "$1ices",
'/(x|ch|ss|sh)$/i' => "$1es",
'/([^aeiouy]|qu)y$/i' => "$1ies",
'/(hive)$/i' => "$1s",
'/(?:([^f])fe|([lr])f)$/i' => "$1$2ves",
'/(shea|lea|loa|thie)f$/i' => "$1ves",
'/sis$/i' => "ses",
'/([ti])um$/i' => "$1a",
'/(tomat|potat|ech|her|vet)o$/i'=> "$1oes",
'/(bu)s$/i' => "$1ses",
'/(alias)$/i' => "$1es",
'/(octop)us$/i' => "$1i",
'/(ax|test)is$/i' => "$1es",
'/(us)$/i' => "$1es",
'/s$/i' => "s",
'/$/' => "s",
];
public static $singular = [
'/(quiz)zes$/i' => "$1",
'/(matr)ices$/i' => "$1ix",
'/(vert|ind)ices$/i' => "$1ex",
'/^(ox)en$/i' => "$1",
'/(alias)es$/i' => "$1",
'/(octop|vir)i$/i' => "$1us",
'/(cris|ax|test)es$/i' => "$1is",
'/(shoe)s$/i' => "$1",
'/(o)es$/i' => "$1",
'/(bus)es$/i' => "$1",
'/([m|l])ice$/i' => "$1ouse",
'/(x|ch|ss|sh)es$/i' => "$1",
'/(m)ovies$/i' => "$1ovie",
'/(s)eries$/i' => "$1eries",
'/([^aeiouy]|qu)ies$/i' => "$1y",
'/([lr])ves$/i' => "$1f",
'/(tive)s$/i' => "$1",
'/(hive)s$/i' => "$1",
'/(li|wi|kni)ves$/i' => "$1fe",
'/(shea|loa|lea|thie)ves$/i'=> "$1f",
'/(^analy)ses$/i' => "$1sis",
'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i' => "$1$2sis",
'/([ti])a$/i' => "$1um",
'/(n)ews$/i' => "$1ews",
'/(h|bl)ouses$/i' => "$1ouse",
'/(corpse)s$/i' => "$1",
'/(us)es$/i' => "$1",
'/s$/i' => "",
];
public static $irregular = [
'move' => 'moves',
'foot' => 'feet',
'goose' => 'geese',
'sex' => 'sexes',
'child' => 'children',
'man' => 'men',
'tooth' => 'teeth',
'person' => 'people',
'valve' => 'valves',
];
public static $uncountable = [
'sheep',
'fish',
'deer',
'series',
'species',
'money',
'rice',
'information',
'equipment',
];
/**
* @param $string
* @return null|string|string[]
*/
public static function pluralize($string)
{
// save some time in the case that singular and plural are the same
if ( in_array( strtolower( $string ), self::$uncountable ) )
return $string;
// check for irregular singular forms
foreach ( self::$irregular as $pattern => $result )
{
$pattern = '/' . $pattern . '$/i';
if ( preg_match( $pattern, $string ) )
return preg_replace( $pattern, $result, $string);
}
// check for matches using regular expressions
foreach ( self::$plural as $pattern => $result )
{
if ( preg_match( $pattern, $string ) )
return preg_replace( $pattern, $result, $string );
}
return $string;
}
public static function singularize( $string )
{
// save some time in the case that singular and plural are the same
if ( in_array( strtolower( $string ), self::$uncountable ) )
return $string;
// check for irregular plural forms
foreach ( self::$irregular as $result => $pattern )
{
$pattern = '/' . $pattern . '$/i';
if ( preg_match( $pattern, $string ) )
return preg_replace( $pattern, $result, $string);
}
// check for matches using regular expressions
foreach ( self::$singular as $pattern => $result )
{
if ( preg_match( $pattern, $string ) )
return preg_replace( $pattern, $result, $string );
}
return $string;
}
/**
* @param $count
* @param $string
* @return string
*/
public static function pluralizeIf($count, $string)
{
if (1 === $count) {
return "1 $string";
} else {
return $count." ".self::pluralize($string);
}
}
/**
* @param string $string
* @return mixed|null|string|string[]
*/
public static function titleize(string $string)
{
$string = self::underscore($string);
$string = self::humanize($string);
$string = preg_replace_callback('/\b(?<![\'’`])[[:lower:]]/u', function($matches) {
return mb_strtoupper($matches[0]);
}, $string);
return $string;
}
/**
* @param $camel_cased_word
* @return mixed|null|string|string[]
*/
public static function underscore($camel_cased_word)
{
$word = (string) $camel_cased_word;
$word = str_replace('\\', '/', $word);
$word = preg_replace_callback('/(?:([[:alpha:]\d])|^)(1(?=a)b)(?=\b|[^[:lower:]])/u', function($matches) {
list(, $m1, $m2) = $matches;
return $m1 . ($m1 ? '_' : '') . mb_strtolower($m2);
}, $word);
$word = preg_replace('/([[:upper:]\d]+)([[:upper:]][[:lower:]])/u', '\1_\2', $word);
$word = preg_replace('/([[:lower:]\d])([[:upper:]])/u','\1_\2', $word);
$word = preg_replace('/\-+|\s+/', '_', $word);
$word = mb_strtolower($word);
return $word;
}
/**
* @param $lower_case_and_underscored_word
* @return null|string|string[]
*/
public static function humanize($lower_case_and_underscored_word)
{
$result = (string) $lower_case_and_underscored_word;
$result = preg_replace('/_id$/', "", $result);
$result = strtr($result, '_', ' ');
$result = preg_replace_callback('/([[:alnum:]]+)/u', function($matches) {
list($m) = $matches;
return mb_strtolower($m);
}, $result);
$result = preg_replace_callback('/^[[:lower:]]/u', function($matches) {
return mb_strtoupper($matches[0]);
}, $result);
return $result;
}
}
| netbull/CoreBundle | src/Utils/Inflect.php | PHP | agpl-3.0 | 9,221 |
<?php
/*
* Xibo - Digital Signage - http://www.xibo.org.uk
* Copyright (C) 2009-2016 Daniel Garner
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Xibo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Xibo. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Xibo\Controller;
use Xibo\Exception\AccessDeniedException;
use Xibo\Exception\InvalidArgumentException;
use Xibo\Factory\DisplayFactory;
use Xibo\Factory\LayoutFactory;
use Xibo\Factory\MediaFactory;
use Xibo\Factory\UserFactory;
use Xibo\Factory\UserGroupFactory;
use Xibo\Helper\ByteFormatter;
use Xibo\Service\ConfigServiceInterface;
use Xibo\Service\DateServiceInterface;
use Xibo\Service\LogServiceInterface;
use Xibo\Service\SanitizerServiceInterface;
use Xibo\Storage\StorageServiceInterface;
/**
* Class Stats
* @package Xibo\Controller
*/
class Stats extends Base
{
/**
* @var StorageServiceInterface
*/
private $store;
/**
* @var DisplayFactory
*/
private $displayFactory;
/**
* @var MediaFactory
*/
private $mediaFactory;
/** @var LayoutFactory */
private $layoutFactory;
/** @var UserFactory */
private $userFactory;
/** @var UserGroupFactory */
private $userGroupFactory;
/**
* Set common dependencies.
* @param LogServiceInterface $log
* @param SanitizerServiceInterface $sanitizerService
* @param \Xibo\Helper\ApplicationState $state
* @param \Xibo\Entity\User $user
* @param \Xibo\Service\HelpServiceInterface $help
* @param DateServiceInterface $date
* @param ConfigServiceInterface $config
* @param StorageServiceInterface $store
* @param DisplayFactory $displayFactory
* @param LayoutFactory $layoutFactory
* @param MediaFactory $mediaFactory
* @param UserFactory $userFactory
* @param UserGroupFactory $userGroupFactory
*/
public function __construct($log, $sanitizerService, $state, $user, $help, $date, $config, $store, $displayFactory, $layoutFactory, $mediaFactory, $userFactory, $userGroupFactory)
{
$this->setCommonDependencies($log, $sanitizerService, $state, $user, $help, $date, $config);
$this->store = $store;
$this->displayFactory = $displayFactory;
$this->layoutFactory = $layoutFactory;
$this->mediaFactory = $mediaFactory;
$this->userFactory = $userFactory;
$this->userGroupFactory = $userGroupFactory;
}
/**
* Stats page
*/
function displayPage()
{
$data = [
// List of Displays this user has permission for
'displays' => $this->displayFactory->query(),
'defaults' => [
'fromDate' => $this->getDate()->getLocalDate(time() - (86400 * 35)),
'fromDateOneDay' => $this->getDate()->getLocalDate(time() - 86400),
'toDate' => $this->getDate()->getLocalDate()
]
];
$this->getState()->template = 'statistics-page';
$this->getState()->setData($data);
}
/**
* Stats page
*/
function displayProofOfPlayPage()
{
$data = [
// List of Displays this user has permission for
'displays' => $this->displayFactory->query(),
// List of Media this user has permission for
'media' => $this->mediaFactory->query(),
// List of Layouts this user has permission for
'layouts' => $this->layoutFactory->query(),
'defaults' => [
'fromDate' => $this->getDate()->getLocalDate(time() - (86400 * 35)),
'fromDateOneDay' => $this->getDate()->getLocalDate(time() - 86400),
'toDate' => $this->getDate()->getLocalDate()
]
];
$this->getState()->template = 'stats-proofofplay-page';
$this->getState()->setData($data);
}
/**
* @SWG\Definition(
* definition="StatisticsData",
* @SWG\Property(
* property="type",
* type="string"
* ),
* @SWG\Property(
* property="display",
* type="string"
* ),
* @SWG\Property(
* property="layout",
* type="string"
* ),
* @SWG\Property(
* property="media",
* type="string"
* ),
* @SWG\Property(
* property="numberPlays",
* type="integer"
* ),
* @SWG\Property(
* property="duration",
* type="integer"
* ),
* @SWG\Property(
* property="minStart",
* type="string"
* ),
* @SWG\Property(
* property="maxEnd",
* type="string"
* )
* )
*
*
* Shows the stats grid
*
* @SWG\Get(
* path="/stats",
* operationId="statsSearch",
* tags={"statistics"},
* @SWG\Parameter(
* name="type",
* in="formData",
* description="The type of stat to return. Layout|Media|Widget or All",
* type="string",
* required=false
* ),
* @SWG\Parameter(
* name="fromDt",
* in="formData",
* description="The start date for the filter. Default = 24 hours ago",
* type="string",
* required=false
* ),
* @SWG\Parameter(
* name="toDt",
* in="formData",
* description="The end date for the filter. Default = now.",
* type="string",
* required=false
* ),
* @SWG\Parameter(
* name="displayId",
* in="formData",
* description="An optional display Id to filter",
* type="integer",
* required=false
* ),
* @SWG\Parameter(
* name="layoutId",
* description="An optional array of layout Id to filter",
* in="formData",
* required=false,
* type="array",
* @SWG\Items(
* type="integer"
* )
* ),
* @SWG\Parameter(
* name="mediaId",
* description="An optional array of media Id to filter",
* in="formData",
* required=false,
* type="array",
* @SWG\Items(
* type="integer"
* )
* ),
* @SWG\Response(
* response=200,
* description="successful operation",
* @SWG\Schema(
* type="array",
* @SWG\Items(
* ref="#/definitions/StatisticsData"
* )
* )
* )
* )
*/
public function grid()
{
$fromDt = $this->getSanitizer()->getDate('fromDt', $this->getSanitizer()->getDate('statsFromDt', $this->getDate()->parse()->addDay(-1)));
$toDt = $this->getSanitizer()->getDate('toDt', $this->getSanitizer()->getDate('statsToDt', $this->getDate()->parse()));
$displayId = $this->getSanitizer()->getInt('displayId');
$layoutIds = $this->getSanitizer()->getIntArray('layoutId');
$mediaIds = $this->getSanitizer()->getIntArray('mediaId');
$type = strtolower($this->getSanitizer()->getString('type'));
// What if the fromdt and todt are exactly the same?
// in this case assume an entire day from midnight on the fromdt to midnight on the todt (i.e. add a day to the todt)
if ($fromDt == $toDt) {
$toDt->addDay(1);
}
$this->getLog()->debug('Converted Times received are: FromDt=' . $fromDt . '. ToDt=' . $toDt);
// Get an array of display id this user has access to.
$display_ids = array();
foreach ($this->displayFactory->query() as $display) {
$display_ids[] = $display->displayId;
}
if (count($display_ids) <= 0)
throw new InvalidArgumentException(__('No displays with View permissions'), 'displays');
// Media on Layouts Ran
$select = '
SELECT stat.type,
display.Display,
layout.Layout,
IFNULL(`media`.name, IFNULL(`widgetoption`.value, `widget`.type)) AS Media,
COUNT(StatID) AS NumberPlays,
SUM(TIME_TO_SEC(TIMEDIFF(end, start))) AS Duration,
MIN(start) AS MinStart,
MAX(end) AS MaxEnd,
layout.layoutId,
stat.mediaId,
stat.widgetId
';
$body = '
FROM stat
INNER JOIN display
ON stat.DisplayID = display.DisplayID
INNER JOIN layout
ON layout.LayoutID = stat.LayoutID
LEFT OUTER JOIN `widget`
ON `widget`.widgetId = stat.widgetId
LEFT OUTER JOIN `widgetoption`
ON `widgetoption`.widgetId = `widget`.widgetId
AND `widgetoption`.type = \'attrib\'
AND `widgetoption`.option = \'name\'
LEFT OUTER JOIN `media`
ON `media`.mediaId = `stat`.mediaId
WHERE stat.type <> \'displaydown\'
AND stat.end > :fromDt
AND stat.start <= :toDt
AND stat.displayID IN (' . implode(',', $display_ids) . ')
';
$params = [
'fromDt' => $this->getDate()->getLocalDate($fromDt),
'toDt' => $this->getDate()->getLocalDate($toDt)
];
// Type filter
if ($type == 'layout') {
$body .= ' AND `stat`.type = \'layout\' ';
} else if ($type == 'media') {
$body .= ' AND `stat`.type = \'media\' AND IFNULL(`media`.mediaId, 0) <> 0 ';
} else if ($type == 'widget') {
$body .= ' AND `stat`.type = \'media\' AND IFNULL(`widget`.widgetId, 0) <> 0 ';
}
// Layout Filter
if (count($layoutIds) != 0) {
$layoutSql = '';
$i = 0;
foreach ($layoutIds as $layoutId) {
$i++;
$layoutSql .= ':layoutId_' . $i . ',';
$params['layoutId_' . $i] = $layoutId;
}
$body .= ' AND `stat`.layoutId IN (' . trim($layoutSql, ',') . ')';
}
// Media Filter
if (count($mediaIds) != 0) {
$mediaSql = '';
$i = 0;
foreach ($mediaIds as $mediaId) {
$i++;
$mediaSql .= ':mediaId_' . $i . ',';
$params['mediaId_' . $i] = $mediaId;
}
$body .= ' AND `media`.mediaId IN (' . trim($mediaSql, ',') . ')';
}
if ($displayId != 0) {
$body .= ' AND stat.displayID = :displayId ';
$params['displayId'] = $displayId;
}
$body .= 'GROUP BY stat.type, display.Display, layout.Layout, layout.layoutId, stat.mediaId, stat.widgetId, IFNULL(`media`.name, IFNULL(`widgetoption`.value, `widget`.type)) ';
// Sorting?
$filterBy = $this->gridRenderFilter();
$sortOrder = $this->gridRenderSort();
$order = '';
if (is_array($sortOrder))
$order .= 'ORDER BY ' . implode(',', $sortOrder);
$limit = '';
// Paging
if ($filterBy !== null && $this->getSanitizer()->getInt('start', $filterBy) !== null && $this->getSanitizer()->getInt('length', $filterBy) !== null) {
$limit = ' LIMIT ' . intval($this->getSanitizer()->getInt('start', $filterBy), 0) . ', ' . $this->getSanitizer()->getInt('length', 10, $filterBy);
}
$sql = $select . $body . $order . $limit;
$rows = array();
foreach ($this->store->select($sql, $params) as $row) {
$entry = [];
$widgetId = $this->getSanitizer()->int($row['widgetId']);
$widgetName = $this->getSanitizer()->string($row['Media']);
// If the media name is empty, and the widgetid is not, then we can assume it has been deleted.
$widgetName = ($widgetName == '' && $widgetId != 0) ? __('Deleted from Layout') : $widgetName;
$entry['type'] = $this->getSanitizer()->string($row['type']);
$entry['display'] = $this->getSanitizer()->string($row['Display']);
$entry['layout'] = $this->getSanitizer()->string($row['Layout']);
$entry['media'] = $widgetName;
$entry['numberPlays'] = $this->getSanitizer()->int($row['NumberPlays']);
$entry['duration'] = $this->getSanitizer()->int($row['Duration']);
$entry['minStart'] = $this->getDate()->getLocalDate($this->getDate()->parse($row['MinStart']));
$entry['maxEnd'] = $this->getDate()->getLocalDate($this->getDate()->parse($row['MaxEnd']));
$entry['layoutId'] = $this->getSanitizer()->int($row['layoutId']);
$entry['widgetId'] = $this->getSanitizer()->int($row['widgetId']);
$entry['mediaId'] = $this->getSanitizer()->int($row['mediaId']);
$rows[] = $entry;
}
// Paging
if ($limit != '' && count($rows) > 0) {
$results = $this->store->select('
SELECT COUNT(*) AS total FROM (SELECT stat.type, display.Display, layout.Layout, IFNULL(`media`.name, IFNULL(`widgetoption`.value, `widget`.type)) ' . $body . ') total
', $params);
$this->getState()->recordsTotal = intval($results[0]['total']);
}
$this->getState()->template = 'grid';
$this->getState()->setData($rows);
}
public function availabilityData()
{
$fromDt = $this->getSanitizer()->getDate('fromDt', $this->getSanitizer()->getDate('availabilityFromDt'));
$toDt = $this->getSanitizer()->getDate('toDt', $this->getSanitizer()->getDate('availabilityToDt'));
$displayId = $this->getSanitizer()->getInt('displayId');
$onlyLoggedIn = $this->getSanitizer()->getCheckbox('onlyLoggedIn') == 1;
// Get an array of display id this user has access to.
$displayIds = array();
foreach ($this->displayFactory->query() as $display) {
$displayIds[] = $display->displayId;
}
if (count($displayIds) <= 0)
throw new InvalidArgumentException(__('No displays with View permissions'), 'displays');
// Get some data for a bandwidth chart
$params = array(
'start' => $fromDt->format('U'),
'end' => $toDt->format('U')
);
$SQL = '
SELECT display.display,
SUM(LEAST(IFNULL(`end`, :end), :end) - GREATEST(`start`, :start)) AS duration
FROM `displayevent`
INNER JOIN `display`
ON display.displayId = `displayevent`.displayId
WHERE `start` <= :end
AND IFNULL(`end`, :end) >= :start
AND display.displayId IN (' . implode(',', $displayIds) . ') ';
if ($displayId != 0) {
$SQL .= ' AND display.displayId = :displayId ';
$params['displayId'] = $displayId;
}
if ($onlyLoggedIn) {
$SQL .= ' AND `display`.loggedIn = 1 ';
}
$SQL .= '
GROUP BY display.display
';
$rows = $this->store->select($SQL, $params);
$labels = [];
$data = [];
$maxDuration = 0;
foreach ($rows as $row) {
$maxDuration = $maxDuration + $this->getSanitizer()->double($row['duration']);
}
if ($maxDuration > 86400) {
$postUnits = __('Days');
$divisor = 86400;
}
else if ($maxDuration > 3600) {
$postUnits = __('Hours');
$divisor = 3600;
}
else {
$postUnits = __('Minutes');
$divisor = 60;
}
foreach ($rows as $row) {
$labels[] = $this->getSanitizer()->string($row['display']);
$data[] = round($this->getSanitizer()->double($row['duration']) / $divisor, 2);
}
$this->getState()->extra = [
'labels' => $labels,
'data' => $data,
'postUnits' => $postUnits
];
}
/**
* Bandwidth Data
*/
public function bandwidthData()
{
$fromDt = $this->getSanitizer()->getDate('fromDt', $this->getSanitizer()->getDate('bandwidthFromDt'));
$toDt = $this->getSanitizer()->getDate('toDt', $this->getSanitizer()->getDate('bandwidthToDt'));
// Get an array of display id this user has access to.
$displayIds = array();
foreach ($this->displayFactory->query() as $display) {
$displayIds[] = $display->displayId;
}
if (count($displayIds) <= 0)
throw new InvalidArgumentException(__('No displays with View permissions'), 'displays');
// Get some data for a bandwidth chart
$dbh = $this->store->getConnection();
$displayId = $this->getSanitizer()->getInt('displayId');
$params = array(
'month' => $this->getDate()->getLocalDate($fromDt->setDateTime($fromDt->year, $fromDt->month, 1, 0, 0), 'U'),
'month2' => $this->getDate()->getLocalDate($toDt->addMonth(1)->setDateTime($toDt->year, $toDt->month, 1, 0, 0), 'U')
);
$SQL = 'SELECT display.display, IFNULL(SUM(Size), 0) AS size ';
if ($displayId != 0)
$SQL .= ', bandwidthtype.name AS type ';
$SQL .= ' FROM `bandwidth`
INNER JOIN `display`
ON display.displayid = bandwidth.displayid';
if ($displayId != 0)
$SQL .= '
INNER JOIN bandwidthtype
ON bandwidthtype.bandwidthtypeid = bandwidth.type
';
$SQL .= ' WHERE month > :month
AND month < :month2
AND display.displayId IN (' . implode(',', $displayIds) . ') ';
if ($displayId != 0) {
$SQL .= ' AND display.displayid = :displayid ';
$params['displayid'] = $displayId;
}
$SQL .= 'GROUP BY display.display ';
if ($displayId != 0)
$SQL .= ' , bandwidthtype.name ';
$SQL .= 'ORDER BY display.display';
$sth = $dbh->prepare($SQL);
$sth->execute($params);
// Get the results
$results = $sth->fetchAll();
$maxSize = 0;
foreach ($results as $library) {
$maxSize = ($library['size'] > $maxSize) ? $library['size'] : $maxSize;
}
// Decide what our units are going to be, based on the size
$base = floor(log($maxSize) / log(1024));
$labels = [];
$data = [];
foreach ($results as $row) {
// label depends whether we are filtered by display
if ($displayId != 0) {
$labels[] = $row['type'];
} else {
$labels[] = $row['display'];
}
$data[] = round((double)$row['size'] / (pow(1024, $base)), 2);
}
// Set up some suffixes
$suffixes = array('bytes', 'k', 'M', 'G', 'T');
$this->getState()->extra = [
'labels' => $labels,
'data' => $data,
'postUnits' => (isset($suffixes[$base]) ? $suffixes[$base] : '')
];
}
/**
* Output CSV Form
*/
public function exportForm()
{
$this->getState()->template = 'statistics-form-export';
$this->getState()->setData([
'displays' => $this->displayFactory->query()
]);
}
/**
* Outputs a CSV of stats
*/
public function export()
{
// We are expecting some parameters
$fromDt = $this->getSanitizer()->getDate('fromDt');
$toDt = $this->getSanitizer()->getDate('toDt');
$displayId = $this->getSanitizer()->getInt('displayId');
// Get an array of display id this user has access to.
$displayIds = array();
foreach ($this->displayFactory->query() as $display) {
$displayIds[] = $display->displayId;
}
if (count($displayIds) <= 0)
throw new AccessDeniedException();
$sql = '
SELECT stat.*, display.Display, layout.Layout, media.Name AS MediaName
FROM stat
INNER JOIN display
ON stat.DisplayID = display.DisplayID
LEFT OUTER JOIN layout
ON layout.LayoutID = stat.LayoutID
LEFT OUTER JOIN media
ON media.mediaID = stat.mediaID
WHERE 1 = 1
AND stat.end > :fromDt
AND stat.start <= :toDt
AND stat.displayID IN (' . implode(',', $displayIds) . ')
';
$params = [
'fromDt' => $this->getDate()->getLocalDate($fromDt),
'toDt' => $this->getDate()->getLocalDate($toDt)
];
if ($displayId != 0) {
$sql .= ' AND stat.displayID = :displayId ';
$params['displayId'] = $displayId;
}
$sql .= " ORDER BY stat.start ";
$out = fopen('php://output', 'w');
fputcsv($out, ['Type', 'FromDT', 'ToDT', 'Layout', 'Display', 'Media', 'Tag']);
// Do some post processing
foreach ($this->store->select($sql, $params) as $row) {
// Read the columns
$type = $this->getSanitizer()->string($row['Type']);
$fromDt = $this->getSanitizer()->string($row['start']);
$toDt = $this->getSanitizer()->string($row['end']);
$layout = $this->getSanitizer()->string($row['Layout']);
$display = $this->getSanitizer()->string($row['Display']);
$media = $this->getSanitizer()->string($row['MediaName']);
$tag = $this->getSanitizer()->string($row['Tag']);
fputcsv($out, [$type, $fromDt, $toDt, $layout, $display, $media, $tag]);
}
fclose($out);
// We want to output a load of stuff to the browser as a text file.
$app = $this->getApp();
$app->response()->header('Content-Type', 'text/csv');
$app->response()->header('Content-Disposition', 'attachment; filename="stats.csv"');
$app->response()->header('Content-Transfer-Encoding', 'binary"');
$app->response()->header('Accept-Ranges', 'bytes');
$this->setNoOutput(true);
}
/**
* Stats page
*/
function displayLibraryPage()
{
$this->getState()->template = 'stats-library-page';
$data = [];
// Set up some suffixes
$suffixes = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
// Widget for the library usage pie chart
try {
if ($this->getUser()->libraryQuota != 0) {
$libraryLimit = $this->getUser()->libraryQuota * 1024;
} else {
$libraryLimit = $this->getConfig()->GetSetting('LIBRARY_SIZE_LIMIT_KB') * 1024;
}
// Library Size in Bytes
$params = [];
$sql = 'SELECT IFNULL(SUM(FileSize), 0) AS SumSize, type FROM `media` WHERE 1 = 1 ';
$this->mediaFactory->viewPermissionSql('Xibo\Entity\Media', $sql, $params, '`media`.mediaId', '`media`.userId');
$sql .= ' GROUP BY type ';
$sth = $this->store->getConnection()->prepare($sql);
$sth->execute($params);
$results = $sth->fetchAll();
// Do we base the units on the maximum size or the library limit
$maxSize = 0;
if ($libraryLimit > 0) {
$maxSize = $libraryLimit;
} else {
// Find the maximum sized chunk of the items in the library
foreach ($results as $library) {
$maxSize = ($library['SumSize'] > $maxSize) ? $library['SumSize'] : $maxSize;
}
}
// Decide what our units are going to be, based on the size
$base = ($maxSize == 0) ? 0 : floor(log($maxSize) / log(1024));
$libraryUsage = [];
$libraryLabels = [];
$totalSize = 0;
foreach ($results as $library) {
$libraryUsage[] = round((double)$library['SumSize'] / (pow(1024, $base)), 2);
$libraryLabels[] = ucfirst($library['type']) . ' ' . $suffixes[$base];
$totalSize = $totalSize + $library['SumSize'];
}
// Do we need to add the library remaining?
if ($libraryLimit > 0) {
$remaining = round(($libraryLimit - $totalSize) / (pow(1024, $base)), 2);
$libraryUsage[] = $remaining;
$libraryLabels[] = __('Free') . ' ' . $suffixes[$base];
}
// What if we are empty?
if (count($results) == 0 && $libraryLimit <= 0) {
$libraryUsage[] = 0;
$libraryLabels[] = __('Empty');
}
$data['libraryLimitSet'] = ($libraryLimit > 0);
$data['libraryLimit'] = (round((double)$libraryLimit / (pow(1024, $base)), 2)) . ' ' . $suffixes[$base];
$data['librarySize'] = ByteFormatter::format($totalSize, 1);
$data['librarySuffix'] = $suffixes[$base];
$data['libraryWidgetLabels'] = json_encode($libraryLabels);
$data['libraryWidgetData'] = json_encode($libraryUsage);
} catch (\Exception $exception) {
$this->getLog()->error('Error rendering the library stats page widget');
}
$data['users'] = $this->userFactory->query();
$data['groups'] = $this->userGroupFactory->query();
$this->getState()->setData($data);
}
public function libraryUsageGrid()
{
$params = [];
$select = '
SELECT `user`.userId,
`user`.userName,
IFNULL(SUM(`media`.FileSize), 0) AS bytesUsed,
COUNT(`media`.mediaId) AS numFiles
';
$body = '
FROM `user`
LEFT OUTER JOIN `media`
ON `media`.userID = `user`.UserID
WHERE 1 = 1
';
// Restrict on the users we have permission to see
// Normal users can only see themselves
$permissions = '';
if ($this->getUser()->userTypeId == 3) {
$permissions .= ' AND user.userId = :currentUserId ';
$filterBy['currentUserId'] = $this->getUser()->userId;
}
// Group admins can only see users from their groups.
else if ($this->getUser()->userTypeId == 2) {
$permissions .= '
AND user.userId IN (
SELECT `otherUserLinks`.userId
FROM `lkusergroup`
INNER JOIN `group`
ON `group`.groupId = `lkusergroup`.groupId
AND `group`.isUserSpecific = 0
INNER JOIN `lkusergroup` `otherUserLinks`
ON `otherUserLinks`.groupId = `group`.groupId
WHERE `lkusergroup`.userId = :currentUserId
)
';
$params['currentUserId'] = $this->getUser()->userId;
}
// Filter by userId
if ($this->getSanitizer()->getInt('userId') !== null) {
$body .= ' AND user.userId = :userId ';
$params['userId'] = $this->getSanitizer()->getInt('userId');
}
// Filter by groupId
if ($this->getSanitizer()->getInt('groupId') !== null) {
$body .= ' AND user.userId IN (SELECT userId FROM `lkusergroup` WHERE groupId = :groupId) ';
$params['groupId'] = $this->getSanitizer()->getInt('groupId');
}
$body .= $permissions;
$body .= '
GROUP BY `user`.userId,
`user`.userName
';
// Sorting?
$filterBy = $this->gridRenderFilter();
$sortOrder = $this->gridRenderSort();
$order = '';
if (is_array($sortOrder))
$order .= 'ORDER BY ' . implode(',', $sortOrder);
$limit = '';
// Paging
if ($filterBy !== null && $this->getSanitizer()->getInt('start', $filterBy) !== null && $this->getSanitizer()->getInt('length', $filterBy) !== null) {
$limit = ' LIMIT ' . intval($this->getSanitizer()->getInt('start', $filterBy), 0) . ', ' . $this->getSanitizer()->getInt('length', 10, $filterBy);
}
$sql = $select . $body . $order . $limit;
$rows = [];
foreach ($this->store->select($sql, $params) as $row) {
$entry = [];
$entry['userId'] = $this->getSanitizer()->int($row['userId']);
$entry['userName'] = $this->getSanitizer()->string($row['userName']);
$entry['bytesUsed'] = $this->getSanitizer()->int($row['bytesUsed']);
$entry['bytesUsedFormatted'] = ByteFormatter::format($this->getSanitizer()->int($row['bytesUsed']), 2);
$entry['numFiles'] = $this->getSanitizer()->int($row['numFiles']);
$rows[] = $entry;
}
// Paging
if ($limit != '' && count($rows) > 0) {
$results = $this->store->select('SELECT COUNT(*) AS total FROM `user` ' . $permissions, $params);
$this->getState()->recordsTotal = intval($results[0]['total']);
}
$this->getState()->template = 'grid';
$this->getState()->setData($rows);
}
}
| guruevi/xibo-cms | lib/Controller/Stats.php | PHP | agpl-3.0 | 29,839 |
/*
* ============================================================================
* Copyright (C) 2017 Kaltura Inc.
*
* Licensed under the AGPLv3 license, unless a different license for a
* particular library is specified in the applicable library path.
*
* You may obtain a copy of the License at
* https://www.gnu.org/licenses/agpl-3.0.html
* ============================================================================
*/
package com.kaltura.playkit.api.base.model;
import android.text.TextUtils;
import com.kaltura.netkit.connect.response.BaseResult;
import com.kaltura.playkit.api.ovp.OvpConfigs;
import java.util.List;
/**
* Created by tehilarozin on 17/11/2016.
*/
public class BasePlaybackSource extends BaseResult {
protected String format;
protected String url;
protected String protocols; // currently list of KalturaString objects
protected List<KalturaDrmPlaybackPluginData> drm;
public List<KalturaDrmPlaybackPluginData> getDrmData() {
return drm;
}
/**
* check if protocol is supported by this source.
* Player can't redirect cross protocols so we make sure that the base protocol is supported
* (included) by the source.
*
* @param protocol - the desired protocol for the source (base play url protocol)
* @return true, if protocol is in the protocols list
*/
public String getProtocol(String protocol) {
if (protocols != null && protocols.length() > 0) {
String protocolsLst[] = protocols.split(",");
for (String prc : protocolsLst) {
if (prc.equals(protocol)) {
return protocol;
}
}
} else if (protocol.equals(OvpConfigs.DefaultHttpProtocol)) {
return protocol;
}
return null;
}
public String getFormat() {
return format;
}
public String getUrl() {
return url;
}
public boolean hasDrmData() {
return drm != null && drm.size() > 0;
}
public String getDrmSchemes(){
StringBuilder schemes = new StringBuilder();
if(hasDrmData()){
for (KalturaDrmPlaybackPluginData drmPlaybackPluginData : drm){
if(!TextUtils.isEmpty(drmPlaybackPluginData.getScheme())) {
schemes.append(drmPlaybackPluginData.getScheme()).append(",");
}
}
}
if(schemes.length() > 0){
schemes.deleteCharAt(schemes.length()-1);
}
return schemes.toString();
}
}
| shaoliancheng/videoplayer-android-tv | playkit/src/main/java/com/kaltura/playkit/api/base/model/BasePlaybackSource.java | Java | agpl-3.0 | 2,574 |
/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/*
This file is similar to CppRegionTest except that it also tests Python nodes.
It is build in nupic.core but tested in nupic. So its execution and README instructions
remains in nupic.
*/
#include <nupic/engine/NuPIC.hpp>
#include <nupic/engine/Network.hpp>
#include <nupic/engine/Region.hpp>
#include <nupic/engine/Spec.hpp>
#include <nupic/engine/Input.hpp>
#include <nupic/engine/Output.hpp>
#include <nupic/engine/Link.hpp>
#include <nupic/ntypes/Dimensions.hpp>
#include <nupic/ntypes/Array.hpp>
#include <nupic/ntypes/ArrayRef.hpp>
#include <nupic/types/Exception.hpp>
#include <nupic/os/OS.hpp> // memory leak detection
#include <nupic/os/Env.hpp>
#include <nupic/os/Path.hpp>
#include <nupic/os/Timer.hpp>
#include <string>
#include <vector>
#include <cmath> // fabs/abs
#include <cstdlib> // exit
#include <iostream>
#include <stdexcept>
#include <capnp/message.h>
bool ignore_negative_tests = false;
#define SHOULDFAIL(statement) \
{ \
if (!ignore_negative_tests) \
{ \
bool caughtException = false; \
try { \
statement; \
} catch(std::exception& ) { \
caughtException = true; \
std::cout << "Caught exception as expected: " # statement "" << std::endl; \
} \
if (!caughtException) { \
NTA_THROW << "Operation '" #statement "' did not fail as expected"; \
} \
} \
}
using namespace nupic;
bool verbose = false;
struct MemoryMonitor
{
MemoryMonitor()
{
OS::getProcessMemoryUsage(initial_vmem, initial_rmem);
}
~MemoryMonitor()
{
if (hasMemoryLeaks())
{
NTA_DEBUG
<< "Memory leaks detected. "
<< "Real Memory: " << diff_rmem
<< ", Virtual Memory: " << diff_vmem;
}
}
void update()
{
OS::getProcessMemoryUsage(current_vmem, current_rmem);
diff_vmem = current_vmem - initial_vmem;
diff_rmem = current_rmem - initial_rmem;
}
bool hasMemoryLeaks()
{
update();
return diff_vmem > 0 || diff_rmem > 0;
}
size_t initial_vmem;
size_t initial_rmem;
size_t current_vmem;
size_t current_rmem;
size_t diff_rmem;
size_t diff_vmem;
};
void testExceptionBug()
{
Network n;
Region *l1 = n.addRegion("l1", "py.TestNode", "");
//Dimensions d(1);
Dimensions d(1);
l1->setDimensions(d);
bool caughtException = false;
try
{
n.run(1);
} catch (std::exception& e) {
NTA_DEBUG << "Caught exception as expected: '" << e.what() << "'";
caughtException = true;
}
if (caughtException)
{
NTA_DEBUG << "testExceptionBug passed";
} else {
NTA_THROW << "testExceptionBug did not throw an exception as expected";
}
}
void testPynodeInputOutputAccess(Region * level2)
{
// --- input/output access for level 2 (Python py.TestNode) ---
SHOULDFAIL(level2->getOutputData("doesnotexist") );
// getting access via zero-copy
std::cout << "Getting output for zero-copy access" << std::endl;
ArrayRef output = level2->getOutputData("bottomUpOut");
std::cout << "Element count in bottomUpOut is " << output.getCount() << "" << std::endl;
Real64 *data_actual = (Real64*)output.getBuffer();
// set the actual output
data_actual[12] = 54321;
}
void testPynodeArrayParameters(Region * level2)
{
// Array a is not allocated by us. Will be allocated inside getParameter
Array a(NTA_BasicType_Int64);
level2->getParameterArray("int64ArrayParam", a);
std::cout << "level2.int64ArrayParam size = " << a.getCount() << std::endl;
std::cout << "level2.int64ArrayParam = [ ";
Int64 * buff = (Int64 *)a.getBuffer();
for (int i = 0; i < int(a.getCount()); ++i)
std::cout << buff[i] << " ";
std::cout << "]" << std::endl;
// --- test setParameterInt64Array ---
std::cout << "Setting level2.int64ArrayParam to [ 1 2 3 4 ]" << std::endl;
std::vector<Int64> v(4);
for (int i = 0; i < 4; ++i)
v[i] = i+1 ;
Array newa(NTA_BasicType_Int64, &v[0], v.size());
level2->setParameterArray("int64ArrayParam", newa);
// get the value of intArrayParam after the setParameter call.
a.releaseBuffer();
a.allocateBuffer(4);
level2->getParameterArray("int64ArrayParam", a);
std::cout << "level2.int64ArrayParam size = " << a.getCount() << std::endl;
std::cout << "level2.int64ArrayParam = [ ";
buff = (Int64 *)a.getBuffer();
for (int i = 0; i < int(a.getCount()); ++i)
std::cout << buff[i] << " ";
std::cout << "]" << std::endl;
}
void testPynodeLinking()
{
Network net = Network();
Region * region1 = net.addRegion("region1", "TestNode", "");
Region * region2 = net.addRegion("region2", "py.TestNode", "");
std::cout << "Linking region 1 to region 2" << std::endl;
net.link("region1", "region2", "TestFanIn2", "");
std::cout << "Setting region1 dims to (6,4)" << std::endl;
Dimensions r1dims;
r1dims.push_back(6);
r1dims.push_back(4);
region1->setDimensions(r1dims);
std::cout << "Initializing network..." << std::endl;
net.initialize();
const Dimensions& r2dims = region2->getDimensions();
NTA_CHECK(r2dims.size() == 2) << " actual dims: " << r2dims.toString();
NTA_CHECK(r2dims[0] == 3) << " actual dims: " << r2dims.toString();
NTA_CHECK(r2dims[1] == 2) << " actual dims: " << r2dims.toString();
ArrayRef r1OutputArray = region1->getOutputData("bottomUpOut");
region1->compute();
std::cout << "Checking region1 output after first iteration..." << std::endl;
Real64 *buffer = (Real64*) r1OutputArray.getBuffer();
for (size_t i = 0; i < r1OutputArray.getCount(); i++)
{
if (verbose)
std::cout << " " << i << " " << buffer[i] << "" << std::endl;
if (i%2 == 0)
NTA_CHECK(buffer[i] == 0);
else
NTA_CHECK(buffer[i] == (i-1)/2);
}
region2->prepareInputs();
ArrayRef r2InputArray = region2->getInputData("bottomUpIn");
std::cout << "Region 2 input after first iteration:" << std::endl;
Real64 *buffer2 = (Real64*) r2InputArray.getBuffer();
NTA_CHECK(buffer != buffer2);
for (size_t i = 0; i < r2InputArray.getCount(); i++)
{
if (verbose)
std::cout << " " << i << " " << buffer2[i] << "" << std::endl;
if (i%2 == 0)
NTA_CHECK(buffer[i] == 0);
else
NTA_CHECK(buffer[i] == (i-1)/2);
}
std::cout << "Region 2 input by node" << std::endl;
std::vector<Real64> r2NodeInput;
for (size_t node = 0; node < 6; node++)
{
region2->getInput("bottomUpIn")->getInputForNode(node, r2NodeInput);
if (verbose)
{
std::cout << "Node " << node << ": ";
for (size_t i = 0; i < r2NodeInput.size(); i++)
{
std::cout << r2NodeInput[i] << " ";
}
std::cout << "" << std::endl;
}
// 4 nodes in r1 fan in to 1 node in r2
int row = node/3;
int col = node - (row * 3);
NTA_CHECK(r2NodeInput.size() == 8);
NTA_CHECK(r2NodeInput[0] == 0);
NTA_CHECK(r2NodeInput[2] == 0);
NTA_CHECK(r2NodeInput[4] == 0);
NTA_CHECK(r2NodeInput[6] == 0);
// these values are specific to the fanin2 link policy
NTA_CHECK(r2NodeInput[1] == row * 12 + col * 2)
<< "row: " << row << " col: " << col << " val: " << r2NodeInput[1];
NTA_CHECK(r2NodeInput[3] == row * 12 + col * 2 + 1)
<< "row: " << row << " col: " << col << " val: " << r2NodeInput[3];
NTA_CHECK(r2NodeInput[5] == row * 12 + 6 + col * 2)
<< "row: " << row << " col: " << col << " val: " << r2NodeInput[5];
NTA_CHECK(r2NodeInput[7] == row * 12 + 6 + col * 2 + 1)
<< "row: " << row << " col: " << col << " val: " << r2NodeInput[7];
}
region2->compute();
}
void testSecondTimeLeak()
{
Network n;
n.addRegion("r1", "py.TestNode", "");
n.addRegion("r2", "py.TestNode", "");
}
void testRegionDuplicateRegister()
{
// Register a region
Network::registerPyRegion("nupic.regions.TestDuplicateNodes",
"TestDuplicateNodes");
// Validate that the same region can be registered multiple times
try
{
Network::registerPyRegion("nupic.regions.TestDuplicateNodes",
"TestDuplicateNodes");
} catch (std::exception& e) {
NTA_THROW << "testRegionDuplicateRegister failed with exception: '"
<< e.what() << "'";
}
// Validate that a region from a different module but with the same name
// cannot be registered
try
{
Network::registerPyRegion("nupic.regions.DifferentModule",
"TestDuplicateNodes");
NTA_THROW << "testRegionDuplicateRegister failed to throw exception for "
<< "region with same name but different module as existing "
<< "registered region";
} catch (std::exception& e) {
}
}
void testCreationParamTypes()
{
// Verify that parameters of all types can be passed in through the creation
// params.
Network n;
Region* region = n.addRegion("test", "py.TestNode",
"{"
"int32Param: -2000000000, uint32Param: 3000000000, "
"int64Param: -5000000000, uint64Param: 5000000001, "
"real32Param: 10.5, real64Param: 11.5, "
"boolParam: true"
"}");
NTA_CHECK(region->getParameterInt32("int32Param") == -2000000000);
NTA_CHECK(region->getParameterUInt32("uint32Param") == 3000000000);
NTA_CHECK(region->getParameterInt64("int64Param") == -5000000000);
NTA_CHECK(region->getParameterUInt64("uint64Param") == 5000000001);
NTA_CHECK(region->getParameterReal32("real32Param") == 10.5);
NTA_CHECK(region->getParameterReal64("real64Param") == 11.5);
NTA_CHECK(region->getParameterBool("boolParam") == true);
}
void testUnregisterRegion()
{
Network n;
n.addRegion("test", "py.TestNode", "");
Network::unregisterPyRegion("TestNode");
bool caughtException = false;
try
{
n.addRegion("test", "py.TestNode", "");
} catch (std::exception& e) {
NTA_DEBUG << "Caught exception as expected: '" << e.what() << "'";
caughtException = true;
}
if (caughtException)
{
NTA_DEBUG << "testUnregisterRegion passed";
} else {
NTA_THROW << "testUnregisterRegion did not throw an exception as expected";
}
}
void testWriteRead()
{
Int32 int32Param = 42;
UInt32 uint32Param = 43;
Int64 int64Param = 44;
UInt64 uint64Param = 45;
Real32 real32Param = 46;
Real64 real64Param = 46;
bool boolParam = true;
std::string stringParam = "hello";
std::vector<Int64> int64ArrayParamBuff(4);
for (int i = 0; i < 4; i++)
{
int64ArrayParamBuff[i] = i + 1;
}
Array int64ArrayParam(NTA_BasicType_Int64,
&int64ArrayParamBuff[0],
int64ArrayParamBuff.size());
std::vector<Real32> real32ArrayParamBuff(4);
for (int i = 0; i < 4; i++)
{
real32ArrayParamBuff[i] = i + 1;
}
Array real32ArrayParam(NTA_BasicType_Real32,
&real32ArrayParamBuff[0],
real32ArrayParamBuff.size());
bool boolArrayParamBuff[4];
for (int i = 0; i < 4; i++)
{
boolArrayParamBuff[i] = (i % 2) == 1;
}
Array boolArrayParam(NTA_BasicType_Bool,
boolArrayParamBuff,
4);
Network n1;
Region* region1 = n1.addRegion("rw1", "py.TestNode", "");
region1->setParameterInt32("int32Param", int32Param);
region1->setParameterUInt32("uint32Param", uint32Param);
region1->setParameterInt64("int64Param", int64Param);
region1->setParameterUInt64("uint64Param", uint64Param);
region1->setParameterReal32("real32Param", real32Param);
region1->setParameterReal64("real64Param", real64Param);
region1->setParameterBool("boolParam", boolParam);
region1->setParameterString("stringParam", stringParam.c_str());
region1->setParameterArray("int64ArrayParam", int64ArrayParam);
region1->setParameterArray("real32ArrayParam", real32ArrayParam);
region1->setParameterArray("boolArrayParam", boolArrayParam);
Network n2;
std::stringstream ss;
n1.write(ss);
n2.read(ss);
const Collection<Region*>& regions = n2.getRegions();
const std::pair<std::string, Region*>& regionPair = regions.getByIndex(0);
Region* region2 = regionPair.second;
NTA_CHECK(region2->getParameterInt32("int32Param") == int32Param);
NTA_CHECK(region2->getParameterUInt32("uint32Param") == uint32Param);
NTA_CHECK(region2->getParameterInt64("int64Param") == int64Param);
NTA_CHECK(region2->getParameterUInt64("uint64Param") == uint64Param);
NTA_CHECK(region2->getParameterReal32("real32Param") == real32Param);
NTA_CHECK(region2->getParameterReal64("real64Param") == real64Param);
NTA_CHECK(region2->getParameterBool("boolParam") == boolParam);
NTA_CHECK(region2->getParameterString("stringParam") == stringParam.c_str());
Array int64Array(NTA_BasicType_Int64);
region2->getParameterArray("int64ArrayParam", int64Array);
Int64 * int64ArrayBuff = (Int64 *)int64Array.getBuffer();
NTA_CHECK(int64ArrayParam.getCount() == int64Array.getCount());
for (int i = 0; i < int(int64ArrayParam.getCount()); i++)
{
NTA_CHECK(int64ArrayBuff[i] == int64ArrayParamBuff[i]);
}
Array real32Array(NTA_BasicType_Real32);
region2->getParameterArray("real32ArrayParam", real32Array);
Real32 * real32ArrayBuff = (Real32 *)real32Array.getBuffer();
NTA_CHECK(real32ArrayParam.getCount() == real32Array.getCount());
for (int i = 0; i < int(real32ArrayParam.getCount()); i++)
{
NTA_CHECK(real32ArrayBuff[i] == real32ArrayParamBuff[i]);
}
Array boolArray(NTA_BasicType_Bool);
region2->getParameterArray("boolArrayParam", boolArray);
bool * boolArrayBuff = (bool *)boolArray.getBuffer();
NTA_CHECK(boolArrayParam.getCount() == boolArray.getCount());
for (int i = 0; i < int(boolArrayParam.getCount()); i++)
{
NTA_CHECK(boolArrayBuff[i] == boolArrayParamBuff[i]);
}
}
int realmain(bool leakTest)
{
// verbose == true turns on extra output that is useful for
// debugging the test (e.g. when the TestNode compute()
// algorithm changes)
std::cout << "Creating network..." << std::endl;
Network n;
std::cout << "Region count is " << n.getRegions().getCount() << "" << std::endl;
std::cout << "Adding a PyNode region..." << std::endl;
Network::registerPyRegion("nupic.bindings.regions.TestNode", "TestNode");
Region* level2 = n.addRegion("level2", "py.TestNode", "{int32Param: 444}");
std::cout << "Region count is " << n.getRegions().getCount() << "" << std::endl;
std::cout << "Node type: " << level2->getType() << "" << std::endl;
std::cout << "Nodespec is:\n" << level2->getSpec()->toString() << "" << std::endl;
Real64 rval;
std::string int64Param("int64Param");
std::string real64Param("real64Param");
// get the value of intArrayParam after the setParameter call.
// --- Test getParameterReal64 of a PyNode
rval = level2->getParameterReal64("real64Param");
NTA_CHECK(rval == 64.1);
std::cout << "level2 getParameterReal64() returned: " << rval << std::endl;
// --- Test setParameterReal64 of a PyNode
level2->setParameterReal64("real64Param", 77.7);
rval = level2->getParameterReal64("real64Param");
NTA_CHECK(rval == 77.7);
// should fail because network has not been initialized
SHOULDFAIL(n.run(1));
// should fail because network can't be initialized
SHOULDFAIL (n.initialize() );
std::cout << "Setting dimensions of level1..." << std::endl;
Dimensions d;
d.push_back(4);
d.push_back(4);
std::cout << "Setting dimensions of level2..." << std::endl;
level2->setDimensions(d);
std::cout << "Initializing again..." << std::endl;
n.initialize();
testExceptionBug();
testPynodeInputOutputAccess(level2);
testPynodeArrayParameters(level2);
testPynodeLinking();
testRegionDuplicateRegister();
testCreationParamTypes();
if (!leakTest)
{
//testNuPIC1x();
//testPynode1xLinking();
}
#if !CAPNP_LITE
// PyRegion::write is implemented only when nupic.core is compiled with
// CAPNP_LITE=0
testWriteRead();
#endif
// testUnregisterRegion needs to be the last test run as it will unregister
// the region 'TestNode'.
testUnregisterRegion();
std::cout << "Done -- all tests passed" << std::endl;
return 0;
}
int main(int argc, char *argv[])
{
/*
* Without arguments, this program is a simple end-to-end demo
* of NuPIC 2 functionality, used as a developer tool (when
* we add a feature, we add it to this program.
* With an integer argument N, runs the same test N times
* and requires that memory use stay constant -- it can't
* grow by even one byte.
*/
// TODO: real argument parsing
// Optional arg is number of iterations to do.
NTA_CHECK(argc == 1 || argc == 2);
size_t count = 1;
if (argc == 2)
{
std::stringstream ss(argv[1]);
ss >> count;
}
// Start checking memory usage after this many iterations.
#if defined(NTA_OS_WINDOWS)
// takes longer to settle down on win32
size_t memoryLeakStartIter = 6000;
#else
size_t memoryLeakStartIter = 150;
#endif
// This determines how frequently we check.
size_t memoryLeakDeltaIterCheck = 10;
size_t minCount = memoryLeakStartIter + 5 * memoryLeakDeltaIterCheck;
if (count > 1 && count < minCount)
{
std::cout << "Run count of " << count << " specified\n";
std::cout << "When run in leak detection mode, count must be at least " << minCount << "\n";
::exit(1);
}
size_t initial_vmem = 0;
size_t initial_rmem = 0;
size_t current_vmem = 0;
size_t current_rmem = 0;
try {
for (size_t i = 0; i < count; i++)
{
//MemoryMonitor m;
NuPIC::init();
realmain(count > 1);
//testExceptionBug();
//testPynode1xLinking();
// testNuPIC1x();
//testSecondTimeLeak();
//testPynodeLinking();
//testCppLinking("TestFanIn2","");
NuPIC::shutdown();
// memory leak detection
// we check even prior to the initial tracking iteration, because the act
// of checking potentially modifies our memory usage
if (i % memoryLeakDeltaIterCheck == 0)
{
OS::getProcessMemoryUsage(current_rmem, current_vmem);
if(i == memoryLeakStartIter)
{
initial_rmem = current_rmem;
initial_vmem = current_vmem;
}
std::cout << "Memory usage: " << current_vmem << " (virtual) "
<< current_rmem << " (real) at iteration " << i << std::endl;
if(i >= memoryLeakStartIter)
{
if (current_vmem > initial_vmem || current_rmem > initial_rmem)
{
std::cout << "Tracked memory usage (iteration "
<< memoryLeakStartIter << "): " << initial_vmem
<< " (virtual) " << initial_rmem << " (real)" << std::endl;
throw std::runtime_error("Memory leak detected");
}
}
}
}
} catch (nupic::Exception& e) {
std::cout
<< "Exception: " << e.getMessage()
<< " at: " << e.getFilename() << ":" << e.getLineNumber()
<< std::endl;
return 1;
} catch (std::exception& e) {
std::cout << "Exception: " << e.what() << "" << std::endl;
return 1;
}
catch (...) {
std::cout << "\nhtmtest is exiting because an exception was thrown" << std::endl;
return 1;
}
if (count > 20)
std::cout << "Memory leak check passed -- " << count << " iterations" << std::endl;
std::cout << "--- ALL TESTS PASSED ---" << std::endl;
return 0;
}
| EricSB/nupic.core | src/test/integration/PyRegionTest.cpp | C++ | agpl-3.0 | 20,414 |
package expr
import (
"context"
"encoding/json"
"fmt"
"github.com/grafana/grafana/pkg/expr/mathexp"
"gonum.org/v1/gonum/graph/simple"
"gonum.org/v1/gonum/graph/topo"
)
// NodeType is the type of a DPNode. Currently either a expression command or datasource query.
type NodeType int
const (
// TypeCMDNode is a NodeType for expression commands.
TypeCMDNode NodeType = iota
// TypeDatasourceNode is a NodeType for datasource queries.
TypeDatasourceNode
)
func (nt NodeType) String() string {
switch nt {
case TypeCMDNode:
return "Expression"
case TypeDatasourceNode:
return "Datasource"
default:
return "Unknown"
}
}
// Node is a node in a Data Pipeline. Node is either a expression command or a datasource query.
type Node interface {
ID() int64 // ID() allows the gonum graph node interface to be fulfilled
NodeType() NodeType
RefID() string
Execute(c context.Context, vars mathexp.Vars, s *Service) (mathexp.Results, error)
String() string
}
// DataPipeline is an ordered set of nodes returned from DPGraph processing.
type DataPipeline []Node
// execute runs all the command/datasource requests in the pipeline return a
// map of the refId of the of each command
func (dp *DataPipeline) execute(c context.Context, s *Service) (mathexp.Vars, error) {
vars := make(mathexp.Vars)
for _, node := range *dp {
res, err := node.Execute(c, vars, s)
if err != nil {
return nil, err
}
vars[node.RefID()] = res
}
return vars, nil
}
// BuildPipeline builds a graph of the nodes, and returns the nodes in an
// executable order.
func (s *Service) buildPipeline(req *Request) (DataPipeline, error) {
graph, err := s.buildDependencyGraph(req)
if err != nil {
return nil, err
}
nodes, err := buildExecutionOrder(graph)
if err != nil {
return nil, err
}
return nodes, nil
}
// buildDependencyGraph returns a dependency graph for a set of queries.
func (s *Service) buildDependencyGraph(req *Request) (*simple.DirectedGraph, error) {
graph, err := s.buildGraph(req)
if err != nil {
return nil, err
}
registry := buildNodeRegistry(graph)
if err := buildGraphEdges(graph, registry); err != nil {
return nil, err
}
return graph, nil
}
// buildExecutionOrder returns a sequence of nodes ordered by dependency.
func buildExecutionOrder(graph *simple.DirectedGraph) ([]Node, error) {
sortedNodes, err := topo.Sort(graph)
if err != nil {
return nil, err
}
nodes := make([]Node, len(sortedNodes))
for i, v := range sortedNodes {
nodes[i] = v.(Node)
}
return nodes, nil
}
// buildNodeRegistry returns a lookup table for reference IDs to respective node.
func buildNodeRegistry(g *simple.DirectedGraph) map[string]Node {
res := make(map[string]Node)
nodeIt := g.Nodes()
for nodeIt.Next() {
if dpNode, ok := nodeIt.Node().(Node); ok {
res[dpNode.RefID()] = dpNode
}
}
return res
}
// buildGraph creates a new graph populated with nodes for every query.
func (s *Service) buildGraph(req *Request) (*simple.DirectedGraph, error) {
dp := simple.NewDirectedGraph()
for _, query := range req.Queries {
if query.DataSource == nil || query.DataSource.Uid == "" {
return nil, fmt.Errorf("missing datasource uid in query with refId %v", query.RefID)
}
rawQueryProp := make(map[string]interface{})
queryBytes, err := query.JSON.MarshalJSON()
if err != nil {
return nil, err
}
err = json.Unmarshal(queryBytes, &rawQueryProp)
if err != nil {
return nil, err
}
rn := &rawNode{
Query: rawQueryProp,
RefID: query.RefID,
TimeRange: query.TimeRange,
QueryType: query.QueryType,
DataSource: query.DataSource,
}
var node Node
if IsDataSource(rn.DataSource.Uid) {
node, err = buildCMDNode(dp, rn)
} else {
node, err = s.buildDSNode(dp, rn, req)
}
if err != nil {
return nil, err
}
dp.AddNode(node)
}
return dp, nil
}
// buildGraphEdges generates graph edges based on each node's dependencies.
func buildGraphEdges(dp *simple.DirectedGraph, registry map[string]Node) error {
nodeIt := dp.Nodes()
for nodeIt.Next() {
node := nodeIt.Node().(Node)
if node.NodeType() != TypeCMDNode {
// datasource node, nothing to do for now. Although if we want expression results to be
// used as datasource query params some day this will need change
continue
}
cmdNode := node.(*CMDNode)
for _, neededVar := range cmdNode.Command.NeedsVars() {
neededNode, ok := registry[neededVar]
if !ok {
return fmt.Errorf("unable to find dependent node '%v'", neededVar)
}
if neededNode.ID() == cmdNode.ID() {
return fmt.Errorf("can not add self referencing node for var '%v' ", neededVar)
}
if cmdNode.CMDType == TypeClassicConditions {
if neededNode.NodeType() != TypeDatasourceNode {
return fmt.Errorf("only data source queries may be inputs to a classic condition, %v is a %v", neededVar, neededNode.NodeType())
}
}
if neededNode.NodeType() == TypeCMDNode {
if neededNode.(*CMDNode).CMDType == TypeClassicConditions {
return fmt.Errorf("classic conditions may not be the input for other expressions, but %v is the input for %v", neededVar, cmdNode.RefID())
}
}
edge := dp.NewEdge(neededNode, cmdNode)
dp.SetEdge(edge)
}
}
return nil
}
| grafana/grafana | pkg/expr/graph.go | GO | agpl-3.0 | 5,270 |
import React from 'react';
import StatisticBox from 'interface/others/StatisticBox';
import { formatNumber, formatPercentage } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import SPELLS from 'common/SPELLS';
import Analyzer from 'parser/core/Analyzer';
const MS_BUFFER=200;
const ABUNDANCE_MANA_REDUCTION = 0.06;
const ABUNDANCE_INCREASED_CRIT = 0.06;
/*
For each Rejuvenation you have active, Regrowth's cost is reduced by 6% and critical effect chance is increased by 6%.
*/
class Abundance extends Analyzer {
manaSavings = [];
critGains = [];
stacks = [];
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.ABUNDANCE_TALENT.id);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if(spellId !== SPELLS.REGROWTH.id) {
return;
}
const abundanceBuff = this.selectedCombatant.getBuff(SPELLS.ABUNDANCE_BUFF.id, event.timestamp, MS_BUFFER);
if(abundanceBuff == null) {
return;
}
if (!this.selectedCombatant.hasBuff(SPELLS.CLEARCASTING_BUFF.id) && !this.selectedCombatant.hasBuff(SPELLS.INNERVATE.id)) {
this.manaSavings.push(abundanceBuff.stacks * ABUNDANCE_MANA_REDUCTION > 1 ? 1 : abundanceBuff.stacks * ABUNDANCE_MANA_REDUCTION);
this.manaCasts++;
}
this.critGains.push((abundanceBuff.stacks * ABUNDANCE_INCREASED_CRIT) > 1 ? 1 : abundanceBuff.stacks * ABUNDANCE_INCREASED_CRIT);
this.stacks.push(abundanceBuff.stacks);
}
statistic() {
const avgManaSavingsPercent = (this.manaSavings.reduce(function(a, b) { return a + b; }, 0) / this.manaSavings.length) || 0;
const avgCritGains = (this.critGains.reduce(function(a, b) { return a + b; }, 0) / this.critGains.length) || 0;
const avgStacks = (this.stacks.reduce(function(a, b) { return a + b; }, 0) / this.stacks.length) || 0;
const avgManaSaings = SPELLS.REGROWTH.manaCost * avgManaSavingsPercent;
// TODO translate these values into healing/throughput.
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.ABUNDANCE_TALENT.id} />}
value={(
<>
{avgStacks.toFixed(2)} Avg. stacks<br />
</>
)}
label={'Abundance'}
tooltip={`Average mana reductions gained was ${formatPercentage(avgManaSavingsPercent)}% or ${formatNumber(avgManaSaings)} mana per cast.<br />
Maximum mana saved was ${avgManaSaings * this.manaSavings.length} <br />
Average crit gain was ${formatPercentage(avgCritGains)}%.
`}
/>
);
}
}
export default Abundance;
| FaideWW/WoWAnalyzer | src/parser/druid/restoration/modules/talents/Abundance.js | JavaScript | agpl-3.0 | 2,620 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MSTech.GestaoEscolar.ObjetosSincronizacao.Entities
{
public class Nivel
{
public int Nvl_id { get; set; }
public int Cur_id { get; set; }
public int Crr_id { get; set; }
public int Crp_id { get; set; }
public int Crp_ordem { get; set; }
public int Cal_id { get; set; }
public int Nvl_ordem { get; set; }
public string Nvl_nome { get; set; }
public DateTime Nvl_dataSincronizacao { get; set; }
public int Tds_id { get; set; }
public List<OrientacaoCurricular> OrientacoesCurriculares { get; set; }
}
}
| prefeiturasp/SME-SGP | Src/MSTech.GestaoEscolar.ObjetosSincronizacao/Entities/Nivel.cs | C# | agpl-3.0 | 701 |
/**
* 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 org.opencps.usermgt;
import com.liferay.portal.kernel.exception.PortalException;
/**
* @author khoavd
*/
public class OutOfLengthUnitEmailException extends PortalException {
public OutOfLengthUnitEmailException() {
super();
}
public OutOfLengthUnitEmailException(String msg) {
super(msg);
}
public OutOfLengthUnitEmailException(String msg, Throwable cause) {
super(msg, cause);
}
public OutOfLengthUnitEmailException(Throwable cause) {
super(cause);
}
} | hltn/opencps | portlets/opencps-portlet/docroot/WEB-INF/service/org/opencps/usermgt/OutOfLengthUnitEmailException.java | Java | agpl-3.0 | 1,076 |
package nl.wietmazairac.bimql.get.attribute;
/******************************************************************************
* Copyright (C) 2009-2017 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import java.util.ArrayList;
import org.bimserver.models.ifc2x3tc1.IfcStructuralLoadSingleForceWarping;
public class GetAttributeSubIfcStructuralLoadSingleForceWarping {
// fields
private Object object;
private String string;
// constructors
public GetAttributeSubIfcStructuralLoadSingleForceWarping(Object object, String string) {
this.object = object;
this.string = string;
}
// methods
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public ArrayList<Object> getResult() {
ArrayList<Object> resultList = new ArrayList<Object>();
if (string.equals("WarpingMoment")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getWarpingMoment());
//1double
}
else if (string.equals("WarpingMomentAsString")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getWarpingMomentAsString());
//1String
}
else if (string.equals("ForceXAsString")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getForceXAsString());
//2String
}
else if (string.equals("ForceYAsString")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getForceYAsString());
//2String
}
else if (string.equals("ForceZAsString")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getForceZAsString());
//2String
}
else if (string.equals("MomentXAsString")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getMomentXAsString());
//2String
}
else if (string.equals("MomentYAsString")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getMomentYAsString());
//2String
}
else if (string.equals("MomentZAsString")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getMomentZAsString());
//2String
}
else if (string.equals("ForceX")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getForceX());
//2double
}
else if (string.equals("ForceY")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getForceY());
//2double
}
else if (string.equals("ForceZ")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getForceZ());
//2double
}
else if (string.equals("MomentX")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getMomentX());
//2double
}
else if (string.equals("MomentY")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getMomentY());
//2double
}
else if (string.equals("MomentZ")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getMomentZ());
//2double
}
else if (string.equals("Name")) {
resultList.add(((IfcStructuralLoadSingleForceWarping) object).getName());
//3String
}
else {
}
return resultList;
}
}
| opensourceBIM/bimql | BimQL/src/nl/wietmazairac/bimql/get/attribute/GetAttributeSubIfcStructuralLoadSingleForceWarping.java | Java | agpl-3.0 | 3,974 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('scrapy', '0003_personvote_timestamp'),
('mps_v2', '0032_auto_20160531_1913'),
]
operations = [
migrations.AddField(
model_name='voting',
name='voting',
field=models.ForeignKey(related_name='stenogram_votings', to='scrapy.Voting', null=True),
),
migrations.AlterUniqueTogether(
name='voting',
unique_together=set([('voting', 'stenogram_topic')]),
),
migrations.RemoveField(
model_name='voting',
name='topic',
),
]
| ManoSeimas/manoseimas.lt | manoseimas/mps_v2/migrations/0033_auto_20160603_1235.py | Python | agpl-3.0 | 745 |
/*
* JBILLING CONFIDENTIAL
* _____________________
*
* [2003] - [2012] Enterprise jBilling Software Ltd.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Enterprise jBilling Software.
* The intellectual and technical concepts contained
* herein are proprietary to Enterprise jBilling Software
* and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden.
*/
/*
* Created on Apr 15, 2003
*
*/
package com.sapienter.jbilling.server.pluggableTask.admin;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.common.FormatLogger;
import com.sapienter.jbilling.server.pluggableTask.PluggableTask;
import com.sapienter.jbilling.server.util.Context;
import org.springframework.util.ClassUtils;
import java.util.ArrayList;
public class PluggableTaskManager<T> {
private static final FormatLogger LOG = new FormatLogger(Logger.getLogger(PluggableTaskManager.class));
private List<PluggableTaskDTO> classes = null;
private Iterator it = null;
private int lastProcessingOrder;
public PluggableTaskManager(Integer entityId, Integer taskCategory)
throws PluggableTaskException {
try {
lastProcessingOrder = 0;
classes = new ArrayList<PluggableTaskDTO>();
classes.addAll(((PluggableTaskDAS) Context.getBean(Context.Name.PLUGGABLE_TASK_DAS)).findByEntityCategory(
entityId, taskCategory));
it = classes.iterator();
LOG.debug("total classes = " + classes.size());
} catch (Exception e) {
throw new PluggableTaskException(e);
}
}
public List<PluggableTaskDTO> getAllTasks() {
return classes;
}
public T getNextClass() throws PluggableTaskException {
if (it != null && it.hasNext()) {
PluggableTaskDTO aRule = (PluggableTaskDTO) it.next();
// check if the order by is in place
int processingOrder = aRule.getProcessingOrder().intValue();
// this is helpful also to identify bad data in the table
if (processingOrder <= lastProcessingOrder) {
// means that the results are not ordered !
LOG.fatal("Results of processing tasks are not ordered");
throw new PluggableTaskException("Processing tasks not ordered");
}
lastProcessingOrder = processingOrder;
String className = aRule.getType().getClassName();
String interfaceName = aRule.getType().getCategory().getInterfaceName();
LOG.debug("Applying task " + className);
return getInstance(className, interfaceName, aRule);
}
return null;
}
/**
* Get a plug-in instance initialized using the parameters from the given PluggableTaskDTO entity. Used to
* load and initialize a plug-in from the database.
*
* @param className class name to get instance of
* @param interfaceName plug-in interface
* @param pluggableTask pluggable task entity to initialize plug-in parameters from
* @return instance of the plug-in class initialized with parameters
* @throws PluggableTaskException throw if an unhandled exception occurs
*/
@SuppressWarnings("unchecked")
public T getInstance(String className, String interfaceName, PluggableTaskDTO pluggableTask)
throws PluggableTaskException {
try {
T instance = (T) getInstance(className, interfaceName);
((PluggableTask) instance).initializeParamters(pluggableTask);
return instance;
} catch (Exception e) {
throw new PluggableTaskException("Unhandled exception initializing plug-in instance", e);
}
}
/**
* Get a plug-in instance for the given class name, ensuring that the resulting instance matches
* the desired plug-in interface.
*
* @param className class name to get instance of
* @param interfaceName plug-in interface
* @return instance of the plug-in class
* @throws PluggableTaskException thrown if plug-in class or interface could not be found, or if plug-in
* does not implement the interface.
*/
public static Object getInstance(String className, String interfaceName) throws PluggableTaskException {
try {
Class task = getClass(className);
Class iface = getClass(interfaceName);
if (task == null) {
throw new PluggableTaskException("Could not load plug-in class '" + className + "', class not found.");
}
if (iface == null) {
throw new PluggableTaskException("Could not load interface '" + interfaceName + "', class not found.");
}
if (!iface.isAssignableFrom(task)) {
throw new PluggableTaskException("Plug-in '" + className + "' does not implement '" + interfaceName + "'");
}
LOG.debug("Creating a new instance of " + className);
return task.newInstance();
} catch (Exception e) {
throw new PluggableTaskException("Unhandled exception fetching plug-in instance", e);
}
}
/**
* Attempts to fetch the class by name. This method goes through all the common class loaders
* allow the loading of plug-ins from 3rd party libraries and to ensure portability across containers.
*
* @param className class to load
* @return class if name found and loadable, null if class could not be found in any class loader
*/
private static Class getClass(String className) {
// attempt to load from the thread class loader
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
return loader.loadClass(className);
} catch (ClassNotFoundException e) {
LOG.debug("Cannot load class from the current thread context class loader.");
}
// last ditch attempt to load from whatever class loader was used to execute this code
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
LOG.fatal("Cannot load class from the caller class loader.", e);
}
return null;
}
}
| maxdelo77/replyit-master-3.2-final | src/java/com/sapienter/jbilling/server/pluggableTask/admin/PluggableTaskManager.java | Java | agpl-3.0 | 6,502 |
<?php
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
App::uses('FileAccessTool', 'Tools');
require_once 'AppShell.php';
/**
* @property User $User
* @property Event $Event
* @property Job $Job
* @property Tag $Tag
* @property Server $Server
*/
class EventShell extends AppShell
{
public $uses = array('Event', 'Post', 'Attribute', 'Job', 'User', 'Task', 'Allowedlist', 'Server', 'Organisation', 'Correlation', 'Tag');
public $tasks = array('ConfigLoad');
public function getOptionParser()
{
$parser = parent::getOptionParser();
$parser->addSubcommand('import', array(
'help' => __('Import event from file into MISP.'),
'parser' => array(
'arguments' => array(
'user_id' => ['help' => __('User ID that will owner of uploaded event.'), 'required' => true],
'file' => ['help' => __('Path to JSON MISP file, can be gzipped or bz2 compressed.'), 'required' => true],
),
'options' => [
'take-ownership' => ['boolean' => true],
'publish' => ['boolean' => true],
],
)
));
$parser->addSubcommand('testEventNotificationEmail', [
'help' => __('Generate event notification email in EML format.'),
'parser' => [
'arguments' => [
'event_id' => ['help' => __('Event ID'), 'required' => true],
'user_id' => ['help' => __('User ID'), 'required' => true],
],
],
]);
$parser->addSubcommand('duplicateTags', [
'help' => __('Show duplicate tags'),
]);
$parser->addSubcommand('mergeTags', [
'help' => __('Merge tags'),
'parser' => [
'arguments' => array(
'source' => ['help' => __('Source tag ID or name. Source tag will be deleted.'), 'required' => true],
'destination' => ['help' => __('Destination tag ID or name.'), 'required' => true],
)
],
]);
return $parser;
}
public function import()
{
list($userId, $path) = $this->args;
$user = $this->getUser($userId);
if (!file_exists($path)) {
$this->error("File '$path' does not exists.");
}
if (!is_readable($path)) {
$this->error("File '$path' is not readable.");
}
$pathInfo = pathinfo($path);
if ($pathInfo['extension'] === 'gz') {
$content = file_get_contents("compress.zlib://$path");
$extension = pathinfo($pathInfo['filename'], PATHINFO_EXTENSION);
} else if ($pathInfo['extension'] === 'bz2') {
$content = file_get_contents("compress.bzip2://$path");
$extension = pathinfo($pathInfo['filename'], PATHINFO_EXTENSION);
} else {
$content = file_get_contents($path);
$extension = $pathInfo['extension'];
}
if ($content === false) {
$this->error("Could not read content from '$path'.");
}
$isXml = $extension === 'xml';
$takeOwnership = $this->param('take_ownership');
$publish = $this->param('publish');
$results = $this->Event->addMISPExportFile($user, $content, $isXml, $takeOwnership, $publish);
foreach ($results as $result) {
if (is_numeric($result['result'])) {
$this->out("Event #{$result['id']}: {$result['info']} imported.");
} else {
$this->out("Could not import event because of validation errors: " . json_encode($result['validationIssues']));
}
}
}
public function mergeTags()
{
list($source, $destination) = $this->args;
$output = $this->Tag->mergeTag($source, $destination);
$this->out("Merged tag `{$output['source_tag']['Tag']['name']}` into `{$output['destination_tag']['Tag']['name']}`");
$this->out(__("%s attribute or event tags changed", $output['changed']));
}
public function duplicateTags()
{
$output = $this->Tag->duplicateTags();
$this->out($this->json($output));
}
public function doPublish()
{
$this->ConfigLoad->execute();
if (empty($this->args[0])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Do publish'] . PHP_EOL);
}
$id = $this->args[0];
$this->Event->id = $id;
if (!$this->Event->exists()) {
throw new NotFoundException(__('Invalid event'));
}
$this->Job->create();
$data = array(
'worker' => 'default',
'job_type' => 'doPublish',
'job_input' => $id,
'status' => 0,
'retries' => 0,
'org' => 0,
'message' => 'Job created.',
);
$this->Job->save($data);
// update the event and set the from field to the current instance's organisation from the bootstrap. We also need to save id and info for the logs.
$this->Event->recursive = -1;
$event = $this->Event->read(null, $id);
$event['Event']['published'] = 1;
$fieldList = array('published', 'id', 'info');
$this->Event->save($event, array('fieldList' => $fieldList));
// only allow form submit CSRF protection.
$this->Job->save([
'status' => Job::STATUS_COMPLETED,
'message' => 'Job done.'
]);
}
public function correlateValue()
{
$this->ConfigLoad->execute();
$value = $this->args[0];
if (!empty($this->args[1])) {
$this->Job->id = intval($this->args[1]);
} else {
$this->Job->createJob(
'SYSTEM',
Job::WORKER_DEFAULT,
'correlateValue',
$value,
'Job created.'
);
}
$this->Correlation->correlateValue($value, $this->Job->id);
$this->Job->save([
'status' => Job::STATUS_COMPLETED,
'message' => 'Job done.',
'progress' => 100
]);
}
public function cache()
{
$this->ConfigLoad->execute();
if (empty($this->args[0]) || empty($this->args[1]) || empty($this->args[2])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Cache event'] . PHP_EOL);
}
$timeStart = time();
$userId = $this->args[0];
$id = $this->args[1];
$user = $this->getUser($userId);
$this->Job->id = $id;
$export_type = $this->args[2];
file_put_contents('/tmp/test', $export_type);
$typeData = $this->Event->export_types[$export_type];
if (!in_array($export_type, array_keys($this->Event->export_types))) {
$this->Job->saveField('progress', 100);
$timeDelta = (time()-$timeStart);
$this->Job->saveField('message', 'Job Failed due to invalid export format. (in '.$timeDelta.'s)');
$this->Job->saveField('date_modified', date("Y-m-d H:i:s"));
return false;
}
if ($export_type == 'text') {
$types = array_keys($this->Attribute->typeDefinitions);
$typeCount = count($types);
foreach ($types as $k => $type) {
$typeData['params']['type'] = $type;
$this->__runCaching($user, $typeData, false, $export_type, '_' . $type);
$this->Job->saveField('message', 'Processing all attributes of type '. $type . '.');
$this->Job->saveField('progress', intval($k / $typeCount));
}
} else {
$this->__runCaching($user, $typeData, $id, $export_type);
}
$this->Job->saveField('progress', 100);
$timeDelta = (time()-$timeStart);
$this->Job->saveField('message', 'Job done. (in '.$timeDelta.'s)');
$this->Job->saveField('date_modified', date("Y-m-d H:i:s"));
}
private function __runCaching($user, $typeData, $id, $export_type, $subType = '')
{
$this->ConfigLoad->execute();
$export_type = strtolower($typeData['type']);
$final = $this->{$typeData['scope']}->restSearch($user, $typeData['params']['returnFormat'], $typeData['params'], false, $id);
$dir = new Folder(APP . 'tmp/cached_exports/' . $export_type, true, 0750);
//echo PHP_EOL . $dir->pwd() . DS . 'misp.' . $export_type . $subType . '.ADMIN' . $typeData['extension'] . PHP_EOL;
if ($user['Role']['perm_site_admin']) {
$file = new File($dir->pwd() . DS . 'misp.' . $export_type . $subType . '.ADMIN' . $typeData['extension']);
} else {
$file = new File($dir->pwd() . DS . 'misp.' . $export_type . $subType . '.' . $user['Organisation']['name'] . $typeData['extension']);
}
$file->write($final);
$file->close();
return true;
}
public function cachebro()
{
$this->ConfigLoad->execute();
if (empty($this->args[0]) || empty($this->args[1])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Cache bro'] . PHP_EOL);
}
$timeStart = time();
$userId = $this->args[0];
$user = $this->getUser($userId);
$id = $this->args[1];
$this->Job->id = $id;
$this->Job->saveField('progress', 1);
App::uses('BroExport', 'Export');
$export = new BroExport();
$types = array_keys($export->mispTypes);
$typeCount = count($types);
$dir = new Folder(APP . DS . '/tmp/cached_exports/bro', true, 0750);
if ($user['Role']['perm_site_admin']) {
$file = new File($dir->pwd() . DS . 'misp.bro.ADMIN.intel');
} else {
$file = new File($dir->pwd() . DS . 'misp.bro.' . $user['Organisation']['name'] . '.intel');
}
$file->write('');
$skipHeader = false;
foreach ($types as $k => $type) {
$final = $this->Attribute->bro($user, $type, false, false, false, false, false, false, $skipHeader);
$skipHeader = true;
foreach ($final as $attribute) {
$file->append($attribute . PHP_EOL);
}
$this->Job->saveField('progress', $k / $typeCount * 100);
}
$file->close();
$timeDelta = (time()-$timeStart);
$this->Job->saveField('progress', 100);
$this->Job->saveField('message', 'Job done. (in '.$timeDelta.'s)');
$this->Job->saveField('date_modified', date("Y-m-d H:i:s"));
}
public function alertemail()
{
$this->ConfigLoad->execute();
if (empty($this->args[0]) || empty($this->args[1]) || empty($this->args[2])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Alert email'] . PHP_EOL);
}
$userId = $this->args[0];
$jobId = $this->args[1];
$eventId = $this->args[2];
$oldpublish = $this->args[3];
$user = $this->getUser($userId);
$this->Event->sendAlertEmail($eventId, $user, $oldpublish, $jobId);
}
public function contactemail()
{
if (empty($this->args[0]) || empty($this->args[1]) || !isset($this->args[2]) ||
empty($this->args[3]) || empty($this->args[4])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Contact email'] . PHP_EOL);
}
$id = $this->args[0];
$message = $this->args[1];
$all = $this->args[2];
$userId = $this->args[3];
$jobId = $this->args[4];
$user = $this->getUser($userId);
$result = $this->Event->sendContactEmail($id, $message, $all, $user);
$this->Job->saveStatus($jobId, $result);
}
public function postsemail()
{
$this->ConfigLoad->execute();
if (
empty($this->args[0]) || empty($this->args[1]) || empty($this->args[2]) ||
empty($this->args[3]) || empty($this->args[4]) || empty($this->args[5])
) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Posts email'] . PHP_EOL);
}
$userId = intval($this->args[0]);
$postId = intval($this->args[1]);
$eventId = intval($this->args[2]);
$title = $this->args[3];
$message = $this->args[4];
$this->Job->id = intval($this->args[5]);
$result = $this->Post->sendPostsEmail($userId, $postId, $eventId, $title, $message);
if ($result) {
$this->Job->save([
'progress' => 100,
'message' => 'Emails sent.',
'date_modified' => date('Y-m-d H:i:s'),
'status' => Job::STATUS_COMPLETED
]);
} else {
$this->Job->save([
'date_modified' => date('Y-m-d H:i:s'),
'status' => Job::STATUS_FAILED
]);
}
}
public function enqueueCaching()
{
$this->ConfigLoad->execute();
if (empty($this->args[0])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Enqueue caching'] . PHP_EOL);
}
$timestamp = $this->args[0];
$task = $this->Task->findByType('cache_exports');
// If the next execution time and the timestamp don't match, it means that this task is no longer valid as the time for the execution has since being scheduled
// been updated.
if ($task['Task']['next_execution_time'] != $timestamp) return;
$users = $this->User->find('all', array(
'recursive' => -1,
'conditions' => array(
'Role.perm_site_admin' => 0,
'User.disabled' => 0,
),
'contain' => array(
'Organisation' => array('fields' => array('name')),
'Role' => array('fields' => array('perm_site_admin'))
),
'fields' => array('User.org_id', 'User.id'),
'group' => array('User.org_id')
));
$site_admin = $this->User->find('first', array(
'recursive' => -1,
'conditions' => array(
'Role.perm_site_admin' => 1,
'User.disabled' => 0
),
'contain' => array(
'Organisation' => array('fields' => array('name')),
'Role' => array('fields' => array('perm_site_admin'))
),
'fields' => array('User.org_id', 'User.id')
));
$users[] = $site_admin;
if ($task['Task']['timer'] > 0) $this->Task->reQueue($task, 'cache', 'EventShell', 'enqueueCaching', false, false);
// Queue a set of exports for admins. This "ADMIN" organisation. The organisation of the admin users doesn't actually matter, it is only used to indentify
// the special cache files containing all events
$i = 0;
foreach ($users as $user) {
foreach ($this->Event->export_types as $k => $type) {
if ($k == 'stix') continue;
$this->Job->cache($k, $user['User']);
$i++;
}
}
$this->Task->id = $task['Task']['id'];
$this->Task->saveField('message', $i . ' job(s) started at ' . date('d/m/Y - H:i:s') . '.');
}
public function publish()
{
$this->ConfigLoad->execute();
if (empty($this->args[0]) || empty($this->args[2]) || empty($this->args[3])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Publish event'] . PHP_EOL);
}
$id = $this->args[0];
$passAlong = $this->args[1];
$jobId = $this->args[2];
$userId = $this->args[3];
$user = $this->getUser($userId);
$job = $this->Job->read(null, $jobId);
$this->Event->Behaviors->unload('SysLogLogable.SysLogLogable');
$result = $this->Event->publish($id, $passAlong);
$job['Job']['progress'] = 100;
$job['Job']['status'] = Job::STATUS_COMPLETED;
$job['Job']['date_modified'] = date("Y-m-d H:i:s");
if ($result) {
$job['Job']['message'] = 'Event published.';
} else {
$job['Job']['message'] = 'Event published, but the upload to other instances may have failed.';
}
$this->Job->save($job);
$log = ClassRegistry::init('Log');
$log->createLogEntry($user, 'publish', 'Event', $id, 'Event (' . $id . '): published.', 'published () => (1)');
}
public function publish_sightings()
{
if (empty($this->args[0]) || empty($this->args[2]) || empty($this->args[3])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Publish sightings'] . PHP_EOL);
}
list($id, $passAlong, $jobId, $userId) = $this->args;
$user = $this->getUser($userId);
$sightingsUuidsToPush = [];
if (isset($this->args[4])) { // push just specific sightings
$path = $this->args[4][0] === '/' ? $this->args[4] : (APP . 'tmp/cache/ingest' . DS . $this->args[4]);
$sightingsUuidsToPush = $this->Event->jsonDecode(FileAccessTool::readAndDelete($path));
}
$this->Event->Behaviors->unload('SysLogLogable.SysLogLogable');
$result = $this->Event->publish_sightings($id, $passAlong, $sightingsUuidsToPush);
$count = count($sightingsUuidsToPush);
$message = $count === 0 ? "All sightings published" : "$count sightings published";
if ($result) {
$message .= '.';
} else {
$message .= ', but the upload to other instances may have failed.';
}
$this->Job->saveStatus($jobId, true, $message);
$log = ClassRegistry::init('Log');
$title = $count === 0 ? "All sightings for event published." : "$count sightings for event published.";
$log->createLogEntry($user, 'publish_sightings', 'Event', $id, $title, 'publish_sightings updated');
}
public function publish_galaxy_clusters()
{
$this->ConfigLoad->execute();
if (empty($this->args[0]) || empty($this->args[1]) || empty($this->args[2]) || !array_key_exists(3, $this->args)) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Publish Galaxy clusters'] . PHP_EOL);
}
$clusterId = $this->args[0];
$jobId = $this->args[1];
$userId = $this->args[2];
$passAlong = $this->args[3];
$user = $this->getUser($userId);
$job = $this->Job->read(null, $jobId);
$this->GalaxyCluster = ClassRegistry::init('GalaxyCluster');
$result = $this->GalaxyCluster->publish($clusterId, $passAlong=$passAlong);
$job['Job']['progress'] = 100;
$job['Job']['date_modified'] = date("Y-m-d H:i:s");
if ($result) {
$job['Job']['message'] = 'Galaxy cluster published.';
} else {
$job['Job']['message'] = 'Galaxy cluster published, but the upload to other instances may have failed.';
}
$this->Job->save($job);
$log = ClassRegistry::init('Log');
$log->createLogEntry($user, 'publish', 'GalaxyCluster', $clusterId, 'GalaxyCluster (' . $clusterId . '): published.', 'published () => (1)');
}
public function enrichment()
{
$this->ConfigLoad->execute();
if (empty($this->args[0]) || empty($this->args[1]) || empty($this->args[2])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Run enrichment'] . PHP_EOL);
}
$userId = $this->args[0];
$user = $this->getUser($userId);
$eventId = $this->args[1];
$modulesRaw = $this->args[2];
try {
$modules = json_decode($modulesRaw, true);
} catch (Exception $e) {
die('Invalid module JSON');
}
if (!empty($this->args[3])) {
$jobId = $this->args[3];
} else {
$this->Job->create();
$data = array(
'worker' => 'default',
'job_type' => 'enrichment',
'job_input' => 'Event: ' . $eventId . ' modules: ' . $modulesRaw,
'status' => 0,
'retries' => 0,
'org' => $user['Organisation']['name'],
'message' => 'Enriching event.',
);
$this->Job->save($data);
$jobId = $this->Job->id;
}
$job = $this->Job->read(null, $jobId);
$options = array(
'user' => $user,
'event_id' => $eventId,
'modules' => $modules
);
$result = $this->Event->enrichment($options);
$job['Job']['progress'] = 100;
$job['Job']['date_modified'] = date("Y-m-d H:i:s");
if ($result) {
$job['Job']['message'] = 'Added ' . $result . ' attribute' . ($result > 1 ? 's.' : '.');
} else {
$job['Job']['message'] = 'Enrichment finished, but no attributes added.';
}
echo $job['Job']['message'] . PHP_EOL;
$this->Job->save($job);
$log = ClassRegistry::init('Log');
$log->createLogEntry($user, 'enrichment', 'Event', $eventId, 'Event (' . $eventId . '): enriched.', 'enriched () => (1)');
}
public function processfreetext()
{
if (empty($this->args[0])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Process free text'] . PHP_EOL);
}
$inputFile = $this->args[0];
$inputFile = $inputFile[0] === '/' ? $inputFile : APP . 'tmp/cache/ingest' . DS . $inputFile;
$inputData = FileAccessTool::readAndDelete($inputFile);
$inputData = $this->Event->jsonDecode($inputData);
Configure::write('CurrentUserId', $inputData['user']['id']);
$this->Event->processFreeTextData(
$inputData['user'],
$inputData['attributes'],
$inputData['id'],
$inputData['default_comment'],
$inputData['proposals'],
$inputData['adhereToWarninglists'],
$inputData['jobId']
);
return true;
}
public function processmoduleresult()
{
if (empty($this->args[0])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Process module result'] . PHP_EOL);
}
$inputFile = $this->args[0];
$inputFile = $inputFile[0] === '/' ? $inputFile : APP . 'tmp/cache/ingest' . DS . $inputFile;
$inputData = FileAccessTool::readAndDelete($inputFile);
$inputData = $this->Event->jsonDecode($inputData);
Configure::write('CurrentUserId', $inputData['user']['id']);
$this->Event->processModuleResultsData(
$inputData['user'],
$inputData['misp_format'],
$inputData['id'],
$inputData['default_comment'],
$inputData['jobId']
);
return true;
}
public function recoverEvent()
{
$this->ConfigLoad->execute();
if (empty($this->args[0]) || empty($this->args[1])) {
die('Usage: ' . $this->Server->command_line_functions['event_management_tasks']['data']['Recover event'] . PHP_EOL);
}
$jobId = $this->args[0];
$id = $this->args[1];
$job = $this->Job->read(null, $jobId);
$job['Job']['progress'] = 1;
$job['Job']['date_modified'] = date("Y-m-d H:i:s");
$job['Job']['message'] = __('Recovering event %s', $id);
$this->Job->save($job);
$result = $this->Event->recoverEvent($id);
$job['Job']['progress'] = 100;
$job['Job']['date_modified'] = date("Y-m-d H:i:s");
$job['Job']['message'] = __('Recovery complete. Event #%s recovered, using %s log entries.', $id, $result);
$this->Job->save($job);
}
public function testEventNotificationEmail()
{
list($eventId, $userId) = $this->args;
$user = $this->getUser($userId);
$eventForUser = $this->Event->fetchEvent($user, [
'eventid' => $eventId,
'includeAllTags' => true,
'includeEventCorrelations' => true,
'noEventReports' => true,
'noSightings' => true,
'metadata' => Configure::read('MISP.event_alert_metadata_only') || Configure::read('MISP.publish_alerts_summary_only'),
]);
if (empty($eventForUser)) {
$this->error("Event with ID $eventId not exists or given user don't have permission to access it.");
}
$emailTemplate = $this->Event->prepareAlertEmail($eventForUser[0], $user);
App::uses('SendEmail', 'Tools');
App::uses('GpgTool', 'Tools');
$sendEmail = new SendEmail(GpgTool::initializeGpg());
$sendEmail->setTransport('Debug');
$result = $sendEmail->sendToUser(['User' => $user], null, $emailTemplate);
echo $result['contents']['headers'] . "\n\n" . $result['contents']['message'] . "\n";
}
/**
* @param int $userId
* @return array
*/
private function getUser($userId)
{
$user = $this->User->getAuthUser($userId, true);
if (empty($user)) {
$this->error("User with ID $userId does not exists.");
}
Configure::write('CurrentUserId', $user['id']); // for audit logging purposes
return $user;
}
public function generateTopCorrelations()
{
$this->ConfigLoad->execute();
$jobId = $this->args[0];
$job = $this->Job->read(null, $jobId);
$job['Job']['progress'] = 1;
$job['Job']['date_modified'] = date("Y-m-d H:i:s");
$job['Job']['message'] = __('Generating top correlations list.');
$this->Job->save($job);
$result = $this->Correlation->generateTopCorrelations($jobId);
$job['Job']['progress'] = 100;
$job['Job']['date_modified'] = date("Y-m-d H:i:s");
$job['Job']['message'] = __('Job done.');
$this->Job->save($job);
}
}
| SteveClement/MISP | app/Console/Command/EventShell.php | PHP | agpl-3.0 | 26,597 |
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#
# LICENCE: This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# IRC #navitia on freenode
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
from datetime import datetime
from jormungandr.interfaces.v1.serializer.base import PbNestedSerializer, EnumField, EnumListField
from jormungandr.interfaces.v1.serializer import pt, jsonschema, base
from jormungandr.interfaces.v1.serializer.fields import LinkSchema, MultiLineStringField
from jormungandr.interfaces.v1.make_links import create_internal_link
from jormungandr.interfaces.v1.serializer.jsonschema.fields import TimeOrDateTimeType
from jormungandr.utils import timestamp_to_str
def _get_links(obj):
display_info = obj.pt_display_informations
uris = display_info.uris
l = [("line", uris.line),
("company", uris.company),
("vehicle_journey", uris.vehicle_journey),
("route", uris.route),
("commercial_mode", uris.commercial_mode),
("physical_mode", uris.physical_mode),
("network", uris.network)]
return [{"type": k, "id": v} for k, v in l if v != ""] + base.make_notes(display_info.notes)
class PassageSerializer(PbNestedSerializer):
route = pt.RouteSerializer()
stop_point = pt.StopPointSerializer()
stop_date_time = pt.StopDateTimeSerializer()
display_informations = pt.VJDisplayInformationSerializer(attr='pt_display_informations')
links = jsonschema.MethodField(schema_type=LinkSchema(many=True))
def get_links(self, obj):
return _get_links(obj)
class DateTimeTypeSerializer(PbNestedSerializer):
date_time = jsonschema.MethodField(schema_type=TimeOrDateTimeType, display_none=True)
additional_informations = pt.AdditionalInformation(attr='additional_informations', display_none=True)
links = pt.PropertiesLinksSerializer(attr="properties")
data_freshness = EnumField(attr="realtime_level", display_none=True)
def get_date_time(self, obj):
__date_time_null_value__ = 2**64 - 1
if obj.time == __date_time_null_value__:
return ""
if obj.HasField('date'):
return timestamp_to_str(obj.date + obj.time)
return datetime.utcfromtimestamp(obj.time).strftime('%H%M%S')
class StopScheduleSerializer(PbNestedSerializer):
stop_point = pt.StopPointSerializer()
route = pt.RouteSerializer()
additional_informations = EnumField(attr="response_status", display_none=True)
display_informations = pt.RouteDisplayInformationSerializer(attr='pt_display_informations')
date_times = DateTimeTypeSerializer(many=True, display_none=True)
links = jsonschema.MethodField(schema_type=LinkSchema(many=True))
def get_links(self, obj):
return _get_links(obj)
class RowSerializer(PbNestedSerializer):
stop_point = pt.StopPointSerializer()
date_times = DateTimeTypeSerializer(many=True, display_none=True)
class HeaderSerializer(PbNestedSerializer):
additional_informations = EnumListField(attr='additional_informations', display_none=True)
display_informations = pt.VJDisplayInformationSerializer(attr='pt_display_informations')
links = jsonschema.MethodField(schema_type=LinkSchema(many=True))
def get_links(self, obj):
return _get_links(obj)
class TableSerializer(PbNestedSerializer):
rows = RowSerializer(many=True, display_none=True)
headers = HeaderSerializer(many=True, display_none=True)
class RouteScheduleSerializer(PbNestedSerializer):
table = TableSerializer()
display_informations = pt.RouteDisplayInformationSerializer(attr='pt_display_informations')
geojson = MultiLineStringField(display_none=False)
additional_informations = EnumField(attr="response_status", display_none=True)
links = jsonschema.MethodField(schema_type=LinkSchema(many=True))
def get_links(self, obj):
return _get_links(obj)
| antoine-de/navitia | source/jormungandr/jormungandr/interfaces/v1/serializer/schedule.py | Python | agpl-3.0 | 4,895 |
package org.marsik.elshelves.api.entities;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Getter;
import lombok.Setter;
import org.marsik.elshelves.ember.EmberModelName;
import org.marsik.elshelves.api.entities.idresolvers.ItemIdResolver;
import java.util.Set;
import java.util.UUID;
@Getter
@Setter
@JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "id", resolver = ItemIdResolver.class)
@JsonTypeName("item")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = "_type",
visible = true,
defaultImpl = ItemApiModel.class)
public class ItemApiModel extends LotApiModel {
public ItemApiModel(UUID id) {
super(id);
}
public ItemApiModel() {
}
public ItemApiModel(String uuid) {
super(uuid);
}
Set<RequirementApiModel> requirements;
Boolean finished;
/**
* Type only used when new project is started. Can't be changed.
*/
PartTypeApiModel type;
@Override
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
| MarSik/shelves | lib/api/src/main/java/org/marsik/elshelves/api/entities/ItemApiModel.java | Java | agpl-3.0 | 1,382 |
/*
* Aphelion
* Copyright (c) 2013 Joshua Edwards
*
* This file is part of Aphelion
*
* Aphelion is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* Aphelion 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 Affero General Public License
* along with Aphelion. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, the following supplemental terms apply, based on section 7 of
* the GNU Affero General Public License (version 3):
* a) Preservation of all legal notices and author attributions
* b) Prohibition of misrepresentation of the origin of this material, and
* modified versions are required to be marked in reasonable ways as
* different from the original version (for example by appending a copyright notice).
*
* Linking this library statically or dynamically with other modules is making a
* combined work based on this library. Thus, the terms and conditions of the
* GNU Affero General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library.
*/
package aphelion.shared.map.tile.classic;
import org.newdawn.slick.Animation;
import aphelion.client.resource.AsyncTexture;
import aphelion.client.graphics.screen.Camera;
import aphelion.shared.map.MapClassic;
import aphelion.shared.map.tile.TileType;
import aphelion.shared.resource.ResourceDB;
import aphelion.shared.swissarmyknife.Point;
import aphelion.shared.swissarmyknife.SwissArmyKnife;
public class TileGoal extends TileTeam
{
private AsyncTexture textureGoalEnemy,
textureGoalTeam;
private Animation anim;
public TileGoal(ResourceDB db, short tileID)
{
super(db, tileID);
this.layer = TileType.TILE_LAYER.ANIMATED;
if (db != null)
{
textureGoalEnemy = db.getTextureLoader().getTexture("mapclassic.goal.enemy");
textureGoalTeam = db.getTextureLoader().getTexture("mapclassic.goal.team");
}
}
@Override
public void render(Camera camera, int tileX, int tileY, MapClassic map)
{
if (textureGoalEnemy.isLoaded() && textureGoalTeam.isLoaded())
{
if (anim == null)
{
if (camera.getFrequency() == this.getFrequency())
{
anim = SwissArmyKnife.spriteToAnimation(textureGoalTeam.getCachedImage(), 9, 1, 100);
}
else
{
anim = SwissArmyKnife.spriteToAnimation(textureGoalEnemy.getCachedImage(), 9, 1, 100);
}
}
}
else
{
return;
}
Point screenPos = new Point();
camera.mapToScreenPosition(tileX * 16, tileY * 16, screenPos);
anim.draw(
screenPos.x,
screenPos.y,
getSize() * 16 * camera.zoom,
getSize() * 16 * camera.zoom);
}
@Override
public boolean physicsIsSolid()
{
return false;
}
}
| Periapsis/aphelion | src/main/java/aphelion/shared/map/tile/classic/TileGoal.java | Java | agpl-3.0 | 4,254 |
// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCSample.Web.Models
{
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Company { get; set; }
public string Title { get; set; }
public string Email { get; set; }
public string Image { get; set; }
}
} | Evilazaro/MCSDAzureTraining | Implement and Design Websites/HOL/ASPNETAzureWebSites/Source/Assets/MVCSample.Web/MVCSample.Web/Models/Customer.cs | C# | agpl-3.0 | 1,429 |
# Copyright 2017-2019 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import exceptions
from odoo.tests import common
class TestPartnerDeduplicateAcl(common.TransactionCase):
def setUp(self):
super().setUp()
self.partner_1 = self.env["res.partner"].create(
{
"name": "Partner 1",
"email": "partner1@example.org",
"is_company": True,
"parent_id": False,
}
)
self.partner_2 = self.partner_1.copy()
self.partner_2.write({"name": "Partner 1", "email": "partner2@example.org"})
self.user = self.env["res.users"].create(
{
"login": "test_crm_deduplicate_acl",
"name": "test_crm_deduplicate_acl",
"email": "partner_deduplicate_acl@example.org",
"groups_id": [
(4, self.env.ref("base.group_user").id),
(4, self.env.ref("base.group_partner_manager").id),
],
}
)
self.wizard = (
self.env["base.partner.merge.automatic.wizard"]
.with_user(self.user)
.create({"group_by_name": True})
)
def test_same_email_restriction(self):
self.wizard.action_start_manual_process()
with self.assertRaises(exceptions.UserError):
self.wizard.action_merge()
self.user.groups_id = [
(4, self.env.ref("partner_deduplicate_acl.group_unrestricted").id)
]
# Now there shouldn't be error
self.wizard.action_merge()
| OCA/partner-contact | partner_deduplicate_acl/tests/test_partner_deduplicate_acl.py | Python | agpl-3.0 | 1,662 |
<?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20150317013950 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE payment CHANGE paymentIPN paymentIPN LONGTEXT DEFAULT NULL COMMENT \'(DC2Type:array)\'');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE payment CHANGE paymentIPN paymentIPN LONGTEXT NOT NULL COLLATE utf8_unicode_ci COMMENT \'(DC2Type:array)\'');
}
}
| LePartiDeGauche/congres | app/DoctrineMigrations/Version20150317013950.php | PHP | agpl-3.0 | 1,165 |
#
# Copyright (C) 2011 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
require File.expand_path(File.dirname(__FILE__) + '/../sharding_spec_helper.rb')
describe Account do
it "should provide a list of courses" do
expect{ Account.new.courses }.not_to raise_error
end
context "equella_settings" do
it "should respond to :equella_settings" do
expect(Account.new).to respond_to(:equella_settings)
expect(Account.new.equella_settings).to be_nil
end
it "should return the equella_settings data if defined" do
a = Account.new
a.equella_endpoint = "http://oer.equella.com/signon.do"
expect(a.equella_settings).not_to be_nil
expect(a.equella_settings.endpoint).to eql("http://oer.equella.com/signon.do")
expect(a.equella_settings.default_action).not_to be_nil
end
end
# it "should have an atom feed" do
# account_model
# @a.to_atom.should be_is_a(Atom::Entry)
# end
context "course lists" do
before :once do
@account = Account.create!
process_csv_data_cleanly([
"user_id,login_id,first_name,last_name,email,status",
"U001,user1,User,One,user1@example.com,active",
"U002,user2,User,Two,user2@example.com,active",
"U003,user3,User,Three,user3@example.com,active",
"U004,user4,User,Four,user4@example.com,active",
"U005,user5,User,Five,user5@example.com,active",
"U006,user6,User,Six,user6@example.com,active",
"U007,user7,User,Seven,user7@example.com,active",
"U008,user8,User,Eight,user8@example.com,active",
"U009,user9,User,Nine,user9@example.com,active",
"U010,user10,User,Ten,user10@example.com,active",
"U011,user11,User,Eleven,user11@example.com,deleted"
])
process_csv_data_cleanly([
"term_id,name,status,start_date,end_date",
"T001,Term 1,active,,",
"T002,Term 2,active,,",
"T003,Term 3,active,,"
])
process_csv_data_cleanly([
"course_id,short_name,long_name,account_id,term_id,status",
"C001,C001,Test Course 1,,T001,active",
"C002,C002,Test Course 2,,T001,deleted",
"C003,C003,Test Course 3,,T002,deleted",
"C004,C004,Test Course 4,,T002,deleted",
"C005,C005,Test Course 5,,T003,active",
"C006,C006,Test Course 6,,T003,active",
"C007,C007,Test Course 7,,T003,active",
"C008,C008,Test Course 8,,T003,active",
"C009,C009,Test Course 9,,T003,active",
"C001S,C001S,Test search Course 1,,T001,active",
"C002S,C002S,Test search Course 2,,T001,deleted",
"C003S,C003S,Test search Course 3,,T002,deleted",
"C004S,C004S,Test search Course 4,,T002,deleted",
"C005S,C005S,Test search Course 5,,T003,active",
"C006S,C006S,Test search Course 6,,T003,active",
"C007S,C007S,Test search Course 7,,T003,active",
"C008S,C008S,Test search Course 8,,T003,active",
"C009S,C009S,Test search Course 9,,T003,active"
])
process_csv_data_cleanly([
"section_id,course_id,name,start_date,end_date,status",
"S001,C001,Sec1,,,active",
"S002,C002,Sec2,,,active",
"S003,C003,Sec3,,,active",
"S004,C004,Sec4,,,active",
"S005,C005,Sec5,,,active",
"S006,C006,Sec6,,,active",
"S007,C007,Sec7,,,active",
"S008,C001,Sec8,,,active",
"S009,C008,Sec9,,,active",
"S001S,C001S,Sec1,,,active",
"S002S,C002S,Sec2,,,active",
"S003S,C003S,Sec3,,,active",
"S004S,C004S,Sec4,,,active",
"S005S,C005S,Sec5,,,active",
"S006S,C006S,Sec6,,,active",
"S007S,C007S,Sec7,,,active",
"S008S,C001S,Sec8,,,active",
"S009S,C008S,Sec9,,,active"
])
process_csv_data_cleanly([
"course_id,user_id,role,section_id,status,associated_user_id",
",U001,student,S001,active,",
",U005,student,S005,active,",
",U006,student,S006,deleted,",
",U007,student,S007,active,",
",U008,student,S008,active,",
",U009,student,S005,deleted,",
",U001,student,S001S,active,",
",U005,student,S005S,active,",
",U006,student,S006S,deleted,",
",U007,student,S007S,active,",
",U008,student,S008S,active,",
",U009,student,S005S,deleted,"
])
end
context "fast list" do
it "should list associated courses" do
expect(@account.fast_all_courses.map(&:sis_source_id).sort).to eq [
"C001", "C005", "C006", "C007", "C008", "C009",
"C001S", "C005S", "C006S", "C007S", "C008S", "C009S", ].sort
end
it "should list associated courses by term" do
expect(@account.fast_all_courses({:term => EnrollmentTerm.where(sis_source_id: "T001").first}).map(&:sis_source_id).sort).to eq ["C001", "C001S"]
expect(@account.fast_all_courses({:term => EnrollmentTerm.where(sis_source_id: "T002").first}).map(&:sis_source_id).sort).to eq []
expect(@account.fast_all_courses({:term => EnrollmentTerm.where(sis_source_id: "T003").first}).map(&:sis_source_id).sort).to eq ["C005", "C006", "C007", "C008", "C009", "C005S", "C006S", "C007S", "C008S", "C009S"].sort
end
it "don't double-count cross-listed courses" do
def check_account(account, expected_length, expected_course_names)
actual_courses = account.fast_all_courses
expect(actual_courses.length).to eq expected_length
actual_course_names = actual_courses.pluck("name").sort!
expect(actual_course_names).to eq(expected_course_names.sort!)
end
root_account = Account.create!
account_a = Account.create!({ :root_account => root_account })
account_b = Account.create!({ :root_account => root_account })
course_a = course_factory({ :account => account_a, :course_name => "course_a" })
course_b = course_factory({ :account => account_b, :course_name => "course_b" })
course_b.course_sections.create!({ :name => "section_b" })
course_b.course_sections.first.crosslist_to_course(course_a)
check_account(account_a, 1, ["course_a"])
check_account(account_b, 1, ["course_b"])
end
it "should list associated nonenrollmentless courses" do
expect(@account.fast_all_courses({:hide_enrollmentless_courses => true}).map(&:sis_source_id).sort).to eq ["C001", "C005", "C007", "C001S", "C005S", "C007S"].sort #C007 probably shouldn't be here, cause the enrollment section is deleted, but we kinda want to minimize database traffic
end
it "should list associated nonenrollmentless courses by term" do
expect(@account.fast_all_courses({:term => EnrollmentTerm.where(sis_source_id: "T001").first, :hide_enrollmentless_courses => true}).map(&:sis_source_id).sort).to eq ["C001", "C001S"]
expect(@account.fast_all_courses({:term => EnrollmentTerm.where(sis_source_id: "T002").first, :hide_enrollmentless_courses => true}).map(&:sis_source_id).sort).to eq []
expect(@account.fast_all_courses({:term => EnrollmentTerm.where(sis_source_id: "T003").first, :hide_enrollmentless_courses => true}).map(&:sis_source_id).sort).to eq ["C005", "C007", "C005S", "C007S"].sort
end
it "should order list by specified parameter" do
order = "courses.created_at ASC"
expect(@account).to receive(:fast_course_base).with(order: order)
@account.fast_all_courses(order: order)
end
end
context "name searching" do
it "should list associated courses" do
expect(@account.courses_name_like("search").map(&:sis_source_id).sort).to eq [
"C001S", "C005S", "C006S", "C007S", "C008S", "C009S"]
end
it "should list associated courses by term" do
expect(@account.courses_name_like("search", {:term => EnrollmentTerm.where(sis_source_id: "T001").first}).map(&:sis_source_id).sort).to eq ["C001S"]
expect(@account.courses_name_like("search", {:term => EnrollmentTerm.where(sis_source_id: "T002").first}).map(&:sis_source_id).sort).to eq []
expect(@account.courses_name_like("search", {:term => EnrollmentTerm.where(sis_source_id: "T003").first}).map(&:sis_source_id).sort).to eq ["C005S", "C006S", "C007S", "C008S", "C009S"]
end
it "should list associated nonenrollmentless courses" do
expect(@account.courses_name_like("search", {:hide_enrollmentless_courses => true}).map(&:sis_source_id).sort).to eq ["C001S", "C005S", "C007S"] #C007 probably shouldn't be here, cause the enrollment section is deleted, but we kinda want to minimize database traffic
end
it "should list associated nonenrollmentless courses by term" do
expect(@account.courses_name_like("search", {:term => EnrollmentTerm.where(sis_source_id: "T001").first, :hide_enrollmentless_courses => true}).map(&:sis_source_id).sort).to eq ["C001S"]
expect(@account.courses_name_like("search", {:term => EnrollmentTerm.where(sis_source_id: "T002").first, :hide_enrollmentless_courses => true}).map(&:sis_source_id).sort).to eq []
expect(@account.courses_name_like("search", {:term => EnrollmentTerm.where(sis_source_id: "T003").first, :hide_enrollmentless_courses => true}).map(&:sis_source_id).sort).to eq ["C005S", "C007S"]
end
end
end
context "services" do
before do
@a = Account.new
end
it "should be able to specify a list of enabled services" do
@a.allowed_services = 'linked_in,twitter'
expect(@a.service_enabled?(:linked_in)).to be_truthy
expect(@a.service_enabled?(:twitter)).to be_truthy
expect(@a.service_enabled?(:diigo)).to be_falsey
expect(@a.service_enabled?(:avatars)).to be_falsey
end
it "should not enable services off by default" do
expect(@a.service_enabled?(:linked_in)).to be_truthy
expect(@a.service_enabled?(:avatars)).to be_falsey
end
it "should add and remove services from the defaults" do
@a.allowed_services = '+avatars,-linked_in'
expect(@a.service_enabled?(:avatars)).to be_truthy
expect(@a.service_enabled?(:twitter)).to be_truthy
expect(@a.service_enabled?(:linked_in)).to be_falsey
end
it "should allow settings services" do
expect {@a.enable_service(:completly_bogs)}.to raise_error("Invalid Service")
@a.disable_service(:twitter)
expect(@a.service_enabled?(:twitter)).to be_falsey
@a.enable_service(:twitter)
expect(@a.service_enabled?(:twitter)).to be_truthy
end
it "should use + and - by default when setting service availabilty" do
@a.enable_service(:twitter)
expect(@a.service_enabled?(:twitter)).to be_truthy
expect(@a.allowed_services).to be_nil
@a.disable_service(:twitter)
expect(@a.allowed_services).to match('\-twitter')
@a.disable_service(:avatars)
expect(@a.service_enabled?(:avatars)).to be_falsey
expect(@a.allowed_services).not_to match('avatars')
@a.enable_service(:avatars)
expect(@a.service_enabled?(:avatars)).to be_truthy
expect(@a.allowed_services).to match('\+avatars')
end
it "should be able to set service availibity for previously hard-coded values" do
@a.allowed_services = 'avatars,linked_in'
@a.enable_service(:twitter)
expect(@a.service_enabled?(:twitter)).to be_truthy
expect(@a.allowed_services).to match(/twitter/)
expect(@a.allowed_services).not_to match(/[+-]/)
@a.disable_service(:linked_in)
expect(@a.allowed_services).not_to match(/linked_in/)
expect(@a.allowed_services).not_to match(/[+-]/)
@a.disable_service(:avatars)
@a.disable_service(:twitter)
expect(@a.allowed_services).to be_nil
end
it "should not wipe out services that are substrings of each other" do
AccountServices.register_service(
:google_docs_prev,
{
:name => "My google docs prev", :description => "", :expose_to_ui => :service, :default => true
}
)
@a.disable_service('google_docs_previews')
@a.disable_service('google_docs_prev')
expect(@a.allowed_services).to eq '-google_docs_previews,-google_docs_prev'
end
describe "services_exposed_to_ui_hash" do
it "should return all ui services by default" do
expected_services = AccountServices.allowable_services.reject { |_, k| !k[:expose_to_ui] || (k[:expose_to_ui_proc] && !k[:expose_to_ui_proc].call(nil)) }.keys
expect(Account.services_exposed_to_ui_hash.keys).to eq expected_services
end
it "should return services of a type if specified" do
expected_services = AccountServices.allowable_services.reject { |_, k| k[:expose_to_ui] != :setting || (k[:expose_to_ui_proc] && !k[:expose_to_ui_proc].call(nil)) }.keys
expect(Account.services_exposed_to_ui_hash(:setting).keys).to eq expected_services
end
it "should filter based on user and account if a proc is specified" do
user1 = User.create!
user2 = User.create!
AccountServices.register_service(:myservice, {
name: "My Test Service",
description: "Nope",
expose_to_ui: :setting,
default: false,
expose_to_ui_proc: proc { |user, account| user == user2 && account == Account.default },
})
expect(Account.services_exposed_to_ui_hash(:setting).keys).not_to be_include(:myservice)
expect(Account.services_exposed_to_ui_hash(:setting, user1, Account.default).keys).not_to be_include(:myservice)
expect(Account.services_exposed_to_ui_hash(:setting, user2, Account.default).keys).to be_include(:myservice)
end
end
describe "plugin services" do
before do
AccountServices.register_service(:myplugin, { :name => "My Plugin", :description => "", :expose_to_ui => :setting, :default => false })
end
it "should return the service" do
expect(AccountServices.allowable_services.keys).to be_include(:myplugin)
end
it "should allow setting the service" do
expect(@a.service_enabled?(:myplugin)).to be_falsey
@a.enable_service(:myplugin)
expect(@a.service_enabled?(:myplugin)).to be_truthy
expect(@a.allowed_services).to match(/\+myplugin/)
@a.disable_service(:myplugin)
expect(@a.service_enabled?(:myplugin)).to be_falsey
expect(@a.allowed_services).to be_blank
end
describe "services_exposed_to_ui_hash" do
it "should return services defined in a plugin" do
expect(Account.services_exposed_to_ui_hash().keys).to be_include(:myplugin)
expect(Account.services_exposed_to_ui_hash(:setting).keys).to be_include(:myplugin)
end
end
end
end
context "settings=" do
it "should filter non-hash hash settings" do
a = Account.new
a.settings = {'sis_default_grade_export' => 'string'}.with_indifferent_access
expect(a.settings[:error_reporting]).to eql(nil)
a.settings = {'sis_default_grade_export' => {
'value' => true
}}.with_indifferent_access
expect(a.settings[:sis_default_grade_export]).to be_is_a(Hash)
expect(a.settings[:sis_default_grade_export][:value]).to eql true
end
end
context "allow_global_includes?" do
let(:root){ Account.default }
it "false unless they've checked the box to allow it" do
expect(root.allow_global_includes?).to be_falsey
end
it "true if they've checked the box to allow it" do
root.settings = {'global_includes' => true}
expect(root.allow_global_includes?).to be_truthy
end
describe "subaccount" do
let(:sub_account){ root.sub_accounts.create! }
it "false if root account hasn't checked global_includes AND subaccount branding" do
expect(sub_account.allow_global_includes?).to be_falsey
sub_account.root_account.settings = {'global_includes' => true, 'sub_account_includes' => false}
expect(sub_account.allow_global_includes?).to be_falsey
sub_account.root_account.settings = {'global_includes' => false, 'sub_account_includes' => true}
expect(sub_account.allow_global_includes?).to be_falsey
end
it "true if root account HAS checked global_includes and turned on subaccount branding" do
sub_account.root_account.settings = {'global_includes' => true, 'sub_account_includes' => true}
expect(sub_account.allow_global_includes?).to be_truthy
end
end
end
context "turnitin secret" do
it "should decrypt the turnitin secret to the original value" do
a = Account.new
a.turnitin_shared_secret = "asdf"
expect(a.turnitin_shared_secret).to eql("asdf")
a.turnitin_shared_secret = "2t87aot72gho8a37gh4g[awg'waegawe-,v-3o7fya23oya2o3"
expect(a.turnitin_shared_secret).to eql("2t87aot72gho8a37gh4g[awg'waegawe-,v-3o7fya23oya2o3")
end
end
context "closest_turnitin_originality" do
before :each do
@root_account = Account.create!(:turnitin_pledge => "root")
@root_account.turnitin_originality = 'after_grading'
@root_account.save!
end
it "should find closest_turnitin_originality from root account" do
expect(@root_account.closest_turnitin_originality).to eq('after_grading')
end
it "should find closest_turnitin_originality from sub account" do
sub_account = Account.create(:name => 'sub', :parent_account => @root_account)
sub_account.turnitin_originality = 'never'
expect(sub_account.closest_turnitin_originality).to eq('never')
end
it "should find closest_turnitin_originality from sub account when set on root account" do
sub_account = Account.create(:name => 'sub', :parent_account => @root_account)
expect(sub_account.closest_turnitin_originality).to eq('after_grading')
end
end
context "closest_turnitin_pledge" do
it "should work for custom sub, custom root" do
root_account = Account.create!(:turnitin_pledge => "root")
sub_account = Account.create!(:parent_account => root_account, :turnitin_pledge => "sub")
expect(root_account.closest_turnitin_pledge).to eq "root"
expect(sub_account.closest_turnitin_pledge).to eq "sub"
end
it "should work for nil sub, custom root" do
root_account = Account.create!(:turnitin_pledge => "root")
sub_account = Account.create!(:parent_account => root_account)
expect(root_account.closest_turnitin_pledge).to eq "root"
expect(sub_account.closest_turnitin_pledge).to eq "root"
end
it "should work for nil sub, nil root" do
root_account = Account.create!
sub_account = Account.create!(:parent_account => root_account)
expect(root_account.closest_turnitin_pledge).not_to be_empty
expect(sub_account.closest_turnitin_pledge).not_to be_empty
end
end
it "should make a default enrollment term if necessary" do
a = Account.create!(:name => "nada")
expect(a.enrollment_terms.size).to eq 1
expect(a.enrollment_terms.first.name).to eq EnrollmentTerm::DEFAULT_TERM_NAME
# don't create a new default term for sub-accounts
a2 = a.all_accounts.create!(:name => "sub")
expect(a2.enrollment_terms.size).to eq 0
end
def account_with_admin_and_restricted_user(account, restricted_role)
admin = User.create
user = User.create
account.account_users.create!(:user => admin, :role => admin_role)
account.account_users.create!(:user => user, :role => restricted_role)
[ admin, user ]
end
it "should set up access policy correctly" do
# double out any "if" permission conditions
RoleOverride.permissions.each do |k, v|
next unless v[:if]
allow_any_instance_of(Account).to receive(v[:if]).and_return(true)
end
site_admin = Account.site_admin
# Set up a hierarchy of 4 accounts - a root account, a sub account,
# a sub sub account, and SiteAdmin account. Create a 'Restricted Admin'
# role available for each one, and create an admin user and a user in that restricted role
@sa_role = custom_account_role('Restricted SA Admin', account: site_admin)
site_admin.settings[:mfa_settings] = 'required'
site_admin.save!
root_account = Account.create
@root_role = custom_account_role('Restricted Root Admin', :account => root_account)
sub_account = Account.create(:parent_account => root_account)
sub_sub_account = Account.create(:parent_account => sub_account)
hash = {}
hash[:site_admin] = { :account => Account.site_admin}
hash[:root] = { :account => root_account}
hash[:sub] = { :account => sub_account}
hash[:sub_sub] = { :account => sub_sub_account}
hash.each do |k, v|
v[:account].update_attribute(:settings, {:no_enrollments_can_create_courses => false})
admin, user = account_with_admin_and_restricted_user(v[:account], (k == :site_admin ? @sa_role : @root_role))
hash[k][:admin] = admin
hash[k][:user] = user
end
limited_access = [ :read, :read_as_admin, :manage, :update, :delete, :read_outcomes ]
conditional_access = RoleOverride.permissions.select { |_, v| v[:account_allows] }.map(&:first)
full_access = RoleOverride.permissions.keys +
limited_access - conditional_access +
[:create_courses] +
[:create_tool_manually]
full_root_access = full_access - RoleOverride.permissions.select { |k, v| v[:account_only] == :site_admin }.map(&:first)
full_sub_access = full_root_access - RoleOverride.permissions.select { |k, v| v[:account_only] == :root }.map(&:first)
# site admin has access to everything everywhere
hash.each do |k, v|
account = v[:account]
expect(account.check_policy(hash[:site_admin][:admin]) - conditional_access).to match_array full_access + (k == :site_admin ? [:read_global_outcomes] : [])
expect(account.check_policy(hash[:site_admin][:user]) - conditional_access).to match_array limited_access + (k == :site_admin ? [:read_global_outcomes] : [])
end
# root admin has access to everything except site admin
account = hash[:site_admin][:account]
expect(account.check_policy(hash[:root][:admin])).to match_array [:read_global_outcomes]
expect(account.check_policy(hash[:root][:user])).to match_array [:read_global_outcomes]
hash.each do |k, v|
next if k == :site_admin
account = v[:account]
expect(account.check_policy(hash[:root][:admin]) - conditional_access).to match_array full_root_access
expect(account.check_policy(hash[:root][:user])).to match_array limited_access
end
# sub account has access to sub and sub_sub
hash.each do |k, v|
next unless k == :site_admin || k == :root
account = v[:account]
expect(account.check_policy(hash[:sub][:admin])).to match_array(k == :site_admin ? [:read_global_outcomes] : [:read_outcomes])
expect(account.check_policy(hash[:sub][:user])).to match_array(k == :site_admin ? [:read_global_outcomes] : [:read_outcomes])
end
hash.each do |k, v|
next if k == :site_admin || k == :root
account = v[:account]
expect(account.check_policy(hash[:sub][:admin]) - conditional_access).to match_array full_sub_access
expect(account.check_policy(hash[:sub][:user])).to match_array limited_access
end
# Grant 'Restricted Admin' a specific permission, and re-check everything
some_access = [:read_reports] + limited_access
hash.each do |k, v|
account = v[:account]
account.role_overrides.create!(:permission => 'read_reports', :role => (k == :site_admin ? @sa_role : @root_role), :enabled => true)
account.role_overrides.create!(:permission => 'reset_any_mfa', :role => @sa_role, :enabled => true)
# clear caches
account.tap{|a| a.settings[:mfa_settings] = :optional; a.save!}
v[:account] = Account.find(account.id)
end
RoleOverride.clear_cached_contexts
AdheresToPolicy::Cache.clear
hash.each do |k, v|
account = v[:account]
admin_array = full_access + (k == :site_admin ? [:read_global_outcomes] : [])
user_array = some_access + [:reset_any_mfa] +
(k == :site_admin ? [:read_global_outcomes] : [])
expect(account.check_policy(hash[:site_admin][:admin]) - conditional_access).to match_array admin_array
expect(account.check_policy(hash[:site_admin][:user])).to match_array user_array
end
account = hash[:site_admin][:account]
expect(account.check_policy(hash[:root][:admin])).to match_array [:read_global_outcomes]
expect(account.check_policy(hash[:root][:user])).to match_array [:read_global_outcomes]
hash.each do |k, v|
next if k == :site_admin
account = v[:account]
expect(account.check_policy(hash[:root][:admin]) - conditional_access).to match_array full_root_access
expect(account.check_policy(hash[:root][:user])).to match_array some_access
end
# sub account has access to sub and sub_sub
hash.each do |k, v|
next unless k == :site_admin || k == :root
account = v[:account]
expect(account.check_policy(hash[:sub][:admin])).to match_array(k == :site_admin ? [:read_global_outcomes] : [:read_outcomes])
expect(account.check_policy(hash[:sub][:user])).to match_array(k == :site_admin ? [:read_global_outcomes] : [:read_outcomes])
end
hash.each do |k, v|
next if k == :site_admin || k == :root
account = v[:account]
expect(account.check_policy(hash[:sub][:admin]) - conditional_access).to match_array full_sub_access
expect(account.check_policy(hash[:sub][:user])).to match_array some_access
end
end
context "sharding" do
specs_require_sharding
it "queries for enrollments correctly when another shard is active" do
teacher_in_course
@enrollment.accept!
@shard1.activate do
expect(@course.grants_right?(@user, :read_sis)).to eq true
end
end
end
it "should allow no_enrollments_can_create_courses correctly" do
a = Account.default
a.settings = { :no_enrollments_can_create_courses => true }
a.save!
user_factory
expect(a.grants_right?(@user, :create_courses)).to be_truthy
end
it "does not allow create_courses even to admins on site admin and children" do
a = Account.site_admin
a.settings = { :no_enrollments_can_create_courses => true }
manual = a.manually_created_courses_account
user_factory
expect(a.grants_right?(@user, :create_courses)).to eq false
expect(manual.grants_right?(@user, :create_courses)).to eq false
end
it "should correctly return sub-accounts as options" do
a = Account.default
sub = Account.create!(:name => 'sub', :parent_account => a)
sub2 = Account.create!(:name => 'sub2', :parent_account => a)
sub2_1 = Account.create!(:name => 'sub2-1', :parent_account => sub2)
options = a.sub_accounts_as_options
expect(options).to eq(
[
["Default Account", a.id],
[" sub", sub.id],
[" sub2", sub2.id],
[" sub2-1", sub2_1.id]
]
)
end
it "should correctly return sub-account_ids recursively" do
a = Account.default
subs = []
sub = Account.create!(name: 'sub', parent_account: a)
subs << grand_sub = Account.create!(name: 'grand_sub', parent_account: sub)
subs << great_grand_sub = Account.create!(name: 'great_grand_sub', parent_account: grand_sub)
subs << Account.create!(name: 'great_great_grand_sub', parent_account: great_grand_sub)
expect(Account.sub_account_ids_recursive(sub.id).sort).to eq(subs.map(&:id).sort)
end
it "should return the correct user count" do
a = Account.default
expect(a.all_users.count).to eq a.user_count
expect(a.user_count).to eq 0
u = User.create!
a.account_users.create!(user: u)
expect(a.all_users.count).to eq a.user_count
expect(a.user_count).to eq 1
course_with_teacher
@teacher.update_account_associations
expect(a.all_users.count).to eq a.user_count
expect(a.user_count).to eq 2
a2 = a.sub_accounts.create!
course_with_teacher(:account => a2)
@teacher.update_account_associations
expect(a.all_users.count).to eq a.user_count
expect(a.user_count).to eq 3
user_with_pseudonym
expect(a.all_users.count).to eq a.user_count
expect(a.user_count).to eq 4
end
it "group_categories should not include deleted categories" do
account = Account.default
expect(account.group_categories.count).to eq 0
category1 = account.group_categories.create(:name => 'category 1')
category2 = account.group_categories.create(:name => 'category 2')
expect(account.group_categories.count).to eq 2
category1.destroy
account.reload
expect(account.group_categories.count).to eq 1
expect(account.group_categories.to_a).to eq [category2]
end
it "all_group_categories should include deleted categories" do
account = Account.default
expect(account.all_group_categories.count).to eq 0
category1 = account.group_categories.create(:name => 'category 1')
category2 = account.group_categories.create(:name => 'category 2')
expect(account.all_group_categories.count).to eq 2
category1.destroy
account.reload
expect(account.all_group_categories.count).to eq 2
end
it "should return correct values for login_handle_name_with_inference" do
account = Account.default
expect(account.login_handle_name_with_inference).to eq "Email"
config = account.authentication_providers.create!(auth_type: 'cas')
account.authentication_providers.first.move_to_bottom
expect(account.login_handle_name_with_inference).to eq "Login"
config.destroy
config = account.authentication_providers.create!(auth_type: 'saml')
account.authentication_providers.active.first.move_to_bottom
expect(account.reload.login_handle_name_with_inference).to eq "Login"
config.destroy
account.authentication_providers.create!(auth_type: 'ldap')
account.authentication_providers.active.first.move_to_bottom
expect(account.reload.login_handle_name_with_inference).to eq "Email"
account.login_handle_name = "LDAP Login"
account.save!
expect(account.reload.login_handle_name_with_inference).to eq "LDAP Login"
end
context "users_not_in_groups" do
before :once do
@account = Account.default
@user1 = account_admin_user(:account => @account)
@user2 = account_admin_user(:account => @account)
@user3 = account_admin_user(:account => @account)
end
it "should not include deleted users" do
@user1.destroy
expect(@account.users_not_in_groups([]).size).to eq 2
end
it "should not include users in one of the groups" do
group = @account.groups.create
group.add_user(@user1)
users = @account.users_not_in_groups([group])
expect(users.size).to eq 2
expect(users).not_to be_include(@user1)
end
it "should include users otherwise" do
group = @account.groups.create
group.add_user(@user1)
users = @account.users_not_in_groups([group])
expect(users).to be_include(@user2)
expect(users).to be_include(@user3)
end
it "should allow ordering by user's sortable name" do
@user1.sortable_name = 'jonny'; @user1.save
@user2.sortable_name = 'bob'; @user2.save
@user3.sortable_name = 'richard'; @user3.save
users = @account.users_not_in_groups([], order: User.sortable_name_order_by_clause('users'))
expect(users.map{ |u| u.id }).to eq [@user2.id, @user1.id, @user3.id]
end
end
context "tabs_available" do
before :once do
@account = Account.default.sub_accounts.create!(:name => "sub-account")
end
it "should include 'Developer Keys' for the authorized users of the site_admin account" do
account_admin_user(:account => Account.site_admin)
tabs = Account.site_admin.tabs_available(@admin)
expect(tabs.map{|t| t[:id] }).to be_include(Account::TAB_DEVELOPER_KEYS)
tabs = Account.site_admin.tabs_available(nil)
expect(tabs.map{|t| t[:id] }).not_to be_include(Account::TAB_DEVELOPER_KEYS)
end
it "should include 'Developer Keys' for the admin users of an account" do
account = Account.create!
account_admin_user(:account => account)
tabs = account.tabs_available(@admin)
expect(tabs.map{|t| t[:id] }).to be_include(Account::TAB_DEVELOPER_KEYS)
tabs = account.tabs_available(nil)
expect(tabs.map{|t| t[:id] }).not_to be_include(Account::TAB_DEVELOPER_KEYS)
end
it "should not include 'Developer Keys' for non-site_admin accounts" do
tabs = @account.tabs_available(nil)
expect(tabs.map{|t| t[:id] }).not_to be_include(Account::TAB_DEVELOPER_KEYS)
tabs = @account.root_account.tabs_available(nil)
expect(tabs.map{|t| t[:id] }).not_to be_include(Account::TAB_DEVELOPER_KEYS)
end
it "should not include external tools if not configured for account navigation" do
tool = @account.context_external_tools.new(:name => "bob", :consumer_key => "bob", :shared_secret => "bob", :domain => "example.com")
tool.user_navigation = {:url => "http://www.example.com", :text => "Example URL"}
tool.save!
expect(tool.has_placement?(:account_navigation)).to eq false
tabs = @account.tabs_available(nil)
expect(tabs.map{|t| t[:id] }).not_to be_include(tool.asset_string)
end
it "should include active external tools if configured on the account" do
tools = []
2.times do |n|
t = @account.context_external_tools.new(
:name => "bob",
:consumer_key => "bob",
:shared_secret => "bob",
:domain => "example.com"
)
t.account_navigation = {
:text => "Example URL",
:url => "http://www.example.com",
}
t.save!
tools << t
end
tool1, tool2 = tools
tool2.destroy
tools.each { |t| expect(t.has_placement?(:account_navigation)).to eq true }
tabs = @account.tabs_available
tab_ids = tabs.map{|t| t[:id] }
expect(tab_ids).to be_include(tool1.asset_string)
expect(tab_ids).not_to be_include(tool2.asset_string)
tab = tabs.detect{|t| t[:id] == tool1.asset_string }
expect(tab[:label]).to eq tool1.settings[:account_navigation][:text]
expect(tab[:href]).to eq :account_external_tool_path
expect(tab[:args]).to eq [@account.id, tool1.id]
end
it "should include external tools if configured on the root account" do
tool = @account.context_external_tools.new(:name => "bob", :consumer_key => "bob", :shared_secret => "bob", :domain => "example.com")
tool.account_navigation = {:url => "http://www.example.com", :text => "Example URL"}
tool.save!
expect(tool.has_placement?(:account_navigation)).to eq true
tabs = @account.tabs_available(nil)
expect(tabs.map{|t| t[:id] }).to be_include(tool.asset_string)
tab = tabs.detect{|t| t[:id] == tool.asset_string }
expect(tab[:label]).to eq tool.settings[:account_navigation][:text]
expect(tab[:href]).to eq :account_external_tool_path
expect(tab[:args]).to eq [@account.id, tool.id]
end
it "should not include external tools for non-admins if visibility is set" do
course_with_teacher(:account => @account)
tool = @account.context_external_tools.new(:name => "bob", :consumer_key => "bob", :shared_secret => "bob", :domain => "example.com")
tool.account_navigation = {:url => "http://www.example.com", :text => "Example URL", :visibility => "admins"}
tool.save!
expect(tool.has_placement?(:account_navigation)).to eq true
tabs = @account.tabs_available(@teacher)
expect(tabs.map{|t| t[:id] }).to_not be_include(tool.asset_string)
admin = account_admin_user(:account => @account)
tabs = @account.tabs_available(admin)
expect(tabs.map{|t| t[:id] }).to be_include(tool.asset_string)
end
it "should use localized labels" do
tool = @account.context_external_tools.new(:name => "bob", :consumer_key => "test", :shared_secret => "secret",
:url => "http://example.com")
account_navigation = {
:text => 'this should not be the title',
:url => 'http://www.example.com',
:labels => {
'en' => 'English Label',
'sp' => 'Spanish Label'
}
}
tool.settings[:account_navigation] = account_navigation
tool.save!
tabs = @account.external_tool_tabs({})
expect(tabs.first[:label]).to eq "English Label"
end
it 'includes message handlers' do
mock_tab = {
:id => '1234',
:label => 'my_label',
:css_class => '1234',
:href => :launch_path_helper,
:visibility => nil,
:external => true,
:hidden => false,
:args => [1, 2]
}
allow(Lti::MessageHandler).to receive(:lti_apps_tabs).and_return([mock_tab])
expect(@account.tabs_available(nil)).to include(mock_tab)
end
it 'uses :manage_assignments to determine question bank tab visibility' do
account_admin_user_with_role_changes(acccount: @account, role_changes: { manage_assignments: true, manage_grades: false})
tabs = @account.tabs_available(@admin)
expect(tabs.map{|t| t[:id] }).to be_include(Account::TAB_QUESTION_BANKS)
end
end
describe "fast_all_users" do
it "should preserve sortable_name" do
user_with_pseudonym(:active_all => 1)
@user.update_attributes(:name => "John St. Clair", :sortable_name => "St. Clair, John")
@johnstclair = @user
user_with_pseudonym(:active_all => 1, :username => 'jt@instructure.com', :name => 'JT Olds')
@jtolds = @user
expect(Account.default.fast_all_users).to eq [@jtolds, @johnstclair]
end
end
it "should not allow setting an sis id for a root account" do
@account = Account.create!
@account.sis_source_id = 'abc'
expect(@account.save).to be_falsey
end
describe "user_list_search_mode_for" do
let_once(:account) { Account.default }
it "should be preferred for anyone if open registration is turned on" do
account.settings = { :open_registration => true }
expect(account.user_list_search_mode_for(nil)).to eq :preferred
expect(account.user_list_search_mode_for(user_factory)).to eq :preferred
end
it "should be preferred for account admins" do
expect(account.user_list_search_mode_for(nil)).to eq :closed
expect(account.user_list_search_mode_for(user_factory)).to eq :closed
user_factory
account.account_users.create!(user: @user)
expect(account.user_list_search_mode_for(@user)).to eq :preferred
end
end
context "sharding" do
specs_require_sharding
it "should properly return site admin permissions regardless of active shard" do
enable_cache do
user_factory
site_admin = Account.site_admin
site_admin.account_users.create!(user: @user)
@shard1.activate do
expect(site_admin.grants_right?(@user, :manage_site_settings)).to be_truthy
end
expect(site_admin.grants_right?(@user, :manage_site_settings)).to be_truthy
user_factory
@shard1.activate do
expect(site_admin.grants_right?(@user, :manage_site_settings)).to be_falsey
end
expect(site_admin.grants_right?(@user, :manage_site_settings)).to be_falsey
end
end
end
context "permissions" do
before(:once) { Account.default }
it "should grant :read_global_outcomes to any user iff site_admin" do
@site_admin = Account.site_admin
expect(@site_admin.grants_right?(User.new, :read_global_outcomes)).to be_truthy
@subaccount = @site_admin.sub_accounts.create!
expect(@subaccount.grants_right?(User.new, :read_global_outcomes)).to be_falsey
end
it "should not grant :read_outcomes to user's outside the account" do
expect(Account.default.grants_right?(User.new, :read_outcomes)).to be_falsey
end
it "should grant :read_outcomes to account admins" do
account_admin_user(:account => Account.default)
expect(Account.default.grants_right?(@admin, :read_outcomes)).to be_truthy
end
it "should grant :read_outcomes to subaccount admins" do
account_admin_user(:account => Account.default.sub_accounts.create!)
expect(Account.default.grants_right?(@admin, :read_outcomes)).to be_truthy
end
it "should grant :read_outcomes to enrollees in account courses" do
course_factory(:account => Account.default)
teacher_in_course
student_in_course
expect(Account.default.grants_right?(@teacher, :read_outcomes)).to be_truthy
expect(Account.default.grants_right?(@student, :read_outcomes)).to be_truthy
end
it "should grant :read_outcomes to enrollees in subaccount courses" do
course_factory(:account => Account.default.sub_accounts.create!)
teacher_in_course
student_in_course
expect(Account.default.grants_right?(@teacher, :read_outcomes)).to be_truthy
expect(Account.default.grants_right?(@student, :read_outcomes)).to be_truthy
end
end
describe "authentication_providers.active" do
let(:account){ Account.default }
let!(:aac){ account.authentication_providers.create!(auth_type: 'facebook') }
it "pulls active AACS" do
expect(account.authentication_providers.active).to include(aac)
end
it "ignores deleted AACs" do
aac.destroy
expect(account.authentication_providers.active).to_not include(aac)
end
end
describe "delegated_authentication?" do
let(:account){ Account.default }
before do
account.authentication_providers.scope.delete_all
end
it "is false for LDAP" do
account.authentication_providers.create!(auth_type: 'ldap')
expect(account.delegated_authentication?).to eq false
end
it "is true for CAS" do
account.authentication_providers.create!(auth_type: 'cas')
expect(account.delegated_authentication?).to eq true
end
end
describe "#non_canvas_auth_configured?" do
let(:account) { Account.default }
it "is false for no aacs" do
expect(account.non_canvas_auth_configured?).to be_falsey
end
it "is true for having aacs" do
Account.default.authentication_providers.create!(auth_type: 'ldap')
expect(account.non_canvas_auth_configured?).to be_truthy
end
it "is false after aacs deleted" do
Account.default.authentication_providers.create!(auth_type: 'ldap')
account.authentication_providers.destroy_all
expect(account.non_canvas_auth_configured?).to be_falsey
end
end
describe '#find_child' do
it 'works for root accounts' do
sub = Account.default.sub_accounts.create!
expect(Account.default.find_child(sub.id)).to eq sub
end
it 'works for children accounts' do
sub = Account.default.sub_accounts.create!
sub_sub = sub.sub_accounts.create!
sub_sub_sub = sub_sub.sub_accounts.create!
expect(sub.find_child(sub_sub_sub.id)).to eq sub_sub_sub
end
it 'raises for out-of-tree accounts' do
sub = Account.default.sub_accounts.create!
sub_sub = sub.sub_accounts.create!
sibling = sub.sub_accounts.create!
expect { sub_sub.find_child(sibling.id) }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "manually created courses account" do
it "should still work with existing manually created courses accounts" do
acct = Account.default
sub = acct.sub_accounts.create!(:name => "Manually-Created Courses")
manual_courses_account = acct.manually_created_courses_account
expect(manual_courses_account.id).to eq sub.id
expect(acct.reload.settings[:manually_created_courses_account_id]).to eq sub.id
end
it "should not create a duplicate manual courses account when locale changes" do
acct = Account.default
sub1 = acct.manually_created_courses_account
I18n.locale = "es"
sub2 = acct.manually_created_courses_account
I18n.locale = "en"
expect(sub1.id).to eq sub2.id
end
it "should work if the saved account id doesn't exist" do
acct = Account.default
acct.settings[:manually_created_courses_account_id] = acct.id + 1000
acct.save!
expect(acct.manually_created_courses_account).to be_present
end
it "should work if the saved account id is not a sub-account" do
acct = Account.default
bad_acct = Account.create!
acct.settings[:manually_created_courses_account_id] = bad_acct.id
acct.save!
manual_course_account = acct.manually_created_courses_account
expect(manual_course_account.id).not_to eq bad_acct.id
end
end
describe "account_users_for" do
it "should be cache coherent for site admin" do
enable_cache do
user_factory
sa = Account.site_admin
expect(sa.account_users_for(@user)).to eq []
au = sa.account_users.create!(user: @user)
# out-of-proc cache should clear, but we have to manually clear
# the in-proc cache
sa = Account.find(sa.id)
expect(sa.account_users_for(@user)).to eq [au]
au.destroy
#ditto
sa = Account.find(sa.id)
expect(sa.account_users_for(@user)).to eq []
end
end
context "sharding" do
specs_require_sharding
it "should be cache coherent for site admin" do
enable_cache do
user_factory
sa = Account.site_admin
@shard1.activate do
expect(sa.account_users_for(@user)).to eq []
au = sa.account_users.create!(user: @user)
# out-of-proc cache should clear, but we have to manually clear
# the in-proc cache
sa = Account.find(sa.id)
expect(sa.account_users_for(@user)).to eq [au]
au.destroy
#ditto
sa = Account.find(sa.id)
expect(sa.account_users_for(@user)).to eq []
end
end
end
end
end
describe "available_custom_course_roles" do
before :once do
account_model
@roleA = @account.roles.create :name => 'A'
@roleA.base_role_type = 'StudentEnrollment'
@roleA.save!
@roleB = @account.roles.create :name => 'B'
@roleB.base_role_type = 'StudentEnrollment'
@roleB.save!
@sub_account = @account.sub_accounts.create!
@roleC = @sub_account.roles.create :name => 'C'
@roleC.base_role_type = 'StudentEnrollment'
@roleC.save!
end
it "should return roles indexed by name" do
expect(@account.available_custom_course_roles.sort_by(&:id)).to eq [ @roleA, @roleB ].sort_by(&:id)
end
it "should not return inactive roles" do
@roleB.deactivate!
expect(@account.available_custom_course_roles).to eq [ @roleA ]
end
it "should not return deleted roles" do
@roleA.destroy
expect(@account.available_custom_course_roles).to eq [ @roleB ]
end
it "should derive roles from parents" do
expect(@sub_account.available_custom_course_roles.sort_by(&:id)).to eq [ @roleA, @roleB, @roleC ].sort_by(&:id)
end
it "should include built-in roles when called" do
expect(@sub_account.available_course_roles.sort_by(&:id)).to eq ([ @roleA, @roleB, @roleC ] + Role.built_in_course_roles).sort_by(&:id)
end
end
describe "account_chain" do
context "sharding" do
specs_require_sharding
it "should find parent accounts when not on the correct shard" do
@shard1.activate do
@account1 = Account.create!
@account2 = @account1.sub_accounts.create!
@account3 = @account2.sub_accounts.create!
end
expect(@account3.account_chain).to eq [@account3, @account2, @account1]
end
end
it "returns parent accounts in order up the tree" do
account1 = Account.create!
account2 = account1.sub_accounts.create!
account3 = account2.sub_accounts.create!
account4 = account3.sub_accounts.create!
expect(account4.account_chain).to eq [account4, account3, account2, account1]
end
end
describe "#can_see_admin_tools_tab?" do
let_once(:account) { Account.create! }
it "returns false if no user is present" do
expect(account.can_see_admin_tools_tab?(nil)).to be_falsey
end
it "returns false if you are a site admin" do
admin = account_admin_user(:account => Account.site_admin)
expect(Account.site_admin.can_see_admin_tools_tab?(admin)).to be_falsey
end
it "doesn't have permission, it returns false" do
allow(account).to receive(:grants_right?).and_return(false)
account_admin_user(:account => account)
expect(account.can_see_admin_tools_tab?(@admin)).to be_falsey
end
it "does have permission, it returns true" do
allow(account).to receive(:grants_right?).and_return(true)
account_admin_user(:account => account)
expect(account.can_see_admin_tools_tab?(@admin)).to be_truthy
end
end
describe "#update_account_associations" do
it "should update associations for all courses" do
account = Account.default.sub_accounts.create!
c1 = account.courses.create!
c2 = account.courses.create!
account.course_account_associations.scope.delete_all
expect(account.associated_courses).to eq []
account.update_account_associations
account.reload
expect(account.associated_courses.sort_by(&:id)).to eq [c1, c2]
end
end
describe "default_time_zone" do
context "root account" do
before :once do
@account = Account.create!
end
it "should use provided value when set" do
@account.default_time_zone = 'America/New_York'
expect(@account.default_time_zone).to eq ActiveSupport::TimeZone['Eastern Time (US & Canada)']
end
it "should have a sensible default if not set" do
expect(@account.default_time_zone).to eq ActiveSupport::TimeZone[Account.time_zone_attribute_defaults[:default_time_zone]]
end
end
context "sub account" do
before :once do
@root_account = Account.create!
@account = @root_account.sub_accounts.create!
@account.root_account = @root_account
end
it "should use provided value when set, regardless of root account setting" do
@root_account.default_time_zone = 'America/Chicago'
@account.default_time_zone = 'America/New_York'
expect(@account.default_time_zone).to eq ActiveSupport::TimeZone['Eastern Time (US & Canada)']
end
it "should default to root account value if not set" do
@root_account.default_time_zone = 'America/Chicago'
expect(@account.default_time_zone).to eq ActiveSupport::TimeZone['Central Time (US & Canada)']
end
it "should have a sensible default if neither is set" do
expect(@account.default_time_zone).to eq ActiveSupport::TimeZone[Account.time_zone_attribute_defaults[:default_time_zone]]
end
end
end
describe "#ensure_defaults" do
it "assigns an lti_guid postfixed by canvas-lms" do``
account = Account.new
account.uuid = '12345'
account.ensure_defaults
expect(account.lti_guid).to eq '12345:canvas-lms'
end
it "does not change existing an lti_guid" do
account = Account.new
account.lti_guid = '12345'
account.ensure_defaults
expect(account.lti_guid).to eq '12345'
end
end
it 'should format a referer url' do
account = Account.new
expect(account.format_referer(nil)).to be_nil
expect(account.format_referer('')).to be_nil
expect(account.format_referer('not a url')).to be_nil
expect(account.format_referer('http://example.com/')).to eq 'http://example.com'
expect(account.format_referer('http://example.com/index.html')).to eq 'http://example.com'
expect(account.format_referer('http://example.com:80')).to eq 'http://example.com'
expect(account.format_referer('https://example.com:443')).to eq 'https://example.com'
expect(account.format_referer('http://example.com:3000')).to eq 'http://example.com:3000'
end
it 'should format trusted referers when set' do
account = Account.new
account.trusted_referers = 'https://example.com/,http://example.com:80,http://example.com:3000'
expect(account.settings[:trusted_referers]).to eq 'https://example.com,http://example.com,http://example.com:3000'
account.trusted_referers = nil
expect(account.settings[:trusted_referers]).to be_nil
account.trusted_referers = ''
expect(account.settings[:trusted_referers]).to be_nil
end
describe 'trusted_referer?' do
let!(:account) do
account = Account.new
account.settings[:trusted_referers] = 'https://example.com,http://example.com,http://example.com:3000'
account
end
it 'should be true when a referer is trusted' do
expect(account.trusted_referer?('http://example.com')).to be_truthy
expect(account.trusted_referer?('http://example.com:3000')).to be_truthy
expect(account.trusted_referer?('http://example.com:80')).to be_truthy
expect(account.trusted_referer?('https://example.com:443')).to be_truthy
end
it 'should be false when a referer is not provided' do
expect(account.trusted_referer?(nil)).to be_falsey
expect(account.trusted_referer?('')).to be_falsey
end
it 'should be false when a referer is not trusted' do
expect(account.trusted_referer?('https://example.com:5000')).to be_falsey
end
it 'should be false when the account has no trusted referer setting' do
account.settings.delete(:trusted_referers)
expect(account.trusted_referer?('https://example.com')).to be_falsey
end
it 'should be false when the account has nil trusted referer setting' do
account.settings[:trusted_referers] = nil
expect(account.trusted_referer?('https://example.com')).to be_falsey
end
it 'should be false when the account has empty trusted referer setting' do
account.settings[:trusted_referers] = ''
expect(account.trusted_referer?('https://example.com')).to be_falsey
end
end
context "quota cache" do
it "should only clear the quota cache if something changes" do
account = account_model
expect(Account).to receive(:invalidate_inherited_caches).once
account.default_storage_quota = 10.megabytes
account.save! # clear here
account.reload
account.save!
account.default_storage_quota = 10.megabytes
account.save!
end
it "should inherit from a parent account's default_storage_quota" do
enable_cache do
account = account_model
account.default_storage_quota = 10.megabytes
account.save!
subaccount = account.sub_accounts.create!
expect(subaccount.default_storage_quota).to eq 10.megabytes
account.default_storage_quota = 20.megabytes
account.save!
# should clear caches
account = Account.find(account.id)
expect(account.default_storage_quota).to eq 20.megabytes
subaccount = Account.find(subaccount.id)
expect(subaccount.default_storage_quota).to eq 20.megabytes
end
end
it "should inherit from a new parent account's default_storage_quota if parent account changes" do
enable_cache do
account = account_model
account.default_storage_quota = 10.megabytes
account.save!
to_be_subaccount = Account.create!
expect(to_be_subaccount.default_storage_quota).to eq Account.default_storage_quota
# should clear caches
to_be_subaccount.parent_account = account
to_be_subaccount.save!
expect(to_be_subaccount.default_storage_quota).to eq 10.megabytes
end
end
end
context "inheritable settings" do
before :each do
account_model
@sub1 = @account.sub_accounts.create!
@sub2 = @sub1.sub_accounts.create!
end
it "should use the default value if nothing is set anywhere" do
expected = {:locked => false, :value => false}
[@account, @sub1, @sub2].each do |a|
expect(a.restrict_student_future_view).to eq expected
expect(a.lock_all_announcements).to eq expected
end
end
it "should be able to lock values for sub-accounts" do
@sub1.settings[:restrict_student_future_view] = {:locked => true, :value => true}
@sub1.settings[:lock_all_announcements] = {:locked => true, :value => true}
@sub1.save!
# should ignore the subaccount's wishes
@sub2.settings[:restrict_student_future_view] = {:locked => true, :value => false}
@sub2.settings[:lock_all_announcements] = {:locked => true, :value => false}
@sub2.save!
expect(@account.restrict_student_future_view).to eq({:locked => false, :value => false})
expect(@account.lock_all_announcements).to eq({:locked => false, :value => false})
expect(@sub1.restrict_student_future_view).to eq({:locked => true, :value => true})
expect(@sub1.lock_all_announcements).to eq({:locked => true, :value => true})
expect(@sub2.restrict_student_future_view).to eq({:locked => true, :value => true, :inherited => true})
expect(@sub2.lock_all_announcements).to eq({:locked => true, :value => true, :inherited => true})
end
it "should grandfather old pre-hash values in" do
@account.settings[:restrict_student_future_view] = true
@account.settings[:lock_all_announcements] = true
@account.save!
@sub2.settings[:restrict_student_future_view] = false
@sub2.settings[:lock_all_announcements] = false
@sub2.save!
expect(@account.restrict_student_future_view).to eq({:locked => false, :value => true})
expect(@account.lock_all_announcements).to eq({:locked => false, :value => true})
expect(@sub1.restrict_student_future_view).to eq({:locked => false, :value => true, :inherited => true})
expect(@sub1.lock_all_announcements).to eq({:locked => false, :value => true, :inherited => true})
expect(@sub2.restrict_student_future_view).to eq({:locked => false, :value => false})
expect(@sub2.lock_all_announcements).to eq({:locked => false, :value => false})
end
it "should translate string values in mass-assignment" do
settings = @account.settings
settings[:restrict_student_future_view] = {"value" => "1", "locked" => "0"}
settings[:lock_all_announcements] = {"value" => "1", "locked" => "0"}
@account.settings = settings
@account.save!
expect(@account.restrict_student_future_view).to eq({:locked => false, :value => true})
expect(@account.lock_all_announcements).to eq({:locked => false, :value => true})
end
context "caching" do
specs_require_sharding
it "should clear cached values correctly" do
enable_cache do
# preload the cached values
[@account, @sub1, @sub2].each(&:restrict_student_future_view)
[@account, @sub1, @sub2].each(&:lock_all_announcements)
@sub1.settings = @sub1.settings.merge(:restrict_student_future_view => {:locked => true, :value => true}, :lock_all_announcements => {:locked => true, :value => true})
@sub1.save!
# hard reload
@account = Account.find(@account.id)
@sub1 = Account.find(@sub1.id)
@sub2 = Account.find(@sub2.id)
expect(@account.restrict_student_future_view).to eq({:locked => false, :value => false})
expect(@account.lock_all_announcements).to eq({:locked => false, :value => false})
expect(@sub1.restrict_student_future_view).to eq({:locked => true, :value => true})
expect(@sub1.lock_all_announcements).to eq({:locked => true, :value => true})
expect(@sub2.restrict_student_future_view).to eq({:locked => true, :value => true, :inherited => true})
expect(@sub2.lock_all_announcements).to eq({:locked => true, :value => true, :inherited => true})
end
end
end
end
context "require terms of use" do
describe "#terms_required?" do
it "returns true by default" do
expect(account_model.terms_required?).to eq true
end
it "returns false by default for new accounts" do
TermsOfService.skip_automatic_terms_creation = false
expect(account_model.terms_required?).to eq false
end
it "returns false if Setting is false" do
Setting.set(:terms_required, "false")
expect(account_model.terms_required?).to eq false
end
it "returns false if account setting is false" do
account = account_model(settings: {account_terms_required: false})
expect(account.terms_required?).to eq false
end
it "consults root account setting" do
parent_account = account_model(settings: {account_terms_required: false})
child_account = Account.create!(parent_account: parent_account)
expect(child_account.terms_required?).to eq false
end
end
end
context "account cache" do
specs_require_sharding
describe ".find_cached" do
let(:nonsense_id){ 987654321 }
it "works relative to a different shard" do
@shard1.activate do
a = Account.create!
expect(Account.find_cached(a.id)).to eq a
end
end
it "errors if infrastructure fails and we can't see the account" do
expect{ Account.find_cached(nonsense_id) }.to raise_error(::Canvas::AccountCacheError)
end
it "includes the account id in the error message" do
begin
Account.find_cached(nonsense_id)
rescue ::Canvas::AccountCacheError => e
expect(e.message).to eq("Couldn't find Account with 'id'=#{nonsense_id}")
end
end
end
describe ".invalidate_cache" do
it "works relative to a different shard" do
enable_cache do
@shard1.activate do
a = Account.create!
Account.find_cached(a.id) # set the cache
expect(Account.invalidate_cache(a.id)).to eq true
end
end
end
end
end
describe "#users_name_like" do
context 'sharding' do
specs_require_sharding
it "should work cross-shard" do
allow(ActiveRecord::Base.connection).to receive(:use_qualified_names?).and_return(true)
@shard1.activate do
@account = Account.create!
@user = user_factory(:name => "silly name")
@user.account_users.create(:account => @account)
end
expect(@account.users_name_like("silly").first).to eq @user
end
end
end
describe "#migrate_to_canvadocs?" do
before(:once) do
@account = Account.create!
end
it "is true if hijack_crocodoc_sessions is true and new annotations are enabled" do
allow(Canvadocs).to receive(:hijack_crocodoc_sessions?).and_return(true)
@account.enable_feature!(:new_annotations)
expect(@account).to be_migrate_to_canvadocs
end
it "is false if new annotations are enabled but hijack_crocodoc_sessions is false" do
allow(Canvadocs).to receive(:hijack_crocodoc_sessions?).and_return(false)
@account.enable_feature!(:new_annotations)
expect(@account).not_to be_migrate_to_canvadocs
end
it "is false if hijack_crocodoc_sessions is true but new annotations are disabled" do
allow(Canvadocs).to receive(:hijack_crocodoc_sessions?).and_return(true)
expect(@account).not_to be_migrate_to_canvadocs
end
end
it "should clear special account cache on updates to special accounts" do
expect(Account.default.settings[:blah]).to be_nil
non_cached = Account.find(Account.default.id)
non_cached.settings[:blah] = true
non_cached.save!
expect(Account.default.settings[:blah]).to eq true
end
end
| venturehive/canvas-lms | spec/models/account_spec.rb | Ruby | agpl-3.0 | 64,875 |
package org.aardin.oncall.tests.unit.dao;
import java.util.List;
import javax.annotation.Resource;
import org.aardin.common.exceptions.ValidationException;
import org.aardin.common.model.Partition;
import org.aardin.common.model.base.PartitionedId;
import org.aardin.oncall.dao.IOnCallEntryDAO;
import org.aardin.oncall.model.OnCallEntry;
import org.aardin.oncall.tests.unit.OnCallServiceTestConfig;
import org.joda.time.DateTime;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
@ContextConfiguration(classes=OnCallServiceTestConfig.class)
@Transactional
public class OnCallEntryDAOTest
extends AbstractTransactionalTestNGSpringContextTests {
@Resource
private IOnCallEntryDAO onCallEntryDAO;
@Test
public void testCrud() throws ValidationException {
List<OnCallEntry> entries = onCallEntryDAO.findAll("partition1");
assertEquals(entries.size(), 8);
Partition p = new Partition();
p.setCode("partition1");
p.setId("p1");
OnCallEntry oce = new OnCallEntry();
oce.setResponder("ue1");
oce.setRotationCode("unix_engineering");
oce.setPartitionedId(new PartitionedId(p));
DateTime now = new DateTime();
oce.setEffectiveDate(now.toDate());
oce = onCallEntryDAO.merge(oce);
entries = onCallEntryDAO.findAll();
assertEquals(entries.size(), 9);
assertNotNull(oce.getPartitionedId().getId());
}
@Test
public void oce_find_by_date_range() {
// Fetch all of the r1 items
List<OnCallEntry> entries = onCallEntryDAO.findByDateRange("partition1", "unix_engineering", null, null);
assertEquals(entries.size(), 8);
// Fetch all of the January items
DateTime from = new DateTime(2013, 1, 1, 7, 0);
DateTime to = new DateTime(2013, 1, 31, 7, 0);
entries = onCallEntryDAO.findByDateRange("partition1", "unix_engineering", from.toDate(), to.toDate());
assertEquals(entries.size(), 5);
// Fetch all of the Dec items
from = new DateTime(2012, 12, 1, 0, 0);
to = new DateTime(2012, 12, 31, 0, 0);
entries = onCallEntryDAO.findByDateRange("partition1", "unix_engineering", from.toDate(), to.toDate());
assertEquals(entries.size(), 1);
// Fetch all of the Feb items
from = new DateTime(2013, 2, 1, 0, 0);
to = new DateTime(2013, 2, 28, 0, 0);
entries = onCallEntryDAO.findByDateRange("partition1", "unix_engineering", from.toDate(), to.toDate());
assertEquals(entries.size(), 2);
// Fetch Jan and before
to = new DateTime(2013, 1, 31, 0, 0);
entries = onCallEntryDAO.findByDateRange("partition1", "unix_engineering", null, to.toDate());
assertEquals(entries.size(), 6);
// Fetch Jan and after
from = new DateTime(2013, 1, 1, 0, 0);
entries = onCallEntryDAO.findByDateRange("partition1", "unix_engineering", from.toDate(), null);
assertEquals(entries.size(), 7);
}
} | sudduth/Aardin | OnCall/OnCallImpl/src/test/java/org/aardin/oncall/tests/unit/dao/OnCallEntryDAOTest.java | Java | agpl-3.0 | 3,002 |
/* © 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
* License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). */
(function ($) {
"use strict";
$('.oe_website_sale').each(function () {
var $this = $(this),
$country_selector = $this.find("select[name=country_id]"),
$no_country_field = $this.find("#no_country_field");
// Change VAT flag when address country changes
$country_selector.on("change", function (event) {
if ($country_selector.val() && !$no_country_field.val()) {
$this.find(".js_select_country_code[data-country_id="
+ $country_selector.val() + "]")
.click();
}
});
});
$('form[action="/shop/confirm_order"]').on('submit', function(){
if(!this.no_country_field.value){
this.vat.value = "";
}
});
})(jQuery);
| brain-tec/e-commerce | website_sale_checkout_country_vat/static/src/js/change_country.js | JavaScript | agpl-3.0 | 921 |
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/
*/
package org.phenotips.entities.spi;
import org.phenotips.Constants;
import org.phenotips.entities.PrimaryEntity;
import org.phenotips.entities.PrimaryEntityConnectionsManager;
import org.xwiki.component.phase.Initializable;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.stability.Unstable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ObjectUtils;
/**
* Base class for implementing predicates, where the connections are stored in the Objects, referencing the Subject.
* <p>
* The abstract class works as-is. In order to create a proper connection manager component all that is needed is to
* extend this abstract class, set the right values for {@link AbstractPrimaryEntityConnectionsManager#subjectsManager}
* and {@link AbstractPrimaryEntityConnectionsManager#objectsManager} in {@link Initializable#initialize()}, add a
* {@code @Component} annotation and a proper {@code @Named} name following the recommended convention of
* {@code subjectType-predicate-objectType}.
* <p>
* The default behavior of this base class is to store connections in the Object XDocument, as a new XObject of type
* {@code PhenoTips.EntityBindingClass}, with a full reference to the Subject stored in the {@code reference} XProperty.
* </p>
*
* @param <S> the type of entities being the subject of the connection
* @param <O> the type of entities being the object of the connection
* @version $Id$
* @since 1.4
*/
@Unstable("New SPI introduced in 1.4")
@SuppressWarnings("checkstyle:MultipleStringLiterals")
public abstract class AbstractIncomingPrimaryEntityConnectionsManager<S extends PrimaryEntity, O extends PrimaryEntity>
extends AbstractPrimaryEntityConnectionsManager<S, O> implements PrimaryEntityConnectionsManager<S, O>
{
/** The XClass used for storing connections by default. */
public static final EntityReference INCOMING_CONNECTION_XCLASS =
new EntityReference("EntityBindingClass", EntityType.DOCUMENT, Constants.CODE_SPACE_REFERENCE);
/** The XProperty used for referencing the Subject document. */
public static final String REFERENCE_XPROPERTY = "reference";
@Override
public boolean connect(S subject, O object)
{
if (!ObjectUtils.allNotNull(subject, object)) {
throw new IllegalArgumentException();
}
return storeConnection(subject, object, object.getXDocument(), subject.getDocumentReference(), false);
}
@Override
public boolean disconnect(S subject, O object)
{
if (!ObjectUtils.allNotNull(subject, object)) {
throw new IllegalArgumentException();
}
return deleteConnection(subject, object, object.getXDocument(), subject.getDocumentReference(), false);
}
@Override
public Collection<O> getAllConnections(S subject)
{
if (subject == null) {
throw new IllegalArgumentException();
}
try {
Query q = this.queryManager.createQuery(
// Look for Object documents
", BaseObject objectObj, BaseObject connectionObj, StringProperty referenceProperty "
+ " where "
// The Object must have the right type
+ " objectObj.name = doc.fullName and "
+ " objectObj.className = :objectClass and "
// The connection is stored in the Object
+ " connectionObj.name = doc.fullName and "
+ " connectionObj.className = :connectionClass and "
// The reference property belongs to the connection
+ " referenceProperty.id.id = connectionObj.id and "
+ " referenceProperty.id.name = :referenceProperty and "
// The connection points to the Subject
+ " referenceProperty.value = :subjectDocument",
Query.HQL);
q.bindValue("objectClass", this.localSerializer.serialize(this.objectsManager.getEntityType()));
q.bindValue("connectionClass", this.localSerializer.serialize(getConnectionXClass()));
q.bindValue("referenceProperty", getReferenceProperty());
q.bindValue("subjectDocument", this.fullSerializer.serialize(subject.getDocumentReference()));
List<String> docNames = q.execute();
return docNames.stream().map(id -> this.objectsManager.get(id)).collect(Collectors.toList());
} catch (QueryException ex) {
this.logger.warn("Failed to query the Objects of type [{}] connected from [{}]: {}",
this.objectsManager.getEntityType(), subject.getId(), ex.getMessage());
}
return Collections.emptyList();
}
@Override
public Collection<S> getAllReverseConnections(O object)
{
if (object == null) {
throw new IllegalArgumentException();
}
try {
String wikiId = this.xcontextProvider.get().getWikiId() + ":";
Query q = this.queryManager.createQuery(
// Look for Subject documents
", BaseObject subjectObj, BaseObject connectionObj, StringProperty referenceProperty "
+ " where "
// The Subject must have the right type
+ " subjectObj.name = doc.fullName and "
+ " subjectObj.className = :subjectClass and "
// The connection is stored in the Object
+ " connectionObj.name = :objectDocument and "
+ " connectionObj.className = :connectionClass and "
// The reference property belongs to the connection
+ " referenceProperty.id.id = connectionObj.id and "
+ " referenceProperty.id.name = :referenceProperty and "
// The connection points to the Subject
+ " referenceProperty.value = concat(:wikiId, doc.fullName)",
Query.HQL);
q.bindValue("subjectClass", this.localSerializer.serialize(this.subjectsManager.getEntityType()));
q.bindValue("objectDocument", this.localSerializer.serialize(object.getDocumentReference()));
q.bindValue("connectionClass", this.localSerializer.serialize(getConnectionXClass()));
q.bindValue("referenceProperty", getReferenceProperty());
q.bindValue("wikiId", wikiId);
List<String> docNames = q.execute();
return docNames.stream().map(id -> this.subjectsManager.get(id)).collect(Collectors.toList());
} catch (QueryException ex) {
this.logger.warn("Failed to query the Subjects of type [{}] connected to [{}]: {}",
this.subjectsManager.getEntityType(), object.getId(), ex.getMessage());
}
return Collections.emptyList();
}
@Override
protected EntityReference getConnectionXClass()
{
return INCOMING_CONNECTION_XCLASS;
}
@Override
protected String getReferenceProperty()
{
return REFERENCE_XPROPERTY;
}
}
| phenotips/phenotips | components/entities/api/src/main/java/org/phenotips/entities/spi/AbstractIncomingPrimaryEntityConnectionsManager.java | Java | agpl-3.0 | 8,148 |
class Ticket::Glance
def self.report(reports)
reports.each do |mthd, klass|
# Define the getter method for this report
class_eval(<<-EOS, __FILE__, __LINE__)
def #{mthd}
@#{mthd} ||= #{klass}.new(@parent)
end
EOS
# Delegate methods to the created method
delegate(*klass.reporting_methods, :prefix => true, :to => mthd)
end
end
report :available => Ticket::Reports::Available,
:sold => Ticket::Reports::Sold,
:comped => Ticket::Reports::Comped,
:sales => Ticket::Reports::Sales
def initialize(parent)
@parent = parent
end
def as_json(options ={})
{ :tickets =>
{ :comped => comped.total,
:available => available.total,
:sold => {
:gross => sales.total
}
}
}
end
end | andrewkrug/artfully_ose | app/models/ticket/glance.rb | Ruby | agpl-3.0 | 846 |
/*
* Copyright © 2014 Benjamin Gehrels
*
* This file is part of The Single Transferable Vote Elections Library.
*
* The Single Transferable Vote Elections Library is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* The Single Transferable Vote Elections 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with The Single Transferable Vote
* Elections Library. If not, see <http://www.gnu.org/licenses/>.
*/
package info.gehrels.voting.genderedElections;
import com.google.common.collect.ImmutableCollection;
import info.gehrels.voting.Ballot;
import info.gehrels.voting.Vote;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static java.lang.String.format;
public final class StringBuilderBackedElectionCalculationWithFemaleExclusivePositionsListener
implements ElectionCalculationWithFemaleExclusivePositionsListener {
private final StringBuilder builder;
public StringBuilderBackedElectionCalculationWithFemaleExclusivePositionsListener(StringBuilder builder) {
this.builder = builder;
}
@Override
public void reducedNotFemaleExclusiveSeats(long numberOfOpenFemaleExclusiveSeats,
long numberOfElectedFemaleExclusiveSeats,
long numberOfOpenNotFemaleExclusiveSeats,
long numberOfElectableNotFemaleExclusiveSeats) {
formatLine(
"Es wurden nur %d von %d Frauenplätzen besetzt. Daher können auch nur %d von %d offenen Plätzen gewählt werden.",
numberOfElectedFemaleExclusiveSeats, numberOfOpenFemaleExclusiveSeats,
numberOfElectableNotFemaleExclusiveSeats, numberOfOpenNotFemaleExclusiveSeats);
}
@Override
public void candidateNotQualified(GenderedCandidate candidate, NonQualificationReason reason) {
formatLine("%s kann in diesem Wahlgang nicht antreten, Grund: %s", candidate.name,
getReasonAsGermanString(reason));
}
@Override
public void startElectionCalculation(GenderedElection election,
ImmutableCollection<Ballot<GenderedCandidate>> ballots) {
formatLine("Starte die Wahlberechnungen für %s.", election);
formatLine("Abgegebene Stimmen:");
List<Long> ballotIdsWithoutAVote = new ArrayList<>();
long numberOfCastVotes = 0;
for (Ballot<GenderedCandidate> ballot : ballots) {
Optional<Vote<GenderedCandidate>> vote = ballot.getVote(election);
if (vote.isPresent()) {
formatLine("Stimmzettel %d: %s", ballot.id, vote.get());
numberOfCastVotes++;
} else {
ballotIdsWithoutAVote.add(ballot.id);
}
}
formatLine("Insgesamt wurden für diese Wahl %d Stimmen abgegeben.", numberOfCastVotes);
if (!ballotIdsWithoutAVote.isEmpty()) {
formatLine("Keine Stimmabgabe auf den Stimmzetteln %s.", ballotIdsWithoutAVote);
}
}
@Override
public void startFemaleExclusiveElectionRun() {
formatLine("Starte die Berechnung der Frauenplätze.");
}
@Override
public void startNotFemaleExclusiveElectionRun() {
formatLine("Starte die Berechnung der offenen Plätze.");
}
private String getReasonAsGermanString(NonQualificationReason reason) {
switch (reason) {
case NOT_FEMALE:
return "Nicht weiblich";
case ALREADY_ELECTED:
return "Bereits gewählt";
}
throw new IllegalArgumentException("Unbekannter Grund: " + reason);
}
private void formatLine(String formatString, Object... objects) {
builder.append(format(formatString, objects)).append('\n');
}
}
| BGehrels/singleTransferableVoteElections | src/test/java/info/gehrels/voting/genderedElections/StringBuilderBackedElectionCalculationWithFemaleExclusivePositionsListener.java | Java | agpl-3.0 | 3,869 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2016
*/
/**
* Class CRM_Membershipcard_BAO_Card.
*
* parent class for building name membership cards
*/
class CRM_Membershipcard_BAO_Card {
/**
* @var bool
*/
public $debug = FALSE;
/**
* @var int
*/
public $border = 0;
/**
* @var string relationship that determines the secondary contact
*/
const RELATIONSHIP_TYPE_FOR_INHERITANCE = 'Provides Membership To';
/**
* @var string name badge used for membership card
*/
const NAME_BADGE_FOR_MEMBERSHIP_CARD = 'Membership Card';
/**
* @var int message template used in membership card
*/
const MEMBERSHIP_CARD_MESSAGE_TEMPLATE_ID = 80;
/**
* This function is called to create membership card pdf.
*
* @param array $memberships
* Associated array with membership info.
* @param array $layoutInfo
* Associated array which contains meta data about format/layout.
*/
public function createLabels(&$memberships, &$layoutInfo) {
$this->pdf = new CRM_Utils_PDF_Label($layoutInfo['format'], 'mm');
$this->pdf->Open();
$this->pdf->setPrintHeader(FALSE);
$this->pdf->setPrintFooter(FALSE);
$this->pdf->SetGenerator($this, "labelCreator");
$this->pdf->SetDisplayMode(100);
// this is very useful for debugging, by default set to FALSE
if ($this->debug) {
$this->border = "LTRB";
}
foreach ($memberships as $membership) {
$formattedRow = self::formatLabel($membership, $layoutInfo);
$this->pdf->AddPage();
$this->pdf->AddPdfLabel($formattedRow);
}
$this->pdf->Output('MembershipCards.pdf', 'D');
CRM_Utils_System::civiExit(1);
}
/**
* Function to create structure and add meta data according to layout.
*
* @param array $row
* Row element that needs to be formatted.
* @param array $layout
* Layout meta data.
*
* @return array
* row with meta data
*/
public static function formatLabel(&$row, &$layout) {
$formattedRow = array('labelFormat' => $layout['format']);
$formattedRow['values'] = $row;
return $formattedRow;
}
/**
* Function to create / place labels on the PDF document
*
* @param $formattedRow
*/
public function labelCreator($formattedRow) {
$this->pdf->SetFont('helvetica', '', '10');
$this->pdf->writeHTMLCell(115, 140, 15, 50, $formattedRow['values']['message']);
$this->pdf->SetFont('helvetica', '', '12');
$this->pdf->writeHTMLCell(80, 7, 19, 253, $formattedRow['values']['primary_first_name'] . ' ' . $formattedRow['values']['primary_last_name']);
$this->pdf->writeHTMLCell(27, 7, 19, 262, $formattedRow['values']['primary_membership_id']);
$this->pdf->writeHTMLCell(30, 7, 65, 262, $formattedRow['values']['membership_end_date']);
$this->pdf->writeHTMLCell(80, 7, 119, 253, $formattedRow['values']['other_first_name'] . ' ' . $formattedRow['values']['other_last_name']);
$this->pdf->writeHTMLCell(27, 7, 119, 262, $formattedRow['values']['other_membership_id']);
$this->pdf->writeHTMLCell(30, 7, 164, 262, $formattedRow['values']['other_membership_end_date']);
}
/**
* Build cards parameters before actually creating badges.
*
* @param array $params
* Associated array of submitted values.
* @param array $membershipIDs
*/
public static function buildCards(&$params, &$membershipIDs) {
// get name membership card layout info
$formatProperties = CRM_Core_OptionGroup::getValue('name_badge', self::NAME_BADGE_FOR_MEMBERSHIP_CARD, 'name');
$layoutInfo['format'] = json_decode($formatProperties, TRUE);
// get the membership data and sent it to the card creator
$rows = array();
$params = array('id' => self::MEMBERSHIP_CARD_MESSAGE_TEMPLATE_ID);
$defaults = array();
CRM_Core_BAO_MessageTemplate::retrieve($params, $defaults);
$message = $defaults['msg_html'];
$messageToken = CRM_Utils_Token::getTokens($message);
$memberships = CRM_Utils_Token::getMembershipTokenDetails($membershipIDs);
$html = array();
foreach ($membershipIDs as $membershipID) {
$membership = $memberships[$membershipID];
// get primary contact information
$contactId = $membership['contact_id'];
$params = array('contact_id' => $contactId);
list($contacts) = CRM_Utils_Token::getTokenDetails($params);
$tokenHtml = CRM_Utils_Token::replaceContactTokens($message, $contacts[$contactId], TRUE, $messageToken);
$tokenHtml = CRM_Utils_Token::replaceEntityTokens('membership', $membership, $tokenHtml, $messageToken);
$tokenHtml = CRM_Utils_Token::parseThroughSmarty($tokenHtml, $contacts[$contactId]);
$html[] = $tokenHtml;
$primaryContact = array(
'primary_first_name' => $contacts[$contactId]['first_name'],
'primary_last_name' => $contacts[$contactId]['last_name'],
'primary_membership_id' => $membershipID,
'membership_end_date' => CRM_Utils_Date::customformat($membership['end_date'], '%m/%d/%Y'),
'message' => $tokenHtml,
);
// get the information on other member of the family
$otherMemberInfo = array();
if (!empty($membership['relationship_name'])
&& $membership['relationship_name'] == self::RELATIONSHIP_TYPE_FOR_INHERITANCE) {
// get the contact via relationship
$result = civicrm_api3('Relationship', 'get', array(
'sequential' => 1,
'return' => array("contact_id_b"),
'relationship_type_id' => 11,
'contact_id_a' => $contactId,
));
$otherContactId = $result['values'][0]['contact_id_b'];
// get contact and membership information
$result = civicrm_api3('Contact', 'get', array(
'sequential' => 1,
'return' => array("first_name", "last_name"),
'id' => $otherContactId,
'api.Membership.get' => array('owner_membership_id' => $membershipID),
));
$otherMemberInfo = array(
'other_first_name' => $result['values'][0]['first_name'],
'other_last_name' => $result['values'][0]['last_name'],
'other_membership_id' => $result['values'][0]['api.Membership.get']['values'][0]['id'],
'other_membership_end_date' => CRM_Utils_Date::customformat($membership['end_date'], '%m/%d/%Y'),
);
}
else {
$otherMemberInfo = array('other_first_name' => 'VOID');
}
// add primary and other contact information
$rows[] = array_merge($primaryContact, $otherMemberInfo);
}
$membershipCardClass = new CRM_Membershipcard_BAO_Card();
$membershipCardClass->createLabels($rows, $layoutInfo);
}
}
| kurund/com.webaccessglobal.membershipcard | CRM/Membershipcard/BAO/Card.php | PHP | agpl-3.0 | 8,234 |
<?php
App::uses('AppController', 'Controller');
App::uses('Xml', 'Utility');
class ServersController extends AppController {
public $components = array('Security' ,'RequestHandler'); // XXX ACL component
public $paginate = array(
'limit' => 60,
'recursive' => -1,
'contain' => array(
'User' => array(
'fields' => array('User.id', 'User.org_id', 'User.email'),
),
'Organisation' => array(
'fields' => array('Organisation.name', 'Organisation.id'),
),
'RemoteOrg' => array(
'fields' => array('RemoteOrg.name', 'RemoteOrg.id'),
),
),
'maxLimit' => 9999, // LATER we will bump here on a problem once we have more than 9999 events
'order' => array(
'Server.url' => 'ASC'
),
);
public $uses = array('Server', 'Event');
public function beforeFilter() {
parent::beforeFilter();
// permit reuse of CSRF tokens on some pages.
switch ($this->request->params['action']) {
case 'push':
case 'pull':
case 'getVersion':
case 'testConnection':
$this->Security->csrfUseOnce = false;
}
}
public function index() {
if (!$this->_isSiteAdmin()) {
if (!$this->userRole['perm_sync'] && !$this->userRole['perm_admin']) $this->redirect(array('controller' => 'events', 'action' => 'index'));
$this->paginate['conditions'] = array('Server.org_id LIKE' => $this->Auth->user('org_id'));
}
$this->set('servers', $this->paginate());
$collection = array();
$collection['orgs'] = $this->Server->Organisation->find('list', array(
'fields' => array('id', 'name'),
));
$this->loadModel('Tag');
$collection['tags'] = $this->Tag->find('list', array(
'fields' => array('id', 'name'),
));
$this->set('collection', $collection);
}
public function previewIndex($id) {
$urlparams = '';
$passedArgs = array();
if (!$this->_isSiteAdmin()) {
throw new MethodNotAllowedException('You are not authorised to do that.');
}
$server = $this->Server->find('first', array('conditions' => array('Server.id' => $id), 'recursive' => -1, 'fields' => array('Server.id', 'Server.url', 'Server.name')));
if (empty($server)) throw new NotFoundException('Invalid server ID.');
$validFilters = $this->Server->validEventIndexFilters;
foreach ($validFilters as $k => $filter) {
if (isset($this->passedArgs[$filter])) {
$passedArgs[$filter] = $this->passedArgs[$filter];
if ($k != 0) $urlparams .= '/';
$urlparams .= $filter . ':' . $this->passedArgs[$filter];
}
}
$combinedArgs = array_merge($this->passedArgs, $passedArgs);
if (!isset($combinedArgs['sort'])) {
$combinedArgs['sort'] = 'timestamp';
$combinedArgs['direction'] = 'desc';
}
$events = $this->Server->previewIndex($id, $this->Auth->user(), $combinedArgs);
$this->loadModel('Event');
$threat_levels = $this->Event->ThreatLevel->find('all');
$this->set('threatLevels', Set::combine($threat_levels, '{n}.ThreatLevel.id', '{n}.ThreatLevel.name'));
App::uses('CustomPaginationTool', 'Tools');
$customPagination = new CustomPaginationTool();
$params = $customPagination->createPaginationRules($events, $this->passedArgs, $this->alias);
$this->params->params['paging'] = array($this->modelClass => $params);
if (is_array($events)) $customPagination->truncateByPagination($events, $params);
else ($events = array());
$this->set('events', $events);
$this->set('eventDescriptions', $this->Event->fieldDescriptions);
$this->set('analysisLevels', $this->Event->analysisLevels);
$this->set('distributionLevels', $this->Event->distributionLevels);
$shortDist = array(0 => 'Organisation', 1 => 'Community', 2 => 'Connected', 3 => 'All', 4 => ' sharing Group');
$this->set('shortDist', $shortDist);
$this->set('ajax', $this->request->is('ajax'));
$this->set('id', $id);
$this->set('urlparams', $urlparams);
$this->set('passedArgs', json_encode($passedArgs));
$this->set('passedArgsArray', $passedArgs);
$this->set('server', $server);
}
public function previewEvent($serverId, $eventId, $all = false) {
if (!$this->_isSiteAdmin()) {
throw new MethodNotAllowedException('You are not authorised to do that.');
}
$server = $this->Server->find('first', array('conditions' => array('Server.id' => $serverId), 'recursive' => -1, 'fields' => array('Server.id', 'Server.url', 'Server.name')));
if (empty($server)) throw new NotFoundException('Invalid server ID.');
$event = $this->Server->previewEvent($serverId, $eventId);
// work on this in the future to improve the feedback
// 2 = wrong error code
if (is_numeric($event))throw new NotFoundException('Invalid event.');
$this->loadModel('Event');
$params = $this->Event->rearrangeEventForView($event, $this->passedArgs, $all);
$this->params->params['paging'] = array('Server' => $params);
$this->set('event', $event);
$this->set('server', $server);
$this->loadModel('Event');
$dataForView = array(
'Attribute' => array('attrDescriptions' => 'fieldDescriptions', 'distributionDescriptions' => 'distributionDescriptions', 'distributionLevels' => 'distributionLevels'),
'Event' => array('eventDescriptions' => 'fieldDescriptions', 'analysisLevels' => 'analysisLevels')
);
foreach ($dataForView as $m => $variables) {
if ($m === 'Event') $currentModel = $this->Event;
else if ($m === 'Attribute') $currentModel = $this->Event->Attribute;
foreach ($variables as $alias => $variable) {
$this->set($alias, $currentModel->{$variable});
}
}
$threat_levels = $this->Event->ThreatLevel->find('all');
$this->set('threatLevels', Set::combine($threat_levels, '{n}.ThreatLevel.id', '{n}.ThreatLevel.name'));
}
public function filterEventIndex($id) {
if (!$this->_isSiteAdmin()) {
throw new MethodNotAllowedException('You are not authorised to do that.');
}
$validFilters = $this->Server->validEventIndexFilters;
$validatedFilterString = '';
foreach ($this->passedArgs as $k => $v) {
if (in_array('' . $k, $validFilters)) {
if ($validatedFilterString != '') $validatedFilterString .= '/';
$validatedFilterString .= $k . ':' . $v;
}
}
$this->set('id', $id);
$this->set('validFilters', $validFilters);
$this->set('filter', $validatedFilterString);
}
public function add() {
if (!$this->_isSiteAdmin()) $this->redirect(array('controller' => 'servers', 'action' => 'index'));
if ($this->request->is('post')) {
if($this->_isRest()) {
if (!isset($this->request->data['Server'])) {
$this->request->data = array('Server' => $this->request->data);
}
}
$json = json_decode($this->request->data['Server']['json'], true);
$fail = false;
if (empty(Configure::read('MISP.host_org_id'))) $this->request->data['Server']['internal'] = 0;
// test the filter fields
if (!empty($this->request->data['Server']['pull_rules']) && !$this->Server->isJson($this->request->data['Server']['pull_rules'])) {
$fail = true;
$error_msg = __('The pull filter rules must be in valid JSON format.');
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'add', false, array('pull_rules' => $error_msg), $this->response->type());
} else {
$this->Session->setFlash($error_msg);
}
}
if (!$fail && !empty($this->request->data['Server']['push_rules']) && !$this->Server->isJson($this->request->data['Server']['push_rules'])) {
$fail = true;
$error_msg = __('The push filter rules must be in valid JSON format.');
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'add', false, array('push_rules' => $error_msg), $this->response->type());
} else {
$this->Session->setFlash($error_msg);
}
}
if (!$fail) {
// force check userid and orgname to be from yourself
$this->request->data['Server']['org_id'] = $this->Auth->user('org_id');
if ($this->request->data['Server']['organisation_type'] < 2) $this->request->data['Server']['remote_org_id'] = $json['id'];
else {
$existingOrgs = $this->Server->Organisation->find('first', array(
'conditions' => array('uuid' => $json['uuid']),
'recursive' => -1,
'fields' => array('id', 'uuid')
));
if (!empty($existingOrgs)) {
$fail = true;
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'add', false, array('Organisation' => 'Remote Organisation\'s uuid already used'), $this->response->type());
} else {
$this->Session->setFlash(__('That organisation could not be created as the uuid is in use already.'));
}
}
if (!$fail) {
$this->Server->Organisation->create();
$orgSave = $this->Server->Organisation->save(array(
'name' => $json['name'],
'uuid' => $json['uuid'],
'local' => 0,
'created_by' => $this->Auth->user('id')
));
if (!$orgSave) {
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'add', false, $this->Server->Organisation->validationError, $this->response->type());
} else {
$this->Session->setFlash(__('Couldn\'t save the new organisation, are you sure that the uuid is in the correct format?.'));
}
$fail = true;
$this->request->data['Server']['external_name'] = $json['name'];
$this->request->data['Server']['external_uuid'] = $json['uuid'];
} else {
$this->request->data['Server']['remote_org_id'] = $this->Server->Organisation->id;
}
}
}
if (Configure::read('MISP.host_org_id') == 0 || $this->request->data['Server']['remote_org_id'] != Configure::read('MISP.host_org_id')) {
$this->request->data['Server']['internal'] = 0;
}
if (!$fail) {
$this->request->data['Server']['org_id'] = $this->Auth->user('org_id');
if ($this->Server->save($this->request->data)) {
if (isset($this->request->data['Server']['submitted_cert']) && $this->request->data['Server']['submitted_cert']['size'] != 0) {
$this->__saveCert($this->request->data, $this->Server->id, false);
}
if (isset($this->request->data['Server']['submitted_client_cert']) && $this->request->data['Server']['submitted_client_cert']['size'] != 0) {
$this->__saveCert($this->request->data, $this->Server->id, true);
}
if($this->_isRest()) {
$server = $this->Server->find('first', array(
'conditions' => array('Server.id' => $this->Server->id),
'recursive' => -1
));
return $this->RestResponse->viewData($server, $this->response->type());
} else {
$this->Session->setFlash(__('The server has been saved'));
$this->redirect(array('action' => 'index'));
}
} else {
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'add', false, $this->Server->validationError, $this->response->type());
} else {
$this->Session->setFlash(__('The server could not be saved. Please, try again.'));
}
}
}
}
}
if($this->_isRest()) {
return $this->RestResponse->describe('Servers', 'add', false, $this->response->type());
} else {
$organisationOptions = array(0 => 'Local organisation', 1 => 'External organisation', 2 => 'New external organisation');
$temp = $this->Server->Organisation->find('all', array(
'conditions' => array('local' => true),
'fields' => array('id', 'name'),
'order' => array('lower(Organisation.name) ASC')
));
$localOrganisations = array();
$allOrgs = array();
foreach ($temp as $o) {
$localOrganisations[$o['Organisation']['id']] = $o['Organisation']['name'];
$allOrgs[] = array('id' => $o['Organisation']['id'], 'name' => $o['Organisation']['name']);
}
$temp = $this->Server->Organisation->find('all', array(
'conditions' => array('local' => false),
'fields' => array('id', 'name'),
'order' => array('lower(Organisation.name) ASC')
));
$externalOrganisations = array();
foreach ($temp as $o) {
$externalOrganisations[$o['Organisation']['id']] = $o['Organisation']['name'];
$allOrgs[] = array('id' => $o['Organisation']['id'], 'name' => $o['Organisation']['name']);
}
$this->set('host_org_id', Configure::read('MISP.host_org_id'));
$this->set('organisationOptions', $organisationOptions);
$this->set('localOrganisations', $localOrganisations);
$this->set('externalOrganisations', $externalOrganisations);
$this->set('allOrganisations', $allOrgs);
// list all tags for the rule picker
$this->loadModel('Tag');
$temp = $this->Tag->find('all', array('recursive' => -1));
$allTags = array();
foreach ($temp as $t) $allTags[] = array('id' => $t['Tag']['id'], 'name' => $t['Tag']['name']);
$this->set('allTags', $allTags);
$this->set('host_org_id', Configure::read('MISP.host_org_id'));
}
}
public function edit($id = null) {
$this->Server->id = $id;
if (!$this->Server->exists()) {
throw new NotFoundException(__('Invalid server'));
}
$s = $this->Server->read(null, $id);
if (!$this->_isSiteAdmin()) $this->redirect(array('controller' => 'servers', 'action' => 'index'));
if ($this->request->is('post') || $this->request->is('put')) {
if (empty(Configure::read('MISP.host_org_id'))) $this->request->data['Server']['internal'] = 0;
if($this->_isRest()) {
if (!isset($this->request->data['Server'])) {
$this->request->data = array('Server' => $this->request->data);
}
}
if(isset($this->request->data['Server']['json'])) {
$json = json_decode($this->request->data['Server']['json'], true);
} else {
$json = NULL;
}
$fail = false;
// test the filter fields
if (!empty($this->request->data['Server']['pull_rules']) && !$this->Server->isJson($this->request->data['Server']['pull_rules'])) {
$fail = true;
$error_msg = __('The pull filter rules must be in valid JSON format.');
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'edit', false, array('pull_rules' => $error_msg), $this->response->type());
} else {
$this->Session->setFlash($error_msg);
}
}
if (!$fail && !empty($this->request->data['Server']['push_rules']) && !$this->Server->isJson($this->request->data['Server']['push_rules'])) {
$fail = true;
$error_msg = __('The push filter rules must be in valid JSON format.');
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'edit', false, array('push_rules' => $error_msg), $this->response->type());
} else {
$this->Session->setFlash($error_msg);
}
}
if (!$fail) {
// say what fields are to be updated
$fieldList = array('id', 'url', 'push', 'pull', 'unpublish_event', 'publish_without_email', 'remote_org_id', 'name' ,'self_signed', 'cert_file', 'client_cert_file', 'push_rules', 'pull_rules', 'internal');
$this->request->data['Server']['id'] = $id;
if (isset($this->request->data['Server']['authkey']) && "" != $this->request->data['Server']['authkey']) $fieldList[] = 'authkey';
if(isset($this->request->data['Server']['organisation_type']) && isset($json)) {
// adds 'remote_org_id' in the fields to update
$fieldList[] = 'remote_org_id';
if ($this->request->data['Server']['organisation_type'] < 2) $this->request->data['Server']['remote_org_id'] = $json['id'];
else {
$existingOrgs = $this->Server->Organisation->find('first', array(
'conditions' => array('uuid' => $json['uuid']),
'recursive' => -1,
'fields' => array('id', 'uuid')
));
if (!empty($existingOrgs)) {
$fail = true;
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'edit', false, array('Organisation' => 'Remote Organisation\'s uuid already used'), $this->response->type());
} else {
$this->Session->setFlash(__('That organisation could not be created as the uuid is in use already.'));
}
}
if (!$fail) {
$this->Server->Organisation->create();
$orgSave = $this->Server->Organisation->save(array(
'name' => $json['name'],
'uuid' => $json['uuid'],
'local' => 0,
'created_by' => $this->Auth->user('id')
));
if (!$orgSave) {
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'edit', false, $this->Server->Organisation->validationError, $this->response->type());
} else {
$this->Session->setFlash(__('Couldn\'t save the new organisation, are you sure that the uuid is in the correct format?.'));
}
$fail = true;
$this->request->data['Server']['external_name'] = $json['name'];
$this->request->data['Server']['external_uuid'] = $json['uuid'];
} else {
$this->request->data['Server']['remote_org_id'] = $this->Server->Organisation->id;
}
}
}
if (empty(Configure::read('MISP.host_org_id')) || $this->request->data['Server']['remote_org_id'] != Configure::read('MISP.host_org_id')) {
$this->request->data['Server']['internal'] = 0;
}
}
}
if (!$fail) {
// Save the data
if ($this->Server->save($this->request->data, true, $fieldList)) {
if (isset($this->request->data['Server']['submitted_cert']) && $this->request->data['Server']['submitted_cert']['size'] != 0 && (!isset($this->request->data['Server']['delete_cert']) || !$this->request->data['Server']['delete_cert'])) {
$this->__saveCert($this->request->data, $this->Server->id, false);
} else {
if (isset($this->request->data['Server']['delete_cert']) && $this->request->data['Server']['delete_cert']) $this->__saveCert($this->request->data, $this->Server->id, false, true);
}
if (isset($this->request->data['Server']['submitted_client_cert']) && $this->request->data['Server']['submitted_client_cert']['size'] != 0 && (!isset($this->request->data['Server']['delete_client_cert']) || !$this->request->data['Server']['delete_client_cert'])) {
$this->__saveCert($this->request->data, $this->Server->id, true);
} else {
if (isset($this->request->data['Server']['delete_client_cert']) && $this->request->data['Server']['delete_client_cert']) $this->__saveCert($this->request->data, $this->Server->id, true, true);
}
if($this->_isRest()) {
$server = $this->Server->find('first', array(
'conditions' => array('Server.id' => $this->Server->id),
'recursive' => -1
));
return $this->RestResponse->viewData($server, $this->response->type());
} else {
$this->Session->setFlash(__('The server has been saved'));
$this->redirect(array('action' => 'index'));
}
} else {
if($this->_isRest()) {
return $this->RestResponse->saveFailResponse('Servers', 'edit', false, $this->Server->validationError, $this->response->type());
} else {
$this->Session->setFlash(__('The server could not be saved. Please, try again.'));
}
}
}
} else {
$this->Server->read(null, $id);
$this->Server->set('authkey', '');
$this->request->data = $this->Server->data;
}
if($this->_isRest()) {
return $this->RestResponse->describe('Servers', 'edit', false, $this->response->type());
} else {
$organisationOptions = array(0 => 'Local organisation', 1 => 'External organisation', 2 => 'New external organisation');
$temp = $this->Server->Organisation->find('all', array(
'conditions' => array('local' => true),
'fields' => array('id', 'name'),
'order' => array('lower(Organisation.name) ASC')
));
$localOrganisations = array();
$allOrgs = array();
foreach ($temp as $o) {
$localOrganisations[$o['Organisation']['id']] = $o['Organisation']['name'];
$allOrgs[] = array('id' => $o['Organisation']['id'], 'name' => $o['Organisation']['name']);
}
$temp = $this->Server->Organisation->find('all', array(
'conditions' => array('local' => false),
'fields' => array('id', 'name'),
'order' => array('lower(Organisation.name) ASC')
));
$externalOrganisations = array();
foreach ($temp as $o) {
$externalOrganisations[$o['Organisation']['id']] = $o['Organisation']['name'];
$allOrgs[] = array('id' => $o['Organisation']['id'], 'name' => $o['Organisation']['name']);
}
$oldRemoteSetting = 0;
if (!$this->Server->data['RemoteOrg']['local']) $oldRemoteSetting = 1;
$this->set('host_org_id', Configure::read('MISP.host_org_id'));
$this->set('oldRemoteSetting', $oldRemoteSetting);
$this->set('oldRemoteOrg', $this->Server->data['RemoteOrg']['id']);
$this->set('organisationOptions', $organisationOptions);
$this->set('localOrganisations', $localOrganisations);
$this->set('externalOrganisations', $externalOrganisations);
$this->set('allOrganisations', $allOrgs);
// list all tags for the rule picker
$this->loadModel('Tag');
$temp = $this->Tag->find('all', array('recursive' => -1));
$allTags = array();
foreach ($temp as $t) $allTags[] = array('id' => $t['Tag']['id'], 'name' => $t['Tag']['name']);
$this->set('allTags', $allTags);
$this->set('server', $s);
$this->set('host_org_id', Configure::read('MISP.host_org_id'));
}
}
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->Server->id = $id;
if (!$this->Server->exists()) {
throw new NotFoundException(__('Invalid server'));
}
$s = $this->Server->read(null, $id);
if (!$this->_isSiteAdmin()) $this->redirect(array('controller' => 'servers', 'action' => 'index'));
if ($this->Server->delete()) {
$this->Session->setFlash(__('Server deleted'));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Server was not deleted'));
$this->redirect(array('action' => 'index'));
}
/**
* Pull one or more events with attributes from a remote instance.
* Set $technique to
* full - download everything
* incremental - only new events
* <int> - specific id of the event to pull
*/
public function pull($id = null, $technique=false) {
$this->Server->id = $id;
if (!$this->Server->exists()) {
throw new NotFoundException(__('Invalid server'));
}
$s = $this->Server->read(null, $id);
if (!$this->_isSiteAdmin() && !($s['Server']['org_id'] == $this->Auth->user('org_id') && $this->_isAdmin())) $this->redirect(array('controller' => 'servers', 'action' => 'index'));
$this->Server->id = $id;
if (!$this->Server->exists()) {
throw new NotFoundException(__('Invalid server'));
}
if (false == $this->Server->data['Server']['pull'] && ($technique == 'full' || $technique == 'incremental')) {
$this->Session->setFlash(__('Pull setting not enabled for this server.'));
$this->redirect(array('action' => 'index'));
}
if (!Configure::read('MISP.background_jobs')) {
$result = $this->Server->pull($this->Auth->user(), $id, $technique, $s);
// error codes
if (isset($result[0]) && is_numeric($result[0])) {
switch ($result[0]) {
case '1' :
$this->Session->setFlash(__('Not authorised. This is either due to an invalid auth key, or due to the sync user not having authentication permissions enabled on the remote server. Another reason could be an incorrect sync server setting.'));
break;
case '2' :
$this->Session->setFlash($result[1]);
break;
case '3' :
throw new NotFoundException('Sorry, this is not yet implemented');
break;
case '4' :
$this->redirect(array('action' => 'index'));
break;
}
$this->redirect($this->referer());
} else {
$this->set('successes', $result[0]);
$this->set('fails', $result[1]);
$this->set('pulledProposals', $result[2]);
$this->set('lastpulledid', $result[3]);
}
} else {
$this->loadModel('Job');
$this->Job->create();
$data = array(
'worker' => 'default',
'job_type' => 'pull',
'job_input' => 'Server: ' . $id,
'status' => 0,
'retries' => 0,
'org' => $this->Auth->user('Organisation')['name'],
'message' => 'Pulling.',
);
$this->Job->save($data);
$jobId = $this->Job->id;
$process_id = CakeResque::enqueue(
'default',
'ServerShell',
array('pull', $this->Auth->user('id'), $id, $technique, $jobId)
);
$this->Job->saveField('process_id', $process_id);
$this->Session->setFlash('Pull queued for background execution.');
$this->redirect($this->referer());
}
}
public function push($id = null, $technique=false) {
$this->Server->id = $id;
if (!$this->Server->exists()) {
throw new NotFoundException(__('Invalid server'));
}
$s = $this->Server->read(null, $id);
if (!$this->_isSiteAdmin() && !($s['Server']['org_id'] == $this->Auth->user('org_id') && $this->_isAdmin())) $this->redirect(array('controller' => 'servers', 'action' => 'index'));
if (!Configure::read('MISP.background_jobs')) {
$server = $this->Server->read(null, $id);
App::uses('SyncTool', 'Tools');
$syncTool = new SyncTool();
$HttpSocket = $syncTool->setupHttpSocket($server);
$result = $this->Server->push($id, $technique, false, $HttpSocket, $this->Auth->user());
if ($result === false) {
$this->Session->setFlash('The remote server is too outdated to initiate a push towards it. Please notify the hosting organisation of the remote instance.');
$this->redirect(array('action' => 'index'));
}
$this->set('successes', $result[0]);
$this->set('fails', $result[1]);
} else {
$this->loadModel('Job');
$this->Job->create();
$data = array(
'worker' => 'default',
'job_type' => 'push',
'job_input' => 'Server: ' . $id,
'status' => 0,
'retries' => 0,
'org' => $this->Auth->user('Organisation')['name'],
'message' => 'Pushing.',
);
$this->Job->save($data);
$jobId = $this->Job->id;
$process_id = CakeResque::enqueue(
'default',
'ServerShell',
array('push', $id, $technique, $jobId, $this->Auth->user('id'))
);
$this->Job->saveField('process_id', $process_id);
$this->Session->setFlash('Push queued for background execution.');
$this->redirect(array('action' => 'index'));
}
}
private function __saveCert($server, $id, $client = false, $delete = false) {
if ($client) {
$subm = 'submitted_client_cert';
$attr = 'client_cert_file';
$ins = '_client';
} else {
$subm = 'submitted_cert';
$attr = 'cert_file';
$ins = '';
}
if (!$delete) {
$ext = '';
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
App::uses('FileAccessTool', 'Tools');
if (!$this->Server->checkFilename($server['Server'][$subm]['name'])) {
throw new Exception ('Filename not allowed');
}
$file = new File($server['Server'][$subm]['name']);
$ext = $file->ext();
if (($ext != 'pem') || !$server['Server'][$subm]['size'] > 0) {
$this->Session->setFlash('Incorrect extension or empty file.');
$this->redirect(array('action' => 'index'));
}
// read pem file data
$pemData = (new FileAccessTool())->readFromFile($server['Server'][$subm]['tmp_name'], $server['Server'][$subm]['size']);
$destpath = APP . "files" . DS . "certs" . DS;
$dir = new Folder(APP . "files" . DS . "certs", true);
$pemfile = new File($destpath . $id . $ins . '.' . $ext);
$result = $pemfile->write($pemData);
$s = $this->Server->read(null, $id);
$s['Server'][$attr] = $s['Server']['id'] . $ins . '.' . $ext;
if ($result) $this->Server->save($s);
} else {
$s = $this->Server->read(null, $id);
$s['Server'][$attr] = '';
$this->Server->save($s);
}
}
public function serverSettingsReloadSetting($setting, $id) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
$pathToSetting = explode('.', $setting);
if (strpos($setting, 'Plugin.Enrichment') !== false || strpos($setting, 'Plugin.Import') !== false || strpos($setting, 'Plugin.Export') !== false) {
$settingObject = $this->Server->getCurrentServerSettings();
}
else $settingObject = $this->Server->serverSettings;
foreach ($pathToSetting as $key) {
if (!isset($settingObject[$key])) throw new MethodNotAllowedException();
$settingObject = $settingObject[$key];
}
$result = $this->Server->serverSettingReadSingle($settingObject, $setting, $key);
$this->set('setting', $result);
$priorityErrorColours = array(0 => 'red', 1 => 'yellow', 2 => 'green');
$this->set('priorityErrorColours', $priorityErrorColours);
$priorities = array(0 => 'Critical', 1 => 'Recommended', 2 => 'Optional', 3 => 'Deprecated');
$this->set('priorities', $priorities);
$this->set('k', $id);
$this->layout = false;
$this->render('/Elements/healthElements/settings_row');
}
private function __loadLocalOrgs() {
$this->loadModel('Organisation');
$local_orgs = $this->Organisation->find('list', array(
'conditions' => array('local' => 1),
'recursive' => -1,
'fields' => array('Organisation.id', 'Organisation.name')
));
return array_replace(array(0 => 'No organisation selected.'), $local_orgs);
}
public function serverSettings($tab=false) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if ($this->request->is('Get')) {
$tabs = array(
'MISP' => array('count' => 0, 'errors' => 0, 'severity' => 5),
'Encryption' => array('count' => 0, 'errors' => 0, 'severity' => 5),
'Proxy' => array('count' => 0, 'errors' => 0, 'severity' => 5),
'Security' => array('count' => 0, 'errors' => 0, 'severity' => 5),
'Plugin' => array('count' => 0, 'errors' => 0, 'severity' => 5)
);
$writeableErrors = array(0 => 'OK', 1 => 'not found', 2 => 'is not writeable');
$readableErrors = array(0 => 'OK', 1 => 'not readable');
$gpgErrors = array(0 => 'OK', 1 => 'FAIL: settings not set', 2 => 'FAIL: Failed to load GPG', 3 => 'FAIL: Issues with the key/passphrase', 4 => 'FAIL: encrypt failed');
$proxyErrors = array(0 => 'OK', 1 => 'not configured (so not tested)', 2 => 'Getting URL via proxy failed');
$zmqErrors = array(0 => 'OK', 1 => 'not enabled (so not tested)', 2 => 'Python ZeroMQ library not installed correctly.', 3 => 'ZeroMQ script not running.');
$stixOperational = array(0 => 'STIX or CyBox library not installed correctly', 1 => 'OK');
$stixVersion = array(0 => 'Incorrect STIX version installed, found $current, expecting $expected', 1 => 'OK');
$cyboxVersion = array(0 => 'Incorrect CyBox version installed, found $current, expecting $expected', 1 => 'OK');
$sessionErrors = array(0 => 'OK', 1 => 'High', 2 => 'Alternative setting used', 3 => 'Test failed');
$moduleErrors = array(0 => 'OK', 1 => 'System not enabled', 2 => 'No modules found');
$finalSettings = $this->Server->serverSettingsRead();
$issues = array(
'errors' => array(
0 => array(
'value' => 0,
'description' => 'MISP will not operate correctly or will be unsecure until these issues are resolved.'
),
1 => array(
'value' => 0,
'description' => 'Some of the features of MISP cannot be utilised until these issues are resolved.'
),
2 => array(
'value' => 0,
'description' => 'There are some optional tweaks that could be done to improve the looks of your MISP instance.'
),
),
'deprecated' => array(),
'overallHealth' => 3,
);
$dumpResults = array();
$tempArray = array();
foreach ($finalSettings as $k => $result) {
if ($result['level'] == 3) $issues['deprecated']++;
$tabs[$result['tab']]['count']++;
if (isset($result['error']) && $result['level'] < 3) {
$issues['errors'][$result['level']]['value']++;
if ($result['level'] < $issues['overallHealth']) $issues['overallHealth'] = $result['level'];
$tabs[$result['tab']]['errors']++;
if ($result['level'] < $tabs[$result['tab']]['severity']) $tabs[$result['tab']]['severity'] = $result['level'];
}
if (isset($result['optionsSource']) && !empty($result['optionsSource'])) {
$result['options'] = $this->{'__load' . $result['optionsSource']}();
}
$dumpResults[] = $result;
if ($result['tab'] == $tab) {
if (isset($result['subGroup'])) $tempArray[$result['subGroup']][] = $result;
else $tempArray['general'][] = $result;
}
}
$finalSettings = $tempArray;
// Diagnostics portion
$diagnostic_errors = 0;
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
$additionalViewVars = array();
if ($tab == 'files') {
$files = $this->__manageFiles();
$this->set('files', $files);
}
// Only run this check on the diagnostics tab
if ($tab == 'diagnostics' || $tab == 'download') {
// check if the current version of MISP is outdated or not
$version = $this->__checkVersion();
$this->set('version', $version);
$gitStatus = $this->Server->getCurrentGitStatus();
$this->set('branch', $gitStatus['branch']);
$this->set('commit', $gitStatus['commit']);
$this->set('latestCommit', $gitStatus['latestCommit']);
$phpSettings = array(
'max_execution_time' => array(
'explanation' => 'The maximum duration that a script can run (does not affect the background workers). A too low number will break long running scripts like comprehensive API exports',
'recommended' => 300,
'unit' => false
),
'memory_limit' => array(
'explanation' => 'The maximum memory that PHP can consume. It is recommended to raise this number since certain exports can generate a fair bit of memory usage',
'recommended' => 512,
'unit' => 'M'
),
'upload_max_filesize' => array(
'explanation' => 'The maximum size that an uploaded file can be. It is recommended to raise this number to allow for the upload of larger samples',
'recommended' => 50,
'unit' => 'M'
),
'post_max_size' => array(
'explanation' => 'The maximum size of a POSTed message, this has to be at least the same size as the upload_max_filesize setting',
'recommended' => 50,
'unit' => 'M'
)
);
foreach ($phpSettings as $setting => $settingArray) {
$phpSettings[$setting]['value'] = ini_get($setting);
if ($settingArray['unit']) $phpSettings[$setting]['value'] = intval(rtrim($phpSettings[$setting]['value'], $phpSettings[$setting]['unit']));
else $phpSettings[$setting]['value'] = intval($phpSettings[$setting]['value']);
}
$this->set('phpSettings', $phpSettings);
if ($version && (!$version['upToDate'] || $version['upToDate'] == 'older')) $diagnostic_errors++;
// check if the STIX and Cybox libraries are working and the correct version using the test script stixtest.py
$stix = $this->Server->stixDiagnostics($diagnostic_errors, $stixVersion, $cyboxVersion);
// if GPG is set up in the settings, try to encrypt a test message
$gpgStatus = $this->Server->gpgDiagnostics($diagnostic_errors);
// if the message queue pub/sub is enabled, check whether the extension works
$zmqStatus = $this->Server->zmqDiagnostics($diagnostic_errors);
// if Proxy is set up in the settings, try to connect to a test URL
$proxyStatus = $this->Server->proxyDiagnostics($diagnostic_errors);
$moduleTypes = array('Enrichment', 'Import', 'Export');
foreach ($moduleTypes as $type) {
$moduleStatus[$type] = $this->Server->moduleDiagnostics($diagnostic_errors, $type);
}
// check the size of the session table
$sessionCount = 0;
$sessionStatus = $this->Server->sessionDiagnostics($diagnostic_errors, $sessionCount);
$this->set('sessionCount', $sessionCount);
$additionalViewVars = array('gpgStatus', 'sessionErrors', 'proxyStatus', 'sessionStatus', 'zmqStatus', 'stixVersion', 'cyboxVersion', 'moduleStatus', 'gpgErrors', 'proxyErrors', 'zmqErrors', 'stixOperational', 'stix', 'moduleErrors', 'moduleTypes');
}
// check whether the files are writeable
$writeableDirs = $this->Server->writeableDirsDiagnostics($diagnostic_errors);
$writeableFiles = $this->Server->writeableFilesDiagnostics($diagnostic_errors);
$readableFiles = $this->Server->readableFilesDiagnostics($diagnostic_errors);
$extensions = $this->Server->extensionDiagnostics();
// check if the encoding is not set to utf8
$dbEncodingStatus = $this->Server->databaseEncodingDiagnostics($diagnostic_errors);
$viewVars = array(
'diagnostic_errors', 'tabs', 'tab', 'issues', 'finalSettings', 'writeableErrors', 'readableErrors', 'writeableDirs', 'writeableFiles', 'readableFiles', 'extensions', 'dbEncodingStatus'
);
$viewVars = array_merge($viewVars, $additionalViewVars);
foreach ($viewVars as $viewVar) $this->set($viewVar, ${$viewVar});
$workerIssueCount = 0;
if (Configure::read('MISP.background_jobs')) {
$this->set('worker_array', $this->Server->workerDiagnostics($workerIssueCount));
} else {
$workerIssueCount = 4;
$this->set('worker_array', array());
}
if ($tab == 'download') {
foreach ($dumpResults as $key => $dr) {
unset($dumpResults[$key]['description']);
}
$dump = array(
'version' => $version,
'phpSettings' => $phpSettings,
'gpgStatus' => $gpgErrors[$gpgStatus],
'proxyStatus' => $proxyErrors[$proxyStatus],
'zmqStatus' => $zmqStatus,
'stix' => $stix,
'moduleStatus' => $moduleStatus,
'writeableDirs' => $writeableDirs,
'writeableFiles' => $writeableFiles,
'readableFiles' => $readableFiles,
'finalSettings' => $dumpResults,
'extensions' => $extensions
);
$this->response->body(json_encode($dump, JSON_PRETTY_PRINT));
$this->response->type('json');
$this->response->download('MISP.report.json');
return $this->response;
}
$priorities = array(0 => 'Critical', 1 => 'Recommended', 2 => 'Optional', 3 => 'Deprecated');
$this->set('priorities', $priorities);
$this->set('workerIssueCount', $workerIssueCount);
$priorityErrorColours = array(0 => 'red', 1 => 'yellow', 2 => 'green');
$this->set('priorityErrorColours', $priorityErrorColours);
$this->set('phpversion', phpversion());
$this->set('phpmin', $this->phpmin);
$this->set('phprec', $this->phprec);
}
}
public function startWorker($type) {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$validTypes = array('default', 'email', 'scheduler', 'cache', 'prio');
if (!in_array($type, $validTypes)) throw new MethodNotAllowedException('Invalid worker type.');
$prepend = '';
if (Configure::read('MISP.rh_shell_fix')) $prepend = 'export PATH=$PATH:"/opt/rh/rh-php56/root/usr/bin:/opt/rh/rh-php56/root/usr/sbin"; ';
if ($type != 'scheduler') shell_exec($prepend . APP . 'Console' . DS . 'cake CakeResque.CakeResque start --interval 5 --queue ' . $type .' > /dev/null 2>&1 &');
else shell_exec($prepend . APP . 'Console' . DS . 'cake CakeResque.CakeResque startscheduler -i 5 > /dev/null 2>&1 &');
$this->redirect('/servers/serverSettings/workers');
}
public function stopWorker($pid) {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->Server->killWorker($pid, $this->Auth->user());
$this->redirect('/servers/serverSettings/workers');
}
private function __checkVersion() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
App::uses('SyncTool', 'Tools');
$syncTool = new SyncTool();
try {
$HttpSocket = $syncTool->setupHttpSocket();
$response = $HttpSocket->get('https://api.github.com/repos/MISP/MISP/tags');
$tags = $response->body;
} catch (Exception $e) {
return false;
}
if ($response->isOK() && !empty($tags)) {
$json_decoded_tags = json_decode($tags);
// find the latest version tag in the v[major].[minor].[hotfix] format
for ($i = 0; $i < count($json_decoded_tags); $i++) {
if (preg_match('/^v[0-9]+\.[0-9]+\.[0-9]+$/', $json_decoded_tags[$i]->name)) break;
}
return $this->Server->checkVersion($json_decoded_tags[$i]->name);
} else {
return false;
}
}
public function serverSettingsEdit($setting, $id, $forceSave = false) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if (!isset($setting) || !isset($id)) throw new MethodNotAllowedException();
$this->set('id', $id);
if (strpos($setting, 'Plugin.Enrichment') !== false || strpos($setting, 'Plugin.Import') !== false || strpos($setting, 'Plugin.Export') !== false) {
$serverSettings = $this->Server->getCurrentServerSettings();
}
else $serverSettings = $this->Server->serverSettings;
$relevantSettings = (array_intersect_key(Configure::read(), $serverSettings));
$found = null;
foreach ($serverSettings as $k => $s) {
if (isset($s['branch'])) {
foreach ($s as $ek => $es) {
if ($ek != 'branch') {
if ($setting == $k . '.' . $ek) {
$found = $es;
continue 2;
}
}
}
} else {
if ($setting == $k) {
$found = $s;
continue;
}
}
}
if ($this->request->is('get')) {
if ($found != null) {
$value = Configure::read($setting);
if ($value) $found['value'] = $value;
$found['setting'] = $setting;
}
if (isset($found['optionsSource']) && !empty($found['optionsSource'])) {
$found['options'] = $this->{'__load' . $found['optionsSource']}();
}
$subGroup = 'general';
$subGroup = explode('.', $setting);
if ($subGroup[0] === 'Plugin') {
$subGroup = explode('_', $subGroup[1])[0];
} else {
$subGroup = 'general';
}
$this->set('subGroup', $subGroup);
$this->set('setting', $found);
$this->render('ajax/server_settings_edit');
}
if ($this->request->is('post')) {
$this->autoRender = false;
$this->loadModel('Log');
if (!is_writeable(APP . 'Config/config.php')) {
$this->Log->create();
$result = $this->Log->save(array(
'org' => $this->Auth->user('Organisation')['name'],
'model' => 'Server',
'model_id' => 0,
'email' => $this->Auth->user('email'),
'action' => 'serverSettingsEdit',
'user_id' => $this->Auth->user('id'),
'title' => 'Server setting issue',
'change' => 'There was an issue witch changing ' . $setting . ' to ' . $this->request->data['Server']['value'] . '. The error message returned is: app/Config.config.php is not writeable to the apache user. No changes were made.',
));
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'app/Config.config.php is not writeable to the apache user.')),'status'=>200));
}
if (isset($found['beforeHook'])) {
$beforeResult = call_user_func_array(array($this->Server, $found['beforeHook']), array($setting, $this->request->data['Server']['value']));
if ($beforeResult !== true) {
$this->Log->create();
$result = $this->Log->save(array(
'org' => $this->Auth->user('Organisation')['name'],
'model' => 'Server',
'model_id' => 0,
'email' => $this->Auth->user('email'),
'action' => 'serverSettingsEdit',
'user_id' => $this->Auth->user('id'),
'title' => 'Server setting issue',
'change' => 'There was an issue witch changing ' . $setting . ' to ' . $this->request->data['Server']['value'] . '. The error message returned is: ' . $beforeResult . 'No changes were made.',
));
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => $beforeResult)),'status'=>200));
}
}
$this->request->data['Server']['value'] = trim($this->request->data['Server']['value']);
if ($found['type'] == 'boolean') {
$this->request->data['Server']['value'] = ($this->request->data['Server']['value'] ? true : false);
}
if ($found['type'] == 'numeric') {
$this->request->data['Server']['value'] = intval($this->request->data['Server']['value']);
}
$testResult = $this->Server->{$found['test']}($this->request->data['Server']['value']);
if (!$forceSave && $testResult !== true) {
if ($testResult === false) $errorMessage = $found['errorMessage'];
else $errorMessage = $testResult;
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => $errorMessage)),'status'=>200));
} else {
$oldValue = Configure::read($setting);
$this->Server->serverSettingsSaveValue($setting, $this->request->data['Server']['value']);
$this->Log->create();
$result = $this->Log->save(array(
'org' => $this->Auth->user('Organisation')['name'],
'model' => 'Server',
'model_id' => 0,
'email' => $this->Auth->user('email'),
'action' => 'serverSettingsEdit',
'user_id' => $this->Auth->user('id'),
'title' => 'Server setting changed',
'change' => $setting . ' (' . $oldValue . ') => (' . $this->request->data['Server']['value'] . ')',
));
// execute after hook
if (isset($found['afterHook'])) {
$afterResult = call_user_func_array(array($this->Server, $found['afterHook']), array($setting, $this->request->data['Server']['value']));
if ($afterResult !== true) {
$this->Log->create();
$result = $this->Log->save(array(
'org' => $this->Auth->user('Organisation')['name'],
'model' => 'Server',
'model_id' => 0,
'email' => $this->Auth->user('email'),
'action' => 'serverSettingsEdit',
'user_id' => $this->Auth->user('id'),
'title' => 'Server setting issue',
'change' => 'There was an issue after setting a new setting. The error message returned is: ' . $afterResult,
));
return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => $afterResult)),'status'=>200));
}
}
return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'Field updated.')),'status'=>200));
}
}
}
public function restartWorkers() {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$this->Server->workerRemoveDead($this->Auth->user());
$prepend = '';
if (Configure::read('MISP.rh_shell_fix')) {
$prepend = 'export PATH=$PATH:"/opt/rh/rh-php56/root/usr/bin:/opt/rh/rh-php56/root/usr/sbin"; ';
if (Configure::read('MISP.rh_shell_fix_path')) {
if ($this->Server->testForPath(Configure::read('MISP.rh_shell_fix_path'))) $prepend = Configure::read('MISP.rh_shell_fix_path');
}
}
shell_exec($prepend . APP . 'Console' . DS . 'worker' . DS . 'start.sh > /dev/null 2>&1 &');
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'workers'));
}
private function __manageFiles() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
$files = $this->Server->grabFiles();
return $files;
}
public function deleteFile($type, $filename) {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if ($this->request->is('post')) {
$validItems = $this->Server->getFileRules();
App::uses('File', 'Utility');
$existingFile = new File($validItems[$type]['path'] . DS . $filename);
if (!$existingFile->exists()) {
$this->Session->setFlash(__('File not found.', true), 'default', array(), 'error');
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
}
if ($existingFile->delete()) {
$this->Session->setFlash('File deleted.');
} else {
$this->Session->setFlash(__('File could not be deleted.', true), 'default', array(), 'error');
}
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
} else {
throw new MethodNotAllowedException('This action expects a POST request.');
}
}
public function uploadFile($type) {
if (!$this->_isSiteAdmin() || !$this->request->is('post')) throw new MethodNotAllowedException();
$validItems = $this->Server->getFileRules();
// Check if there were problems with the file upload
// only keep the last part of the filename, this should prevent directory attacks
$filename = basename($this->request->data['Server']['file']['name']);
if (!preg_match("/" . $validItems[$type]['regex'] . "/", $filename)) {
$this->Session->setFlash(__($validItems[$type]['regex_error'], true), 'default', array(), 'error');
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
}
if (empty($this->request->data['Server']['file']['tmp_name']) || !is_uploaded_file($this->request->data['Server']['file']['tmp_name'])) {
$this->Session->setFlash(__('Upload failed.', true), 'default', array(), 'error');
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
}
// check if the file already exists
App::uses('File', 'Utility');
$existingFile = new File($validItems[$type]['path'] . DS . $filename);
if ($existingFile->exists()) {
$this->Session->setFlash(__('File already exists. If you would like to replace it, remove the old one first.', true), 'default', array(), 'error');
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
}
$result = move_uploaded_file($this->request->data['Server']['file']['tmp_name'], $validItems[$type]['path'] . DS . $filename);
if ($result) {
$this->Session->setFlash('File uploaded.');
} else {
$this->Session->setFlash(__('Upload failed.', true), 'default', array(), 'error');
}
$this->redirect(array('controller' => 'servers', 'action' => 'serverSettings', 'files'));
}
public function fetchServersForSG($idList = '{}') {
$id_exclusion_list = json_decode($idList, true);
$temp = $this->Server->find('all', array(
'conditions' => array(
'id !=' => $id_exclusion_list,
),
'recursive' => -1,
'fields' => array('id', 'name', 'url')
));
$servers = array();
foreach ($temp as $server) {
$servers[] = array('id' => $server['Server']['id'], 'name' => $server['Server']['name'], 'url' => $server['Server']['url']);
}
$this->layout = false;
$this->autoRender = false;
$this->set('servers', $servers);
$this->render('ajax/fetch_servers_for_sg');
}
public function postTest() {
if ($this->request->is('post')) {
// Fix for PHP-FPM / Nginx / etc
// Fix via https://www.popmartian.com/tipsntricks/2015/07/14/howto-use-php-getallheaders-under-fastcgi-php-fpm-nginx-etc/
if (!function_exists('getallheaders')) {
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
} else {
$headers = getallheaders();
}
$result = array();
$result['body'] = $this->request->data;
$result['headers']['Content-type'] = isset($headers['Content-type']) ? $headers['Content-type'] : 0;
$result['headers']['Accept'] = isset($headers['Accept']) ? $headers['Accept'] : 0;
$result['headers']['Authorization'] = isset($headers['Authorization']) ? 'OK' : 0;
return new CakeResponse(array('body'=> json_encode($result)));
} else {
throw new MethodNotAllowedException('Invalid request, expecting a POST request.');
}
}
public function testConnection($id = false) {
if (!$this->Auth->user('Role')['perm_sync'] && !$this->Auth->user('Role')['perm_site_admin']) throw new MethodNotAllowedException('You don\'t have permission to do that.');
$this->Server->id = $id;
if (!$this->Server->exists()) {
throw new NotFoundException(__('Invalid server'));
}
$result = $this->Server->runConnectionTest($id);
if ($result['status'] == 1) {
$version = json_decode($result['message'], true);
if (isset($version['version']) && preg_match('/^[0-9]+\.+[0-9]+\.[0-9]+$/', $version['version'])) {
App::uses('Folder', 'Utility');
$file = new File(ROOT . DS . 'VERSION.json', true);
$local_version = json_decode($file->read(), true);
$file->close();
$version = explode('.', $version['version']);
$mismatch = false;
$newer = false;
$parts = array('major', 'minor', 'hotfix');
if ($version[0] == 2 && $version[1] == 4 && $version[2] > 68) {
$post = $this->Server->runPOSTTest($id);
}
$testPost = false;
foreach ($parts as $k => $v) {
if (!$mismatch) {
if ($version[$k] > $local_version[$v]) {
$mismatch = $v;
$newer = 'remote';
} else if ($version[$k] < $local_version[$v]) {
$mismatch = $v;
$newer = 'local';
}
}
}
if (!isset($version['perm_sync'])) {
if (!$this->Server->checkLegacyServerSyncPrivilege($id)) {
$result['status'] = 7;
return new CakeResponse(array('body'=> json_encode($result)));
}
} else {
if (!$version['perm_sync']) {
$result['status'] = 7;
return new CakeResponse(array('body'=> json_encode($result)));
}
}
return new CakeResponse(array('body'=> json_encode(array('status' => 1, 'local_version' => implode('.', $local_version), 'version' => implode('.', $version), 'mismatch' => $mismatch, 'newer' => $newer, 'post' => isset($post) ? $post : 'too old'))));
} else {
$result['status'] = 3;
}
}
return new CakeResponse(array('body'=> json_encode($result)));
}
public function startZeroMQServer() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
App::uses('PubSubTool', 'Tools');
$pubSubTool = new PubSubTool();
$result = $pubSubTool->restartServer();
if ($result === true) return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'ZeroMQ server successfully started.')),'status'=>200));
else return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => $result)),'status'=>200));
}
public function stopZeroMQServer() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
App::uses('PubSubTool', 'Tools');
$pubSubTool = new PubSubTool();
$result = $pubSubTool->killService();
if ($result === true) return new CakeResponse(array('body'=> json_encode(array('saved' => true, 'success' => 'ZeroMQ server successfully killed.')),'status'=>200));
else return new CakeResponse(array('body'=> json_encode(array('saved' => false, 'errors' => 'Could not kill the previous instance of the ZeroMQ script.')),'status'=>200));
}
public function statusZeroMQServer() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
App::uses('PubSubTool', 'Tools');
$pubSubTool = new PubSubTool();
$result = $pubSubTool->statusCheck();
if (!empty($result)) {
$this->set('events', $result['publishCount']);
$this->set('time', date('Y/m/d H:i:s', $result['timestamp']));
$this->set('time2', date('Y/m/d H:i:s', $result['timestampSettings']));
}
$this->render('ajax/zeromqstatus');
}
public function purgeSessions() {
if (!$this->_isSiteAdmin()) throw new MethodNotAllowedException();
if ($this->Server->updateDatabase('cleanSessionTable') == false) {
$this->Session->setFlash('Could not purge the session table.');
}
$this->redirect('/servers/serverSettings/diagnostics');
}
public function clearWorkerQueue($worker) {
if (!$this->_isSiteAdmin() || !$this->request->is('Post') || $this->request->is('ajax')) throw new MethodNotAllowedException();
$worker_array = array('cache', 'default', 'email', 'prio');
if (!in_array($worker, $worker_array)) throw new MethodNotAllowedException('Invalid worker');
$redis = Resque::redis();
$redis->del('queue:' . $worker);
$this->Session->setFlash('Queue cleared.');
$this->redirect($this->referer());
}
public function getVersion() {
if (!$this->userRole['perm_auth']) throw new MethodNotAllowedException('This action requires API access.');
$versionArray = $this->Server->checkMISPVersion();
$this->set('response', array('version' => $versionArray['major'] . '.' . $versionArray['minor'] . '.' . $versionArray['hotfix'], 'perm_sync' => $this->userRole['perm_sync']));
$this->set('_serialize', 'response');
}
public function getPyMISPVersion() {
$this->set('response', array('version' => $this->pyMispVersion));
$this->set('_serialize', 'response');
}
public function getGit() {
$status = $this->Server->getCurrentGitStatus();
}
public function checkout() {
$result = $this->Server->checkoutMain();
}
public function update() {
if ($this->request->is('post')) {
$status = $this->Server->getCurrentGitStatus();
$update = $this->Server->update($status);
return new CakeResponse(array('body'=> $update));
} else {
$branch = $this->Server->getCurrentBranch();
$this->set('branch', $branch);
$this->render('ajax/update');
}
}
}
| cristianbell/MISP | app/Controller/ServersController.php | PHP | agpl-3.0 | 56,712 |
#!/usr/bin/env python2
from titanembeds.app import app, socketio
import subprocess
def init_debug():
import os
from flask import jsonify, request
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # Testing oauthlib
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Session viewer https://gist.github.com/babldev/502364a3f7c9bafaa6db
def decode_flask_cookie(secret_key, cookie_str):
import hashlib
from itsdangerous import URLSafeTimedSerializer
from flask.sessions import TaggedJSONSerializer
salt = 'cookie-session'
serializer = TaggedJSONSerializer()
signer_kwargs = {
'key_derivation': 'hmac',
'digest_method': hashlib.sha1
}
s = URLSafeTimedSerializer(secret_key, salt=salt, serializer=serializer, signer_kwargs=signer_kwargs)
return s.loads(cookie_str)
@app.route("/session")
def session():
cookie = request.cookies.get('session')
if cookie:
decoded = decode_flask_cookie(app.secret_key, request.cookies.get('session'))
else:
decoded = None
return jsonify(session_cookie=decoded)
@app.route("/github-update", methods=["POST"])
def github_update():
try:
subprocess.Popen("git pull", shell=True).wait()
except OSError:
return "ERROR"
@app.route("/error")
def make_error():
1 / 0
return "OK"
if __name__ == "__main__":
init_debug()
socketio.run(app, host="0.0.0.0",port=3000,debug=True)
| TitanEmbeds/Titan | webapp/run.py | Python | agpl-3.0 | 1,599 |
//
// ImportUtils.cs
//
// Author:
// Emmanuel Mathot <emmanuel.mathot@terradue.com>
//
// Copyright (c) 2014 Terradue
using System;
using System.Collections.Generic;
using System.Xml;
using Terradue.ServiceModel.Syndication;
using System.Collections.Specialized;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using Newtonsoft.Json.Linq;
using Terradue.OpenSearch.Result;
using Terradue.GeoJson.Geometry;
using Terradue.ServiceModel.Ogc.GeoRss.GeoRss;
namespace Terradue.OpenSearch.GeoJson.Import
{
public class ImportUtils
{
ImportOptions options;
public ImportUtils(ImportOptions options)
{
this.options = options;
}
public Dictionary<string, object> SyndicationElementExtensions(SyndicationElementExtensionCollection elements, ref NameValueCollection namespaces)
{
string prefix = "";
Dictionary<string, object> properties = new Dictionary<string, object>();
XPathDocument x = new XPathDocument(elements.GetReaderAtElementExtensions());
XPathNavigator nav = x.CreateNavigator();
if (options.KeepNamespaces) {
var allNodes = nav.SelectDescendants(XPathNodeType.All, true);
while (allNodes.MoveNext()) {
var names = allNodes.Current.GetNamespacesInScope(XmlNamespaceScope.Local);
foreach (var n in names.Keys) {
namespaces.Set(n, names[n]);
}
}
}
nav.MoveToRoot();
var childnodes = nav.SelectChildren(XPathNodeType.Element);
XPathNavigator prev = null;
while (childnodes.MoveNext()) {
var childnode = childnodes.Current;
XmlNamespaceManager xnsm = new XmlNamespaceManager(childnode.NameTable);
if (options.KeepNamespaces) {
prefix = childnode.Prefix + ":";
}
try {
properties.Add(prefix + childnode.LocalName, ImportNode(childnode.Clone()));
} catch (ArgumentException) {
if (properties.ContainsKey(prefix + childnode.LocalName) && properties[prefix + childnode.LocalName] is object[]) {
object[] array = (object[])properties[prefix + childnode.LocalName];
List<object> list = array.ToList();
list.Add(ImportNode(childnode.Clone()));
properties[prefix + childnode.LocalName] = list.ToArray();
} else {
List<object> list = new List<object>();
list.Add(ImportNode(childnode.Clone()));
properties[prefix + childnode.LocalName] = list.ToArray();
}
}
prev = childnode.Clone();
}
return properties;
}
public SyndicationElementExtension[] PropertiesToSyndicationElementExtensions(Dictionary<string, object> properties)
{
XmlNamespaceManager xmlns = new XmlNamespaceManager(new NameTable());
List<SyndicationElementExtension> elements = new List<SyndicationElementExtension>();
NameValueCollection namespaces = new NameValueCollection();
if (properties.ContainsKey("@namespaces")) {
var temp = properties["@namespaces"];
var namedic = (Dictionary<string, object>)temp;
namedic.Keys.SingleOrDefault(k => {
namespaces.Set(k, (string)namedic[k]);
return false;
});
}
foreach (var key in properties.Keys) {
if (key.StartsWith("@atom") || key.StartsWith("atom"))
continue;
if (key == "@namespaces")
continue;
XDocument xdoc = new XDocument();
var prop = ImportProperty(key, properties[key], namespaces);
xdoc.Add(prop);
XmlReader xreader = xdoc.CreateReader();
xreader.Settings.IgnoreWhitespace = true;
xmlns = new XmlNamespaceManager(xreader.NameTable);
foreach (var prefix in namespaces.AllKeys) {
if (string.IsNullOrEmpty(prefix))
continue;
xmlns.AddNamespace(prefix, namespaces[prefix]);
}
elements.Add(new SyndicationElementExtension(xreader));
}
return elements.ToArray();
}
XObject ImportProperty(string key, object obj, NameValueCollection namespaces)
{
string ns, localname;
XObject xobject;
ns = "";
localname = key;
if (key.StartsWith("@")) {
localname = localname.Remove(0, 1);
}
if (localname.Contains(":")) {
string prefix = localname.Split(':')[0];
ns = namespaces[prefix] == null ? "" : namespaces[prefix];
localname = key.Split(':')[1];
}
if (key.StartsWith("@")) {
xobject = new XAttribute(XName.Get(localname, ns), obj);
return xobject;
}
if (obj is Dictionary<string, object>) {
Dictionary<string, object> prop = (Dictionary<string, object>)obj;
List<object> objects = new List<object>();
foreach (var key2 in prop.Keys) {
XObject child = ImportProperty(key2, prop[key2], namespaces);
if (child is XElement && ((XElement)child).Name == XName.Get(localname, ns) && ((XElement)child).FirstNode.NodeType == XmlNodeType.Text)
objects.Add(((XElement)child).Value);
else
objects.Add(child);
}
xobject = new XElement(XName.Get(localname, ns), objects.ToArray());
} else
xobject = new XElement(XName.Get(localname, ns), obj);
return xobject;
}
/*public Dictionary<string, object> SyndicationElementExtensions(XmlElement[] elements, ref NameValueCollection namespaces) {
string prefix = "";
Dictionary<string,object> prop = new Dictionary<string, object>();
foreach (XmlElement node in elements) {
if (node.Prefix == "xmlns")
continue;
if (options.KeepNamespaces) {
prefix = node.Prefix + ":";
XmlNamespaceManager xnsm2 = new XmlNamespaceManager(node.OwnerDocument.NameTable);
foreach (var names in xnsm2.GetNamespacesInScope(XmlNamespaceScope.All)) {
namespaces.Set(names.Key, names.Value);
}
}
prop.Add(prefix + node.LocalName, ImportNode(node));
}
return prop;
}*/
public Dictionary<string, object> ImportAttributeExtensions(Dictionary<XmlQualifiedName, string> attributeExtensions, NameValueCollection namespaces, XmlNamespaceManager xnsm)
{
Dictionary<string, object> properties = new Dictionary<string, object>();
string prefix = "";
foreach (var key in attributeExtensions.Keys) {
if (options.KeepNamespaces && !string.IsNullOrEmpty(xnsm.LookupPrefix(key.Namespace))) {
prefix = xnsm.LookupPrefix(key.Namespace) + ":";
}
properties.Add("@" + prefix + key.Name, attributeExtensions[key]);
}
return properties;
}
/*public object ImportNode(XmlNode node) {
string prefix = "";
if (options.KeepNamespaces) {
prefix = node.Prefix + ":";
}
if (node.NodeType == XmlNodeType.Attribute)
return node.Value;
if (node.NodeType == XmlNodeType.Text)
return node.InnerText;
if (node.NodeType == XmlNodeType.Element | node.NodeType == XmlNodeType.Document) {
if (node.ChildNodes.Count == 1 && node.FirstChild.NodeType == XmlNodeType.Text) {
return node.FirstChild.InnerText;
}
Dictionary<string, object> properties = new Dictionary<string, object>();
foreach (XmlNode childnode in node.ChildNodes) {
if (node.Prefix == "xmlns")
continue;
try {
properties.Add(prefix + childnode.LocalName, ImportNode(childnode));
} catch (ArgumentException) {
if (properties[prefix + childnode.LocalName] is object[]) {
object[] array = (object[])properties[prefix + childnode.LocalName];
List<object> list = array.ToList();
list.Add(ImportNode(childnode));
properties[prefix + childnode.LocalName] = list.ToArray();
} else {
List<object> list = new List<object>();
list.Add(ImportNode(childnode));
properties[prefix + childnode.LocalName] = list.ToArray();
}
}
}
if (node.Attributes != null) {
foreach (XmlAttribute attr in node.Attributes) {
if (attr.Prefix == "xmlns")
continue;
properties.Add("@" + prefix + attr.LocalName, ImportNode(attr));
}
}
return properties;
}
return null;
;
}*/
public object ImportNode(XPathNavigator nav)
{
string prefix = "";
string text = null;
var childnodes = nav.SelectChildren(XPathNodeType.All);
string textNodeLocalName = nav.LocalName;
Dictionary<string, object> properties = new Dictionary<string, object>();
while (childnodes.MoveNext()) {
textNodeLocalName = nav.LocalName;
var childnode = childnodes.Current;
if (childnode.Prefix == "xmlns")
continue;
if (options.KeepNamespaces && !string.IsNullOrEmpty(childnode.Prefix)) {
prefix = childnode.Prefix + ":";
}
if (childnode.NodeType == XPathNodeType.Attribute) {
properties.Add("@" + prefix + childnode.LocalName, childnode.Value);
continue;
}
if (childnode.NodeType == XPathNodeType.Text) {
text = childnode.Value;
continue;
}
if (childnode.NodeType == XPathNodeType.Element) {
try {
var subprop = ImportNode(childnode.Clone());
if (subprop is Dictionary<string, object> && ((Dictionary<string, object>)subprop).Count == 0) {
continue;
}
if (properties.ContainsKey(prefix + childnode.LocalName)) {
List<object> array = null;
if (properties[prefix + childnode.LocalName] is List<object>) {
array = (List<object>)properties[prefix + childnode.LocalName];
} else {
array = new List<object>();
array.Add(properties[prefix + childnode.LocalName]);
properties.Remove(prefix + childnode.LocalName);
properties.Add(prefix + childnode.LocalName, array);
}
array.Add(subprop);
} else {
properties.Add(prefix + childnode.LocalName, subprop);
}
} catch (ArgumentException) {
if (properties[prefix + childnode.LocalName] is object[]) {
object[] array = (object[])properties[prefix + childnode.LocalName];
List<object> list = array.ToList();
list.Add(ImportNode(childnode));
properties[prefix + childnode.LocalName] = list.ToArray();
} else {
List<object> list = new List<object>();
list.Add(ImportNode(childnode));
properties[prefix + childnode.LocalName] = list.ToArray();
}
}
}
}
if (nav.MoveToFirstAttribute()) {
if ((options.KeepNamespaces || textNodeLocalName == "Query") && !string.IsNullOrEmpty(nav.Prefix)) {
prefix = nav.Prefix + ":";
}
properties.Add("@" + prefix + nav.LocalName, nav.Value);
while (nav.MoveToNextAttribute()) {
if ((options.KeepNamespaces || textNodeLocalName == "Query") && !string.IsNullOrEmpty(nav.Prefix)) {
prefix = nav.Prefix + ":";
}
try {
properties.Add("@" + prefix + nav.LocalName, nav.Value);
} catch (ArgumentException) {
}
}
}
if (string.IsNullOrEmpty(text))
return properties;
if (options.AsMixed == false && text != null && properties.Count == 0) {
return text;
}
if (text != null) {
if (options.KeepNamespaces && !string.IsNullOrEmpty(nav.Prefix)) {
prefix = nav.Prefix + ":";
}
properties.Add(prefix + textNodeLocalName, text);
}
return properties;
}
public static GeometryObject FindGeometry(IOpenSearchResultItem item)
{
GeometryObject savegeom = null;
if (item.ElementExtensions != null && item.ElementExtensions.Count > 0) {
foreach (var ext in item.ElementExtensions) {
XmlReader xr = ext.GetReader();
if ( string.IsNullOrEmpty(xr.LocalName))
xr.Read();
var name = xr.LocalName;
switch (xr.NamespaceURI) {
// 1) search for georss
case "http://www.georss.org/georss":
savegeom = ServiceModel.Ogc.GeoRss.GeoRss.GeoRssHelper.Deserialize(xr).ToGeometry();
if (name != "box" && name != "point") {
return savegeom;
}
break;
// 2) search for georss10
case "http://www.georss.org/georss/10":
savegeom = ServiceModel.Ogc.GeoRss.GeoRss10.GeoRss10Extensions.ToGeometry(ServiceModel.Ogc.GeoRss.GeoRss10.GeoRss10Helper.Deserialize(xr));
if (name != "box" && name != "point") {
return savegeom;
}
break;
// 3) search for dct:spatial
case "http://purl.org/dc/terms/":
if (xr.LocalName == "spatial") {
xr.Read();
savegeom = WktExtensions.WktToGeometry(xr.Value);
if (!(savegeom is Point)) {
return savegeom;
}
}
break;
default:
continue;
}
}
}
return savegeom;
}
public static SyndicationLink FromDictionnary(Dictionary<string, object> link, string prefix = "")
{
if (link.ContainsKey("@" + prefix + "href")) {
long length = 0;
string rel = null;
string title = null;
string type = null;
Uri href = new Uri((string)link["@" + prefix + "href"]);
object r = null;
if (link.TryGetValue("@" + prefix + "rel", out r))
rel = (string)r;
if (link.TryGetValue("@" + prefix + "title", out r))
title = (string)r;
if (link.TryGetValue("@" + prefix + "type", out r))
type = (string)r;
if (link.TryGetValue("@" + prefix + "", out r))
if (r is string)
long.TryParse((string)r, out length);
else
length = (long)r;
SyndicationLink slink = new SyndicationLink(href, rel, title, type, length);
return slink;
}
throw new ArgumentException("Not a link");
}
public static SyndicationLink FromJTokenList(JToken link, string prefix = "")
{
if (link.SelectToken("@" + prefix + "href") != null) {
long length = 0;
string rel = null;
string title = null;
string type = null;
Uri href = new Uri((string)link.SelectToken("@" + prefix + "href").ToString());
object r = null;
if (link.SelectToken("@" + prefix + "rel") != null)
rel = link.SelectToken("@" + prefix + "rel").ToString();
if (link.SelectToken("@" + prefix + "title") != null)
title = link.SelectToken("@" + prefix + "title").ToString();
if (link.SelectToken("@" + prefix + "type") != null)
type = link.SelectToken("@" + prefix + "type").ToString();
if (link.SelectToken("@" + prefix + "size") != null)
long.TryParse(link.SelectToken("@" + prefix + "size").ToString(), out length);
else
length = 0;
SyndicationLink slink = new SyndicationLink(href, rel, title, type, length);
return slink;
}
throw new ArgumentException("Not a link");
}
}
}
| Terradue/DotNetOpenSearchGeoJson | Terradue.OpenSearch.GeoJson/Terradue/OpenSearch/GeoJson/Import/ImportUtils.cs | C# | agpl-3.0 | 14,902 |
package humanize
import "strings"
// Language definition structures.
// List all the existing language providers here.
var languages = map[string]LanguageProvider{
"pl": lang_pl,
"en": lang_en,
"zh-cn": lang_zh_cn,
}
func Register(language string, provider LanguageProvider) {
language = strings.ToLower(language)
languages[language] = provider
}
func HasLanguage(language string) bool {
language = strings.ToLower(language)
_, ok := languages[language]
return ok
}
func AllLanguages() map[string]LanguageProvider {
return languages
}
// LanguageProvider is a struct defining all the needed language elements.
type LanguageProvider struct {
Times Times
}
var (
DefaultLanguage = `en`
DefaultTimeUnits = TimeUnits{
"second": 1,
"minute": Minute,
"hour": Hour,
"day": Day,
"week": Week,
"month": Month,
"year": Year,
}
)
// Times Time related language elements.
type Times struct {
// Time ranges to humanize time.
Ranges []TimeRanges
// String for formatting time in the future.
Future string
// String for formatting time in the past.
Past string
// String to humanize now.
Now string
// Remainder separator
RemainderSep string
// Unit values for matching the input. Partial matches are ok.
Units TimeUnits
}
// TimeUnits Time unit definitions for input parsing. Use partial matches.
type TimeUnits map[string]int64
// TimeRanges Definition of time ranges to match against.
type TimeRanges struct {
UpperLimit int64
DivideBy int64
Ranges []TimeRange
}
type TimeRange struct {
UpperLimit int64
Format string
}
| admpub/nging | vendor/github.com/admpub/humanize/lang_structs.go | GO | agpl-3.0 | 1,591 |
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'play_more' => 'Thay vào đó, hay là chơi osu! một chút nhỉ?',
'require_login' => 'Vui lòng đăng nhập để tiếp tục.',
'require_verification' => 'Vui lòng xác minh để tiếp tục.',
'restricted' => "Không thể làm việc đó trong khi bị hạn chế.",
'silenced' => "Không thể làm việc đó trong khi bị cấm nói.",
'unauthorized' => 'Truy cập bị từ chối.',
'beatmap_discussion' => [
'destroy' => [
'is_hype' => 'Không thể hủy bỏ hype.',
'has_reply' => 'Không thể xóa cuộc thảo luận có trả lời trong đó',
],
'nominate' => [
'exhausted' => 'Bạn đã đạt giới hạn số lần đề cử của hôm nay, hãy thử lại vào ngày mai.',
'incorrect_state' => 'Có lỗi khi thực hiện, hãy thử tải lại trang.',
'owner' => "Bạn không thể đề cử beatmap của bạn.",
'set_metadata' => 'Bạn phải chọn thể loại nhạc và ngôn ngữ trước khi nominating.',
],
'resolve' => [
'not_owner' => 'Chỉ có người mở thread và chủ beatmap mới có thể đánh dấu cuộc thảo luận là đã được giải quyết.',
],
'store' => [
'mapper_note_wrong_user' => 'Chỉ chủ beatmap hoặc người đề cử beatmap/thành viên của NAT mới có thể đăng ghi chú.',
],
'vote' => [
'bot' => "Không thể bầu trên thảo luận tạo bởi bot",
'limit_exceeded' => 'Vui lòng đợi một lúc trước khi bình chọn thêm',
'owner' => "Không thể bình chọn cuộc thảo luận của bạn.",
'wrong_beatmapset_state' => 'Chỉ có thể bình chọn cuộc thảo luận của beatmap ở trạng thái pending.',
],
],
'beatmap_discussion_post' => [
'destroy' => [
'not_owner' => 'Bạn chỉ có thể xóa bài đăng của chính mình.',
'resolved' => 'Bạn không thể xoá một bài đăng về một thảo luận đã được giải quyết.',
'system_generated' => 'Không thể xóa bài đăng được tạo tự động.',
],
'edit' => [
'not_owner' => 'Bài đăng chỉ có thể được chỉnh sửa bởi người đăng.',
'resolved' => 'Bạn không thể sửa một bài đăng về một thảo luận đã được giải quyết.',
'system_generated' => 'Không thể chỉnh sửa bài đăng được tạo tự động.',
],
'store' => [
'beatmapset_locked' => 'Thảo luận bị khóa cho beatmap này.',
],
],
'beatmapset' => [
'metadata' => [
'nominated' => 'Bạn không thể thay đổi metadata của map đã được nominated. Liên hệ với một BN hoặc NAT nếu bạn thấy metadata bị sai.',
],
],
'chat' => [
'blocked' => 'Không thể nhắn tin cho người dùng đã chặn bạn hoặc nếu bạn đã chặn người đó.',
'friends_only' => 'Người dùng này đang chặn tin nhắn từ những người không trong danh sách bạn của họ.',
'moderated' => 'Kênh hiện đang được kiểm duyệt.',
'no_access' => 'Bạn không có quyền truy cập vào kênh này.',
'restricted' => 'Bạn không thể gửi tin nhắn trong khi bị silenced, bị hạn chế hoặc bị cấm (ban).',
'silenced' => 'Bạn không thể gửi tin nhắn khi bị tắt tiếng, bị hạn chế hoặc bị cấm.',
],
'comment' => [
'update' => [
'deleted' => "Không thể chỉnh sửa bài đăng đã bị xóa.",
],
],
'contest' => [
'voting_over' => 'Bạn không thể đổi phiếu bầu sau khi giai đoạn bầu chọn của cuộc thi này kết thúc.',
'entry' => [
'limit_reached' => 'Bạn đã đạt giới hạn bài dự thi cho cuộc thi này',
'over' => 'Cảm ơn về bài dự thi của bạn! Cuộc thi đã không còn nhận thêm mục nào nữa và sẽ sớm mở bình chọn.',
],
],
'forum' => [
'moderate' => [
'no_permission' => 'Bạn không có quyền chỉnh sửa forum này.',
],
'post' => [
'delete' => [
'only_last_post' => 'Chỉ có thể xóa bài đăng cuối cùng.',
'locked' => 'Không thể xóa bài đăng của một topic bị khóa.',
'no_forum_access' => 'Yêu cầu quyền truy cập vào forum mong muốn.',
'not_owner' => 'Chỉ người đăng mới có thể xóa bài đăng.',
],
'edit' => [
'deleted' => 'Không thể chỉnh sửa bài đăng đã bị xóa.',
'locked' => 'Bài đăng đã bị khóa chỉnh sửa.',
'no_forum_access' => 'Yêu cầu quyền truy cập vào forum mong muốn.',
'not_owner' => 'Chỉ có người đăng mới có thể chỉnh sửa bài đăng.',
'topic_locked' => 'Không thể chỉnh sửa bài đăng của một chủ đề bị khóa.',
],
'store' => [
'play_more' => 'Vui lòng thử chơi game này trước khi đăng bài lên diễn đàn! Nếu bạn gặp vấn đề khi chơi, Vui lòng đăng bài lên diễn đàn Trợ Giúp và Hỗ Trợ (Help and Support).',
'too_many_help_posts' => "Bạn cần phải chơi game này nhiều hơn trước khi bạn tạo thêm bài đăng. Nếu bạn vẫn còn gặp vấn đề khi chơi game, hãy gửi email tới địa chỉ support@ppy.sh", // FIXME: unhardcode email address.
],
],
'topic' => [
'reply' => [
'double_post' => 'Vui lòng chỉnh sửa bài đăng cuối cùng của bạn thay vì đăng thêm lần nữa.',
'locked' => 'Không thể trả lời một thread bị khóa.',
'no_forum_access' => 'Yêu cầu quyền truy cập vào forum mong muốn.',
'no_permission' => 'Không có quyền trả lời.',
'user' => [
'require_login' => 'Vui lòng đăng nhập để trả lời.',
'restricted' => "Không thể trả lời trong khi bị hạn chế.",
'silenced' => "Không thể trả lời trong khi bị im lặng.",
],
],
'store' => [
'no_forum_access' => 'Yêu cầu quyền truy cập vào forum mong muốn.',
'no_permission' => 'Không có quyền tạo topic mới.',
'forum_closed' => 'Forum này đã bị đóng và không thể đăng thêm bài.',
],
'vote' => [
'no_forum_access' => 'Yêu cầu quyền truy cập vào forum mong muốn.',
'over' => 'Đã kết thúc bỏ phiếu và không thể bình chọn nữa.',
'play_more' => 'Bạn cần chơi nhiều hơn trước khi bỏ phiếu trên diễn đàn.',
'voted' => 'Không cho phép đổi phiếu bầu.',
'user' => [
'require_login' => 'Vui lòng đăng nhập để bình chọn.',
'restricted' => "Không thể bình chọn trong khi bị hạn chế",
'silenced' => "Không thể bình chọn khi im lặng",
],
],
'watch' => [
'no_forum_access' => 'Yêu cầu quyền truy cập vào forum mong muốn.',
],
],
'topic_cover' => [
'edit' => [
'uneditable' => 'Ảnh bìa đã chỉ định không hợp lệ.',
'not_owner' => 'Chỉ có người đăng mới có thể chỉnh sửa ảnh bìa.',
],
'store' => [
'forum_not_allowed' => 'Forum này không chấp thuận topic cover.',
],
],
'view' => [
'admin_only' => 'Chỉ có admin mới có thể xem diễn đàn này.',
],
],
'user' => [
'page' => [
'edit' => [
'locked' => 'Trang người dùng này đã bị khóa.',
'not_owner' => 'Chỉ có thể chỉnh sửa trang người dùng của bạn.',
'require_supporter_tag' => 'phải có osu!supporter.',
],
],
],
];
| LiquidPL/osu-web | resources/lang/vi/authorization.php | PHP | agpl-3.0 | 8,941 |
/*
* Copyright (C) 2000 - 2012 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.admin.web;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.silverpeas.web.Exposable;
/**
* Web entity abstraction which provides the type of the entity
* @author Yohann Chastagnier
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class AbstractTypeEntity implements Exposable {
private static final long serialVersionUID = -5806451025306340551L;
@XmlElement(required = true, defaultValue = "")
private final String type;
protected AbstractTypeEntity(final String type) {
this.type = type;
}
public String getType() {
return type;
}
}
| NicolasEYSSERIC/Silverpeas-Core | web-core/src/main/java/org/silverpeas/admin/web/AbstractTypeEntity.java | Java | agpl-3.0 | 1,911 |
package net.contargo.iris.address.dto;
import net.contargo.iris.GeoLocation;
import net.contargo.iris.address.nominatim.service.OsmType;
import java.util.List;
import java.util.Map;
/**
* Delegates to AddressService and converts Address Beans into Address DTOs.
*
* @author Arnold Franke - franke@synyx.de
* @author Oliver Messner - messner@synyx.de
*/
public interface AddressDtoService {
/**
* Returns a {@link AddressDto} with information behind the given osmId.
*
* @param osmId search parameter
*
* @return The address for a certain osmId
*
* @deprecated use {@link #getAddressByOsmIdAndOsmType(long, OsmType)} instead
*/
@Deprecated
AddressDto getAddressByOsmId(long osmId);
/**
* Returns the OSM address associated with the specified OSM id and OSM type. Nominatim reverse geo-coding using an
* OSM Id requires an OSM type to be specified, which represents either a node, a way or a relation (see
* https://nominatim.org/release-docs/develop/api/Reverse/)
*
* @param osmId the OSM Id
* @param type the OSM type
*
* @return an address or {@code null}
*
* @see OsmType
*/
AddressDto getAddressByOsmIdAndOsmType(long osmId, OsmType type);
/**
* Wraps the given AddressDto as first element of an {@link AddressListDto} This is needed to provide a consistent
* format of returned Addresses for API-Clients.
*
* @param addressDto
*
* @return
*/
List<AddressListDto> wrapInListOfAddressLists(AddressDto addressDto);
/**
* Returns the corresponding {@link AddressDto} object from a given {@link GeoLocation}.
*
* @param location keeps the basis information for the {@link AddressDto} search.
*
* @return The address for the given {@link GeoLocation}.
*/
AddressDto getAddressForGeoLocation(GeoLocation location);
/**
* Resolves an address (described by the given parameters) to a {@link java.util.List} of
* {@link net.contargo.iris.address.Address} objects with the attributes name, latitude and longitude. Uses
* multiple fallback strategies to find addresses if not all parameters are provided
*
* @param addressDetails The parameters describing the addresses we are looking for
*
* @return A List of Address Lists
*/
List<AddressListDto> getAddressesByDetails(Map<String, String> addressDetails);
/**
* Resolves an address (described by the given parameters) to a {@link java.util.List} of
* {@link net.contargo.iris.address.Address} objects with the attributes name, latitude and longitude. Uses
* multiple fallback strategies to find addresses if not all parameters are provided
*
* @param addressDetails The parameters describing the addresses we are looking for
*
* @return A List of Addresses
*/
List<AddressDto> getAddressesByDetailsPlain(Map<String, String> addressDetails);
/**
* Returns all Addresses where the given place is in.
*
* @param placeId the OSM Place ID
*
* @return All addresses belonging to the OSM-Place defined by the OSM Place ID
*/
List<AddressDto> getAddressesWherePlaceIsIn(Long placeId);
/**
* Returns one {@link AddressDto} with the given hashKey.
*
* @param hashKey as search parameter
*
* @return the {@link AddressDto} with the given hashKey
*/
AddressDto getAddressesByHashKey(String hashKey);
/**
* Returns a list of addresses matching the query.
*
* @param query the address query
*
* @return a list of matching addresses
*/
List<AddressDto> getAddressesByQuery(String query);
}
| Contargo/iris | src/main/java/net/contargo/iris/address/dto/AddressDtoService.java | Java | agpl-3.0 | 3,782 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^pool/(?P<pk>[0-9a-zA-Z\/]+)/$', views.UserRedirectView.as_view(), name='pool'),
url(r'^pool/(?P<pk>[\d\w_]+)$', views.pool_fix, name='pool_fix'), #allow decimal and words only.
]
| agusmakmun/Some-Examples-of-Simple-Python-Script | Django/redirect/urls.py | Python | agpl-3.0 | 264 |
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import android.os.Parcel;
import com.google.gson.JsonObject;
import com.kaltura.client.Params;
import com.kaltura.client.utils.request.MultiRequestBuilder;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
@MultiRequestBuilder.Tokenizer(ESearchEntryNestedBaseItem.Tokenizer.class)
public abstract class ESearchEntryNestedBaseItem extends ESearchEntryBaseNestedObject {
public interface Tokenizer extends ESearchEntryBaseNestedObject.Tokenizer {
}
public ESearchEntryNestedBaseItem() {
super();
}
public ESearchEntryNestedBaseItem(JsonObject jsonObject) throws APIException {
super(jsonObject);
}
public Params toParams() {
Params kparams = super.toParams();
kparams.add("objectType", "KalturaESearchEntryNestedBaseItem");
return kparams;
}
public ESearchEntryNestedBaseItem(Parcel in) {
super(in);
}
}
| kaltura/KalturaGeneratedAPIClientsAndroid | KalturaClient/src/main/java/com/kaltura/client/types/ESearchEntryNestedBaseItem.java | Java | agpl-3.0 | 2,352 |