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 |
|---|---|---|---|---|---|
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "record".
*
* @property string $todaydetail
* @property string $st_classmark
* @property string $startday
* @property string $endday
* @property integer $totalday
* @property string $country
* @property string $countryEN
* @property string $st_name
* @property string $st_nameEN
* @property string $gaokaohao
* @property string $idcard
* @property string $sex
* @property string $st_year
* @property string $st_class
* @property string $academy
* @property string $major
* @property string $status
* @property string $model
* @property string $today
*/
class Record extends \yii\db\ActiveRecord
{
private static $_instance;
public static function getinstance()
{
if(!(self::$_instance instanceof self))
{
self::$_instance =new self();
}
return self::$_instance;
}
/**
* @inheritdoc
*/
public static function tableName()
{
return 'record';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['todaydetail', 'st_classmark'], 'required'],
[['idcard'],'string', 'length' =>18],
[['startday', 'endday'],'string', 'length' =>10],
[['totalday'], 'integer'],
[['todaydetail', 'model', 'today'], 'string', 'max' => 50],
[['st_classmark','refusereason','reason', 'country', 'countryEN', 'st_name', 'st_nameEN', 'gaokaohao', 'st_year', 'st_class', 'academy', 'major'], 'string', 'max' => 100],
[['sex', 'status'], 'string', 'max' => 20]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'todaydetail' => '时间编号',
'today' => '申请时间(点击可排序)',
'st_classmark' => '学号',
'refusereason' => '拒绝理由(若批审核不通过时填写)',
'reason' => '申请理由(必填 例具体缘由:医保证明)',
'startday' => '出发日期',
'endday' => '来校报到日期',
'totalday' => '出国总天数',
'country' => '目的国家(中文)',
'countryEN' => '目的国家(英文)',
'st_name' => '学生姓名',
'st_nameEN' => '英文名(中文姓名拼音)',
'gaokaohao' => '高考报名号(由学生处填写)',
'idcard' => '身份证',
'sex' => '性别(male/female)',
'st_year' => '入学年份',
'st_class' => '班级编号',
'academy' => '学院',
'major' => '专业',
'status' => '状态(点击可排序)',
'model' => '申请类型',
];
}
}
| Jirachiii/sues_print | models/Record.php | PHP | bsd-3-clause | 2,805 |
package com.michaelbaranov.microba.gradient;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import com.michaelbaranov.microba.common.AbstractBoundedTableModel;
/**
* A very basic implementation of {@link AbstractBoundedTableModel} used by
* default by {@link GradientBar}. This implementation has bounds 0 - 100 and
* is mutable.
*
* @author Michael Baranov
*
*/
public class DefaultGradientModel extends AbstractBoundedTableModel {
protected static final int POSITION_COLUMN = 0;
protected static final int COLOR_COLUMN = 1;
protected List positionList = new ArrayList(32);
protected List colorList = new ArrayList(32);
/**
* Constructor.
*/
public DefaultGradientModel() {
super();
positionList.add(new Integer(0));
colorList.add(Color.YELLOW);
positionList.add(new Integer(50));
colorList.add(Color.RED);
positionList.add(new Integer(100));
colorList.add(Color.GREEN);
}
public int getLowerBound() {
return 0;
}
public int getUpperBound() {
return 100;
}
public int getRowCount() {
return positionList.size();
}
public int getColumnCount() {
return 2;
}
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case POSITION_COLUMN:
return Integer.class;
case COLOR_COLUMN:
return Color.class;
}
return super.getColumnClass(columnIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case POSITION_COLUMN:
return positionList.get(rowIndex);
case COLOR_COLUMN:
return colorList.get(rowIndex);
}
return null;
}
/**
* Adds a color point.
*
* @param color
* @param position
*/
public void add(Color color, int position) {
colorList.add(color);
positionList.add(new Integer(position));
fireTableDataChanged();
}
/**
* Removes a color point at specified index.
*
* @param index
*/
public void remove(int index) {
colorList.remove(index);
positionList.remove(index);
fireTableDataChanged();
}
/**
* Removes all color points.
*/
public void clear() {
colorList.clear();
positionList.clear();
fireTableDataChanged();
}
}
| ezegarra/microbrowser | microba/com/michaelbaranov/microba/gradient/DefaultGradientModel.java | Java | bsd-3-clause | 2,149 |
/* Scala.js runtime support
* Copyright 2013 LAMP/EPFL
* Author: Sébastien Doeraene
*/
/* ---------------------------------- *
* The top-level Scala.js environment *
* ---------------------------------- */
//!if outputMode == ECMAScript51Global
var ScalaJS = {};
//!endif
// Get the environment info
ScalaJS.env = (typeof __ScalaJSEnv === "object" && __ScalaJSEnv) ? __ScalaJSEnv : {};
// Global scope
ScalaJS.g =
(typeof ScalaJS.env["global"] === "object" && ScalaJS.env["global"])
? ScalaJS.env["global"]
: ((typeof global === "object" && global && global["Object"] === Object) ? global : this);
ScalaJS.env["global"] = ScalaJS.g;
// Where to send exports
//!if moduleKind == CommonJSModule
ScalaJS.e = exports;
//!else
ScalaJS.e =
(typeof ScalaJS.env["exportsNamespace"] === "object" && ScalaJS.env["exportsNamespace"])
? ScalaJS.env["exportsNamespace"] : ScalaJS.g;
//!endif
ScalaJS.env["exportsNamespace"] = ScalaJS.e;
// Freeze the environment info
ScalaJS.g["Object"]["freeze"](ScalaJS.env);
// Linking info - must be in sync with scala.scalajs.runtime.LinkingInfo
ScalaJS.linkingInfo = {
"envInfo": ScalaJS.env,
"semantics": {
//!if asInstanceOfs == Compliant
"asInstanceOfs": 0,
//!else
//!if asInstanceOfs == Fatal
"asInstanceOfs": 1,
//!else
"asInstanceOfs": 2,
//!endif
//!endif
//!if arrayIndexOutOfBounds == Compliant
"arrayIndexOutOfBounds": 0,
//!else
//!if arrayIndexOutOfBounds == Fatal
"arrayIndexOutOfBounds": 1,
//!else
"arrayIndexOutOfBounds": 2,
//!endif
//!endif
//!if moduleInit == Compliant
"moduleInit": 0,
//!else
//!if moduleInit == Fatal
"moduleInit": 1,
//!else
"moduleInit": 2,
//!endif
//!endif
//!if floats == Strict
"strictFloats": true,
//!else
"strictFloats": false,
//!endif
//!if productionMode == true
"productionMode": true
//!else
"productionMode": false
//!endif
},
//!if outputMode == ECMAScript6
"assumingES6": true,
//!else
"assumingES6": false,
//!endif
"linkerVersion": "{{LINKER_VERSION}}"
};
ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo);
ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo["semantics"]);
// Snapshots of builtins and polyfills
//!if outputMode == ECMAScript6
ScalaJS.imul = ScalaJS.g["Math"]["imul"];
ScalaJS.fround = ScalaJS.g["Math"]["fround"];
ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"];
//!else
ScalaJS.imul = ScalaJS.g["Math"]["imul"] || (function(a, b) {
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
const ah = (a >>> 16) & 0xffff;
const al = a & 0xffff;
const bh = (b >>> 16) & 0xffff;
const bl = b & 0xffff;
// the shift by 0 fixes the sign on the high part
// the final |0 converts the unsigned value into a signed value
return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
});
ScalaJS.fround = ScalaJS.g["Math"]["fround"] ||
//!if floats == Strict
(ScalaJS.g["Float32Array"] ? (function(v) {
const array = new ScalaJS.g["Float32Array"](1);
array[0] = v;
return array[0];
}) : (function(v) {
return ScalaJS.m.sjsr_package$().froundPolyfill__D__D(+v);
}));
//!else
(function(v) {
return +v;
});
//!endif
ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"] || (function(i) {
// See Hacker's Delight, Section 5-3
if (i === 0) return 32;
let r = 1;
if ((i & 0xffff0000) === 0) { i <<= 16; r += 16; };
if ((i & 0xff000000) === 0) { i <<= 8; r += 8; };
if ((i & 0xf0000000) === 0) { i <<= 4; r += 4; };
if ((i & 0xc0000000) === 0) { i <<= 2; r += 2; };
return r + (i >> 31);
});
//!endif
// Other fields
//!if outputMode == ECMAScript51Global
ScalaJS.d = {}; // Data for types
ScalaJS.a = {}; // Scala.js-defined JS class value accessors
ScalaJS.b = {}; // Scala.js-defined JS class value fields
ScalaJS.c = {}; // Scala.js constructors
ScalaJS.h = {}; // Inheritable constructors (without initialization code)
ScalaJS.s = {}; // Static methods
ScalaJS.t = {}; // Static fields
ScalaJS.f = {}; // Default methods
ScalaJS.n = {}; // Module instances
ScalaJS.m = {}; // Module accessors
ScalaJS.is = {}; // isInstanceOf methods
ScalaJS.isArrayOf = {}; // isInstanceOfArrayOf methods
//!if asInstanceOfs != Unchecked
ScalaJS.as = {}; // asInstanceOf methods
ScalaJS.asArrayOf = {}; // asInstanceOfArrayOf methods
//!endif
ScalaJS.lastIDHash = 0; // last value attributed to an id hash code
ScalaJS.idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null;
//!else
let $lastIDHash = 0; // last value attributed to an id hash code
//!if outputMode == ECMAScript6
const $idHashCodeMap = new ScalaJS.g["WeakMap"]();
//!else
const $idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null;
//!endif
//!endif
// Core mechanism
ScalaJS.makeIsArrayOfPrimitive = function(primitiveData) {
return function(obj, depth) {
return !!(obj && obj.$classData &&
(obj.$classData.arrayDepth === depth) &&
(obj.$classData.arrayBase === primitiveData));
}
};
//!if asInstanceOfs != Unchecked
ScalaJS.makeAsArrayOfPrimitive = function(isInstanceOfFunction, arrayEncodedName) {
return function(obj, depth) {
if (isInstanceOfFunction(obj, depth) || (obj === null))
return obj;
else
ScalaJS.throwArrayCastException(obj, arrayEncodedName, depth);
}
};
//!endif
/** Encode a property name for runtime manipulation
* Usage:
* env.propertyName({someProp:0})
* Returns:
* "someProp"
* Useful when the property is renamed by a global optimizer (like Closure)
* but we must still get hold of a string of that name for runtime
* reflection.
*/
ScalaJS.propertyName = function(obj) {
for (const prop in obj)
return prop;
};
// Runtime functions
ScalaJS.isScalaJSObject = function(obj) {
return !!(obj && obj.$classData);
};
//!if asInstanceOfs != Unchecked
ScalaJS.throwClassCastException = function(instance, classFullName) {
//!if asInstanceOfs == Compliant
throw new ScalaJS.c.jl_ClassCastException().init___T(
instance + " is not an instance of " + classFullName);
//!else
throw new ScalaJS.c.sjsr_UndefinedBehaviorError().init___jl_Throwable(
new ScalaJS.c.jl_ClassCastException().init___T(
instance + " is not an instance of " + classFullName));
//!endif
};
ScalaJS.throwArrayCastException = function(instance, classArrayEncodedName, depth) {
for (; depth; --depth)
classArrayEncodedName = "[" + classArrayEncodedName;
ScalaJS.throwClassCastException(instance, classArrayEncodedName);
};
//!endif
//!if arrayIndexOutOfBounds != Unchecked
ScalaJS.throwArrayIndexOutOfBoundsException = function(i) {
const msg = (i === null) ? null : ("" + i);
//!if arrayIndexOutOfBounds == Compliant
throw new ScalaJS.c.jl_ArrayIndexOutOfBoundsException().init___T(msg);
//!else
throw new ScalaJS.c.sjsr_UndefinedBehaviorError().init___jl_Throwable(
new ScalaJS.c.jl_ArrayIndexOutOfBoundsException().init___T(msg));
//!endif
};
//!endif
ScalaJS.noIsInstance = function(instance) {
throw new ScalaJS.g["TypeError"](
"Cannot call isInstance() on a Class representing a raw JS trait/object");
};
ScalaJS.makeNativeArrayWrapper = function(arrayClassData, nativeArray) {
return new arrayClassData.constr(nativeArray);
};
ScalaJS.newArrayObject = function(arrayClassData, lengths) {
return ScalaJS.newArrayObjectInternal(arrayClassData, lengths, 0);
};
ScalaJS.newArrayObjectInternal = function(arrayClassData, lengths, lengthIndex) {
const result = new arrayClassData.constr(lengths[lengthIndex]);
if (lengthIndex < lengths.length-1) {
const subArrayClassData = arrayClassData.componentData;
const subLengthIndex = lengthIndex+1;
const underlying = result.u;
for (let i = 0; i < underlying.length; i++) {
underlying[i] = ScalaJS.newArrayObjectInternal(
subArrayClassData, lengths, subLengthIndex);
}
}
return result;
};
ScalaJS.objectToString = function(instance) {
if (instance === void 0)
return "undefined";
else
return instance.toString();
};
ScalaJS.objectGetClass = function(instance) {
switch (typeof instance) {
case "string":
return ScalaJS.d.T.getClassOf();
case "number": {
const v = instance | 0;
if (v === instance) { // is the value integral?
if (ScalaJS.isByte(v))
return ScalaJS.d.jl_Byte.getClassOf();
else if (ScalaJS.isShort(v))
return ScalaJS.d.jl_Short.getClassOf();
else
return ScalaJS.d.jl_Integer.getClassOf();
} else {
if (ScalaJS.isFloat(instance))
return ScalaJS.d.jl_Float.getClassOf();
else
return ScalaJS.d.jl_Double.getClassOf();
}
}
case "boolean":
return ScalaJS.d.jl_Boolean.getClassOf();
case "undefined":
return ScalaJS.d.sr_BoxedUnit.getClassOf();
default:
if (instance === null)
return instance.getClass__jl_Class();
else if (ScalaJS.is.sjsr_RuntimeLong(instance))
return ScalaJS.d.jl_Long.getClassOf();
else if (ScalaJS.isScalaJSObject(instance))
return instance.$classData.getClassOf();
else
return null; // Exception?
}
};
ScalaJS.objectClone = function(instance) {
if (ScalaJS.isScalaJSObject(instance) || (instance === null))
return instance.clone__O();
else
throw new ScalaJS.c.jl_CloneNotSupportedException().init___();
};
ScalaJS.objectNotify = function(instance) {
// final and no-op in java.lang.Object
if (instance === null)
instance.notify__V();
};
ScalaJS.objectNotifyAll = function(instance) {
// final and no-op in java.lang.Object
if (instance === null)
instance.notifyAll__V();
};
ScalaJS.objectFinalize = function(instance) {
if (ScalaJS.isScalaJSObject(instance) || (instance === null))
instance.finalize__V();
// else no-op
};
ScalaJS.objectEquals = function(instance, rhs) {
if (ScalaJS.isScalaJSObject(instance) || (instance === null))
return instance.equals__O__Z(rhs);
else if (typeof instance === "number")
return typeof rhs === "number" && ScalaJS.numberEquals(instance, rhs);
else
return instance === rhs;
};
ScalaJS.numberEquals = function(lhs, rhs) {
return (lhs === rhs) ? (
// 0.0.equals(-0.0) must be false
lhs !== 0 || 1/lhs === 1/rhs
) : (
// are they both NaN?
(lhs !== lhs) && (rhs !== rhs)
);
};
ScalaJS.objectHashCode = function(instance) {
switch (typeof instance) {
case "string":
return ScalaJS.m.sjsr_RuntimeString$().hashCode__T__I(instance);
case "number":
return ScalaJS.m.sjsr_Bits$().numberHashCode__D__I(instance);
case "boolean":
return instance ? 1231 : 1237;
case "undefined":
return 0;
default:
if (ScalaJS.isScalaJSObject(instance) || instance === null)
return instance.hashCode__I();
//!if outputMode != ECMAScript6
else if (ScalaJS.idHashCodeMap === null)
return 42;
//!endif
else
return ScalaJS.systemIdentityHashCode(instance);
}
};
ScalaJS.comparableCompareTo = function(instance, rhs) {
switch (typeof instance) {
case "string":
//!if asInstanceOfs != Unchecked
ScalaJS.as.T(rhs);
//!endif
return instance === rhs ? 0 : (instance < rhs ? -1 : 1);
case "number":
//!if asInstanceOfs != Unchecked
ScalaJS.as.jl_Number(rhs);
//!endif
return ScalaJS.m.jl_Double$().compare__D__D__I(instance, rhs);
case "boolean":
//!if asInstanceOfs != Unchecked
ScalaJS.asBoolean(rhs);
//!endif
return instance - rhs; // yes, this gives the right result
default:
return instance.compareTo__O__I(rhs);
}
};
ScalaJS.charSequenceLength = function(instance) {
if (typeof(instance) === "string")
//!if asInstanceOfs != Unchecked
return ScalaJS.uI(instance["length"]);
//!else
return instance["length"] | 0;
//!endif
else
return instance.length__I();
};
ScalaJS.charSequenceCharAt = function(instance, index) {
if (typeof(instance) === "string")
//!if asInstanceOfs != Unchecked
return ScalaJS.uI(instance["charCodeAt"](index)) & 0xffff;
//!else
return instance["charCodeAt"](index) & 0xffff;
//!endif
else
return instance.charAt__I__C(index);
};
ScalaJS.charSequenceSubSequence = function(instance, start, end) {
if (typeof(instance) === "string")
//!if asInstanceOfs != Unchecked
return ScalaJS.as.T(instance["substring"](start, end));
//!else
return instance["substring"](start, end);
//!endif
else
return instance.subSequence__I__I__jl_CharSequence(start, end);
};
ScalaJS.booleanBooleanValue = function(instance) {
if (typeof instance === "boolean") return instance;
else return instance.booleanValue__Z();
};
ScalaJS.numberByteValue = function(instance) {
if (typeof instance === "number") return (instance << 24) >> 24;
else return instance.byteValue__B();
};
ScalaJS.numberShortValue = function(instance) {
if (typeof instance === "number") return (instance << 16) >> 16;
else return instance.shortValue__S();
};
ScalaJS.numberIntValue = function(instance) {
if (typeof instance === "number") return instance | 0;
else return instance.intValue__I();
};
ScalaJS.numberLongValue = function(instance) {
if (typeof instance === "number")
return ScalaJS.m.sjsr_RuntimeLong$().fromDouble__D__sjsr_RuntimeLong(instance);
else
return instance.longValue__J();
};
ScalaJS.numberFloatValue = function(instance) {
if (typeof instance === "number") return ScalaJS.fround(instance);
else return instance.floatValue__F();
};
ScalaJS.numberDoubleValue = function(instance) {
if (typeof instance === "number") return instance;
else return instance.doubleValue__D();
};
ScalaJS.isNaN = function(instance) {
return instance !== instance;
};
ScalaJS.isInfinite = function(instance) {
return !ScalaJS.g["isFinite"](instance) && !ScalaJS.isNaN(instance);
};
ScalaJS.doubleToInt = function(x) {
return (x > 2147483647) ? (2147483647) : ((x < -2147483648) ? -2147483648 : (x | 0));
};
/** Instantiates a JS object with variadic arguments to the constructor. */
ScalaJS.newJSObjectWithVarargs = function(ctor, args) {
// This basically emulates the ECMAScript specification for 'new'.
const instance = ScalaJS.g["Object"]["create"](ctor.prototype);
const result = ctor["apply"](instance, args);
switch (typeof result) {
case "string": case "number": case "boolean": case "undefined": case "symbol":
return instance;
default:
return result === null ? instance : result;
}
};
ScalaJS.resolveSuperRef = function(initialProto, propName) {
const getPrototypeOf = ScalaJS.g["Object"]["getPrototypeOf"];
const getOwnPropertyDescriptor = ScalaJS.g["Object"]["getOwnPropertyDescriptor"];
let superProto = getPrototypeOf(initialProto);
while (superProto !== null) {
const desc = getOwnPropertyDescriptor(superProto, propName);
if (desc !== void 0)
return desc;
superProto = getPrototypeOf(superProto);
}
return void 0;
};
ScalaJS.superGet = function(initialProto, self, propName) {
const desc = ScalaJS.resolveSuperRef(initialProto, propName);
if (desc !== void 0) {
const getter = desc["get"];
if (getter !== void 0)
return getter["call"](self);
else
return desc["value"];
}
return void 0;
};
ScalaJS.superSet = function(initialProto, self, propName, value) {
const desc = ScalaJS.resolveSuperRef(initialProto, propName);
if (desc !== void 0) {
const setter = desc["set"];
if (setter !== void 0) {
setter["call"](self, value);
return void 0;
}
}
throw new ScalaJS.g["TypeError"]("super has no setter '" + propName + "'.");
};
//!if moduleKind == CommonJSModule
ScalaJS.moduleDefault = function(m) {
return (m && (typeof m === "object") && "default" in m) ? m["default"] : m;
};
//!endif
ScalaJS.propertiesOf = function(obj) {
const result = [];
for (const prop in obj)
result["push"](prop);
return result;
};
ScalaJS.systemArraycopy = function(src, srcPos, dest, destPos, length) {
const srcu = src.u;
const destu = dest.u;
//!if arrayIndexOutOfBounds != Unchecked
if (srcPos < 0 || destPos < 0 || length < 0 ||
(srcPos > ((srcu.length - length) | 0)) ||
(destPos > ((destu.length - length) | 0))) {
ScalaJS.throwArrayIndexOutOfBoundsException(null);
}
//!endif
if (srcu !== destu || destPos < srcPos || (((srcPos + length) | 0) < destPos)) {
for (let i = 0; i < length; i = (i + 1) | 0)
destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0];
} else {
for (let i = (length - 1) | 0; i >= 0; i = (i - 1) | 0)
destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0];
}
};
ScalaJS.systemIdentityHashCode =
//!if outputMode != ECMAScript6
(ScalaJS.idHashCodeMap !== null) ?
//!endif
(function(obj) {
switch (typeof obj) {
case "string": case "number": case "boolean": case "undefined":
return ScalaJS.objectHashCode(obj);
default:
if (obj === null) {
return 0;
} else {
let hash = ScalaJS.idHashCodeMap["get"](obj);
if (hash === void 0) {
hash = (ScalaJS.lastIDHash + 1) | 0;
ScalaJS.lastIDHash = hash;
ScalaJS.idHashCodeMap["set"](obj, hash);
}
return hash;
}
}
//!if outputMode != ECMAScript6
}) :
(function(obj) {
if (ScalaJS.isScalaJSObject(obj)) {
let hash = obj["$idHashCode$0"];
if (hash !== void 0) {
return hash;
} else if (!ScalaJS.g["Object"]["isSealed"](obj)) {
hash = (ScalaJS.lastIDHash + 1) | 0;
ScalaJS.lastIDHash = hash;
obj["$idHashCode$0"] = hash;
return hash;
} else {
return 42;
}
} else if (obj === null) {
return 0;
} else {
return ScalaJS.objectHashCode(obj);
}
//!endif
});
// is/as for hijacked boxed classes (the non-trivial ones)
ScalaJS.isByte = function(v) {
return (v << 24 >> 24) === v && 1/v !== 1/-0;
};
ScalaJS.isShort = function(v) {
return (v << 16 >> 16) === v && 1/v !== 1/-0;
};
ScalaJS.isInt = function(v) {
return (v | 0) === v && 1/v !== 1/-0;
};
ScalaJS.isFloat = function(v) {
//!if floats == Strict
return v !== v || ScalaJS.fround(v) === v;
//!else
return typeof v === "number";
//!endif
};
//!if asInstanceOfs != Unchecked
ScalaJS.asUnit = function(v) {
if (v === void 0 || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "scala.runtime.BoxedUnit");
};
ScalaJS.asBoolean = function(v) {
if (typeof v === "boolean" || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Boolean");
};
ScalaJS.asByte = function(v) {
if (ScalaJS.isByte(v) || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Byte");
};
ScalaJS.asShort = function(v) {
if (ScalaJS.isShort(v) || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Short");
};
ScalaJS.asInt = function(v) {
if (ScalaJS.isInt(v) || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Integer");
};
ScalaJS.asFloat = function(v) {
if (ScalaJS.isFloat(v) || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Float");
};
ScalaJS.asDouble = function(v) {
if (typeof v === "number" || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Double");
};
//!endif
// Unboxes
//!if asInstanceOfs != Unchecked
ScalaJS.uZ = function(value) {
return !!ScalaJS.asBoolean(value);
};
ScalaJS.uB = function(value) {
return ScalaJS.asByte(value) | 0;
};
ScalaJS.uS = function(value) {
return ScalaJS.asShort(value) | 0;
};
ScalaJS.uI = function(value) {
return ScalaJS.asInt(value) | 0;
};
ScalaJS.uJ = function(value) {
return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1
: ScalaJS.as.sjsr_RuntimeLong(value);
};
ScalaJS.uF = function(value) {
/* Here, it is fine to use + instead of fround, because asFloat already
* ensures that the result is either null or a float.
*/
return +ScalaJS.asFloat(value);
};
ScalaJS.uD = function(value) {
return +ScalaJS.asDouble(value);
};
//!else
ScalaJS.uJ = function(value) {
return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : value;
};
//!endif
// TypeArray conversions
ScalaJS.byteArray2TypedArray = function(value) { return new ScalaJS.g["Int8Array"](value.u); };
ScalaJS.shortArray2TypedArray = function(value) { return new ScalaJS.g["Int16Array"](value.u); };
ScalaJS.charArray2TypedArray = function(value) { return new ScalaJS.g["Uint16Array"](value.u); };
ScalaJS.intArray2TypedArray = function(value) { return new ScalaJS.g["Int32Array"](value.u); };
ScalaJS.floatArray2TypedArray = function(value) { return new ScalaJS.g["Float32Array"](value.u); };
ScalaJS.doubleArray2TypedArray = function(value) { return new ScalaJS.g["Float64Array"](value.u); };
ScalaJS.typedArray2ByteArray = function(value) {
const arrayClassData = ScalaJS.d.B.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Int8Array"](value));
};
ScalaJS.typedArray2ShortArray = function(value) {
const arrayClassData = ScalaJS.d.S.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Int16Array"](value));
};
ScalaJS.typedArray2CharArray = function(value) {
const arrayClassData = ScalaJS.d.C.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Uint16Array"](value));
};
ScalaJS.typedArray2IntArray = function(value) {
const arrayClassData = ScalaJS.d.I.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Int32Array"](value));
};
ScalaJS.typedArray2FloatArray = function(value) {
const arrayClassData = ScalaJS.d.F.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Float32Array"](value));
};
ScalaJS.typedArray2DoubleArray = function(value) {
const arrayClassData = ScalaJS.d.D.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Float64Array"](value));
};
// TypeData class
//!if outputMode != ECMAScript6
/** @constructor */
ScalaJS.TypeData = function() {
//!else
class $TypeData {
constructor() {
//!endif
// Runtime support
this.constr = void 0;
this.parentData = void 0;
this.ancestors = null;
this.componentData = null;
this.arrayBase = null;
this.arrayDepth = 0;
this.zero = null;
this.arrayEncodedName = "";
this._classOf = void 0;
this._arrayOf = void 0;
this.isArrayOf = void 0;
// java.lang.Class support
this["name"] = "";
this["isPrimitive"] = false;
this["isInterface"] = false;
this["isArrayClass"] = false;
this["isRawJSType"] = false;
this["isInstance"] = void 0;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.initPrim = function(
//!else
initPrim(
//!endif
zero, arrayEncodedName, displayName) {
// Runtime support
this.ancestors = {};
this.componentData = null;
this.zero = zero;
this.arrayEncodedName = arrayEncodedName;
this.isArrayOf = function(obj, depth) { return false; };
// java.lang.Class support
this["name"] = displayName;
this["isPrimitive"] = true;
this["isInstance"] = function(obj) { return false; };
return this;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.initClass = function(
//!else
initClass(
//!endif
internalNameObj, isInterface, fullName,
ancestors, isRawJSType, parentData, isInstance, isArrayOf) {
const internalName = ScalaJS.propertyName(internalNameObj);
isInstance = isInstance || function(obj) {
return !!(obj && obj.$classData && obj.$classData.ancestors[internalName]);
};
isArrayOf = isArrayOf || function(obj, depth) {
return !!(obj && obj.$classData && (obj.$classData.arrayDepth === depth)
&& obj.$classData.arrayBase.ancestors[internalName])
};
// Runtime support
this.parentData = parentData;
this.ancestors = ancestors;
this.arrayEncodedName = "L"+fullName+";";
this.isArrayOf = isArrayOf;
// java.lang.Class support
this["name"] = fullName;
this["isInterface"] = isInterface;
this["isRawJSType"] = !!isRawJSType;
this["isInstance"] = isInstance;
return this;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.initArray = function(
//!else
initArray(
//!endif
componentData) {
// The constructor
const componentZero0 = componentData.zero;
// The zero for the Long runtime representation
// is a special case here, since the class has not
// been defined yet, when this file is read
const componentZero = (componentZero0 == "longZero")
? ScalaJS.m.sjsr_RuntimeLong$().Zero$1
: componentZero0;
//!if outputMode != ECMAScript6
/** @constructor */
const ArrayClass = function(arg) {
if (typeof(arg) === "number") {
// arg is the length of the array
this.u = new Array(arg);
for (let i = 0; i < arg; i++)
this.u[i] = componentZero;
} else {
// arg is a native array that we wrap
this.u = arg;
}
}
ArrayClass.prototype = new ScalaJS.h.O;
ArrayClass.prototype.constructor = ArrayClass;
//!if arrayIndexOutOfBounds != Unchecked
ArrayClass.prototype.get = function(i) {
if (i < 0 || i >= this.u.length)
ScalaJS.throwArrayIndexOutOfBoundsException(i);
return this.u[i];
};
ArrayClass.prototype.set = function(i, v) {
if (i < 0 || i >= this.u.length)
ScalaJS.throwArrayIndexOutOfBoundsException(i);
this.u[i] = v;
};
//!endif
ArrayClass.prototype.clone__O = function() {
if (this.u instanceof Array)
return new ArrayClass(this.u["slice"](0));
else
// The underlying Array is a TypedArray
return new ArrayClass(new this.u.constructor(this.u));
};
//!else
class ArrayClass extends ScalaJS.c.O {
constructor(arg) {
super();
if (typeof(arg) === "number") {
// arg is the length of the array
this.u = new Array(arg);
for (let i = 0; i < arg; i++)
this.u[i] = componentZero;
} else {
// arg is a native array that we wrap
this.u = arg;
}
};
//!if arrayIndexOutOfBounds != Unchecked
get(i) {
if (i < 0 || i >= this.u.length)
ScalaJS.throwArrayIndexOutOfBoundsException(i);
return this.u[i];
};
set(i, v) {
if (i < 0 || i >= this.u.length)
ScalaJS.throwArrayIndexOutOfBoundsException(i);
this.u[i] = v;
};
//!endif
clone__O() {
if (this.u instanceof Array)
return new ArrayClass(this.u["slice"](0));
else
// The underlying Array is a TypedArray
return new ArrayClass(new this.u.constructor(this.u));
};
};
//!endif
ArrayClass.prototype.$classData = this;
// Don't generate reflective call proxies. The compiler special cases
// reflective calls to methods on scala.Array
// The data
const encodedName = "[" + componentData.arrayEncodedName;
const componentBase = componentData.arrayBase || componentData;
const arrayDepth = componentData.arrayDepth + 1;
const isInstance = function(obj) {
return componentBase.isArrayOf(obj, arrayDepth);
}
// Runtime support
this.constr = ArrayClass;
this.parentData = ScalaJS.d.O;
this.ancestors = {O: 1, jl_Cloneable: 1, Ljava_io_Serializable: 1};
this.componentData = componentData;
this.arrayBase = componentBase;
this.arrayDepth = arrayDepth;
this.zero = null;
this.arrayEncodedName = encodedName;
this._classOf = undefined;
this._arrayOf = undefined;
this.isArrayOf = undefined;
// java.lang.Class support
this["name"] = encodedName;
this["isPrimitive"] = false;
this["isInterface"] = false;
this["isArrayClass"] = true;
this["isInstance"] = isInstance;
return this;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.getClassOf = function() {
//!else
getClassOf() {
//!endif
if (!this._classOf)
this._classOf = new ScalaJS.c.jl_Class().init___jl_ScalaJSClassData(this);
return this._classOf;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.getArrayOf = function() {
//!else
getArrayOf() {
//!endif
if (!this._arrayOf)
this._arrayOf = new ScalaJS.TypeData().initArray(this);
return this._arrayOf;
};
// java.lang.Class support
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype["getFakeInstance"] = function() {
//!else
"getFakeInstance"() {
//!endif
if (this === ScalaJS.d.T)
return "some string";
else if (this === ScalaJS.d.jl_Boolean)
return false;
else if (this === ScalaJS.d.jl_Byte ||
this === ScalaJS.d.jl_Short ||
this === ScalaJS.d.jl_Integer ||
this === ScalaJS.d.jl_Float ||
this === ScalaJS.d.jl_Double)
return 0;
else if (this === ScalaJS.d.jl_Long)
return ScalaJS.m.sjsr_RuntimeLong$().Zero$1;
else if (this === ScalaJS.d.sr_BoxedUnit)
return void 0;
else
return {$classData: this};
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype["getSuperclass"] = function() {
//!else
"getSuperclass"() {
//!endif
return this.parentData ? this.parentData.getClassOf() : null;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype["getComponentType"] = function() {
//!else
"getComponentType"() {
//!endif
return this.componentData ? this.componentData.getClassOf() : null;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype["newArrayOfThisClass"] = function(lengths) {
//!else
"newArrayOfThisClass"(lengths) {
//!endif
let arrayClassData = this;
for (let i = 0; i < lengths.length; i++)
arrayClassData = arrayClassData.getArrayOf();
return ScalaJS.newArrayObject(arrayClassData, lengths);
};
//!if outputMode == ECMAScript6
};
//!endif
// Create primitive types
ScalaJS.d.V = new ScalaJS.TypeData().initPrim(undefined, "V", "void");
ScalaJS.d.Z = new ScalaJS.TypeData().initPrim(false, "Z", "boolean");
ScalaJS.d.C = new ScalaJS.TypeData().initPrim(0, "C", "char");
ScalaJS.d.B = new ScalaJS.TypeData().initPrim(0, "B", "byte");
ScalaJS.d.S = new ScalaJS.TypeData().initPrim(0, "S", "short");
ScalaJS.d.I = new ScalaJS.TypeData().initPrim(0, "I", "int");
ScalaJS.d.J = new ScalaJS.TypeData().initPrim("longZero", "J", "long");
ScalaJS.d.F = new ScalaJS.TypeData().initPrim(0.0, "F", "float");
ScalaJS.d.D = new ScalaJS.TypeData().initPrim(0.0, "D", "double");
// Instance tests for array of primitives
ScalaJS.isArrayOf.Z = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.Z);
ScalaJS.d.Z.isArrayOf = ScalaJS.isArrayOf.Z;
ScalaJS.isArrayOf.C = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.C);
ScalaJS.d.C.isArrayOf = ScalaJS.isArrayOf.C;
ScalaJS.isArrayOf.B = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.B);
ScalaJS.d.B.isArrayOf = ScalaJS.isArrayOf.B;
ScalaJS.isArrayOf.S = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.S);
ScalaJS.d.S.isArrayOf = ScalaJS.isArrayOf.S;
ScalaJS.isArrayOf.I = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.I);
ScalaJS.d.I.isArrayOf = ScalaJS.isArrayOf.I;
ScalaJS.isArrayOf.J = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.J);
ScalaJS.d.J.isArrayOf = ScalaJS.isArrayOf.J;
ScalaJS.isArrayOf.F = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.F);
ScalaJS.d.F.isArrayOf = ScalaJS.isArrayOf.F;
ScalaJS.isArrayOf.D = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.D);
ScalaJS.d.D.isArrayOf = ScalaJS.isArrayOf.D;
//!if asInstanceOfs != Unchecked
// asInstanceOfs for array of primitives
ScalaJS.asArrayOf.Z = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.Z, "Z");
ScalaJS.asArrayOf.C = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.C, "C");
ScalaJS.asArrayOf.B = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.B, "B");
ScalaJS.asArrayOf.S = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.S, "S");
ScalaJS.asArrayOf.I = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.I, "I");
ScalaJS.asArrayOf.J = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.J, "J");
ScalaJS.asArrayOf.F = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.F, "F");
ScalaJS.asArrayOf.D = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.D, "D");
//!endif
| xuwei-k/scala-js | tools/scalajsenv.js | JavaScript | bsd-3-clause | 32,145 |
package com.percolate.sdk.dto;
import com.fasterxml.jackson.annotation.*;
import com.percolate.sdk.interfaces.HasExtraFields;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FacebookConversationMessage implements Serializable, HasExtraFields {
private static final long serialVersionUID = -7978616001157824820L;
@JsonIgnore
public List<FacebookConversationMessage> extraMessages = new ArrayList<>(); // Set by client to group messages happening around the same time
@JsonIgnore
public String stickerUrl; //Set by client. If message is empty, ApiGetFacebookMessage is used to check for images/stickers.
@JsonIgnore
public List<FacebookMessageAttachment> attachments; //Set by client after calling ApiGetFacebookMessage.
@JsonIgnore
public Flag flag; //Set by client after calling ApiGetFlags
@JsonProperty("id")
protected String id;
@JsonProperty("conversation_id")
protected String conversationId;
@JsonProperty("from")
protected FacebookUser from;
// ApiGetFacebookConversations API returns "from"
// ApiGetFlag API returns "from_user"
// The setter method for this value sets <code>from</code> field.
@JsonProperty("from_user")
protected FacebookUser tempFromUser;
@JsonProperty("created_at")
protected String createdAt;
@JsonProperty("has_attachments")
protected Boolean hasAttachments;
@JsonProperty("message")
protected String message;
@JsonIgnore
protected Map<String, Object> extraFields = new HashMap<>();
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getConversationId() {
return conversationId;
}
public void setConversationId(String conversationId) {
this.conversationId = conversationId;
}
public FacebookUser getFrom() {
return from;
}
public void setFrom(FacebookUser from) {
this.from = from;
}
public void setTempFromUser(FacebookUser from) {
this.tempFromUser = from;
this.from = from;
}
public FacebookUser getTempFromUser() {
return tempFromUser;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public Boolean getHasAttachments() {
return hasAttachments;
}
public void setHasAttachments(Boolean hasAttachments) {
this.hasAttachments = hasAttachments;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public Map<String, Object> getExtraFields() {
if(extraFields == null) {
extraFields = new HashMap<>();
}
return extraFields;
}
@Override
@JsonAnySetter
public void putExtraField(String key, Object value) {
getExtraFields().put(key, value);
}
}
| percolate/percolate-java-sdk | core/src/main/java/com/percolate/sdk/dto/FacebookConversationMessage.java | Java | bsd-3-clause | 3,496 |
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\helpers\ArrayHelper;
use backend\modules\qtn\models\Survey;
/* @var $this yii\web\View */
/* @var $searchModel backend\modules\qtn\Models\SurveySearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Qtn Surveys';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="qtn-survey-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Qtn Survey', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'showPageSummary'=>true,
'pjax'=>true,
'striped'=>true,
'hover'=>true,
'panel'=>['type'=>'primary', 'heading'=>'Grid Grouping Example'],
'columns' => [
['class'=>'kartik\grid\SerialColumn'],
[
'attribute'=>'id',
'format' => 'raw',
'width'=>'310px',
'value'=>function ($model, $key, $index, $widget) {
$txt= $model->surveyTab->survey->name;
if($model->surveyTab->survey->status==0){
$txt .= ' '.Html::a('<span class=" glyphicon glyphicon-pencil"></span>',[ 'survey/update?id=' . $model->surveyTab->survey_id]);
}
$txt .= '___' .Html::a('<span class="glyphicon glyphicon-list-alt"></span>',[ 'survey/view?id=' .$model->surveyTab->survey_id]);
return $txt;
},
'filterInputOptions'=>['placeholder'=>'Any supplier'],
'group'=>true, // enable grouping,
'groupedRow'=>true, // move grouped column to a single grouped row
'groupOddCssClass'=>'kv-grouped-row', // configure odd group cell css class
'groupEvenCssClass'=>'kv-grouped-row', // configure even group cell css class
],
[
'attribute'=>'survey_tab_id',
'width'=>'310px',
'value'=>function ($model, $key, $index, $widget) {
return $model->surveyTab->name;
},
'group'=>true,
],
[
'attribute'=>'name',
'format' => 'raw',
'value'=>function ($data) {
$txt= $data->name;
if($data->surveyTab->survey->status==0){
$txt .= ' '.Html::a('คำถาม',[ 'survey/question?id=' . $data->surveyTab->survey_id]);
//$txt .=Html::a('table',[ 'survey/choice-title?id=' . $data->id]);
}
return $txt;
},
],
],
]); ?>
</div>
| yuttapong/webapp | backend/modules/qtn/views/survey/index.php | PHP | bsd-3-clause | 2,807 |
Bool_t SetGeneratedSmearingHistos = kFALSE;
Bool_t GetCentralityFromAlien = kFALSE;
std::string centralityFilename = "";
std::string centralityFilenameFromAlien = "/alice/cern.ch/user/a/acapon/.root";
const Int_t triggerNames = AliVEvent::kINT7;
const Int_t nMCSignal = 0;
const Int_t nCutsetting = 0;
const Double_t minGenPt = 0.05;
const Double_t maxGenPt = 20;
const Double_t minGenEta = -1.5;
const Double_t maxGenEta = 1.5;
const Double_t minPtCut = 0.2;
const Double_t maxPtCut = 15.0;
const Double_t minEtaCut = -0.8;
const Double_t maxEtaCut = 0.8;
// const Double_t minPtCut = 0.2;
// const Double_t maxPtCut = 8.0;
// const Double_t minEtaCut = -0.8;
// const Double_t maxEtaCut = 0.8;
// binning of single leg histograms
Bool_t usePtVector = kTRUE;
Double_t ptBins[] = {0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,
0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85,
0.90,0.95,1.00,1.10,1.20,1.30,1.40,1.50,1.60,
1.70,1.80,1.90,2.00,2.10,2.30,2.50,3.00,3.50,
4.00,5.00,6.00,7.00,8.00,10.0,15.0};
const Int_t nBinsPt = ( sizeof(ptBins) / sizeof(ptBins[0]) )-1;
const Double_t minPtBin = 0;
const Double_t maxPtBin = 20;
const Int_t stepsPtBin = 800;
const Double_t minEtaBin = -1.0;
const Double_t maxEtaBin = 1.0;
const Int_t stepsEtaBin = 20;
const Double_t minPhiBin = 0;
const Double_t maxPhiBin = 6.3;
const Int_t stepsPhiBin = 20;
const Double_t minThetaBin = 0;
const Double_t maxThetaBin = TMath::TwoPi();
const Int_t stepsThetaBin = 60;
const Double_t minMassBin = 0;
const Double_t maxMassBin = 5;
const Int_t stepsMassBin = 500;
const Double_t minPairPtBin = 0;
const Double_t maxPairPtBin = 10;
const Int_t stepsPairPtBin = 100;
// Binning of resolution histograms
const Int_t NbinsDeltaMom = 2000;
const Double_t DeltaMomMin = -10.0;
const Double_t DeltaMomMax = 10.0;
const Int_t NbinsRelMom = 400;
const Double_t RelMomMin = 0.0;
const Double_t RelMomMax = 2.0;
const Int_t NbinsDeltaEta = 200;
const Double_t DeltaEtaMin = -0.4;
const Double_t DeltaEtaMax = 0.4;
const Int_t NbinsDeltaTheta = 200;
const Double_t DeltaThetaMin = -0.4;
const Double_t DeltaThetaMax = 0.4;
const Int_t NbinsDeltaPhi = 200;
const Double_t DeltaPhiMin = -0.4;
const Double_t DeltaPhiMax = 0.4;
void GetCentrality(const Int_t centrality, Double_t& CentMin, Double_t& CentMax){
std::cout << "GetCentrality with centrality " << centrality << std::endl;
if (centrality == 0){CentMin = 0; CentMax = 100;}
else if(centrality == 1){CentMin = 0; CentMax = 20;}
else if(centrality == 2){CentMin = 20; CentMax = 40;}
else if(centrality == 3){CentMin = 40; CentMax = 60;}
else if(centrality == 4){CentMin = 60; CentMax = 100;}
else if(centrality == 5){CentMin = 60; CentMax = 80;}
else if(centrality == 6){CentMin = 80; CentMax = 100;}
else if(centrality == 7){CentMin = 0; CentMax = 5;}
else if(centrality == 8){CentMin = -1; CentMax = -1;}
else {std::cout << "WARNING::Centrality range not found....." std::endl;}
return;
}
void ApplyPIDpostCalibration(AliAnalysisTaskElectronEfficiencyV2* task, Int_t whichDet, Bool_t wSDD){
std::cout << task << std::endl;
std::cout << "starting ApplyPIDpostCalibration()\n";
if(whichDet == 0 && wSDD){// ITS
std::cout << "Loading ITS correction" << std::endl;
TString localPath = "/home/aaron/Data/diElec_framework_output/PIDcalibration/";
TString fileName = "outputITS_MC.root";
TFile* inFile = TFile::Open(localPath+fileName);
if(!inFile){
gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PIDcalibration/"+fileName+" .");
std::cout << "Copy ITS correction from Alien" << std::endl;
inFile = TFile::Open(fileName);
}
else {
std::cout << "Correction loaded" << std::endl;
}
TH3D* mean = dynamic_cast<TH3D*>(inFile->Get("sum_mean_correction"));
TH3D* width= dynamic_cast<TH3D*>(inFile->Get("sum_width_correction"));
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, mean, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly);
task->SetWidthCorrFunction (AliAnalysisTaskElectronEfficiencyV2::kITS, width, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly);
}
if(whichDet == 1){// TOF
std::cout << "Loading TOF correction" << std::endl;
TString localPath = "/home/aaron/Data/diElec_framework_output/PIDcalibration/";
TString fileName = "outputTOF";
if(wSDD == kTRUE){
fileName.Append("_MC.root");
}else{
fileName.Append("_woSDD_MC.root");
}
TFile* inFile = TFile::Open(localPath+fileName);
if(!inFile){
gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PIDcalibration/"+fileName+" .");
std::cout << "Copy TOF correction from Alien" << std::endl;
inFile = TFile::Open(fileName);
}
else {
std::cout << "Correction loaded" << std::endl;
}
TH3D* mean = dynamic_cast<TH3D*>(inFile->Get("sum_mean_correction"));
TH3D* width= dynamic_cast<TH3D*>(inFile->Get("sum_width_correction"));
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, mean, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly);
task->SetWidthCorrFunction (AliAnalysisTaskElectronEfficiencyV2::kTOF, width, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly);
}
}
// #########################################################
// #########################################################
AliAnalysisFilter* SetupTrackCutsAndSettings(TString cutDefinition, Bool_t wSDD)
{
std::cout << "SetupTrackCutsAndSettings( cutInstance = " << cutDefinition << " )" <<std::endl;
AliAnalysisFilter *anaFilter = new AliAnalysisFilter("anaFilter","anaFilter"); // named constructor seems mandatory!
LMEECutLib* LMcutlib = new LMEECutLib(wSDD);
if(cutDefinition == "kResolutionCuts"){
std::cout << "Resolution Track Cuts being set" << std::endl;
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kResolutionTrackCuts, LMEECutLib::kResolutionTrackCuts));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutSet1"){ //TMVA
std::cout << "Setting up cut set 1" << std::endl;
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kCutSet1));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kTheoPID"){ // PID cut set from a Run 1 pPb analysis. Standard track cuts
std::cout << "Setting up Theo PID. Standard track cuts." << std::endl;
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kTheoPID));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kScheidCuts"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kScheidCuts, LMEECutLib::kScheidCuts));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
// ######## PID Cut variation settings #################
// These variations use the kCutSet1 track cuts and only vary PID
else if(cutDefinition == "kPIDcut1"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut1));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut2"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut2));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut3"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut3));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut4"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut4));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut5"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut5));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut6"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut6));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut7"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut7));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut8"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut8));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut9"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut9));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut10"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut10));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut11"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut11));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut12"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut12));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut13"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut13));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut14"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut14));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut15"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut15));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut16"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut16));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut17"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut17));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut18"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut18));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut19"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut19));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut20"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut20));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
// ######## Track+ePID Cut variation settings #################
else if(cutDefinition == "kCutVar1"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar1, LMEECutLib::kCutVar1));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar2"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar2, LMEECutLib::kCutVar2));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar3"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar3, LMEECutLib::kCutVar3));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar4"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar4, LMEECutLib::kCutVar4));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar5"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar5, LMEECutLib::kCutVar5));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar6"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar6, LMEECutLib::kCutVar6));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar7"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar7, LMEECutLib::kCutVar7));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar8"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar8, LMEECutLib::kCutVar8));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar9"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar9, LMEECutLib::kCutVar9));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar10"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar10, LMEECutLib::kCutVar10));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar11"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar11, LMEECutLib::kCutVar11));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar12"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar12, LMEECutLib::kCutVar12));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar13"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar13, LMEECutLib::kCutVar13));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar14"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar14, LMEECutLib::kCutVar14));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar15"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar15, LMEECutLib::kCutVar15));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar16"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar16, LMEECutLib::kCutVar16));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar17"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar17, LMEECutLib::kCutVar17));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar18"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar18, LMEECutLib::kCutVar18));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar19"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar19, LMEECutLib::kCutVar19));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar20"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar20, LMEECutLib::kCutVar20));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else{
std::cout << "Undefined cut definition...." << std::endl;
return 0x0;
}
return anaFilter;
}
// #########################################################
// #########################################################
std::vector<Bool_t> AddSingleLegMCSignal(AliAnalysisTaskElectronEfficiencyV2* task){
// SetLegPDGs() requires two pdg codes. For single tracks a dummy value is
// passed, "1".
// All final state electrons (excluding conversion electrons)
AliDielectronSignalMC eleFinalState("eleFinalState","eleFinalState");
eleFinalState.SetLegPDGs(11,1);
eleFinalState.SetCheckBothChargesLegs(kTRUE,kTRUE);
eleFinalState.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
eleFinalState.SetMotherPDGs(22, 22, kTRUE, kTRUE); // Exclude conversion electrons
// Electrons from open charm mesons and baryons
AliDielectronSignalMC eleFinalStateFromD("eleFinalStateFromD","eleFinalStateFromD");
eleFinalStateFromD.SetLegPDGs(11,1);
eleFinalStateFromD.SetCheckBothChargesLegs(kTRUE,kTRUE);
eleFinalStateFromD.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
eleFinalStateFromD.SetMotherPDGs(402, 402);
eleFinalStateFromD.SetCheckBothChargesMothers(kTRUE,kTRUE);
// Electrons from open beauty mesons and baryons
AliDielectronSignalMC eleFinalStateFromB("eleFinalStateFromB","eleFinalStateFromB");
eleFinalStateFromB.SetLegPDGs(11,1);
eleFinalStateFromB.SetCheckBothChargesLegs(kTRUE,kTRUE);
eleFinalStateFromB.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
eleFinalStateFromB.SetMotherPDGs(502, 502);
eleFinalStateFromB.SetCheckBothChargesMothers(kTRUE,kTRUE);
// Add signals
task->AddSingleLegMCSignal(eleFinalState);
task->AddSingleLegMCSignal(eleFinalStateFromD);
task->AddSingleLegMCSignal(eleFinalStateFromB);
// This is used to get electrons not from same mother for pair efficiency.
// Needed to look at D and B meson electrons as functionality to pair those is
// not implemented in the framework. Instead, use all final start electrons
// from D or B decays for efficiency correction, for example.
// The ordering must match the ordering of the added signals above*.
std::vector<Bool_t> DielectronsPairNotFromSameMother;
DielectronsPairNotFromSameMother.push_back(kFALSE);
DielectronsPairNotFromSameMother.push_back(kTRUE);
DielectronsPairNotFromSameMother.push_back(kTRUE);
return DielectronsPairNotFromSameMother;
}
// #########################################################
// #########################################################
void AddPairMCSignal(AliAnalysisTaskElectronEfficiencyV2* task){
// Dielectron pairs from same mother (excluding conversions)
AliDielectronSignalMC pair_sameMother("sameMother","sameMother");
pair_sameMother.SetLegPDGs(11,-11);
pair_sameMother.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother.SetMotherPDGs(22,22,kTRUE,kTRUE); // Exclude conversion
//###################################################################
// Signals for specific dielectron decay channels
AliDielectronSignalMC pair_sameMother_pion("sameMother_pion","sameMother_pion");
pair_sameMother_pion.SetLegPDGs(11,-11);
pair_sameMother_pion.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_pion.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_pion.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_pion.SetMotherPDGs(111,111);
AliDielectronSignalMC pair_sameMother_eta("sameMother_eta","sameMother_eta");
pair_sameMother_eta.SetLegPDGs(11,-11);
pair_sameMother_eta.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_eta.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_eta.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_eta.SetMotherPDGs(221,221);
AliDielectronSignalMC pair_sameMother_etaP("sameMother_etaP","sameMother_etaP");
pair_sameMother_etaP.SetLegPDGs(11,-11);
pair_sameMother_etaP.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_etaP.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_etaP.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_etaP.SetMotherPDGs(331,331);
AliDielectronSignalMC pair_sameMother_rho("sameMother_rho","sameMother_rho");
pair_sameMother_rho.SetLegPDGs(11,-11);
pair_sameMother_rho.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_rho.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_rho.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_rho.SetMotherPDGs(113, 113);
AliDielectronSignalMC pair_sameMother_omega("sameMother_omega","sameMother_omega");
pair_sameMother_omega.SetLegPDGs(11,-11);
pair_sameMother_omega.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_omega.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_omega.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_omega.SetMotherPDGs(223, 223);
AliDielectronSignalMC pair_sameMother_phi("sameMother_phi","sameMother_phi");
pair_sameMother_phi.SetLegPDGs(11,-11);
pair_sameMother_phi.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_phi.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_phi.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_phi.SetMotherPDGs(333, 333);
AliDielectronSignalMC pair_sameMother_jpsi("sameMother_jpsi","sameMother_jpsi");
pair_sameMother_jpsi.SetLegPDGs(11,-11);
pair_sameMother_jpsi.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_jpsi.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_jpsi.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_jpsi.SetMotherPDGs(443, 443);
task->AddPairMCSignal(pair_sameMother);
// task->AddPairMCSignal(pair_sameMother_pion);
// task->AddPairMCSignal(pair_sameMother_eta);
// task->AddPairMCSignal(pair_sameMother_etaP);
// task->AddPairMCSignal(pair_sameMother_rho);
// task->AddPairMCSignal(pair_sameMother_omega);
// task->AddPairMCSignal(pair_sameMother_phi);
// task->AddPairMCSignal(pair_sameMother_jpsi);
}
| carstooon/AliPhysics | PWGDQ/dielectron/macrosLMEE/Config_acapon_Efficiency.C | C++ | bsd-3-clause | 22,296 |
<?php
/*
Copyright (c) 2007, Till Brehm, projektfarm Gmbh
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of THConfig nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/******************************************
* Begin Form configuration
******************************************/
$list_def_file = "list/web_aliasdomain.list.php";
$tform_def_file = "form/web_aliasdomain.tform.php";
/******************************************
* End Form configuration
******************************************/
require_once('../../lib/config.inc.php');
require_once('../../lib/app.inc.php');
//* Check permissions for module
$app->auth->check_module_permissions('sites');
$app->uses("tform_actions");
$app->tform_actions->onDelete();
?> | TR-Host/THConfig | interface/web/sites/web_aliasdomain_del.php | PHP | bsd-3-clause | 2,098 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_preferences_util.h"
#include <stdint.h>
#include <string>
#include <vector>
#include "base/macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/net/convert_explicitly_allowed_network_ports_pref.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/ash/login/demo_mode/demo_session.h"
#endif
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/pref_names.h"
#include "components/language/core/browser/language_prefs.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/renderer_preferences_util.h"
#include "media/media_buildflags.h"
#include "third_party/blink/public/common/peerconnection/webrtc_ip_handling_policy.h"
#include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
#include "third_party/blink/public/public_buildflags.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/ui_base_features.h"
#if defined(TOOLKIT_VIEWS)
#include "ui/views/controls/textfield/textfield.h"
#endif
#if defined(OS_MAC)
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif
#include "content/nw/src/common/nw_content_common_hooks.h"
namespace {
// Parses a string |range| with a port range in the form "<min>-<max>".
// If |range| is not in the correct format or contains an invalid range, zero
// is written to |min_port| and |max_port|.
// TODO(guidou): Consider replacing with remoting/protocol/port_range.cc
void ParsePortRange(const std::string& range,
uint16_t* min_port,
uint16_t* max_port) {
*min_port = 0;
*max_port = 0;
if (range.empty())
return;
size_t separator_index = range.find('-');
if (separator_index == std::string::npos)
return;
std::string min_port_string, max_port_string;
base::TrimWhitespaceASCII(range.substr(0, separator_index), base::TRIM_ALL,
&min_port_string);
base::TrimWhitespaceASCII(range.substr(separator_index + 1), base::TRIM_ALL,
&max_port_string);
unsigned min_port_uint, max_port_uint;
if (!base::StringToUint(min_port_string, &min_port_uint) ||
!base::StringToUint(max_port_string, &max_port_uint)) {
return;
}
if (min_port_uint == 0 || min_port_uint > max_port_uint ||
max_port_uint > UINT16_MAX) {
return;
}
*min_port = static_cast<uint16_t>(min_port_uint);
*max_port = static_cast<uint16_t>(max_port_uint);
}
// Extracts the string representation of URLs allowed for local IP exposure.
std::vector<std::string> GetLocalIpsAllowedUrls(
const base::ListValue* allowed_urls) {
std::vector<std::string> ret;
if (allowed_urls) {
const auto& urls = allowed_urls->GetList();
for (const auto& url : urls)
ret.push_back(url.GetString());
}
return ret;
}
std::string GetLanguageListForProfile(Profile* profile,
const std::string& language_list) {
if (profile->IsOffTheRecord()) {
// In incognito mode return only the first language.
return language::GetFirstLanguage(language_list);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// On Chrome OS, if in demo mode, add the demo mode private language list.
if (ash::DemoSession::IsDeviceInDemoMode()) {
return language_list + "," + ash::DemoSession::GetAdditionalLanguageList();
}
#endif
return language_list;
}
} // namespace
namespace renderer_preferences_util {
void UpdateFromSystemSettings(blink::RendererPreferences* prefs,
Profile* profile) {
const PrefService* pref_service = profile->GetPrefs();
prefs->accept_languages = GetLanguageListForProfile(
profile, pref_service->GetString(language::prefs::kAcceptLanguages));
prefs->enable_referrers = pref_service->GetBoolean(prefs::kEnableReferrers);
prefs->enable_do_not_track =
pref_service->GetBoolean(prefs::kEnableDoNotTrack);
prefs->enable_encrypted_media =
pref_service->GetBoolean(prefs::kEnableEncryptedMedia);
prefs->webrtc_ip_handling_policy = std::string();
#if !defined(OS_ANDROID)
prefs->caret_browsing_enabled =
pref_service->GetBoolean(prefs::kCaretBrowsingEnabled);
content::BrowserAccessibilityState::GetInstance()->SetCaretBrowsingState(
prefs->caret_browsing_enabled);
#endif
if (prefs->webrtc_ip_handling_policy.empty()) {
prefs->webrtc_ip_handling_policy =
pref_service->GetString(prefs::kWebRTCIPHandlingPolicy);
}
std::string webrtc_udp_port_range =
pref_service->GetString(prefs::kWebRTCUDPPortRange);
ParsePortRange(webrtc_udp_port_range, &prefs->webrtc_udp_min_port,
&prefs->webrtc_udp_max_port);
const base::ListValue* allowed_urls =
pref_service->GetList(prefs::kWebRtcLocalIpsAllowedUrls);
prefs->webrtc_local_ips_allowed_urls = GetLocalIpsAllowedUrls(allowed_urls);
prefs->webrtc_allow_legacy_tls_protocols =
pref_service->GetBoolean(prefs::kWebRTCAllowLegacyTLSProtocols);
#if defined(USE_AURA)
prefs->focus_ring_color = SkColorSetRGB(0x4D, 0x90, 0xFE);
#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
// This color is 0x544d90fe modulated with 0xffffff.
prefs->active_selection_bg_color = SkColorSetRGB(0xCB, 0xE4, 0xFA);
prefs->active_selection_fg_color = SK_ColorBLACK;
prefs->inactive_selection_bg_color = SkColorSetRGB(0xEA, 0xEA, 0xEA);
prefs->inactive_selection_fg_color = SK_ColorBLACK;
#endif
#endif
#if defined(TOOLKIT_VIEWS)
prefs->caret_blink_interval = views::Textfield::GetCaretBlinkInterval();
#endif
#if defined(OS_MAC)
base::TimeDelta interval;
if (ui::TextInsertionCaretBlinkPeriod(&interval))
prefs->caret_blink_interval = interval;
#endif
#if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
views::LinuxUI* linux_ui = views::LinuxUI::instance();
if (linux_ui) {
if (ThemeServiceFactory::GetForProfile(profile)->UsingSystemTheme()) {
prefs->focus_ring_color = linux_ui->GetFocusRingColor();
prefs->active_selection_bg_color = linux_ui->GetActiveSelectionBgColor();
prefs->active_selection_fg_color = linux_ui->GetActiveSelectionFgColor();
prefs->inactive_selection_bg_color =
linux_ui->GetInactiveSelectionBgColor();
prefs->inactive_selection_fg_color =
linux_ui->GetInactiveSelectionFgColor();
}
// If we have a linux_ui object, set the caret blink interval regardless of
// whether we're in native theme mode.
prefs->caret_blink_interval = linux_ui->GetCursorBlinkInterval();
}
#endif
#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \
defined(OS_WIN)
content::UpdateFontRendererPreferencesFromSystemSettings(prefs);
#endif
#if !defined(OS_MAC)
prefs->plugin_fullscreen_allowed =
pref_service->GetBoolean(prefs::kFullscreenAllowed);
#endif
PrefService* local_state = g_browser_process->local_state();
if (local_state) {
prefs->allow_cross_origin_auth_prompt =
local_state->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
prefs->explicitly_allowed_network_ports =
ConvertExplicitlyAllowedNetworkPortsPref(local_state);
}
#if defined(OS_MAC)
prefs->focus_ring_color = SkColorSetRGB(0x00, 0x5F, 0xCC);
#else
prefs->focus_ring_color = SkColorSetRGB(0x10, 0x10, 0x10);
#endif
std::string user_agent;
if (nw::GetUserAgentFromManifest(&user_agent))
prefs->user_agent_override.ua_string_override = user_agent;
}
} // namespace renderer_preferences_util
| nwjs/chromium.src | chrome/browser/renderer_preferences_util.cc | C++ | bsd-3-clause | 8,221 |
package net.minidev.ovh.api.price.dedicatedcloud._2014v1.sbg1a.infrastructure.filer;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Enum of Hourlys
*/
public enum OvhHourlyEnum {
@JsonProperty("iscsi-1200-GB")
iscsi_1200_GB("iscsi-1200-GB"),
@JsonProperty("iscsi-13200g-GB")
iscsi_13200g_GB("iscsi-13200g-GB"),
@JsonProperty("iscsi-3300-GB")
iscsi_3300_GB("iscsi-3300-GB"),
@JsonProperty("iscsi-6600-GB")
iscsi_6600_GB("iscsi-6600-GB"),
@JsonProperty("iscsi-800-GB")
iscsi_800_GB("iscsi-800-GB"),
@JsonProperty("nfs-100-GB")
nfs_100_GB("nfs-100-GB"),
@JsonProperty("nfs-1200-GB")
nfs_1200_GB("nfs-1200-GB"),
@JsonProperty("nfs-13200-GB")
nfs_13200_GB("nfs-13200-GB"),
@JsonProperty("nfs-1600-GB")
nfs_1600_GB("nfs-1600-GB"),
@JsonProperty("nfs-2400-GB")
nfs_2400_GB("nfs-2400-GB"),
@JsonProperty("nfs-3300-GB")
nfs_3300_GB("nfs-3300-GB"),
@JsonProperty("nfs-6600-GB")
nfs_6600_GB("nfs-6600-GB"),
@JsonProperty("nfs-800-GB")
nfs_800_GB("nfs-800-GB");
final String value;
OvhHourlyEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
| UrielCh/ovh-java-sdk | ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/price/dedicatedcloud/_2014v1/sbg1a/infrastructure/filer/OvhHourlyEnum.java | Java | bsd-3-clause | 1,119 |
<?php
/**
* Rules_Whitespace_SuperfluousWhitespaceRule.
*
* Checks that no whitespace at the end of each line and no two empty lines in the content.
*
* @package SmartyLint
* @author Umakant Patil <me@umakantpatil.com>
* @copyright 2013-15 Umakant Patil
* @license https://github.com/umakantp/SmartyLint/blob/master/LICENSE BSD Licence
* @link https://github.com/umakantp/SmartyLint
*/
class Rules_Whitespace_SuperfluousWhitespaceRule implements SmartyLint_Rule {
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register() {
return array('NEW_LINE');
}
/**
* Processes this rule, when one of its tokens is encountered.
*
* @param SmartyLint_File $smartylFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(SmartyLint_File $smartylFile, $stackPtr) {
$tokens = $smartylFile->getTokens();
$beforeNewLine = false;
if (isset($tokens[($stackPtr - 1)])) {
$beforeNewLine = $tokens[($stackPtr - 1)]['type'];
if ($beforeNewLine == 'TAB' || $beforeNewLine == 'SPACE') {
$smartylFile->addError('Whitespace found at end of line', $stackPtr, 'EndFile');
}
}
$newLinesFound = 1;
for ($i = ($stackPtr-1); $i >= 0; $i--) {
if (isset($tokens[$i]) && $tokens[$i]['type'] == 'NEW_LINE') {
$newLinesFound++;
} else {
break;
}
}
if ($newLinesFound > 3) {
$error = 'Found %s empty lines in a row.';
$data = array($newLinesFound);
$smartylFile->addError($error, ($stackPtr - $newLinesFound), 'EmptyLines', $data);
}
}
}
| umakantp/SmartyLint | SmartyLint/Rules/Whitespace/SuperfluousWhitespaceRule.php | PHP | bsd-3-clause | 1,961 |
<?php
App::uses('CloggyAppModel', 'Cloggy.Model');
class CloggySearchFullText extends CloggyAppModel {
public $name = 'CloggySearchFullText';
public $useTable = 'search_fulltext';
public $actsAs = array('CloggySearchFullTexIndex','CloggySearchFullTextTerm');
public function getTotal() {
return $this->find('count');
}
/**
* Do search using MysqlFullTextSearch
*
* @link http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html NATURAL SEARCH
* @link http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html BOOLEAN MODE
* @param string $query
* @return array
*/
public function search($query) {
//default used mode
$usedMode = __d('cloggy','Natural Search');
/*
* first try to search with natural search
* NATURAL SEARCH
*/
$data = $this->find('all',array(
'contain' => false,
'fields' => array('*','MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\') AS rating'),
'conditions' => array('MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\')'),
'order' => array('rating' => 'desc')
));
/*
* if failed or empty results then
* reset search in BOOLEAN MODE
* with operator '*' that means search
* data which contain 'query' or 'queries', etc
*/
if (empty($data)) {
//format query string
$query = $this->buildTerm($query);
/*
* begin searching data
*/
$data = $this->find('all',array(
'contain' => false,
'fields' => array('*','MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\' IN BOOLEAN MODE) AS rating'),
'conditions' => array('MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\' IN BOOLEAN MODE)'),
'order' => array('rating' => 'desc')
));
//switch search mode
$usedMode = __d('cloggy','Boolean Mode');
}
return array(
'mode' => $usedMode,
'results' => $data
);
}
} | hiraq/Cloggy | Module/CloggySearch/Model/CloggySearchFullText.php | PHP | bsd-3-clause | 2,568 |
package org.usfirst.frc369.Robot2017Code.subsystems;
import org.usfirst.frc369.Robot2017Code.Robot;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
*/
public class LED extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void LEDOn(){
Robot.LEDSys.equals(Relay.Value.kForward);
}
public void LEDelse(){
Robot.LEDSys.equals(Relay.Value.kReverse);
}
public void LEDOff(){
Robot.LEDSys.equals(Relay.Value.kOff);
}
}
| ShadowShitler/Bridgette | src/org/usfirst/frc369/Robot2017Code/subsystems/LED.java | Java | bsd-3-clause | 726 |
var NETKI_PUBAPI_HOST = 'https://pubapi.netki.com';
var NETKI_API_HOST = 'https://api.netki.com';
var SHORTCODES = {
'btc': 'Bitcoin',
'tbtc': 'Bitcoin Testnet',
'ltc': 'Litecoin',
'dgc': 'Dogecoin',
'nmc': 'Namecoin',
'tusd': 'tetherUSD',
'teur': 'tetherEUR',
'tjpy': 'tetherJPY',
'oap': 'Open Asset',
'fct': 'Factom Factoid',
'fec': 'Factom Entry Credit',
'eth': 'Ethereum Ether'
};
function isWalletName(walletName) {
var pattern = /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA-Z0-9-]+\.[a-zA-Z]{2,24}?$/i;
return pattern.test(walletName);
} | netkicorp/walletname-chrome-extension | app/scripts.babel/netkiUtils.js | JavaScript | bsd-3-clause | 573 |
<?php
/**
* Cache subsystem library
* @package Cotonti
* @version 0.9.10
* @author Cotonti Team
* @copyright Copyright (c) Cotonti Team 2009-2014
* @license BSD
*/
defined('COT_CODE') or die('Wrong URL');
/**
* Stores the list of advanced cachers provided by the host
* @var array
*/
$cot_cache_drivers = array();
/**
* Default cache realm
*/
define('COT_DEFAULT_REALM', 'cot');
/**
* Default time to live for temporary cache objects
*/
define('COT_DEFAULT_TTL', 3600);
/**
* Default cache type, uneffective
*/
define('COT_CACHE_TYPE_ALL', 0);
/**
* Disk cache type
*/
define('COT_CACHE_TYPE_DISK', 1);
/**
* Database cache type
*/
define('COT_CACHE_TYPE_DB', 2);
/**
* Shared memory cache type
*/
define('COT_CACHE_TYPE_MEMORY', 3);
/**
* Page cache type
*/
define('COT_CACHE_TYPE_PAGE', 4);
/**
* Default cache type
*/
define('COT_CACHE_TYPE_DEFAULT', COT_CACHE_TYPE_DB);
/**
* Abstract class containing code common for all cache drivers
* @author Cotonti Team
*/
abstract class Cache_driver
{
/**
* Clears all cache entries served by current driver
* @param string $realm Cache realm name, to clear specific realm only
* @return bool
*/
abstract public function clear($realm = COT_DEFAULT_REALM);
/**
* Checks if an object is stored in cache
* @param string $id Object identifier
* @param string $realm Cache realm
* @return bool
*/
abstract public function exists($id, $realm = COT_DEFAULT_REALM);
/**
* Returns value of cached image
* @param string $id Object identifier
* @param string $realm Realm name
* @return mixed Cached item value or NULL if the item was not found in cache
*/
abstract public function get($id, $realm = COT_DEFAULT_REALM);
/**
* Removes object image from cache
* @param string $id Object identifier
* @param string $realm Realm name
* @return bool
*/
abstract public function remove($id, $realm = COT_DEFAULT_REALM);
}
/**
* Static cache is used to store large amounts of rarely modified data
*/
abstract class Static_cache_driver
{
/**
* Stores data as object image in cache
* @param string $id Object identifier
* @param mixed $data Object value
* @param string $realm Realm name
* @return bool
*/
abstract public function store($id, $data, $realm = COT_DEFAULT_REALM);
}
/**
* Dynamic cache is used to store data that is not too large
* and is modified more or less frequently
*/
abstract class Dynamic_cache_driver
{
/**
* Stores data as object image in cache
* @param string $id Object identifier
* @param mixed $data Object value
* @param string $realm Realm name
* @param int $ttl Time to live, 0 for unlimited
* @return bool
*/
abstract public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL);
}
/**
* Persistent cache driver that writes all entries back on script termination.
* Persistent cache drivers work slower but guarantee long-term data consistency.
*/
abstract class Writeback_cache_driver extends Dynamic_cache_driver
{
/**
* Values for delayed writeback to persistent cache
* @var array
*/
protected $writeback_data = array();
/**
* Keys that are to be removed
*/
protected $removed_data = array();
/**
* Writes modified entries back to persistent storage
*/
abstract public function flush();
/**
* Removes cache image of the object from the database
* @param string $id Object identifier
* @param string $realm Realm name
*/
public function remove($id, $realm = COT_DEFAULT_REALM)
{
$this->removed_data[] = array('id' => $id, 'realm' => $realm);
}
/**
* Removes item immediately, avoiding writeback.
* @param string $id Item identifirer
* @param string $realm Cache realm
* @return bool
* @see Cache_driver::remove()
*/
abstract public function remove_now($id, $realm = COT_DEFAULT_REALM);
/**
* Stores data as object image in cache
* @param string $id Object identifier
* @param mixed $data Object value
* @param string $realm Realm name
* @param int $ttl Time to live, 0 for unlimited
* @return bool
* @see Cache_driver::store()
*/
public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = 0)
{
$this->writeback_data[] = array('id' => $id, 'data' => $data, 'realm' => $realm, 'ttl' => $ttl);
return true;
}
/**
* Writes item to cache immediately, avoiding writeback.
* @param string $id Object identifier
* @param mixed $data Object value
* @param string $realm Realm name
* @param int $ttl Time to live, 0 for unlimited
* @return bool
* @see Cache_driver::store()
*/
abstract public function store_now($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL);
}
/**
* Query cache drivers are driven by database
*/
abstract class Db_cache_driver extends Writeback_cache_driver
{
/**
* Loads all variables from a specified realm(s) into the global scope
* @param mixed $realm Realm name or array of realm names
* @return int Number of items loaded
*/
abstract public function get_all($realm = COT_DEFAULT_REALM);
}
/**
* Temporary cache driver is fast in-memory cache. It usually works faster and provides
* automatic garbage collection, but it doesn't save data if PHP stops whatsoever.
* Use it for individual frequently modified variables.
*/
abstract class Temporary_cache_driver extends Dynamic_cache_driver
{
/**
* Increments counter value
* @param string $id Counter identifier
* @param string $realm Realm name
* @param int $value Increment value
* return int Result value
*/
public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1)
{
$res = $this->get($id, $realm);
$res += $value;
$this->store($id, $res, $realm);
return $res;
}
/**
* Decrements counter value
* @param string $id Counter identifier
* @param string $realm Realm name
* @param int $value Increment value
* return int Result value
*/
public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1)
{
$res = $this->get($id, $realm);
$res -= $value;
$this->store($id, $res, $realm);
return $res;
}
/**
* Returns information about memory usage if available.
* Possible keys: available, occupied, max.
* If the driver cannot provide a value, it sets it to -1.
* @return array Associative array containing information
*/
abstract public function get_info();
/**
* Gets a size limit from php.ini
* @param string $name INI setting name
* @return int Number of bytes
*/
protected function get_ini_size($name)
{
$ini = ini_get($name);
$suffix = strtoupper(substr($ini, -1));
$prefix = substr($ini, 0, -1);
switch ($suffix)
{
case 'K':
return ((int) $prefix) * 1024;
break;
case 'M':
return ((int) $prefix) * 1048576;
break;
case 'G':
return ((int) $prefix) * 1073741824;
break;
default:
return (int) $ini;
}
}
}
/**
* A persistent cache using local file system tree. It does not use multilevel structure
* or lexicograph search, so it may slow down when your cache grows very big.
* But normally it is very fast reads.
* @author Cotonti Team
*/
class File_cache extends Static_cache_driver
{
/**
* Cache root directory
* @var string
*/
private $dir;
/**
* Cache storage object constructor
* @param string $dir Cache root directory. System default will be used if empty.
* @throws Exception
* @return File_cache
*/
public function __construct($dir = '')
{
global $cfg;
if (empty($dir)) $dir = $cfg['cache_dir'];
if (!empty($dir) && !file_exists($dir)) mkdir($dir, 0755, true);
if (file_exists($dir) && is_writeable($dir))
{
$this->dir = $dir;
}
else
{
throw new Exception('Cache directory '.$dir.' is not writeable!'); // TODO: Need translate
}
}
/**
* @see Cache_driver::clear()
*/
public function clear($realm = COT_DEFAULT_REALM)
{
if (empty($realm))
{
if(is_dir($this->dir))
{
$dp = opendir($this->dir);
while ($f = readdir($dp))
{
$dname = $this->dir.'/'.$f;
if ($f[0] != '.' && is_dir($dname))
{
$this->clear($f);
}
}
closedir($dp);
}
}
else
{
if(is_dir($this->dir.'/'.$realm))
{
$dp = opendir($this->dir.'/'.$realm);
while ($f = readdir($dp))
{
$fname = $this->dir.'/'.$realm.'/'.$f;
if (is_file($fname))
{
unlink($fname);
}
}
closedir($dp);
}
}
return TRUE;
}
/**
* Checks if an object is stored in disk cache
* @param string $id Object identifier
* @param string $realm Cache realm
* @param int $ttl Lifetime in seconds, 0 means unlimited
* @return bool
*/
public function exists($id, $realm = COT_DEFAULT_REALM, $ttl = 0)
{
$filename = $this->dir.'/'.$realm.'/'.$id;
return file_exists($filename) && ($ttl == 0 || time() - filemtime($filename) < $ttl);
}
/**
* Gets an object directly from disk
* @param string $id Object identifier
* @param string $realm Realm name
* @param int $ttl Lifetime in seconds, 0 means unlimited
* @return mixed Cached item value or NULL if the item was not found in cache
*/
public function get($id, $realm = COT_DEFAULT_REALM, $ttl = 0)
{
if ($this->exists($id, $realm, $ttl))
{
return unserialize(file_get_contents($this->dir.'/'.$realm.'/'.$id));
}
else
{
return NULL;
}
}
/**
* Removes cache image of the object from disk
* @param string $id Object identifier
* @param string $realm Realm name
*/
public function remove($id, $realm = COT_DEFAULT_REALM)
{
if ($this->exists($id, $realm))
{
unlink($this->dir.'/'.$realm.'/'.$id);
return true;
}
else return false;
}
/**
* Stores disk cache entry
* @param string $id Object identifier
* @param mixed $data Object value
* @param string $realm Realm name
* @return bool
*/
public function store($id, $data, $realm = COT_DEFAULT_REALM)
{
if (!file_exists($this->dir.'/'.$realm))
{
mkdir($this->dir.'/'.$realm);
}
file_put_contents($this->dir.'/'.$realm.'/'.$id, serialize($data));
return true;
}
}
/**
* A cache that stores entire page outputs. Disk-based.
*/
class Page_cache
{
/**
* Cache root
*/
private $dir;
/**
* Relative page (item) path
*/
private $path;
/**
* Short file name
*/
private $name;
/**
* Parameters to exclude
*/
private $excl;
/**
* Filename extension
*/
private $ext;
/**
* Full path to page cache image
*/
private $filename;
/**
* Directory permissions
*/
private $perms;
/**
* Constructs controller object and sets basic configuration
* @param string $dir Cache directory
* @param int $perms Octal permission mask for cache directories
*/
public function __construct($dir, $perms = 0777)
{
$this->dir = $dir;
$this->perms = $perms;
}
/**
* Removes an item and all contained items and cache files
* @param string $path Item path
* @return int Number of files removed
*/
public function clear($path)
{
return $this->rm_r($this->dir . '/' . $path);
}
/**
* Initializes actual page cache
* @param string $path Page path string
* @param string $name Short name for the cache file
* @param array $exclude A list of GET params to be excluded from consideration
* @param string $ext File extension
*/
public function init($path, $name, $exclude = array(), $ext = '')
{
$this->path = $path;
$this->name = $name;
$this->excl = $exclude;
$this->ext = $ext;
}
/**
* Reads the page cache object from disk and sends it to output.
* If the cache object does not exist, then just calculates the path
* for a following write() call.
*/
public function read()
{
$filename = $this->dir. '/' . $this->path . '/' . $this->name;
$args = array();
foreach ($_GET as $key => $val)
{
if (!in_array($key, $this->excl))
{
$args[$key] = $val;
}
}
ksort($args);
if (count($args) > 0)
{
$hashkey = serialize($args);
$filename .= '_' . md5($hashkey) . sha1($hashkey);
}
if (!empty($this->ext))
{
$filename .= '.' . $this->ext;
}
if (file_exists($filename))
{
// Browser cache headers
$filemtime = filemtime($filename);
$etag = md5($filename . filesize($filename) . $filemtime);
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
// convert to unix timestamp
$if_modified_since = strtotime(preg_replace('#;.*$#', '',
stripslashes($_SERVER['HTTP_IF_MODIFIED_SINCE'])));
}
else
{
$if_modified_since = false;
}
$if_none_match = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
if ($if_none_match == $etag
&& $if_modified_since >= $filemtime)
{
$protocol = (isset($_SERVER['SERVER_PROTOCOL'])) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
header($protocol . ' 304 Not Modified');
header("Etag: $etag");
exit;
}
header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', $filemtime));
header("ETag: $etag");
header('Expires: Mon, 01 Apr 1974 00:00:00 GMT');
header('Cache-Control: must-revalidate, proxy-revalidate');
// Page output
header('Content-Type: text/html; charset=UTF-8');
if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === FALSE)
{
readgzfile($filename);
}
else
{
header('Content-Encoding: gzip');
echo file_get_contents($filename);
}
exit;
}
$this->filename = $filename;
}
/**
* Writes output buffer contents to a cache image file
*/
public function write()
{
if (!empty($this->filename))
{
if (!file_exists($this->dir . '/' . $this->path))
{
mkdir($this->dir . '/' . $this->path, $this->perms, true);
}
file_put_contents($this->filename, gzencode(cot_outputfilters(ob_get_contents())));
}
}
/**
* Removes a directory with all its contents recursively
* @param string $path Directory path
* @return int Number of items removed
*/
private function rm_r($path)
{
$cnt = 0;
if(is_dir($path))
{
$dp = opendir($path);
while ($f = readdir($dp))
{
$fpath = $path . '/' . $f;
if (is_dir($fpath) && $f != '.' && $f != '..')
{
$cnt += $this->rm_r($fpath);
}
elseif (is_file($fpath))
{
unlink($fpath);
++$cnt;
}
}
closedir($dp);
rmdir($path);
}
return ++$cnt;
}
}
/**
* A very popular caching solution using MySQL as a storage. It is quite slow compared to
* File_cache but may be considered more reliable.
* @author Cotonti Team
*/
class MySQL_cache extends Db_cache_driver
{
/**
* Prefetched data to avoid duplicate queries
* @var array
*/
private $buffer = array();
/**
* Performs pre-load actions
*/
public function __construct()
{
// 10% GC probability
if (mt_rand(1, 10) == 5)
{
$this->gc();
}
}
/**
* Enforces flush()
*/
public function __destruct()
{
$this->flush();
}
/**
* Saves all modified data with one query
*/
public function flush()
{
global $db, $db_cache, $sys;
if (count($this->removed_data) > 0)
{
$q = "DELETE FROM $db_cache WHERE";
$i = 0;
foreach ($this->removed_data as $entry)
{
$c_name = $db->quote($entry['id']);
$c_realm = $db->quote($entry['realm']);
$or = $i == 0 ? '' : ' OR';
$q .= $or." (c_name = $c_name AND c_realm = $c_realm)";
$i++;
}
$this->removed_data = array();
$db->query($q);
}
if (count($this->writeback_data) > 0)
{
$q = "INSERT INTO $db_cache (c_name, c_realm, c_expire, c_value) VALUES ";
$i = 0;
foreach ($this->writeback_data as $entry)
{
$c_name = $db->quote($entry['id']);
$c_realm = $db->quote($entry['realm']);
$c_expire = $entry['ttl'] > 0 ? $sys['now'] + $entry['ttl'] : 0;
$c_value = $db->quote(serialize($entry['data']));
$comma = $i == 0 ? '' : ',';
$q .= $comma."($c_name, $c_realm, $c_expire, $c_value)";
$i++;
}
$this->writeback_data = array();
$q .= " ON DUPLICATE KEY UPDATE c_value=VALUES(c_value), c_expire=VALUES(c_expire)";
$db->query($q);
}
}
/**
* @see Cache_driver::clear()
*/
public function clear($realm = '')
{
global $db, $db_cache;
if (empty($realm))
{
$db->query("TRUNCATE $db_cache");
}
else
{
$db->query("DELETE FROM $db_cache WHERE c_realm = " . $db->quote($realm));
}
$this->buffer = array();
return TRUE;
}
/**
* @see Cache_driver::exists()
*/
public function exists($id, $realm = COT_DEFAULT_REALM)
{
global $db, $db_cache;
if (isset($this->buffer[$realm][$id]))
{
return true;
}
$sql = $db->query("SELECT c_value FROM $db_cache WHERE c_realm = ".$db->quote($realm)." AND c_name = ".$db->quote($id));
$res = $sql->rowCount() == 1;
if ($res)
{
$this->buffer[$realm][$id] = unserialize($sql->fetchColumn());
}
return $res;
}
/**
* Garbage collector function. Removes cache entries which are not valid anymore.
* @return int Number of entries removed
*/
private function gc()
{
global $db, $db_cache, $sys;
$db->query("DELETE FROM $db_cache WHERE c_expire > 0 AND c_expire < ".$sys['now']);
return $db->affectedRows;
}
/**
* @see Cache_driver::get()
*/
public function get($id, $realm = COT_DEFAULT_REALM)
{
if($this->exists($id, $realm))
{
return $this->buffer[$realm][$id];
}
else
{
return null;
}
}
/**
* @see Db_cache_driver::get_all()
*/
public function get_all($realms = COT_DEFAULT_REALM)
{
global $db, $db_cache;
if (is_array($realms))
{
$r_where = "c_realm IN(";
$i = 0;
foreach ($realms as $realm)
{
$glue = $i == 0 ? "'" : ",'";
$r_where .= $glue.$db->prep($realm)."'";
$i++;
}
$r_where .= ')';
}
else
{
$r_where = "c_realm = '".$db->prep($realms)."'";
}
$sql = $db->query("SELECT c_name, c_value FROM `$db_cache` WHERE c_auto=1 AND $r_where");
$i = 0;
while ($row = $sql->fetch())
{
global ${$row['c_name']};
${$row['c_name']} = unserialize($row['c_value']);
$i++;
}
$sql->closeCursor();
return $i;
}
/**
* @see Writeback_cache_driver::remove_now()
*/
public function remove_now($id, $realm = COT_DEFAULT_REALM)
{
global $db, $db_cache;
$db->query("DELETE FROM $db_cache WHERE c_realm = ".$db->quote($realm)." AND c_name = ".$db->quote($id));
unset($this->buffer[$realm][$id]);
return $db->affectedRows == 1;
}
/**
* Stores data as object image in cache
* @param string $id Object identifier
* @param mixed $data Object value
* @param string $realm Realm name
* @param int $ttl Time to live, 0 for unlimited
* @return bool
* @see Cache_driver::store()
*/
public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = 0)
{
global $db;
// Check data length
if ($data)
{
if (strlen($db->prep(serialize($data))) > 16777215) // MySQL max MEDIUMTEXT size
{
return false;
}
}
return parent::store($id, $data, $realm, $ttl);
}
/**
* Writes item to cache immediately, avoiding writeback.
* @param string $id Object identifier
* @param mixed $data Object value
* @param string $realm Realm name
* @param int $ttl Time to live, 0 for unlimited
* @return bool
* @see Cache_driver::store()
*/
public function store_now($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL)
{
global $db, $db_cache, $sys;
$c_name = $db->quote($id);
$c_realm = $db->quote($realm);
$c_expire = $ttl > 0 ? $sys['now'] + $ttl : 0;
$c_value = $db->quote(serialize($data));
$db->query("INSERT INTO $db_cache (c_name, c_realm, c_expire, c_value)
VALUES ($c_name, $c_realm, $c_expire, $c_value)");
$this->buffer[$realm][$id] = $data;
return $db->affectedRows == 1;
}
}
if (extension_loaded('memcache'))
{
$cot_cache_drivers[] = 'Memcache_driver';
/**
* Memcache distributed persistent cache driver implementation. Give it a higher priority
* if a cluster of webservers is used and Memcached is running via TCP/IP between them.
* In other circumstances this only should be used if no APC/XCache available,
* keeping in mind that File_cache might be still faster.
* @author Cotonti Team
*/
class Memcache_driver extends Temporary_cache_driver
{
/**
* PHP Memcache instance
* @var Memcache
*/
protected $memcache = NULL;
/**
* Creates an object and establishes Memcached server connection
* @param string $host Memcached host
* @param int $port Memcached port
* @param bool $persistent Use persistent connection
* @return Memcache_driver
*/
public function __construct($host = 'localhost', $port = 11211, $persistent = true)
{
$this->memcache = new Memcache;
$this->memcache->addServer($host, $port, $persistent);
}
/**
* Make unique key for one of different sites on one memcache pool
* @param $key
* @return string
*/
public static function createKey($key) {
if (is_array($key)) $key = serialize($key);
return md5(cot::$cfg['site_id'].$key);
}
/**
* @see Cache_driver::clear()
*/
public function clear($realm = '')
{
if (empty($realm))
{
return $this->memcache->flush();
}
else
{
// FIXME implement exact realm cleanup (not yet provided by Memcache)
return $this->memcache->flush();
}
}
/**
* @see Temporary_cache_driver::dec()
*/
public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1)
{
$id = self::createKey($id);
return $this->memcache->decrement($realm.'/'.$id, $value);
}
/**
* @see Cache_driver::exists()
*/
public function exists($id, $realm = COT_DEFAULT_REALM)
{
$id = self::createKey($id);
return $this->memcache->get($realm.'/'.$id) !== FALSE;
}
/**
* @see Cache_driver::get()
*/
public function get($id, $realm = COT_DEFAULT_REALM)
{
$id = self::createKey($id);
return $this->memcache->get($realm.'/'.$id);
}
/**
* @see Temporary_cache_driver::get_info()
*/
public function get_info()
{
$info = $this->memcache->getstats();
return array(
'available' => $info['limit_maxbytes'] - $info['bytes'],
'max' => $info['limit_maxbytes'],
'occupied' => $info['bytes']
);
}
/**
* @see Temporary_cache_driver::inc()
*/
public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1)
{
$id = self::createKey($id);
return $this->memcache->increment($realm.'/'.$id, $value);
}
/**
* @see Cache_driver::remove()
*/
public function remove($id, $realm = COT_DEFAULT_REALM)
{
$id = self::createKey($id);
return $this->memcache->delete($realm.'/'.$id);
}
/**
* @see Dynamic_cache_driver::store()
*/
public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL)
{
$id = self::createKey($id);
return $this->memcache->set($realm.'/'.$id, $data, 0, $ttl);
}
}
}
if (extension_loaded('apc'))
{
$cot_cache_drivers[] = 'APC_driver';
/**
* Accelerated PHP Cache driver implementation. This should be used as default cacher
* on APC-enabled hosts.
* @author Cotonti Team
*/
class APC_driver extends Temporary_cache_driver
{
/**
* @see Cache_driver::clear()
*/
public function clear($realm = '')
{
if (empty($realm))
{
return apc_clear_cache();
}
else
{
// TODO implement exact realm cleanup
return FALSE;
}
}
/**
* @see Cache_driver::exists()
*/
public function exists($id, $realm = COT_DEFAULT_REALM)
{
return apc_fetch($realm.'/'.$id) !== FALSE;
}
/**
* @see Cache_driver::get()
*/
public function get($id, $realm = COT_DEFAULT_REALM)
{
return unserialize(apc_fetch($realm.'/'.$id));
}
/**
* @see Temporary_cache_driver::get_info()
*/
public function get_info()
{
$info = apc_sma_info();
$max = ini_get('apc.shm_segments') * ini_get('apc.shm_size') * 1024 * 1024;
$occupied = $max - $info['avail_mem'];
return array(
'available' => $info['avail_mem'],
'max' => $max,
'occupied' => $occupied
);
}
/**
* @see Cache_driver::remove()
*/
public function remove($id, $realm = COT_DEFAULT_REALM)
{
return apc_delete($realm.'/'.$id);
}
/**
* @see Dynamic_cache_driver::store()
*/
public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL)
{
// Protect from exhausted memory
$info = $this->get_info();
if ($info['available'] < $info['max'] * 0.2)
{
$this->clear();
}
return apc_store($realm.'/'.$id, serialize($data), $ttl);
}
}
}
if (extension_loaded('xcache'))
{
$cot_cache_drivers[] = 'Xcache_driver';
/**
* XCache variable cache driver. It should be used on hosts that use XCache for
* PHP acceleration and variable cache.
* @author Cotonti Team
*/
class Xcache_driver extends Temporary_cache_driver
{
/**
* @see Cache_driver::clear()
*/
public function clear($realm = '')
{
if (function_exists('xcache_unset_by_prefix'))
{
if (empty($realm))
{
return xcache_unset_by_prefix('');
}
else
{
return xcache_unset_by_prefix($realm.'/');
}
}
else
{
// This does not actually mean success but we can do nothing with it
return true;
}
}
/**
* @see Cache_driver::exists()
*/
public function exists($id, $realm = COT_DEFAULT_REALM)
{
return xcache_isset($realm.'/'.$id);
}
/**
* @see Temporary_cache_driver::dec()
*/
public function dec($id, $realm = COT_DEFAULT_REALM, $value = 1)
{
return xcache_dec($realm.'/'.$id, $value);
}
/**
* @see Cache_driver::get()
*/
public function get($id, $realm = COT_DEFAULT_REALM)
{
return xcache_get($realm.'/'.$id);
}
/**
* @see Temporary_cache_driver::get_info()
*/
public function get_info()
{
return array(
'available' => -1,
'max' => $this->get_ini_size('xcache.var_size'),
'occupied' => -1
);
}
/**
* @see Temporary_cache_driver::inc()
*/
public function inc($id, $realm = COT_DEFAULT_REALM, $value = 1)
{
return xcache_inc($realm.'/'.$id, $value);
}
/**
* @see Cache_driver::remove()
*/
public function remove($id, $realm = COT_DEFAULT_REALM)
{
return xcache_unset($realm.'/'.$id);
}
/**
* @see Dynamic_cache_driver::store()
*/
public function store($id, $data, $realm = COT_DEFAULT_REALM, $ttl = COT_DEFAULT_TTL)
{
return xcache_set($realm.'/'.$id, $data, $ttl);
}
}
}
/**
* Multi-layer universal cache controller for Cotonti
*
* @property-read bool $mem_available Memory storage availability flag
*/
class Cache
{
/**
* Persistent cache underlayer driver.
* Stores disk-only cache entries. Use it for large objects, which you don't want to put
* into memory cache.
* @var Static_cache_driver
*/
public $disk;
/**
* Intermediate database cache driver.
* It is recommended to use memory cache for particular objects rather than DB cache.
* @var Db_cache_driver
*/
public $db;
/**
* Mutable top-layer shared memory driver.
* Is FALSE if memory cache is not available
* @var Temporary_cache_driver
*/
public $mem;
/**
* Page cache driver.
* Is FALSE if page cache is disabled
* @var Page_cache
*/
public $page;
/**
* Event bindings
* @var array
*/
private $bindings;
/**
* A flag to apply binding changes before termination
* @var bool
*/
private $resync_on_exit = false;
/**
* Selected memory driver
* @var string
*/
private $selected_drv = '';
/**
* Initializes Page cache for early page caching
*/
public function __construct()
{
global $cfg;
$this->page = new Page_cache($cfg['cache_dir'], $cfg['dir_perms']);
}
/**
* Performs actions before script termination
*/
public function __destruct()
{
if ($this->resync_on_exit)
{
$this->resync_bindings();
}
}
/**
* Property handler
* @param string $name Property name
* @return mixed Property value
*/
public function __get($name)
{
switch ($name)
{
case 'mem_available':
return $this->mem !== FALSE;
break;
case 'mem_driver':
return $this->selected_drv;
break;
default:
return null;
break;
}
}
/**
* Initializes the rest Cache components when the sources are available
*/
public function init()
{
global $cfg, $cot_cache_autoload, $cot_cache_drivers, $cot_cache_bindings, $env;
$this->disk = new File_cache($cfg['cache_dir']);
$this->db = new MySQL_cache();
$cot_cache_autoload = is_array($cot_cache_autoload)
? array_merge(array('system', 'cot', $env['ext']), $cot_cache_autoload)
: array('system', 'cot', $env['ext']);
$this->db->get_all($cot_cache_autoload);
$cfg['cache_drv'] .= '_driver';
if (in_array($cfg['cache_drv'], $cot_cache_drivers))
{
$selected = $cfg['cache_drv'];
}
if (!empty($selected))
{
$mem = new $selected();
// Some drivers may be enabled but without variable cache
$info = $mem->get_info();
if ($info['max'] > 1024)
{
$this->mem = $mem;
$this->selected_drv = $selected;
}
}
else
{
$this->mem = false;
}
if (!$cot_cache_bindings)
{
$this->resync_bindings();
}
else
{
unset($cot_cache_bindings);
}
}
/**
* Rereads bindings from database
*/
private function resync_bindings()
{
// global $db, $db_cache_bindings;
$this->bindings = array();
// $sql = $db->query("SELECT * FROM `$db_cache_bindings`");
// while ($row = $sql->fetch())
// {
// $this->bindings[$row['c_event']][] = array('id' => $row['c_id'], 'realm' => $row['c_realm']);
// }
// $sql->closeCursor();
// $this->db->store('cot_cache_bindings', $this->bindings, 'system');
}
/**
* Binds an event to automatic cache field invalidation
* @param string $event Event name
* @param string $id Cache entry id
* @param string $realm Cache realm name
* @param int $type Storage type, one of COT_CACHE_TYPE_* values
* @return bool TRUE on success, FALSE on error
*/
public function bind($event, $id, $realm = COT_DEFAULT_REALM, $type = COT_CACHE_TYPE_DEFAULT)
{
global $db, $db_cache_bindings;
$c_event = $db->quote($event);
$c_id = $db->quote($id);
$c_realm = $db->quote($realm);
$c_type = (int) $type;
$db->query("INSERT INTO `$db_cache_bindings` (c_event, c_id, c_realm, c_type)
VALUES ($c_event, $c_id, $c_realm, $c_type)");
$res = $db->affectedRows == 1;
if ($res)
{
$this->resync_on_exit = true;
}
return $res;
}
/**
* Binds multiple cache fields to events, all represented as an associative array
* Binding keys:
* event - name of the event the field is binded to
* id - cache object id
* realm - cache realm name
* type - cache storage type, one of COT_CACHE_TYPE_* constants
* @param array $bindings An indexed array of bindings.
* Each binding is an associative array with keys: event, realm, id, type.
* @return int Number of bindings added
*/
public function bind_array($bindings)
{
global $db, $db_cache_bindings;
$q = "INSERT INTO `$db_cache_bindings` (c_event, c_id, c_realm, c_type) VALUES ";
$i = 0;
foreach ($bindings as $entry)
{
$c_event = $db->prep($entry['event']);
$c_id = $db->prep($entry['id']);
$c_realm = $db->prep($entry['realm']);
$c_type = (int) $entry['type'];
$comma = $i == 0 ? '' : ',';
$q .= $comma."('$c_event', '$c_id', '$c_realm', $c_type)";
}
$db->query($q);
$res = $db->affectedRows;
if ($res > 0)
{
$this->resync_on_exit = true;
}
return $res;
}
/**
* Clears all cache entries
* @param int $type Cache storage type:
* COT_CACHE_TYPE_ALL, COT_CACHE_TYPE_DB, COT_CACHE_TYPE_DISK, COT_CACHE_TYPE_MEMORY.
* @return bool
*/
public function clear($type = COT_CACHE_TYPE_ALL)
{
$res = true;
switch ($type)
{
case COT_CACHE_TYPE_DB:
$res = $this->db->clear();
break;
case COT_CACHE_TYPE_DISK:
$res = $this->disk->clear();
break;
case COT_CACHE_TYPE_MEMORY:
if ($this->mem)
{
$res = $this->mem->clear();
}
break;
case COT_CACHE_TYPE_PAGE:
$res = $this->disk->clear();
break;
default:
if ($this->mem)
{
$res &= $this->mem->clear();
}
$res &= $this->db->clear();
$res &= $this->disk->clear();
}
return $res;
}
/**
* Clears cache in specific realm
* @param string $realm Realm name
* @param int $type Cache storage type:
* COT_CACHE_TYPE_ALL, COT_CACHE_TYPE_DB, COT_CACHE_TYPE_DISK, COT_CACHE_TYPE_MEMORY.
*/
public function clear_realm($realm = COT_DEFAULT_REALM, $type = COT_CACHE_TYPE_ALL)
{
switch ($type)
{
case COT_CACHE_TYPE_DB:
$this->db->clear($realm);
break;
case COT_CACHE_TYPE_DISK:
$this->disk->clear($realm);
break;
case COT_CACHE_TYPE_MEMORY:
if ($this->mem)
{
$this->mem->clear($realm);
}
break;
case COT_CACHE_TYPE_PAGE:
$this->page->clear($realm);
break;
default:
if ($this->mem)
{
$this->mem->clear($realm);
}
$this->db->clear($realm);
$this->disk->clear($realm);
$this->page->clear($realm);
}
}
/**
* Returns information about memory driver usage
* @return array Usage information
*/
public function get_info()
{
if ($this->mem)
{
return $this->mem->get_info();
}
else
{
return array();
}
}
/**
* Invalidates cache cells which were binded to the event.
* @param string $event Event name
* @return int Number of cells cleaned
*/
public function trigger($event)
{
$cnt = 0;
if (isset($this->bindings[$event]) && count($this->bindings[$event]) > 0)
{
foreach ($this->bindings[$event] as $cell)
{
switch ($cell['type'])
{
case COT_CACHE_TYPE_DISK:
$this->disk->remove($cell['id'], $cell['realm']);
break;
case COT_CACHE_TYPE_DB:
$this->db->remove($cell['id'], $cell['realm']);
break;
case COT_CACHE_TYPE_MEMORY:
if ($this->mem)
{
$this->mem->remove($cell['id'], $cell['realm']);
}
break;
case COT_CACHE_TYPE_PAGE:
$this->page->clear($cell['realm'] . '/' . $cell['id']);
break;
default:
if ($this->mem)
{
$this->mem->remove($cell['id'], $cell['realm']);
}
$this->disk->remove($cell['id'], $cell['realm']);
$this->db->remove($cell['id'], $cell['realm']);
$this->page->clear($cell['realm'] . '/' . $cell['id']);
}
$cnt++;
}
}
return $cnt;
}
/**
* Removes event/cache bindings
* @param string $realm Realm name (required)
* @param string $id Object identifier. Optional, if not specified, all bindings from the realm are removed.
* @return int Number of bindings removed
*/
public function unbind($realm, $id = '')
{
global $db, $db_cache_bindings;
$c_realm = $db->quote($realm);
$q = "DELETE FROM `$db_cache_bindings` WHERE c_realm = $c_realm";
if (!empty($id))
{
$c_id = $db->quote($id);
$q .= " AND c_id = $c_id";
}
$db->query($q);
$res = $db->affectedRows;
if ($res > 0)
{
$this->resync_on_exit = true;
}
return $res;
}
}
| Velm14/dribascorp | system/cache.php | PHP | bsd-3-clause | 35,088 |
/*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk-pre411/LICENSE.txt for details.
*/
package gov.nih.nci.system.webservice;
import gov.nih.nci.system.applicationservice.ApplicationService;
import gov.nih.nci.system.client.proxy.ListProxy;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import gov.nih.nci.system.query.nestedcriteria.NestedCriteriaPath;
import gov.nih.nci.system.util.ClassCache;
import gov.nih.nci.system.webservice.util.WSUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.xml.rpc.ServiceException;
import org.apache.log4j.Logger;
import org.springframework.remoting.jaxrpc.ServletEndpointSupport;
public class WSQueryImpl extends ServletEndpointSupport implements WSQuery{
private static Logger log = Logger.getLogger(WSQueryImpl.class);
private static ApplicationService applicationService;
private static ClassCache classCache;
private static int resultCountPerQuery = 1000;
public void destroy() {
applicationService = null;
classCache = null;
resultCountPerQuery = 0;
}
protected void onInit() throws ServiceException {
classCache = (ClassCache)getWebApplicationContext().getBean("ClassCache");
applicationService = (ApplicationService)getWebApplicationContext().getBean("ApplicationServiceImpl");
Properties systemProperties = (Properties) getWebApplicationContext().getBean("SystemProperties");
try {
String count = systemProperties.getProperty("resultCountPerQuery");
log.debug("resultCountPerQuery: " + count);
if (count != null) {
resultCountPerQuery = Integer.parseInt(count);
}
} catch (Exception ex) {
log.error("Exception initializing resultCountPerQuery: ", ex);
throw new ServiceException("Exception initializing resultCountPerQuery: ", ex);
}
}
public int getTotalNumberOfRecords(String targetClassName, Object criteria) throws Exception{
return getNestedCriteriaResultSet(targetClassName, criteria, 0).size();
}
public List queryObject(String targetClassName, Object criteria) throws Exception
{
return query(targetClassName,criteria,0);
}
public List query(String targetClassName, Object criteria, int startIndex) throws Exception
{
List results = new ArrayList();
results = getNestedCriteriaResultSet(targetClassName, criteria, startIndex);
List alteredResults = alterResultSet(results);
return alteredResults;
}
private List getNestedCriteriaResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{
List results = new ArrayList();
String searchClassName = getSearchClassName(targetClassName);
try
{
if(searchClassName != null && searchCriteria != null){
List<Object> paramList = new ArrayList<Object>();
paramList.add(searchCriteria);
NestedCriteriaPath pathCriteria = new NestedCriteriaPath(targetClassName,paramList);
results = applicationService.query(pathCriteria, startIndex, targetClassName);
}
else{
throw new Exception("Invalid arguments passed over to the server");
}
}
catch(Exception e)
{
log.error("WSQuery caught an exception: ", e);
throw e;
}
return results;
}
public List getAssociation(Object source, String associationName, int startIndex) throws Exception
{
List results = new ArrayList();
String targetClassName = source.getClass().getName();
log.debug("targetClassName: " + targetClassName);
String hql = "select obj."+associationName+" from "+targetClassName+" obj where obj = ?";
log.debug("hql: " + hql);
List<Object> params = new ArrayList<Object>();
params.add(source);
HQLCriteria criteria = new HQLCriteria(hql,params);
results = getHQLResultSet(targetClassName, criteria, startIndex);
List alteredResults = alterResultSet(results);
return alteredResults;
}
private List getHQLResultSet(String targetClassName, Object searchCriteria, int startIndex) throws Exception{
List results = new ArrayList();
String searchClassName = getSearchClassName(targetClassName);
try
{
if(searchClassName != null && searchCriteria != null){
results = applicationService.query(searchCriteria, startIndex, targetClassName);
}
else{
throw new Exception("Invalid arguments passed over to the server");
}
}
catch(Exception e)
{
log.error("WSQuery caught an exception: ", e);
throw e;
}
return results;
}
private String getSearchClassName(String targetClassName)throws Exception {
String searchClassName = "";
if(targetClassName.indexOf(",")>0){
StringTokenizer st = new StringTokenizer(targetClassName, ",");
while(st.hasMoreTokens()){
String className = st.nextToken();
String validClassName = classCache.getQualifiedClassName(className);
log.debug("validClassName: " + validClassName);
searchClassName += validClassName + ",";
}
searchClassName = searchClassName.substring(0,searchClassName.lastIndexOf(","));
} else{
searchClassName = classCache.getQualifiedClassName(targetClassName);
}
if(searchClassName == null){
throw new Exception("Invalid class name: " + targetClassName);
}
return searchClassName;
}
private List alterResultSet(List results) {
List objList;
if (results instanceof ListProxy)
{
ListProxy listProxy = (ListProxy)results;
objList = listProxy.getListChunk();
}
else
{
objList = results;
}
WSUtils util = new WSUtils();
objList = (List)util.convertToProxy(null, objList);
return objList;
}
}
| NCIP/cacore-sdk-pre411 | SDK4/system/src/gov/nih/nci/system/webservice/WSQueryImpl.java | Java | bsd-3-clause | 5,667 |
package au.gov.ga.geodesy.sitelog.domain.model;
import javax.validation.constraints.Size;
/**
* http://sopac.ucsd.edu/ns/geodesy/doc/igsSiteLog/contact/2004/baseContactLib.xsd:contactType
*/
public class Contact {
private Integer id;
@Size(max = 200)
protected String name;
@Size(max = 200)
protected String telephonePrimary;
@Size(max = 200)
protected String telephoneSecondary;
@Size(max = 200)
protected String fax;
@Size(max = 200)
protected String email;
@SuppressWarnings("unused")
private Integer getId() {
return id;
}
@SuppressWarnings("unused")
private void setId(Integer id) {
this.id = id;
}
/**
* Return name.
*/
public String getName() {
return name;
}
/**
* Set name.
*/
public void setName(String value) {
this.name = value;
}
/**
* Return primary telephone number.
*/
public String getTelephonePrimary() {
return telephonePrimary;
}
/**
* Set primary telephone number.
*/
public void setTelephonePrimary(String value) {
this.telephonePrimary = value;
}
/**
* Return secondary telephone number.
*/
public String getTelephoneSecondary() {
return telephoneSecondary;
}
/**
* Set secondary telephone number.
*/
public void setTelephoneSecondary(String value) {
this.telephoneSecondary = value;
}
/**
* Return fax number.
*/
public String getFax() {
return fax;
}
/**
* Set fax number.
*/
public void setFax(String value) {
this.fax = value;
}
/**
* Return email address.
*/
public String getEmail() {
return email;
}
/**
* Set email address.
*/
public void setEmail(String value) {
this.email = value;
}
}
| GeoscienceAustralia/geodesy-sitelog-domain | src/main/java/au/gov/ga/geodesy/sitelog/domain/model/Contact.java | Java | bsd-3-clause | 1,834 |
namespace Leaderboard
{
public enum SortBy
{
None,
Score,
Rank
}
}
| jalaziz/leaderboard-csharp | Leaderboard/SortBy.cs | C# | bsd-3-clause | 106 |
#region License Header
// /*******************************************************************************
// * Open Behavioral Health Information Technology Architecture (OBHITA.org)
// *
// * Redistribution and use in source and binary forms, with or without
// * modification, are permitted provided that the following conditions are met:
// * * Redistributions of source code must retain the above copyright
// * notice, this list of conditions and the following disclaimer.
// * * Redistributions in binary form must reproduce the above copyright
// * notice, this list of conditions and the following disclaimer in the
// * documentation and/or other materials provided with the distribution.
// * * Neither the name of the <organization> nor the
// * names of its contributors may be used to endorse or promote products
// * derived from this software without specific prior written permission.
// *
// * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ******************************************************************************/
#endregion
namespace ProCenter.Mvc.Infrastructure.Service.Completeness
{
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Domain.AssessmentModule.Lookups;
using ProCenter.Domain.AssessmentModule.Metadata;
using ProCenter.Service.Message.Assessment;
using ProCenter.Service.Message.Common.Lookups;
using ProCenter.Service.Message.Metadata;
#endregion
/// <summary>The completeness model validtor provider class.</summary>
public class CompletenessModelValidtorProvider : ModelValidatorProvider
{
#region Public Methods and Operators
/// <summary>
/// Gets a list of validators.
/// </summary>
/// <param name="metadata">The metadata.</param>
/// <param name="context">The context.</param>
/// <returns>
/// A list of validators.
/// </returns>
public override IEnumerable<ModelValidator> GetValidators ( ModelMetadata metadata, ControllerContext context )
{
if ( metadata.PropertyName != null &&
context is ViewContext &&
(context.Controller.ViewData.Model is IValidateCompleteness || context.Controller.ViewData.Model is SectionDto ))
{
var viewContext = context as ViewContext;
if ( viewContext.ViewData != null )
{
if ( ( metadata.ContainerType == typeof(ItemDto) && metadata.PropertyName == "Value" ) ||
( metadata.ContainerType == typeof(LookupDto) && metadata.PropertyName == "Code" ) )
{
// only care about value
var sectionDto = context.Controller.ViewData.Model is IValidateCompleteness ? (context.Controller.ViewData.Model as IValidateCompleteness).CurrentSectionDto
: context.Controller.ViewData.Model as SectionDto;
if ( sectionDto != null )
{
var propertyParts = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldName ( metadata.PropertyName ).Split ( '.' );
if ( propertyParts.Length == 2 )
{
var index = propertyParts[0].IndexOf ( "_Value", StringComparison.Ordinal );
if ( index != -1 )
{
var code = propertyParts[0].Substring ( 0, index );
var itemDto = GetItemDtoByCode ( sectionDto, code );
if ( itemDto != null )
{
var metadataItemDto = itemDto.Metadata.FindMetadataItem<RequiredForCompletenessMetadataItem> ();
if ( metadataItemDto != null )
{
yield return new CompletenessModelValidator ( metadata, context, metadataItemDto.CompletenessCategory );
}
}
}
}
}
}
}
}
}
#endregion
#region Methods
private static ItemDto GetItemDtoByCode ( IContainItems sectionDto, string code )
{
foreach ( var itemDto in sectionDto.Items )
{
if ( itemDto.ItemDefinitionCode == code && itemDto.ItemType == ItemType.Question.CodedConcept.Code )
{
return itemDto;
}
if ( itemDto.Items != null )
{
foreach (
var childItemDto in
itemDto.Items.Where ( childItemDto => childItemDto.ItemDefinitionCode == code && childItemDto.ItemType == ItemType.Question.CodedConcept.Code ) )
{
return childItemDto;
}
foreach (var containerDto in itemDto.Items.Where(i => i.ItemType != ItemType.Question.CodedConcept.Code).OfType<IContainItems> ())
{
var childItem = GetItemDtoByCode ( containerDto, code );
if ( childItem != null )
{
return childItem;
}
}
}
}
return null;
}
#endregion
}
} | OBHITA/PROCenter | ProCenter.Mvc.Infrastructure/Service/Completeness/CompletenessModelValidtorProvider.cs | C# | bsd-3-clause | 6,717 |
"""
Commands that are available from the connect screen.
"""
import re
import traceback
from django.conf import settings
from src.players.models import PlayerDB
from src.objects.models import ObjectDB
from src.server.models import ServerConfig
from src.comms.models import Channel
from src.utils import create, logger, utils, ansi
from src.commands.default.muxcommand import MuxCommand
from src.commands.cmdhandler import CMD_LOGINSTART
# limit symbol import for API
__all__ = ("CmdUnconnectedConnect", "CmdUnconnectedCreate", "CmdUnconnectedQuit", "CmdUnconnectedLook", "CmdUnconnectedHelp", "Magic")
CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE
CONNECTION_SCREEN = ""
try:
CONNECTION_SCREEN = ansi.parse_ansi(utils.string_from_module(CONNECTION_SCREEN_MODULE))
except Exception:
pass
if not CONNECTION_SCREEN:
CONNECTION_SCREEN = "\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid."
class Magic(MuxCommand):
"""
Hidden command for the web client's magic cookie authenticator.
"""
key = "magic"
def func(self):
session = self.caller
player = PlayerDB.objects.player_search(self.lhs)
if len(player) != 1:
player = None
else:
player = player[0]
if player.name.lower() != self.lhs.lower():
player=None
pswd = None
if player:
pswd = self.rhs == player.db.magic_cookie
if not (player and pswd):
# No playername or password match
session.msg("Could not verify Magic Cookie. Please email the server administrator for assistance.")
return
# Check IP and/or name bans
bans = ServerConfig.objects.conf("server_bans")
if bans and (any(tup[0]==player.name for tup in bans)
or
any(tup[2].match(session.address[0]) for tup in bans if tup[2])):
# this is a banned IP or name!
string = "{rYou have been banned and cannot continue from here."
string += "\nIf you feel this ban is in error, please email an admin.{x"
session.msg(string)
session.execute_cmd("quit")
return
session.sessionhandler.login(session, player)
class Connect(MuxCommand):
"""
Connect to the game.
Usage (at login screen):
connect playername password
connect "player name" "pass word"
Use the create command to first create an account before logging in.
If you have spaces in your name, enclose it in quotes.
"""
key = "connect"
aliases = ["conn", "con", "co"]
locks = "cmd:all()" # not really needed
def func(self):
"""
Uses the Django admin api. Note that unlogged-in commands
have a unique position in that their func() receives
a session object instead of a source_object like all
other types of logged-in commands (this is because
there is no object yet before the player has logged in)
"""
session = self.caller
args = self.args
# extract quoted parts
parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()]
if len(parts) == 1:
# this was (hopefully) due to no quotes being found
parts = parts[0].split(None, 1)
if len(parts) != 2:
session.msg("\n\r Usage (without <>): connect <name> <password>")
return
playername, password = parts
# Match account name and check password
player = PlayerDB.objects.player_search(playername)
if len(player) != 1:
player = None
else:
player = player[0]
if player.name.lower() != playername.lower():
player=None
pswd = None
if player:
pswd = player.check_password(password)
if not (player and pswd):
# No playername or password match
string = "Wrong login information given.\nIf you have spaces in your name or "
string += "password, don't forget to enclose it in quotes. Also capitalization matters."
string += "\nIf you are new you should first create a new account "
string += "using the 'create' command."
session.msg(string)
return
# Check IP and/or name bans
bans = ServerConfig.objects.conf("server_bans")
if bans and (any(tup[0]==player.name for tup in bans)
or
any(tup[2].match(session.address[0]) for tup in bans if tup[2])):
# this is a banned IP or name!
string = "{rYou have been banned and cannot continue from here."
string += "\nIf you feel this ban is in error, please email an admin.{x"
session.msg(string)
session.execute_cmd("quit")
return
# actually do the login. This will call all other hooks:
# session.at_init()
# if character:
# at_first_login() # only once
# at_pre_login()
# player.at_post_login() - calls look if no character is set
# character.at_post_login() - this calls look command by default
session.sessionhandler.login(session, player)
class Create(MuxCommand):
"""
Create a new account.
Usage (at login screen):
create <playername> <password>
create "player name" "pass word"
This creates a new player account.
If you have spaces in your name, enclose it in quotes.
"""
key = "create"
aliases = ["cre", "cr"]
locks = "cmd:all()"
def func(self):
"Do checks and create account"
session = self.caller
args = self.args.strip()
# extract quoted parts
parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()]
if len(parts) == 1:
# this was (hopefully) due to no quotes being found
parts = parts[0].split(None, 1)
if len(parts) != 2:
string = "\n Usage (without <>): create <name> <password>"
string += "\nIf <name> or <password> contains spaces, enclose it in quotes."
session.msg(string)
return
playername, password = parts
print "playername '%s', password: '%s'" % (playername, password)
# sanity checks
if not re.findall('^[\w. @+-]+$', playername) or not (0 < len(playername) <= 30):
# this echoes the restrictions made by django's auth module (except not
# allowing spaces, for convenience of logging in).
string = "\n\r Playername can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only."
session.msg(string)
return
# strip excessive spaces in playername
playername = re.sub(r"\s+", " ", playername).strip()
if PlayerDB.objects.filter(user__username__iexact=playername) or PlayerDB.objects.filter(username__iexact=playername):
# player already exists (we also ignore capitalization here)
session.msg("Sorry, there is already a player with the name '%s'." % playername)
return
if not re.findall('^[\w. @+-]+$', password) or not (3 < len(password)):
string = "\n\r Password should be longer than 3 characers. Letters, spaces, digits and @\.\+\-\_ only."
string += "\nFor best security, make it longer than 8 characters. You can also use a phrase of"
string += "\nmany words if you enclose the password in quotes."
session.msg(string)
return
# everything's ok. Create the new player account.
try:
default_home = ObjectDB.objects.get_id(settings.CHARACTER_DEFAULT_HOME)
typeclass = settings.BASE_CHARACTER_TYPECLASS
permissions = settings.PERMISSION_PLAYER_DEFAULT
try:
new_character = create.create_player(playername, None, password,
permissions=permissions,
character_typeclass=typeclass,
character_location=default_home,
character_home=default_home)
except Exception:
session.msg("There was an error creating the default Character/Player:\n%s\n If this problem persists, contact an admin.")
return
new_player = new_character.player
# This needs to be called so the engine knows this player is logging in for the first time.
# (so it knows to call the right hooks during login later)
utils.init_new_player(new_player)
# join the new player to the public channel
pchanneldef = settings.CHANNEL_PUBLIC
if pchanneldef:
pchannel = Channel.objects.get_channel(pchanneldef[0])
if not pchannel.connect_to(new_player):
string = "New player '%s' could not connect to public channel!" % new_player.key
logger.log_errmsg(string)
# allow only the character itself and the player to puppet this character (and Immortals).
new_character.locks.add("puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)" %
(new_character.id, new_player.id))
# If no description is set, set a default description
if not new_character.db.desc:
new_character.db.desc = "This is a Player."
# tell the caller everything went well.
string = "A new account '%s' was created. Welcome!"
if " " in playername:
string += "\n\nYou can now log in with the command 'connect \"%s\" <your password>'."
else:
string += "\n\nYou can now log with the command 'connect %s <your password>'."
session.msg(string % (playername, playername))
except Exception:
# We are in the middle between logged in and -not, so we have to handle tracebacks
# ourselves at this point. If we don't, we won't see any errors at all.
string = "%s\nThis is a bug. Please e-mail an admin if the problem persists."
session.msg(string % (traceback.format_exc()))
logger.log_errmsg(traceback.format_exc())
class CmdUnconnectedQuit(MuxCommand):
"""
We maintain a different version of the quit command
here for unconnected players for the sake of simplicity. The logged in
version is a bit more complicated.
"""
key = "quit"
aliases = ["q", "qu"]
locks = "cmd:all()"
def func(self):
"Simply close the connection."
session = self.caller
session.msg("Good bye! Disconnecting ...")
session.session_disconnect()
class CmdUnconnectedLook(MuxCommand):
"""
This is an unconnected version of the look command for simplicity.
This is called by the server and kicks everything in gear.
All it does is display the connect screen.
"""
key = CMD_LOGINSTART
aliases = ["look", "l"]
locks = "cmd:all()"
def func(self):
"Show the connect screen."
self.caller.msg(CONNECTION_SCREEN)
class CmdUnconnectedHelp(MuxCommand):
"""
This is an unconnected version of the help command,
for simplicity. It shows a pane of info.
"""
key = "help"
aliases = ["h", "?"]
locks = "cmd:all()"
def func(self):
"Shows help"
string = \
"""
You are not yet logged into the game. Commands available at this point:
{wcreate, connect, look, help, quit{n
To login to the system, you need to do one of the following:
{w1){n If you have no previous account, you need to use the 'create'
command.
{wcreate Anna c67jHL8p{n
Note that if you use spaces in your name, you have to enclose in quotes.
{wcreate "Anna the Barbarian" c67jHL8p{n
It's always a good idea (not only here, but everywhere on the net)
to not use a regular word for your password. Make it longer than
6 characters or write a passphrase.
{w2){n If you have an account already, either because you just created
one in {w1){n above or you are returning, use the 'connect' command:
{wconnect Anna c67jHL8p{n
(Again, if there are spaces in the name you have to enclose it in quotes).
This should log you in. Run {whelp{n again once you're logged in
to get more aid. Hope you enjoy your stay!
You can use the {wlook{n command if you want to see the connect screen again.
"""
self.caller.msg(string)
| TaliesinSkye/evennia | wintersoasis-master/commands/unloggedin.py | Python | bsd-3-clause | 12,835 |
package edu.cmu.minorthird.text.gui;
import edu.cmu.minorthird.text.FancyLoader;
import edu.cmu.minorthird.text.TextLabels;
import edu.cmu.minorthird.util.gui.ControlledViewer;
import edu.cmu.minorthird.util.gui.VanillaViewer;
import edu.cmu.minorthird.util.gui.Viewer;
import edu.cmu.minorthird.util.gui.ViewerFrame;
import edu.cmu.minorthird.util.gui.ZoomedViewer;
/**
* View the contents of a bunch of spans, using the util.gui.Viewer framework.
*
* <p> Hopefully this will evolve into a cleaner version of the
* TextBaseViewer, TextBaseEditor, etc suite. It replaces an earlier
* attempt, the SpanLooperViewer.
*
* @author William Cohen
*/
public class ZoomingTextLabelsViewer extends ZoomedViewer{
static final long serialVersionUID=20080202L;
public ZoomingTextLabelsViewer(TextLabels labels){
Viewer zoomedOut=new ControlledViewer(new TextLabelsViewer(labels),new MarkupControls(labels));
Viewer zoomedIn=new VanillaViewer("[Empty TextBase]");
if(labels.getTextBase().size()>0){
zoomedIn=new SpanViewer(labels,labels.getTextBase().documentSpanIterator().next());
}
this.setSubViews(zoomedOut,zoomedIn);
}
// test case
public static void main(String[] argv){
try{
final TextLabels labels=FancyLoader.loadTextLabels(argv[0]);
new ViewerFrame(argv[0],new ZoomingTextLabelsViewer(labels));
}catch(Exception e){
e.printStackTrace();
System.out.println("Usage: labelKey");
}
}
}
| TeamCohen/MinorThird | src/main/java/edu/cmu/minorthird/text/gui/ZoomingTextLabelsViewer.java | Java | bsd-3-clause | 1,434 |
<?php
$modules["recurringinvoices"]["name"] = "Recurring Invoices";
$modules["recurringinvoices"]["version"] = "1.01";
$modules["recurringinvoices"]["description"] =
"This module adds the ability to repeat invoices on a scheduled basis.";
$modules["recurringinvoices"]["requirements"] =
"phpBMS Core v0.9 or greater; BMS module v0.9 or greater; phpBMS Scheduler activated through cron or other scheduling program.";
?> | eandbsoftware/phpbms | modules/recurringinvoices/install/version.php | PHP | bsd-3-clause | 434 |
/* eslint-disable no-underscore-dangle */
export default function ({
client,
filterQuery,
mustContain,
busy,
encodeQueryAsString,
}) {
return {
listUsers(query) {
const params = filterQuery(
query,
'text',
'limit',
'offset',
'sort',
'sortdir'
);
return busy(
client._.get('/user', {
params,
})
);
},
createUser(user) {
const expected = [
'login',
'email',
'firstName',
'lastName',
'password',
'admin',
];
const params = filterQuery(user, ...expected);
const { missingKeys, promise } = mustContain(user, ...expected);
return missingKeys
? promise
: busy(client._.post(`/user${encodeQueryAsString(params)}`));
},
changePassword(old, newPassword) {
const params = {
old,
new: newPassword,
};
return busy(client._.put(`/user/password${encodeQueryAsString(params)}`));
},
resetPassword(email) {
const params = {
email,
};
return busy(
client._.delete('/user/password', {
params,
})
);
},
deleteUser(id) {
return busy(client._.delete(`/user/${id}`));
},
getUser(id) {
return busy(client._.get(`/user/${id}`));
},
updateUser(user) {
const expected = ['email', 'firstName', 'lastName', '_id'];
const params = filterQuery(user, ...expected.slice(0, 3)); // Remove '_id'
const { missingKeys, promise } = mustContain(user, ...expected);
return missingKeys
? promise
: busy(client._.put(`/user/${user._id}${encodeQueryAsString(params)}`));
},
};
}
| Kitware/paraviewweb | src/IO/Girder/CoreEndpoints/user.js | JavaScript | bsd-3-clause | 1,750 |
module.exports = (function () {
var TypeChecker = Cactus.Util.TypeChecker;
var JSON = Cactus.Util.JSON;
var stringify = JSON.stringify;
var object = Cactus.Addon.Object;
var collection = Cactus.Data.Collection;
var gettype = TypeChecker.gettype.bind(TypeChecker);
return {
"null and undefined" : function () {
var o = new TypeChecker({
type : "number"
});
exception(/Expected "number", but got undefined \(type "undefined"\)/,
o.parse.bind(o, undefined));
exception(/Expected "number", but got null \(type "null"\)/,
o.parse.bind(o, null));
},
"required values" : function () {
var o = new TypeChecker({
required : false,
type : "boolean"
});
equal(true, o.parse(true));
o.parse(null);
},
"default value" : function () {
var o = new TypeChecker({
type : "number",
defaultValue : 3
});
assert.eql(3, o.parse(null));
assert.eql(4, o.parse(4));
o = new TypeChecker({
type : {
a : {
type : "number",
defaultValue : 1
}
}
});
var h = o.parse({ a : 2 });
assert.eql(2, o.parse({ a : 2}).a);
assert.eql(1, o.parse({ a : null }).a);
assert.eql(1, o.parse({}).a);
o = new TypeChecker({
type : {
x : {
type : "boolean",
defaultValue : false
}
}
});
eql({ x : true }, o.parse({ x : true }));
eql({ x : false }, o.parse({ x : false }));
eql({ x : false }, o.parse({}));
// When not passing bool properties.
o = new TypeChecker({
type : {
b : { type : "boolean", defaultValue : false }
}
});
eql({ b : false }, o.parse({}));
// Default values with incorrect types should have special error message (always throw error)
exception(/Expected "boolean", but got 1/, function () {
return new TypeChecker({
type : "boolean",
defaultValue : 1
});
});
},
defaultValueFunc : function () {
var o = new TypeChecker({
defaultValueFunc : function () { return 1; },
type : "number"
});
assert.strictEqual(1, o.parse(null));
o = new TypeChecker({
type : {
a : {
defaultValueFunc : function () { return 2; },
type : "number"
}
}
});
assert.strictEqual(2, o.parse({ a : null }).a);
assert.strictEqual(2, o.parse({}).a);
// defaultValueFunc return value must match type.
exception(/expected "boolean", but got 1/i,
function () {
return new TypeChecker({
defaultValueFunc : function () { return 1; },
type : "boolean"
}).parse(undefined);
});
exception(/expected "boolean", but got 1/i,
function () {
return new TypeChecker({
type : {
a : {
defaultValueFunc : function () { return 1; },
type : "boolean"
}
}
}).parse({});
});
},
validators : function () {
var o = new TypeChecker({
type : "number",
validators : [{
func : function (v) {
return v > 0;
}
}]
});
o.parse(1);
o.parse(0, false);
eql({
"" : ["Validation failed: got 0."]
}, o.getErrors());
// Validation error message.
o = new TypeChecker({
type : "number",
validators : [{
func : function (v) {
return v > 0;
},
message : "Expected positive number."
}]
});
o.parse(1);
exception(/TypeChecker: Error: Expected positive number./,
o.parse.bind(o, 0));
eql({
"" : ["Expected positive number."]
}, o.getErrors());
// Multiple ordered validators.
o = new TypeChecker({
type : "number",
validators : [{
func : function (v) {
return v > -1;
},
message : "Expected number bigger than -1."
}, {
func : function (v) {
return v < 1;
},
message : "Expected number smaller than 1."
}]
});
o.parse(0);
exception(/Expected number bigger than -1/i, o.parse.bind(o, -1));
exception(/Expected number smaller than 1/i, o.parse.bind(o, 1));
o = new TypeChecker({
type : "number",
validators : [{
func : function (v) {
return v > 0;
},
message : "Expected number bigger than 0."
}, {
func : function (v) {
return v > 1;
},
message : "Expected number bigger than 1."
}]
});
o.parse(2);
exception(/bigger than 0.+ bigger than 1./i, o.parse.bind(o, 0));
},
"simple interface" : function () {
var o = TypeChecker.simple("number");
o.parse(1);
o = TypeChecker.simple(["number"]);
o.parse([1]);
o = TypeChecker.simple({
a : "number",
b : "boolean"
});
o.parse({
a : 1,
b : true
});
o = TypeChecker.simple({
a : ["number"]
});
o.parse({
a : [1]
});
o = TypeChecker.simple({
a : {
b : "boolean"
}
});
o.parse({
a : {
b : true
}
});
// Classes.
Class("X");
o = TypeChecker.simple({ _type : X });
o.parse(new X());
o = TypeChecker.simple({
a : { _type : X }
});
o.parse({
a : new X()
});
},
errorHash : function () {
var o = TypeChecker.simple("string");
exception(/Nothing parsed/i, o.hasErrors.bind(o));
exception(/Nothing parsed/i, o.getErrors.bind(o));
o.parse("x", false);
exception(/No errors exist/, o.getErrors.bind(o));
o.parse(1, false);
ok(o.hasErrors());
var errors = o.getErrors();
ok(o.hasErrorsFor(""));
not(o.hasErrorsFor("foo"));
eql({ "" : ['Expected "string", but got 1 (type "number")'] }, o.getErrors());
o = TypeChecker.simple({
a : "number",
b : "number"
});
o.parse({
a : "x",
b : true
}, false);
ok(o.hasErrors());
eql({
a : ['Expected "number", but got "x" (type "string")'],
b : ['Expected "number", but got true (type "boolean")']
}, o.getErrors());
ok(o.hasErrorsFor("a"));
ok(o.hasErrorsFor("b"));
eql(['Expected "number", but got "x" (type "string")'], o.getErrorsFor("a"));
eql(['Expected "number", but got true (type "boolean")'], o.getErrorsFor("b"));
o = new TypeChecker({
type : "number",
validators : [{
func : Function.returning(false),
message : "false"
}]
});
o.parse(1, false);
eql({
"" : ["false"]
}, o.getErrors());
// Errors for array validators.
o = new TypeChecker({
type : {
p : {
type : "string",
validators : [{
func : Function.returning(false),
message : "Error #1."
}, {
func : Function.returning(false),
message : "Error #2."
}]
}
}
});
o.parse({ p : "" }, false);
eql({ p : ["Error #1.", "Error #2."] }, o.getErrors());
// When Error is thrown, there should be a hash property with the error
// messages as well.
o = new TypeChecker({
type : "string"
});
o.parse(1, false);
assert.throws(o.parse.bind(o, 1), function (e) {
assert.ok(/expected "string".+got 1 \(type "number"\)/i.test(e.message));
assert.ok("hash" in e, "Missing hash property");
eql({
"" : ['Expected "string", but got 1 (type "number")']
}, e.hash);
return true;
});
},
validators2 : function () {
// Validators should run only if all other validations pass.
var ran = false;
var o = new TypeChecker({
type : "number",
defaultValue : 0,
validators : [{
func : function (v) {
ran = true;
return v === 0;
},
message : "Only way to validate is to send null or 0."
}]
});
o.parse(0);
o.parse("x", false);
eql({
"" : [
'Expected "number", but got "x" (type "string")',
'Only way to validate is to send null or 0.'
]
}, o.getErrors());
// Do not run validators if constraints fail.
o.parse("x", false);
assert.strictEqual(1, object.count(o.getErrors()));
o.parse(-1, false);
eql({
"" : ["Only way to validate is to send null or 0."]
}, o.getErrors());
// Default value should be applied before validation as well.
ran = false;
assert.strictEqual(0, o.parse(null));
assert.ok(ran, "Validation did not run.");
},
"predefined validations" : function () {
var o = new TypeChecker({
type : "number",
validators : ["natural"]
});
o.parse(1);
o.parse(0);
o.parse(-1, false);
eql({ "" : ["Expected natural number."] }, o.getErrors());
o = new TypeChecker({
type : "number",
validators : ["positive"]
});
o.parse(1);
o.parse(0, false);
eql({ "" : ["Expected positive number."] }, o.getErrors());
o = new TypeChecker({
type : "number",
validators : ["negative"]
});
o.parse(-1);
o.parse(0, false);
eql({ "" : ["Expected negative number."] }, o.getErrors());
o = new TypeChecker({
type : "number",
validators : ["x"]
});
exception(/Undefined built in validator "x"/i, o.parse.bind(o, 1));
o = new TypeChecker({
type : {
a : {
type : "number",
validators : ["x"]
}
}
});
exception(/Undefined built in validator "x"/i, o.parse.bind(o, { a : 1 }));
o = new TypeChecker({
type : "string",
validators : ["non empty string"]
});
o.parse("x");
o.parse("", false);
eql({ "" : ["Expected non-empty string."] }, o.getErrors());
},
T_Array : function () {
eql([{ type : "string" }], gettype(new TypeChecker.types.T_Array({ type : "string" })));
var o = new TypeChecker({
type : [{ type : "number" }]
});
eql([1, 2], o.parse([1, 2]));
eql([], o.parse([]));
exception(/Expected \[\{"type":"number"\}\], but got "a" \(type "string"\)/i, o.parse.bind(o, "a"));
exception(/error in property "0": expected "number", but got "a" \(type "string"\)/i, o.parse.bind(o, ["a"]));
exception(/error in property "1": expected "number", but got true \(type "boolean"\)/i, o.parse.bind(o, [1, true]));
exception(/error in property "0": expected "number", but got "a"[\s\S]+error in property "1": expected "number", but got true/i, o.parse.bind(o, ["a", true]));
// Nesting of arrays.
var o = new TypeChecker({
type : [{ type : [{ type : "number" }] }]
});
eql([[1, 2]], o.parse([[1, 2]]));
exception(/^TypeChecker: Error in property "0": expected \[\{"type":"number"\}\], but got 1/i,
o.parse.bind(o, [1, [2, 3]]));
exception(/^TypeChecker: Error in property "1.1": expected "number", but got true/i,
o.parse.bind(o, [[1], [2, true]]));
eql([[]], o.parse([[]]));
eql([], o.parse([]));
// Optional arrays.
o = new TypeChecker({
type : [{
type : "mixed"
}],
defaultValue : []
});
o.parse(null);
// Optional array in hash.
o = new TypeChecker({
type : {
a : {
type : [{
type : "number"
}],
defaultValue : []
}
}
});
o.parse({});
},
T_Primitive : function () {
var o = new TypeChecker({
type : "string"
});
assert.eql("aoeu", o.parse("aoeu"));
exception(/expected "string", but got 1 \(type "number"\)/i, o.parse.bind(o, 1));
exception(/expected "string", but got true \(type "boolean"\)/i, o.parse.bind(o, true));
o = new TypeChecker({
type : "number"
});
assert.eql(100, o.parse(100));
exception(/^TypeChecker: Error: Expected "number", but got "1" \(type "string"\)$/, o.parse.bind(o, "1"));
// Default values
o = new TypeChecker({
type : "boolean",
defaultValue : false
});
o.parse(true);
o.parse(false);
not(o.parse(null));
},
T_Enumerable : function () {
var o = new TypeChecker({
enumerable : [1,2,3]
});
eql(1, o.parse(1));
o.parse(2);
o.parse(3);
exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 0$/, o.parse.bind(o, 0));
exception(/^TypeChecker: Error: Expected a value in \[1,2,3\], but got 4$/, o.parse.bind(o, 4));
eql({ enumerable : [1,2,3] }, gettype(new TypeChecker.types.T_Enumerable([1, 2, 3])));
},
"T_Union" : function () {
var o = new TypeChecker({
union : ["string", "number"]
});
eql(1, o.parse(1));
eql("x", o.parse("x"));
exception(/Expected a Union/, o.parse.bind(o, true));
eql({ union : [
{ type : "string"},
{ type : "number" }
]}, gettype(new TypeChecker.types.T_Union([
{ type : "string" },
{ type : "number" }
])));
},
"T_Instance" : function () {
var Foo2 = Class("Foo2", {});
Class("Bar", {
isa : Foo2
});
var o = new TypeChecker({
type : Foo2
});
var foo2 = new Foo2();
equal(foo2, o.parse(foo2));
o.parse(new Bar());
exception(/Expected an instance of "Foo2", but got value <1> \(type "number"\)/,
o.parse.bind(o, 1));
Class("Baz");
exception(/Expected an instance of "Foo2", but got value <a Baz> \(type "Baz"\)$/,
o.parse.bind(o, new Baz()));
// Non-Joose classes.
function Bax() {
}
function Qux() {
}
Qux.extend(Bax);
o = new TypeChecker({
type : Bax
});
o.parse(new Bax());
o.parse(new Qux());
function Qax() {
}
Qax.prototype.toString = function () {
return "my Qax";
};
exception(/Expected an instance of "Bax", but got value <1> \(type "number"\)/,
o.parse.bind(o, 1));
exception(/Expected an instance of "Bax", but got value <my Qax> \(type "Qax"\)$/,
o.parse.bind(o, new Qax()));
// Anonymous classes.
var F = function () {};
var G = function () {};
o = new TypeChecker({
type : F
});
G.extend(F);
o.parse(new F());
o.parse(new G());
var H = function () {};
H.prototype.toString = Function.returning("my H");
exception(/Expected an instance of "anonymous type", but got value <1>/,
o.parse.bind(o, 1));
exception(/Expected an instance of "anonymous type", but got value <my H> \(type "anonymous type"\)/i,
o.parse.bind(o, new H()));
function I() {}
equal(I, gettype(new TypeChecker.types.T_Instance(I)).type);
},
T_Hash : function () {
var o = new TypeChecker({ x : { type : "boolean" } });
eql({ x : { type : "boolean" } }, gettype(new TypeChecker.types.T_Hash({ x : { type : "boolean" } })));
o = new TypeChecker({
type : {
a : { type : "number" },
b : { type : "boolean" }
}
});
eql({ a : 1, b : true }, o.parse({ a : 1, b : true }));
o = new TypeChecker({
type : {
a : { type : "number" },
b : { type : "boolean" }
}
});
exception(/Expected \{"a":\{"type":"number"\},"b":\{"type":"boolean"\}\}, but got 1/i,
o.parse.bind(o, 1));
exception(/Error in property "a": expected "number", but got "2"/i,
o.parse.bind(o, { a : "2", b : true }));
exception(/Error in property "a": expected "number", but got "2"[\s\S]+Error in property "b": expected "boolean", but got "2"/i,
o.parse.bind(o, { a : "2", b : "2" }));
exception(/Error in property "b": Missing property/,
o.parse.bind(o, { a : 1 }));
exception(/Error in property "c": Property lacks definition/i,
o.parse.bind(o, { a : 1, b : true, c : "1" }));
// With required specified.
o = new TypeChecker({
type : {
name : { type : "string", required : true }
}
});
assert.throws(o.parse.bind(o, {}), function (e) {
assert.ok(/"name": Missing property/.test(e.message));
return true;
});
// Non-required properties.
o = new TypeChecker({
type : {
a : { type : "number", required : false },
b : { type : "boolean", required : false }
}
});
eql({ a : 1, b : false },
o.parse({ a : 1, b : false }));
var h = o.parse({ a : 1, b : undefined });
ok(!("b" in h));
h = o.parse({ a : 1, b : null });
equal(null, h.b);
h = o.parse({ a : undefined, b : undefined });
ok(object.isEmpty(h));
h = o.parse({});
ok(object.isEmpty(h));
// Skip properties not in definition.
o = new TypeChecker({
allowUndefined : true,
type : {
a : { type : "number" }
}
});
o.parse({}, false);
eql({
a : ["Missing property"]
}, o.getErrors());
o.parse({ a : 1 });
o.parse({ a : 1, b : 2 });
o.parse({ b : 2 }, false);
eql({
a : ["Missing property"]
}, o.getErrors());
// Remove skipped props that are undefined.
eql({ a : 1 }, o.parse({ a : 1 }));
},
T_Map : function () {
var o = new TypeChecker({
map : true,
type : "number"
});
eql({ a : 1, b : 1 }, o.parse({ a : 1, b : 1 }));
o.parse({ a : 1, b : false }, false);
eql({ b : ['Expected "number", but got false (type "boolean")'] }, o.getErrors());
},
"T_Mixed" : function () {
var o = new TypeChecker({
type : "mixed"
});
equal(true, o.parse(true));
o.parse("");
o.parse({});
eql([], o.parse([]));
ok(null === o.parse(null));
ok(undefined === o.parse(undefined));
equal("mixed", gettype(new TypeChecker.types.T_Mixed()));
},
"typeof" : function () {
var t = TypeChecker.typeof.bind(TypeChecker);
equal("number", t(1));
equal("boolean", t(true));
equal("undefined", t(undefined));
equal("null", t(null));
equal("Function", t(function () {}));
equal("Object", t({}));
equal("Array", t([]));
Class("JooseClass");
equal("JooseClass", t(new JooseClass()));
function MyClass() {}
equal("MyClass", t(new MyClass()));
var AnonymousClass = function () {};
equal("anonymous type", t(new AnonymousClass));
},
"BUILD errors" : function () {
exception(/Must be a hash/i,
function () { return new TypeChecker(); });
exception(/May only specify one of required, defaultValue and defaultValueFunc/i,
function () { return new TypeChecker({ required : true, defaultValue : 1 }); });
// required or defaultValue or defaultValueFunc
},
helpers : function () {
//var tc = new TypeChecker({
// type : "number",
// validators : [{
// func : function (o, helpers) {
// return !!helpers;
// },
// message : "helpers == false"
// }]
//});
//tc.parse(1, true, true);
//tc.parse(1, false, true);
//eql({
// "" : ["helpers == false"]
//}, tc.getErrors());
},
"recursive definition" : function () {
var o = new TypeChecker({
type : {
// type
type : {
required : false,
type : "mixed",
validators : [{
func : function (v) {
if (typeof v === "string") {
return collection.hasValue(["string", "number", "object", "function", "boolean", "mixed"], v);
} else if (v instanceof Array) {
// Flat check only.
return v.length === 1;
} else if (v instanceof Object) {
// Flat check only.
return true;
}
return false;
}
}]
},
required : {
type : "boolean",
defaultValue : true
},
defaultValue : {
required : false,
type : "mixed"
},
defaultValueFunc : {
required : false,
type : Function
},
validators : {
type : [{
type : {
func : { type : Function },
message : { type : "string" }
}
}],
defaultValue : []
},
enumerable : {
required : false,
type : Array
},
allowUndefined : {
defaultValue : false,
type : "boolean"
}
}
});
o.parse({
type : "string"
});
o.parse({
type : "number"
});
o.parse({
required : false,
type : "number"
});
o.parse({
defaultValue : 3,
type : "number"
});
o.parse({
defaultValue : true,
type : "boolean"
});
o.parse({
defaultValue : 4,
type : "mixed"
});
o.parse({
defaultValue : {},
type : "mixed"
});
o.parse({
defaultValueFunc : function () { return 1; },
type : "number"
});
o.parse({
type : [{ type : "string" }]
});
o.parse({
type : "mixed",
validators : [{
func : Function.empty,
message : "msg"
}]
});
o.parse({
type : "number",
enumerable : [1,2,3]
});
o.parse({
type : {}
});
o.parse({
allowUndefined : true,
type : {}
});
}
};
})();
| bergmark/Cactus | module/Core/lib/Util/Util.TypeChecker.test.js | JavaScript | bsd-3-clause | 22,955 |
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "mcp_accesslogs".
*
* @property integer $user_id
* @property string $browser
* @property string $ip
* @property string $session
* @property string $intime
* @property string $outtime
*/
class McpAccesslogs extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'mcp_accesslogs';
}
/**
* @return \yii\db\Connection the database connection used by this AR class.
*/
public static function getDb()
{
return Yii::$app->get('oldcmsdb');
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id'], 'integer'],
[['intime', 'outtime'], 'safe'],
[['browser'], 'string', 'max' => 255],
[['ip'], 'string', 'max' => 30],
[['session'], 'string', 'max' => 40]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'user_id' => 'user,s reference',
'browser' => 'Browser',
'ip' => 'Ip',
'session' => 'Session',
'intime' => 'Intime',
'outtime' => 'Outtime',
];
}
}
| rajanishtimes/partnerapi | common/models/McpAccesslogs.php | PHP | bsd-3-clause | 1,297 |
/**
* Swedish translation for bootstrap-wysihtml5
*/
(function($){
$.fn.wysihtml5.locale["sv-SE"] = {
font_styles: {
normal: "Normal Text",
h1: "Rubrik 1",
h2: "Rubrik 2",
h3: "Rubrik 3"
},
emphasis: {
bold: "Fet",
italic: "Kursiv",
underline: "Understruken"
},
lists: {
unordered: "Osorterad lista",
ordered: "Sorterad lista",
outdent: "Minska indrag",
indent: "Öka indrag"
},
link: {
insert: "Lägg till länk",
cancel: "Avbryt"
},
image: {
insert: "Lägg till Bild",
cancel: "Avbryt"
},
html: {
edit: "Redigera HTML"
},
colours: {
black: "Svart",
silver: "Silver",
gray: "Grå",
maroon: "Kastaniebrun",
red: "Röd",
purple: "Lila",
green: "Grön",
olive: "Olivgrön",
navy: "Marinblå",
blue: "Blå",
orange: "Orange"
}
};
}(jQuery));
| landasystems/tamanharapan | backend/extensions/bootstrap/assets/js/locales/bootstrap-wysihtml5.sv-SE.js | JavaScript | bsd-3-clause | 1,185 |
<?php
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
<div class="bodyParser">
<?=$this->render('table', [
'dataHistory' => $dataHistory
])?>
</div>
| TexToro/parser-on-yii2 | frontend/views/site/index.php | PHP | bsd-3-clause | 189 |
// Benchpress: A collection of micro-benchmarks.
var allResults = [ ];
// -----------------------------------------------------------------------------
// F r a m e w o r k
// -----------------------------------------------------------------------------
function Benchmark(string, run) {
this.string = string;
this.run = run;
}
// Run each benchmark for two seconds and count number of iterations.
function time(benchmark) {
var elapsed = 0;
var start = new Date();
for (var n = 0; elapsed < 2000; n++) {
benchmark.run();
elapsed = new Date() - start;
}
var usec = (elapsed * 1000) / n;
allResults.push(usec);
print('Time (' + benchmark.string + '): ' + Math.floor(usec) + ' us.');
}
function error(string) {
print(string);
}
// -----------------------------------------------------------------------------
// L o o p
// -----------------------------------------------------------------------------
function loop() {
var sum = 0;
for (var i = 0; i < 200; i++) {
for (var j = 0; j < 100; j++) {
sum++;
}
}
if (sum != 20000) error("Wrong result: " + sum + " should be: 20000");
}
var Loop = new Benchmark("Loop", loop);
// -----------------------------------------------------------------------------
// M a i n
// -----------------------------------------------------------------------------
time(Loop);
var logMean = 0;
for (var i = 0; i < allResults.length; i++)
logMean += Math.log(allResults[i]);
logMean /= allResults.length;
print("Geometric mean: " + Math.round(Math.pow(Math.E, logMean)) + " us.");
| daejunpark/jsaf | benchmarks/v8_v1/units/loop.js | JavaScript | bsd-3-clause | 1,571 |
'use strict';
myApp.controller('editProfileController', ['$scope', '$state', 'loadingMaskService', 'CONSTANTS', '$uibModal', '$log', '$rootScope', '$http', function ($scope, $state, loadingMaskService, CONSTANTS, $uibModal, $log, $rootScope, $http) {
var userInfo = JSON.parse(localStorage.getItem(CONSTANTS.LOCAL_STORAGE_KEY));
$scope.email = userInfo.email;
$scope.date = userInfo.birthDate;
$scope.firstName = userInfo.firstName;
$scope.lastName = userInfo.lastName;
$scope.relations = userInfo.relations;
$scope.relationOptions = ['Мама', 'Отец', 'Брат'];
$scope.submit = function () {
if ($scope.editProfileForm.$valid && $scope.editProfileForm.$dirty) { // if form is valid
var userInfo = {
email: $scope.email,
birthDate: $scope.date,
firstName: $scope.firstName,
lastName: $scope.lastName,
relations: $scope.relations
};
$http({
method: 'POST',
url: '/editRelation',
data: {
email: userInfo.email,
relations: $scope.relations
}
}).then(function successCallback(response) {
localStorage.setItem(CONSTANTS.LOCAL_STORAGE_KEY, JSON.stringify(userInfo));
loadingMaskService.sendRequest();
$state.go('mainPageState.userProfile');
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
$rootScope.$on('relationsUpdated', function(event, relations){
$scope.relations = relations;
});
$rootScope.$on('relationRemoved', function(event, relations){
$scope.relations = relations;
});
$scope.removeRelation = function(index) {
var modalInstance = $uibModal.open({
templateUrl: 'app/pages/src/editProfilePage/src/tpl/removeRelationConfirm.tpl.html',
controller: 'removeRelationController',
resolve: {
index: function () {
return index
}
}
});
}
$scope.open = function (size) {
var modalInstance = $uibModal.open({
templateUrl: 'app/pages/src/editProfilePage/src/tpl/addARelation.tpl.html',
controller: 'addRelationController'
});
};
}]); | yslepianok/analysis_site | views/tests/app/pages/src/editProfilePage/src/editProfileController.js | JavaScript | bsd-3-clause | 2,590 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage StrikeIron
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Service\StrikeIron;
use SoapHeader,
SoapClient;
/**
* @category Zend
* @package Zend_Service
* @subpackage StrikeIron
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Base
{
/**
* Configuration options
* @param array
*/
protected $options = array(
'username' => null,
'password' => null,
'client' => null,
'options' => null,
'headers' => null,
'wsdl' => null,
);
/**
* Output headers returned by the last call to SOAPClient->_soapCall()
* @param array
*/
protected $outputHeaders = array();
/**
* Class constructor
*
* @param array $options Key/value pair options
* @throws Exception\RuntimeException if soap extension is not loaded
*/
public function __construct($options = array())
{
if (!extension_loaded('soap')) {
throw new Exception\RuntimeException('SOAP extension is not enabled');
}
$this->options = array_merge($this->options, $options);
$this->initSoapHeaders();
$this->initSoapClient();
}
/**
* Proxy method calls to the SOAPClient instance, transforming method
* calls and responses for convenience.
*
* @param string $method Method name
* @param array $params Parameters for method
* @return mixed Result
* @throws Exception\RuntimeException if error occurs during soap call
*/
public function __call($method, $params)
{
// prepare method name and parameters for soap call
list($method, $params) = $this->transformCall($method, $params);
$params = isset($params[0]) ? array($params[0]) : array();
// make soap call, capturing the result and output headers
try {
$result = $this->options['client']->__soapCall(
$method,
$params,
$this->options['options'],
$this->options['headers'],
$this->outputHeaders
);
} catch (\Exception $e) {
$message = get_class($e) . ': ' . $e->getMessage();
throw new Exception\RuntimeException($message, $e->getCode(), $e);
}
// transform/decorate the result and return it
$result = $this->transformResult($result, $method, $params);
return $result;
}
/**
* Initialize the SOAPClient instance
*
* @return void
*/
protected function initSoapClient()
{
if (!isset($this->options['options'])) {
$this->options['options'] = array();
}
if (!isset($this->options['client'])) {
$this->options['client'] = new SoapClient(
$this->options['wsdl'],
$this->options['options']
);
}
}
/**
* Initialize the headers to pass to SOAPClient->_soapCall()
*
* @return void
* @throws Exception\RuntimeException if invalid headers encountered
*/
protected function initSoapHeaders()
{
// validate headers and check if LicenseInfo was given
$foundLicenseInfo = false;
if (isset($this->options['headers'])) {
if (! is_array($this->options['headers'])) {
$this->options['headers'] = array($this->options['headers']);
}
foreach ($this->options['headers'] as $header) {
if (!$header instanceof SoapHeader) {
throw new Exception\RuntimeException('Header must be instance of SoapHeader');
} elseif ($header->name == 'LicenseInfo') {
$foundLicenseInfo = true;
break;
}
}
} else {
$this->options['headers'] = array();
}
// add default LicenseInfo header if a custom one was not supplied
if (!$foundLicenseInfo) {
$this->options['headers'][] = new SoapHeader(
'http://ws.strikeiron.com',
'LicenseInfo',
array(
'RegisteredUser' => array(
'UserID' => $this->options['username'],
'Password' => $this->options['password'],
),
)
);
}
}
/**
* Transform a method name or method parameters before sending them
* to the remote service. This can be useful for inflection or other
* transforms to give the method call a more PHP-like interface.
*
* @see __call()
* @param string $method Method name called from PHP
* @param mixed $param Parameters passed from PHP
* @return array [$method, $params] for SOAPClient->_soapCall()
*/
protected function transformCall($method, $params)
{
return array(ucfirst($method), $params);
}
/**
* Transform the result returned from a method before returning
* it to the PHP caller. This can be useful for transforming
* the SOAPClient returned result to be more PHP-like.
*
* The $method name and $params passed to the method are provided to
* allow decisions to be made about how to transform the result based
* on what was originally called.
*
* @see __call()
* @param $result Raw result returned from SOAPClient_>__soapCall()
* @param $method Method name that was passed to SOAPClient->_soapCall()
* @param $params Method parameters that were passed to SOAPClient->_soapCall()
* @return mixed Transformed result
*/
protected function transformResult($result, $method, $params)
{
$resultObjectName = "{$method}Result";
if (isset($result->$resultObjectName)) {
$result = $result->$resultObjectName;
}
if (is_object($result)) {
$result = new Decorator($result, $resultObjectName);
}
return $result;
}
/**
* Get the WSDL URL for this service.
*
* @return string
*/
public function getWsdl()
{
return $this->options['wsdl'];
}
/**
* Get the SOAP Client instance for this service.
*/
public function getSoapClient()
{
return $this->options['client'];
}
/**
* Get the StrikeIron output headers returned with the last method response.
*
* @return array
*/
public function getLastOutputHeaders()
{
return $this->outputHeaders;
}
/**
* Get the StrikeIron subscription information for this service.
* If any service method was recently called, the subscription info
* should have been returned in the SOAP headers so it is cached
* and returned from the cache. Otherwise, the getRemainingHits()
* method is called as a dummy to get the subscription info headers.
*
* @param boolean $now Force a call to getRemainingHits instead of cache?
* @param string $queryMethod Method that will cause SubscriptionInfo header to be sent
* @return Decorator Decorated subscription info
* @throws Exception\RuntimeException if no subscription information headers present
*/
public function getSubscriptionInfo($now = false, $queryMethod = 'GetRemainingHits')
{
if ($now || empty($this->outputHeaders['SubscriptionInfo'])) {
$this->$queryMethod();
}
// capture subscription info if returned in output headers
if (isset($this->outputHeaders['SubscriptionInfo'])) {
$info = (object)$this->outputHeaders['SubscriptionInfo'];
$subscriptionInfo = new Decorator($info, 'SubscriptionInfo');
} else {
$msg = 'No SubscriptionInfo header found in last output headers';
throw new Exception\RuntimeException($msg);
}
return $subscriptionInfo;
}
}
| dineshkummarc/zf2 | library/Zend/Service/StrikeIron/Base.php | PHP | bsd-3-clause | 8,807 |
<?php $deleteStyle = isset($this->existing) ? 'inline' : 'none' ?>
<?php $addStyle = $deleteStyle == 'inline' ? 'none' : 'inline' ?>
<div id="watch-controls">
</div>
<h2><?php $this->o($this->notes[0]->title);?></h2>
<?php $note = null; ?>
<?php foreach ($this->notes as $note): ?>
<div class="note">
<div class="note-header">
<form class="inline right" method="post" action="<?php echo build_url('note', 'delete')?>" onsubmit="return confirm('Are you sure?')">
<input type="hidden" value="<?php echo $note->id?>" name="id" />
<input title="Delete" type="image" src="<?php echo resource('images/delete.png')?>" />
</form>
<h4><?php $this->o($note->title)?></h4>
<span class="note-by">By <?php $this->o($note->userid.' on '.$note->created)?></span>
</div>
<div class="note-body"><?php $this->bbCode($note->note);?></div>
</div>
<?php endforeach; ?>
<div class="note">
<form method="post" action="<?php echo build_url('note', 'add');?>">
<input type="hidden" value="<?php echo $note->attachedtotype?>" name="attachedtotype"/>
<input type="hidden" value="<?php echo $note->attachedtoid?>" name="attachedtoid"/>
<input type="hidden" value="<?php echo za()->getUser()->getUsername()?>" name="userid"/>
<p>
<label for="note-title">Title:</label>
<input class="input" type="text" name="title" id="note-title" value="Re: <?php $this->o(str_replace('Re: ', '', $note->title))?>" />
</p>
<p>
<label for="note-note">Note:</label>
<textarea name="note" rows="5" cols="45" id="note-note"></textarea>
</p>
<p>
<input type="submit" class="abutton" value="Add Note" />
<a class="abutton" style="display: <?php echo $deleteStyle?>;" id="delete-watch" href="#" onclick="$.get('<?php echo build_url('note', 'deletewatch')?>', {id:'<?php echo $this->itemid?>', type:'<?php echo $this->itemtype?>'}, function() {$('#delete-watch').hide();$('#add-watch').show(); }); return false;">Remove Watch</a>
<a class="abutton" style="display: <?php echo $addStyle?>;" id="add-watch" href="#" onclick="$.get('<?php echo build_url('note', 'addwatch')?>', {id:'<?php echo $this->itemid?>', type:'<?php echo $this->itemtype?>'}, function() {$('#add-watch').hide();$('#delete-watch').show(); }); return false;">Add Watch</a>
</p>
</form>
</div> | nyeholt/relapse | views/note/thread-view.php | PHP | bsd-3-clause | 2,359 |
/**
* \file PancakeNode.hpp
*
*
*
* \author eaburns
* \date 18-01-2010
*/
#include "search/Node.hpp"
#include "pancake/PancakeTypes.hpp"
#include "pancake/PancakeState.hpp"
#if !defined(_PANCAKE_NODE_H_)
#define _PANCAKE_NODE_H_
typedef Node<PancakeState14, PancakeCost> PancakeNode14;
#endif // !_PANCAKE_NODE_H_
| bradlarsen/switchback | src/pancake/PancakeNode.hpp | C++ | bsd-3-clause | 326 |
//-----------------------------------------------------------------------------
//Cortex
//Copyright (c) 2010-2015, Joshua Scoggins
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Cortex nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL Joshua Scoggins BE LIABLE FOR ANY
//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.IO;
using System.Linq;
namespace Cortex.Operation
{
public class GraphVizLink : IGraphLink
{
private int from, to;
private string label;
public int From { get { return from; } }
public int To { get { return to; } }
public string Label { get { return label; } }
public GraphVizLink(int from, int to, string label)
{
this.from = from;
this.to = to;
this.label = label;
}
public override string ToString()
{
if(label.Equals(string.Empty))
return string.Format("node{0} -> node{1};", From, To);
else
return string.Format("node{0} -> node{1} {2};", From, To, Label);
}
}
public class GraphVizGraphBuilder : GraphBuilder<GraphVizLink>
{
public GraphVizGraphBuilder() : base() { }
public override void Link(int i0, int i1, string label)
{
Add(new GraphVizLink(i0,i1,label));
}
public override string ToString(string graphName)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("digraph {0}\n",graphName);
sb.AppendLine("{");
foreach(var v in this)
sb.AppendLine(v.ToString());
sb.AppendLine("}");
return sb.ToString();
}
}
}
| DrItanium/Cortex | Operation/GraphVizSpecificBuilder.cs | C# | bsd-3-clause | 3,083 |
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkPluginActivator.h"
#include "DicomEventHandler.h"
#include <service/event/ctkEventConstants.h>
#include <ctkDictionary.h>
#include <mitkLogMacros.h>
#include <mitkDataNode.h>
#include <mitkIDataStorageService.h>
#include <service/event/ctkEventAdmin.h>
#include <ctkServiceReference.h>
#include <mitkRenderingManager.h>
#include <QVector>
#include "mitkImage.h"
#include <mitkContourModelSet.h>
#include <mitkDICOMFileReaderSelector.h>
#include <mitkDICOMDCMTKTagScanner.h>
#include <mitkDICOMEnums.h>
#include <mitkDICOMTagsOfInterestHelper.h>
#include <mitkDICOMProperty.h>
#include <mitkPropertyNameHelper.h>
#include "mitkBaseDICOMReaderService.h"
#include <mitkRTDoseReaderService.h>
#include <mitkRTPlanReaderService.h>
#include <mitkRTStructureSetReaderService.h>
#include <mitkRTConstants.h>
#include <mitkIsoDoseLevelCollections.h>
#include <mitkIsoDoseLevelSetProperty.h>
#include <mitkIsoDoseLevelVectorProperty.h>
#include <mitkDoseImageVtkMapper2D.h>
#include <mitkRTUIConstants.h>
#include <mitkIsoLevelsGenerator.h>
#include <mitkDoseNodeHelper.h>
#include <vtkSmartPointer.h>
#include <vtkMath.h>
#include <mitkTransferFunction.h>
#include <mitkTransferFunctionProperty.h>
#include <mitkRenderingModeProperty.h>
#include <mitkLocaleSwitch.h>
#include <mitkIOUtil.h>
#include <berryIPreferencesService.h>
#include <berryIPreferences.h>
#include <berryPlatform.h>
#include <ImporterUtil.h>
DicomEventHandler::DicomEventHandler()
{
}
DicomEventHandler::~DicomEventHandler()
{
}
void DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent)
{
QStringList listOfFilesForSeries;
listOfFilesForSeries = ctkEvent.getProperty("FilesForSeries").toStringList();
if (!listOfFilesForSeries.isEmpty())
{
//for rt data, if the modality tag isn't defined or is "CT" the image is handled like before
if(ctkEvent.containsProperty("Modality") &&
(ctkEvent.getProperty("Modality").toString().compare("RTDOSE",Qt::CaseInsensitive) == 0 ||
ctkEvent.getProperty("Modality").toString().compare("RTSTRUCT",Qt::CaseInsensitive) == 0 ||
ctkEvent.getProperty("Modality").toString().compare("RTPLAN", Qt::CaseInsensitive) == 0))
{
QString modality = ctkEvent.getProperty("Modality").toString();
if(modality.compare("RTDOSE",Qt::CaseInsensitive) == 0)
{
auto doseReader = mitk::RTDoseReaderService();
doseReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front()));
std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = doseReader.Read();
if (!readerOutput.empty()){
mitk::Image::Pointer doseImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer());
mitk::DataNode::Pointer doseImageNode = mitk::DataNode::New();
doseImageNode->SetData(doseImage);
doseImageNode->SetName("RTDose");
if (doseImage != nullptr)
{
std::string sopUID;
if (mitk::GetBackwardsCompatibleDICOMProperty(0x0008, 0x0016, "dicomseriesreader.SOPClassUID", doseImage->GetPropertyList(), sopUID))
{
doseImageNode->SetName(sopUID);
};
berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService();
berry::IPreferences::Pointer prefNode = prefService->GetSystemPreferences()->Node(mitk::RTUIConstants::ROOT_DOSE_VIS_PREFERENCE_NODE_ID.c_str());
if (prefNode.IsNull())
{
mitkThrow() << "Error in preference interface. Cannot find preset node under given name. Name: " << prefNode->ToString().toStdString();
}
//set some specific colorwash and isoline properties
bool showColorWashGlobal = prefNode->GetBool(mitk::RTUIConstants::GLOBAL_VISIBILITY_COLORWASH_ID.c_str(), true);
//Set reference dose property
double referenceDose = prefNode->GetDouble(mitk::RTUIConstants::REFERENCE_DOSE_ID.c_str(), mitk::RTUIConstants::DEFAULT_REFERENCE_DOSE_VALUE);
mitk::ConfigureNodeAsDoseNode(doseImageNode, mitk::GenerateIsoLevels_Virtuos(), referenceDose, showColorWashGlobal);
ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();
mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);
mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();
dataStorage->Add(doseImageNode);
mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage);
}
}//END DOSE
}
else if(modality.compare("RTSTRUCT",Qt::CaseInsensitive) == 0)
{
auto structReader = mitk::RTStructureSetReaderService();
structReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front()));
std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = structReader.Read();
if (readerOutput.empty()){
MITK_ERROR << "No structure sets were created" << endl;
}
else {
std::vector<mitk::DataNode::Pointer> modelVector;
ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();
mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);
mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();
for (const auto& aStruct : readerOutput){
mitk::ContourModelSet::Pointer countourModelSet = dynamic_cast<mitk::ContourModelSet*>(aStruct.GetPointer());
mitk::DataNode::Pointer structNode = mitk::DataNode::New();
structNode->SetData(countourModelSet);
structNode->SetProperty("name", aStruct->GetProperty("name"));
structNode->SetProperty("color", aStruct->GetProperty("contour.color"));
structNode->SetProperty("contour.color", aStruct->GetProperty("contour.color"));
structNode->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false));
structNode->SetVisibility(true, mitk::BaseRenderer::GetInstance(
mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget0")));
structNode->SetVisibility(false, mitk::BaseRenderer::GetInstance(
mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1")));
structNode->SetVisibility(false, mitk::BaseRenderer::GetInstance(
mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget2")));
structNode->SetVisibility(true, mitk::BaseRenderer::GetInstance(
mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget3")));
dataStorage->Add(structNode);
}
mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(dataStorage);
}
}
else if (modality.compare("RTPLAN", Qt::CaseInsensitive) == 0)
{
auto planReader = mitk::RTPlanReaderService();
planReader.SetInput(ImporterUtil::getUTF8String(listOfFilesForSeries.front()));
std::vector<itk::SmartPointer<mitk::BaseData> > readerOutput = planReader.Read();
if (!readerOutput.empty()){
//there is no image, only the properties are interesting
mitk::Image::Pointer planDummyImage = dynamic_cast<mitk::Image*>(readerOutput.at(0).GetPointer());
mitk::DataNode::Pointer planImageNode = mitk::DataNode::New();
planImageNode->SetData(planDummyImage);
planImageNode->SetName("RTPlan");
ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();
mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);
mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();
dataStorage->Add(planImageNode);
}
}
}
else
{
mitk::StringList seriesToLoad;
QStringListIterator it(listOfFilesForSeries);
while (it.hasNext())
{
seriesToLoad.push_back(ImporterUtil::getUTF8String(it.next()));
}
//Get Reference for default data storage.
ctkServiceReference serviceReference = mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();
mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);
mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();
std::vector<mitk::BaseData::Pointer> baseDatas = mitk::IOUtil::Load(seriesToLoad.front());
for (const auto &data : baseDatas)
{
mitk::DataNode::Pointer node = mitk::DataNode::New();
node->SetData(data);
std::string nodeName = mitk::DataNode::NO_NAME_VALUE();
auto nameDataProp = data->GetProperty("name");
if (nameDataProp.IsNotNull())
{ //if data has a name property set by reader, use this name
nodeName = nameDataProp->GetValueAsString();
}
else
{ //reader didn't specify a name, generate one.
nodeName = mitk::GenerateNameFromDICOMProperties(node);
}
node->SetName(nodeName);
dataStorage->Add(node);
}
}
}
else
{
MITK_INFO << "There are no files for the current series";
}
}
void DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& /*ctkEvent*/)
{
}
void DicomEventHandler::SubscribeSlots()
{
ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>();
if (ref)
{
ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref);
ctkDictionary properties;
properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/ADD";
eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties);
properties[ctkEventConstants::EVENT_TOPIC] = "org/mitk/gui/qt/dicom/DELETED";
eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties);
}
}
| fmilano/mitk | Plugins/org.mitk.gui.qt.dicom/src/internal/DicomEventHandler.cpp | C++ | bsd-3-clause | 11,194 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// godoc: Go Documentation Server
// Web server tree:
//
// http://godoc/ main landing page
// http://godoc/doc/ serve from $GOROOT/doc - spec, mem, etc.
// http://godoc/src/ serve files from $GOROOT/src; .go gets pretty-printed
// http://godoc/cmd/ serve documentation about commands
// http://godoc/pkg/ serve documentation about packages
// (idea is if you say import "compress/zlib", you go to
// http://godoc/pkg/compress/zlib)
//
// Command-line interface:
//
// godoc packagepath [name ...]
//
// godoc compress/zlib
// - prints doc for package compress/zlib
// godoc crypto/block Cipher NewCMAC
// - prints doc for Cipher and NewCMAC in package crypto/block
// +build !appengine
package main
import (
"archive/zip"
_ "expvar" // to serve /debug/vars
"flag"
"fmt"
"go/build"
"log"
"net/http"
"net/http/httptest"
_ "net/http/pprof" // to serve /debug/pprof/*
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"golang.org/x/tools/godoc"
"golang.org/x/tools/godoc/analysis"
"golang.org/x/tools/godoc/static"
"golang.org/x/tools/godoc/vfs"
"golang.org/x/tools/godoc/vfs/gatefs"
"golang.org/x/tools/godoc/vfs/mapfs"
"golang.org/x/tools/godoc/vfs/zipfs"
)
const defaultAddr = ":6060" // default webserver address
var (
// file system to serve
// (with e.g.: zip -r go.zip $GOROOT -i \*.go -i \*.html -i \*.css -i \*.js -i \*.txt -i \*.c -i \*.h -i \*.s -i \*.png -i \*.jpg -i \*.sh -i favicon.ico)
zipfile = flag.String("zip", "", "zip file providing the file system to serve; disabled if empty")
// file-based index
writeIndex = flag.Bool("write_index", false, "write index to a file; the file name must be specified with -index_files")
analysisFlag = flag.String("analysis", "", `comma-separated list of analyses to perform (supported: type, pointer). See http://golang.org/lib/godoc/analysis/help.html`)
// network
httpAddr = flag.String("http", "", "HTTP service address (e.g., '"+defaultAddr+"')")
serverAddr = flag.String("server", "", "webserver address for command line searches")
// layout control
html = flag.Bool("html", false, "print HTML in command-line mode")
srcMode = flag.Bool("src", false, "print (exported) source in command-line mode")
allMode = flag.Bool("all", false, "include unexported identifiers in command-line mode")
urlFlag = flag.String("url", "", "print HTML for named URL")
// command-line searches
query = flag.Bool("q", false, "arguments are considered search queries")
verbose = flag.Bool("v", false, "verbose mode")
// file system roots
// TODO(gri) consider the invariant that goroot always end in '/'
goroot = flag.String("goroot", runtime.GOROOT(), "Go root directory")
// layout control
tabWidth = flag.Int("tabwidth", 4, "tab width")
showTimestamps = flag.Bool("timestamps", false, "show timestamps with directory listings")
templateDir = flag.String("templates", "", "load templates/JS/CSS from disk in this directory")
showPlayground = flag.Bool("play", false, "enable playground in web interface")
showExamples = flag.Bool("ex", false, "show examples in command line mode")
declLinks = flag.Bool("links", true, "link identifiers to their declarations")
// search index
indexEnabled = flag.Bool("index", false, "enable search index")
indexFiles = flag.String("index_files", "", "glob pattern specifying index files; if not empty, the index is read from these files in sorted order")
indexInterval = flag.Duration("index_interval", 0, "interval of indexing; 0 for default (5m), negative to only index once at startup")
maxResults = flag.Int("maxresults", 10000, "maximum number of full text search results shown")
indexThrottle = flag.Float64("index_throttle", 0.75, "index throttle value; 0.0 = no time allocated, 1.0 = full throttle")
// source code notes
notesRx = flag.String("notes", "BUG", "regular expression matching note markers to show")
)
func usage() {
fmt.Fprintf(os.Stderr,
"usage: godoc package [name ...]\n"+
" godoc -http="+defaultAddr+"\n")
flag.PrintDefaults()
os.Exit(2)
}
func loggingHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
log.Printf("%s\t%s", req.RemoteAddr, req.URL)
h.ServeHTTP(w, req)
})
}
func handleURLFlag() {
// Try up to 10 fetches, following redirects.
urlstr := *urlFlag
for i := 0; i < 10; i++ {
// Prepare request.
u, err := url.Parse(urlstr)
if err != nil {
log.Fatal(err)
}
req := &http.Request{
URL: u,
}
// Invoke default HTTP handler to serve request
// to our buffering httpWriter.
w := httptest.NewRecorder()
http.DefaultServeMux.ServeHTTP(w, req)
// Return data, error, or follow redirect.
switch w.Code {
case 200: // ok
os.Stdout.Write(w.Body.Bytes())
return
case 301, 302, 303, 307: // redirect
redirect := w.HeaderMap.Get("Location")
if redirect == "" {
log.Fatalf("HTTP %d without Location header", w.Code)
}
urlstr = redirect
default:
log.Fatalf("HTTP error %d", w.Code)
}
}
log.Fatalf("too many redirects")
}
func initCorpus(corpus *godoc.Corpus) {
err := corpus.Init()
if err != nil {
log.Fatal(err)
}
}
func main() {
flag.Usage = usage
flag.Parse()
if certInit != nil {
certInit()
}
playEnabled = *showPlayground
// Check usage: server and no args.
if (*httpAddr != "" || *urlFlag != "") && (flag.NArg() > 0) {
fmt.Fprintln(os.Stderr, "can't use -http with args.")
usage()
}
// Check usage: command line args or index creation mode.
if (*httpAddr != "" || *urlFlag != "") != (flag.NArg() == 0) && !*writeIndex {
fmt.Fprintln(os.Stderr, "missing args.")
usage()
}
var fsGate chan bool
fsGate = make(chan bool, 20)
// Determine file system to use.
if *zipfile == "" {
// use file system of underlying OS
rootfs := gatefs.New(vfs.OS(*goroot), fsGate)
fs.Bind("/", rootfs, "/", vfs.BindReplace)
} else {
// use file system specified via .zip file (path separator must be '/')
rc, err := zip.OpenReader(*zipfile)
if err != nil {
log.Fatalf("%s: %s\n", *zipfile, err)
}
defer rc.Close() // be nice (e.g., -writeIndex mode)
fs.Bind("/", zipfs.New(rc, *zipfile), *goroot, vfs.BindReplace)
}
if *templateDir != "" {
fs.Bind("/lib/godoc", vfs.OS(*templateDir), "/", vfs.BindBefore)
} else {
fs.Bind("/lib/godoc", mapfs.New(static.Files), "/", vfs.BindReplace)
}
// Bind $GOPATH trees into Go root.
for _, p := range filepath.SplitList(build.Default.GOPATH) {
fs.Bind("/src", gatefs.New(vfs.OS(p), fsGate), "/src", vfs.BindAfter)
}
httpMode := *httpAddr != ""
var typeAnalysis, pointerAnalysis bool
if *analysisFlag != "" {
for _, a := range strings.Split(*analysisFlag, ",") {
switch a {
case "type":
typeAnalysis = true
case "pointer":
pointerAnalysis = true
default:
log.Fatalf("unknown analysis: %s", a)
}
}
}
corpus := godoc.NewCorpus(fs)
corpus.Verbose = *verbose
corpus.MaxResults = *maxResults
corpus.IndexEnabled = *indexEnabled && httpMode
if *maxResults == 0 {
corpus.IndexFullText = false
}
corpus.IndexFiles = *indexFiles
corpus.IndexDirectory = indexDirectoryDefault
corpus.IndexThrottle = *indexThrottle
corpus.IndexInterval = *indexInterval
if *writeIndex {
corpus.IndexThrottle = 1.0
corpus.IndexEnabled = true
}
if *writeIndex || httpMode || *urlFlag != "" {
if httpMode {
go initCorpus(corpus)
} else {
initCorpus(corpus)
}
}
pres = godoc.NewPresentation(corpus)
pres.TabWidth = *tabWidth
pres.ShowTimestamps = *showTimestamps
pres.ShowPlayground = *showPlayground
pres.ShowExamples = *showExamples
pres.DeclLinks = *declLinks
pres.SrcMode = *srcMode
pres.HTMLMode = *html
pres.AllMode = *allMode
if *notesRx != "" {
pres.NotesRx = regexp.MustCompile(*notesRx)
}
readTemplates(pres, httpMode || *urlFlag != "")
registerHandlers(pres)
if *writeIndex {
// Write search index and exit.
if *indexFiles == "" {
log.Fatal("no index file specified")
}
log.Println("initialize file systems")
*verbose = true // want to see what happens
corpus.UpdateIndex()
log.Println("writing index file", *indexFiles)
f, err := os.Create(*indexFiles)
if err != nil {
log.Fatal(err)
}
index, _ := corpus.CurrentIndex()
_, err = index.WriteTo(f)
if err != nil {
log.Fatal(err)
}
log.Println("done")
return
}
// Print content that would be served at the URL *urlFlag.
if *urlFlag != "" {
handleURLFlag()
return
}
if httpMode {
// HTTP server mode.
var handler http.Handler = http.DefaultServeMux
if *verbose {
log.Printf("Go Documentation Server")
log.Printf("version = %s", runtime.Version())
log.Printf("address = %s", *httpAddr)
log.Printf("goroot = %s", *goroot)
log.Printf("tabwidth = %d", *tabWidth)
switch {
case !*indexEnabled:
log.Print("search index disabled")
case *maxResults > 0:
log.Printf("full text index enabled (maxresults = %d)", *maxResults)
default:
log.Print("identifier search index enabled")
}
fs.Fprint(os.Stderr)
handler = loggingHandler(handler)
}
// Initialize search index.
if *indexEnabled {
go corpus.RunIndexer()
}
// Start type/pointer analysis.
if typeAnalysis || pointerAnalysis {
go analysis.Run(pointerAnalysis, &corpus.Analysis)
}
if runHTTPS != nil {
go func() {
if err := runHTTPS(handler); err != nil {
log.Fatalf("ListenAndServe TLS: %v", err)
}
}()
}
// Start http server.
if *verbose {
log.Println("starting HTTP server")
}
if wrapHTTPMux != nil {
handler = wrapHTTPMux(handler)
}
if err := http.ListenAndServe(*httpAddr, handler); err != nil {
log.Fatalf("ListenAndServe %s: %v", *httpAddr, err)
}
return
}
if *query {
handleRemoteSearch()
return
}
if err := godoc.CommandLine(os.Stdout, fs, pres, flag.Args()); err != nil {
log.Print(err)
}
}
// Hooks that are set non-nil in autocert.go if the "autocert" build tag
// is used.
var (
certInit func()
runHTTPS func(http.Handler) error
wrapHTTPMux func(http.Handler) http.Handler
)
| myitcv/react | _vendor/src/golang.org/x/tools/cmd/godoc/main.go | GO | bsd-3-clause | 10,263 |
<?php
return array(
'Status\\V1\\Rpc\\Ping\\Controller' => array(
'GET' => array(
'description' => 'Ping the API for availability and receive a timestamp for acknowledgement.',
'request' => null,
'response' => '{
"ack": "Acknowledge the request with a timestamp"
}',
),
'description' => 'Ping the API for availability.',
),
'Status\\V1\\Rest\\Status\\Controller' => array(
'collection' => array(
'GET' => array(
'description' => 'Retrieve a paginated list of status messages.',
'request' => null,
'response' => null,
),
'POST' => array(
'description' => 'Create a new status messages.',
'request' => null,
'response' => null,
),
'description' => 'Manipulate lists of status messages.',
),
'entity' => array(
'GET' => array(
'description' => 'Retrieve a status message.',
'request' => null,
'response' => '{
"_links": {
"self": {
"href": "/status[/:status_id]"
}
}
"message": "A status message of no more than 140 characters.",
"user": "The user submitting the status message.",
"timestamp": "The timestamp when the status message was last modified."
}',
),
'PATCH' => array(
'description' => 'Update a status message.',
'request' => '{
"message": "A status message of no more than 140 characters.",
"user": "The user submitting the status message.",
"timestamp": "The timestamp when the status message was last modified."
}',
'response' => '{
"_links": {
"self": {
"href": "/status[/:status_id]"
}
}
"message": "A status message of no more than 140 characters.",
"user": "The user submitting the status message.",
"timestamp": "The timestamp when the status message was last modified."
}',
),
'PUT' => array(
'description' => 'Replace a status message.',
'request' => '{
"message": "A status message of no more than 140 characters.",
"user": "The user submitting the status message.",
"timestamp": "The timestamp when the status message was last modified."
}',
'response' => '{
"_links": {
"self": {
"href": "/status[/:status_id]"
}
}
"message": "A status message of no more than 140 characters.",
"user": "The user submitting the status message.",
"timestamp": "The timestamp when the status message was last modified."
}',
),
'DELETE' => array(
'description' => 'Delete a status message.',
'request' => null,
'response' => null,
),
'description' => 'Manipulate and retrieve individual status messages.',
),
'description' => 'Create, manipulate, and retrieve status messages.',
),
);
| baptistecosta/apigility | module/Status/config/documentation.config.php | PHP | bsd-3-clause | 3,099 |
#include <pulsar/testing/CppTester.hpp>
#include <pulsar/system/Atom.hpp>
using namespace pulsar;
TEST_SIMPLE(TestAtom){
CppTester tester("Testing the Atom class");
Atom H=create_atom({0.0,0.0,0.0},1);
Atom H2=create_atom({0.0,0.0,0.0},1,1);
tester.test_equal("create_atom works",H,H2);
tester.test_equal("correct Z",1,H.Z);
tester.test_equal("correct isotope",1,H.isotope);
tester.test_equal("correct mass",1.007975,H.mass);
tester.test_equal("correct isotope mass",1.0078250322,H.isotope_mass);
tester.test_equal("correct charge",0,H.charge);
tester.test_equal("correct multiplicity",2,H.multiplicity);
tester.test_equal("correct nelectrons",1,H.nelectrons);
tester.test_equal("correct covalent radius",0.5858150988919267,H.cov_radius);
tester.test_equal("correct vDW radius",2.267671350549394,H.vdw_radius);
Atom H3(H2);
tester.test_equal("copy constructor works",H,H3);
Atom H4(std::move(H3));
tester.test_equal("move constructor works",H,H4);
Atom D=create_atom({0.0,0.0,0.0},1,2);
tester.test_equal("Isotopes work",2,D.isotope);
tester.test_equal("Isotopes are different",true,D!=H);
D=H4;
tester.test_equal("assignment works",D,H);
Atom U=create_atom({0.0,0.0,0.0},92);
U=std::move(H4);
tester.test_equal("move assignment works",U,H);
tester.test_equal("hash works",H.my_hash(),U.my_hash());
tester.test_equal("hash works 1",H.my_hash(),H2.my_hash());
tester.test_equal("hash works 2",H.my_hash(),D.my_hash());
Atom GH=make_ghost_atom(H2);
tester.test_equal("ghost works",true,is_ghost_atom(GH));
Atom q=make_point_charge(H2,3.3),q2=make_point_charge(H2.get_coords(),3.3);
tester.test_equal("point charges work",true,is_point_charge(q));
tester.test_equal("point charges work 2",true,is_point_charge(q2));
tester.test_equal("is same point charge",q,q2);
Atom Dm=make_dummy_atom(H),Dm2=make_dummy_atom(H.get_coords());
tester.test_equal("is dummy atom",true,is_dummy_atom(Dm));
tester.test_equal("is dummy atom 2",true,is_dummy_atom(Dm2));
tester.test_equal("is same dummy atom",Dm,Dm2);
tester.print_results();
return tester.nfailed();
}
| pulsar-chem/Pulsar-Core | test/system/TestAtom.cpp | C++ | bsd-3-clause | 2,239 |
<?php
class ReCopyWidget extends CWidget {
public $targetClass='clone'; //Target CSS class target for duplicate
public $limit=0; //The number of allowed copies. Default: 0 is unlimited
public $addButtonId; // Add button id. Set id differently if this widget is called multiple times per page.
public $addButtonLabel='Add more'; //Add button text.
public $addButtonCssClass=''; //Add button CSS class.
public $removeButtonLabel='Remove'; //Remove button text
public $removeButtonCssClass='recopy-remove'; //Remove button CSS class.
public $excludeSelector; //A jQuery selector used to exclude an element and its children
public $copyClass; //A class to attach to each copy
public $clearInputs; //Boolean Option to clear each copies text input fields or textarea
private $_assetsUrl;
/**
* Initializes the widgets
*/
public function init() {
parent::init();
if ($this->_assetsUrl === null) {
$assetsDir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets';
$this->_assetsUrl = Yii::app()->assetManager->publish($assetsDir);
}
$this->addButtonId=trim($this->addButtonId);
if(empty($this->addButtonId))
$this->addButtonId='recopy-add';
if($this->limit)
$this->limit= (is_numeric($this->limit) && $this->limit > 0)? (int)ceil($this->limit):0;
}
/**
* Execute the widgets
*/
public function run() {
if($this->limit==1) return ;
Yii::app()->clientScript
->registerScriptFile($this->_assetsUrl . '/reCopy.js', CClientScript::POS_HEAD)
->registerScript(__CLASS__.$this->addButtonId, '
$(function(){
var removeLink = \' <a class="'.$this->removeButtonCssClass.'" href="#" onclick="$(this).parent().slideUp(function(){ $(this).remove() }); return false">'.$this->removeButtonLabel.'</a>\';
$("a#'.$this->addButtonId.'").relCopy({'.implode(', ', array_filter(array(
empty($this->excludeSelector)?'':'excludeSelector: "'.$this->excludeSelector.'"',
empty($this->limit)? '': 'limit: '.$this->limit,
empty($this->copyClass)? '': 'copyClass: "'.$this->copyClass.'"',
$this->clearInputs===true? 'clearInputs: true':'',
$this->clearInputs===false? 'clearInputs: false':'',
'append: removeLink',
))).'});
});
', CClientScript::POS_END);
echo CHtml::link($this->addButtonLabel, '#', array(
'id'=>$this->addButtonId,
'rel'=>'.'.$this->targetClass,
'class'=>$this->addButtonCssClass)
);
}
}//end class | elorian/crm.inreserve.kz | protected/extensions/recopy/ReCopyWidget.php | PHP | bsd-3-clause | 2,946 |
/**
*============================================================================
* The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC,
* and Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-workflow/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.portal.portlet.workflow.mvc;
import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowExecutionService;
import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowRegistryService;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SessionEprs;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SubmitWorkflowCommand;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowDescription;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowSubmitted;
import gov.nih.nci.cagrid.portal.portlet.workflow.util.Utils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.PortletRequestUtils;
import org.springframework.web.portlet.mvc.SimpleFormController;
@Controller
@RequestMapping(params={"action=newInstance"})
@SuppressWarnings("deprecation")
public class NewInstanceFormController extends SimpleFormController {
protected final Log log = LogFactory.getLog(getClass());
@Autowired
private WorkflowExecutionService workflowService;
@Autowired
@Qualifier("MyExperiment")
private WorkflowRegistryService registry;
@Autowired
private SessionEprs eprs;
@Autowired
private Utils utilities;
/* @see org.springframework.web.portlet.mvc.SimpleFormController#processFormSubmission(javax.portlet.ActionRequest, javax.portlet.ActionResponse, java.lang.Object, org.springframework.validation.BindException) */
@Override
protected void processFormSubmission(ActionRequest request, ActionResponse response, Object command, BindException errors) throws Exception {
String id = PortletRequestUtils.getStringParameter(request, "id", "NaN");
log.debug("processFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id - " + id);
SubmitWorkflowCommand cmd = (SubmitWorkflowCommand)command;
log.debug("Command Object: " + cmd.getTheWorkflow());
try {
WorkflowDescription selectedWorkflow = registry.getWorkflow(id);
log.info("Submitting the selected workflow.. #" + id);
String tempFilePath = saveWorkflowDefinition(selectedWorkflow);
EndpointReferenceType epr = workflowService.submitWorkflow(selectedWorkflow.getName(), tempFilePath, cmd.getInputValues());
UUID uuid = UUID.randomUUID();
log.debug("Will submit UUID : " + uuid.toString());
eprs.put(uuid.toString(), new WorkflowSubmitted(epr, selectedWorkflow, "Submitted"));
cmd.setResult("The Workflow was submitted successfully.");
log.info("The Workflow was submitted successfully.");
} catch(Throwable e) {
log.error("Error submitting workflow", e);
Throwable ex = e.getCause();
while(ex.getCause() !=null ) {
ex = ex.getCause();
}
cmd.setResult(e.getClass().getSimpleName() + " submitting workflow: " + e.getMessage());
}
}
/* @see org.springframework.web.portlet.mvc.SimpleFormController#renderFormSubmission(javax.portlet.RenderRequest, javax.portlet.RenderResponse, java.lang.Object, org.springframework.validation.BindException) */
@Override
protected ModelAndView renderFormSubmission(RenderRequest request, RenderResponse response, Object cmd, BindException errors) throws Exception {
log.debug("renderFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN"));
return new ModelAndView("json", "contents", ((SubmitWorkflowCommand)cmd).getResult());
}
/* @see org.springframework.web.portlet.mvc.SimpleFormController#showForm(javax.portlet.RenderRequest, javax.portlet.RenderResponse, org.springframework.validation.BindException) */
@Override
protected ModelAndView showForm(RenderRequest request, RenderResponse response, BindException errors) throws Exception {
String id = PortletRequestUtils.getStringParameter(request, "id", "NaN");
log.info("showForm. Action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id: " + id);
SubmitWorkflowCommand cmd = new SubmitWorkflowCommand();
cmd.setTheWorkflow(registry.getWorkflow(id));
return new ModelAndView("newInstance", "cmd", cmd);
}
/**
* Download the workflow definition to local filesystem
* @param wd Workflow Definition
* @return path of temporary file
* @throws IOException
* @throws HttpException
*/
private String saveWorkflowDefinition(WorkflowDescription wd) throws HttpException, IOException {
File tmpPath = new File( System.getProperty("java.io.tmpdir")+"/taverna" );
tmpPath.mkdirs();
String defPath = tmpPath.getAbsolutePath()+"/myexperiment_"+wd.getId()+"_v"+wd.getVersion()+".t2flow";
if(new File(defPath).exists()) { log.debug("Definition temporary file already exists so not downloading again."); return defPath; }
getUtilities().saveFile(defPath, getUtilities().download(wd.getContentURI()) );
return defPath;
}
public SessionEprs getSessionEprs() {return eprs;}
public void setSessionEprs(SessionEprs sessionEprs) {this.eprs = sessionEprs;}
public WorkflowExecutionService getWorkflowService() {return workflowService;}
public void setWorkflowService(WorkflowExecutionService workflowService) {this.workflowService = workflowService;}
public WorkflowRegistryService getRegistry() {return registry;}
public void setRegistry(WorkflowRegistryService registry) {this.registry = registry;}
public Utils getUtilities() {return utilities;}
public void setUtilities(Utils utilities) {this.utilities = utilities;}
}
| NCIP/cagrid-workflow | workflow-portlet/src/main/java/gov/nih/nci/cagrid/portal/portlet/workflow/mvc/NewInstanceFormController.java | Java | bsd-3-clause | 6,693 |
# -*- coding: utf-8 -*-
"""
eve.io.media
~~~~~~~~~~~~
Media storage for Eve-powered APIs.
:copyright: (c) 2014 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
class MediaStorage(object):
""" The MediaStorage class provides a standardized API for storing files,
along with a set of default behaviors that all other storage systems can
inherit or override as necessary.
..versioneadded:: 0.3
"""
def __init__(self, app=None):
"""
:param app: the flask application (eve itself). This can be used by
the class to access, amongst other things, the app.config object to
retrieve class-specific settings.
"""
self.app = app
def get(self, id_or_filename):
""" Opens the file given by name or unique id. Note that although the
returned file is guaranteed to be a File object, it might actually be
some subclass. Returns None if no file was found.
"""
raise NotImplementedError
def put(self, content, filename=None, content_type=None):
""" Saves a new file using the storage system, preferably with the name
specified. If there already exists a file with this name name, the
storage system may modify the filename as necessary to get a unique
name. Depending on the storage system, a unique id or the actual name
of the stored file will be returned. The content type argument is used
to appropriately identify the file when it is retrieved.
.. versionchanged:: 0.5
Allow filename to be optional (#414).
"""
raise NotImplementedError
def delete(self, id_or_filename):
""" Deletes the file referenced by name or unique id. If deletion is
not supported on the target storage system this will raise
NotImplementedError instead
"""
raise NotImplementedError
def exists(self, id_or_filename):
""" Returns True if a file referenced by the given name or unique id
already exists in the storage system, or False if the name is available
for a new file.
"""
raise NotImplementedError
| opticode/eve | eve/io/media.py | Python | bsd-3-clause | 2,207 |
from django.utils.translation import ugettext as _
from django.db import models
from jmbo.models import ModelBase
class Superhero(ModelBase):
name = models.CharField(max_length=256, editable=False)
class Meta:
verbose_name_plural = _("Superheroes")
| praekelt/jmbo-superhero | superhero/models.py | Python | bsd-3-clause | 269 |
<?php
namespace common\widgets;
use yii\helpers\VarDumper;
/**
* Created by PhpStorm.
* User: Александр Чернявенко
* Date: 25.11.2014
* Time: 14:09
*/
class PredictionAsset extends \yii\web\AssetBundle
{
public $depends = [
'yii\web\JqueryAsset',
];
public $css = [
];
public $js = [
];
public function init()
{
$this->setSourcePath(__DIR__ . '/assets/prediction');
parent::init();
}
/**
* Sets the source path if empty
*
* @param string $path the path to be set
*/
protected function setSourcePath($path)
{
if (empty($this->sourcePath)) {
$this->sourcePath = $path;
}
}
} | AleksandrChernyavenko/hintbox | common/widgets/PredictionAsset.php | PHP | bsd-3-clause | 728 |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
''' Processor functions for images '''
import numpy as np
def squeeze_image(img):
''' Return image, remove axes length 1 at end of image shape
For example, an image may have shape (10,20,30,1,1). In this case
squeeze will result in an image with shape (10,20,30). See doctests
for further description of behavior.
Parameters
----------
img : ``SpatialImage``
Returns
-------
squeezed_img : ``SpatialImage``
Copy of img, such that data, and data shape have been squeezed,
for dimensions > 3rd, and at the end of the shape list
Examples
--------
>>> import nipype.externals.pynifti as nf
>>> shape = (10,20,30,1,1)
>>> data = np.arange(np.prod(shape)).reshape(shape)
>>> affine = np.eye(4)
>>> img = nf.Nifti1Image(data, affine)
>>> img.get_shape()
(10, 20, 30, 1, 1)
>>> img2 = squeeze_image(img)
>>> img2.get_shape()
(10, 20, 30)
If the data are 3D then last dimensions of 1 are ignored
>>> shape = (10,1,1)
>>> data = np.arange(np.prod(shape)).reshape(shape)
>>> img = nf.ni1.Nifti1Image(data, affine)
>>> img.get_shape()
(10, 1, 1)
>>> img2 = squeeze_image(img)
>>> img2.get_shape()
(10, 1, 1)
Only *final* dimensions of 1 are squeezed
>>> shape = (1, 1, 5, 1, 2, 1, 1)
>>> data = data.reshape(shape)
>>> img = nf.ni1.Nifti1Image(data, affine)
>>> img.get_shape()
(1, 1, 5, 1, 2, 1, 1)
>>> img2 = squeeze_image(img)
>>> img2.get_shape()
(1, 1, 5, 1, 2)
'''
klass = img.__class__
shape = img.get_shape()
slen = len(shape)
if slen < 4:
return klass.from_image(img)
for bdim in shape[3::][::-1]:
if bdim == 1:
slen-=1
else:
break
if slen == len(shape):
return klass.from_image(img)
shape = shape[:slen]
data = img.get_data()
data = data.reshape(shape)
return klass(data,
img.get_affine(),
img.get_header(),
img.extra)
def concat_images(images):
''' Concatenate images in list to single image, along last dimension '''
n_imgs = len(images)
img0 = images[0]
i0shape = img0.get_shape()
affine = img0.get_affine()
header = img0.get_header()
out_shape = (n_imgs, ) + i0shape
out_data = np.empty(out_shape)
for i, img in enumerate(images):
if not np.all(img.get_affine() == affine):
raise ValueError('Affines do not match')
out_data[i] = img.get_data()
out_data = np.rollaxis(out_data, 0, len(i0shape)+1)
klass = img0.__class__
return klass(out_data, affine, header)
| satra/NiPypeold | nipype/externals/pynifti/funcs.py | Python | bsd-3-clause | 2,788 |
<?php
namespace VKBansal\Test\Spectrum\Plugin;
class PlugTest extends \PHPUnit_Framework_TestCase{
protected $plugin;
protected $plug;
public function setUp()
{
$this->plugin = $this->getMockForAbstractClass('VKBansal\Spectrum\Plugin\AbstractPlugin');
$this->plugin
->method('getName')->will($this->returnValue('test-plugin'));
$this->plugin
->method('add')->will($this->returnValue(true));
$this->plugin
->method('remove')->will($this->returnValue(true));
$this->plug = $this->getMockForTrait('VKBansal\Spectrum\Plugin\PluggableTrait', [], 'Spectrum');
}
/**
* @expectedException \VKBansal\Spectrum\Plugin\PluginNotFoundException
*/
public function testRemoveException()
{
$this->markTestSkipped();
$this->plug->addPlugin($this->plugin);
$this->plug->removePlugin('test-plugin');
$this->plug->removePlugin('test-plugin');
}
}
| vkbansal/spectrum | test/Plugin/PlugTest.php | PHP | bsd-3-clause | 996 |
/*
Copyright (C) 2009-2010 ProFUSION embedded systems
Copyright (C) 2009-2010 Samsung Electronics
This library 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 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "ewk_history.h"
#include "BackForwardList.h"
#include "CairoUtilitiesEfl.h"
#include "HistoryItem.h"
#include "IconDatabaseBase.h"
#include "Image.h"
#include "IntSize.h"
#include "Page.h"
#include "PageGroup.h"
#include "ewk_history_private.h"
#include "ewk_private.h"
#include <Eina.h>
#include <eina_safety_checks.h>
#include <wtf/text/CString.h>
struct _Ewk_History {
WebCore::BackForwardList* core;
};
#define EWK_HISTORY_CORE_GET_OR_RETURN(history, core_, ...) \
if (!(history)) { \
CRITICAL("history is NULL."); \
return __VA_ARGS__; \
} \
if (!(history)->core) { \
CRITICAL("history->core is NULL."); \
return __VA_ARGS__; \
} \
if (!(history)->core->enabled()) { \
ERR("history->core is disabled!."); \
return __VA_ARGS__; \
} \
WebCore::BackForwardList* core_ = (history)->core
struct _Ewk_History_Item {
WebCore::HistoryItem* core;
const char* title;
const char* alternateTitle;
const char* uri;
const char* originalUri;
};
#define EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core_, ...) \
if (!(item)) { \
CRITICAL("item is NULL."); \
return __VA_ARGS__; \
} \
if (!(item)->core) { \
CRITICAL("item->core is NULL."); \
return __VA_ARGS__; \
} \
WebCore::HistoryItem* core_ = (item)->core
static inline Eina_List* _ewk_history_item_list_get(const WebCore::HistoryItemVector& coreItems)
{
Eina_List* result = 0;
unsigned int size;
size = coreItems.size();
for (unsigned int i = 0; i < size; i++) {
Ewk_History_Item* item = ewk_history_item_new_from_core(coreItems[i].get());
if (item)
result = eina_list_append(result, item);
}
return result;
}
Eina_Bool ewk_history_clear(Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false);
WebCore::Page* page = core->page();
if (page && page->groupPtr())
page->groupPtr()->removeVisitedLinks();
const int limit = ewk_history_limit_get(history);
ewk_history_limit_set(history, 0);
ewk_history_limit_set(history, limit);
return true;
}
Eina_Bool ewk_history_forward(Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false);
if (core->forwardListCount() < 1)
return false;
core->goForward();
return true;
}
Eina_Bool ewk_history_back(Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false);
if (core->backListCount() < 1)
return false;
core->goBack();
return true;
}
Eina_Bool ewk_history_history_item_add(Ewk_History* history, const Ewk_History_Item* item)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false);
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false);
history_core->addItem(item_core);
return true;
}
Eina_Bool ewk_history_history_item_set(Ewk_History* history, const Ewk_History_Item* item)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false);
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false);
history_core->goToItem(item_core);
return true;
}
Ewk_History_Item* ewk_history_history_item_back_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return ewk_history_item_new_from_core(core->backItem());
}
Ewk_History_Item* ewk_history_history_item_current_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItem* currentItem = core->currentItem();
if (currentItem)
return ewk_history_item_new_from_core(currentItem);
return 0;
}
Ewk_History_Item* ewk_history_history_item_forward_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return ewk_history_item_new_from_core(core->forwardItem());
}
Ewk_History_Item* ewk_history_history_item_nth_get(const Ewk_History* history, int index)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return ewk_history_item_new_from_core(core->itemAtIndex(index));
}
Eina_Bool ewk_history_history_item_contains(const Ewk_History* history, const Ewk_History_Item* item)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, history_core, false);
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, item_core, false);
return history_core->containsItem(item_core);
}
Eina_List* ewk_history_forward_list_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItemVector items;
int limit = core->forwardListCount();
core->forwardListWithLimit(limit, items);
return _ewk_history_item_list_get(items);
}
Eina_List* ewk_history_forward_list_get_with_limit(const Ewk_History* history, int limit)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItemVector items;
core->forwardListWithLimit(limit, items);
return _ewk_history_item_list_get(items);
}
int ewk_history_forward_list_length(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return core->forwardListCount();
}
Eina_List* ewk_history_back_list_get(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItemVector items;
int limit = core->backListCount();
core->backListWithLimit(limit, items);
return _ewk_history_item_list_get(items);
}
Eina_List* ewk_history_back_list_get_with_limit(const Ewk_History* history, int limit)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
WebCore::HistoryItemVector items;
core->backListWithLimit(limit, items);
return _ewk_history_item_list_get(items);
}
int ewk_history_back_list_length(const Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return core->backListCount();
}
int ewk_history_limit_get(Ewk_History* history)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, 0);
return core->capacity();
}
Eina_Bool ewk_history_limit_set(const Ewk_History* history, int limit)
{
EWK_HISTORY_CORE_GET_OR_RETURN(history, core, false);
core->setCapacity(limit);
return true;
}
Ewk_History_Item* ewk_history_item_new_from_core(WebCore::HistoryItem* core)
{
Ewk_History_Item* item;
if (!core) {
ERR("WebCore::HistoryItem is NULL.");
return 0;
}
core->ref();
item = new Ewk_History_Item;
memset(item, 0, sizeof(*item));
item->core = core;
return item;
}
Ewk_History_Item* ewk_history_item_new(const char* uri, const char* title)
{
WTF::String historyUri = WTF::String::fromUTF8(uri);
WTF::String historyTitle = WTF::String::fromUTF8(title);
WTF::RefPtr<WebCore::HistoryItem> core = WebCore::HistoryItem::create(historyUri, historyTitle, 0);
Ewk_History_Item* item = ewk_history_item_new_from_core(core.release().leakRef());
return item;
}
static inline void _ewk_history_item_free(Ewk_History_Item* item, WebCore::HistoryItem* core)
{
core->deref();
delete item;
}
void ewk_history_item_free(Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core);
_ewk_history_item_free(item, core);
}
void ewk_history_item_list_free(Eina_List* history_items)
{
void* deleteItem;
EINA_LIST_FREE(history_items, deleteItem) {
Ewk_History_Item* item = (Ewk_History_Item*)deleteItem;
_ewk_history_item_free(item, item->core);
}
}
const char* ewk_history_item_title_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
// hide the following optimzation from outside
Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item);
eina_stringshare_replace(&historyItem->title, core->title().utf8().data());
return historyItem->title;
}
const char* ewk_history_item_title_alternate_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
// hide the following optimzation from outside
Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item);
eina_stringshare_replace(&historyItem->alternateTitle,
core->alternateTitle().utf8().data());
return historyItem->alternateTitle;
}
void ewk_history_item_title_alternate_set(Ewk_History_Item* item, const char* title)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core);
if (!eina_stringshare_replace(&item->alternateTitle, title))
return;
core->setAlternateTitle(WTF::String::fromUTF8(title));
}
const char* ewk_history_item_uri_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
// hide the following optimzation from outside
Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>((item));
eina_stringshare_replace(&historyItem->uri, core->urlString().utf8().data());
return historyItem->uri;
}
const char* ewk_history_item_uri_original_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
// hide the following optimzation from outside
Ewk_History_Item* historyItem = const_cast<Ewk_History_Item*>(item);
eina_stringshare_replace(&historyItem->originalUri,
core->originalURLString().utf8().data());
return historyItem->originalUri;
}
double ewk_history_item_time_last_visited_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0.0);
return core->lastVisitedTime();
}
cairo_surface_t* ewk_history_item_icon_surface_get(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
RefPtr<cairo_surface_t> icon = WebCore::iconDatabase().synchronousNativeIconForPageURL(core->url(), WebCore::IntSize(16, 16));
if (!icon)
ERR("icon is NULL.");
return icon.get();
}
Evas_Object* ewk_history_item_icon_object_add(const Ewk_History_Item* item, Evas* canvas)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
EINA_SAFETY_ON_NULL_RETURN_VAL(canvas, 0);
RefPtr<cairo_surface_t> surface = WebCore::iconDatabase().synchronousNativeIconForPageURL(core->url(), WebCore::IntSize(16, 16));
if (!surface) {
ERR("icon is NULL.");
return 0;
}
return surface ? WebCore::evasObjectFromCairoImageSurface(canvas, surface.get()).leakRef() : 0;
}
Eina_Bool ewk_history_item_page_cache_exists(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, false);
return core->isInPageCache();
}
int ewk_history_item_visit_count(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, 0);
return core->visitCount();
}
Eina_Bool ewk_history_item_visit_last_failed(const Ewk_History_Item* item)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(item, core, true);
return core->lastVisitWasFailure();
}
/* internal methods ****************************************************/
/**
* @internal
*
* Creates history for given view. Called internally by ewk_view and
* should never be called from outside.
*
* @param core WebCore::BackForwardList instance to use internally.
*
* @return newly allocated history instance or @c NULL on errors.
*/
Ewk_History* ewk_history_new(WebCore::BackForwardList* core)
{
Ewk_History* history;
EINA_SAFETY_ON_NULL_RETURN_VAL(core, 0);
DBG("core=%p", core);
history = new Ewk_History;
history->core = core;
core->ref();
return history;
}
/**
* @internal
*
* Destroys previously allocated history instance. This is called
* automatically by ewk_view and should never be called from outside.
*
* @param history instance to free
*/
void ewk_history_free(Ewk_History* history)
{
DBG("history=%p", history);
history->core->deref();
delete history;
}
namespace EWKPrivate {
WebCore::HistoryItem* coreHistoryItem(const Ewk_History_Item* ewkHistoryItem)
{
EWK_HISTORY_ITEM_CORE_GET_OR_RETURN(ewkHistoryItem, core, 0);
return core;
}
} // namespace EWKPrivate
| klim-iv/phantomjs-qt5 | src/webkit/Source/WebKit/efl/ewk/ewk_history.cpp | C++ | bsd-3-clause | 13,646 |
<?php
/**
* Yasc.
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.
* It is also available through the world-wide-web at this URL:
* http://github.com/nebiros/yasc/raw/master/LICENSE
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to mail@jfalvarez.com so we can send you a copy immediately.
*
* @category Yasc
* @package Yasc
* @subpackage Yasc_App
* @copyright Copyright (c) 2010 - 2014 Juan Felipe Alvarez Sadarriaga. (http://juan.im)
* @version $Id$
* @license http://github.com/nebiros/yasc/raw/master/LICENSE New BSD License
*/
/**
* Configuration.
*
* @package Yasc
* @subpackage Yasc_App
* @copyright Copyright (c) 2010 - 2014 Juan Felipe Alvarez Sadarriaga. (http://juan.im)
* @license http://github.com/nebiros/yasc/raw/master/LICENSE New BSD License
* @author nebiros
*/
class Yasc_App_Config {
/**
*
* @var array
*/
protected $_options = array();
/**
*
* @var bool
*/
protected $_useViewStream = false;
/**
* Layout.
*
* @var string
*/
protected $_layoutScript = null;
/**
*
*/
public function __construct() {
$this->_addDefaultPaths();
}
/**
*
* @param array $options
* @return Yasc_App_Config
*/
public function setOptions(Array $options) {
$this->_options = $options;
return $this;
}
/**
*
* @return array
*/
public function getOptions() {
return $this->_options;
}
/**
*
* @param mixed $key
* @param mixed $default
* @return mixed|null
*/
public function getOption($key, $default = null) {
if (true === isset($this->_options[$key])) {
return $this->_options[$key];
}
return $default;
}
/**
*
* @param array $options
* @return Yasc_App_Config
*/
public function addOptions(Array $options) {
$this->_options = array_merge($this->_options, $options);
return $this;
}
/**
*
* @param mixed $key
* @param mixed $value
* @return Yasc_App_Config
*/
public function addOption($key, $value = null) {
$this->_options[$key] = $value;
return $this;
}
/**
*
* @param bool $flag
* @return Yasc_App_Config
*/
public function setViewStream($flag = false) {
$this->_useViewStream = $flag;
return $this;
}
/**
*
* @return bool
*/
public function useViewStream() {
return $this->_useViewStream;
}
/**
*
* @return array
*/
public function getViewsPaths() {
return Yasc_Autoloader_Manager::getInstance()->getPaths(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW);
}
/**
*
* @param string $path
* @return Yasc_App_Config
*/
public function setViewsPath($path) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path);
return $this;
}
/**
*
* @param string $path
* @return Yasc_App_Config
*/
public function addViewsPath($path) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW, $path);
return $this;
}
/**
*
* @return string
*/
public function getLayoutScript() {
return $this->_layoutScript;
}
/**
*
* @param string $layout
* @return Yasc_App_Config
*/
public function setLayoutScript($layout) {
if (false === is_string($layout)) {
return false;
}
$layout = realpath($layout);
if (false === is_file($layout)) {
throw new Yasc_App_Exception("Layout file '{$layout}' not found");
}
$this->_layoutScript = $layout;
// Cause a layout is a view too, we going to add layout script folder
// to the views folders.
$this->addViewsPath(dirname($this->_layoutScript));
return $this;
}
/**
*
* @return array
*/
public function getViewHelperPaths() {
return Yasc_Autoloader_Manager::getInstance()->getPaths(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER);
}
/**
*
* @param string $classPrefix
* @return string
*/
public function getViewHelpersPath($classPrefix = null) {
return Yasc_Autoloader_Manager::getInstance()->getPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $classPrefix);
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function setViewHelpersPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->setPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path, $classPrefix);
return $this;
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function addViewHelpersPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $path, $classPrefix);
return $this;
}
/**
*
* @return array
*/
public function getFunctionHelperPaths() {
return Yasc_Autoloader_Manager::getInstance()->getPaths(
Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER);
}
/**
*
* @param string $classPrefix
* @return string
*/
public function getFunctionHelpersPath($classPrefix = null) {
return Yasc_Autoloader_Manager::getInstance()->getPath(
Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $classPrefix);
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function setFunctionHelpersPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->setPath(
Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $path, $classPrefix);
return $this;
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function addFunctionHelpersPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_FUNCTION_HELPER, $path, $classPrefix);
return $this;
}
/**
*
* @return array
*/
public function getModelPaths() {
return Yasc_Autoloader_Manager::getInstance()->getPaths(
Yasc_Autoloader_Manager::PATH_TYPE_MODEL);
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function setModelsPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->setPath(
Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $path, $classPrefix);
return $this;
}
/**
*
* @param string $path
* @param string $classPrefix
* @return Yasc_App_Config
*/
public function addModelsPath($path, $classPrefix = null) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $path, $classPrefix);
return $this;
}
/**
*
* @return void
*/
protected function _addDefaultPaths() {
$views = realpath(APPLICATION_PATH . "/views");
$helpers = realpath(APPLICATION_PATH . "/views/helpers");
$models = realpath(APPLICATION_PATH . "/models");
// default paths, if they exist.
if (true === is_dir($views)) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW, $views);
}
if (true === is_dir($helpers)) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_VIEW_HELPER, $helpers, "Helper");
}
if (true === is_dir($models)) {
Yasc_Autoloader_Manager::getInstance()->addPath(
Yasc_Autoloader_Manager::PATH_TYPE_MODEL, $models, "Model");
}
}
}
| nebiros/yasc | src/Yasc/App/Config.php | PHP | bsd-3-clause | 8,643 |
//===-- lib/Evaluate/fold-real.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "fold-implementation.h"
namespace Fortran::evaluate {
template <int KIND>
Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction(
FoldingContext &context,
FunctionRef<Type<TypeCategory::Real, KIND>> &&funcRef) {
using T = Type<TypeCategory::Real, KIND>;
using ComplexT = Type<TypeCategory::Complex, KIND>;
ActualArguments &args{funcRef.arguments()};
auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
CHECK(intrinsic);
std::string name{intrinsic->name};
if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" ||
(name == "atan" && args.size() == 1) || name == "atanh" ||
name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" ||
name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" ||
name == "erfc" || name == "erfc_scaled" || name == "exp" ||
name == "gamma" || name == "log" || name == "log10" ||
name == "log_gamma" || name == "sin" || name == "sinh" ||
name == "sqrt" || name == "tan" || name == "tanh") {
CHECK(args.size() == 1);
if (auto callable{context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, T>(name)}) {
return FoldElementalIntrinsic<T, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(real(kind=%d)) cannot be folded on host"_en_US, name, KIND);
}
} else if (name == "atan" || name == "atan2" || name == "hypot" ||
name == "mod") {
std::string localName{name == "atan2" ? "atan" : name};
CHECK(args.size() == 2);
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, T, T>(localName)}) {
return FoldElementalIntrinsic<T, T, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(real(kind=%d), real(kind%d)) cannot be folded on host"_en_US,
name, KIND, KIND);
}
} else if (name == "bessel_jn" || name == "bessel_yn") {
if (args.size() == 2) { // elemental
// runtime functions use int arg
using Int4 = Type<TypeCategory::Integer, 4>;
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, Int4, T>(name)}) {
return FoldElementalIntrinsic<T, Int4, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_en_US,
name, KIND);
}
}
} else if (name == "abs") {
// Argument can be complex or real
if (auto *x{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
return FoldElementalIntrinsic<T, T>(
context, std::move(funcRef), &Scalar<T>::ABS);
} else if (auto *z{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, ComplexT>("abs")}) {
return FoldElementalIntrinsic<T, ComplexT>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"abs(complex(kind=%d)) cannot be folded on host"_en_US, KIND);
}
} else {
common::die(" unexpected argument type inside abs");
}
} else if (name == "aimag") {
return FoldElementalIntrinsic<T, ComplexT>(
context, std::move(funcRef), &Scalar<ComplexT>::AIMAG);
} else if (name == "aint" || name == "anint") {
// ANINT rounds ties away from zero, not to even
common::RoundingMode mode{name == "aint"
? common::RoundingMode::ToZero
: common::RoundingMode::TiesAwayFromZero};
return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
ScalarFunc<T, T>([&name, &context, mode](
const Scalar<T> &x) -> Scalar<T> {
ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)};
if (y.flags.test(RealFlag::Overflow)) {
context.messages().Say("%s intrinsic folding overflow"_en_US, name);
}
return y.value;
}));
} else if (name == "dprod") {
if (auto scalars{GetScalarConstantArguments<T, T>(context, args)}) {
return Fold(context,
Expr<T>{Multiply<T>{
Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}});
}
} else if (name == "epsilon") {
return Expr<T>{Scalar<T>::EPSILON()};
} else if (name == "huge") {
return Expr<T>{Scalar<T>::HUGE()};
} else if (name == "max") {
return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
} else if (name == "merge") {
return FoldMerge<T>(context, std::move(funcRef));
} else if (name == "min") {
return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
} else if (name == "real") {
if (auto *expr{args[0].value().UnwrapExpr()}) {
return ToReal<KIND>(context, std::move(*expr));
}
} else if (name == "sign") {
return FoldElementalIntrinsic<T, T, T>(
context, std::move(funcRef), &Scalar<T>::SIGN);
} else if (name == "tiny") {
return Expr<T>{Scalar<T>::TINY()};
}
// TODO: cshift, dim, dot_product, eoshift, fraction, matmul,
// maxval, minval, modulo, nearest, norm2, pack, product,
// reduce, rrspacing, scale, set_exponent, spacing, spread,
// sum, transfer, transpose, unpack, bessel_jn (transformational) and
// bessel_yn (transformational)
return Expr<T>{std::move(funcRef)};
}
template <int KIND>
Expr<Type<TypeCategory::Real, KIND>> FoldOperation(
FoldingContext &context, ComplexComponent<KIND> &&x) {
using Operand = Type<TypeCategory::Complex, KIND>;
using Result = Type<TypeCategory::Real, KIND>;
if (auto array{ApplyElementwise(context, x,
std::function<Expr<Result>(Expr<Operand> &&)>{
[=](Expr<Operand> &&operand) {
return Expr<Result>{ComplexComponent<KIND>{
x.isImaginaryPart, std::move(operand)}};
}})}) {
return *array;
}
using Part = Type<TypeCategory::Real, KIND>;
auto &operand{x.left()};
if (auto value{GetScalarConstantValue<Operand>(operand)}) {
if (x.isImaginaryPart) {
return Expr<Part>{Constant<Part>{value->AIMAG()}};
} else {
return Expr<Part>{Constant<Part>{value->REAL()}};
}
}
return Expr<Part>{std::move(x)};
}
FOR_EACH_REAL_KIND(template class ExpressionBase, )
template class ExpressionBase<SomeReal>;
} // namespace Fortran::evaluate
| endlessm/chromium-browser | third_party/llvm/flang/lib/Evaluate/fold-real.cpp | C++ | bsd-3-clause | 6,929 |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*/
class LoginForm extends Model
{
public $login;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['login', 'password'], 'required'],
['login', 'exist', 'targetClass' => '\app\models\UserModel', 'message' => Yii::t('app', 'A specified login does not exist')],
['rememberMe', 'boolean'],
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, Yii::t('app', 'Incorrect password'));
}
}
}
/**
* Logs in a user using the provided username and password.
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = UserModel::findByLogin($this->login);
}
return $this->_user;
}
}
| Per1phery/wholetthedogout | models/LoginForm.php | PHP | bsd-3-clause | 1,861 |
<?php
namespace app\models;
use Yii;
use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;
/**
* This is the model class for table "tbl_six_step".
*
* @property integer $six_step_id
* @property integer $atlet_id
* @property string $stage
* @property string $status
*/
class SixStepBiomekanik extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tbl_six_step_biomekanik';
}
public function behaviors()
{
return [
'bedezign\yii2\audit\AuditTrailBehavior',
[
'class' => \yii\behaviors\BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
[
'class' => \yii\behaviors\TimestampBehavior::className(),
'createdAtAttribute' => 'created',
'updatedAtAttribute' => 'updated',
'value' => new \yii\db\Expression('NOW()'),
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['atlet_id', 'stage', 'status', 'tarikh'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required],
[['atlet_id', 'kategori_atlet', 'sukan', 'acara'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
[['stage', 'status'], 'string', 'max' => 30, 'tooLong' => GeneralMessage::yii_validation_string_max],
[['stage', 'status'], function ($attribute, $params) {
if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
$this->addError($attribute, GeneralMessage::yii_validation_xss);
}
}],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'six_step_id' => GeneralLabel::six_step_id,
'atlet_id' => GeneralLabel::atlet_id,
'kategori_atlet' => GeneralLabel::kategori_atlet,
'sukan' => GeneralLabel::sukan,
'acara' => GeneralLabel::acara,
'stage' => GeneralLabel::stage,
'status' => GeneralLabel::status,
'tarikh' => GeneralLabel::tarikh,
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getAtlet(){
return $this->hasOne(Atlet::className(), ['atlet_id' => 'atlet_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRefSixstepBiomekanikStage(){
return $this->hasOne(RefSixstepBiomekanikStage::className(), ['id' => 'stage']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRefSixstepBiomekanikStatus(){
return $this->hasOne(RefSixstepBiomekanikStatus::className(), ['id' => 'status']);
}
}
| hung101/kbs | frontend/models/SixStepBiomekanik.php | PHP | bsd-3-clause | 2,953 |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ----------------------------------------------------------------------------
from qiime2.plugin import SemanticType
from ..plugin_setup import plugin
from . import AlphaDiversityDirectoryFormat
SampleData = SemanticType('SampleData', field_names='type')
AlphaDiversity = SemanticType('AlphaDiversity',
variant_of=SampleData.field['type'])
plugin.register_semantic_types(SampleData, AlphaDiversity)
plugin.register_semantic_type_to_format(
SampleData[AlphaDiversity],
artifact_format=AlphaDiversityDirectoryFormat
)
| qiime2/q2-types | q2_types/sample_data/_type.py | Python | bsd-3-clause | 832 |
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Serialization;
using JetBat.Client.Entities;
using JetBat.Client.Metadata.Abstract;
using JetBat.Client.Metadata.Definitions;
using JetBat.Client.Metadata.Misc;
using JetBat.Client.Metadata.Simple;
namespace JetBat.Client.SqlServer.Concrete
{
public class PlainObjectListViewDefinitionSqlLoader : IObjectDefinitionSqlLoader
{
private const int PlainObjectListViewObjectTypeID = 2;
private readonly string _connectionString;
private readonly bool _enableCaching;
public PlainObjectListViewDefinitionSqlLoader(string connectionString, bool enableCaching)
{
_connectionString = connectionString;
_enableCaching = enableCaching;
}
#region IObjectDefinitionSqlLoader Members
public Type TargetObjectType
{
get { return typeof(PlainObjectListViewDefinition); }
}
public int TargetObjectID
{
get { return PlainObjectListViewObjectTypeID; }
}
public ObjectDefinition LoadImmutable(string objectNamespace, string objectName)
{
return new PlainObjectListViewDefinition((PlainObjectListView)Load(objectNamespace, objectName));
}
#endregion
public BusinessObject Load(string objectNamespace, string objectName)
{
#region Load from cache
string cacheDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, StaticHelper.MetadataCacheDirectoryName + @"\PlainObjectListView");
string cacheFileName = string.Format(@"{0}\{1}.{2}.xml", cacheDirectory, objectNamespace, objectName);
if (_enableCaching)
{
if (File.Exists(cacheFileName))
{
XmlSerializer serializer = new XmlSerializer(typeof(PlainObjectListView));
using (FileStream stream = new FileStream(cacheFileName, FileMode.Open, FileAccess.Read))
return (PlainObjectListView)serializer.Deserialize(stream);
}
}
#endregion
string uiListCaption;
string basicObjectNamespace;
string basicObjectName;
string objectActionNameLoadList;
string objectMethodNameLoadList;
string namespaceName;
string name;
int objectType;
string friendlyName;
string description;
NamedObjectCollection<ObjectAttribute> attributes;
NamedObjectCollection<ObjectComplexAttribute> complexAttributes;
NamedObjectCollection<ObjectAction> actions;
NamedObjectCollection<ObjectMethod> methods;
using (SqlConnection sqlConnection = new SqlConnection(_connectionString))
{
sqlConnection.Open();
SqlCommand command = new SqlCommand("MetadataEngine_LoadPlainObjectListViewDescriptor", sqlConnection) { CommandType = CommandType.StoredProcedure };
command.Parameters.AddWithValue("@Namespace", objectNamespace);
command.Parameters.AddWithValue("@Name", objectName);
SqlDataReader reader = command.ExecuteReader();
if (reader == null) throw new NullReferenceException("DataReader is null while must not be.");
using (reader)
{
reader.Read();
uiListCaption = reader["UIListCaption"].ToString();
basicObjectNamespace = Convert.ToString(reader["EntityNamespaceName"]);
basicObjectName = Convert.ToString(reader["EntityName"]);
objectActionNameLoadList = reader["ObjectActionNameLoadList"].Equals(DBNull.Value)
? ""
: Convert.ToString(reader["ObjectActionNameLoadList"]);
objectMethodNameLoadList = reader["ObjectMethodNameLoadList"].Equals(DBNull.Value)
? ""
: Convert.ToString(reader["ObjectMethodNameLoadList"]);
objectType = Convert.ToInt32(reader["ObjectTypeID"]);
namespaceName = Convert.ToString(reader["NamespaceName"]);
name = Convert.ToString(reader["Name"]);
friendlyName = Convert.ToString(reader["FriendlyName"]);
description = Convert.ToString(reader["Description"]);
reader.NextResult();
attributes = StaticHelper.getAttributesFormReader(reader);
reader.NextResult();
complexAttributes = StaticHelper.getComplexAttributesFromReader(reader);
reader.NextResult();
StaticHelper.getComplexAttributeAttributePairsFromReader(reader, complexAttributes);
reader.NextResult();
actions = StaticHelper.getActionsFormReader(reader);
reader.NextResult();
methods = StaticHelper.getMethodsFromReader(reader);
reader.NextResult();
StaticHelper.getMethodParametersFromReader(reader, methods);
}
}
BusinessObject definition = new PlainObjectListView
{
UIListCaption = uiListCaption,
BasicObjectNamespace = basicObjectNamespace,
BasicObjectName = basicObjectName,
ObjectActionNameLoadList = objectActionNameLoadList,
ObjectMethodNameLoadList = objectMethodNameLoadList,
ObjectNamespace = namespaceName,
ObjectName = name,
ObjectType = objectType,
FriendlyName = friendlyName,
Description = description,
Attributes = attributes,
ComplexAttributes = complexAttributes,
Actions = actions,
Methods = methods
};
#region Save to cache
if (_enableCaching)
{
if (!Directory.Exists(cacheDirectory))
Directory.CreateDirectory(cacheDirectory);
XmlSerializer serializer = new XmlSerializer(typeof(PlainObjectListView));
using (FileStream stream = new FileStream(cacheFileName, FileMode.OpenOrCreate, FileAccess.Write))
serializer.Serialize(stream, definition);
}
#endregion
return definition;
}
}
} | shestakov/jetbat | JetBat.Client/SqlServer/Concrete/PlainObjectListViewDefinitionSqlLoader.cs | C# | bsd-3-clause | 5,650 |
/*
* Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Business Objects nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* IntellicutList.java
* Creation date: Dec 10th 2002
* By: Ken Wong
*/
package org.openquark.gems.client;
import java.awt.Container;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.JList;
import javax.swing.JViewport;
import javax.swing.ListSelectionModel;
import org.openquark.gems.client.IntellicutListModel.FilterLevel;
import org.openquark.gems.client.IntellicutListModelAdapter.IntellicutListEntry;
import org.openquark.gems.client.IntellicutManager.IntellicutMode;
/**
* A list that encapsulates all the details associated with populating
* a list with the unqualified names of gems.
* @author Ken Wong
* @author Frank Worsley
*/
public class IntellicutList extends JList {
private static final long serialVersionUID = -8515575227984050475L;
/** The last list index that was visible when the state was saved. */
private int savedVisibleIndex = -1;
/** The last list entry that was visible when the state was saved. */
private IntellicutListEntry savedVisibleEntry = null;
/** The list entry that was selected when the state was saved. */
private IntellicutListEntry savedSelectedEntry = null;
/** Whether or not this list should be drawn transparently. */
private boolean transparent = false;
/**
* Constructor for IntellicutList.
*/
public IntellicutList(IntellicutMode mode) {
setName("MatchingGemsList");
setCellRenderer(new IntellicutListRenderer(mode));
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
/**
* Enables the list to be transparent. If the list is transparent non selected list items
* will let the components below them show through. Selected list items will draw a blue
* semi-transparent tint as their background.
* @param value whether or not the list should be transparent
*/
void setTransparent(boolean value) {
this.transparent = value;
updateUI();
}
/**
* @return whether or not the intellicut list is transparent
*/
public boolean isTransparent() {
return transparent;
}
/**
* Saves the currently selected list item and the scroll position of the
* list so that the list state can be restored later.
*/
private void saveListState() {
IntellicutListModel listModel = (IntellicutListModel) getModel();
savedVisibleEntry = null;
savedSelectedEntry = null;
savedVisibleIndex = getLastVisibleIndex();
int selectedIndex = getSelectedIndex();
try {
savedVisibleEntry = listModel.get(savedVisibleIndex);
savedSelectedEntry = listModel.get(selectedIndex);
// We only want to make the selected entry visible again after refreshing
// the list if it was visible before.
if (selectedIndex > getLastVisibleIndex() || selectedIndex < getFirstVisibleIndex()) {
savedSelectedEntry = null;
}
} catch (Exception ex) {
// This might throw a NullPointerException or ArrayIndexOutOfBoundsException
// if the model is not initialized. In that case there is no index we can restore.
}
}
/**
* Restores the previously saved list state as closely as possible.
*/
private void restoreListState() {
IntellicutListModel listModel = (IntellicutListModel) getModel();
int newSelectedIndex = listModel.indexOf(savedSelectedEntry);
int newVisibleIndex = listModel.indexOf(savedVisibleEntry);
if (newVisibleIndex == -1) {
newVisibleIndex = savedVisibleIndex;
}
// We have to add one cell height, otherwise the cell will be just
// outside of the visible range of the list. ensureIndexIsVisible doesn't
// work here since we want the index to appear at the very bottom.
Point newLocation = indexToLocation(newVisibleIndex);
if (newLocation != null) {
newLocation.y += getCellBounds(0, 0).height;
scrollRectToVisible(new Rectangle(newLocation));
}
if (newSelectedIndex != -1) {
setSelectedIndex(newSelectedIndex);
ensureIndexIsVisible(newSelectedIndex);
} else {
setSelectedIndex(0);
}
}
/**
* Refreshes the list while remembering the selected item and scroll position
* as closely as possible. Simply refreshing the list model will not remember
* the list state.
* @param prefix the new prefix for values in the list
*/
public void refreshList(String prefix) {
IntellicutListModel listModel = (IntellicutListModel) getModel();
saveListState();
listModel.refreshList(prefix);
restoreListState();
}
/**
* Finds the JViewport this list is embedded in.
* @return the viewport or null if there is no viewport
*/
private JViewport getViewport() {
Container parent = getParent();
while (parent != null && !(parent instanceof JViewport)) {
parent = parent.getParent ();
}
return (JViewport) parent;
}
/**
* Scrolls the given index as close as possible to the top of the list's viewport.
* @param index index of the item to scroll to the top
*/
void scrollToTop(int index) {
Point location = indexToLocation(index);
if (location == null) {
return;
}
JViewport viewport = getViewport();
// Scroll this element as close to the top as possible.
if (viewport.getViewSize().height - location.y < viewport.getSize().height) {
location.y -= viewport.getSize().height - viewport.getViewSize().height + location.y;
}
viewport.setViewPosition(location);
}
/**
* Sets the current gem filtering level.
*
* The list is automatically refreshed after doing this. This method also saves
* the list's displayed state as opposed to just setting the filter level which
* will not remember the list state.
* @param filterLevel the new level to filter at
*/
void setFilterLevel(FilterLevel filterLevel) {
if (filterLevel == null) {
throw new NullPointerException("filterLevel must not be null in IntellicutList.setFilterLevel");
}
IntellicutListModel listModel = (IntellicutListModel) getModel();
saveListState();
listModel.setFilterLevel(filterLevel);
restoreListState();
}
/**
* Returns the user selected IntellicutListEntry
* @return IntellicutListEntry
*/
IntellicutListEntry getSelected(){
return getModel().getSize() > 0 ? (IntellicutListEntry) getSelectedValue() : null;
}
/**
* We want tooltips to be displayed to the right of an item.
* If there is no item at the coordinates it returns null.
* @param e the mouse event for which to determine the location
* @return the tooltip location for the list item at the coordinates of the mouse event
*/
@Override
public Point getToolTipLocation(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (index == -1) {
return null;
}
Rectangle cellBounds = getCellBounds(index, index);
// take off 50 and add 5 for good looks
return new Point (cellBounds.x + cellBounds.width - 50, cellBounds.y + 5);
}
/**
* @param e the MouseEvent for which to get the tooltip text
* @return the tooltip text for the list item at the coordinates or null if there is no
* item at the coordinates
*/
@Override
public String getToolTipText(MouseEvent e) {
int index = locationToIndex(e.getPoint());
if (index == -1) {
return null;
}
IntellicutListEntry listEntry = (IntellicutListEntry) getModel().getElementAt(index);
if (listEntry == null) {
return null;
}
IntellicutListModel listModel = (IntellicutListModel) getModel();
return listModel.getAdapter().getToolTipTextForEntry(listEntry, this);
}
}
| levans/Open-Quark | src/Quark_Gems/src/org/openquark/gems/client/IntellicutList.java | Java | bsd-3-clause | 10,380 |
require("../pc.v0");
require("util").puts(JSON.stringify({
"name": "pc",
"version": pc.version,
"description": "property creation for reusable d3.js code.",
"keywords": ["d3", "visualization"],
"homepage": "http://milroc.github.com/pc/",
"author": {"name": "Miles McCrocklin", "url": "http://www.milesmccrocklin.com" },
"repository": {"type": "git", "url": "http://github.com/milroc/pc.git"},
"devDependencies": {
"uglify-js": "1.2.6",
"vows": "0.6.0"
}
}, null, 2)); | milroc/pc.js | src/package.js | JavaScript | bsd-3-clause | 485 |
/*
* Author: Kiveisha Yevgeniy
* Copyright (c) 2015 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "Utilities.h"
#include <string.h>
char
Utilities::toHEX (char code) {
return m_hex[code & 15];
}
long
Utilities::Escaping (char * src, char * dest) {
char *pstr = src;
char *pbuf = dest;
long count = 0;
while (*pstr) {
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') {
*pbuf++ = *pstr;
count++;
} else if (*pstr == ' ') {
*pbuf++ = '+';
count++;
} else if (*pstr == '=') {
*pbuf++ = *pstr;
count++;
} else {
*pbuf++ = '%', *pbuf++ = toHEX(*pstr >> 4), *pbuf++ = toHEX(*pstr & 15);
count += 3;
}
pstr++;
}
*pbuf = '\0';
return count;
}
std::string
Utilities::EncodeBase64 (unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++) {
ret += m_base64_chars[char_array_4[i]];
}
i = 0;
}
}
if (i) {
for(j = i; j < 3; j++) {
char_array_3[j] = '\0';
}
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++) {
ret += m_base64_chars[char_array_4[j]];
}
while((i++ < 3))
ret += '=';
}
return ret;
} | ykiveish/cortica-sdk | src/Utilities.cpp | C++ | bsd-3-clause | 2,892 |
#include "synchronization/Communicator.hpp"
namespace Synchronization
{
Communicator::Communicator()
: _numManagedCons(0),
_numManagedFmus(0)
{
}
size_type Synchronization::Communicator::addFmu(FMI::AbstractFmu* in, vector<FMI::InputMapping> & valuePacking)
{
vector<ConnectionSPtr>& connList = in->getConnections();
size_type numNewCons = 0;
for (auto & con : connList)
{
con->initialize(in->getFmuName());
size_type conId;
auto it = _knownConIds.find(con->getStartTag());
if (it == _knownConIds.end())
{
valuePacking.push_back(con->getPacking());
conId = _numManagedCons++;
_knownConIds[con->getStartTag()] = conId;
++numNewCons;
}
else
{
conId = it->second;
if (con->isShared())
{
++numNewCons;
valuePacking.push_back(con->getPacking());
}
}
con->setLocalId(conId);
}
in->setSharedId(_numManagedFmus++);
for (auto & con : connList)
{
if (con->getLocalId() + 1 > _connections.size())
{
_connections.resize(con->getLocalId() + 1);
_connections[con->getLocalId()] = con;
}
}
if (_outConnectionIds.size() < in->getSharedId() + 1)
{
_outConnectionIds.resize(in->getSharedId() + 1);
}
if (_inConnectionIds.size() < in->getSharedId() + 1)
{
_inConnectionIds.resize(in->getSharedId() + 1);
}
for (auto & i : connList)
{
if (i->isOutgoing(in->getFmuName()))
{
_outConnectionIds[in->getSharedId()].push_back(i->getLocalId());
}
else
{
_inConnectionIds[in->getSharedId()].push_back(i->getLocalId());
}
}
return numNewCons;
}
bool_type Communicator::send(HistoryEntry const & in, size_type communicationId)
{
return static_cast<bool_type>(_connections[communicationId]->send(in));
}
HistoryEntry Communicator::recv(size_type communicationId)
{
return _connections[communicationId]->recv();
}
int_type Communicator::connectionIsFree(size_type communicationId)
{
return _connections[communicationId]->hasFreeBuffer();
}
const vector<size_type> & Communicator::getInConnectionIds(const FMI::AbstractFmu * in) const
{
return _inConnectionIds[in->getSharedId()];
}
const vector<size_type> & Communicator::getOutConnectionIds(const FMI::AbstractFmu * in) const
{
return _outConnectionIds[in->getSharedId()];
}
size_type Communicator::getNumInConnections() const
{
size_type sum = 0;
for (const auto & _inConnectionId : _inConnectionIds)
{
sum += _inConnectionId.size();
}
return sum;
}
size_type Communicator::getNumOutConnections() const
{
size_type sum = 0;
for (const auto & _outConnectionId : _outConnectionIds)
{
sum += _outConnectionId.size();
}
return sum;
}
} /* namespace Synchronization */
| marchartung/ParallelFMU | src/synchronization/Communicator.cpp | C++ | bsd-3-clause | 3,412 |
#!/usr/bin/env python2
from __future__ import print_function
import sys
import os
import urllib
import argparse
import xml.etree.ElementTree as ET
def warn(*msgs):
for x in msgs: print('[WARNING]:', x, file=sys.stderr)
class PDBTM:
def __init__(self, filename):
#self.tree = ET.parse(filename)
#self.root = self.tree.getroot()
def strsum(l):
s = ''
for x in l: s += x.rstrip() + '\n'
return s
f = open(filename)
s = []
for l in f: s.append(l)
#s = strsum(s[1:-1]).strip()
s = strsum(s).strip()
self.root = ET.fromstring(s)
print(root)
def get_database(prefix='.'):
if not prefix.endswith('/'): prefix += '/'
print('Fetching database...', file=sys.stderr)
db = urllib.urlopen('http://pdbtm.enzim.hu/data/pdbtmall')
print('Saving database...', file=sys.stderr)
f = open('%s/pdbtmall' % prefix, 'w')
for l in db: f.write(l)
#f.write(db.read())
db.close()
f.close()
def build_database(fn, prefix):
print('Unpacking database...', file=sys.stderr)
f = open(fn)
db = f.read()
f.close()
firstline = 1
header = ''
entries = []
pdbids = []
for l in db.split('\n'):
if firstline:
header += l
firstline -= 1
continue
if 'PDBTM>' in l: continue
if l.startswith('<?'): continue
if l.startswith('<pdbtm'):
a = l.find('ID=') + 4
b = a + 4
pdbids.append(l[a:b])
entries.append(header)
entries[-1] += '\n' + l
if not prefix.endswith('/'): prefix += '/'
if not os.path.isdir(prefix): os.mkdir(prefix)
for entry in zip(pdbids, entries):
f = open(prefix + entry[0] + '.xml', 'w')
f.write(entry[1])
f.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Manages PDBTM databases. Automatically fetches the PDBTM database if no options are specified. Run without any arguments, dbtool will retrieve the PDBTM database, store it in pdbtm, and unpack it.')
parser.add_argument('-d', '--db', default='pdbtmall', help='name of concatenated database file {default:pdbtmall}')
parser.add_argument('-b', '--build-db', action='store_true', help='(re)build database from an existing pdbtmsall file (available at http://pdbtm.enzim.hu/data/pdbtmall)')
parser.add_argument('directory', nargs='?', default='pdbtm', help='directory to store database in')
parser.add_argument('-f', '--force-refresh', action='store_true', help='force overwrite of existing database. Functionally equivalent to removing the old database and rerunning.')
#parser.add_argument('-n', metavar='bundle_size', type=int, help='size to cut bundles into')
args = parser.parse_args()
if args.build_db: build_database(args.db, args.directory)
else: #db = PDBTM(args.db)
if not os.path.isdir(args.directory): os.mkdir(args.directory)
if args.force_refresh or not os.path.isfile('%s/%s' % (args.directory, args.db)): get_database(args.directory)
build_database('%s/%s' % (args.directory, args.db), args.directory)
#http://pdbtm.enzim.hu/data/pdbtmall
| khendarg/pdbtmtop | dbtool.py | Python | bsd-3-clause | 2,933 |
from django.template import Library, Node, resolve_variable, TemplateSyntaxError
from django.core.urlresolvers import reverse
register = Library()
@register.simple_tag
def active(request, pattern):
import re
if re.search(pattern, request.get_full_path()):
return 'active'
return '' | Kami/munin_exchange | munin_exchange/apps/core/templatetags/navclass.py | Python | bsd-3-clause | 307 |
#if !(NET35 || NET20 || WINDOWS_PHONE)
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Newtonsoft.Json.Utilities
{
internal sealed class DynamicProxyMetaObject<T> : DynamicMetaObject
{
private readonly DynamicProxy<T> _proxy;
private readonly bool _dontFallbackFirst;
internal DynamicProxyMetaObject(Expression expression, T value, DynamicProxy<T> proxy, bool dontFallbackFirst)
: base(expression, BindingRestrictions.Empty, value)
{
_proxy = proxy;
_dontFallbackFirst = dontFallbackFirst;
}
private new T Value { get { return (T)base.Value; } }
private bool IsOverridden(string method)
{
return _proxy.GetType().GetMember(method, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance).Cast<MethodInfo>()
.Any(info =>
// check that the method overrides the original on DynamicObjectProxy
info.DeclaringType != typeof(DynamicProxy<T>) &&
info.GetBaseDefinition().DeclaringType == typeof(DynamicProxy<T>));
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
return IsOverridden("TryGetMember")
? CallMethodWithResult("TryGetMember", binder, NoArgs, e => binder.FallbackGetMember(this, e))
: base.BindGetMember(binder);
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
return IsOverridden("TrySetMember")
? CallMethodReturnLast("TrySetMember", binder, GetArgs(value), e => binder.FallbackSetMember(this, value, e))
: base.BindSetMember(binder, value);
}
public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder)
{
return IsOverridden("TryDeleteMember")
? CallMethodNoResult("TryDeleteMember", binder, NoArgs, e => binder.FallbackDeleteMember(this, e))
: base.BindDeleteMember(binder);
}
public override DynamicMetaObject BindConvert(ConvertBinder binder)
{
return IsOverridden("TryConvert")
? CallMethodWithResult("TryConvert", binder, NoArgs, e => binder.FallbackConvert(this, e))
: base.BindConvert(binder);
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
if (!IsOverridden("TryInvokeMember"))
return base.BindInvokeMember(binder, args);
//
// Generate a tree like:
//
// {
// object result;
// TryInvokeMember(payload, out result)
// ? result
// : TryGetMember(payload, out result)
// ? FallbackInvoke(result)
// : fallbackResult
// }
//
// Then it calls FallbackInvokeMember with this tree as the
// "error", giving the language the option of using this
// tree or doing .NET binding.
//
Fallback fallback = e => binder.FallbackInvokeMember(this, args, e);
DynamicMetaObject call = BuildCallMethodWithResult(
"TryInvokeMember",
binder,
GetArgArray(args),
BuildCallMethodWithResult(
"TryGetMember",
new GetBinderAdapter(binder),
NoArgs,
fallback(null),
e => binder.FallbackInvoke(e, args, null)
),
null
);
return _dontFallbackFirst ? call : fallback(call);
}
public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args)
{
return IsOverridden("TryCreateInstance")
? CallMethodWithResult("TryCreateInstance", binder, GetArgArray(args), e => binder.FallbackCreateInstance(this, args, e))
: base.BindCreateInstance(binder, args);
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args)
{
return IsOverridden("TryInvoke")
? CallMethodWithResult("TryInvoke", binder, GetArgArray(args), e => binder.FallbackInvoke(this, args, e))
: base.BindInvoke(binder, args);
}
public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg)
{
return IsOverridden("TryBinaryOperation")
? CallMethodWithResult("TryBinaryOperation", binder, GetArgs(arg), e => binder.FallbackBinaryOperation(this, arg, e))
: base.BindBinaryOperation(binder, arg);
}
public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder)
{
return IsOverridden("TryUnaryOperation")
? CallMethodWithResult("TryUnaryOperation", binder, NoArgs, e => binder.FallbackUnaryOperation(this, e))
: base.BindUnaryOperation(binder);
}
public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
{
return IsOverridden("TryGetIndex")
? CallMethodWithResult("TryGetIndex", binder, GetArgArray(indexes), e => binder.FallbackGetIndex(this, indexes, e))
: base.BindGetIndex(binder, indexes);
}
public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
{
return IsOverridden("TrySetIndex")
? CallMethodReturnLast("TrySetIndex", binder, GetArgArray(indexes, value), e => binder.FallbackSetIndex(this, indexes, value, e))
: base.BindSetIndex(binder, indexes, value);
}
public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes)
{
return IsOverridden("TryDeleteIndex")
? CallMethodNoResult("TryDeleteIndex", binder, GetArgArray(indexes), e => binder.FallbackDeleteIndex(this, indexes, e))
: base.BindDeleteIndex(binder, indexes);
}
private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion);
private readonly static Expression[] NoArgs = new Expression[0];
private static Expression[] GetArgs(params DynamicMetaObject[] args)
{
return args.Select(arg => Expression.Convert(arg.Expression, typeof(object))).ToArray();
}
private static Expression[] GetArgArray(DynamicMetaObject[] args)
{
return new[] { Expression.NewArrayInit(typeof(object), GetArgs(args)) };
}
private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value)
{
return new Expression[]
{
Expression.NewArrayInit(typeof(object), GetArgs(args)),
Expression.Convert(value.Expression, typeof(object))
};
}
private static ConstantExpression Constant(DynamicMetaObjectBinder binder)
{
Type t = binder.GetType();
while (!t.IsVisible)
t = t.BaseType;
return Expression.Constant(binder, t);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic that returns a result
/// </summary>
private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke = null)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
DynamicMetaObject callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke)
{
//
// Build a new expression like:
// {
// object result;
// TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs.Add(result);
DynamicMetaObject resultMetaObject = new DynamicMetaObject(result, BindingRestrictions.Empty);
// Need to add a conversion if calling TryConvert
if (binder.ReturnType != typeof (object))
{
UnaryExpression convert = Expression.Convert(resultMetaObject.Expression, binder.ReturnType);
// will always be a cast or unbox
resultMetaObject = new DynamicMetaObject(convert, resultMetaObject.Restrictions);
}
if (fallbackInvoke != null)
resultMetaObject = fallbackInvoke(resultMetaObject);
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] {result},
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
resultMetaObject.Expression,
fallbackResult.Expression,
binder.ReturnType
)
),
GetRestrictions().Merge(resultMetaObject.Restrictions).Merge(fallbackResult.Restrictions)
);
return callDynamic;
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
/// </summary>
private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
//
// Build a new expression like:
// {
// object result;
// TrySetMember(payload, result = value) ? result : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof (T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs[args.Length + 1] = Expression.Assign(result, callArgs[args.Length + 1]);
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { result },
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
result,
fallbackResult.Expression,
typeof(object)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
/// </summary>
private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
//
// Build a new expression like:
// if (TryDeleteMember(payload)) { } else { fallbackResult }
//
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
Expression.Empty(),
fallbackResult.Expression,
typeof (void)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
/// <summary>
/// Returns a Restrictions object which includes our current restrictions merged
/// with a restriction limiting our type
/// </summary>
private BindingRestrictions GetRestrictions()
{
return (Value == null && HasValue)
? BindingRestrictions.GetInstanceRestriction(Expression, null)
: BindingRestrictions.GetTypeRestriction(Expression, LimitType);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _proxy.GetDynamicMemberNames(Value);
}
// It is okay to throw NotSupported from this binder. This object
// is only used by DynamicObject.GetMember--it is not expected to
// (and cannot) implement binding semantics. It is just so the DO
// can use the Name and IgnoreCase properties.
private sealed class GetBinderAdapter : GetMemberBinder
{
internal GetBinderAdapter(InvokeMemberBinder binder) :
base(binder.Name, binder.IgnoreCase)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotSupportedException();
}
}
}
}
#endif | hawkstalion/Tog-Mobile | Tog/json.net/Source/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs | C# | bsd-3-clause | 14,749 |
'''
Given a number, find the next higher number using only the digits in the given number.
For example if the given number is 1234, next higher number with same digits is 1243
'''
def FindNext(num):
number = str(num)
length = len(number)
for i in range(length-2,-1,-1):
current = number[i]
right = number[i+1]
if current < right:
temp = sorted(number[i:])
Next = temp[temp.index(current)+1]
temp.remove(Next)
temp = ''.join(temp)
return int(number[:i]+Next+temp)
return num
| jenniferwx/Programming_Practice | FindNextHigherNumberWithSameDigits.py | Python | bsd-3-clause | 578 |
package manifest
import (
"encoding/json"
"fmt"
"log"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/fatih/color"
"github.com/servehub/serve/manifest/processor"
"github.com/servehub/utils"
"github.com/servehub/utils/gabs"
)
type Manifest struct {
tree *gabs.Container
}
func (m Manifest) String() string {
return m.tree.StringIndent("", " ")
}
func (m Manifest) Unwrap() interface{} {
return m.tree.Data()
}
func (m Manifest) Has(path string) bool {
v := m.tree.Path(path).Data()
return v != nil && v != ""
}
func (m Manifest) GetString(path string) string {
return fmt.Sprintf("%v", m.tree.Path(path).Data())
}
func (m Manifest) GetStringOr(path string, defaultVal string) string {
if m.tree.ExistsP(path) {
return m.GetString(path)
}
return defaultVal
}
func (m Manifest) GetFloat(path string) float64 {
f, err := strconv.ParseFloat(m.GetString(path), 64)
if err != nil {
log.Fatalf("Error on parse float64 '%v' from: %v", path, m.GetString(path))
}
return f
}
func (m Manifest) GetInt(path string) int {
i, err := strconv.Atoi(m.GetString(path))
if err != nil {
log.Fatalf("Error on parse integer '%v' from: %v", path, m.GetString(path))
}
return i
}
func (m Manifest) GetIntOr(path string, defaultVal int) int {
if m.tree.ExistsP(path) {
return m.GetInt(path)
}
return defaultVal
}
func (m Manifest) GetBool(path string) bool {
return strings.ToLower(m.GetString(path)) == "true"
}
func (m Manifest) GetMap(path string) map[string]Manifest {
out := make(map[string]Manifest)
tree := m.tree
if len(path) > 0 && path != "." && path != "/" {
tree = m.tree.Path(path)
}
mmap, err := tree.ChildrenMap()
if err != nil {
log.Fatalf("Error get map '%v' from: %v. Error: %s", path, m.tree.Path(path).Data(), err)
}
for k, v := range mmap {
out[k] = Manifest{v}
}
return out
}
func (m Manifest) GetArray(path string) []Manifest {
out := make([]Manifest, 0)
arr, err := m.tree.Path(path).Children()
if err != nil {
log.Fatalf("Error get array `%v` from: %v", path, m.tree.Path(path).Data())
}
for _, v := range arr {
out = append(out, Manifest{v})
}
return out
}
func (m Manifest) GetArrayForce(path string) []interface{} {
out := make([]interface{}, 0)
arr, err := m.tree.Path(path).Children()
if err != nil && m.tree.ExistsP(path) {
arr = append(arr, m.tree.Path(path))
}
for _, v := range arr {
out = append(out, v.Data())
}
return out
}
func (m Manifest) GetTree(path string) Manifest {
return Manifest{m.tree.Path(path)}
}
func (m Manifest) Set(path string, value interface{}) {
m.tree.SetP(value, path)
}
func (m Manifest) ArrayAppend(path string, value interface{}) {
m.tree.ArrayAppendP(value, path)
}
func (m Manifest) FindPlugins(plugin string) ([]PluginData, error) {
tree := m.tree.Path(plugin)
result := make([]PluginData, 0)
if tree.Data() == nil {
return nil, fmt.Errorf("Plugin `%s` not found in manifest!", plugin)
}
if _, ok := tree.Data().([]interface{}); ok {
arr, _ := tree.Children()
for _, item := range arr {
if _, ok := item.Data().(string); ok {
result = append(result, makePluginPair(plugin, item))
} else if res, err := item.ChildrenMap(); err == nil {
if len(res) == 1 {
for subplugin, data := range res {
result = append(result, makePluginPair(plugin+"."+subplugin, data))
break
}
} else if len(res) == 0 && !PluginRegestry.Has(plugin) {
// skip subplugin with empty data
} else {
result = append(result, makePluginPair(plugin, item))
}
}
}
} else if PluginRegestry.Has(plugin) {
result = append(result, makePluginPair(plugin, tree))
} else {
log.Println(color.YellowString("Plugins for `%s` section not specified, skip...", plugin))
}
return result, nil
}
func (m Manifest) DelTree(path string) error {
return m.tree.DeleteP(path)
}
func (m Manifest) GetPluginWithData(plugin string) PluginData {
return makePluginPair(plugin, m.tree)
}
var envNameRegex = regexp.MustCompile("\\W")
func (m Manifest) ToEnvMap(prefix string) map[string]string {
result := make(map[string]string)
if children, err := m.tree.ChildrenMap(); err == nil {
for k, child := range children {
result = utils.MergeMaps(result, Manifest{child}.ToEnvMap(prefix+strings.ToUpper(envNameRegex.ReplaceAllString(k, "_"))+"_"))
}
} else if children, err := m.tree.Children(); err == nil {
for i, child := range children {
result = utils.MergeMaps(result, Manifest{child}.ToEnvMap(prefix+strconv.Itoa(i)+"_"))
}
} else if m.tree.Data() != nil {
result[prefix[:len(prefix)-1]] = fmt.Sprintf("%v", m.tree.Data())
}
return result
}
func Load(path string, vars map[string]string) *Manifest {
tree, err := gabs.LoadYamlFile(path)
if err != nil {
log.Fatalln("Error on load file:", err)
}
for k, v := range vars {
tree.Set(v, "vars", k)
}
for _, proc := range processor.GetAll() {
if err := proc.Process(tree); err != nil {
log.Fatalf("Error in processor '%v': %v. \n\nManifest: %s", reflect.ValueOf(proc).Type().Name(), err, tree.StringIndent("", " "))
}
}
return &Manifest{tree}
}
func LoadJSON(path string) *Manifest {
tree, err := gabs.ParseJSONFile(path)
if err != nil {
log.Fatalf("Error on load json file '%s': %v\n", path, err)
}
return &Manifest{tree}
}
func ParseJSON(json string) *Manifest {
tree, err := gabs.ParseJSON([]byte(json))
if err != nil {
log.Fatalf("Error on parse json '%s': %v\n", json, err)
}
return &Manifest{tree}
}
func makePluginPair(plugin string, data *gabs.Container) PluginData {
if s, ok := data.Data().(string); ok {
obj := gabs.New()
ns := strings.Split(plugin, ".")
obj.Set(s, ns[len(ns)-1])
data = obj
} else {
var cpy interface{}
bs, _ := json.Marshal(data.Data())
json.Unmarshal(bs, &cpy)
data.Set(cpy)
}
return PluginData{plugin, PluginRegestry.Get(plugin), Manifest{data}}
}
| servehub/serve | manifest/manifest.go | GO | bsd-3-clause | 5,887 |
<?php
return array (
'This user account is not approved yet!' => 'Tento účet ještě není aktivován!',
'User not found!' => 'Uživatel nebyl nalezen!',
'You need to login to view this user profile!' => 'Abyste mohli prohlížet tento profil, je potřeba se nejdříve přihlásit.',
);
| LeonidLyalin/vova | common/humhub/protected/humhub/modules/user/messages/cs/behaviors_ProfileControllerBehavior.php | PHP | bsd-3-clause | 296 |
#region copyright
// Copyright (c) 2012, TIGWI
// All rights reserved.
// Distributed under BSD 2-Clause license
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Tigwi.UI.Models.Storage
{
using Tigwi.Storage.Library;
public class DuplicateUserException : Exception
{
public DuplicateUserException(string login, UserAlreadyExists innerException)
: base("This username is already taken.", innerException)
{
}
}
public class UserNotFoundException : Exception
{
public UserNotFoundException(string login, UserNotFound innerException)
: base("There is no user with the given login `" + login + "'.", innerException)
{
}
public UserNotFoundException(Guid id, UserNotFound innerException)
: base("There is no user with the given ID `" + id + "'.", innerException)
{
}
}
public class DuplicateAccountException : Exception
{
public DuplicateAccountException(string name, AccountAlreadyExists innerException)
: base("There is already an account with the given name `" + name + "'.", innerException)
{
}
}
public class AccountNotFoundException : Exception
{
public AccountNotFoundException(string name, AccountNotFound innerException)
: base("There is no account with the given name `" + name + "'.", innerException)
{
}
}
} | ismaelbelghiti/Tigwi | Core/Tigwi.UI/Models/Storage/StorageException.cs | C# | bsd-3-clause | 1,512 |
import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
if self.data:
return
resp = requests.get(self.url)
if resp.status_code != 200:
resp.raise_for_status()
self.data = resp.json()
self.created = self.data[-1]['created']
def summary(self):
"""Generates summary data of today's state"""
self.get_data()
highlight = self.highlight
last_item = self.data[-1]
output = {}
output['app'] = self.app or 'ALL'
data = last_item['locales']
if self.app:
get_item = lambda x: x['apps'][self.app]
else:
get_item = lambda x: x
apps = data.items()[0][1]['apps'].keys()
apps.sort()
output['apps'] = apps
items = [item for item in data.items() if item[0] not in highlight]
hitems = [item for item in data.items() if item[0] in highlight]
highlighted = []
if hitems:
for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
highlighted.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['highlighted'] = highlighted
locales = []
for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
locales.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['locales'] = locales
output['created'] = self.created
return output
def _mark_movement(self, data):
"""For each item, converts to a tuple of (movement, item)"""
ret = []
prev_day = None
for i, day in enumerate(data):
if i == 0:
ret.append(('', day))
prev_day = day
continue
if prev_day > day:
item = ('down', day)
elif prev_day < day:
item = ('up', day)
else:
item = ('equal', day)
prev_day = day
ret.append(item)
return ret
def history(self):
self.get_data()
data = self.data
highlight = self.highlight
app = self.app
# Get a list of the locales we'll iterate through
locales = sorted(data[-1]['locales'].keys())
num_days = 14
# Truncate the data to what we want to look at
data = data[-num_days:]
if app:
get_data = lambda x: x['apps'][app]['percent']
else:
get_data = lambda x: x['percent']
hlocales = [loc for loc in locales if loc in highlight]
locales = [loc for loc in locales if loc not in highlight]
output = {}
output['app'] = self.app or 'All'
output['headers'] = [item['created'] for item in data]
output['highlighted'] = sorted(
(loc, self._mark_movement(get_data(day['locales'][loc]) for day in data))
for loc in hlocales
)
output['locales'] = sorted(
(loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data))
for loc in locales
)
output['created'] = self.created
return output
| willkg/postatus | postatus/status.py | Python | bsd-3-clause | 4,559 |
<?php
/**
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cloud_StorageService
* @subpackage Adapter
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* namespace
*/
namespace Zend\Cloud\StorageService\Adapter;
use Traversable,
Zend\Cloud\StorageService\Adapter,
Zend\Cloud\StorageService\Exception,
Zend\Service\Rackspace\Exception as RackspaceException,
Zend\Service\Rackspace\Files as RackspaceFile,
Zend\Stdlib\ArrayUtils;
/**
* Adapter for Rackspace cloud storage
*
* @category Zend
* @package Zend_Cloud_StorageService
* @subpackage Adapter
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Rackspace implements Adapter
{
const USER = 'user';
const API_KEY = 'key';
const REMOTE_CONTAINER = 'container';
const DELETE_METADATA_KEY = 'ZF_metadata_deleted';
/**
* The Rackspace adapter
* @var RackspaceFile
*/
protected $rackspace;
/**
* Container in which files are stored
* @var string
*/
protected $container = 'default';
/**
* Constructor
*
* @param array|Traversable $options
* @return void
*/
function __construct($options = array())
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (!is_array($options) || empty($options)) {
throw new Exception\InvalidArgumentException('Invalid options provided');
}
try {
$this->rackspace = new RackspaceFile($options[self::USER], $options[self::API_KEY]);
} catch (RackspaceException $e) {
throw new Exception\RuntimeException('Error on create: '.$e->getMessage(), $e->getCode(), $e);
}
if (isset($options[self::HTTP_ADAPTER])) {
$this->rackspace->getHttpClient()->setAdapter($options[self::HTTP_ADAPTER]);
}
if (!empty($options[self::REMOTE_CONTAINER])) {
$this->container = $options[self::REMOTE_CONTAINER];
}
}
/**
* Get an item from the storage service.
*
* @param string $path
* @param array $options
* @return mixed
*/
public function fetchItem($path, $options = null)
{
$item = $this->rackspace->getObject($this->container,$path, $options);
if (!$this->rackspace->isSuccessful() && ($this->rackspace->getErrorCode()!='404')) {
throw new Exception\RuntimeException('Error on fetch: '.$this->rackspace->getErrorMsg());
}
if (!empty($item)) {
return $item->getContent();
} else {
return false;
}
}
/**
* Store an item in the storage service.
*
* @param string $destinationPath
* @param mixed $data
* @param array $options
* @return void
*/
public function storeItem($destinationPath, $data, $options = null)
{
$this->rackspace->storeObject($this->container,$destinationPath,$data,$options);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on store: '.$this->rackspace->getErrorMsg());
}
}
/**
* Delete an item in the storage service.
*
* @param string $path
* @param array $options
* @return void
*/
public function deleteItem($path, $options = null)
{
$this->rackspace->deleteObject($this->container,$path);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on delete: '.$this->rackspace->getErrorMsg());
}
}
/**
* Copy an item in the storage service to a given path.
*
* @param string $sourcePath
* @param string $destination path
* @param array $options
* @return void
*/
public function copyItem($sourcePath, $destinationPath, $options = null)
{
$this->rackspace->copyObject($this->container,$sourcePath,$this->container,$destinationPath,$options);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on copy: '.$this->rackspace->getErrorMsg());
}
}
/**
* Move an item in the storage service to a given path.
* WARNING: This operation is *very* expensive for services that do not
* support moving an item natively.
*
* @param string $sourcePath
* @param string $destination path
* @param array $options
* @return void
*/
public function moveItem($sourcePath, $destinationPath, $options = null)
{
try {
$this->copyItem($sourcePath, $destinationPath, $options);
} catch (Exception\RuntimeException $e) {
throw new Exception\RuntimeException('Error on move: '.$e->getMessage());
}
try {
$this->deleteItem($sourcePath);
} catch (Exception\RuntimeException $e) {
$this->deleteItem($destinationPath);
throw new Exception\RuntimeException('Error on move: '.$e->getMessage());
}
}
/**
* Rename an item in the storage service to a given name.
*
* @param string $path
* @param string $name
* @param array $options
* @return void
*/
public function renameItem($path, $name, $options = null)
{
throw new Exception\OperationNotAvailableException('Renaming not implemented');
}
/**
* Get a key/value array of metadata for the given path.
*
* @param string $path
* @param array $options
* @return array An associative array of key/value pairs specifying the metadata for this object.
* If no metadata exists, an empty array is returned.
*/
public function fetchMetadata($path, $options = null)
{
$result = $this->rackspace->getMetadataObject($this->container,$path);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on fetch metadata: '.$this->rackspace->getErrorMsg());
}
$metadata = array();
if (isset($result['metadata'])) {
$metadata = $result['metadata'];
}
// delete the self::DELETE_METADATA_KEY - this is a trick to remove all
// the metadata information of an object (see deleteMetadata).
// Rackspace doesn't have an API to remove the metadata of an object
unset($metadata[self::DELETE_METADATA_KEY]);
return $metadata;
}
/**
* Store a key/value array of metadata at the given path.
* WARNING: This operation overwrites any metadata that is located at
* $destinationPath.
*
* @param string $destinationPath
* @param array $metadata associative array specifying the key/value pairs for the metadata.
* @param array $options
* @return void
*/
public function storeMetadata($destinationPath, $metadata, $options = null)
{
$this->rackspace->setMetadataObject($this->container, $destinationPath, $metadata);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on store metadata: '.$this->rackspace->getErrorMsg());
}
}
/**
* Delete a key/value array of metadata at the given path.
*
* @param string $path
* @param array $metadata - An associative array specifying the key/value pairs for the metadata
* to be deleted. If null, all metadata associated with the object will
* be deleted.
* @param array $options
* @return void
*/
public function deleteMetadata($path, $metadata = null, $options = null)
{
if (empty($metadata)) {
$newMetadata = array(self::DELETE_METADATA_KEY => true);
try {
$this->storeMetadata($path, $newMetadata);
} catch (Exception\RuntimeException $e) {
throw new Exception\RuntimeException('Error on delete metadata: '.$e->getMessage());
}
} else {
try {
$oldMetadata = $this->fetchMetadata($path);
} catch (Exception\RuntimeException $e) {
throw new Exception\RuntimeException('Error on delete metadata: '.$e->getMessage());
}
$newMetadata = array_diff_assoc($oldMetadata, $metadata);
try {
$this->storeMetadata($path, $newMetadata);
} catch (Exception\RuntimeException $e) {
throw new Exception\RuntimeException('Error on delete metadata: '.$e->getMessage());
}
}
}
/*
* Recursively traverse all the folders and build an array that contains
* the path names for each folder.
*
* @param string $path folder path to get the list of folders from.
* @param array& $resultArray reference to the array that contains the path names
* for each folder.
* @return void
*/
private function getAllFolders($path, &$resultArray)
{
if (!empty($path)) {
$options = array (
'prefix' => $path
);
}
$files = $this->rackspace->getObjects($this->container,$options);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on get all folders: '.$this->rackspace->getErrorMsg());
}
$resultArray = array();
foreach ($files as $file) {
$resultArray[dirname($file->getName())] = true;
}
$resultArray = array_keys($resultArray);
}
/**
* Return an array of the items contained in the given path. The items
* returned are the files or objects that in the specified path.
*
* @param string $path
* @param array $options
* @return array
*/
public function listItems($path, $options = null)
{
if (!empty($path)) {
$options = array (
'prefix' => $path
);
}
$files = $this->rackspace->getObjects($this->container,$options);
if (!$this->rackspace->isSuccessful()) {
throw new Exception\RuntimeException('Error on list items: '.$this->rackspace->getErrorMsg());
}
$resultArray = array();
if (!empty($files)) {
foreach ($files as $file) {
$resultArray[] = $file->getName();
}
}
return $resultArray;
}
/**
* Get the concrete client.
*
* @return RackspaceFile
*/
public function getClient()
{
return $this->rackspace;
}
}
| dineshkummarc/zf2 | library/Zend/Cloud/StorageService/Adapter/Rackspace.php | PHP | bsd-3-clause | 11,465 |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package contenant la commande 'débarquer'."""
from math import sqrt
from primaires.interpreteur.commande.commande import Commande
from secondaires.navigation.constantes import *
class CmdDebarquer(Commande):
"""Commande 'debarquer'"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "debarquer", "debark")
self.nom_categorie = "navire"
self.aide_courte = "débarque du navire"
self.aide_longue = \
"Cette commande permet de débarquer du navire sur lequel " \
"on se trouve. On doit se trouver assez prêt d'une côte " \
"pour débarquer dessus."
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
salle = personnage.salle
if not hasattr(salle, "navire") or salle.navire is None:
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
navire = salle.navire
if navire.etendue is None:
personnage << "|err|Vous n'êtes pas sur un navire.|ff|"
return
personnage.agir("bouger")
# On va chercher la salle la plus proche
etendue = navire.etendue
# On cherche la salle de nagvire la plus proche
d_salle = None # la salle de destination
distance = 2
x, y, z = salle.coords.tuple()
for t_salle in etendue.cotes.values():
if t_salle.coords.z == z:
t_x, t_y, t_z = t_salle.coords.tuple()
t_distance = sqrt((x - t_x) ** 2 + (y - t_y) ** 2)
if t_distance < distance and t_salle.nom_terrain in \
TERRAINS_ACCOSTABLES:
d_salle = t_salle
distance = t_distance
if d_salle is None:
personnage << "|err|Aucun quai n'a pu être trouvé à " \
"proximité.|ff|"
return
personnage.salle = d_salle
personnage << "Vous sautez sur {}.".format(
d_salle.titre.lower())
personnage << d_salle.regarder(personnage)
d_salle.envoyer("{{}} arrive en sautant depuis {}.".format(
navire.nom), personnage)
salle.envoyer("{{}} saute sur {}.".format(
d_salle.titre.lower()), personnage)
importeur.hook["personnage:deplacer"].executer(
personnage, d_salle, None, 0)
if not hasattr(d_salle, "navire") or d_salle.navire is None:
personnage.envoyer_tip("N'oubliez pas d'amarrer votre navire " \
"avec %amarre% %amarre:attacher%.")
| vlegoff/tsunami | src/secondaires/navigation/commandes/debarquer/__init__.py | Python | bsd-3-clause | 4,221 |
#include<iostream>
using namespace std;
int a[]={1,255,8,6,25,47,14,35,58,75,96,158,657};
const int len = sizeof(a)/sizeof(int);
int b[10][len+1] = { 0 }; //将b全部置0
void bucketSort(int a[]);//桶排序函数
void distributeElments(int a[],int b[10][len+1],int digits);
void collectElments(int a[],int b[10][len+1]);
int numOfDigits(int a[]);
void zeroBucket(int b[10][len+1]);//将b数组中的全部元素置0
int main()
{
cout<<"原始数组:";
for(int i=0;i<len;i++)
cout<<a[i]<<",";
cout<<endl;
bucketSort(a);
cout<<"排序后数组:";
for(int i=0;i<len;i++)
cout<<a[i]<<",";
cout<<endl;
return 0;
}
void bucketSort(int a[])
{
int digits=numOfDigits(a);
for(int i=1;i<=digits;i++)
{
distributeElments(a,b,i);
collectElments(a,b);
if(i!=digits)
zeroBucket(b);
}
}
int numOfDigits(int a[])
{
int largest=0;
for(int i=0;i<len;i++)//获取最大值
if(a[i]>largest)
largest=a[i];
int digits=0;//digits为最大值的位数
while(largest)
{
digits++;
largest/=10;
}
return digits;
}
void distributeElments(int a[],int b[10][len+1],int digits)
{
int divisor=10;//除数
for(int i=1;i<digits;i++)
divisor*=10;
for(int j=0;j<len;j++)
{
int numOfDigist=(a[j]%divisor-a[j]%(divisor/10))/(divisor/10);
//numOfDigits为相应的(divisor/10)位的值,如当divisor=10时,求的是个位数
int num=++b[numOfDigist][0];//用b中第一列的元素来储存每行中元素的个数
b[numOfDigist][num]=a[j];
}
}
void collectElments(int a[],int b[10][len+1])
{
int k=0;
for(int i=0;i<10;i++)
for(int j=1;j<=b[i][0];j++)
a[k++]=b[i][j];
}
void zeroBucket(int b[][len+1])
{
for(int i=0;i<10;i++)
for(int j=0;j<len+1;j++)
b[i][j]=0;
}
| 1106944911/leetcode | C++/bucketSort.cpp | C++ | bsd-3-clause | 1,907 |
#
# GtkMain.py -- pygtk threading help routines.
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
"""
GUI threading help routines.
Usage:
import GtkMain
# See constructor for GtkMain for options
self.mygtk = GtkMain.GtkMain()
# NOT THIS
#gtk.main()
# INSTEAD, main thread calls this:
self.mygtk.mainloop()
# (asynchronous call)
self.mygtk.gui_do(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN)
# OR
# (synchronous call)
res = self.mygtk.gui_call(method, arg1, arg2, ... argN, kwd1=val1, ..., kwdN=valN)
# To cause the GUI thread to terminate the mainloop
self.mygtk.qui_quit()
"""
import sys, traceback
import thread, threading
import logging
import Queue as que
import gtk
from ginga.misc import Task, Future
class GtkMain(object):
def __init__(self, queue=None, logger=None, ev_quit=None):
# You can pass in a queue if you prefer to do so
if not queue:
queue = que.Queue()
self.gui_queue = queue
# You can pass in a logger if you prefer to do so
if logger == None:
logger = logging.getLogger('GtkHelper')
self.logger = logger
if not ev_quit:
ev_quit = threading.Event()
self.ev_quit = ev_quit
self.gui_thread_id = None
def update_pending(self, timeout=0.0):
"""Process all pending GTK events and return. _timeout_ is a tuning
parameter for performance.
"""
# Process "out-of-band" GTK events
try:
while gtk.events_pending():
#gtk.main_iteration(False)
gtk.main_iteration()
finally:
pass
done = False
while not done:
# Process "in-band" GTK events
try:
future = self.gui_queue.get(block=True,
timeout=timeout)
# Execute the GUI method
try:
try:
res = future.thaw(suppress_exception=False)
except Exception, e:
future.resolve(e)
self.logger.error("gui error: %s" % str(e))
try:
(type, value, tb) = sys.exc_info()
tb_str = "".join(traceback.format_tb(tb))
self.logger.error("Traceback:\n%s" % (tb_str))
except Exception, e:
self.logger.error("Traceback information unavailable.")
finally:
pass
except que.Empty:
done = True
except Exception, e:
self.logger.error("Main GUI loop error: %s" % str(e))
# Process "out-of-band" GTK events again
try:
while gtk.events_pending():
#gtk.main_iteration(False)
gtk.main_iteration()
finally:
pass
def gui_do(self, method, *args, **kwdargs):
"""General method for asynchronously calling into the GUI.
It makes a future to call the given (method) with the given (args)
and (kwdargs) inside the gui thread. If the calling thread is a
non-gui thread the future is returned.
"""
future = Future.Future()
future.freeze(method, *args, **kwdargs)
self.gui_queue.put(future)
my_id = thread.get_ident()
if my_id != self.gui_thread_id:
return future
def gui_call(self, method, *args, **kwdargs):
"""General method for synchronously calling into the GUI.
This waits until the method has completed before returning.
"""
my_id = thread.get_ident()
if my_id == self.gui_thread_id:
return method(*args, **kwdargs)
else:
future = self.gui_do(method, *args, **kwdargs)
return future.wait()
def gui_do_future(self, future):
self.gui_queue.put(future)
return future
def nongui_do(self, method, *args, **kwdargs):
task = Task.FuncTask(method, args, kwdargs, logger=self.logger)
return self.nongui_do_task(task)
def nongui_do_cb(self, tup, method, *args, **kwdargs):
task = Task.FuncTask(method, args, kwdargs, logger=self.logger)
task.register_callback(tup[0], args=tup[1:])
return self.nongui_do_task(task)
def nongui_do_future(self, future):
task = Task.FuncTask(future.thaw, (), {}, logger=self.logger)
return self.nongui_do_task(task)
def nongui_do_task(self, task):
try:
task.init_and_start(self)
return task
except Exception, e:
self.logger.error("Error starting task: %s" % (str(e)))
raise(e)
def assert_gui_thread(self):
my_id = thread.get_ident()
assert my_id == self.gui_thread_id, \
Exception("Non-GUI thread (%d) is executing GUI code!" % (
my_id))
def assert_nongui_thread(self):
my_id = thread.get_ident()
assert my_id != self.gui_thread_id, \
Exception("GUI thread (%d) is executing non-GUI code!" % (
my_id))
def mainloop(self, timeout=0.001):
# Mark our thread id
self.gui_thread_id = thread.get_ident()
while not self.ev_quit.isSet():
self.update_pending(timeout=timeout)
def gui_quit(self):
"Call this to cause the GUI thread to quit the mainloop."""
self.ev_quit.set()
# END
| Rbeaty88/ginga | ginga/gtkw/GtkMain.py | Python | bsd-3-clause | 5,866 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model backend\modules\inspection\models\InspectionHospitalMapSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="inspection-hospital-map-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'insp_id') ?>
<?= $form->field($model, 'hosp_id') ?>
<?= $form->field($model, 'contact') ?>
<?php // echo $form->field($model, 'isleaf') ?>
<?php // echo $form->field($model, 'status') ?>
<?php // echo $form->field($model, 'utime') ?>
<?php // echo $form->field($model, 'uid') ?>
<?php // echo $form->field($model, 'ctime') ?>
<?php // echo $form->field($model, 'cid') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| Gcaufy/shengzaizai | backend/modules/inspection/views/hospital/_search.php | PHP | bsd-3-clause | 1,079 |
/*! jQuery UI - v1.11.4 - 2015-12-06
* http://jqueryui.com
* Includes: core.js, datepicker.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
/*!
* jQuery UI Core 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.11.4",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
scrollParent: function( includeHidden ) {
var position = this.css( "position" ),
excludeStaticParent = position === "absolute",
overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
scrollParent = this.parents().filter( function() {
var parent = $( this );
if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
return false;
}
return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
}).eq( 0 );
return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
},
uniqueId: (function() {
var uuid = 0;
return function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + ( ++uuid );
}
});
};
})(),
removeUniqueId: function() {
return this.each(function() {
if ( /^ui-id-\d+$/.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
});
}
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap='#" + mapName + "']" )[ 0 ];
return !!img && visible( img );
}
return ( /^(input|select|textarea|button|object)$/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
$.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
}) :
// support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
$.fn.removeData = (function( removeData ) {
return function( key ) {
if ( arguments.length ) {
return removeData.call( this, $.camelCase( key ) );
} else {
return removeData.call( this );
}
};
})( $.fn.removeData );
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
$.fn.extend({
focus: (function( orig ) {
return function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
orig.apply( this, arguments );
};
})( $.fn.focus ),
disableSelection: (function() {
var eventType = "onselectstart" in document.createElement( "div" ) ?
"selectstart" :
"mousedown";
return function() {
return this.bind( eventType + ".ui-disableSelection", function( event ) {
event.preventDefault();
});
};
})(),
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
}
});
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
$.ui.plugin = {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args, allowDisconnected ) {
var i,
set = instance.plugins[ name ];
if ( !set ) {
return;
}
if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
};
/*!
* jQuery UI Datepicker 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/datepicker/
*/
$.extend($.ui, { datepicker: { version: "1.11.4" } });
var datepicker_instActive;
function datepicker_getZindex( elem ) {
var position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
return 0;
}
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[""] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: ["January","February","March","April","May","June",
"July","August","September","October","November","December"], // Names of months for drop-down and formatting
monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend(this._defaults, this.regional[""]);
this.regional.en = $.extend( true, {}, this.regional[ "" ]);
this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: "hasDatepicker",
//Keep track of the maximum number of rows displayed (see #7043)
maxRows: 4,
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
* @param settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function(settings) {
datepicker_extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
* @param target element - the target input field or division or span
* @param settings object - the new settings to use for this date picker instance (anonymous)
*/
_attachDatepicker: function(target, settings) {
var nodeName, inline, inst;
nodeName = target.nodeName.toLowerCase();
inline = (nodeName === "div" || nodeName === "span");
if (!target.id) {
this.uuid += 1;
target.id = "dp" + this.uuid;
}
inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {});
if (nodeName === "input") {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName)) {
return;
}
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
keypress(this._doKeyPress).keyup(this._doKeyUp);
this._autoSize(inst);
$.data(target, "datepicker", inst);
//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var showOn, buttonText, buttonImage,
appendText = this._get(inst, "appendText"),
isRTL = this._get(inst, "isRTL");
if (inst.append) {
inst.append.remove();
}
if (appendText) {
inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
input[isRTL ? "before" : "after"](inst.append);
}
input.unbind("focus", this._showDatepicker);
if (inst.trigger) {
inst.trigger.remove();
}
showOn = this._get(inst, "showOn");
if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
}
if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
buttonText = this._get(inst, "buttonText");
buttonImage = this._get(inst, "buttonImage");
inst.trigger = $(this._get(inst, "buttonImageOnly") ?
$("<img/>").addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$("<button type='button'></button>").addClass(this._triggerClass).
html(!buttonImage ? buttonText : $("<img/>").attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? "before" : "after"](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
$.datepicker._hideDatepicker();
} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
$.datepicker._hideDatepicker();
$.datepicker._showDatepicker(input[0]);
} else {
$.datepicker._showDatepicker(input[0]);
}
return false;
});
}
},
/* Apply the maximum length for the date format. */
_autoSize: function(inst) {
if (this._get(inst, "autoSize") && !inst.inline) {
var findMax, max, maxI, i,
date = new Date(2009, 12 - 1, 20), // Ensure double digits
dateFormat = this._get(inst, "dateFormat");
if (dateFormat.match(/[DM]/)) {
findMax = function(names) {
max = 0;
maxI = 0;
for (i = 0; i < names.length; i++) {
if (names[i].length > max) {
max = names[i].length;
maxI = i;
}
}
return maxI;
};
date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
"monthNames" : "monthNamesShort"))));
date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
}
inst.input.attr("size", this._formatDate(inst, date).length);
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName)) {
return;
}
divSpan.addClass(this.markerClassName).append(inst.dpDiv);
$.data(target, "datepicker", inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
inst.dpDiv.css( "display", "block" );
},
/* Pop-up the date picker in a "dialog" box.
* @param input element - ignored
* @param date string or Date - the initial date to display
* @param onSelect function - the function to call when a date is selected
* @param settings object - update the dialog date picker instance's settings (anonymous object)
* @param pos int[2] - coordinates for the dialog's position within the screen or
* event - with x/y coordinates or
* leave empty for default (screen centre)
* @return the manager object
*/
_dialogDatepicker: function(input, date, onSelect, settings, pos) {
var id, browserWidth, browserHeight, scrollX, scrollY,
inst = this._dialogInst; // internal instance
if (!inst) {
this.uuid += 1;
id = "dp" + this.uuid;
this._dialogInput = $("<input type='text' id='" + id +
"' style='position: absolute; top: -100px; width: 0px;'/>");
this._dialogInput.keydown(this._doKeyDown);
$("body").append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], "datepicker", inst);
}
datepicker_extendRemove(inst.settings, settings || {});
date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
this._dialogInput.val(date);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
browserWidth = document.documentElement.clientWidth;
browserHeight = document.documentElement.clientHeight;
scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI) {
$.blockUI(this.dpDiv);
}
$.data(this._dialogInput[0], "datepicker", inst);
return this;
},
/* Detach a datepicker from its control.
* @param target element - the target input field or division or span
*/
_destroyDatepicker: function(target) {
var nodeName,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
$.removeData(target, "datepicker");
if (nodeName === "input") {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind("focus", this._showDatepicker).
unbind("keydown", this._doKeyDown).
unbind("keypress", this._doKeyPress).
unbind("keyup", this._doKeyUp);
} else if (nodeName === "div" || nodeName === "span") {
$target.removeClass(this.markerClassName).empty();
}
if ( datepicker_instActive === inst ) {
datepicker_instActive = null;
}
},
/* Enable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_enableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = false;
inst.trigger.filter("button").
each(function() { this.disabled = false; }).end().
filter("img").css({opacity: "1.0", cursor: ""});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().removeClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", false);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_disableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = true;
inst.trigger.filter("button").
each(function() { this.disabled = true; }).end().
filter("img").css({opacity: "0.5", cursor: "default"});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().addClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", true);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
* @param target element - the target input field or division or span
* @return boolean - true if disabled, false if enabled
*/
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] === target) {
return true;
}
}
return false;
},
/* Retrieve the instance data for the target control.
* @param target element - the target input field or division or span
* @return object - the associated instance data
* @throws error if a jQuery problem getting data
*/
_getInst: function(target) {
try {
return $.data(target, "datepicker");
}
catch (err) {
throw "Missing instance data for this datepicker";
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
* @param target element - the target input field or division or span
* @param name object - the new settings to update or
* string - the name of the setting to change or retrieve,
* when retrieving also "all" for all instance settings or
* "defaults" for all global defaults
* @param value any - the new value for the setting
* (omit if above is an object or to retrieve a value)
*/
_optionDatepicker: function(target, name, value) {
var settings, date, minDate, maxDate,
inst = this._getInst(target);
if (arguments.length === 2 && typeof name === "string") {
return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
(inst ? (name === "all" ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
settings = name || {};
if (typeof name === "string") {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst === inst) {
this._hideDatepicker();
}
date = this._getDateDatepicker(target, true);
minDate = this._getMinMaxDate(inst, "min");
maxDate = this._getMinMaxDate(inst, "max");
datepicker_extendRemove(inst.settings, settings);
// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
inst.settings.minDate = this._formatDate(inst, minDate);
}
if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
inst.settings.maxDate = this._formatDate(inst, maxDate);
}
if ( "disabled" in settings ) {
if ( settings.disabled ) {
this._disableDatepicker(target);
} else {
this._enableDatepicker(target);
}
}
this._attachments($(target), inst);
this._autoSize(inst);
this._setDate(inst, date);
this._updateAlternate(inst);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
* @param target element - the target input field or division or span
*/
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
* @param target element - the target input field or division or span
* @param date Date - the new date
*/
_setDateDatepicker: function(target, date) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
* @param target element - the target input field or division or span
* @param noDefault boolean - true if no default date is to be used
* @return Date - the current date
*/
_getDateDatepicker: function(target, noDefault) {
var inst = this._getInst(target);
if (inst && !inst.inline) {
this._setDateFromField(inst, noDefault);
}
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var onSelect, dateStr, sel,
inst = $.datepicker._getInst(event.target),
handled = true,
isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
inst._keyEvent = true;
if ($.datepicker._datepickerShowing) {
switch (event.keyCode) {
case 9: $.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
$.datepicker._currentClass + ")", inst.dpDiv);
if (sel[0]) {
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
}
onSelect = $.datepicker._get(inst, "onSelect");
if (onSelect) {
dateStr = $.datepicker._formatDate(inst);
// trigger custom callback
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
} else {
$.datepicker._hideDatepicker();
}
return false; // don't submit the form
case 27: $.datepicker._hideDatepicker();
break; // hide on escape
case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
break; // next month/year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) {
$.datepicker._clearDate(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) {
$.datepicker._gotoToday(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
}
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, -7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
}
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, +7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
} else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var chars, chr,
inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, "constrainInput")) {
chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function(event) {
var date,
inst = $.datepicker._getInst(event.target);
if (inst.input.val() !== inst.lastVal) {
try {
date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
(inst.input ? inst.input.val() : null),
$.datepicker._getFormatConfig(inst));
if (date) { // only if valid
$.datepicker._setDateFromField(inst);
$.datepicker._updateAlternate(inst);
$.datepicker._updateDatepicker(inst);
}
}
catch (err) {
}
}
return true;
},
/* Pop-up the date picker for a given input field.
* If false returned from beforeShow event handler do not show.
* @param input element - the input field attached to the date picker or
* event - if triggered by focus
*/
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
input = $("input", input.parentNode)[0];
}
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
return;
}
var inst, beforeShow, beforeShowSettings, isFixed,
offset, showAnim, duration;
inst = $.datepicker._getInst(input);
if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
$.datepicker._curInst.dpDiv.stop(true, true);
if ( inst && $.datepicker._datepickerShowing ) {
$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
}
}
beforeShow = $.datepicker._get(inst, "beforeShow");
beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
if(beforeShowSettings === false){
return;
}
datepicker_extendRemove(inst.settings, beforeShowSettings);
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) { // hide cursor
input.value = "";
}
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css("position") === "fixed";
return !isFixed;
});
offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
"static" : (isFixed ? "fixed" : "absolute")), display: "none",
left: offset.left + "px", top: offset.top + "px"});
if (!inst.inline) {
showAnim = $.datepicker._get(inst, "showAnim");
duration = $.datepicker._get(inst, "duration");
inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
$.datepicker._datepickerShowing = true;
if ( $.effects && $.effects.effect[ showAnim ] ) {
inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
} else {
inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
}
if ( $.datepicker._shouldFocusInput( inst ) ) {
inst.input.focus();
}
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
datepicker_instActive = inst; // for delegate hover events
inst.dpDiv.empty().append(this._generateHTML(inst));
this._attachHandlers(inst);
var origyearshtml,
numMonths = this._getNumberOfMonths(inst),
cols = numMonths[1],
width = 17,
activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );
if ( activeCell.length > 0 ) {
datepicker_handleMouseover.apply( activeCell.get( 0 ) );
}
inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
if (cols > 1) {
inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
}
inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
"Class"]("ui-datepicker-multi");
inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
"Class"]("ui-datepicker-rtl");
if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
inst.input.focus();
}
// deffered render of the years select (to avoid flashes on Firefox)
if( inst.yearshtml ){
origyearshtml = inst.yearshtml;
setTimeout(function(){
//assure that inst.yearshtml didn't change.
if( origyearshtml === inst.yearshtml && inst.yearshtml ){
inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
}
origyearshtml = inst.yearshtml = null;
}, 0);
}
},
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
// Support: IE and jQuery <1.9
_shouldFocusInput: function( inst ) {
return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth(),
dpHeight = inst.dpDiv.outerHeight(),
inputWidth = inst.input ? inst.input.outerWidth() : 0,
inputHeight = inst.input ? inst.input.outerHeight() : 0,
viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
* @param input element - the input field attached to the date picker
*/
_hideDatepicker: function(input) {
var showAnim, duration, postProcess, onClose,
inst = this._curInst;
if (!inst || (input && inst !== $.data(input, "datepicker"))) {
return;
}
if (this._datepickerShowing) {
showAnim = this._get(inst, "showAnim");
duration = this._get(inst, "duration");
postProcess = function() {
$.datepicker._tidyDialog(inst);
};
// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
} else {
inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
}
if (!showAnim) {
postProcess();
}
this._datepickerShowing = false;
onClose = this._get(inst, "onClose");
if (onClose) {
onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
}
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
if ($.blockUI) {
$.unblockUI();
$("body").append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst) {
return;
}
var $target = $(event.target),
inst = $.datepicker._getInst($target[0]);
if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.closest("." + $.datepicker._triggerClass).length &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
$.datepicker._hideDatepicker();
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id),
inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var date,
target = $(id),
inst = this._getInst(target[0]);
if (this._get(inst, "gotoCurrent") && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id),
inst = this._getInst(target[0]);
inst["selected" + (period === "M" ? "Month" : "Year")] =
inst["draw" + (period === "M" ? "Month" : "Year")] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var inst,
target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $("a", td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
this._selectDate(target, "");
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var onSelect,
target = $(id),
inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input) {
inst.input.val(dateStr);
}
this._updateAlternate(inst);
onSelect = this._get(inst, "onSelect");
if (onSelect) {
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
} else if (inst.input) {
inst.input.trigger("change"); // fire the change event
}
if (inst.inline){
this._updateDatepicker(inst);
} else {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) !== "object") {
inst.input.focus(); // restore focus
}
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altFormat, date, dateStr,
altField = this._get(inst, "altField");
if (altField) { // update alternate field too
altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
date = this._getDate(inst);
dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() { $(this).val(dateStr); });
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
* @param date Date - the date to customise
* @return [boolean, string] - is this date selectable?, what is its CSS class?
*/
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ""];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* @param date Date - the date to get the week for
* @return number - the number of the week within the year that contains this date
*/
iso8601Week: function(date) {
var time,
checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
},
/* Parse a string value into a date object.
* See formatDate below for the possible formats.
*
* @param format string - the expected format of the date
* @param value string - the date in the above format
* @param settings Object - attributes include:
* shortYearCutoff number - the cutoff year for determining the century (optional)
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return Date - the extracted date value or null if value is blank
*/
parseDate: function (format, value, settings) {
if (format == null || value == null) {
throw "Invalid arguments";
}
value = (typeof value === "object" ? value.toString() : value + "");
if (value === "") {
return null;
}
var iFormat, dim, extra,
iValue = 0,
shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
year = -1,
month = -1,
day = -1,
doy = -1,
literal = false,
date,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Extract a number from the string value
getNumber = function(match) {
var isDoubled = lookAhead(match),
size = (match === "@" ? 14 : (match === "!" ? 20 :
(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
minSize = (match === "y" ? size : 1),
digits = new RegExp("^\\d{" + minSize + "," + size + "}"),
num = value.substring(iValue).match(digits);
if (!num) {
throw "Missing number at position " + iValue;
}
iValue += num[0].length;
return parseInt(num[0], 10);
},
// Extract a name from the string value and convert to an index
getName = function(match, shortNames, longNames) {
var index = -1,
names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
return [ [k, v] ];
}).sort(function (a, b) {
return -(a[1].length - b[1].length);
});
$.each(names, function (i, pair) {
var name = pair[1];
if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
index = pair[0];
iValue += name.length;
return false;
}
});
if (index !== -1) {
return index + 1;
} else {
throw "Unknown name at position " + iValue;
}
},
// Confirm that a literal character matches the string value
checkLiteral = function() {
if (value.charAt(iValue) !== format.charAt(iFormat)) {
throw "Unexpected literal at position " + iValue;
}
iValue++;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
checkLiteral();
}
} else {
switch (format.charAt(iFormat)) {
case "d":
day = getNumber("d");
break;
case "D":
getName("D", dayNamesShort, dayNames);
break;
case "o":
doy = getNumber("o");
break;
case "m":
month = getNumber("m");
break;
case "M":
month = getName("M", monthNamesShort, monthNames);
break;
case "y":
year = getNumber("y");
break;
case "@":
date = new Date(getNumber("@"));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "!":
date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'")){
checkLiteral();
} else {
literal = true;
}
break;
default:
checkLiteral();
}
}
}
if (iValue < value.length){
extra = value.substr(iValue);
if (!/^\s+/.test(extra)) {
throw "Extra/unparsed characters found in date: " + extra;
}
}
if (year === -1) {
year = new Date().getFullYear();
} else if (year < 100) {
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
}
if (doy > -1) {
month = 1;
day = doy;
do {
dim = this._getDaysInMonth(year, month - 1);
if (day <= dim) {
break;
}
month++;
day -= dim;
} while (true);
}
date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
throw "Invalid date"; // E.g. 31/02/00
}
return date;
},
/* Standard date formats. */
ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
COOKIE: "D, dd M yy",
ISO_8601: "yy-mm-dd",
RFC_822: "D, d M y",
RFC_850: "DD, dd-M-y",
RFC_1036: "D, d M y",
RFC_1123: "D, d M yy",
RFC_2822: "D, d M yy",
RSS: "D, d M y", // RFC 822
TICKS: "!",
TIMESTAMP: "@",
W3C: "yy-mm-dd", // ISO 8601
_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
/* Format a date object into a string value.
* The format can be combinations of the following:
* d - day of month (no leading zero)
* dd - day of month (two digit)
* o - day of year (no leading zeros)
* oo - day of year (three digit)
* D - day name short
* DD - day name long
* m - month of year (no leading zero)
* mm - month of year (two digit)
* M - month name short
* MM - month name long
* y - year (two digit)
* yy - year (four digit)
* @ - Unix timestamp (ms since 01/01/1970)
* ! - Windows ticks (100ns since 01/01/0001)
* "..." - literal text
* '' - single quote
*
* @param format string - the desired format of the date
* @param date Date - the date value to format
* @param settings Object - attributes include:
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return string - the date in the above format
*/
formatDate: function (format, date, settings) {
if (!date) {
return "";
}
var iFormat,
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Format a number, with leading zero if necessary
formatNumber = function(match, value, len) {
var num = "" + value;
if (lookAhead(match)) {
while (num.length < len) {
num = "0" + num;
}
}
return num;
},
// Format a name, short or long as requested
formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
},
output = "",
literal = false;
if (date) {
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
output += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d":
output += formatNumber("d", date.getDate(), 2);
break;
case "D":
output += formatName("D", date.getDay(), dayNamesShort, dayNames);
break;
case "o":
output += formatNumber("o",
Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
break;
case "m":
output += formatNumber("m", date.getMonth() + 1, 2);
break;
case "M":
output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
break;
case "y":
output += (lookAhead("y") ? date.getFullYear() :
(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
break;
case "@":
output += date.getTime();
break;
case "!":
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if (lookAhead("'")) {
output += "'";
} else {
literal = true;
}
break;
default:
output += format.charAt(iFormat);
}
}
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var iFormat,
chars = "",
literal = false,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
chars += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d": case "m": case "y": case "@":
chars += "0123456789";
break;
case "D": case "M":
return null; // Accept anything
case "'":
if (lookAhead("'")) {
chars += "'";
} else {
literal = true;
}
break;
default:
chars += format.charAt(iFormat);
}
}
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() === inst.lastVal) {
return;
}
var dateFormat = this._get(inst, "dateFormat"),
dates = inst.lastVal = inst.input ? inst.input.val() : null,
defaultDate = this._getDefaultDate(inst),
date = defaultDate,
settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
dates = (noDefault ? "" : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
},
offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date(),
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || "d") {
case "d" : case "D" :
day += parseInt(matches[1],10); break;
case "w" : case "W" :
day += parseInt(matches[1],10) * 7; break;
case "m" : case "M" :
month += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case "y": case "Y" :
year += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
},
newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
/* Handle switch to/from daylight saving.
* Hours may be non-zero on daylight saving cut-over:
* > 12 when midnight changeover, but then cannot generate
* midnight datetime, so jump to 1AM, otherwise reset.
* @param date (Date) the date to check
* @return (Date) the corrected date
*/
_daylightSavingAdjust: function(date) {
if (!date) {
return null;
}
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, noChange) {
var clear = !date,
origMonth = inst.selectedMonth,
origYear = inst.selectedYear,
newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.selectedDay = inst.currentDay = newDate.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
this._notifyChange(inst);
}
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? "" : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Attach the onxxx handlers. These are declared statically so
* they work with static code transformers like Caja.
*/
_attachHandlers: function(inst) {
var stepMonths = this._get(inst, "stepMonths"),
id = "#" + inst.id.replace( /\\\\/g, "\\" );
inst.dpDiv.find("[data-handler]").map(function () {
var handler = {
prev: function () {
$.datepicker._adjustDate(id, -stepMonths, "M");
},
next: function () {
$.datepicker._adjustDate(id, +stepMonths, "M");
},
hide: function () {
$.datepicker._hideDatepicker();
},
today: function () {
$.datepicker._gotoToday(id);
},
selectDay: function () {
$.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
return false;
},
selectMonth: function () {
$.datepicker._selectMonthYear(id, this, "M");
return false;
},
selectYear: function () {
$.datepicker._selectMonthYear(id, this, "Y");
return false;
}
};
$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
});
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
printDate, dRow, tbody, daySettings, otherMonth, unselectable,
tempDate = new Date(),
today = this._daylightSavingAdjust(
new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
isRTL = this._get(inst, "isRTL"),
showButtonPanel = this._get(inst, "showButtonPanel"),
hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
numMonths = this._getNumberOfMonths(inst),
showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
stepMonths = this._get(inst, "stepMonths"),
isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
drawMonth = inst.drawMonth - showCurrentAtPos,
drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
prevText = this._get(inst, "prevText");
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
nextText = this._get(inst, "nextText");
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
currentText = this._get(inst, "currentText");
gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
this._get(inst, "closeText") + "</button>" : "");
buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
firstDay = parseInt(this._get(inst, "firstDay"),10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
showWeek = this._get(inst, "showWeek");
dayNames = this._get(inst, "dayNames");
dayNamesMin = this._get(inst, "dayNamesMin");
monthNames = this._get(inst, "monthNames");
monthNamesShort = this._get(inst, "monthNamesShort");
beforeShowDay = this._get(inst, "beforeShowDay");
showOtherMonths = this._get(inst, "showOtherMonths");
selectOtherMonths = this._get(inst, "selectOtherMonths");
defaultDate = this._getDefaultDate(inst);
html = "";
dow;
for (row = 0; row < numMonths[0]; row++) {
group = "";
this.maxRows = 4;
for (col = 0; col < numMonths[1]; col++) {
selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
cornerClass = " ui-corner-all";
calender = "";
if (isMultiMonth) {
calender += "<div class='ui-datepicker-group";
if (numMonths[1] > 1) {
switch (col) {
case 0: calender += " ui-datepicker-group-first";
cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
case numMonths[1]-1: calender += " ui-datepicker-group-last";
cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
}
}
calender += "'>";
}
calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
"</div><table class='ui-datepicker-calendar'><thead>" +
"<tr>";
thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
for (dow = 0; dow < 7; dow++) { // days of the week
day = (dow + firstDay) % 7;
thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
}
calender += thead + "</tr></thead><tbody>";
daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
}
leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
this.maxRows = numRows;
printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += "<tr>";
tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
this._get(inst, "calculateWeek")(printDate) + "</td>");
for (dow = 0; dow < 7; dow++) { // create date picker days
daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
otherMonth = (printDate.getMonth() !== drawMonth);
unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += "<td class='" +
((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
(otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
" " + this._dayOverClass : "") + // highlight selected day
(unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days
(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
(printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title
(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
(otherMonth && !showOtherMonths ? " " : // display for other months
(unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
(printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
(printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
(otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + "</tr>";
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
group += calender;
}
html += group;
}
html += buttonPanel;
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// month selection
if (secondary || !changeMonth) {
monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
} else {
inMinYear = (minDate && minDate.getFullYear() === drawYear);
inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
for ( month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
monthHtml += "<option value='" + month + "'" +
(month === drawMonth ? " selected='selected'" : "") +
">" + monthNamesShort[month] + "</option>";
}
}
monthHtml += "</select>";
}
if (!showMonthAfterYear) {
html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
}
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get(inst, "yearSuffix");
if (showMonthAfterYear) {
html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
}
html += "</div>"; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period === "Y" ? offset : 0),
month = inst.drawMonth + (period === "M" ? offset : 0),
day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period === "M" || period === "Y") {
this._notifyChange(inst);
}
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
newDate = (minDate && date < minDate ? minDate : date);
return (maxDate && newDate > maxDate ? maxDate : newDate);
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, "onChangeMonthYear");
if (onChange) {
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
}
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, "numberOfMonths");
return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst),
date = this._daylightSavingAdjust(new Date(curYear,
curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
if (offset < 0) {
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var yearSplit, currentYear,
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
minYear = null,
maxYear = null,
years = this._get(inst, "yearRange");
if (years){
yearSplit = years.split(":");
currentYear = new Date().getFullYear();
minYear = parseInt(yearSplit[0], 10);
maxYear = parseInt(yearSplit[1], 10);
if ( yearSplit[0].match(/[+\-].*/) ) {
minYear += currentYear;
}
if ( yearSplit[1].match(/[+\-].*/) ) {
maxYear += currentYear;
}
}
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) &&
(!minYear || date.getFullYear() >= minYear) &&
(!maxYear || date.getFullYear() <= maxYear));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, "shortYearCutoff");
shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day === "object" ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
}
});
/*
* Bind hover events for datepicker elements.
* Done via delegate so the binding only occurs once in the lifetime of the parent div.
* Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
*/
function datepicker_bindHover(dpDiv) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.delegate(selector, "mouseout", function() {
$(this).removeClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).removeClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).removeClass("ui-datepicker-next-hover");
}
})
.delegate( selector, "mouseover", datepicker_handleMouseover );
}
function datepicker_handleMouseover() {
if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) {
$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).addClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).addClass("ui-datepicker-next-hover");
}
}
}
/* jQuery extend now ignores nulls! */
function datepicker_extendRemove(target, props) {
$.extend(target, props);
for (var name in props) {
if (props[name] == null) {
target[name] = props[name];
}
}
return target;
}
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options){
/* Verify an empty collection wasn't passed - Fixes #6976 */
if ( !this.length ) {
return this;
}
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick);
$.datepicker.initialized = true;
}
/* Append datepicker main container to body if not exist. */
if ($("#"+$.datepicker._mainDivId).length === 0) {
$("body").append($.datepicker.dpDiv);
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
return this.each(function() {
typeof options === "string" ?
$.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.11.4";
var datepicker = $.datepicker;
})); | davidred/spree_delivery_time | app/assets/javascripts/spree/frontend/store/datepicker.js | JavaScript | bsd-3-clause | 91,677 |
var sbModule = angular.module('sbServices', ['ngResource']);
sbModule.factory('App', function($resource) {
return $resource('/api/v1/app/:name', { q: '' }, {
get: { method: 'GET' }, //isArray: false },
query: { method: 'GET'} //, params: { q: '' }//, isArray: false }
});
});
| beni55/shipbuilder | webroot/js/services.js | JavaScript | bsd-3-clause | 302 |
# coding: utf-8
# This file is part of Thomas Aquinas.
#
# Thomas Aquinas 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.
#
# Thomas Aquinas 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 Thomas Aquinas. If not, see <http://www.gnu.org/licenses/>.
#
# veni, Sancte Spiritus.
import ctypes
import logging
| shackra/thomas-aquinas | summa/audio/system.py | Python | bsd-3-clause | 776 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Validate
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: AllTests.php 24594 2012-01-05 21:27:01Z matthew $
*/
if (!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'Zend_Validate_Sitemap_AllTests::main');
}
require_once 'Zend/Validate/Sitemap/ChangefreqTest.php';
require_once 'Zend/Validate/Sitemap/LastmodTest.php';
require_once 'Zend/Validate/Sitemap/LocTest.php';
require_once 'Zend/Validate/Sitemap/PriorityTest.php';
/**
* @category Zend
* @package Zend_Validate
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Validate
* @group Zend_Validate_Sitemap
*/
class Zend_Validate_Sitemap_AllTests
{
public static function main()
{
PHPUnit_TextUI_TestRunner::run(self::suite());
}
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('Zend Framework - Zend_Validate_Sitemap');
$suite->addTestSuite('Zend_Validate_Sitemap_ChangefreqTest');
$suite->addTestSuite('Zend_Validate_Sitemap_LastmodTest');
$suite->addTestSuite('Zend_Validate_Sitemap_LocTest');
$suite->addTestSuite('Zend_Validate_Sitemap_PriorityTest');
return $suite;
}
}
if (PHPUnit_MAIN_METHOD == 'Zend_Validate_Sitemap_AllTests::main') {
Zend_Validate_Sitemap_AllTests::main();
}
| karthiksekarnz/educulas | tests/Zend/Validate/Sitemap/AllTests.php | PHP | bsd-3-clause | 2,115 |
#include "ADTFPinMessageEncoder.h"
using namespace A2O;
ADTFPinMessageEncoder::ADTFPinMessageEncoder(IAction::Ptr action,
ICarMetaModel::ConstPtr carMetaModel)
: _action(action)
{
// Create output pins
const std::vector<IServoDriveConfig::ConstPtr>& servoDriveConfigs = carMetaModel->getServoDriveConfigs();
for (unsigned int i = 0; i < servoDriveConfigs.size(); i++) {
_pins.push_back(OutputPin(servoDriveConfigs[i]->getEffectorName(), "tSignalValue"));
}
std::vector<IActuatorConfig::ConstPtr> actuatorConfigs = carMetaModel->getMotorConfigs();
for (unsigned int i = 0; i < actuatorConfigs.size(); i++) {
_pins.push_back(OutputPin(actuatorConfigs[i]->getEffectorName(), "tSignalValue"));
}
actuatorConfigs = carMetaModel->getLightConfigs();
for (unsigned int i = 0; i < actuatorConfigs.size(); i++) {
_pins.push_back(OutputPin(actuatorConfigs[i]->getEffectorName(), "tBoolSignalValue"));
}
actuatorConfigs = carMetaModel->getManeuverStatusConfigs();
for (unsigned int i = 0; i < actuatorConfigs.size(); i++) {
_pins.push_back(OutputPin(actuatorConfigs[i]->getEffectorName(), "tDriverStruct"));
}
}
ADTFPinMessageEncoder::~ADTFPinMessageEncoder()
{
}
int ADTFPinMessageEncoder::indexOfPin(OutputPin pin) const
{
for (unsigned int i = 0; i < _pins.size(); i++) {
if (_pins[i] == pin) {
return i;
}
}
return -1;
}
const std::vector<OutputPin>& ADTFPinMessageEncoder::getOutputPins()
{
return _pins;
}
bool ADTFPinMessageEncoder::encode(const OutputPin& pin,
adtf::IMediaTypeDescription* mediaTypeDescription,
adtf::IMediaSample* mediaSample)
{
int pinIndex = indexOfPin(pin);
bool toTransmit = false;
if (pinIndex >= 0) {
cObjectPtr<adtf::IMediaSerializer> serializer;
mediaTypeDescription->GetMediaSampleSerializer(&serializer);
tInt size = serializer->GetDeserializedSize();
mediaSample->AllocBuffer(size);
cObjectPtr<adtf::IMediaCoder> mediaCoder;
tUInt32 timestamp = 0;
if (pin.signalType == "tBoolSignalValue") {
IBoolValueEffector::Ptr boolEffector = _action->getLightEffector(pin.name);
if (boolEffector) {
__adtf_sample_write_lock_mediadescription(mediaTypeDescription, mediaSample, mediaCoder);
if(!mediaCoder)
{
return false;
}
tBool value = boolEffector->getValue();
mediaCoder->Set("bValue", (tVoid*)&value);
mediaCoder->Set("ui32ArduinoTimestamp", (tVoid*)×tamp);
toTransmit = true;
}
} else if (pin.signalType == "tSignalValue") {
IDoubleValueEffector::Ptr valueEffector = boost::dynamic_pointer_cast<IDoubleValueEffector>(_action->getEffector(pin.name));
if (valueEffector) {
__adtf_sample_write_lock_mediadescription(mediaTypeDescription, mediaSample, mediaCoder);
if(!mediaCoder)
{
return false;
}
tFloat32 value = valueEffector->getValue();
mediaCoder->Set("f32Value", (tVoid*)&value);
mediaCoder->Set("ui32ArduinoTimestamp", (tVoid*)×tamp);
toTransmit = true;
}
} else if (pin.signalType == "tDriverStruct") {
IManeuverStatusEffector::Ptr valueEffector = boost::dynamic_pointer_cast<IManeuverStatusEffector>(_action->getEffector(pin.name));
if (valueEffector)
{
__adtf_sample_write_lock_mediadescription(mediaTypeDescription, mediaSample, mediaCoder);
if(!mediaCoder)
{
return false;
}
int state = valueEffector->getStatus();
int maneuverId = valueEffector->getManeuverId();
mediaCoder->Set("i8StateID", (tVoid*)&state);
mediaCoder->Set("i16ManeuverEntry", (tVoid*)&maneuverId);
toTransmit = true;
}
}
}
return toTransmit;
}
| AppliedAutonomyOffenburg/AADC_2015_A2O | src/aadcUser/src/HSOG_Runtime/adtf/encoder/ADTFPinMessageEncoder.cpp | C++ | bsd-3-clause | 3,690 |
<?php namespace Exchange\EWSType; use Exchange\EWSType;
/**
* Contains EWSType_TentativelyAcceptItemType.
*/
/**
* Represents a Tentative reply to a meeting request.
*
* @package php-ews\Types
*
* @todo Extend EWSType_WellKnownResponseObjectType.
*/
class EWSType_TentativelyAcceptItemType extends EWSType
{
/**
* Contains the item or file that is attached to an item in the Exchange
* store.
*
* @since Exchange 2007
*
* @var EWSType_ArrayOfAttachmentsType
*/
public $Attachments;
/**
* Represents a collection of recipients to receive a blind carbon copy
* (Bcc) of an e-mail.
*
* @since Exchange 2007
*
* @var EWSType_ArrayOfRecipientsType
*/
public $BccRecipients;
/**
* Represents the actual body content of a message.
*
* @since Exchange 2007
*
* @var EWSType_BodyType
*/
public $Body;
/**
* Represents a collection of recipients that will receive a copy of the
* message.
*
* @since Exchange 2007
*
* @var EWSType_ArrayOfRecipientsType
*/
public $CcRecipients;
/**
* Represents the Internet message header name for a given header within the
* headers collection.
*
* @since Exchange 2007
*
* @var EWSType_NonEmptyArrayOfInternetHeadersType
*/
public $InternetMessageHeaders;
/**
* Indicates whether the sender of an item requests a delivery receipt.
*
* @since Exchange 2007
*
* @var boolean
*/
public $IsDeliveryReceiptRequested;
/**
* Indicates whether the sender of an item requests a read receipt.
*
* @since Exchange 2007
*
* @var boolean
*/
public $IsReadReceiptRequested;
/**
* Represents the message class of an item.
*
* @since Exchange 2007
*
* @var EWSType_ItemClassType
*/
public $ItemClass;
/**
* Identifies the delegate in a delegate access scenario.
*
* @since Exchange 2007 SP1
*
* @var EWSType_SingleRecipientType
*/
public $ReceivedBy;
/**
* Identifies the principal in a delegate access scenario.
*
* @since Exchange 2007 SP1
*
* @var EWSType_SingleRecipientType
*/
public $ReceivedRepresenting;
/**
* Identifies the item to which the response object refers.
*
* @since Exchange 2007
*
* @var EWSType_ItemIdType
*/
public $ReferenceItemId;
/**
* Identifies the sender of an item.
*
* @since Exchange 2007
*
* @var EWSType_SingleRecipientType
*/
public $Sender;
/**
* Identifies the sensitivity of an item.
*
* @since Exchange 2007
*
* @var EWSType_SensitivityChoicesType
*/
public $Sensitivity;
/**
* Contains a set of recipients of an item.
*
* These are the primary recipients of an item.
*
* @since Exchange 2007
*
* @var EWSType_ArrayOfRecipientsType
*/
public $ToRecipients;
}
| segpacto/yii2-exchange | EWSType/EWSType_TentativelyAcceptItemType.php | PHP | bsd-3-clause | 3,092 |
<?php
namespace app\modules\admin\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Trigger;
/**
* TriggerSearch represents the model behind the search form about `app\models\Trigger`.
*/
class TriggerSearch extends Trigger
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'type', 'item_id', 'active'], 'integer'],
[['date', 'time', 'weekdays', 'item_value', 'name'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Trigger::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'type' => $this->type,
'item_id' => $this->item_id,
'active' => $this->active,
]);
$query->andFilterWhere(['like', 'date', $this->date])
->andFilterWhere(['like', 'time', $this->time])
->andFilterWhere(['like', 'weekdays', $this->weekdays])
->andFilterWhere(['like', 'item_value', $this->item_value])
->andFilterWhere(['like', 'name', $this->name]);
return $dataProvider;
}
}
| CyanoFresh/SmartHome | modules/admin/models/TriggerSearch.php | PHP | bsd-3-clause | 1,914 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdlib.h>
#include "base/basictypes.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/net/url_fixer_upper.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/url_parse.h"
namespace {
class URLFixerUpperTest : public testing::Test {
};
};
namespace url_parse {
std::ostream& operator<<(std::ostream& os, const Component& part) {
return os << "(begin=" << part.begin << ", len=" << part.len << ")";
}
} // namespace url_parse
struct SegmentCase {
const std::string input;
const std::string result;
const url_parse::Component scheme;
const url_parse::Component username;
const url_parse::Component password;
const url_parse::Component host;
const url_parse::Component port;
const url_parse::Component path;
const url_parse::Component query;
const url_parse::Component ref;
};
static const SegmentCase segment_cases[] = {
{ "http://www.google.com/", "http",
url_parse::Component(0, 4), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(7, 14), // host
url_parse::Component(), // port
url_parse::Component(21, 1), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "aBoUt:vErSiOn", "about",
url_parse::Component(0, 5), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(6, 7), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "about:host/path?query#ref", "about",
url_parse::Component(0, 5), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(6, 4), // host
url_parse::Component(), // port
url_parse::Component(10, 5), // path
url_parse::Component(16, 5), // query
url_parse::Component(22, 3), // ref
},
{ "about://host/path?query#ref", "about",
url_parse::Component(0, 5), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(8, 4), // host
url_parse::Component(), // port
url_parse::Component(12, 5), // path
url_parse::Component(18, 5), // query
url_parse::Component(24, 3), // ref
},
{ "chrome:host/path?query#ref", "chrome",
url_parse::Component(0, 6), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(7, 4), // host
url_parse::Component(), // port
url_parse::Component(11, 5), // path
url_parse::Component(17, 5), // query
url_parse::Component(23, 3), // ref
},
{ "chrome://host/path?query#ref", "chrome",
url_parse::Component(0, 6), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(9, 4), // host
url_parse::Component(), // port
url_parse::Component(13, 5), // path
url_parse::Component(19, 5), // query
url_parse::Component(25, 3), // ref
},
{ " www.google.com:124?foo#", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(4, 14), // host
url_parse::Component(19, 3), // port
url_parse::Component(), // path
url_parse::Component(23, 3), // query
url_parse::Component(27, 0), // ref
},
{ "user@www.google.com", "http",
url_parse::Component(), // scheme
url_parse::Component(0, 4), // username
url_parse::Component(), // password
url_parse::Component(5, 14), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "ftp:/user:P:a$$Wd@..ftp.google.com...::23///pub?foo#bar", "ftp",
url_parse::Component(0, 3), // scheme
url_parse::Component(5, 4), // username
url_parse::Component(10, 7), // password
url_parse::Component(18, 20), // host
url_parse::Component(39, 2), // port
url_parse::Component(41, 6), // path
url_parse::Component(48, 3), // query
url_parse::Component(52, 3), // ref
},
{ "[2001:db8::1]/path", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(0, 13), // host
url_parse::Component(), // port
url_parse::Component(13, 5), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "[::1]", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(0, 5), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
// Incomplete IPv6 addresses (will not canonicalize).
{ "[2001:4860:", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(0, 11), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "[2001:4860:/foo", "http",
url_parse::Component(), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(0, 11), // host
url_parse::Component(), // port
url_parse::Component(11, 4), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
{ "http://:b005::68]", "http",
url_parse::Component(0, 4), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(7, 10), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
// Can't do anything useful with this.
{ ":b005::68]", "",
url_parse::Component(0, 0), // scheme
url_parse::Component(), // username
url_parse::Component(), // password
url_parse::Component(), // host
url_parse::Component(), // port
url_parse::Component(), // path
url_parse::Component(), // query
url_parse::Component(), // ref
},
};
TEST(URLFixerUpperTest, SegmentURL) {
std::string result;
url_parse::Parsed parts;
for (size_t i = 0; i < arraysize(segment_cases); ++i) {
SegmentCase value = segment_cases[i];
result = URLFixerUpper::SegmentURL(value.input, &parts);
EXPECT_EQ(value.result, result);
EXPECT_EQ(value.scheme, parts.scheme);
EXPECT_EQ(value.username, parts.username);
EXPECT_EQ(value.password, parts.password);
EXPECT_EQ(value.host, parts.host);
EXPECT_EQ(value.port, parts.port);
EXPECT_EQ(value.path, parts.path);
EXPECT_EQ(value.query, parts.query);
EXPECT_EQ(value.ref, parts.ref);
}
}
// Creates a file and returns its full name as well as the decomposed
// version. Example:
// full_path = "c:\foo\bar.txt"
// dir = "c:\foo"
// file_name = "bar.txt"
static bool MakeTempFile(const base::FilePath& dir,
const base::FilePath& file_name,
base::FilePath* full_path) {
*full_path = dir.Append(file_name);
return file_util::WriteFile(*full_path, "", 0) == 0;
}
// Returns true if the given URL is a file: URL that matches the given file
static bool IsMatchingFileURL(const std::string& url,
const base::FilePath& full_file_path) {
if (url.length() <= 8)
return false;
if (std::string("file:///") != url.substr(0, 8))
return false; // no file:/// prefix
if (url.find('\\') != std::string::npos)
return false; // contains backslashes
base::FilePath derived_path;
net::FileURLToFilePath(GURL(url), &derived_path);
return base::FilePath::CompareEqualIgnoreCase(derived_path.value(),
full_file_path.value());
}
struct FixupCase {
const std::string input;
const std::string desired_tld;
const std::string output;
} fixup_cases[] = {
{"www.google.com", "", "http://www.google.com/"},
{" www.google.com ", "", "http://www.google.com/"},
{" foo.com/asdf bar", "", "http://foo.com/asdf%20%20bar"},
{"..www.google.com..", "", "http://www.google.com./"},
{"http://......", "", "http://....../"},
{"http://host.com:ninety-two/", "", "http://host.com:ninety-two/"},
{"http://host.com:ninety-two?foo", "", "http://host.com:ninety-two/?foo"},
{"google.com:123", "", "http://google.com:123/"},
{"about:", "", "chrome://version/"},
{"about:foo", "", "chrome://foo/"},
{"about:version", "", "chrome://version/"},
{"about:usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"},
{"about://usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"},
{"chrome:usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"},
{"chrome://usr:pwd@hst/pth?qry#ref", "", "chrome://usr:pwd@hst/pth?qry#ref"},
{"www:123", "", "http://www:123/"},
{" www:123", "", "http://www:123/"},
{"www.google.com?foo", "", "http://www.google.com/?foo"},
{"www.google.com#foo", "", "http://www.google.com/#foo"},
{"www.google.com?", "", "http://www.google.com/?"},
{"www.google.com#", "", "http://www.google.com/#"},
{"www.google.com:123?foo#bar", "", "http://www.google.com:123/?foo#bar"},
{"user@www.google.com", "", "http://user@www.google.com/"},
{"\xE6\xB0\xB4.com" , "", "http://xn--1rw.com/"},
// It would be better if this next case got treated as http, but I don't see
// a clean way to guess this isn't the new-and-exciting "user" scheme.
{"user:passwd@www.google.com:8080/", "", "user:passwd@www.google.com:8080/"},
// {"file:///c:/foo/bar%20baz.txt", "", "file:///C:/foo/bar%20baz.txt"},
{"ftp.google.com", "", "ftp://ftp.google.com/"},
{" ftp.google.com", "", "ftp://ftp.google.com/"},
{"FTP.GooGle.com", "", "ftp://ftp.google.com/"},
{"ftpblah.google.com", "", "http://ftpblah.google.com/"},
{"ftp", "", "http://ftp/"},
{"google.ftp.com", "", "http://google.ftp.com/"},
// URLs which end with 0x85 (NEL in ISO-8859).
{ "http://google.com/search?q=\xd0\x85", "",
"http://google.com/search?q=%D0%85"
},
{ "http://google.com/search?q=\xec\x97\x85", "",
"http://google.com/search?q=%EC%97%85"
},
{ "http://google.com/search?q=\xf0\x90\x80\x85", "",
"http://google.com/search?q=%F0%90%80%85"
},
// URLs which end with 0xA0 (non-break space in ISO-8859).
{ "http://google.com/search?q=\xd0\xa0", "",
"http://google.com/search?q=%D0%A0"
},
{ "http://google.com/search?q=\xec\x97\xa0", "",
"http://google.com/search?q=%EC%97%A0"
},
{ "http://google.com/search?q=\xf0\x90\x80\xa0", "",
"http://google.com/search?q=%F0%90%80%A0"
},
// URLs containing IPv6 literals.
{"[2001:db8::2]", "", "http://[2001:db8::2]/"},
{"[::]:80", "", "http://[::]/"},
{"[::]:80/path", "", "http://[::]/path"},
{"[::]:180/path", "", "http://[::]:180/path"},
// TODO(pmarks): Maybe we should parse bare IPv6 literals someday.
{"::1", "", "::1"},
// Semicolon as scheme separator for standard schemes.
{"http;//www.google.com/", "", "http://www.google.com/"},
{"about;chrome", "", "chrome://chrome/"},
// Semicolon left as-is for non-standard schemes.
{"whatsup;//fool", "", "whatsup://fool"},
// Semicolon left as-is in URL itself.
{"http://host/port?query;moar", "", "http://host/port?query;moar"},
// Fewer slashes than expected.
{"http;www.google.com/", "", "http://www.google.com/"},
{"http;/www.google.com/", "", "http://www.google.com/"},
// Semicolon at start.
{";http://www.google.com/", "", "http://%3Bhttp//www.google.com/"},
};
TEST(URLFixerUpperTest, FixupURL) {
for (size_t i = 0; i < arraysize(fixup_cases); ++i) {
FixupCase value = fixup_cases[i];
EXPECT_EQ(value.output, URLFixerUpper::FixupURL(value.input,
value.desired_tld).possibly_invalid_spec())
<< "input: " << value.input;
}
// Check the TLD-appending functionality
FixupCase tld_cases[] = {
{"google", "com", "http://www.google.com/"},
{"google.", "com", "http://www.google.com/"},
{"google..", "com", "http://www.google.com/"},
{".google", "com", "http://www.google.com/"},
{"www.google", "com", "http://www.google.com/"},
{"google.com", "com", "http://google.com/"},
{"http://google", "com", "http://www.google.com/"},
{"..google..", "com", "http://www.google.com/"},
{"http://www.google", "com", "http://www.google.com/"},
{"9999999999999999", "com", "http://www.9999999999999999.com/"},
{"google/foo", "com", "http://www.google.com/foo"},
{"google.com/foo", "com", "http://google.com/foo"},
{"google/?foo=.com", "com", "http://www.google.com/?foo=.com"},
{"www.google/?foo=www.", "com", "http://www.google.com/?foo=www."},
{"google.com/?foo=.com", "com", "http://google.com/?foo=.com"},
{"http://www.google.com", "com", "http://www.google.com/"},
{"google:123", "com", "http://www.google.com:123/"},
{"http://google:123", "com", "http://www.google.com:123/"},
};
for (size_t i = 0; i < arraysize(tld_cases); ++i) {
FixupCase value = tld_cases[i];
EXPECT_EQ(value.output, URLFixerUpper::FixupURL(value.input,
value.desired_tld).possibly_invalid_spec());
}
}
// Test different types of file inputs to URIFixerUpper::FixupURL. This
// doesn't go into the nice array of fixups above since the file input
// has to exist.
TEST(URLFixerUpperTest, FixupFile) {
// this "original" filename is the one we tweak to get all the variations
base::FilePath dir;
base::FilePath original;
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir));
ASSERT_TRUE(MakeTempFile(
dir,
base::FilePath(FILE_PATH_LITERAL("url fixer upper existing file.txt")),
&original));
// reference path
GURL golden(net::FilePathToFileURL(original));
// c:\foo\bar.txt -> file:///c:/foo/bar.txt (basic)
#if defined(OS_WIN)
GURL fixedup(URLFixerUpper::FixupURL(base::WideToUTF8(original.value()),
std::string()));
#elif defined(OS_POSIX)
GURL fixedup(URLFixerUpper::FixupURL(original.value(), std::string()));
#endif
EXPECT_EQ(golden, fixedup);
// TODO(port): Make some equivalent tests for posix.
#if defined(OS_WIN)
// c|/foo\bar.txt -> file:///c:/foo/bar.txt (pipe allowed instead of colon)
std::string cur(base::WideToUTF8(original.value()));
EXPECT_EQ(':', cur[1]);
cur[1] = '|';
EXPECT_EQ(golden, URLFixerUpper::FixupURL(cur, std::string()));
FixupCase file_cases[] = {
{"c:\\This%20is a non-existent file.txt", "",
"file:///C:/This%2520is%20a%20non-existent%20file.txt"},
// \\foo\bar.txt -> file://foo/bar.txt
// UNC paths, this file won't exist, but since there are no escapes, it
// should be returned just converted to a file: URL.
{"\\\\SomeNonexistentHost\\foo\\bar.txt", "",
"file://somenonexistenthost/foo/bar.txt"},
// We do this strictly, like IE8, which only accepts this form using
// backslashes and not forward ones. Turning "//foo" into "http" matches
// Firefox and IE, silly though it may seem (it falls out of adding "http"
// as the default protocol if you haven't entered one).
{"//SomeNonexistentHost\\foo/bar.txt", "",
"http://somenonexistenthost/foo/bar.txt"},
{"file:///C:/foo/bar", "", "file:///C:/foo/bar"},
// Much of the work here comes from GURL's canonicalization stage.
{"file://C:/foo/bar", "", "file:///C:/foo/bar"},
{"file:c:", "", "file:///C:/"},
{"file:c:WINDOWS", "", "file:///C:/WINDOWS"},
{"file:c|Program Files", "", "file:///C:/Program%20Files"},
{"file:/file", "", "file://file/"},
{"file:////////c:\\foo", "", "file:///C:/foo"},
{"file://server/folder/file", "", "file://server/folder/file"},
// These are fixups we don't do, but could consider:
//
// {"file:///foo:/bar", "", "file://foo/bar"},
// {"file:/\\/server\\folder/file", "", "file://server/folder/file"},
};
#elif defined(OS_POSIX)
#if defined(OS_MACOSX)
#define HOME "/Users/"
#else
#define HOME "/home/"
#endif
URLFixerUpper::home_directory_override = "/foo";
FixupCase file_cases[] = {
// File URLs go through GURL, which tries to escape intelligently.
{"/This%20is a non-existent file.txt", "",
"file:///This%2520is%20a%20non-existent%20file.txt"},
// A plain "/" refers to the root.
{"/", "",
"file:///"},
// These rely on the above home_directory_override.
{"~", "",
"file:///foo"},
{"~/bar", "",
"file:///foo/bar"},
// References to other users' homedirs.
{"~foo", "",
"file://" HOME "foo"},
{"~x/blah", "",
"file://" HOME "x/blah"},
};
#endif
for (size_t i = 0; i < arraysize(file_cases); i++) {
EXPECT_EQ(file_cases[i].output, URLFixerUpper::FixupURL(file_cases[i].input,
file_cases[i].desired_tld).possibly_invalid_spec());
}
EXPECT_TRUE(base::DeleteFile(original, false));
}
TEST(URLFixerUpperTest, FixupRelativeFile) {
base::FilePath full_path, dir;
base::FilePath file_part(
FILE_PATH_LITERAL("url_fixer_upper_existing_file.txt"));
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir));
ASSERT_TRUE(MakeTempFile(dir, file_part, &full_path));
full_path = base::MakeAbsoluteFilePath(full_path);
ASSERT_FALSE(full_path.empty());
// make sure we pass through good URLs
for (size_t i = 0; i < arraysize(fixup_cases); ++i) {
FixupCase value = fixup_cases[i];
base::FilePath input = base::FilePath::FromUTF8Unsafe(value.input);
EXPECT_EQ(value.output,
URLFixerUpper::FixupRelativeFile(dir, input).possibly_invalid_spec());
}
// make sure the existing file got fixed-up to a file URL, and that there
// are no backslashes
EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir,
file_part).possibly_invalid_spec(), full_path));
EXPECT_TRUE(base::DeleteFile(full_path, false));
// create a filename we know doesn't exist and make sure it doesn't get
// fixed up to a file URL
base::FilePath nonexistent_file(
FILE_PATH_LITERAL("url_fixer_upper_nonexistent_file.txt"));
std::string fixedup(URLFixerUpper::FixupRelativeFile(dir,
nonexistent_file).possibly_invalid_spec());
EXPECT_NE(std::string("file:///"), fixedup.substr(0, 8));
EXPECT_FALSE(IsMatchingFileURL(fixedup, nonexistent_file));
// make a subdir to make sure relative paths with directories work, also
// test spaces:
// "app_dir\url fixer-upper dir\url fixer-upper existing file.txt"
base::FilePath sub_dir(FILE_PATH_LITERAL("url fixer-upper dir"));
base::FilePath sub_file(
FILE_PATH_LITERAL("url fixer-upper existing file.txt"));
base::FilePath new_dir = dir.Append(sub_dir);
base::CreateDirectory(new_dir);
ASSERT_TRUE(MakeTempFile(new_dir, sub_file, &full_path));
full_path = base::MakeAbsoluteFilePath(full_path);
ASSERT_FALSE(full_path.empty());
// test file in the subdir
base::FilePath relative_file = sub_dir.Append(sub_file);
EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir,
relative_file).possibly_invalid_spec(), full_path));
// test file in the subdir with different slashes and escaping.
base::FilePath::StringType relative_file_str = sub_dir.value() +
FILE_PATH_LITERAL("/") + sub_file.value();
ReplaceSubstringsAfterOffset(&relative_file_str, 0,
FILE_PATH_LITERAL(" "), FILE_PATH_LITERAL("%20"));
EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir,
base::FilePath(relative_file_str)).possibly_invalid_spec(), full_path));
// test relative directories and duplicate slashes
// (should resolve to the same file as above)
relative_file_str = sub_dir.value() + FILE_PATH_LITERAL("/../") +
sub_dir.value() + FILE_PATH_LITERAL("///./") + sub_file.value();
EXPECT_TRUE(IsMatchingFileURL(URLFixerUpper::FixupRelativeFile(dir,
base::FilePath(relative_file_str)).possibly_invalid_spec(), full_path));
// done with the subdir
EXPECT_TRUE(base::DeleteFile(full_path, false));
EXPECT_TRUE(base::DeleteFile(new_dir, true));
// Test that an obvious HTTP URL isn't accidentally treated as an absolute
// file path (on account of system-specific craziness).
base::FilePath empty_path;
base::FilePath http_url_path(FILE_PATH_LITERAL("http://../"));
EXPECT_TRUE(URLFixerUpper::FixupRelativeFile(
empty_path, http_url_path).SchemeIs("http"));
}
| ChromiumWebApps/chromium | chrome/common/net/url_fixer_upper_unittest.cc | C++ | bsd-3-clause | 20,955 |
#<pycode(py_choose)>
class Choose:
"""
Choose - class for choose() with callbacks
"""
def __init__(self, list, title, flags=0, deflt=1, icon=37):
self.list = list
self.title = title
self.flags = flags
self.x0 = -1
self.x1 = -1
self.y0 = -1
self.y1 = -1
self.width = -1
self.deflt = deflt
self.icon = icon
# HACK: Add a circular reference for non-modal choosers. This prevents the GC
# from collecting the class object the callbacks need. Unfortunately this means
# that the class will never be collected, unless refhack is set to None explicitly.
if (flags & Choose2.CH_MODAL) == 0:
self.refhack = self
def sizer(self):
"""
Callback: sizer - returns the length of the list
"""
return len(self.list)
def getl(self, n):
"""
Callback: getl - get one item from the list
"""
if n == 0:
return self.title
if n <= self.sizer():
return str(self.list[n-1])
else:
return "<Empty>"
def ins(self):
pass
def update(self, n):
pass
def edit(self, n):
pass
def enter(self, n):
print "enter(%d) called" % n
def destroy(self):
pass
def get_icon(self, n):
pass
def choose(self):
"""
choose - Display the choose dialogue
"""
old = set_script_timeout(0)
n = _idaapi.choose_choose(
self,
self.flags,
self.x0,
self.y0,
self.x1,
self.y1,
self.width,
self.deflt,
self.icon)
set_script_timeout(old)
return n
#</pycode(py_choose)>
| nihilus/src | pywraps/py_choose.py | Python | bsd-3-clause | 1,595 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Console;
/**
* A static, utility class for interacting with Console environment.
* Declared abstract to prevent from instantiating.
*/
abstract class Console
{
/**
* @var Adapter\AdapterInterface
*/
protected static $instance;
/**
* Allow overriding whether or not we're in a console env. If set, and
* boolean, returns that value from isConsole().
* @var bool
*/
protected static $isConsole;
/**
* Create and return Adapter\AdapterInterface instance.
*
* @param null|string $forceAdapter Optional adapter class name. Can be absolute namespace or class name
* relative to Zend\Console\Adapter\. If not provided, a best matching
* adapter will be automatically selected.
* @param null|string $forceCharset optional charset name can be absolute namespace or class name relative to
* Zend\Console\Charset\. If not provided, charset will be detected
* automatically.
* @throws Exception\InvalidArgumentException
* @throws Exception\RuntimeException
* @return Adapter\AdapterInterface
*/
public static function getInstance($forceAdapter = null, $forceCharset = null)
{
if (static::$instance instanceof Adapter\AdapterInterface) {
return static::$instance;
}
// Create instance
if ($forceAdapter !== null) {
// Use the supplied adapter class
if (substr($forceAdapter, 0, 1) == '\\') {
$className = $forceAdapter;
} elseif (stristr($forceAdapter, '\\')) {
$className = __NAMESPACE__ . '\\' . ltrim($forceAdapter, '\\');
} else {
$className = __NAMESPACE__ . '\\Adapter\\' . $forceAdapter;
}
if (!class_exists($className)) {
throw new Exception\InvalidArgumentException(sprintf(
'Cannot find Console adapter class "%s"',
$className
));
}
} else {
// Try to detect best instance for console
$className = static::detectBestAdapter();
// Check if we were able to detect console adapter
if (!$className) {
throw new Exception\RuntimeException('Cannot create Console adapter - am I running in a console?');
}
}
// Create adapter instance
static::$instance = new $className();
// Try to use the supplied charset class
if ($forceCharset !== null) {
if (substr($forceCharset, 0, 1) == '\\') {
$className = $forceCharset;
} elseif (stristr($forceAdapter, '\\')) {
$className = __NAMESPACE__ . '\\' . ltrim($forceCharset, '\\');
} else {
$className = __NAMESPACE__ . '\\Charset\\' . $forceCharset;
}
if (!class_exists($className)) {
throw new Exception\InvalidArgumentException(sprintf(
'Cannot find Charset class "%s"',
$className
));
}
// Set adapter charset
static::$instance->setCharset(new $className());
}
return static::$instance;
}
/**
* Reset the console instance
*/
public static function resetInstance()
{
static::$instance = null;
}
/**
* Check if currently running under MS Windows
*
* @see http://stackoverflow.com/questions/738823/possible-values-for-php-os
* @return bool
*/
public static function isWindows()
{
return
(defined('PHP_OS') && (substr_compare(PHP_OS, 'win', 0, 3, true) === 0)) ||
(getenv('OS') != false && substr_compare(getenv('OS'), 'windows', 0, 7, true))
;
}
/**
* Check if running under MS Windows Ansicon
*
* @return bool
*/
public static function isAnsicon()
{
return getenv('ANSICON') !== false;
}
/**
* Check if running in a console environment (CLI)
*
* By default, returns value of PHP_SAPI global constant. If $isConsole is
* set, and a boolean value, that value will be returned.
*
* @return bool
*/
public static function isConsole()
{
if (null === static::$isConsole) {
static::$isConsole = (PHP_SAPI == 'cli');
}
return static::$isConsole;
}
/**
* Override the "is console environment" flag
*
* @param null|bool $flag
*/
public static function overrideIsConsole($flag)
{
if (null != $flag) {
$flag = (bool) $flag;
}
static::$isConsole = $flag;
}
/**
* Try to detect best matching adapter
* @return string|null
*/
public static function detectBestAdapter()
{
// Check if we are in a console environment
if (!static::isConsole()) {
return null;
}
// Check if we're on windows
if (static::isWindows()) {
if (static::isAnsicon()) {
$className = __NAMESPACE__ . '\Adapter\WindowsAnsicon';
} else {
$className = __NAMESPACE__ . '\Adapter\Windows';
}
return $className;
}
// Default is a Posix console
$className = __NAMESPACE__ . '\Adapter\Posix';
return $className;
}
/**
* Pass-thru static call to current AdapterInterface instance.
*
* @param $funcName
* @param $arguments
* @return mixed
*/
public static function __callStatic($funcName, $arguments)
{
$instance = static::getInstance();
return call_user_func_array(array($instance, $funcName), $arguments);
}
}
| ishvaram/email-app | vendor/ZF2/library/Zend/Console/Console.php | PHP | bsd-3-clause | 6,488 |
<?php
/**
* inerface INewsDB
* содержит основные методы для работы с новостной лентой
*/
interface INewsDB{
/**
* Добавление новой записи в новостную ленту
*
* @param string $title - заголовок новости
* @param string $category - категория новости
* @param string $description - текст новости
* @param string $source - источник новости
*
* @return boolean - результат успех/ошибка
*/
function saveNews($t, $c, $d, $s);
/**
* Выборка всех записей из новостной ленты
*
* @return array - результат выборки в виде массива
*/
function getNews();
/**
* Удаление записи из новостной ленты
*
* @param integer $id - идентификатор удаляемой записи
*
* @return boolean - результат успех/ошибка
*/
function deleteNews($id);
}
?> | sowanderr/phonebook | web/phone/INewsDB.class.php | PHP | bsd-3-clause | 1,140 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ABI41_0_0AndroidDialogPickerProps.h"
#include <ABI41_0_0React/components/image/conversions.h>
#include <ABI41_0_0React/core/propsConversions.h>
namespace ABI41_0_0facebook {
namespace ABI41_0_0React {
AndroidDialogPickerProps::AndroidDialogPickerProps(
const AndroidDialogPickerProps &sourceProps,
const RawProps &rawProps)
: ViewProps(sourceProps, rawProps),
color(convertRawProp(rawProps, "color", sourceProps.color, {})),
enabled(convertRawProp(rawProps, "enabled", sourceProps.enabled, {true})),
items(convertRawProp(rawProps, "items", sourceProps.items, {})),
prompt(convertRawProp(rawProps, "prompt", sourceProps.prompt, {""})),
selected(
convertRawProp(rawProps, "selected", sourceProps.selected, {0})) {}
} // namespace ABI41_0_0React
} // namespace ABI41_0_0facebook
| exponent/exponent | ios/versioned-react-native/ABI41_0_0/ReactNative/ReactCommon/fabric/components/picker/androidpicker/ABI41_0_0AndroidDialogPickerProps.cpp | C++ | bsd-3-clause | 1,031 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/drive/drive_api_util.h"
#include <string>
#include "base/files/file.h"
#include "base/logging.h"
#include "base/md5.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/drive/drive_api_parser.h"
#include "google_apis/drive/gdata_wapi_parser.h"
#include "net/base/escape.h"
#include "third_party/re2/re2/re2.h"
#include "url/gurl.h"
namespace drive {
namespace util {
namespace {
// Google Apps MIME types:
const char kGoogleDocumentMimeType[] = "application/vnd.google-apps.document";
const char kGoogleDrawingMimeType[] = "application/vnd.google-apps.drawing";
const char kGooglePresentationMimeType[] =
"application/vnd.google-apps.presentation";
const char kGoogleSpreadsheetMimeType[] =
"application/vnd.google-apps.spreadsheet";
const char kGoogleTableMimeType[] = "application/vnd.google-apps.table";
const char kGoogleFormMimeType[] = "application/vnd.google-apps.form";
const char kDriveFolderMimeType[] = "application/vnd.google-apps.folder";
std::string GetMimeTypeFromEntryKind(google_apis::DriveEntryKind kind) {
switch (kind) {
case google_apis::ENTRY_KIND_DOCUMENT:
return kGoogleDocumentMimeType;
case google_apis::ENTRY_KIND_SPREADSHEET:
return kGoogleSpreadsheetMimeType;
case google_apis::ENTRY_KIND_PRESENTATION:
return kGooglePresentationMimeType;
case google_apis::ENTRY_KIND_DRAWING:
return kGoogleDrawingMimeType;
case google_apis::ENTRY_KIND_TABLE:
return kGoogleTableMimeType;
case google_apis::ENTRY_KIND_FORM:
return kGoogleFormMimeType;
default:
return std::string();
}
}
ScopedVector<std::string> CopyScopedVectorString(
const ScopedVector<std::string>& source) {
ScopedVector<std::string> result;
result.reserve(source.size());
for (size_t i = 0; i < source.size(); ++i)
result.push_back(new std::string(*source[i]));
return result.Pass();
}
// Converts AppIcon (of GData WAPI) to DriveAppIcon.
scoped_ptr<google_apis::DriveAppIcon>
ConvertAppIconToDriveAppIcon(const google_apis::AppIcon& app_icon) {
scoped_ptr<google_apis::DriveAppIcon> resource(
new google_apis::DriveAppIcon);
switch (app_icon.category()) {
case google_apis::AppIcon::ICON_UNKNOWN:
resource->set_category(google_apis::DriveAppIcon::UNKNOWN);
break;
case google_apis::AppIcon::ICON_DOCUMENT:
resource->set_category(google_apis::DriveAppIcon::DOCUMENT);
break;
case google_apis::AppIcon::ICON_APPLICATION:
resource->set_category(google_apis::DriveAppIcon::APPLICATION);
break;
case google_apis::AppIcon::ICON_SHARED_DOCUMENT:
resource->set_category(google_apis::DriveAppIcon::SHARED_DOCUMENT);
break;
default:
NOTREACHED();
}
resource->set_icon_side_length(app_icon.icon_side_length());
resource->set_icon_url(app_icon.GetIconURL());
return resource.Pass();
}
// Converts InstalledApp to AppResource.
scoped_ptr<google_apis::AppResource>
ConvertInstalledAppToAppResource(
const google_apis::InstalledApp& installed_app) {
scoped_ptr<google_apis::AppResource> resource(new google_apis::AppResource);
resource->set_application_id(installed_app.app_id());
resource->set_name(installed_app.app_name());
resource->set_object_type(installed_app.object_type());
resource->set_supports_create(installed_app.supports_create());
{
ScopedVector<std::string> primary_mimetypes(
CopyScopedVectorString(installed_app.primary_mimetypes()));
resource->set_primary_mimetypes(primary_mimetypes.Pass());
}
{
ScopedVector<std::string> secondary_mimetypes(
CopyScopedVectorString(installed_app.secondary_mimetypes()));
resource->set_secondary_mimetypes(secondary_mimetypes.Pass());
}
{
ScopedVector<std::string> primary_file_extensions(
CopyScopedVectorString(installed_app.primary_extensions()));
resource->set_primary_file_extensions(primary_file_extensions.Pass());
}
{
ScopedVector<std::string> secondary_file_extensions(
CopyScopedVectorString(installed_app.secondary_extensions()));
resource->set_secondary_file_extensions(secondary_file_extensions.Pass());
}
{
const ScopedVector<google_apis::AppIcon>& app_icons =
installed_app.app_icons();
ScopedVector<google_apis::DriveAppIcon> icons;
icons.reserve(app_icons.size());
for (size_t i = 0; i < app_icons.size(); ++i) {
icons.push_back(ConvertAppIconToDriveAppIcon(*app_icons[i]).release());
}
resource->set_icons(icons.Pass());
}
// supports_import, installed and authorized are not supported in
// InstalledApp.
return resource.Pass();
}
// Returns the argument string.
std::string Identity(const std::string& resource_id) { return resource_id; }
} // namespace
std::string EscapeQueryStringValue(const std::string& str) {
std::string result;
result.reserve(str.size());
for (size_t i = 0; i < str.size(); ++i) {
if (str[i] == '\\' || str[i] == '\'') {
result.push_back('\\');
}
result.push_back(str[i]);
}
return result;
}
std::string TranslateQuery(const std::string& original_query) {
// In order to handle non-ascii white spaces correctly, convert to UTF16.
base::string16 query = base::UTF8ToUTF16(original_query);
const base::string16 kDelimiter(
base::kWhitespaceUTF16 +
base::string16(1, static_cast<base::char16>('"')));
std::string result;
for (size_t index = query.find_first_not_of(base::kWhitespaceUTF16);
index != base::string16::npos;
index = query.find_first_not_of(base::kWhitespaceUTF16, index)) {
bool is_exclusion = (query[index] == '-');
if (is_exclusion)
++index;
if (index == query.length()) {
// Here, the token is '-' and it should be ignored.
continue;
}
size_t begin_token = index;
base::string16 token;
if (query[begin_token] == '"') {
// Quoted query.
++begin_token;
size_t end_token = query.find('"', begin_token);
if (end_token == base::string16::npos) {
// This is kind of syntax error, since quoted string isn't finished.
// However, the query is built by user manually, so here we treat
// whole remaining string as a token as a fallback, by appending
// a missing double-quote character.
end_token = query.length();
query.push_back('"');
}
token = query.substr(begin_token, end_token - begin_token);
index = end_token + 1; // Consume last '"', too.
} else {
size_t end_token = query.find_first_of(kDelimiter, begin_token);
if (end_token == base::string16::npos) {
end_token = query.length();
}
token = query.substr(begin_token, end_token - begin_token);
index = end_token;
}
if (token.empty()) {
// Just ignore an empty token.
continue;
}
if (!result.empty()) {
// If there are two or more tokens, need to connect with "and".
result.append(" and ");
}
// The meaning of "fullText" should include title, description and content.
base::StringAppendF(
&result,
"%sfullText contains \'%s\'",
is_exclusion ? "not " : "",
EscapeQueryStringValue(base::UTF16ToUTF8(token)).c_str());
}
return result;
}
std::string ExtractResourceIdFromUrl(const GURL& url) {
return net::UnescapeURLComponent(url.ExtractFileName(),
net::UnescapeRule::URL_SPECIAL_CHARS);
}
std::string CanonicalizeResourceId(const std::string& resource_id) {
// If resource ID is in the old WAPI format starting with a prefix like
// "document:", strip it and return the remaining part.
std::string stripped_resource_id;
if (RE2::FullMatch(resource_id, "^[a-z-]+(?::|%3A)([\\w-]+)$",
&stripped_resource_id))
return stripped_resource_id;
return resource_id;
}
ResourceIdCanonicalizer GetIdentityResourceIdCanonicalizer() {
return base::Bind(&Identity);
}
const char kDocsListScope[] = "https://docs.google.com/feeds/";
const char kDriveAppsScope[] = "https://www.googleapis.com/auth/drive.apps";
void ParseShareUrlAndRun(const google_apis::GetShareUrlCallback& callback,
google_apis::GDataErrorCode error,
scoped_ptr<base::Value> value) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (!value) {
callback.Run(error, GURL());
return;
}
// Parsing ResourceEntry is cheap enough to do on UI thread.
scoped_ptr<google_apis::ResourceEntry> entry =
google_apis::ResourceEntry::ExtractAndParse(*value);
if (!entry) {
callback.Run(google_apis::GDATA_PARSE_ERROR, GURL());
return;
}
const google_apis::Link* share_link =
entry->GetLinkByType(google_apis::Link::LINK_SHARE);
callback.Run(error, share_link ? share_link->href() : GURL());
}
scoped_ptr<google_apis::AboutResource>
ConvertAccountMetadataToAboutResource(
const google_apis::AccountMetadata& account_metadata,
const std::string& root_resource_id) {
scoped_ptr<google_apis::AboutResource> resource(
new google_apis::AboutResource);
resource->set_largest_change_id(account_metadata.largest_changestamp());
resource->set_quota_bytes_total(account_metadata.quota_bytes_total());
resource->set_quota_bytes_used(account_metadata.quota_bytes_used());
resource->set_root_folder_id(root_resource_id);
return resource.Pass();
}
scoped_ptr<google_apis::AppList>
ConvertAccountMetadataToAppList(
const google_apis::AccountMetadata& account_metadata) {
scoped_ptr<google_apis::AppList> resource(new google_apis::AppList);
const ScopedVector<google_apis::InstalledApp>& installed_apps =
account_metadata.installed_apps();
ScopedVector<google_apis::AppResource> app_resources;
app_resources.reserve(installed_apps.size());
for (size_t i = 0; i < installed_apps.size(); ++i) {
app_resources.push_back(
ConvertInstalledAppToAppResource(*installed_apps[i]).release());
}
resource->set_items(app_resources.Pass());
// etag is not supported in AccountMetadata.
return resource.Pass();
}
scoped_ptr<google_apis::FileResource> ConvertResourceEntryToFileResource(
const google_apis::ResourceEntry& entry) {
scoped_ptr<google_apis::FileResource> file(new google_apis::FileResource);
file->set_file_id(entry.resource_id());
file->set_title(entry.title());
file->set_created_date(entry.published_time());
if (std::find(entry.labels().begin(), entry.labels().end(),
"shared-with-me") != entry.labels().end()) {
// Set current time to mark the file is shared_with_me, since ResourceEntry
// doesn't have |shared_with_me_date| equivalent.
file->set_shared_with_me_date(base::Time::Now());
}
file->set_shared(std::find(entry.labels().begin(), entry.labels().end(),
"shared") != entry.labels().end());
if (entry.is_folder()) {
file->set_mime_type(kDriveFolderMimeType);
} else {
std::string mime_type = GetMimeTypeFromEntryKind(entry.kind());
if (mime_type.empty())
mime_type = entry.content_mime_type();
file->set_mime_type(mime_type);
}
file->set_md5_checksum(entry.file_md5());
file->set_file_size(entry.file_size());
file->mutable_labels()->set_trashed(entry.deleted());
file->set_etag(entry.etag());
google_apis::ImageMediaMetadata* image_media_metadata =
file->mutable_image_media_metadata();
image_media_metadata->set_width(entry.image_width());
image_media_metadata->set_height(entry.image_height());
image_media_metadata->set_rotation(entry.image_rotation());
std::vector<google_apis::ParentReference>* parents = file->mutable_parents();
for (size_t i = 0; i < entry.links().size(); ++i) {
using google_apis::Link;
const Link& link = *entry.links()[i];
switch (link.type()) {
case Link::LINK_PARENT: {
google_apis::ParentReference parent;
parent.set_parent_link(link.href());
std::string file_id =
drive::util::ExtractResourceIdFromUrl(link.href());
parent.set_file_id(file_id);
parent.set_is_root(file_id == kWapiRootDirectoryResourceId);
parents->push_back(parent);
break;
}
case Link::LINK_ALTERNATE:
file->set_alternate_link(link.href());
break;
default:
break;
}
}
file->set_modified_date(entry.updated_time());
file->set_last_viewed_by_me_date(entry.last_viewed_time());
return file.Pass();
}
google_apis::DriveEntryKind GetKind(
const google_apis::FileResource& file_resource) {
if (file_resource.IsDirectory())
return google_apis::ENTRY_KIND_FOLDER;
const std::string& mime_type = file_resource.mime_type();
if (mime_type == kGoogleDocumentMimeType)
return google_apis::ENTRY_KIND_DOCUMENT;
if (mime_type == kGoogleSpreadsheetMimeType)
return google_apis::ENTRY_KIND_SPREADSHEET;
if (mime_type == kGooglePresentationMimeType)
return google_apis::ENTRY_KIND_PRESENTATION;
if (mime_type == kGoogleDrawingMimeType)
return google_apis::ENTRY_KIND_DRAWING;
if (mime_type == kGoogleTableMimeType)
return google_apis::ENTRY_KIND_TABLE;
if (mime_type == kGoogleFormMimeType)
return google_apis::ENTRY_KIND_FORM;
if (mime_type == "application/pdf")
return google_apis::ENTRY_KIND_PDF;
return google_apis::ENTRY_KIND_FILE;
}
scoped_ptr<google_apis::ResourceEntry>
ConvertFileResourceToResourceEntry(
const google_apis::FileResource& file_resource) {
scoped_ptr<google_apis::ResourceEntry> entry(new google_apis::ResourceEntry);
// ResourceEntry
entry->set_resource_id(file_resource.file_id());
entry->set_id(file_resource.file_id());
entry->set_kind(GetKind(file_resource));
entry->set_title(file_resource.title());
entry->set_published_time(file_resource.created_date());
std::vector<std::string> labels;
if (!file_resource.shared_with_me_date().is_null())
labels.push_back("shared-with-me");
if (file_resource.shared())
labels.push_back("shared");
entry->set_labels(labels);
// This should be the url to download the file_resource.
{
google_apis::Content content;
content.set_mime_type(file_resource.mime_type());
entry->set_content(content);
}
// TODO(kochi): entry->resource_links_
// For file entries
entry->set_filename(file_resource.title());
entry->set_suggested_filename(file_resource.title());
entry->set_file_md5(file_resource.md5_checksum());
entry->set_file_size(file_resource.file_size());
// If file is removed completely, that information is only available in
// ChangeResource, and is reflected in |removed_|. If file is trashed, the
// file entry still exists but with its "trashed" label true.
entry->set_deleted(file_resource.labels().is_trashed());
// ImageMediaMetadata
entry->set_image_width(file_resource.image_media_metadata().width());
entry->set_image_height(file_resource.image_media_metadata().height());
entry->set_image_rotation(file_resource.image_media_metadata().rotation());
// CommonMetadata
entry->set_etag(file_resource.etag());
// entry->authors_
// entry->links_.
ScopedVector<google_apis::Link> links;
for (size_t i = 0; i < file_resource.parents().size(); ++i) {
google_apis::Link* link = new google_apis::Link;
link->set_type(google_apis::Link::LINK_PARENT);
link->set_href(file_resource.parents()[i].parent_link());
links.push_back(link);
}
if (!file_resource.alternate_link().is_empty()) {
google_apis::Link* link = new google_apis::Link;
link->set_type(google_apis::Link::LINK_ALTERNATE);
link->set_href(file_resource.alternate_link());
links.push_back(link);
}
entry->set_links(links.Pass());
// entry->categories_
entry->set_updated_time(file_resource.modified_date());
entry->set_last_viewed_time(file_resource.last_viewed_by_me_date());
entry->FillRemainingFields();
return entry.Pass();
}
scoped_ptr<google_apis::ResourceEntry>
ConvertChangeResourceToResourceEntry(
const google_apis::ChangeResource& change_resource) {
scoped_ptr<google_apis::ResourceEntry> entry;
if (change_resource.file())
entry = ConvertFileResourceToResourceEntry(*change_resource.file()).Pass();
else
entry.reset(new google_apis::ResourceEntry);
entry->set_resource_id(change_resource.file_id());
// If |is_deleted()| returns true, the file is removed from Drive.
entry->set_removed(change_resource.is_deleted());
entry->set_changestamp(change_resource.change_id());
entry->set_modification_date(change_resource.modification_date());
return entry.Pass();
}
scoped_ptr<google_apis::ResourceList>
ConvertFileListToResourceList(const google_apis::FileList& file_list) {
scoped_ptr<google_apis::ResourceList> feed(new google_apis::ResourceList);
const ScopedVector<google_apis::FileResource>& items = file_list.items();
ScopedVector<google_apis::ResourceEntry> entries;
for (size_t i = 0; i < items.size(); ++i)
entries.push_back(ConvertFileResourceToResourceEntry(*items[i]).release());
feed->set_entries(entries.Pass());
ScopedVector<google_apis::Link> links;
if (!file_list.next_link().is_empty()) {
google_apis::Link* link = new google_apis::Link;
link->set_type(google_apis::Link::LINK_NEXT);
link->set_href(file_list.next_link());
links.push_back(link);
}
feed->set_links(links.Pass());
return feed.Pass();
}
scoped_ptr<google_apis::ResourceList>
ConvertChangeListToResourceList(const google_apis::ChangeList& change_list) {
scoped_ptr<google_apis::ResourceList> feed(new google_apis::ResourceList);
const ScopedVector<google_apis::ChangeResource>& items = change_list.items();
ScopedVector<google_apis::ResourceEntry> entries;
for (size_t i = 0; i < items.size(); ++i) {
entries.push_back(
ConvertChangeResourceToResourceEntry(*items[i]).release());
}
feed->set_entries(entries.Pass());
feed->set_largest_changestamp(change_list.largest_change_id());
ScopedVector<google_apis::Link> links;
if (!change_list.next_link().is_empty()) {
google_apis::Link* link = new google_apis::Link;
link->set_type(google_apis::Link::LINK_NEXT);
link->set_href(change_list.next_link());
links.push_back(link);
}
feed->set_links(links.Pass());
return feed.Pass();
}
std::string GetMd5Digest(const base::FilePath& file_path) {
const int kBufferSize = 512 * 1024; // 512kB.
base::File file(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
if (!file.IsValid())
return std::string();
base::MD5Context context;
base::MD5Init(&context);
int64 offset = 0;
scoped_ptr<char[]> buffer(new char[kBufferSize]);
while (true) {
int result = file.Read(offset, buffer.get(), kBufferSize);
if (result < 0) {
// Found an error.
return std::string();
}
if (result == 0) {
// End of file.
break;
}
offset += result;
base::MD5Update(&context, base::StringPiece(buffer.get(), result));
}
base::MD5Digest digest;
base::MD5Final(&digest, &context);
return MD5DigestToBase16(digest);
}
const char kWapiRootDirectoryResourceId[] = "folder:root";
} // namespace util
} // namespace drive
| patrickm/chromium.src | chrome/browser/drive/drive_api_util.cc | C++ | bsd-3-clause | 19,627 |
class Vehicletype < ActiveRecord::Base
has_many :vehicles
attr_accessible :capacity, :fuel, :maintcycle, :name
validates :name, :uniqueness => true
end
| alliciga/MWM | app/models/vehicletype.rb | Ruby | bsd-3-clause | 158 |
'use strict';
describe('Directive: searchFilters', function () {
// load the directive's module
beforeEach(module('searchApp'));
var element,
scope;
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new();
}));
it('should make hidden element visible', inject(function ($compile) {
element = angular.element('<search-filters></search-filters>');
element = $compile(element)(scope);
expect(element.text()).toBe('this is the searchFilters directive');
}));
});
| MLR-au/esrc-search | test/spec/directives/search-filters.js | JavaScript | bsd-3-clause | 509 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\Fahrtenbuch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="fahrtenbuch-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'fahrer')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'fahrzeug')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'start')->textInput() ?>
<?= $form->field($model, 'ende')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| smoos/fb_dispo | views/fahrtenbuch/_form.php | PHP | bsd-3-clause | 745 |
# This code is free software; you can redistribute it and/or modify it under
# the terms of the new BSD License.
#
# Copyright (c) 2011, Sebastian Staudt
require 'fixtures'
require 'helper'
class TestGitHub < Test::Unit::TestCase
context 'The GitHub implementation' do
should 'not support file stats' do
assert_not Metior::GitHub.supports? :file_stats
end
should 'not support line stats' do
assert_not Metior::GitHub.supports? :line_stats
end
end
context 'A GitHub repository' do
setup do
@repo = Metior::GitHub::Repository.new 'mojombo', 'grit'
api_response = Fixtures.commits_as_rashies(''..'master')
@commits_stub = Octokit.stubs :commits
14.times { @commits_stub.returns api_response.shift(35) }
@commits_stub.then.raises Octokit::NotFound.new(nil)
end
should 'be able to load all commits from the repository\'s default branch' do
commits = @repo.commits
assert_equal 460, commits.size
assert commits.all? { |commit| commit.is_a? Metior::GitHub::Commit }
head = commits.first
assert_equal '1b2fe77', head.id
end
should 'be able to load a range of commits from the repository' do
@commits_stub = Octokit.stubs :commits
api_response = Fixtures.commits_as_rashies(''..'4c592b4')
14.times { @commits_stub.returns api_response.shift(35) }
@commits_stub.raises Octokit::NotFound.new(nil)
api_response = Fixtures.commits_as_rashies(''..'ef2870b')
13.times { @commits_stub.returns api_response.shift(35) }
@commits_stub.then.raises Octokit::NotFound.new(nil)
commits = @repo.commits 'ef2870b'..'4c592b4'
assert_equal 6, commits.size
assert commits.all? { |commit| commit.is_a? Metior::GitHub::Commit }
assert_equal '4c592b4', commits.first.id
assert_equal 'f0cc7f7', commits.last.id
end
should 'know the authors of the repository' do
authors = @repo.authors
assert_equal 37, authors.size
assert authors.values.all? { |author| author.is_a? Metior::GitHub::Actor }
assert_equal %w{
adam@therealadam.com aman@tmm1.net antonin@hildebrand.cz
bobbywilson0@gmail.com bryce@worldmedia.net cehoffman@gmail.com
chapados@sciencegeeks.org cho45@lowreal.net chris@ozmm.org
davetron5000@gmail.com david.kowis@rackspace.com dustin@spy.net
engel@engel.uk.to evil@che.lu gram.gibson@uky.edu
hiroshi3110@gmail.com igor@wiedler.ch johan@johansorensen.com
jos@catnook.com jpriddle@nevercraft.net kamal.fariz@gmail.com
koraktor@gmail.com mtraverso@acm.org ohnobinki@ohnopublishing.net
paul+git@mjr.org pjhyett@gmail.com rsanheim@gmail.com
rtomayko@gmail.com schacon@gmail.com scott@railsnewbie.com
technoweenie@gmail.com tim@dysinger.net tim@spork.in
tom@mojombo.com tom@taco.(none) voker57@gmail.com wayne@larsen.st
}, authors.keys.sort
end
should 'know the committers of the repository' do
committers = @repo.committers
assert_equal 29, committers.size
assert committers.values.all? { |committer| committer.is_a? Metior::GitHub::Actor }
assert_equal %w{
adam@therealadam.com aman@tmm1.net antonin@hildebrand.cz
bobbywilson0@gmail.com bryce@worldmedia.net chris@ozmm.org
davetron5000@gmail.com david.kowis@rackspace.com dustin@spy.net
engel@engel.uk.to evil@che.lu hiroshi3110@gmail.com
johan@johansorensen.com jos@catnook.com kamal.fariz@gmail.com
koraktor@gmail.com mtraverso@acm.org ohnobinki@ohnopublishing.net
paul+git@mjr.org pjhyett@gmail.com rsanheim@gmail.com
rtomayko@gmail.com schacon@gmail.com technoweenie@gmail.com
tim@dysinger.net tim@spork.in tom@mojombo.com tom@taco.(none)
voker57@gmail.com
}, committers.keys.sort
end
should 'know the top authors of the repository' do
authors = @repo.top_authors
assert_equal 3, authors.size
assert authors.all? { |author| author.is_a? Metior::GitHub::Actor }
assert_equal [
"tom@mojombo.com", "schacon@gmail.com", "technoweenie@gmail.com"
], authors.collect { |author| author.id }
end
should 'not be able to get file stats of a repository' do
assert_raises UnsupportedError do
@repo.file_stats
end
end
should 'not be able to get the most significant authors of a repository' do
assert_raises UnsupportedError do
@repo.significant_authors
end
end
should 'not be able to get the most significant commits of a repository' do
assert_raises UnsupportedError do
@repo.significant_commits
end
end
should 'provide easy access to simple repository statistics' do
stats = Metior.simple_stats :github, 'mojombo', 'grit'
assert_equal 157, stats[:active_days].size
assert_equal 460, stats[:commit_count]
assert_in_delta 2.92993630573248, stats[:commits_per_active_day], 0.0001
assert_equal Time.at(1191997100), stats[:first_commit_date]
assert_equal Time.at(1306794294), stats[:last_commit_date]
assert_equal 5, stats[:top_contributors].size
end
end
end
| travis-repos/metior | test/test_github.rb | Ruby | bsd-3-clause | 5,231 |
/*
* HE_Mesh Frederik Vanhoutte - www.wblut.com
*
* https://github.com/wblut/HE_Mesh
* A Processing/Java library for for creating and manipulating polygonal meshes.
*
* Public Domain: http://creativecommons.org/publicdomain/zero/1.0/
* I , Frederik Vanhoutte, have waived all copyright and related or neighboring
* rights.
*
* This work is published from Belgium. (http://creativecommons.org/publicdomain/zero/1.0/)
*
*/
package wblut.geom;
/**
* Interface for implementing mutable mathematical operations on 3D coordinates.
*
* All of the operators defined in the interface change the calling object. All
* operators use the label "Self", such as "addSelf" to indicate this.
*
* @author Frederik Vanhoutte
*
*/
public interface WB_MutableCoordinateMath3D extends WB_CoordinateMath3D {
/**
* Add coordinate values.
*
* @param x
* @return this
*/
public WB_Coord addSelf(final double... x);
/**
* Add coordinate values.
*
* @param p
* @return this
*/
public WB_Coord addSelf(final WB_Coord p);
/**
* Subtract coordinate values.
*
* @param x
* @return this
*/
public WB_Coord subSelf(final double... x);
/**
* Subtract coordinate values.
*
* @param p
* @return this
*/
public WB_Coord subSelf(final WB_Coord p);
/**
* Multiply by factor.
*
* @param f
* @return this
*/
public WB_Coord mulSelf(final double f);
/**
* Divide by factor.
*
* @param f
* @return this
*/
public WB_Coord divSelf(final double f);
/**
* Add multiple of coordinate values.
*
* @param f
* multiplier
* @param x
* @return this
*/
public WB_Coord addMulSelf(final double f, final double... x);
/**
* Add multiple of coordinate values.
*
* @param f
* @param p
* @return this
*/
public WB_Coord addMulSelf(final double f, final WB_Coord p);
/**
* Multiply this coordinate by factor f and add other coordinate values
* multiplied by g.
*
* @param f
* @param g
* @param x
* @return this
*/
public WB_Coord mulAddMulSelf(final double f, final double g, final double... x);
/**
* Multiply this coordinate by factor f and add other coordinate values
* multiplied by g.
*
* @param f
* @param g
* @param p
* @return this
*/
public WB_Coord mulAddMulSelf(final double f, final double g, final WB_Coord p);
/**
*
*
* @param p
* @return this
*/
public WB_Coord crossSelf(final WB_Coord p);
/**
* Normalize this vector. Return the length before normalization. If this
* vector is degenerate 0 is returned and the vector remains the zero
* vector.
*
* @return this
*/
public double normalizeSelf();
/**
* If vector is larger than given value, trim vector.
*
* @param d
* @return this
*/
public WB_Coord trimSelf(final double d);
}
| DweebsUnited/CodeMonkey | java/CodeMonkey/HEMesh/wblut/geom/WB_MutableCoordinateMath3D.java | Java | bsd-3-clause | 2,810 |
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Zend\\View\\' => array($vendorDir . '/zendframework/zend-view/src'),
'Zend\\Validator\\' => array($vendorDir . '/zendframework/zend-validator/src'),
'Zend\\Uri\\' => array($vendorDir . '/zendframework/zend-uri/src'),
'Zend\\Stdlib\\' => array($vendorDir . '/zendframework/zend-stdlib/src'),
'Zend\\Session\\' => array($vendorDir . '/zendframework/zend-session/src'),
'Zend\\ServiceManager\\' => array($vendorDir . '/zendframework/zend-servicemanager/src'),
'Zend\\Router\\' => array($vendorDir . '/zendframework/zend-router/src'),
'Zend\\Mvc\\Plugin\\Prg\\' => array($vendorDir . '/zendframework/zend-mvc-plugin-prg/src'),
'Zend\\Mvc\\Plugin\\Identity\\' => array($vendorDir . '/zendframework/zend-mvc-plugin-identity/src'),
'Zend\\Mvc\\Plugin\\FlashMessenger\\' => array($vendorDir . '/zendframework/zend-mvc-plugin-flashmessenger/src'),
'Zend\\Mvc\\Plugin\\FilePrg\\' => array($vendorDir . '/zendframework/zend-mvc-plugin-fileprg/src'),
'Zend\\Mvc\\I18n\\' => array($vendorDir . '/zendframework/zend-mvc-i18n/src'),
'Zend\\Mvc\\' => array($vendorDir . '/zendframework/zend-mvc/src'),
'Zend\\ModuleManager\\' => array($vendorDir . '/zendframework/zend-modulemanager/src'),
'Zend\\Loader\\' => array($vendorDir . '/zendframework/zend-loader/src'),
'Zend\\Json\\' => array($vendorDir . '/zendframework/zend-json/src'),
'Zend\\InputFilter\\' => array($vendorDir . '/zendframework/zend-inputfilter/src'),
'Zend\\I18n\\' => array($vendorDir . '/zendframework/zend-i18n/src'),
'Zend\\Hydrator\\' => array($vendorDir . '/zendframework/zend-hydrator/src'),
'Zend\\Http\\' => array($vendorDir . '/zendframework/zend-http/src'),
'Zend\\Form\\' => array($vendorDir . '/zendframework/zend-form/src'),
'Zend\\Filter\\' => array($vendorDir . '/zendframework/zend-filter/src'),
'Zend\\EventManager\\' => array($vendorDir . '/zendframework/zend-eventmanager/src'),
'Zend\\Escaper\\' => array($vendorDir . '/zendframework/zend-escaper/src'),
'Zend\\Debug\\' => array($vendorDir . '/zendframework/zend-debug/src'),
'Zend\\Db\\' => array($vendorDir . '/zendframework/zend-db/src'),
'Zend\\Config\\' => array($vendorDir . '/zendframework/zend-config/src'),
'Zend\\ComponentInstaller\\' => array($vendorDir . '/zendframework/zend-component-installer/src'),
'Zend\\Code\\' => array($vendorDir . '/zendframework/zend-code/src'),
'Zend\\Authentication\\' => array($vendorDir . '/zendframework/zend-authentication/src'),
'ZendDeveloperTools\\' => array($vendorDir . '/zendframework/zend-developer-tools/src'),
'ZF\\DevelopmentMode\\' => array($vendorDir . '/zfcampus/zf-development-mode/src'),
'Pajakdaerah\\' => array($baseDir . '/module/Pajakdaerah/src'),
'Interop\\Container\\' => array($vendorDir . '/container-interop/container-interop/src/Interop/Container'),
'Application\\' => array($baseDir . '/module/Application/src'),
'ApplicationTest\\' => array($baseDir . '/module/Application/test'),
);
| fabi4n/pajakdaerah | vendor/composer/autoload_psr4.php | PHP | bsd-3-clause | 3,163 |
/*
* Software License Agreement (New BSD License)
*
* Copyright (c) 2013, Keith Leung, Felipe Inostroza
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Advanced Mining Technology Center (AMTC), the
* Universidad de Chile, nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AMTC, UNIVERSIDAD DE CHILE, OR THE COPYRIGHT
* HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <assert.h>
#include <boost/filesystem.hpp>
#include "GaussianMixture.hpp"
#include "Landmark.hpp"
#include "COLA.hpp"
#include "Particle.hpp"
#include "Pose.hpp"
#include <stdio.h>
#include <string>
#include <vector>
typedef unsigned int uint;
using namespace rfs;
class MM : public Landmark2d{
public:
MM(double x, double y, rfs::TimeStamp t = TimeStamp() ){
x_(0) = x;
x_(1) = y;
this->setTime(t);
}
~MM(){}
double operator-(const MM& other){
rfs::Landmark2d::Vec dx = x_ - other.x_;
return dx.norm();
//return sqrt(mahalanobisDist2( other )); For Mahalanobis distance
}
};
struct COLA_Error{
double error; // combined average error
double loc; // localization error
double card; // cardinality error
TimeStamp t;
};
/**
* \class LogFileReader2dSim
* \brief A class for reading 2d sim log files and for calculating errors
*/
class LogFileReader2dSim
{
public:
typedef Particle<Pose2d, GaussianMixture<Landmark2d> > TParticle;
typedef std::vector< TParticle > TParticleSet;
/** Constructor */
LogFileReader2dSim(const char* logDir){
std::string filename_gtpose( logDir );
std::string filename_gtlmk( logDir );
std::string filename_pose( logDir );
std::string filename_lmk( logDir );
std::string filename_dr( logDir );
filename_gtpose += "gtPose.dat";
filename_gtlmk += "gtLandmark.dat";
filename_pose += "particlePose.dat";
filename_lmk += "landmarkEst.dat";
filename_dr += "deadReckoning.dat";
pGTPoseFile = fopen(filename_gtpose.data(), "r");
pGTLandmarkFile = fopen(filename_gtlmk.data(), "r");
pParticlePoseFile = fopen(filename_pose.data(), "r");
pLandmarkEstFile = fopen(filename_lmk.data(), "r");
pDRFile = fopen(filename_dr.data(), "r");
readLandmarkGroundtruth();
int nread = fscanf(pParticlePoseFile, "%lf %d %lf %lf %lf %lf", &p_t_, &p_id_, &p_x_, &p_y_, &p_z_, &p_w_);
//printf("n = %d\n", nread);
//printf("t = %f [%d] %f %f %f\n", p_t_, p_id_, p_x_, p_y_, p_w_);
nread = fscanf(pLandmarkEstFile, "%lf %d %lf %lf %lf %lf %lf %lf\n",
&lmk_t_, &lmk_pid_, &lmk_x_, &lmk_y_, &lmk_sxx_, &lmk_sxy_, &lmk_syy_, &lmk_w_);
//printf("n = %d\n", nread);
//printf("t = %f [%d] %f %f %f\n", lmk_t_, lmk_pid_, lmk_x_, lmk_y_, lmk_w_);
}
/** Destructor */
~LogFileReader2dSim(){
fclose(pGTPoseFile);
fclose(pGTLandmarkFile);
fclose(pParticlePoseFile);
fclose(pLandmarkEstFile);
fclose(pDRFile);
}
/** Read landmark groundtruth data
* \return number of landmarks
*/
void readLandmarkGroundtruth(){
double x, y, t;
while( fscanf(pGTLandmarkFile, "%lf %lf %lf", &x, &y, &t) == 3){
map_e_M_.push_back( MM( x, y, TimeStamp(t) ) );
}
}
/** Read data for the next timestep
* \return time for which data was read
*/
double readNextStepData(){
if( fscanf(pGTPoseFile, "%lf %lf %lf %lf\n", &t_currentStep_, &rx_, &ry_, &rz_ ) == 4){
// Dead reckoning
int rval = fscanf(pDRFile, "%lf %lf %lf %lf\n", &dr_t_, &dr_x_, &dr_y_, &dr_z_);
// Particles
particles_.clear();
particles_.reserve(200);
w_sum_ = 0;
double w_hi = 0;
while(fabs(p_t_ - t_currentStep_) < 1e-12 ){
// printf("t = %f [%d] %f %f %f\n", p_t_, p_id_, p_x_, p_y_, p_w_);
w_sum_ += p_w_;
if( p_w_ > w_hi ){
i_hi_ = p_id_;
w_hi = p_w_;
}
Pose2d p;
p[0] = p_x_;
p[1] = p_y_;
p[2] = p_z_;
TParticle particle(p_id_, p, p_w_);
particles_.push_back( particle );
particles_[p_id_].setData( TParticle::PtrData( new GaussianMixture<Landmark2d> ));
if( fscanf(pParticlePoseFile, "%lf %d %lf %lf %lf %lf", &p_t_, &p_id_, &p_x_, &p_y_, &p_z_, &p_w_) != 6)
break;
}
// Landmark estimate from highest weighted particle
double const W_THRESHOLD = 0.75;
emap_e_M_.clear();
cardEst_ = 0;
while(fabs(lmk_t_ - t_currentStep_) < 1e-12){
if( lmk_pid_ == i_hi_ ){
if( lmk_w_ >= W_THRESHOLD ){
MM m_e_M(lmk_x_, lmk_y_, lmk_t_);
rfs::Landmark2d::Cov mCov;
mCov << lmk_sxx_, lmk_sxy_, lmk_sxy_, lmk_syy_;
m_e_M.setCov(mCov);
emap_e_M_.push_back(m_e_M);
}
cardEst_ += lmk_w_;
}
if(fscanf(pLandmarkEstFile, "%lf %d %lf %lf %lf %lf %lf %lf\n",
&lmk_t_, &lmk_pid_, &lmk_x_, &lmk_y_, &lmk_sxx_, &lmk_sxy_, &lmk_syy_, &lmk_w_) != 8)
break;
}
return t_currentStep_;
}
return -1;
}
/** Calculate the cardinality error for landmark estimates
* \param[out] nLandmarksObservable the actual number of observed landnmarks up to the current time
* \return cardinality estimate
*/
double getCardinalityEst( int &nLandmarksObservable ){
std::vector<MM> map_e_k_M; // observed groundtruth map storage (for Mahananobis distance calculations)
map_e_k_M.clear();
for(uint i = 0; i < map_e_M_.size(); i++){
if( map_e_M_[i].getTime().getTimeAsDouble() <= t_currentStep_ ){
map_e_k_M.push_back(map_e_M_[i]);
}
}
nLandmarksObservable = map_e_k_M.size();
return cardEst_;
}
/** Caclculate the error for landmark estimates
* \return COLA errors
*/
COLA_Error calcLandmarkError(){
double const cutoff = 0.20; // cola cutoff
double const order = 1.0; // cola order
std::vector<MM> map_e_k_M; // observed groundtruth map storage (for Mahananobis distance calculations)
map_e_k_M.clear();
for(uint i = 0; i < map_e_M_.size(); i++){
if( map_e_M_[i].getTime().getTimeAsDouble() <= t_currentStep_ ){
map_e_k_M.push_back(map_e_M_[i]);
}
}
COLA_Error e_cola;
e_cola.t = t_currentStep_;
COLA<MM> cola(emap_e_M_, map_e_k_M, cutoff, order);
e_cola.error = cola.calcError(&(e_cola.loc), &(e_cola.card));
return e_cola;
}
/** Calculate the dead reckoning error */
void calcDRError(double &err_x, double &err_y, double &err_rot, double &err_dist){
err_x = dr_x_ - rx_;
err_y = dr_y_ - ry_;
err_rot = dr_z_ - rz_;
if(err_rot > PI)
err_rot -= 2*PI;
else if(err_rot < -PI)
err_rot += 2*PI;
err_dist = sqrt(err_x * err_x + err_y * err_y);
}
/** Calculate the error for vehicle pose estimate */
void calcPoseError(double &err_x, double &err_y, double &err_rot, double &err_dist, bool getAverageError = true){
err_x = 0;
err_y = 0;
err_rot = 0;
err_dist = 0;
Pose2d poseEst;
double w = 1;
double ex;
double ey;
double er;
for(int i = 0; i < particles_.size(); i++){
if( !getAverageError && i != i_hi_){
continue;
}
if( getAverageError ){
w = particles_[i].getWeight();
}
poseEst = particles_[i];
ex = poseEst[0] - rx_;
ey = poseEst[1] - ry_;
er = poseEst[2] - rz_;
if(er > PI)
er -= 2 * PI;
else if(er < -PI)
er += 2 * PI;
err_x += ex * w;
err_y += ey * w;
err_rot += er * w;
err_dist += sqrt(ex * ex + ey * ey) * w;
if( !getAverageError && i == i_hi_){
break;
}
}
if( getAverageError ){
err_x /= w_sum_;
err_y /= w_sum_;
err_rot /= w_sum_;
err_dist /= w_sum_;
}
}
private:
FILE* pGTPoseFile; /**< robot pose groundtruth file pointer */
FILE* pGTLandmarkFile; /**< landmark groundtruth file pointer */
FILE* pParticlePoseFile; /**< pose estimate file pointer */
FILE* pLandmarkEstFile; /**< landmark estimate file pointer */
FILE* pMapEstErrorFile; /**< landmark estimate error file pointer */
FILE* pDRFile; /**< Dead-reckoning file */
double mx_; /**< landmark x pos */
double my_; /**< landmark y pos */
double t_currentStep_;
double rx_;
double ry_;
double rz_;
double dr_x_;
double dr_y_;
double dr_z_;
double dr_t_;
double i_hi_; /** highest particle weight index */
double w_sum_; /** particle weight sum */
TParticleSet particles_;
std::vector< Pose2d > pose_gt_;
std::vector<MM> map_e_M_; // groundtruth map storage (for Mahananobis distance calculations)
std::vector<MM> emap_e_M_; // estimated map storage (for Mahananobis distance calculations)
double cardEst_; // cardinality estimate
double p_t_;
int p_id_;
double p_x_;
double p_y_;
double p_z_;
double p_w_;
double lmk_t_;
int lmk_pid_;
double lmk_x_;
double lmk_y_;
double lmk_sxx_;
double lmk_sxy_;
double lmk_syy_;
double lmk_w_;
};
int main(int argc, char* argv[]){
if( argc != 2 ){
printf("Usage: analysis2dSim DATA_DIR/\n");
return 0;
}
const char* logDir = argv[1];
printf("Log directory: %s\n", logDir);
boost::filesystem::path dir(logDir);
if(!exists(dir)){
printf("Log directory %s does not exist\n", logDir);
return 0;
}
std::string filenameLandmarkEstError( logDir );
std::string filenamePoseEstError( logDir );
std::string filenameDREstError( logDir );
filenameLandmarkEstError += "landmarkEstError.dat";
filenamePoseEstError += "poseEstError.dat";
filenameDREstError += "deadReckoningError.dat";
FILE* pMapEstErrorFile = fopen(filenameLandmarkEstError.data(), "w");
FILE* pPoseEstErrorFile = fopen(filenamePoseEstError.data(), "w");
FILE* pDREstErrorFile = fopen(filenameDREstError.data(), "w");
LogFileReader2dSim reader(logDir);
double k = reader.readNextStepData();
while( k != -1){
//printf("Time: %f\n", k);
double ex, ey, er, ed;
reader.calcDRError( ex, ey, er, ed);
fprintf(pDREstErrorFile, "%f %f %f %f %f\n", k, ex, ey, er, ed);
reader.calcPoseError( ex, ey, er, ed, false );
fprintf(pPoseEstErrorFile, "%f %f %f %f %f\n", k, ex, ey, er, ed);
//printf(" error x: %f error y: %f error rot: %f error dist: %f\n", ex, ey, er, ed);
int nLandmarksObserved;
double cardEst = reader.getCardinalityEst( nLandmarksObserved );
COLA_Error colaError = reader.calcLandmarkError();
fprintf(pMapEstErrorFile, "%f %d %f %f\n", k, nLandmarksObserved, cardEst, colaError.error);
//printf(" nLandmarks: %d nLandmarks estimated: %f COLA error: %f\n", nLandmarksObserved, cardEst, colaError.loc + colaError.card);
//printf("--------------------\n");
k = reader.readNextStepData();
}
fclose(pPoseEstErrorFile);
fclose(pMapEstErrorFile);
fclose(pDREstErrorFile);
return 0;
}
| RangerKD/RFS-SLAM | src/analysis2dSim.cpp | C++ | bsd-3-clause | 12,152 |
/*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "config.h"
#include "TextEvent.h"
#include "DocumentFragment.h"
#include "EventNames.h"
namespace WebCore {
PassRefPtr<TextEvent> TextEvent::create()
{
return adoptRef(new TextEvent);
}
PassRefPtr<TextEvent> TextEvent::create(PassRefPtr<AbstractView> view, const String& data, TextEventInputType inputType)
{
return adoptRef(new TextEvent(view, data, inputType));
}
PassRefPtr<TextEvent> TextEvent::createForPlainTextPaste(PassRefPtr<AbstractView> view, const String& data, bool shouldSmartReplace)
{
return adoptRef(new TextEvent(view, data, 0, shouldSmartReplace, false));
}
PassRefPtr<TextEvent> TextEvent::createForFragmentPaste(PassRefPtr<AbstractView> view, PassRefPtr<DocumentFragment> data, bool shouldSmartReplace, bool shouldMatchStyle)
{
return adoptRef(new TextEvent(view, "", data, shouldSmartReplace, shouldMatchStyle));
}
PassRefPtr<TextEvent> TextEvent::createForDrop(PassRefPtr<AbstractView> view, const String& data)
{
return adoptRef(new TextEvent(view, data, TextEventInputDrop));
}
PassRefPtr<TextEvent> TextEvent::createForDictation(PassRefPtr<AbstractView> view, const String& data, const Vector<DictationAlternative>& dictationAlternatives)
{
return adoptRef(new TextEvent(view, data, dictationAlternatives));
}
TextEvent::TextEvent()
: m_inputType(TextEventInputKeyboard)
, m_shouldSmartReplace(false)
, m_shouldMatchStyle(false)
{
}
TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, TextEventInputType inputType)
: UIEvent(eventNames().textInputEvent, true, true, view, 0)
, m_inputType(inputType)
, m_data(data)
, m_pastingFragment(0)
, m_shouldSmartReplace(false)
, m_shouldMatchStyle(false)
{
}
TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, PassRefPtr<DocumentFragment> pastingFragment,
bool shouldSmartReplace, bool shouldMatchStyle)
: UIEvent(eventNames().textInputEvent, true, true, view, 0)
, m_inputType(TextEventInputPaste)
, m_data(data)
, m_pastingFragment(pastingFragment)
, m_shouldSmartReplace(shouldSmartReplace)
, m_shouldMatchStyle(shouldMatchStyle)
{
}
TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, const Vector<DictationAlternative>& dictationAlternatives)
: UIEvent(eventNames().textInputEvent, true, true, view, 0)
, m_inputType(TextEventInputDictation)
, m_data(data)
, m_shouldSmartReplace(false)
, m_shouldMatchStyle(false)
, m_dictationAlternatives(dictationAlternatives)
{
}
TextEvent::~TextEvent()
{
}
void TextEvent::initTextEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, const String& data)
{
if (dispatched())
return;
initUIEvent(type, canBubble, cancelable, view, 0);
m_data = data;
}
EventInterface TextEvent::eventInterface() const
{
return TextEventInterfaceType;
}
} // namespace WebCore
| klim-iv/phantomjs-qt5 | src/webkit/Source/WebCore/dom/TextEvent.cpp | C++ | bsd-3-clause | 4,309 |
// 1000-page badge
// Awarded when total read page count exceeds 1000.
var sys = require('sys');
var _ = require('underscore');
var users = require('../../users');
var badge_template = require('./badge');
// badge key, must be unique.
var name = "1000page";
exports.badge_info =
{
id: name,
name: "1,000 Pages",
achievement: "Reading over 1,000 pages."
}
// the in-work state of a badge for a user
function Badge (userid) {
badge_template.Badge.apply(this,arguments);
this.id = name;
this.page_goal = 1000;
};
// inherit from the badge template
sys.inherits(Badge, badge_template.Badge);
// Steps to perform when a book is added or modified in the read list
Badge.prototype.add_reading_transform = function(reading,callback) {
var pages = parseInt(reading.book.pages);
if (_.isNumber(pages)) {
this.state[reading.book_id] = pages
}
callback();
};
// Steps to perform when a book is removed from the read list.
Badge.prototype.remove_book_transform = function(book,callback) {
delete(this.state[book.id]);
callback();
};
// determine if the badge should be awarded, and if yes, do so
Badge.prototype.should_award = function(callback) {
// sum all page counts in state
var pagecount = 0;
for (bookid in this.state) {
pagecount += this.state[bookid]
}
return (pagecount >= this.page_goal);
}
exports.Badge = Badge; | scsibug/read52 | badger/badges/1000page.js | JavaScript | bsd-3-clause | 1,422 |
/*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class StaticRouteProfile extends ApplyProfile {
public String key;
public String getKey() {
return this.key;
}
public void setKey(String key) {
this.key=key;
}
} | xebialabs/vijava | src/com/vmware/vim25/StaticRouteProfile.java | Java | bsd-3-clause | 1,954 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/timezone/timezone_request.h"
#include <string>
#include "base/json/json_reader.h"
#include "base/metrics/histogram.h"
#include "base/metrics/sparse_histogram.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "base/values.h"
#include "content/public/common/geoposition.h"
#include "google_apis/google_api_keys.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
namespace chromeos {
namespace {
const char kDefaultTimezoneProviderUrl[] =
"https://maps.googleapis.com/maps/api/timezone/json?";
const char kKeyString[] = "key";
// Language parameter is unsupported for now.
// const char kLanguageString[] = "language";
const char kLocationString[] = "location";
const char kSensorString[] = "sensor";
const char kTimestampString[] = "timestamp";
const char kDstOffsetString[] = "dstOffset";
const char kRawOffsetString[] = "rawOffset";
const char kTimeZoneIdString[] = "timeZoneId";
const char kTimeZoneNameString[] = "timeZoneName";
const char kStatusString[] = "status";
const char kErrorMessageString[] = "error_message";
// Sleep between timezone request retry on HTTP error.
const unsigned int kResolveTimeZoneRetrySleepOnServerErrorSeconds = 5;
// Sleep between timezone request retry on bad server response.
const unsigned int kResolveTimeZoneRetrySleepBadResponseSeconds = 10;
struct StatusString2Enum {
const char* string;
TimeZoneResponseData::Status value;
};
const StatusString2Enum statusString2Enum[] = {
{"OK", TimeZoneResponseData::OK},
{"INVALID_REQUEST", TimeZoneResponseData::INVALID_REQUEST},
{"OVER_QUERY_LIMIT", TimeZoneResponseData::OVER_QUERY_LIMIT},
{"REQUEST_DENIED", TimeZoneResponseData::REQUEST_DENIED},
{"UNKNOWN_ERROR", TimeZoneResponseData::UNKNOWN_ERROR},
{"ZERO_RESULTS", TimeZoneResponseData::ZERO_RESULTS}, };
enum TimeZoneRequestEvent {
// NOTE: Do not renumber these as that would confuse interpretation of
// previously logged data. When making changes, also update the enum list
// in tools/metrics/histograms/histograms.xml to keep it in sync.
TIMEZONE_REQUEST_EVENT_REQUEST_START = 0,
TIMEZONE_REQUEST_EVENT_RESPONSE_SUCCESS = 1,
TIMEZONE_REQUEST_EVENT_RESPONSE_NOT_OK = 2,
TIMEZONE_REQUEST_EVENT_RESPONSE_EMPTY = 3,
TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED = 4,
// NOTE: Add entries only immediately above this line.
TIMEZONE_REQUEST_EVENT_COUNT = 5
};
enum TimeZoneRequestResult {
// NOTE: Do not renumber these as that would confuse interpretation of
// previously logged data. When making changes, also update the enum list
// in tools/metrics/histograms/histograms.xml to keep it in sync.
TIMEZONE_REQUEST_RESULT_SUCCESS = 0,
TIMEZONE_REQUEST_RESULT_FAILURE = 1,
TIMEZONE_REQUEST_RESULT_SERVER_ERROR = 2,
TIMEZONE_REQUEST_RESULT_CANCELLED = 3,
// NOTE: Add entries only immediately above this line.
TIMEZONE_REQUEST_RESULT_COUNT = 4
};
// Too many requests (more than 1) mean there is a problem in implementation.
void RecordUmaEvent(TimeZoneRequestEvent event) {
UMA_HISTOGRAM_ENUMERATION(
"TimeZone.TimeZoneRequest.Event", event, TIMEZONE_REQUEST_EVENT_COUNT);
}
void RecordUmaResponseCode(int code) {
UMA_HISTOGRAM_SPARSE_SLOWLY("TimeZone.TimeZoneRequest.ResponseCode", code);
}
// Slow timezone resolve leads to bad user experience.
void RecordUmaResponseTime(base::TimeDelta elapsed, bool success) {
if (success) {
UMA_HISTOGRAM_TIMES("TimeZone.TimeZoneRequest.ResponseSuccessTime",
elapsed);
} else {
UMA_HISTOGRAM_TIMES("TimeZone.TimeZoneRequest.ResponseFailureTime",
elapsed);
}
}
void RecordUmaResult(TimeZoneRequestResult result, unsigned retries) {
UMA_HISTOGRAM_ENUMERATION(
"TimeZone.TimeZoneRequest.Result", result, TIMEZONE_REQUEST_RESULT_COUNT);
UMA_HISTOGRAM_SPARSE_SLOWLY("TimeZone.TimeZoneRequest.Retries", retries);
}
// Creates the request url to send to the server.
GURL TimeZoneRequestURL(const GURL& url,
const content::Geoposition& geoposition,
bool sensor) {
std::string query(url.query());
query += base::StringPrintf(
"%s=%f,%f", kLocationString, geoposition.latitude, geoposition.longitude);
if (url == DefaultTimezoneProviderURL()) {
std::string api_key = google_apis::GetAPIKey();
if (!api_key.empty()) {
query += "&";
query += kKeyString;
query += "=";
query += net::EscapeQueryParamValue(api_key, true);
}
}
if (!geoposition.timestamp.is_null()) {
query += base::StringPrintf(
"&%s=%ld", kTimestampString, geoposition.timestamp.ToTimeT());
}
query += "&";
query += kSensorString;
query += "=";
query += (sensor ? "true" : "false");
GURL::Replacements replacements;
replacements.SetQueryStr(query);
return url.ReplaceComponents(replacements);
}
void PrintTimeZoneError(const GURL& server_url,
const std::string& message,
TimeZoneResponseData* timezone) {
timezone->status = TimeZoneResponseData::REQUEST_ERROR;
timezone->error_message =
base::StringPrintf("TimeZone provider at '%s' : %s.",
server_url.GetOrigin().spec().c_str(),
message.c_str());
LOG(WARNING) << "TimeZoneRequest::GetTimeZoneFromResponse() : "
<< timezone->error_message;
}
// Parses the server response body. Returns true if parsing was successful.
// Sets |*timezone| to the parsed TimeZone if a valid timezone was received,
// otherwise leaves it unchanged.
bool ParseServerResponse(const GURL& server_url,
const std::string& response_body,
TimeZoneResponseData* timezone) {
DCHECK(timezone);
if (response_body.empty()) {
PrintTimeZoneError(server_url, "Server returned empty response", timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_EMPTY);
return false;
}
VLOG(1) << "TimeZoneRequest::ParseServerResponse() : Parsing response "
<< response_body;
// Parse the response, ignoring comments.
std::string error_msg;
scoped_ptr<base::Value> response_value(base::JSONReader::ReadAndReturnError(
response_body, base::JSON_PARSE_RFC, NULL, &error_msg));
if (response_value == NULL) {
PrintTimeZoneError(server_url, "JSONReader failed: " + error_msg, timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
return false;
}
const base::DictionaryValue* response_object = NULL;
if (!response_value->GetAsDictionary(&response_object)) {
PrintTimeZoneError(server_url,
"Unexpected response type : " +
base::StringPrintf("%u", response_value->GetType()),
timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
return false;
}
std::string status;
if (!response_object->GetStringWithoutPathExpansion(kStatusString, &status)) {
PrintTimeZoneError(server_url, "Missing status attribute.", timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
return false;
}
bool found = false;
for (size_t i = 0; i < arraysize(statusString2Enum); ++i) {
if (status != statusString2Enum[i].string)
continue;
timezone->status = statusString2Enum[i].value;
found = true;
break;
}
if (!found) {
PrintTimeZoneError(
server_url, "Bad status attribute value: '" + status + "'", timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
return false;
}
const bool status_ok = (timezone->status == TimeZoneResponseData::OK);
if (!response_object->GetDoubleWithoutPathExpansion(kDstOffsetString,
&timezone->dstOffset) &&
status_ok) {
PrintTimeZoneError(server_url, "Missing dstOffset attribute.", timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
return false;
}
if (!response_object->GetDoubleWithoutPathExpansion(kRawOffsetString,
&timezone->rawOffset) &&
status_ok) {
PrintTimeZoneError(server_url, "Missing rawOffset attribute.", timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
return false;
}
if (!response_object->GetStringWithoutPathExpansion(kTimeZoneIdString,
&timezone->timeZoneId) &&
status_ok) {
PrintTimeZoneError(server_url, "Missing timeZoneId attribute.", timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
return false;
}
if (!response_object->GetStringWithoutPathExpansion(
kTimeZoneNameString, &timezone->timeZoneName) &&
status_ok) {
PrintTimeZoneError(server_url, "Missing timeZoneName attribute.", timezone);
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_MALFORMED);
return false;
}
// "error_message" field is optional. Ignore result.
response_object->GetStringWithoutPathExpansion(kErrorMessageString,
&timezone->error_message);
return true;
}
// Attempts to extract a position from the response. Detects and indicates
// various failure cases.
scoped_ptr<TimeZoneResponseData> GetTimeZoneFromResponse(
bool http_success,
int status_code,
const std::string& response_body,
const GURL& server_url) {
scoped_ptr<TimeZoneResponseData> timezone(new TimeZoneResponseData);
// HttpPost can fail for a number of reasons. Most likely this is because
// we're offline, or there was no response.
if (!http_success) {
PrintTimeZoneError(server_url, "No response received", timezone.get());
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_EMPTY);
return timezone.Pass();
}
if (status_code != net::HTTP_OK) {
std::string message = "Returned error code ";
message += base::IntToString(status_code);
PrintTimeZoneError(server_url, message, timezone.get());
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_NOT_OK);
return timezone.Pass();
}
if (!ParseServerResponse(server_url, response_body, timezone.get()))
return timezone.Pass();
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_RESPONSE_SUCCESS);
return timezone.Pass();
}
} // namespace
TimeZoneResponseData::TimeZoneResponseData()
: dstOffset(0), rawOffset(0), status(ZERO_RESULTS) {
}
GURL DefaultTimezoneProviderURL() {
return GURL(kDefaultTimezoneProviderUrl);
}
TimeZoneRequest::TimeZoneRequest(
net::URLRequestContextGetter* url_context_getter,
const GURL& service_url,
const content::Geoposition& geoposition,
bool sensor,
base::TimeDelta retry_timeout)
: url_context_getter_(url_context_getter),
service_url_(service_url),
geoposition_(geoposition),
sensor_(sensor),
retry_timeout_abs_(base::Time::Now() + retry_timeout),
retries_(0) {
}
TimeZoneRequest::~TimeZoneRequest() {
DCHECK(thread_checker_.CalledOnValidThread());
// If callback is not empty, request is cancelled.
if (!callback_.is_null()) {
RecordUmaResponseTime(base::Time::Now() - request_started_at_, false);
RecordUmaResult(TIMEZONE_REQUEST_RESULT_CANCELLED, retries_);
}
}
void TimeZoneRequest::StartRequest() {
DCHECK(thread_checker_.CalledOnValidThread());
RecordUmaEvent(TIMEZONE_REQUEST_EVENT_REQUEST_START);
request_started_at_ = base::Time::Now();
++retries_;
url_fetcher_.reset(
net::URLFetcher::Create(request_url_, net::URLFetcher::GET, this));
url_fetcher_->SetRequestContext(url_context_getter_);
url_fetcher_->SetLoadFlags(net::LOAD_BYPASS_CACHE |
net::LOAD_DISABLE_CACHE |
net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA);
url_fetcher_->Start();
}
void TimeZoneRequest::MakeRequest(TimeZoneResponseCallback callback) {
callback_ = callback;
request_url_ =
TimeZoneRequestURL(service_url_, geoposition_, false /* sensor */);
StartRequest();
}
void TimeZoneRequest::Retry(bool server_error) {
const base::TimeDelta delay = base::TimeDelta::FromSeconds(
server_error ? kResolveTimeZoneRetrySleepOnServerErrorSeconds
: kResolveTimeZoneRetrySleepBadResponseSeconds);
timezone_request_scheduled_.Start(
FROM_HERE, delay, this, &TimeZoneRequest::StartRequest);
}
void TimeZoneRequest::OnURLFetchComplete(const net::URLFetcher* source) {
DCHECK_EQ(url_fetcher_.get(), source);
net::URLRequestStatus status = source->GetStatus();
int response_code = source->GetResponseCode();
RecordUmaResponseCode(response_code);
std::string data;
source->GetResponseAsString(&data);
scoped_ptr<TimeZoneResponseData> timezone = GetTimeZoneFromResponse(
status.is_success(), response_code, data, source->GetURL());
const bool server_error =
!status.is_success() || (response_code >= 500 && response_code < 600);
url_fetcher_.reset();
DVLOG(1) << "TimeZoneRequest::OnURLFetchComplete(): timezone={"
<< timezone->ToStringForDebug() << "}";
const base::Time now = base::Time::Now();
const bool retry_timeout = (now >= retry_timeout_abs_);
const bool success = (timezone->status == TimeZoneResponseData::OK);
if (!success && !retry_timeout) {
Retry(server_error);
return;
}
RecordUmaResponseTime(base::Time::Now() - request_started_at_, success);
const TimeZoneRequestResult result =
(server_error ? TIMEZONE_REQUEST_RESULT_SERVER_ERROR
: (success ? TIMEZONE_REQUEST_RESULT_SUCCESS
: TIMEZONE_REQUEST_RESULT_FAILURE));
RecordUmaResult(result, retries_);
TimeZoneResponseCallback callback = callback_;
// Empty callback is used to identify "completed or not yet started request".
callback_.Reset();
// callback.Run() usually destroys TimeZoneRequest, because this is the way
// callback is implemented in TimeZoneProvider.
callback.Run(timezone.Pass(), server_error);
// "this" is already destroyed here.
}
std::string TimeZoneResponseData::ToStringForDebug() const {
static const char* const status2string[] = {
"OK",
"INVALID_REQUEST",
"OVER_QUERY_LIMIT",
"REQUEST_DENIED",
"UNKNOWN_ERROR",
"ZERO_RESULTS",
"REQUEST_ERROR"
};
return base::StringPrintf(
"dstOffset=%f, rawOffset=%f, timeZoneId='%s', timeZoneName='%s', "
"error_message='%s', status=%u (%s)",
dstOffset,
rawOffset,
timeZoneId.c_str(),
timeZoneName.c_str(),
error_message.c_str(),
(unsigned)status,
(status < arraysize(status2string) ? status2string[status] : "unknown"));
};
} // namespace chromeos
| patrickm/chromium.src | chrome/browser/chromeos/timezone/timezone_request.cc | C++ | bsd-3-clause | 15,268 |
package com.krishagni.catissueplus.core.biospecimen.events;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.krishagni.catissueplus.core.administrative.events.StorageLocationSummary;
import com.krishagni.catissueplus.core.common.events.UserSummary;
import com.krishagni.catissueplus.core.de.events.ExtensionDetail;
public class SpecimenAliquotsSpec {
private Long parentId;
private String parentLabel;
private String derivedReqCode;
private String cpShortTitle;
private Integer noOfAliquots;
private String labels;
private String barcodes;
private BigDecimal qtyPerAliquot;
private String specimenClass;
private String type;
private BigDecimal concentration;
private Date createdOn;
private UserSummary createdBy;
private String parentContainerName;
private String containerType;
private String containerName;
private String positionX;
private String positionY;
private Integer position;
private List<StorageLocationSummary> locations;
private Integer freezeThawCycles;
private Integer incrParentFreezeThaw;
private Boolean closeParent;
private Boolean createDerived;
private Boolean printLabel;
private String comments;
private ExtensionDetail extensionDetail;
private boolean linkToReqs;
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getParentLabel() {
return parentLabel;
}
public void setParentLabel(String parentLabel) {
this.parentLabel = parentLabel;
}
public String getDerivedReqCode() {
return derivedReqCode;
}
public void setDerivedReqCode(String derivedReqCode) {
this.derivedReqCode = derivedReqCode;
}
public String getCpShortTitle() {
return cpShortTitle;
}
public void setCpShortTitle(String cpShortTitle) {
this.cpShortTitle = cpShortTitle;
}
public Integer getNoOfAliquots() {
return noOfAliquots;
}
public void setNoOfAliquots(Integer noOfAliquots) {
this.noOfAliquots = noOfAliquots;
}
public String getLabels() {
return labels;
}
public void setLabels(String labels) {
this.labels = labels;
}
public String getBarcodes() {
return barcodes;
}
public void setBarcodes(String barcodes) {
this.barcodes = barcodes;
}
public BigDecimal getQtyPerAliquot() {
return qtyPerAliquot;
}
public void setQtyPerAliquot(BigDecimal qtyPerAliquot) {
this.qtyPerAliquot = qtyPerAliquot;
}
public String getSpecimenClass() {
return specimenClass;
}
public void setSpecimenClass(String specimenClass) {
this.specimenClass = specimenClass;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public BigDecimal getConcentration() {
return concentration;
}
public void setConcentration(BigDecimal concentration) {
this.concentration = concentration;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public UserSummary getCreatedBy() {
return createdBy;
}
public void setCreatedBy(UserSummary createdBy) {
this.createdBy = createdBy;
}
public String getParentContainerName() {
return parentContainerName;
}
public void setParentContainerName(String parentContainerName) {
this.parentContainerName = parentContainerName;
}
public String getContainerType() {
return containerType;
}
public void setContainerType(String containerType) {
this.containerType = containerType;
}
public String getContainerName() {
return containerName;
}
public void setContainerName(String containerName) {
this.containerName = containerName;
}
public String getPositionX() {
return positionX;
}
public void setPositionX(String positionX) {
this.positionX = positionX;
}
public String getPositionY() {
return positionY;
}
public void setPositionY(String positionY) {
this.positionY = positionY;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public List<StorageLocationSummary> getLocations() {
return locations;
}
public void setLocations(List<StorageLocationSummary> locations) {
this.locations = locations;
}
public Integer getFreezeThawCycles() {
return freezeThawCycles;
}
public void setFreezeThawCycles(Integer freezeThawCycles) {
this.freezeThawCycles = freezeThawCycles;
}
public Integer getIncrParentFreezeThaw() {
return incrParentFreezeThaw;
}
public void setIncrParentFreezeThaw(Integer incrParentFreezeThaw) {
this.incrParentFreezeThaw = incrParentFreezeThaw;
}
public Boolean getCloseParent() {
return closeParent;
}
public void setCloseParent(Boolean closeParent) {
this.closeParent = closeParent;
}
public boolean closeParent() {
return closeParent != null && closeParent;
}
public Boolean getCreateDerived() {
return createDerived;
}
public void setCreateDerived(Boolean createDerived) {
this.createDerived = createDerived;
}
public boolean createDerived() { return createDerived != null && createDerived; }
public Boolean getPrintLabel() {
return printLabel;
}
public void setPrintLabel(Boolean printLabel) {
this.printLabel = printLabel;
}
public boolean printLabel() { return printLabel != null && printLabel; }
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public ExtensionDetail getExtensionDetail() {
return extensionDetail;
}
public void setExtensionDetail(ExtensionDetail extensionDetail) {
this.extensionDetail = extensionDetail;
}
public boolean isLinkToReqs() {
return linkToReqs;
}
public void setLinkToReqs(boolean linkToReqs) {
this.linkToReqs = linkToReqs;
}
} | krishagni/openspecimen | WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/events/SpecimenAliquotsSpec.java | Java | bsd-3-clause | 5,811 |
// $Id: MainClass.java,v 1.6 2003/10/07 21:46:08 idgay Exp $
/* tab:4
* "Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
* Copyright (c) 2002-2003 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/**
* @author Wei Hong
*/
//***********************************************************************
//***********************************************************************
//this is the main class that holds all global variables
//and from where "main" is run.
//the global variables can be accessed as: MainClass.MainFrame for example.
//***********************************************************************
//***********************************************************************
package net.tinyos.tinydb.topology;
import java.util.*;
import net.tinyos.tinydb.*;
import net.tinyos.tinydb.topology.event.*;
import net.tinyos.tinydb.topology.util.*;
import net.tinyos.tinydb.topology.PacketAnalyzer.*;
import net.tinyos.tinydb.topology.Dialog.*;
import net.tinyos.tinydb.topology.Packet.*;
import javax.swing.event.*;
import java.beans.*;
import java.awt.*;
import java.io.*;
import net.tinyos.tinydb.parser.*;
public class MainClass implements ResultListener
{
public static MainFrame mainFrame;
public static DisplayManager displayManager;
public static ObjectMaintainer objectMaintainer;
public static SensorAnalyzer sensorAnalyzer;
public static LocationAnalyzer locationAnalyzer;
public static Vector packetAnalyzers;
public static TinyDBQuery topologyQuery;
public static boolean topologyQueryRunning = false;
public static String topologyQueryText = "select nodeid, parent, light, temp, voltage epoch duration 2048";
TinyDBNetwork nw;
public MainClass(TinyDBNetwork nw, byte qid) throws IOException
{
this.nw = nw;
nw.addResultListener(this, false, qid);
mainFrame = new MainFrame("Sensor Network Topology", nw);
displayManager = new DisplayManager(mainFrame);
packetAnalyzers = new Vector();
objectMaintainer = new ObjectMaintainer();
objectMaintainer.AddEdgeEventListener(displayManager);
objectMaintainer.AddNodeEventListener(displayManager);
locationAnalyzer = new LocationAnalyzer();
sensorAnalyzer = new SensorAnalyzer();
packetAnalyzers.add(objectMaintainer);
packetAnalyzers.add(sensorAnalyzer);
//make the MainFrame visible as the last thing
mainFrame.setVisible(true);
try
{
System.out.println("Topology Query: " + topologyQueryText);
topologyQuery = SensorQueryer.translateQuery(topologyQueryText, qid);
}
catch (ParseException pe)
{
System.out.println("Topology Query: " + topologyQueryText);
System.out.println("Parse Error: " + pe.getParseError());
topologyQuery = null;
}
nw.sendQuery(topologyQuery);
TinyDBMain.notifyAddedQuery(topologyQuery);
topologyQueryRunning = true;
}
public void addResult(QueryResult qr) {
Packet packet = new Packet(qr);
try {
if (packet.getNodeId().intValue() < 0 ||
packet.getNodeId().intValue() > 128 ||
packet.getParent().intValue() < 0 ||
packet.getParent().intValue() > 128 )
return;
} catch (ArrayIndexOutOfBoundsException e) {
return;
}
PacketEventListener currentListener;
for(Enumeration list = packetAnalyzers.elements(); list.hasMoreElements();)
{
currentListener = (PacketEventListener)list.nextElement();
PacketEvent e = new PacketEvent(nw, packet,
Calendar.getInstance().getTime());
currentListener.PacketReceived(e);//send the listener an event
}
}
}
| fresskarma/tinyos-1.x | tools/java/net/tinyos/tinydb/topology/MainClass.java | Java | bsd-3-clause | 4,833 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Web;
namespace BotR.API {
public class BotRAPI {
private string _apiURL = "";
private string _args = "";
private NameValueCollection _queryString = null;
public string Key { get; set; }
public string Secret { get; set; }
public string APIFormat { get; set; }
public BotRAPI(string key, string secret) : this("http://api.bitsontherun.com", "v1", key, secret) { }
public BotRAPI(string url, string version, string key, string secret) {
Key = key;
Secret = secret;
_apiURL = string.Format("{0}/{1}", url, version);
}
/// <summary>
/// Call the API method with no params beyond the required
/// </summary>
/// <param name="apiCall">The path to the API method call (/videos/list)</param>
/// <returns>The string response from the API call</returns>
public string Call(string apiCall) {
return Call(apiCall, null);
}
/// <summary>
/// Call the API method with additional, non-required params
/// </summary>
/// <param name="apiCall">The path to the API method call (/videos/list)</param>
/// <param name="args">Additional, non-required arguments</param>
/// <returns>The string response from the API call</returns>
public string Call(string apiCall, NameValueCollection args) {
_queryString = new NameValueCollection();
//add the non-required args to the required args
if (args != null)
_queryString.Add(args);
buildArgs();
WebClient client = createWebClient();
string callUrl = _apiURL + apiCall;
try {
return client.DownloadString(callUrl);
} catch {
return "";
}
}
/// <summary>
/// Upload a file to account
/// </summary>
/// <param name="uploadUrl">The url returned from /videos/create call</param>
/// <param name="args">Optional args (video meta data)</param>
/// <param name="filePath">Path to file to upload</param>
/// <returns>The string response from the API call</returns>
public string Upload(string uploadUrl, NameValueCollection args, string filePath) {
_queryString = args; //no required args
WebClient client = createWebClient();
_queryString["api_format"] = APIFormat ?? "xml"; //xml if not specified - normally set in required args routine
queryStringToArgs();
string callUrl = _apiURL + uploadUrl + "?" + _args;
callUrl = uploadUrl + "?" + _args;
try {
byte[] response = client.UploadFile(callUrl, filePath);
return Encoding.UTF8.GetString(response);
} catch {
return "";
}
}
/// <summary>
/// Hash the provided arguments
/// </summary>
private string signArgs() {
queryStringToArgs();
HashAlgorithm ha = HashAlgorithm.Create("SHA");
byte[] hashed = ha.ComputeHash(Encoding.UTF8.GetBytes(_args + Secret));
return BitConverter.ToString(hashed).Replace("-", "").ToLower();
}
/// <summary>
/// Convert args collection to ordered string
/// </summary>
private void queryStringToArgs() {
Array.Sort(_queryString.AllKeys);
StringBuilder sb = new StringBuilder();
foreach (string key in _queryString.AllKeys) {
sb.AppendFormat("{0}={1}&", key, _queryString[key]);
}
sb.Remove(sb.Length - 1, 1); //remove trailing &
_args = sb.ToString();
}
/// <summary>
/// Append required arguments to URL
/// </summary>
private void buildArgs() {
_queryString["api_format"] = APIFormat ?? "xml"; //xml if not specified
_queryString["api_key"] = Key;
_queryString["api_kit"] = "dnet-1.0";
_queryString["api_nonce"] = string.Format("{0:00000000}", new Random().Next(99999999));
_queryString["api_timestamp"] = getUnixTime().ToString();
_queryString["api_signature"] = signArgs();
_args = string.Concat(_args, "&api_signature=", _queryString["api_signature"]);
}
/// <summary>
/// Construct instance of WebClient for request
/// </summary>
/// <returns></returns>
private WebClient createWebClient() {
ServicePointManager.Expect100Continue = false; //upload will fail w/o
WebClient client = new WebClient();
client.BaseAddress = _apiURL;
client.QueryString = _queryString;
client.Encoding = UTF8Encoding.UTF8;
return client;
}
/// <summary>
/// Get timestamp in Unix format
/// </summary>
/// <returns></returns>
private int getUnixTime() {
return (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
}
}
}
| bitsontherun/botr-api-dotnet | BotRAPI.cs | C# | bsd-3-clause | 5,584 |
/* prevent execution of jQuery if included more than once */
if(typeof window.jQuery == "undefined") {
/*
* jQuery 1.1.2 - New Wave Javascript
*
* Copyright (c) 2007 John Resig (jquery.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* $Date: 2007-04-03 22:27:21 $
* $Rev: 1465 $
*/
// Global undefined variable
window.undefined = window.undefined;
var jQuery = function(a,c) {
// If the context is global, return a new object
if ( window == this )
return new jQuery(a,c);
// Make sure that a selection was provided
a = a || document;
// HANDLE: $(function)
// Shortcut for document ready
if ( jQuery.isFunction(a) )
return new jQuery(document)[ jQuery.fn.ready ? "ready" : "load" ]( a );
// Handle HTML strings
if ( typeof a == "string" ) {
// HANDLE: $(html) -> $(array)
var m = /^[^<]*(<(.|\s)+>)[^>]*$/.exec(a);
if ( m )
a = jQuery.clean( [ m[1] ] );
// HANDLE: $(expr)
else
return new jQuery( c ).find( a );
}
return this.setArray(
// HANDLE: $(array)
a.constructor == Array && a ||
// HANDLE: $(arraylike)
// Watch for when an array-like object is passed as the selector
(a.jquery || a.length && a != window && !a.nodeType && a[0] != undefined && a[0].nodeType) && jQuery.makeArray( a ) ||
// HANDLE: $(*)
[ a ] );
};
// Map over the $ in case of overwrite
if ( typeof $ != "undefined" )
jQuery._$ = $;
// Map the jQuery namespace to the '$' one
var $ = jQuery;
jQuery.fn = jQuery.prototype = {
jquery: "1.1.2",
size: function() {
return this.length;
},
length: 0,
get: function( num ) {
return num == undefined ?
// Return a 'clean' array
jQuery.makeArray( this ) :
// Return just the object
this[num];
},
pushStack: function( a ) {
var ret = jQuery(a);
ret.prevObject = this;
return ret;
},
setArray: function( a ) {
this.length = 0;
[].push.apply( this, a );
return this;
},
each: function( fn, args ) {
return jQuery.each( this, fn, args );
},
index: function( obj ) {
var pos = -1;
this.each(function(i){
if ( this == obj ) pos = i;
});
return pos;
},
attr: function( key, value, type ) {
var obj = key;
// Look for the case where we're accessing a style value
if ( key.constructor == String )
if ( value == undefined )
return this.length && jQuery[ type || "attr" ]( this[0], key ) || undefined;
else {
obj = {};
obj[ key ] = value;
}
// Check to see if we're setting style values
return this.each(function(index){
// Set all the styles
for ( var prop in obj )
jQuery.attr(
type ? this.style : this,
prop, jQuery.prop(this, obj[prop], type, index, prop)
);
});
},
css: function( key, value ) {
return this.attr( key, value, "curCSS" );
},
text: function(e) {
if ( typeof e == "string" )
return this.empty().append( document.createTextNode( e ) );
var t = "";
jQuery.each( e || this, function(){
jQuery.each( this.childNodes, function(){
if ( this.nodeType != 8 )
t += this.nodeType != 1 ?
this.nodeValue : jQuery.fn.text([ this ]);
});
});
return t;
},
wrap: function() {
// The elements to wrap the target around
var a = jQuery.clean(arguments);
// Wrap each of the matched elements individually
return this.each(function(){
// Clone the structure that we're using to wrap
var b = a[0].cloneNode(true);
// Insert it before the element to be wrapped
this.parentNode.insertBefore( b, this );
// Find the deepest point in the wrap structure
while ( b.firstChild )
b = b.firstChild;
// Move the matched element to within the wrap structure
b.appendChild( this );
});
},
append: function() {
return this.domManip(arguments, true, 1, function(a){
this.appendChild( a );
});
},
prepend: function() {
return this.domManip(arguments, true, -1, function(a){
this.insertBefore( a, this.firstChild );
});
},
before: function() {
return this.domManip(arguments, false, 1, function(a){
this.parentNode.insertBefore( a, this );
});
},
after: function() {
return this.domManip(arguments, false, -1, function(a){
this.parentNode.insertBefore( a, this.nextSibling );
});
},
end: function() {
return this.prevObject || jQuery([]);
},
find: function(t) {
return this.pushStack( jQuery.map( this, function(a){
return jQuery.find(t,a);
}), t );
},
clone: function(deep) {
return this.pushStack( jQuery.map( this, function(a){
var a = a.cloneNode( deep != undefined ? deep : true );
a.$events = null; // drop $events expando to avoid firing incorrect events
return a;
}) );
},
filter: function(t) {
return this.pushStack(
jQuery.isFunction( t ) &&
jQuery.grep(this, function(el, index){
return t.apply(el, [index])
}) ||
jQuery.multiFilter(t,this) );
},
not: function(t) {
return this.pushStack(
t.constructor == String &&
jQuery.multiFilter(t, this, true) ||
jQuery.grep(this, function(a) {
return ( t.constructor == Array || t.jquery )
? jQuery.inArray( a, t ) < 0
: a != t;
})
);
},
add: function(t) {
return this.pushStack( jQuery.merge(
this.get(),
t.constructor == String ?
jQuery(t).get() :
t.length != undefined && (!t.nodeName || t.nodeName == "FORM") ?
t : [t] )
);
},
is: function(expr) {
return expr ? jQuery.filter(expr,this).r.length > 0 : false;
},
val: function( val ) {
return val == undefined ?
( this.length ? this[0].value : null ) :
this.attr( "value", val );
},
html: function( val ) {
return val == undefined ?
( this.length ? this[0].innerHTML : null ) :
this.empty().append( val );
},
domManip: function(args, table, dir, fn){
var clone = this.length > 1;
var a = jQuery.clean(args);
if ( dir < 0 )
a.reverse();
return this.each(function(){
var obj = this;
if ( table && jQuery.nodeName(this, "table") && jQuery.nodeName(a[0], "tr") )
obj = this.getElementsByTagName("tbody")[0] || this.appendChild(document.createElement("tbody"));
jQuery.each( a, function(){
fn.apply( obj, [ clone ? this.cloneNode(true) : this ] );
});
});
}
};
jQuery.extend = jQuery.fn.extend = function() {
// copy reference to target object
var target = arguments[0],
a = 1;
// extend jQuery itself if only one argument is passed
if ( arguments.length == 1 ) {
target = this;
a = 0;
}
var prop;
while (prop = arguments[a++])
// Extend the base object
for ( var i in prop ) target[i] = prop[i];
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function() {
if ( jQuery._$ )
$ = jQuery._$;
return jQuery;
},
// This may seem like some crazy code, but trust me when I say that this
// is the only cross-browser way to do this. --John
isFunction: function( fn ) {
return !!fn && typeof fn != "string" && !fn.nodeName &&
typeof fn[0] == "undefined" && /function/i.test( fn + "" );
},
// check if an element is in a XML document
isXMLDoc: function(elem) {
return elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
},
// args is for internal usage only
each: function( obj, fn, args ) {
if ( obj.length == undefined )
for ( var i in obj )
fn.apply( obj[i], args || [i, obj[i]] );
else
for ( var i = 0, ol = obj.length; i < ol; i++ )
if ( fn.apply( obj[i], args || [i, obj[i]] ) === false ) break;
return obj;
},
prop: function(elem, value, type, index, prop){
// Handle executable functions
if ( jQuery.isFunction( value ) )
value = value.call( elem, [index] );
// exclude the following css properties to add px
var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i;
// Handle passing in a number to a CSS property
return value && value.constructor == Number && type == "curCSS" && !exclude.test(prop) ?
value + "px" :
value;
},
className: {
// internal only, use addClass("class")
add: function( elem, c ){
jQuery.each( c.split(/\s+/), function(i, cur){
if ( !jQuery.className.has( elem.className, cur ) )
elem.className += ( elem.className ? " " : "" ) + cur;
});
},
// internal only, use removeClass("class")
remove: function( elem, c ){
elem.className = c ?
jQuery.grep( elem.className.split(/\s+/), function(cur){
return !jQuery.className.has( c, cur );
}).join(" ") : "";
},
// internal only, use is(".class")
has: function( t, c ) {
t = t.className || t;
// escape regex characters
c = c.replace(/([\.\\\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
return t && new RegExp("(^|\\s)" + c + "(\\s|$)").test( t );
}
},
swap: function(e,o,f) {
for ( var i in o ) {
e.style["old"+i] = e.style[i];
e.style[i] = o[i];
}
f.apply( e, [] );
for ( var i in o )
e.style[i] = e.style["old"+i];
},
css: function(e,p) {
if ( p == "height" || p == "width" ) {
var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"];
jQuery.each( d, function(){
old["padding" + this] = 0;
old["border" + this + "Width"] = 0;
});
jQuery.swap( e, old, function() {
if (jQuery.css(e,"display") != "none") {
oHeight = e.offsetHeight;
oWidth = e.offsetWidth;
} else {
e = jQuery(e.cloneNode(true))
.find(":radio").removeAttr("checked").end()
.css({
visibility: "hidden", position: "absolute", display: "block", right: "0", left: "0"
}).appendTo(e.parentNode)[0];
var parPos = jQuery.css(e.parentNode,"position");
if ( parPos == "" || parPos == "static" )
e.parentNode.style.position = "relative";
oHeight = e.clientHeight;
oWidth = e.clientWidth;
if ( parPos == "" || parPos == "static" )
e.parentNode.style.position = "static";
e.parentNode.removeChild(e);
}
});
return p == "height" ? oHeight : oWidth;
}
return jQuery.curCSS( e, p );
},
curCSS: function(elem, prop, force) {
var ret;
if (prop == "opacity" && jQuery.browser.msie)
return jQuery.attr(elem.style, "opacity");
if (prop == "float" || prop == "cssFloat")
prop = jQuery.browser.msie ? "styleFloat" : "cssFloat";
if (!force && elem.style[prop])
ret = elem.style[prop];
else if (document.defaultView && document.defaultView.getComputedStyle) {
if (prop == "cssFloat" || prop == "styleFloat")
prop = "float";
prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase();
var cur = document.defaultView.getComputedStyle(elem, null);
if ( cur )
ret = cur.getPropertyValue(prop);
else if ( prop == "display" )
ret = "none";
else
jQuery.swap(elem, { display: "block" }, function() {
var c = document.defaultView.getComputedStyle(this, "");
ret = c && c.getPropertyValue(prop) || "";
});
} else if (elem.currentStyle) {
var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();});
ret = elem.currentStyle[prop] || elem.currentStyle[newProp];
}
return ret;
},
clean: function(a) {
var r = [];
jQuery.each( a, function(i,arg){
if ( !arg ) return;
if ( arg.constructor == Number )
arg = arg.toString();
// Convert html string into DOM nodes
if ( typeof arg == "string" ) {
// Trim whitespace, otherwise indexOf won't work as expected
var s = jQuery.trim(arg), div = document.createElement("div"), tb = [];
var wrap =
// option or optgroup
!s.indexOf("<opt") &&
[1, "<select>", "</select>"] ||
(!s.indexOf("<thead") || !s.indexOf("<tbody") || !s.indexOf("<tfoot")) &&
[1, "<table>", "</table>"] ||
!s.indexOf("<tr") &&
[2, "<table><tbody>", "</tbody></table>"] ||
// <thead> matched above
(!s.indexOf("<td") || !s.indexOf("<th")) &&
[3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
[0,"",""];
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + s + wrap[2];
// Move to the right depth
while ( wrap[0]-- )
div = div.firstChild;
// Remove IE's autoinserted <tbody> from table fragments
if ( jQuery.browser.msie ) {
// String was a <table>, *may* have spurious <tbody>
if ( !s.indexOf("<table") && s.indexOf("<tbody") < 0 )
tb = div.firstChild && div.firstChild.childNodes;
// String was a bare <thead> or <tfoot>
else if ( wrap[1] == "<table>" && s.indexOf("<tbody") < 0 )
tb = div.childNodes;
for ( var n = tb.length-1; n >= 0 ; --n )
if ( jQuery.nodeName(tb[n], "tbody") && !tb[n].childNodes.length )
tb[n].parentNode.removeChild(tb[n]);
}
arg = [];
for (var i=0, l=div.childNodes.length; i<l; i++)
arg.push(div.childNodes[i]);
}
if ( arg.length === 0 && !jQuery.nodeName(arg, "form") )
return;
if ( arg[0] == undefined || jQuery.nodeName(arg, "form") )
r.push( arg );
else
r = jQuery.merge( r, arg );
});
return r;
},
attr: function(elem, name, value){
var fix = jQuery.isXMLDoc(elem) ? {} : {
"for": "htmlFor",
"class": "className",
"float": jQuery.browser.msie ? "styleFloat" : "cssFloat",
cssFloat: jQuery.browser.msie ? "styleFloat" : "cssFloat",
innerHTML: "innerHTML",
className: "className",
value: "value",
disabled: "disabled",
checked: "checked",
readonly: "readOnly",
selected: "selected"
};
// IE actually uses filters for opacity ... elem is actually elem.style
if ( name == "opacity" && jQuery.browser.msie && value != undefined ) {
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
elem.zoom = 1;
// Set the alpha filter to set the opacity
return elem.filter = elem.filter.replace(/alpha\([^\)]*\)/gi,"") +
( value == 1 ? "" : "alpha(opacity=" + value * 100 + ")" );
} else if ( name == "opacity" && jQuery.browser.msie )
return elem.filter ?
parseFloat( elem.filter.match(/alpha\(opacity=(.*)\)/)[1] ) / 100 : 1;
// Mozilla doesn't play well with opacity 1
if ( name == "opacity" && jQuery.browser.mozilla && value == 1 )
value = 0.9999;
// Certain attributes only work when accessed via the old DOM 0 way
if ( fix[name] ) {
if ( value != undefined ) elem[fix[name]] = value;
return elem[fix[name]];
} else if ( value == undefined && jQuery.browser.msie && jQuery.nodeName(elem, "form") && (name == "action" || name == "method") )
return elem.getAttributeNode(name).nodeValue;
// IE elem.getAttribute passes even for style
else if ( elem.tagName ) {
if ( value != undefined ) elem.setAttribute( name, value );
if ( jQuery.browser.msie && /href|src/.test(name) && !jQuery.isXMLDoc(elem) )
return elem.getAttribute( name, 2 );
return elem.getAttribute( name );
// elem is actually elem.style ... set the style
} else {
name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();});
if ( value != undefined ) elem[name] = value;
return elem[name];
}
},
trim: function(t){
return t.replace(/^\s+|\s+$/g, "");
},
makeArray: function( a ) {
var r = [];
if ( a.constructor != Array )
for ( var i = 0, al = a.length; i < al; i++ )
r.push( a[i] );
else
r = a.slice( 0 );
return r;
},
inArray: function( b, a ) {
for ( var i = 0, al = a.length; i < al; i++ )
if ( a[i] == b )
return i;
return -1;
},
merge: function(first, second) {
var r = [].slice.call( first, 0 );
// Now check for duplicates between the two arrays
// and only add the unique items
for ( var i = 0, sl = second.length; i < sl; i++ )
// Check for duplicates
if ( jQuery.inArray( second[i], r ) == -1 )
// The item is unique, add it
first.push( second[i] );
return first;
},
grep: function(elems, fn, inv) {
// If a string is passed in for the function, make a function
// for it (a handy shortcut)
if ( typeof fn == "string" )
fn = new Function("a","i","return " + fn);
var result = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, el = elems.length; i < el; i++ )
if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) )
result.push( elems[i] );
return result;
},
map: function(elems, fn) {
// If a string is passed in for the function, make a function
// for it (a handy shortcut)
if ( typeof fn == "string" )
fn = new Function("a","return " + fn);
var result = [], r = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, el = elems.length; i < el; i++ ) {
var val = fn(elems[i],i);
if ( val !== null && val != undefined ) {
if ( val.constructor != Array ) val = [val];
result = result.concat( val );
}
}
var r = result.length ? [ result[0] ] : [];
check: for ( var i = 1, rl = result.length; i < rl; i++ ) {
for ( var j = 0; j < i; j++ )
if ( result[i] == r[j] )
continue check;
r.push( result[i] );
}
return r;
}
});
/*
* Whether the W3C compliant box model is being used.
*
* @property
* @name $.boxModel
* @type Boolean
* @cat JavaScript
*/
new function() {
var b = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
jQuery.browser = {
safari: /webkit/.test(b),
opera: /opera/.test(b),
msie: /msie/.test(b) && !/opera/.test(b),
mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)
};
// Check to see if the W3C box model is being used
jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat";
};
jQuery.each({
parent: "a.parentNode",
parents: "jQuery.parents(a)",
next: "jQuery.nth(a,2,'nextSibling')",
prev: "jQuery.nth(a,2,'previousSibling')",
siblings: "jQuery.sibling(a.parentNode.firstChild,a)",
children: "jQuery.sibling(a.firstChild)"
}, function(i,n){
jQuery.fn[ i ] = function(a) {
var ret = jQuery.map(this,n);
if ( a && typeof a == "string" )
ret = jQuery.multiFilter(a,ret);
return this.pushStack( ret );
};
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after"
}, function(i,n){
jQuery.fn[ i ] = function(){
var a = arguments;
return this.each(function(){
for ( var j = 0, al = a.length; j < al; j++ )
jQuery(a[j])[n]( this );
});
};
});
jQuery.each( {
removeAttr: function( key ) {
jQuery.attr( this, key, "" );
this.removeAttribute( key );
},
addClass: function(c){
jQuery.className.add(this,c);
},
removeClass: function(c){
jQuery.className.remove(this,c);
},
toggleClass: function( c ){
jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this, c);
},
remove: function(a){
if ( !a || jQuery.filter( a, [this] ).r.length )
this.parentNode.removeChild( this );
},
empty: function() {
while ( this.firstChild )
this.removeChild( this.firstChild );
}
}, function(i,n){
jQuery.fn[ i ] = function() {
return this.each( n, arguments );
};
});
jQuery.each( [ "eq", "lt", "gt", "contains" ], function(i,n){
jQuery.fn[ n ] = function(num,fn) {
return this.filter( ":" + n + "(" + num + ")", fn );
};
});
jQuery.each( [ "height", "width" ], function(i,n){
jQuery.fn[ n ] = function(h) {
return h == undefined ?
( this.length ? jQuery.css( this[0], n ) : null ) :
this.css( n, h.constructor == String ? h : h + "px" );
};
});
jQuery.extend({
expr: {
"": "m[2]=='*'||jQuery.nodeName(a,m[2])",
"#": "a.getAttribute('id')==m[2]",
":": {
// Position Checks
lt: "i<m[3]-0",
gt: "i>m[3]-0",
nth: "m[3]-0==i",
eq: "m[3]-0==i",
first: "i==0",
last: "i==r.length-1",
even: "i%2==0",
odd: "i%2",
// Child Checks
"nth-child": "jQuery.nth(a.parentNode.firstChild,m[3],'nextSibling',a)==a",
"first-child": "jQuery.nth(a.parentNode.firstChild,1,'nextSibling')==a",
"last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
"only-child": "jQuery.sibling(a.parentNode.firstChild).length==1",
// Parent Checks
parent: "a.firstChild",
empty: "!a.firstChild",
// Text Check
contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0",
// Visibility
visible: 'a.type!="hidden"&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
hidden: 'a.type=="hidden"||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',
// Form attributes
enabled: "!a.disabled",
disabled: "a.disabled",
checked: "a.checked",
selected: "a.selected||jQuery.attr(a,'selected')",
// Form elements
text: "a.type=='text'",
radio: "a.type=='radio'",
checkbox: "a.type=='checkbox'",
file: "a.type=='file'",
password: "a.type=='password'",
submit: "a.type=='submit'",
image: "a.type=='image'",
reset: "a.type=='reset'",
button: 'a.type=="button"||jQuery.nodeName(a,"button")',
input: "/input|select|textarea|button/i.test(a.nodeName)"
},
".": "jQuery.className.has(a,m[2])",
"@": {
"=": "z==m[4]",
"!=": "z!=m[4]",
"^=": "z&&!z.indexOf(m[4])",
"$=": "z&&z.substr(z.length - m[4].length,m[4].length)==m[4]",
"*=": "z&&z.indexOf(m[4])>=0",
"": "z",
_resort: function(m){
return ["", m[1], m[3], m[2], m[5]];
},
_prefix: "z=a[m[3]];if(!z||/href|src/.test(m[3]))z=jQuery.attr(a,m[3]);"
},
"[": "jQuery.find(m[2],a).length"
},
// The regular expressions that power the parsing engine
parse: [
// Match: [@value='test'], [@foo]
/^\[ *(@)([a-z0-9_-]*) *([!*$^=]*) *('?"?)(.*?)\4 *\]/i,
// Match: [div], [div p]
/^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,
// Match: :contains('foo')
/^(:)([a-z0-9_-]*)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/i,
// Match: :even, :last-chlid
/^([:.#]*)([a-z0-9_*-]*)/i
],
token: [
/^(\/?\.\.)/, "a.parentNode",
/^(>|\/)/, "jQuery.sibling(a.firstChild)",
/^(\+)/, "jQuery.nth(a,2,'nextSibling')",
/^(~)/, function(a){
var s = jQuery.sibling(a.parentNode.firstChild);
return s.slice(jQuery.inArray(a,s) + 1);
}
],
multiFilter: function( expr, elems, not ) {
var old, cur = [];
while ( expr && expr != old ) {
old = expr;
var f = jQuery.filter( expr, elems, not );
expr = f.t.replace(/^\s*,\s*/, "" );
cur = not ? elems = f.r : jQuery.merge( cur, f.r );
}
return cur;
},
find: function( t, context ) {
// Quickly handle non-string expressions
if ( typeof t != "string" )
return [ t ];
// Make sure that the context is a DOM Element
if ( context && !context.nodeType )
context = null;
// Set the correct context (if none is provided)
context = context || document;
// Handle the common XPath // expression
if ( !t.indexOf("//") ) {
context = context.documentElement;
t = t.substr(2,t.length);
// And the / root expression
} else if ( !t.indexOf("/") ) {
context = context.documentElement;
t = t.substr(1,t.length);
if ( t.indexOf("/") >= 1 )
t = t.substr(t.indexOf("/"),t.length);
}
// Initialize the search
var ret = [context], done = [], last = null;
// Continue while a selector expression exists, and while
// we're no longer looping upon ourselves
while ( t && last != t ) {
var r = [];
last = t;
t = jQuery.trim(t).replace( /^\/\//i, "" );
var foundToken = false;
// An attempt at speeding up child selectors that
// point to a specific element tag
var re = /^[\/>]\s*([a-z0-9*-]+)/i;
var m = re.exec(t);
if ( m ) {
// Perform our own iteration and filter
jQuery.each( ret, function(){
for ( var c = this.firstChild; c; c = c.nextSibling )
if ( c.nodeType == 1 && ( jQuery.nodeName(c, m[1]) || m[1] == "*" ) )
r.push( c );
});
ret = r;
t = t.replace( re, "" );
if ( t.indexOf(" ") == 0 ) continue;
foundToken = true;
} else {
// Look for pre-defined expression tokens
for ( var i = 0; i < jQuery.token.length; i += 2 ) {
// Attempt to match each, individual, token in
// the specified order
var re = jQuery.token[i];
var m = re.exec(t);
// If the token match was found
if ( m ) {
// Map it against the token's handler
r = ret = jQuery.map( ret, jQuery.isFunction( jQuery.token[i+1] ) ?
jQuery.token[i+1] :
function(a){ return eval(jQuery.token[i+1]); });
// And remove the token
t = jQuery.trim( t.replace( re, "" ) );
foundToken = true;
break;
}
}
}
// See if there's still an expression, and that we haven't already
// matched a token
if ( t && !foundToken ) {
// Handle multiple expressions
if ( !t.indexOf(",") ) {
// Clean the result set
if ( ret[0] == context ) ret.shift();
// Merge the result sets
jQuery.merge( done, ret );
// Reset the context
r = ret = [context];
// Touch up the selector string
t = " " + t.substr(1,t.length);
} else {
// Optomize for the case nodeName#idName
var re2 = /^([a-z0-9_-]+)(#)([a-z0-9\\*_-]*)/i;
var m = re2.exec(t);
// Re-organize the results, so that they're consistent
if ( m ) {
m = [ 0, m[2], m[3], m[1] ];
} else {
// Otherwise, do a traditional filter check for
// ID, class, and element selectors
re2 = /^([#.]?)([a-z0-9\\*_-]*)/i;
m = re2.exec(t);
}
// Try to do a global search by ID, where we can
if ( m[1] == "#" && ret[ret.length-1].getElementById ) {
// Optimization for HTML document case
var oid = ret[ret.length-1].getElementById(m[2]);
// Do a quick check for the existence of the actual ID attribute
// to avoid selecting by the name attribute in IE
if ( jQuery.browser.msie && oid && oid.id != m[2] )
oid = jQuery('[@id="'+m[2]+'"]', ret[ret.length-1])[0];
// Do a quick check for node name (where applicable) so
// that div#foo searches will be really fast
ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
} else {
// Pre-compile a regular expression to handle class searches
if ( m[1] == "." )
var rec = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
// We need to find all descendant elements, it is more
// efficient to use getAll() when we are already further down
// the tree - we try to recognize that here
jQuery.each( ret, function(){
// Grab the tag name being searched for
var tag = m[1] != "" || m[0] == "" ? "*" : m[2];
// Handle IE7 being really dumb about <object>s
if ( jQuery.nodeName(this, "object") && tag == "*" )
tag = "param";
jQuery.merge( r,
m[1] != "" && ret.length != 1 ?
jQuery.getAll( this, [], m[1], m[2], rec ) :
this.getElementsByTagName( tag )
);
});
// It's faster to filter by class and be done with it
if ( m[1] == "." && ret.length == 1 )
r = jQuery.grep( r, function(e) {
return rec.test(e.className);
});
// Same with ID filtering
if ( m[1] == "#" && ret.length == 1 ) {
// Remember, then wipe out, the result set
var tmp = r;
r = [];
// Then try to find the element with the ID
jQuery.each( tmp, function(){
if ( this.getAttribute("id") == m[2] ) {
r = [ this ];
return false;
}
});
}
ret = r;
}
t = t.replace( re2, "" );
}
}
// If a selector string still exists
if ( t ) {
// Attempt to filter it
var val = jQuery.filter(t,r);
ret = r = val.r;
t = jQuery.trim(val.t);
}
}
// Remove the root context
if ( ret && ret[0] == context ) ret.shift();
// And combine the results
jQuery.merge( done, ret );
return done;
},
filter: function(t,r,not) {
// Look for common filter expressions
while ( t && /^[a-z[({<*:.#]/i.test(t) ) {
var p = jQuery.parse, m;
jQuery.each( p, function(i,re){
// Look for, and replace, string-like sequences
// and finally build a regexp out of it
m = re.exec( t );
if ( m ) {
// Remove what we just matched
t = t.substring( m[0].length );
// Re-organize the first match
if ( jQuery.expr[ m[1] ]._resort )
m = jQuery.expr[ m[1] ]._resort( m );
return false;
}
});
// :not() is a special case that can be optimized by
// keeping it out of the expression list
if ( m[1] == ":" && m[2] == "not" )
r = jQuery.filter(m[3], r, true).r;
// Handle classes as a special case (this will help to
// improve the speed, as the regexp will only be compiled once)
else if ( m[1] == "." ) {
var re = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
r = jQuery.grep( r, function(e){
return re.test(e.className || "");
}, not);
// Otherwise, find the expression to execute
} else {
var f = jQuery.expr[m[1]];
if ( typeof f != "string" )
f = jQuery.expr[m[1]][m[2]];
// Build a custom macro to enclose it
eval("f = function(a,i){" +
( jQuery.expr[ m[1] ]._prefix || "" ) +
"return " + f + "}");
// Execute it against the current filter
r = jQuery.grep( r, f, not );
}
}
// Return an array of filtered elements (r)
// and the modified expression string (t)
return { r: r, t: t };
},
getAll: function( o, r, token, name, re ) {
for ( var s = o.firstChild; s; s = s.nextSibling )
if ( s.nodeType == 1 ) {
var add = true;
if ( token == "." )
add = s.className && re.test(s.className);
else if ( token == "#" )
add = s.getAttribute("id") == name;
if ( add )
r.push( s );
if ( token == "#" && r.length ) break;
if ( s.firstChild )
jQuery.getAll( s, r, token, name, re );
}
return r;
},
parents: function( elem ){
var matched = [];
var cur = elem.parentNode;
while ( cur && cur != document ) {
matched.push( cur );
cur = cur.parentNode;
}
return matched;
},
nth: function(cur,result,dir,elem){
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType == 1 ) num++;
if ( num == result || result == "even" && num % 2 == 0 && num > 1 && cur == elem ||
result == "odd" && num % 2 == 1 && cur == elem ) return cur;
}
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType == 1 && (!elem || n != elem) )
r.push( n );
}
return r;
}
});
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code orignated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function(element, type, handler, data) {
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( jQuery.browser.msie && element.setInterval != undefined )
element = window;
// if data is passed, bind to handler
if( data )
handler.data = data;
// Make sure that the function being executed has a unique ID
if ( !handler.guid )
handler.guid = this.guid++;
// Init the element's event structure
if (!element.$events)
element.$events = {};
// Get the current list of functions bound to this event
var handlers = element.$events[type];
// If it hasn't been initialized yet
if (!handlers) {
// Init the event handler queue
handlers = element.$events[type] = {};
// Remember an existing handler, if it's already there
if (element["on" + type])
handlers[0] = element["on" + type];
}
// Add the function to the element's handler list
handlers[handler.guid] = handler;
// And bind the global event handler to the element
element["on" + type] = this.handle;
// Remember the function in a global list (for triggering)
if (!this.global[type])
this.global[type] = [];
this.global[type].push( element );
},
guid: 1,
global: {},
// Detach an event or set of events from an element
remove: function(element, type, handler) {
if (element.$events) {
var i,j,k;
if ( type && type.type ) { // type is actually an event object here
handler = type.handler;
type = type.type;
}
if (type && element.$events[type])
// remove the given handler for the given type
if ( handler )
delete element.$events[type][handler.guid];
// remove all handlers for the given type
else
for ( i in element.$events[type] )
delete element.$events[type][i];
// remove all handlers
else
for ( j in element.$events )
this.remove( element, j );
// remove event handler if no more handlers exist
for ( k in element.$events[type] )
if (k) {
k = true;
break;
}
if (!k) element["on" + type] = null;
}
},
trigger: function(type, data, element) {
// Clone the incoming data, if any
data = jQuery.makeArray(data || []);
// Handle a global trigger
if ( !element )
jQuery.each( this.global[type] || [], function(){
jQuery.event.trigger( type, data, this );
});
// Handle triggering a single element
else {
var handler = element["on" + type ], val,
fn = jQuery.isFunction( element[ type ] );
if ( handler ) {
// Pass along a fake event
data.unshift( this.fix({ type: type, target: element }) );
// Trigger the event
if ( (val = handler.apply( element, data )) !== false )
this.triggered = true;
}
if ( fn && val !== false )
element[ type ]();
this.triggered = false;
}
},
handle: function(event) {
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
// Empty object is for triggered events with no data
event = jQuery.event.fix( event || window.event || {} );
// returned undefined or false
var returnValue;
var c = this.$events[event.type];
var args = [].slice.call( arguments, 1 );
args.unshift( event );
for ( var j in c ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
args[0].handler = c[j];
args[0].data = c[j].data;
if ( c[j].apply( this, args ) === false ) {
event.preventDefault();
event.stopPropagation();
returnValue = false;
}
}
// Clean up added properties in IE to prevent memory leak
if (jQuery.browser.msie) event.target = event.preventDefault = event.stopPropagation = event.handler = event.data = null;
return returnValue;
},
fix: function(event) {
// Fix target property, if necessary
if ( !event.target && event.srcElement )
event.target = event.srcElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == undefined && event.clientX != undefined ) {
var e = document.documentElement, b = document.body;
event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
}
// check if target is a textnode (safari)
if (jQuery.browser.safari && event.target.nodeType == 3) {
// store a copy of the original event object
// and clone because target is read only
var originalEvent = event;
event = jQuery.extend({}, originalEvent);
// get parentnode from textnode
event.target = originalEvent.target.parentNode;
// add preventDefault and stopPropagation since
// they will not work on the clone
event.preventDefault = function() {
return originalEvent.preventDefault();
};
event.stopPropagation = function() {
return originalEvent.stopPropagation();
};
}
// fix preventDefault and stopPropagation
if (!event.preventDefault)
event.preventDefault = function() {
this.returnValue = false;
};
if (!event.stopPropagation)
event.stopPropagation = function() {
this.cancelBubble = true;
};
return event;
}
};
jQuery.fn.extend({
bind: function( type, data, fn ) {
return this.each(function(){
jQuery.event.add( this, type, fn || data, data );
});
},
one: function( type, data, fn ) {
return this.each(function(){
jQuery.event.add( this, type, function(event) {
jQuery(this).unbind(event);
return (fn || data).apply( this, arguments);
}, data);
});
},
unbind: function( type, fn ) {
return this.each(function(){
jQuery.event.remove( this, type, fn );
});
},
trigger: function( type, data ) {
return this.each(function(){
jQuery.event.trigger( type, data, this );
});
},
toggle: function() {
// Save reference to arguments for access in closure
var a = arguments;
return this.click(function(e) {
// Figure out which function to execute
this.lastToggle = this.lastToggle == 0 ? 1 : 0;
// Make sure that clicks stop
e.preventDefault();
// and execute the function
return a[this.lastToggle].apply( this, [e] ) || false;
});
},
hover: function(f,g) {
// A private function for handling mouse 'hovering'
function handleHover(e) {
// Check if mouse(over|out) are still within the same parent element
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
// Traverse up the tree
while ( p && p != this ) try { p = p.parentNode } catch(e) { p = this; };
// If we actually just moused on to a sub-element, ignore it
if ( p == this ) return false;
// Execute the right function
return (e.type == "mouseover" ? f : g).apply(this, [e]);
}
// Bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
},
ready: function(f) {
// If the DOM is already ready
if ( jQuery.isReady )
// Execute the function immediately
f.apply( document, [jQuery] );
// Otherwise, remember the function for later
else {
// Add the function to the wait list
jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
}
return this;
}
});
jQuery.extend({
/*
* All the code that makes DOM Ready work nicely.
*/
isReady: false,
readyList: [],
// Handle when the DOM is ready
ready: function() {
// Make sure that the DOM is not already loaded
if ( !jQuery.isReady ) {
// Remember that the DOM is ready
jQuery.isReady = true;
// If there are functions bound, to execute
if ( jQuery.readyList ) {
// Execute all of them
jQuery.each( jQuery.readyList, function(){
this.apply( document );
});
// Reset the list of functions
jQuery.readyList = null;
}
// Remove event lisenter to avoid memory leak
if ( jQuery.browser.mozilla || jQuery.browser.opera )
document.removeEventListener( "DOMContentLoaded", jQuery.ready, false );
}
}
});
new function(){
jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
"mousedown,mouseup,mousemove,mouseover,mouseout,change,select," +
"submit,keydown,keypress,keyup,error").split(","), function(i,o){
// Handle event binding
jQuery.fn[o] = function(f){
return f ? this.bind(o, f) : this.trigger(o);
};
});
// If Mozilla is used
if ( jQuery.browser.mozilla || jQuery.browser.opera )
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
// If IE is used, use the excellent hack by Matthias Miller
// http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
else if ( jQuery.browser.msie ) {
// Only works if you document.write() it
document.write("<scr" + "ipt id=__ie_init defer=true " +
"src=//:><\/script>");
// Use the defer script hack
var script = document.getElementById("__ie_init");
// script does not exist if jQuery is loaded dynamically
if ( script )
script.onreadystatechange = function() {
if ( this.readyState != "complete" ) return;
this.parentNode.removeChild( this );
jQuery.ready();
};
// Clear from memory
script = null;
// If Safari is used
} else if ( jQuery.browser.safari )
// Continually check to see if the document.readyState is valid
jQuery.safariTimer = setInterval(function(){
// loaded and complete are both valid states
if ( document.readyState == "loaded" ||
document.readyState == "complete" ) {
// If either one are found, remove the timer
clearInterval( jQuery.safariTimer );
jQuery.safariTimer = null;
// and execute any waiting functions
jQuery.ready();
}
}, 10);
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
};
// Clean up after IE to avoid memory leaks
if (jQuery.browser.msie)
jQuery(window).one("unload", function() {
var global = jQuery.event.global;
for ( var type in global ) {
var els = global[type], i = els.length;
if ( i && type != 'unload' )
do
jQuery.event.remove(els[i-1], type);
while (--i);
}
});
jQuery.fn.extend({
loadIfModified: function( url, params, callback ) {
this.load( url, params, callback, 1 );
},
load: function( url, params, callback, ifModified ) {
if ( jQuery.isFunction( url ) )
return this.bind("load", url);
callback = callback || function(){};
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params )
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else {
params = jQuery.param( params );
type = "POST";
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
data: params,
ifModified: ifModified,
complete: function(res, status){
if ( status == "success" || !ifModified && status == "notmodified" )
// Inject the HTML into all the matched elements
self.attr("innerHTML", res.responseText)
// Execute all the scripts inside of the newly-injected HTML
.evalScripts()
// Execute callback
.each( callback, [res.responseText, status, res] );
else
callback.apply( self, [res.responseText, status, res] );
}
});
return this;
},
serialize: function() {
return jQuery.param( this );
},
evalScripts: function() {
return this.find("script").each(function(){
if ( this.src )
jQuery.getScript( this.src );
else
jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
}).end();
}
});
// If IE is used, create a wrapper for the XMLHttpRequest object
if ( !window.XMLHttpRequest )
XMLHttpRequest = function(){
return new ActiveXObject("Microsoft.XMLHTTP");
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
jQuery.fn[o] = function(f){
return this.bind(o, f);
};
});
jQuery.extend({
get: function( url, data, callback, type, ifModified ) {
// shift arguments if data argument was ommited
if ( jQuery.isFunction( data ) ) {
callback = data;
data = null;
}
return jQuery.ajax({
url: url,
data: data,
success: callback,
dataType: type,
ifModified: ifModified
});
},
getIfModified: function( url, data, callback, type ) {
return jQuery.get(url, data, callback, type, 1);
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
// timeout (ms)
//timeout: 0,
ajaxTimeout: function( timeout ) {
jQuery.ajaxSettings.timeout = timeout;
},
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
global: true,
type: "GET",
timeout: 0,
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
data: null
},
// Last-Modified header cache for next request
lastModified: {},
ajax: function( s ) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
// if data available
if ( s.data ) {
// convert data if not already a string
if (s.processData && typeof s.data != "string")
s.data = jQuery.param(s.data);
// append data to url for get requests
if( s.type.toLowerCase() == "get" ) {
// "?" + data or "&" + data (in case there are already params)
s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
// IE likes to send both get and post data, prevent this
s.data = null;
}
}
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
jQuery.event.trigger( "ajaxStart" );
var requestDone = false;
// Create the request object
var xml = new XMLHttpRequest();
// Open the socket
xml.open(s.type, s.url, s.async);
// Set the correct header, if data is being sent
if ( s.data )
xml.setRequestHeader("Content-Type", s.contentType);
// Set the If-Modified-Since header, if ifModified mode.
if ( s.ifModified )
xml.setRequestHeader("If-Modified-Since",
jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
// Set header so the called script knows that it's an XMLHttpRequest
xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Make sure the browser sends the right content length
if ( xml.overrideMimeType )
xml.setRequestHeader("Connection", "close");
// Allow custom headers/mimetypes
if( s.beforeSend )
s.beforeSend(xml);
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var onreadystatechange = function(isTimeout){
// The transfer is complete and the data is available, or the request timed out
if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
requestDone = true;
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
var status;
try {
status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" ) {
// Cache Last-Modified header, if ifModified mode.
var modRes;
try {
modRes = xml.getResponseHeader("Last-Modified");
} catch(e) {} // swallow exception thrown by FF if header is not available
if ( s.ifModified && modRes )
jQuery.lastModified[s.url] = modRes;
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.httpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e) {
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
// Stop memory leaks
if(s.async)
xml = null;
}
};
// don't attach the handler to the request, just poll it instead
var ival = setInterval(onreadystatechange, 13);
// Timeout checker
if ( s.timeout > 0 )
setTimeout(function(){
// Check to see if the request is still happening
if ( xml ) {
// Cancel the request
xml.abort();
if( !requestDone )
onreadystatechange( "timeout" );
}
}, s.timeout);
// Send the data
try {
xml.send(s.data);
} catch(e) {
jQuery.handleError(s, xml, null, e);
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async )
onreadystatechange();
// return XMLHttpRequest to allow aborting the request etc.
return xml;
},
handleError: function( s, xml, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) s.error( xml, status, e );
// Fire the global callback
if ( s.global )
jQuery.event.trigger( "ajaxError", [xml, s, e] );
},
// Counter for holding the number of active queries
active: 0,
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( r ) {
try {
return !r.status && location.protocol == "file:" ||
( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
jQuery.browser.safari && r.status == undefined;
} catch(e){}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xml, url ) {
try {
var xmlRes = xml.getResponseHeader("Last-Modified");
// Firefox always returns 200. check Last-Modified date
return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
jQuery.browser.safari && xml.status == undefined;
} catch(e){}
return false;
},
/* Get the data out of an XMLHttpRequest.
* Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
* otherwise return plain text.
* (String) data - The type of data that you're expecting back,
* (e.g. "xml", "html", "script")
*/
httpData: function( r, type ) {
var ct = r.getResponseHeader("content-type");
var data = !type && ct && ct.indexOf("xml") >= 0;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a ) {
var s = [];
// If an array was passed in, assume that it is an array
// of form elements
if ( a.constructor == Array || a.jquery )
// Serialize the form elements
jQuery.each( a, function(){
s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
});
// Otherwise, assume that it's an object of key/value pairs
else
// Serialize the key/values
for ( var j in a )
// If the value is an array then the key names need to be repeated
if ( a[j] && a[j].constructor == Array )
jQuery.each( a[j], function(){
s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
});
else
s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
// Return the resulting serialization
return s.join("&");
},
// evalulates a script in global context
// not reliable for safari
globalEval: function( data ) {
if ( window.execScript )
window.execScript( data );
else if ( jQuery.browser.safari )
// safari doesn't provide a synchronous global eval
window.setTimeout( data, 0 );
else
eval.call( window, data );
}
});
jQuery.fn.extend({
show: function(speed,callback){
var hidden = this.filter(":hidden");
speed ?
hidden.animate({
height: "show", width: "show", opacity: "show"
}, speed, callback) :
hidden.each(function(){
this.style.display = this.oldblock ? this.oldblock : "";
if ( jQuery.css(this,"display") == "none" )
this.style.display = "block";
});
return this;
},
hide: function(speed,callback){
var visible = this.filter(":visible");
speed ?
visible.animate({
height: "hide", width: "hide", opacity: "hide"
}, speed, callback) :
visible.each(function(){
this.oldblock = this.oldblock || jQuery.css(this,"display");
if ( this.oldblock == "none" )
this.oldblock = "block";
this.style.display = "none";
});
return this;
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2 ){
var args = arguments;
return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
this._toggle( fn, fn2 ) :
this.each(function(){
jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]
.apply( jQuery(this), args );
});
},
slideDown: function(speed,callback){
return this.animate({height: "show"}, speed, callback);
},
slideUp: function(speed,callback){
return this.animate({height: "hide"}, speed, callback);
},
slideToggle: function(speed, callback){
return this.each(function(){
var state = jQuery(this).is(":hidden") ? "show" : "hide";
jQuery(this).animate({height: state}, speed, callback);
});
},
fadeIn: function(speed, callback){
return this.animate({opacity: "show"}, speed, callback);
},
fadeOut: function(speed, callback){
return this.animate({opacity: "hide"}, speed, callback);
},
fadeTo: function(speed,to,callback){
return this.animate({opacity: to}, speed, callback);
},
animate: function( prop, speed, easing, callback ) {
return this.queue(function(){
this.curAnim = jQuery.extend({}, prop);
var opt = jQuery.speed(speed, easing, callback);
for ( var p in prop ) {
var e = new jQuery.fx( this, opt, p );
if ( prop[p].constructor == Number )
e.custom( e.cur(), prop[p] );
else
e[ prop[p] ]( prop );
}
});
},
queue: function(type,fn){
if ( !fn ) {
fn = type;
type = "fx";
}
return this.each(function(){
if ( !this.queue )
this.queue = {};
if ( !this.queue[type] )
this.queue[type] = [];
this.queue[type].push( fn );
if ( this.queue[type].length == 1 )
fn.apply(this);
});
}
});
jQuery.extend({
speed: function(speed, easing, fn) {
var opt = speed && speed.constructor == Object ? speed : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && easing.constructor != Function && easing
};
opt.duration = (opt.duration && opt.duration.constructor == Number ?
opt.duration :
{ slow: 600, fast: 200 }[opt.duration]) || 400;
// Queueing
opt.old = opt.complete;
opt.complete = function(){
jQuery.dequeue(this, "fx");
if ( jQuery.isFunction( opt.old ) )
opt.old.apply( this );
};
return opt;
},
easing: {},
queue: {},
dequeue: function(elem,type){
type = type || "fx";
if ( elem.queue && elem.queue[type] ) {
// Remove self
elem.queue[type].shift();
// Get next function
var f = elem.queue[type][0];
if ( f ) f.apply( elem );
}
},
/*
* I originally wrote fx() as a clone of moo.fx and in the process
* of making it small in size the code became illegible to sane
* people. You've been warned.
*/
fx: function( elem, options, prop ){
var z = this;
// The styles
var y = elem.style;
// Store display property
var oldDisplay = jQuery.css(elem, "display");
// Make sure that nothing sneaks out
y.overflow = "hidden";
// Simple function for setting a style value
z.a = function(){
if ( options.step )
options.step.apply( elem, [ z.now ] );
if ( prop == "opacity" )
jQuery.attr(y, "opacity", z.now); // Let attr handle opacity
else if ( parseInt(z.now) ) // My hate for IE will never die
y[prop] = parseInt(z.now) + "px";
y.display = "block"; // Set display property to block for animation
};
// Figure out the maximum number to run to
z.max = function(){
return parseFloat( jQuery.css(elem,prop) );
};
// Get the current size
z.cur = function(){
var r = parseFloat( jQuery.curCSS(elem, prop) );
return r && r > -10000 ? r : z.max();
};
// Start an animation from one number to another
z.custom = function(from,to){
z.startTime = (new Date()).getTime();
z.now = from;
z.a();
z.timer = setInterval(function(){
z.step(from, to);
}, 13);
};
// Simple 'show' function
z.show = function(){
if ( !elem.orig ) elem.orig = {};
// Remember where we started, so that we can go back to it later
elem.orig[prop] = this.cur();
options.show = true;
// Begin the animation
z.custom(0, elem.orig[prop]);
// Stupid IE, look what you made me do
if ( prop != "opacity" )
y[prop] = "1px";
};
// Simple 'hide' function
z.hide = function(){
if ( !elem.orig ) elem.orig = {};
// Remember where we started, so that we can go back to it later
elem.orig[prop] = this.cur();
options.hide = true;
// Begin the animation
z.custom(elem.orig[prop], 0);
};
//Simple 'toggle' function
z.toggle = function() {
if ( !elem.orig ) elem.orig = {};
// Remember where we started, so that we can go back to it later
elem.orig[prop] = this.cur();
if(oldDisplay == "none") {
options.show = true;
// Stupid IE, look what you made me do
if ( prop != "opacity" )
y[prop] = "1px";
// Begin the animation
z.custom(0, elem.orig[prop]);
} else {
options.hide = true;
// Begin the animation
z.custom(elem.orig[prop], 0);
}
};
// Each step of an animation
z.step = function(firstNum, lastNum){
var t = (new Date()).getTime();
if (t > options.duration + z.startTime) {
// Stop the timer
clearInterval(z.timer);
z.timer = null;
z.now = lastNum;
z.a();
if (elem.curAnim) elem.curAnim[ prop ] = true;
var done = true;
for ( var i in elem.curAnim )
if ( elem.curAnim[i] !== true )
done = false;
if ( done ) {
// Reset the overflow
y.overflow = "";
// Reset the display
y.display = oldDisplay;
if (jQuery.css(elem, "display") == "none")
y.display = "block";
// Hide the element if the "hide" operation was done
if ( options.hide )
y.display = "none";
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show )
for ( var p in elem.curAnim )
if (p == "opacity")
jQuery.attr(y, p, elem.orig[p]);
else
y[p] = "";
}
// If a callback was provided, execute it
if ( done && jQuery.isFunction( options.complete ) )
// Execute the complete function
options.complete.apply( elem );
} else {
var n = t - this.startTime;
// Figure out where in the animation we are and set the number
var p = n / options.duration;
// If the easing function exists, then use it
z.now = options.easing && jQuery.easing[options.easing] ?
jQuery.easing[options.easing](p, n, firstNum, (lastNum-firstNum), options.duration) :
// else use default linear easing
((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum;
// Perform the next step of the animation
z.a();
}
};
}
});
}
| NCIP/eagle | WebRoot/js/lib/jquery.js | JavaScript | bsd-3-clause | 59,266 |
# Author: Immanuel Bayer
# License: BSD 3 clause
import ffm
import numpy as np
from .base import FactorizationMachine
from sklearn.utils.testing import assert_array_equal
from .validation import check_array, assert_all_finite
class FMRecommender(FactorizationMachine):
""" Factorization Machine Recommender with pairwise (BPR) loss solver.
Parameters
----------
n_iter : int, optional
The number of interations of individual samples .
init_stdev: float, optional
Sets the stdev for the initialization of the parameter
random_state: int, optional
The seed of the pseudo random number generator that
initializes the parameters and mcmc chain.
rank: int
The rank of the factorization used for the second order interactions.
l2_reg_w : float
L2 penalty weight for pairwise coefficients.
l2_reg_V : float
L2 penalty weight for linear coefficients.
l2_reg : float
L2 penalty weight for all coefficients (default=0).
step_size : float
Stepsize for the SGD solver, the solver uses a fixed step size and
might require a tunning of the number of iterations `n_iter`.
Attributes
---------
w0_ : float
bias term
w_ : float | array, shape = (n_features)
Coefficients for linear combination.
V_ : float | array, shape = (rank_pair, n_features)
Coefficients of second order factor matrix.
"""
def __init__(self, n_iter=100, init_stdev=0.1, rank=8, random_state=123,
l2_reg_w=0.1, l2_reg_V=0.1, l2_reg=0, step_size=0.1):
super(FMRecommender, self).\
__init__(n_iter=n_iter, init_stdev=init_stdev, rank=rank,
random_state=random_state)
if (l2_reg != 0):
self.l2_reg_V = l2_reg
self.l2_reg_w = l2_reg
else:
self.l2_reg_w = l2_reg_w
self.l2_reg_V = l2_reg_V
self.step_size = step_size
self.task = "ranking"
def fit(self, X, pairs):
""" Fit model with specified loss.
Parameters
----------
X : scipy.sparse.csc_matrix, (n_samples, n_features)
y : float | ndarray, shape = (n_compares, 2)
Each row `i` defines a pair of samples such that
the first returns a high value then the second
FM(X[i,0]) > FM(X[i, 1]).
"""
X = X.T
X = check_array(X, accept_sparse="csc", dtype=np.float64)
assert_all_finite(pairs)
pairs = pairs.astype(np.float64)
# check that pairs contain no real values
assert_array_equal(pairs, pairs.astype(np.int32))
assert pairs.max() <= X.shape[1]
assert pairs.min() >= 0
self.w0_, self.w_, self.V_ = ffm.ffm_fit_sgd_bpr(self, X, pairs)
return self
| ibayer/fastFM-fork | fastFM/bpr.py | Python | bsd-3-clause | 2,859 |
package me.hatter.tools.resourceproxy.commons.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
public class FilePrintWriter extends PrintWriter {
public FilePrintWriter(File file) throws FileNotFoundException {
super(new OutputStreamWriter(new FileOutputStream(file)));
}
public FilePrintWriter(File file, String charset) throws UnsupportedEncodingException, FileNotFoundException {
super(new OutputStreamWriter(new FileOutputStream(file), charset));
}
}
| KingBowser/hatter-source-code | resourceproxy/commons/src/me/hatter/tools/resourceproxy/commons/io/FilePrintWriter.java | Java | bsd-3-clause | 646 |
#include "torch-moveit.h"
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include "utils.h"
typedef std::shared_ptr<moveit_msgs::CollisionObject> CollisionObjectPtr;
MOVIMP(CollisionObjectPtr*, CollisionObject, new)()
{
CollisionObjectPtr *p = new CollisionObjectPtr(new moveit_msgs::CollisionObject());
(*p)->operation = moveit_msgs::CollisionObject::ADD;
return p;
}
MOVIMP(void, CollisionObject, delete)(CollisionObjectPtr *ptr)
{
if (ptr)
delete ptr;
}
MOVIMP(const char *, CollisionObject, getId)(CollisionObjectPtr *self)
{
return (*self)->id.c_str();
}
MOVIMP(void, CollisionObject, setId)(CollisionObjectPtr *self, const char *id)
{
(*self)->id = id;
}
MOVIMP(const char *, CollisionObject, getFrameId)(CollisionObjectPtr *self)
{
return (*self)->header.frame_id.c_str();
}
MOVIMP(void, CollisionObject, setFrameId)(CollisionObjectPtr *self, const char *id)
{
(*self)->header.frame_id = id;
}
MOVIMP(int, CollisionObject, getOperation)(CollisionObjectPtr *self)
{
return (*self)->operation;
}
MOVIMP(void, CollisionObject, setOperation)(CollisionObjectPtr *self, int operation)
{
(*self)->operation = static_cast< moveit_msgs::CollisionObject::_operation_type>(operation);
}
MOVIMP(void, CollisionObject, addPrimitive)(CollisionObjectPtr *self, int type, THDoubleTensor *dimensions, tf::Transform *transform)
{
shape_msgs::SolidPrimitive primitive;
primitive.type = type;
Tensor2vector(dimensions, primitive.dimensions);
(*self)->primitives.push_back(primitive);
geometry_msgs::Pose pose; // convert transform to pose msg
poseTFToMsg(*transform, pose);
(*self)->primitive_poses.push_back(pose);
}
MOVIMP(void, CollisionObject, addPlane)(CollisionObjectPtr *self, THDoubleTensor *coefs, tf::Transform *transform)
{
shape_msgs::Plane plane;
for (int i = 0; i < 4; ++i)
plane.coef[i] = THDoubleTensor_get1d(coefs, i);
(*self)->planes.push_back(plane);
geometry_msgs::Pose pose; // convert transform to pose msg
poseTFToMsg(*transform, pose);
(*self)->plane_poses.push_back(pose);
}
| Xamla/torch-moveit | src/collision_object.cpp | C++ | bsd-3-clause | 2,089 |
// Generated by delombok at Sat Jun 11 11:12:44 CEST 2016
public final class Zoo {
private final String meerkat;
private final String warthog;
public Zoo create() {
return new Zoo("tomon", "pumbaa");
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
Zoo(final String meerkat, final String warthog) {
this.meerkat = meerkat;
this.warthog = warthog;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public static class ZooBuilder {
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
private String meerkat;
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
private String warthog;
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
ZooBuilder() {
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public ZooBuilder meerkat(final String meerkat) {
this.meerkat = meerkat;
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public ZooBuilder warthog(final String warthog) {
this.warthog = warthog;
return this;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public Zoo build() {
return new Zoo(meerkat, warthog);
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public java.lang.String toString() {
return "Zoo.ZooBuilder(meerkat=" + this.meerkat + ", warthog=" + this.warthog + ")";
}
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public static ZooBuilder builder() {
return new ZooBuilder();
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public String getMeerkat() {
return this.meerkat;
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public String getWarthog() {
return this.warthog;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public boolean equals(final java.lang.Object o) {
if (o == this) return true;
if (!(o instanceof Zoo)) return false;
final Zoo other = (Zoo) o;
final java.lang.Object this$meerkat = this.getMeerkat();
final java.lang.Object other$meerkat = other.getMeerkat();
if (this$meerkat == null ? other$meerkat != null : !this$meerkat.equals(other$meerkat)) return false;
final java.lang.Object this$warthog = this.getWarthog();
final java.lang.Object other$warthog = other.getWarthog();
if (this$warthog == null ? other$warthog != null : !this$warthog.equals(other$warthog)) return false;
return true;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public int hashCode() {
final int PRIME = 59;
int result = 1;
final java.lang.Object $meerkat = this.getMeerkat();
result = result * PRIME + ($meerkat == null ? 43 : $meerkat.hashCode());
final java.lang.Object $warthog = this.getWarthog();
result = result * PRIME + ($warthog == null ? 43 : $warthog.hashCode());
return result;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public java.lang.String toString() {
return "Zoo(meerkat=" + this.getMeerkat() + ", warthog=" + this.getWarthog() + ")";
}
}
| AlexejK/lombok-intellij-plugin | testData/after/value/ValueAndBuilder93.java | Java | bsd-3-clause | 3,489 |
<?php
/*
* This file is part of the codeliner/ginger-plugin-installer package.
* (c) Alexander Miertsch <kontakt@codeliner.ws>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return array(
); | gingerwfms/ginger-plugin-installer | config/module.config.php | PHP | bsd-3-clause | 284 |