repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
abingham/rosalind | csharp/rosalind_test/CircularBufferTest.cs | 3557 | using NUnit.Framework;
using System;
using System.Diagnostics.Contracts;
using rosalind;
namespace rosalind_test
{
[TestFixture()]
public class CircularBufferTest
{
[Test()]
public void TestInitialState()
{
int cap = 10;
var b = new CircularBuffer<int> (cap);
Assert.AreEqual (b.capacity, cap);
Assert.AreEqual (b.size, 0);
}
[Test()]
public void TestPushFrontIncreasesSize()
{
var b = new CircularBuffer<int> (10);
b.pushFront (42);
Assert.AreEqual (b.size, 1);
}
[Test()]
public void TestPushFrontAddsElement()
{
var b = new CircularBuffer<int> (10);
b.pushFront (42);
Assert.AreEqual (b[0], 42);
}
[Test()]
public void TestPopFrontReturnsAndRemovesItem()
{
var b = new CircularBuffer<int> (10);
b.pushFront (42);
b.pushFront (69);
Assert.AreEqual (b.popFront (), 69);
Assert.AreEqual (b [0], 42);
Assert.AreEqual (b.size, 1);
}
[Test()]
public void TestPopFrontOnEmptyBufferThrows()
{
var b = new CircularBuffer<int> (10);
try
{
b.popFront();
}
catch (Exception ex)
{
Assert.True(ex.GetType().Name == "ContractException");
return;
}
Assert.Fail("ContractException has not been thrown.");
}
[Test()]
public void TestPushBackIncreasesSize()
{
var b = new CircularBuffer<int> (10);
b.pushBack (42);
Assert.AreEqual (b.size, 1);
}
[Test()]
public void TestPushBackAddsElement()
{
var b = new CircularBuffer<int> (10);
b.pushBack (42);
Assert.AreEqual (b[0], 42);
}
[Test()]
public void TestPopBackReturnsAndRemovesItem()
{
var b = new CircularBuffer<int> (10);
b.pushFront (42);
b.pushFront (69);
Assert.AreEqual (b.popBack (), 42);
Assert.AreEqual (b [0], 69);
Assert.AreEqual (b.size, 1);
}
[Test()]
public void TestPopBackOnEmptyBufferThrows()
{
var b = new CircularBuffer<int> (10);
try
{
b.popBack();
}
catch (Exception ex)
{
Assert.True(ex.GetType().Name == "ContractException");
return;
}
Assert.Fail("ContractException has not been thrown.");
}
[Test()]
public void TestCapacityCanBeReachedAtMiddle() {
var b = new CircularBuffer<int> (10);
for (int i = 0; i < b.capacity; ++i) {
b.pushBack (42);
}
for (int i = 0; i < b.capacity / 2; ++i) {
b.popFront ();
}
for (int i = 0; i < b.capacity / 2; ++i) {
b.pushBack (42);
}
try
{
b.pushBack(1337);
}
catch (Exception ex)
{
Assert.True(ex.GetType().Name == "ContractException");
return;
}
Assert.Fail("ContractException has not been thrown.");
}
}
}
| mit |
boully/comake | setup.py | 905 | from setuptools import setup, find_packages
setup(
name = 'comake',
packages=find_packages(), # this must be the same as the name above
version = 'v0.1.6',
description = 'A c++ build tool',
author = 'liaosiwei',
author_email = '[email protected]',
url = 'https://github.com/boully/comake',
download_url = 'https://github.com/boully/comake/tarball/v0.1.6',
keywords = ['c++', 'auto-build', 'dependency'],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
install_requires=[
"GitPython",
"pytoml",
"Jinja2",
],
entry_points={
'console_scripts': [
'comake=comake.Comake:main',
],
},
)
| mit |
linq2db/linq2db | Tests/Tests.T4/Databases/Access.generated.cs | 34502 | //---------------------------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by T4Model template for T4 (https://github.com/linq2db/linq2db).
// Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
// </auto-generated>
//---------------------------------------------------------------------------------------------------
#pragma warning disable 1591
#nullable enable
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using LinqToDB;
using LinqToDB.Common;
using LinqToDB.Configuration;
using LinqToDB.Data;
using LinqToDB.Mapping;
namespace AccessDataContext
{
public partial class TestDataDB : LinqToDB.Data.DataConnection
{
public ITable<AllType> AllTypes { get { return this.GetTable<AllType>(); } }
public ITable<Child> Children { get { return this.GetTable<Child>(); } }
public ITable<DataTypeTest> DataTypeTests { get { return this.GetTable<DataTypeTest>(); } }
public ITable<Doctor> Doctors { get { return this.GetTable<Doctor>(); } }
public ITable<Dual> Duals { get { return this.GetTable<Dual>(); } }
public ITable<GrandChild> GrandChildren { get { return this.GetTable<GrandChild>(); } }
public ITable<InheritanceChild> InheritanceChildren { get { return this.GetTable<InheritanceChild>(); } }
public ITable<InheritanceParent> InheritanceParents { get { return this.GetTable<InheritanceParent>(); } }
public ITable<LinqDataType> LinqDataTypes { get { return this.GetTable<LinqDataType>(); } }
public ITable<LinqDataTypesQuery> LinqDataTypesQueries { get { return this.GetTable<LinqDataTypesQuery>(); } }
public ITable<LinqDataTypesQuery1> LinqDataTypesQuery1 { get { return this.GetTable<LinqDataTypesQuery1>(); } }
public ITable<LinqDataTypesQuery2> LinqDataTypesQuery2 { get { return this.GetTable<LinqDataTypesQuery2>(); } }
public ITable<Parent> Parents { get { return this.GetTable<Parent>(); } }
public ITable<Patient> Patients { get { return this.GetTable<Patient>(); } }
public ITable<PatientSelectAll> PatientSelectAll { get { return this.GetTable<PatientSelectAll>(); } }
public ITable<Person> People { get { return this.GetTable<Person>(); } }
public ITable<PersonSelectAll> PersonSelectAll { get { return this.GetTable<PersonSelectAll>(); } }
public ITable<ScalarDataReader> ScalarDataReaders { get { return this.GetTable<ScalarDataReader>(); } }
public ITable<TestIdentity> TestIdentities { get { return this.GetTable<TestIdentity>(); } }
public ITable<TestMerge1> TestMerge1 { get { return this.GetTable<TestMerge1>(); } }
public ITable<TestMerge2> TestMerge2 { get { return this.GetTable<TestMerge2>(); } }
public TestDataDB()
{
InitDataContext();
InitMappingSchema();
}
public TestDataDB(string configuration)
: base(configuration)
{
InitDataContext();
InitMappingSchema();
}
public TestDataDB(LinqToDbConnectionOptions options)
: base(options)
{
InitDataContext();
InitMappingSchema();
}
public TestDataDB(LinqToDbConnectionOptions<TestDataDB> options)
: base(options)
{
InitDataContext();
InitMappingSchema();
}
partial void InitDataContext ();
partial void InitMappingSchema();
}
[Table("AllTypes")]
public partial class AllType
{
[Column( DbType="Long", DataType=LinqToDB.DataType.Int32), NotNull ] public int ID { get; set; } // Long
[Column("bitDataType", DbType="Bit", DataType=LinqToDB.DataType.Boolean), NotNull ] public bool BitDataType { get; set; } // Bit
[Column("smallintDataType", DbType="Short", DataType=LinqToDB.DataType.Int16), Nullable] public short? SmallintDataType { get; set; } // Short
[Column("decimalDataType", DbType="Decimal(18, 0)", DataType=LinqToDB.DataType.Decimal, Precision=18, Scale=0), Nullable] public decimal? DecimalDataType { get; set; } // Decimal(18, 0)
[Column("intDataType", DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? IntDataType { get; set; } // Long
[Column("tinyintDataType", DbType="Byte", DataType=LinqToDB.DataType.Byte), Nullable] public byte? TinyintDataType { get; set; } // Byte
[Column("moneyDataType", DbType="Currency", DataType=LinqToDB.DataType.Money), Nullable] public decimal? MoneyDataType { get; set; } // Currency
[Column("floatDataType", DbType="Double", DataType=LinqToDB.DataType.Double), Nullable] public double? FloatDataType { get; set; } // Double
[Column("realDataType", DbType="Single", DataType=LinqToDB.DataType.Single), Nullable] public float? RealDataType { get; set; } // Single
[Column("datetimeDataType", DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable] public DateTime? DatetimeDataType { get; set; } // DateTime
[Column("charDataType", DbType="CHAR(1)", DataType=LinqToDB.DataType.Char, Length=1), Nullable] public char? CharDataType { get; set; } // CHAR(1)
[Column("char20DataType", DbType="CHAR(20)", DataType=LinqToDB.DataType.Char, Length=20), Nullable] public string? Char20DataType { get; set; } // CHAR(20)
[Column("varcharDataType", DbType="VarChar(20)", DataType=LinqToDB.DataType.VarChar, Length=20), Nullable] public string? VarcharDataType { get; set; } // VarChar(20)
[Column("textDataType", DbType="LongText", DataType=LinqToDB.DataType.NText), Nullable] public string? TextDataType { get; set; } // LongText
[Column("ncharDataType", DbType="CHAR(20)", DataType=LinqToDB.DataType.Char, Length=20), Nullable] public string? NcharDataType { get; set; } // CHAR(20)
[Column("nvarcharDataType", DbType="VarChar(20)", DataType=LinqToDB.DataType.VarChar, Length=20), Nullable] public string? NvarcharDataType { get; set; } // VarChar(20)
[Column("ntextDataType", DbType="LongText", DataType=LinqToDB.DataType.NText), Nullable] public string? NtextDataType { get; set; } // LongText
[Column("binaryDataType", DbType="VARBINARY(10)", DataType=LinqToDB.DataType.VarBinary, Length=10), Nullable] public byte[]? BinaryDataType { get; set; } // VARBINARY(10)
[Column("varbinaryDataType", DbType="VARBINARY(510)", DataType=LinqToDB.DataType.VarBinary, Length=510), Nullable] public byte[]? VarbinaryDataType { get; set; } // VARBINARY(510)
[Column("imageDataType", DbType="LongBinary", DataType=LinqToDB.DataType.Image), Nullable] public byte[]? ImageDataType { get; set; } // LongBinary
[Column("oleObjectDataType", DbType="LongBinary", DataType=LinqToDB.DataType.Image), Nullable] public byte[]? OleObjectDataType { get; set; } // LongBinary
[Column("uniqueidentifierDataType", DbType="GUID", DataType=LinqToDB.DataType.Guid), Nullable] public Guid? UniqueidentifierDataType { get; set; } // GUID
}
[Table("Child")]
public partial class Child
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? ParentID { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? ChildID { get; set; } // Long
}
[Table("DataTypeTest")]
public partial class DataTypeTest
{
[Column( DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int DataTypeID { get; set; } // Long
[Column("Binary_", DbType="LongBinary", DataType=LinqToDB.DataType.Image), Nullable ] public byte[]? Binary { get; set; } // LongBinary
[Column("Boolean_", DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Boolean { get; set; } // Long
[Column("Byte_", DbType="Byte", DataType=LinqToDB.DataType.Byte), Nullable ] public byte? Byte { get; set; } // Byte
[Column("Bytes_", DbType="LongBinary", DataType=LinqToDB.DataType.Image), Nullable ] public byte[]? Bytes { get; set; } // LongBinary
[Column("Char_", DbType="VarChar(1)", DataType=LinqToDB.DataType.VarChar, Length=1), Nullable ] public char? Char { get; set; } // VarChar(1)
[Column("DateTime_", DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable ] public DateTime? DateTime { get; set; } // DateTime
[Column("Decimal_", DbType="Currency", DataType=LinqToDB.DataType.Money), Nullable ] public decimal? Decimal { get; set; } // Currency
[Column("Double_", DbType="Double", DataType=LinqToDB.DataType.Double), Nullable ] public double? Double { get; set; } // Double
[Column("Guid_", DbType="GUID", DataType=LinqToDB.DataType.Guid), Nullable ] public Guid? Guid { get; set; } // GUID
[Column("Int16_", DbType="Short", DataType=LinqToDB.DataType.Int16), Nullable ] public short? Int16 { get; set; } // Short
[Column("Int32_", DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Int32 { get; set; } // Long
[Column("Int64_", DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Int64 { get; set; } // Long
[Column("Money_", DbType="Currency", DataType=LinqToDB.DataType.Money), Nullable ] public decimal? Money { get; set; } // Currency
[Column("SByte_", DbType="Byte", DataType=LinqToDB.DataType.Byte), Nullable ] public byte? SByte { get; set; } // Byte
[Column("Single_", DbType="Single", DataType=LinqToDB.DataType.Single), Nullable ] public float? Single { get; set; } // Single
[Column("Stream_", DbType="LongBinary", DataType=LinqToDB.DataType.Image), Nullable ] public byte[]? Stream { get; set; } // LongBinary
[Column("String_", DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable ] public string? String { get; set; } // VarChar(50)
[Column("UInt16_", DbType="Short", DataType=LinqToDB.DataType.Int16), Nullable ] public short? UInt16 { get; set; } // Short
[Column("UInt32_", DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? UInt32 { get; set; } // Long
[Column("UInt64_", DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? UInt64 { get; set; } // Long
[Column("Xml_", DbType="LongText", DataType=LinqToDB.DataType.NText), Nullable ] public string? Xml { get; set; } // LongText
}
[Table("Doctor")]
public partial class Doctor
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int PersonID { get; set; } // Long
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), NotNull] public string Taxonomy { get; set; } = null!; // VarChar(50)
#region Associations
/// <summary>
/// PersonDoctor
/// </summary>
[Association(ThisKey="PersonID", OtherKey="PersonID", CanBeNull=false, Relationship=LinqToDB.Mapping.Relationship.OneToOne, KeyName="PersonDoctor", BackReferenceName="PersonDoctor")]
public Person Person { get; set; } = null!;
#endregion
}
[Table("Dual")]
public partial class Dual
{
[Column(DbType="VarChar(10)", DataType=LinqToDB.DataType.VarChar, Length=10), Nullable] public string? Dummy { get; set; } // VarChar(10)
}
[Table("GrandChild")]
public partial class GrandChild
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? ParentID { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? ChildID { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? GrandChildID { get; set; } // Long
}
[Table("InheritanceChild")]
public partial class InheritanceChild
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int InheritanceChildId { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), NotNull] public int InheritanceParentId { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? TypeDiscriminator { get; set; } // Long
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable ] public string? Name { get; set; } // VarChar(50)
}
[Table("InheritanceParent")]
public partial class InheritanceParent
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int InheritanceParentId { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? TypeDiscriminator { get; set; } // Long
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable ] public string? Name { get; set; } // VarChar(50)
}
[Table("LinqDataTypes")]
public partial class LinqDataType
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? ID { get; set; } // Long
[Column(DbType="Decimal(10, 4)", DataType=LinqToDB.DataType.Decimal, Precision=10, Scale=4), Nullable] public decimal? MoneyValue { get; set; } // Decimal(10, 4)
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable] public DateTime? DateTimeValue { get; set; } // DateTime
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable] public DateTime? DateTimeValue2 { get; set; } // DateTime
[Column(DbType="Bit", DataType=LinqToDB.DataType.Boolean), NotNull ] public bool BoolValue { get; set; } // Bit
[Column(DbType="GUID", DataType=LinqToDB.DataType.Guid), Nullable] public Guid? GuidValue { get; set; } // GUID
[Column(DbType="LongBinary", DataType=LinqToDB.DataType.Image), Nullable] public byte[]? BinaryValue { get; set; } // LongBinary
[Column(DbType="Short", DataType=LinqToDB.DataType.Int16), Nullable] public short? SmallIntValue { get; set; } // Short
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? IntValue { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? BigIntValue { get; set; } // Long
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable] public string? StringValue { get; set; } // VarChar(50)
}
[Table("LinqDataTypes Query", IsView=true)]
public partial class LinqDataTypesQuery
{
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable] public DateTime? DateTimeValue { get; set; } // DateTime
}
[Table("LinqDataTypes Query1", IsView=true)]
public partial class LinqDataTypesQuery1
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? ID { get; set; } // Long
}
[Table("LinqDataTypes Query2", IsView=true)]
public partial class LinqDataTypesQuery2
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? ID { get; set; } // Long
}
[Table("Parent")]
public partial class Parent
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? ParentID { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? Value1 { get; set; } // Long
}
[Table("Patient")]
public partial class Patient
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int PersonID { get; set; } // Long
[Column(DbType="VarChar(255)", DataType=LinqToDB.DataType.VarChar, Length=255), NotNull] public string Diagnosis { get; set; } = null!; // VarChar(255)
#region Associations
/// <summary>
/// PersonPatient
/// </summary>
[Association(ThisKey="PersonID", OtherKey="PersonID", CanBeNull=false, Relationship=LinqToDB.Mapping.Relationship.OneToOne, KeyName="PersonPatient", BackReferenceName="PersonPatient")]
public Person Person { get; set; } = null!;
#endregion
}
[Table("Patient_SelectAll", IsView=true)]
public partial class PatientSelectAll
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), NotNull ] public int PersonID { get; set; } // Long
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable] public string? FirstName { get; set; } // VarChar(50)
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable] public string? LastName { get; set; } // VarChar(50)
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable] public string? MiddleName { get; set; } // VarChar(50)
[Column(DbType="VarChar(1)", DataType=LinqToDB.DataType.VarChar, Length=1), Nullable] public char? Gender { get; set; } // VarChar(1)
[Column(DbType="VarChar(255)", DataType=LinqToDB.DataType.VarChar, Length=255), Nullable] public string? Diagnosis { get; set; } // VarChar(255)
}
[Table("Person")]
public partial class Person
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int PersonID { get; set; } // Long
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), NotNull] public string FirstName { get; set; } = null!; // VarChar(50)
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), NotNull] public string LastName { get; set; } = null!; // VarChar(50)
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable ] public string? MiddleName { get; set; } // VarChar(50)
[Column(DbType="VarChar(1)", DataType=LinqToDB.DataType.VarChar, Length=1), NotNull] public char Gender { get; set; } // VarChar(1)
#region Associations
/// <summary>
/// PersonDoctor_BackReference
/// </summary>
[Association(ThisKey="PersonID", OtherKey="PersonID", CanBeNull=true, Relationship=LinqToDB.Mapping.Relationship.OneToOne, IsBackReference=true)]
public Doctor? PersonDoctor { get; set; }
/// <summary>
/// PersonPatient_BackReference
/// </summary>
[Association(ThisKey="PersonID", OtherKey="PersonID", CanBeNull=true, Relationship=LinqToDB.Mapping.Relationship.OneToOne, IsBackReference=true)]
public Patient? PersonPatient { get; set; }
#endregion
}
[Table("Person_SelectAll", IsView=true)]
public partial class PersonSelectAll
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), NotNull ] public int PersonID { get; set; } // Long
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable] public string? FirstName { get; set; } // VarChar(50)
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable] public string? LastName { get; set; } // VarChar(50)
[Column(DbType="VarChar(50)", DataType=LinqToDB.DataType.VarChar, Length=50), Nullable] public string? MiddleName { get; set; } // VarChar(50)
[Column(DbType="VarChar(1)", DataType=LinqToDB.DataType.VarChar, Length=1), Nullable] public char? Gender { get; set; } // VarChar(1)
}
[Table("Scalar_DataReader", IsView=true)]
public partial class ScalarDataReader
{
[Column("intField", DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable] public int? IntField { get; set; } // Long
[Column("stringField", DbType="VarChar(255)", DataType=LinqToDB.DataType.VarChar, Length=255), Nullable] public string? StringField { get; set; } // VarChar(255)
}
[Table("TestIdentity")]
public partial class TestIdentity
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int ID { get; set; } // Long
}
[Table("TestMerge1")]
public partial class TestMerge1
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int Id { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field1 { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field2 { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field3 { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field4 { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field5 { get; set; } // Long
[Column(DbType="Bit", DataType=LinqToDB.DataType.Boolean), NotNull] public bool FieldBoolean { get; set; } // Bit
[Column(DbType="VarChar(20)", DataType=LinqToDB.DataType.VarChar, Length=20), Nullable ] public string? FieldString { get; set; } // VarChar(20)
[Column(DbType="VarChar(20)", DataType=LinqToDB.DataType.VarChar, Length=20), Nullable ] public string? FieldNString { get; set; } // VarChar(20)
[Column(DbType="CHAR(1)", DataType=LinqToDB.DataType.Char, Length=1), Nullable ] public char? FieldChar { get; set; } // CHAR(1)
[Column(DbType="CHAR(1)", DataType=LinqToDB.DataType.Char, Length=1), Nullable ] public char? FieldNChar { get; set; } // CHAR(1)
[Column(DbType="Single", DataType=LinqToDB.DataType.Single), Nullable ] public float? FieldFloat { get; set; } // Single
[Column(DbType="Double", DataType=LinqToDB.DataType.Double), Nullable ] public double? FieldDouble { get; set; } // Double
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable ] public DateTime? FieldDateTime { get; set; } // DateTime
[Column(DbType="VARBINARY(20)", DataType=LinqToDB.DataType.VarBinary, Length=20), Nullable ] public byte[]? FieldBinary { get; set; } // VARBINARY(20)
[Column(DbType="GUID", DataType=LinqToDB.DataType.Guid), Nullable ] public Guid? FieldGuid { get; set; } // GUID
[Column(DbType="Decimal(24, 10)", DataType=LinqToDB.DataType.Decimal, Precision=24, Scale=10), Nullable ] public decimal? FieldDecimal { get; set; } // Decimal(24, 10)
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable ] public DateTime? FieldDate { get; set; } // DateTime
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable ] public DateTime? FieldTime { get; set; } // DateTime
[Column(DbType="VarChar(20)", DataType=LinqToDB.DataType.VarChar, Length=20), Nullable ] public string? FieldEnumString { get; set; } // VarChar(20)
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? FieldEnumNumber { get; set; } // Long
}
[Table("TestMerge2")]
public partial class TestMerge2
{
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), PrimaryKey, NotNull] public int Id { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field1 { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field2 { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field3 { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field4 { get; set; } // Long
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? Field5 { get; set; } // Long
[Column(DbType="Bit", DataType=LinqToDB.DataType.Boolean), NotNull] public bool FieldBoolean { get; set; } // Bit
[Column(DbType="VarChar(20)", DataType=LinqToDB.DataType.VarChar, Length=20), Nullable ] public string? FieldString { get; set; } // VarChar(20)
[Column(DbType="VarChar(20)", DataType=LinqToDB.DataType.VarChar, Length=20), Nullable ] public string? FieldNString { get; set; } // VarChar(20)
[Column(DbType="CHAR(1)", DataType=LinqToDB.DataType.Char, Length=1), Nullable ] public char? FieldChar { get; set; } // CHAR(1)
[Column(DbType="CHAR(1)", DataType=LinqToDB.DataType.Char, Length=1), Nullable ] public char? FieldNChar { get; set; } // CHAR(1)
[Column(DbType="Single", DataType=LinqToDB.DataType.Single), Nullable ] public float? FieldFloat { get; set; } // Single
[Column(DbType="Double", DataType=LinqToDB.DataType.Double), Nullable ] public double? FieldDouble { get; set; } // Double
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable ] public DateTime? FieldDateTime { get; set; } // DateTime
[Column(DbType="VARBINARY(20)", DataType=LinqToDB.DataType.VarBinary, Length=20), Nullable ] public byte[]? FieldBinary { get; set; } // VARBINARY(20)
[Column(DbType="GUID", DataType=LinqToDB.DataType.Guid), Nullable ] public Guid? FieldGuid { get; set; } // GUID
[Column(DbType="Decimal(24, 10)", DataType=LinqToDB.DataType.Decimal, Precision=24, Scale=10), Nullable ] public decimal? FieldDecimal { get; set; } // Decimal(24, 10)
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable ] public DateTime? FieldDate { get; set; } // DateTime
[Column(DbType="DateTime", DataType=LinqToDB.DataType.DateTime), Nullable ] public DateTime? FieldTime { get; set; } // DateTime
[Column(DbType="VarChar(20)", DataType=LinqToDB.DataType.VarChar, Length=20), Nullable ] public string? FieldEnumString { get; set; } // VarChar(20)
[Column(DbType="Long", DataType=LinqToDB.DataType.Int32), Nullable ] public int? FieldEnumNumber { get; set; } // Long
}
public static partial class TestDataDBStoredProcedures
{
#region AddIssue792Record
public static int AddIssue792Record(this TestDataDB dataConnection)
{
return dataConnection.ExecuteProc("[AddIssue792Record]");
}
#endregion
#region PatientSelectByName
public static IEnumerable<PatientSelectAll> PatientSelectByName(this TestDataDB dataConnection, string? @firstName, string? @lastName)
{
return dataConnection.QueryProc<PatientSelectAll>("[Patient_SelectByName]",
new DataParameter("@firstName", @firstName, LinqToDB.DataType.NText),
new DataParameter("@lastName", @lastName, LinqToDB.DataType.NText));
}
#endregion
#region PersonDelete
public static int PersonDelete(this TestDataDB dataConnection, int? @PersonID)
{
return dataConnection.ExecuteProc("[Person_Delete]",
new DataParameter("@PersonID", @PersonID, LinqToDB.DataType.Int32));
}
#endregion
#region PersonInsert
public static int PersonInsert(this TestDataDB dataConnection, string? @FirstName, string? @MiddleName, string? @LastName, char? @Gender)
{
return dataConnection.ExecuteProc("[Person_Insert]",
new DataParameter("@FirstName", @FirstName, LinqToDB.DataType.NText),
new DataParameter("@MiddleName", @MiddleName, LinqToDB.DataType.NText),
new DataParameter("@LastName", @LastName, LinqToDB.DataType.NText),
new DataParameter("@Gender", @Gender, LinqToDB.DataType.NText));
}
#endregion
#region PersonSelectByKey
public static IEnumerable<Person> PersonSelectByKey(this TestDataDB dataConnection, int? @id)
{
return dataConnection.QueryProc<Person>("[Person_SelectByKey]",
new DataParameter("@id", @id, LinqToDB.DataType.Int32));
}
#endregion
#region PersonSelectByName
public static IEnumerable<Person> PersonSelectByName(this TestDataDB dataConnection, string? @firstName, string? @lastName)
{
return dataConnection.QueryProc<Person>("[Person_SelectByName]",
new DataParameter("@firstName", @firstName, LinqToDB.DataType.NText),
new DataParameter("@lastName", @lastName, LinqToDB.DataType.NText));
}
#endregion
#region PersonSelectListByName
public static IEnumerable<Person> PersonSelectListByName(this TestDataDB dataConnection, string? @firstName, string? @lastName)
{
return dataConnection.QueryProc<Person>("[Person_SelectListByName]",
new DataParameter("@firstName", @firstName, LinqToDB.DataType.NText),
new DataParameter("@lastName", @lastName, LinqToDB.DataType.NText));
}
#endregion
#region PersonUpdate
public static int PersonUpdate(this TestDataDB dataConnection, int? @id, int? @PersonID, string? @FirstName, string? @MiddleName, string? @LastName, char? @Gender)
{
return dataConnection.ExecuteProc("[Person_Update]",
new DataParameter("@id", @id, LinqToDB.DataType.Int32),
new DataParameter("@PersonID", @PersonID, LinqToDB.DataType.Int32),
new DataParameter("@FirstName", @FirstName, LinqToDB.DataType.NText),
new DataParameter("@MiddleName", @MiddleName, LinqToDB.DataType.NText),
new DataParameter("@LastName", @LastName, LinqToDB.DataType.NText),
new DataParameter("@Gender", @Gender, LinqToDB.DataType.NText));
}
#endregion
}
public static partial class TableExtensions
{
public static DataTypeTest? Find(this ITable<DataTypeTest> table, int DataTypeID)
{
return table.FirstOrDefault(t =>
t.DataTypeID == DataTypeID);
}
public static Doctor? Find(this ITable<Doctor> table, int PersonID)
{
return table.FirstOrDefault(t =>
t.PersonID == PersonID);
}
public static InheritanceChild? Find(this ITable<InheritanceChild> table, int InheritanceChildId)
{
return table.FirstOrDefault(t =>
t.InheritanceChildId == InheritanceChildId);
}
public static InheritanceParent? Find(this ITable<InheritanceParent> table, int InheritanceParentId)
{
return table.FirstOrDefault(t =>
t.InheritanceParentId == InheritanceParentId);
}
public static Patient? Find(this ITable<Patient> table, int PersonID)
{
return table.FirstOrDefault(t =>
t.PersonID == PersonID);
}
public static Person? Find(this ITable<Person> table, int PersonID)
{
return table.FirstOrDefault(t =>
t.PersonID == PersonID);
}
public static TestIdentity? Find(this ITable<TestIdentity> table, int ID)
{
return table.FirstOrDefault(t =>
t.ID == ID);
}
public static TestMerge1? Find(this ITable<TestMerge1> table, int Id)
{
return table.FirstOrDefault(t =>
t.Id == Id);
}
public static TestMerge2? Find(this ITable<TestMerge2> table, int Id)
{
return table.FirstOrDefault(t =>
t.Id == Id);
}
}
}
#pragma warning restore 1591
| mit |
zapplebee/phpNetsh | api.php | 4059 | <?php //api.php
header('Content-Type: application/json');
define('ns', "phpNetsh_");
function ob_catch($function){
//start the buffer and call the original funciton. if it has a return value, return that. otherwise return buffer
ob_start();
$originalReturn = call_user_func($function);
$r = ob_get_clean();
if($originalReturn !== null){
return $originalReturn;
} else {
return $r;
}
}
function error($httpCode,$text){
http_response_code($httpCode);
throw new Exception($text);
}
function jp($array){
echo json_encode($array);
return $array;
}
class TempFilesHandler {
private $files = array();
private $dir;
function __construct(){
$this->files[0] = tempnam(false,false);
$this->dir = dirname($this->files[0]);
}
public function get($file){
$this->files[] = $file;
return file_get_contents($file);
}
public function put($fileContents){
$file = tempnam(false,false);
file_put_contents($file,$fileContents);
$this->files[] = $file;
return $file;
}
public function getDirectory(){
return $this->dir;
}
function __destruct() {
foreach($this->files as $f){
unlink($f);
}
}
}
$f = new TempFilesHandler();
function phpNetsh_getProfiles(){
$profiles_raw = shell_exec('netsh wlan show profiles');
preg_match_all("/(All|Current) User Profile +: (.+)/", $profiles_raw, $profiles);
array_shift($profiles);
$r = array();
$scopes = $profiles[0];
$ssids = $profiles[1];
for($i = 0 ; $i < count($scopes); $i++){
$r[$ssids[$i]] = array(
'SSID' => $ssids[$i],
'scope' => $scopes[$i],
);
}
jp($r);
return $r;
}
function phpNetsh_getProfileDetails(){
if(!isset($_POST['SSID'])){
error(400, 'No SSID Specified');
}
$profiles = ob_catch('phpNetsh_getProfiles');
if(!array_key_exists($_POST['SSID'], $profiles)){
error(400, 'No such SSID as ' . $_POST['SSID']);
}
$output = shell_exec('Netsh WLAN export profile "'.$_POST['SSID'].'" key=clear folder="'.$GLOBALS['f']->getDirectory().'"');
preg_match("/Interface profile \".+\" is saved in file \"(.+)\"/", $output, $profileFile);
if(count($profileFile) !== 2){
error(500, 'Could not export profile');
}
$fileContents = $GLOBALS['f']->get($profileFile[1]);
$r = array();
preg_match_all("/<keyMaterial>(.+)<\/keyMaterial>/", $fileContents, $keyMaterial);
if(count($keyMaterial) !== 2 || !isset($keyMaterial[1][0])){
$r['password'] = false;
}else {
$r['password'] = $keyMaterial[1][0];
}
preg_match_all("/<authentication>(.+)<\/authentication>/", $fileContents, $authentication);
if(count($authentication) !== 2 || !isset($authentication[1][0])){
$r['auth'] = false;
}else {
$r['auth'] = $authentication[1][0];
}
jp($r);
return array('profiles' => $profiles, 'fileContents' => $fileContents);
}
function phpNetsh_setProfilePassword(){
if(!isset($_POST['password'])){
error(400,"Incomplete Form Data: No Password Set");
}
$password = htmlspecialchars($_POST['password'], ENT_XML1, 'UTF-8');
$t = ob_catch('phpNetsh_getProfileDetails');
$fileContents = $t['fileContents'];
$fileContents = preg_replace("/<keyMaterial>(.*)<\/keyMaterial>/", "<keyMaterial>".$password."</keyMaterial>", $t['fileContents']);
$file = $GLOBALS['f']->put($fileContents);
$output = shell_exec('Netsh WLAN add profile filename="'.$file.'" user=' . strtolower($t[$_POST['SSID']]['scope']));
if($output !== "Profile ".$_POST['SSID']." is added on interface Wi-Fi.\n"){
throw new Exception(trim(explode("\n",$output)[0]));
} else {
echo json_encode(array('success' => trim(explode("\n",str_replace("added", "updated", $output))[0])));
}
}
try{
if(isset($_POST['action']) && function_exists(ns.$_POST['action'])){
call_user_func(ns.$_POST['action']);
} else {
error(400,"Bad Request");
}
} catch (Exception $e){
jp(array("error" => $e->getMessage()));
}
?> | mit |
AbbyJonesDev/PreschoolOnRails | app/models/newsletter.rb | 669 | class Newsletter < ActiveRecord::Base
has_attached_file :file
validates_attachment :file, :presence => true,
:content_type => { :content_type => "application/pdf"}
validates :date, :presence => true
def self.newest
self.order(date: :desc).first
end
def self.for_year (startYear)
@start = Date.new(startYear, 8, 1) # August of the start year
self.where(date: @[email protected]_year).order(date: :desc)
end
def self.for_current_school_year
@current = Time.now
if @current.month > 7
return Newsletter.for_year @current.year
end
return Newsletter.for_year @current.year - 1
end
end
| mit |
howardjones/network-weathermap | editor-resources/cacti-pick.js | 4638 | "use strict";
/*global jQuery:false */
/*global rra_path:false */
/*global base_url:false */
/*global overlib:false */
/*global aggregate:false */
/*global selected_host:false */
function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
}
function buildUrl(url, parameters) {
var qs = "";
for (var key in parameters) {
if (parameters.hasOwnProperty(key)) {
var value = parameters[key];
qs += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&";
}
}
if (qs.length > 0) {
qs = qs.substring(0, qs.length - 1); //chop off last "&"
url = url + "?" + qs;
}
return url;
}
function applyDSFilterChange(objForm) {
var params = {
'host_id': objForm.host_id.value,
'action': getUrlParameter('action'),
'target': getUrlParameter('target'),
'overlib': objForm.overlib.checked ? 1 : 0,
'aggregate': objForm.aggregate.checked ? 1 : 0
};
document.location = buildUrl("", params);
}
function update_source_link_step2(graphid) {
var graph_url, info_url;
if (typeof window.opener === "object") {
graph_url = base_url + 'graph_image.php?local_graph_id=' + graphid + '&rra_id=0&graph_nolegend=true&graph_height=100&graph_width=300';
info_url = base_url + 'graph.php?rra_id=all&local_graph_id=' + graphid;
opener.document.forms.frmMain.link_infourl.value = info_url;
opener.document.forms.frmMain.link_hover.value = graph_url;
}
window.close();
}
function dataSelected(event) {
var newlocation;
var data_id = $(this).data("source-id");
var path = $(this).data("path");
var fullpath = path.replace(/<path_rra>/, rra_path);
if (document.mini.dsstats.checked) {
fullpath = "8*dsstats:" + data_id + ":traffic_in:traffic_out";
}
console.log(fullpath);
if (window.opener && typeof window.opener === "object") {
if (document.forms.mini.aggregate.checked) {
opener.document.forms.frmMain.link_target.value = opener.document.forms.frmMain.link_target.value + " " + fullpath;
} else {
opener.document.forms.frmMain.link_target.value = fullpath;
}
}
// If it's just a TARGET update, we're done, otherwise go onto step 2 to find a matching graph
if (document.forms.mini.overlib.checked) {
newlocation = 'cacti-pick.php?action=link_step2&dataid=' + data_id;
window.location = newlocation;
} else {
window.close();
}
}
function nodeGraphSelected(event) {
var graph_id = $(this).data("graph-id");
// var width = $(this).data("width");
// var height = $(this).data("height");
var graph_url = base_url + 'graph_image.php?rra_id=0&graph_nolegend=true&graph_height=100&graph_width=300&local_graph_id=' + graph_id;
var info_url = base_url + 'graph.php?rra_id=all&local_graph_id=' + graph_id;
console.log(graph_url);
if (window.opener && typeof window.opener === "object") {
// only set the overlib URL unless the box is checked
if (document.forms.mini.overlib.checked) {
opener.document.forms.frmMain.node_infourl.value = info_url;
}
opener.document.forms.frmMain.node_hover.value = graph_url;
}
window.close();
}
$(document).ready(function () {
$("#dslist li:odd").addClass("row0");
$("#dslist li:even").addClass("row1");
$('#host_id').change(function () {
applyDSFilterChange(document.mini);
});
$("body.data-picker span.ds_includegraph").show();
$("body.data-picker span.aggregate_choice").show();
$("body.data-picker span.ds_dsstats").show();
if (aggregate == 1) {
// TODO: Check what this did before!
document.mini.aggregate.checked = (aggregate == 1 ? true : false);
}
if (overlib == 1) {
// TODO: Check what this did before!
document.mini.overlib.checked = (overlib == 1 ? true : false);
}
if (selected_host >= 0) {
$("select#host_id").val(selected_host);
}
$('span.filter').show();
$('#filterstring').fastLiveFilter("#dslist");
$("body.data-picker #dslist li").click(dataSelected);
$("body.graph-picker #dslist li").click(nodeGraphSelected);
});
| mit |
sschloesser/foodBlog | node_modules/poet/test/helpers.test.js | 6289 | var
Poet = require('../lib/poet'),
express = require('express'),
chai = require('chai'),
should = chai.should(),
expect = chai.expect;
describe('helpers.getTags()', function () {
it('should return all tags, sorted and unique', function (done) {
setup(function (poet) {
var tags = poet.helpers.getTags();
expect(tags).to.have.length(4);
expect(tags[0]).to.be.equal('a');
expect(tags[1]).to.be.equal('b');
expect(tags[2]).to.be.equal('c');
expect(tags[3]).to.be.equal('d');
done();
}, done);
});
});
describe('helpers.getCategories()', function () {
it('should return all categories, sorted and unique', function (done) {
setup(function (poet) {
var cats = poet.helpers.getCategories();
expect(cats).to.have.length(2);
expect(cats[0]).to.be.equal('other cat');
expect(cats[1]).to.be.equal('testing');
done();
}, done);
});
});
describe('helpers[tag|category|page]URL()', function () {
it('replaces the parameter with value for [tag|page|category]URL', function (done) {
setup(function (poet) {
expect(poet.helpers.tagURL('glitchstep')).to.be.equal('/tag/glitchstep');
expect(poet.helpers.categoryURL('glitchstep')).to.be.equal('/category/glitchstep');
expect(poet.helpers.pageURL('glitchstep')).to.be.equal('/page/glitchstep');
done();
}, done);
});
it('encodes the URL safely in [tag|category|page]URL', function (done) {
setup(function (poet) {
expect(poet.helpers.categoryURL('phat bass')).to.be.equal('/category/phat%20bass');
expect(poet.helpers.pageURL('phat bass')).to.be.equal('/page/phat%20bass');
expect(poet.helpers.tagURL('phat bass')).to.be.equal('/tag/phat%20bass');
done();
}, done);
});
});
describe('helpers.getPostCount()', function () {
it('should return correct count of posts', function (done) {
setup(function (poet) {
expect(poet.helpers.getPostCount()).to.be.equal(6);
expect(poet.helpers.getPosts().length).to.be.equal(6);
done();
}, done);
});
it('should return correct count of posts with `showDrafts` false', function (done) {
setup(function (poet) {
poet.options.showDrafts = false;
expect(poet.helpers.getPostCount()).to.be.equal(5);
expect(poet.helpers.getPosts().length).to.be.equal(5);
done();
}, done);
});
it('should return correct count of posts with `showFuture` false', function (done) {
setup(function (poet) {
poet.options.showFuture = false;
expect(poet.helpers.getPostCount()).to.be.equal(5);
expect(poet.helpers.getPosts().length).to.be.equal(5);
done();
}, done);
});
});
describe('helpers.getPost(title)', function () {
it('should return the correct post associated with `title`', function (done) {
setup(function (poet) {
var post = poet.helpers.getPost('jadeTemplate');
expect(post.slug).to.be.equal('jadeTemplate');
expect(post.title).to.be.equal('Jade Test');
done();
}, done);
});
});
describe('helpers.getPosts()', function () {
it('should return all posts if both `from` or `to` are not specified', function (done) {
setup(function (poet) {
expect(poet.helpers.getPosts().length).to.be.equal(6);
expect(poet.helpers.getPosts(3).length).to.be.equal(6);
expect(poet.helpers.getPosts(undefined, 3).length).to.be.equal(6);
done();
}, done);
});
it('should return a range if both `from` and `to` are specified', function (done) {
setup(function (poet) {
expect(poet.helpers.getPosts(1,3).length).to.be.equal(2);
done();
}, done);
});
});
describe('helpers.getPageCount()', function () {
it('returns the correct number of pages', function (done) {
setup(function (poet) {
// Based off of 6 posts and default postsPerPage of 5
expect(poet.helpers.getPageCount()).to.be.equal(2);
done();
}, done);
});
it('returns the correct number of pages based off of drafts', function (done) {
setup(function (poet) {
// Based off of 5 non-draft posts and default postsPerPage of 5
poet.options.showDrafts = false;
expect(poet.helpers.getPageCount()).to.be.equal(1);
done();
}, done);
});
});
describe('helpers.postsWithTag()', function () {
it('should return posts ordered by date, newest first', function (done) {
setup(function (poet) {
var posts = poet.helpers.postsWithTag('a');
(posts[0].date.getTime() > posts[1].date.getTime()).should.equal(true);
(posts[1].date.getTime() > posts[2].date.getTime()).should.equal(true);
done();
}, done);
});
it('should not see drafts when `showDrafts` false', function (done) {
setup(function (poet) {
poet.options.showDrafts = false;
expect(poet.helpers.postsWithTag('d').length).to.be.equal(1);
done();
}, done);
});
it('should not see future posts when `showFuture` false', function (done) {
setup(function (poet) {
poet.options.showFuture = false;
expect(poet.helpers.postsWithTag('c').length).to.be.equal(0);
done();
}, done);
});
});
describe('helpers.postsWithCategories()', function () {
it('should return posts ordered by date, newest first', function (done) {
setup(function (poet) {
var posts = poet.helpers.postsWithCategory('testing');
(posts[0].date.getTime() > posts[1].date.getTime()).should.equal(true);
(posts[1].date.getTime() > posts[2].date.getTime()).should.equal(true);
done();
}, done);
});
it('should not see drafts when `showDrafts` false', function (done) {
setup(function (poet) {
poet.options.showDrafts = false;
var posts = poet.helpers.postsWithCategory('other cat');
(posts.length).should.equal(1);
done();
}, done);
});
it('should not see future posts when `showFuture` false', function (done) {
setup(function (poet) {
poet.options.showFuture = false;
expect(poet.helpers.postsWithCategory('testing').length).to.be.equal(2);
done();
}, done);
});
});
function setup (callback, done) {
var app = express();
var poet = Poet(app, {
posts: './test/_postsJson'
});
poet.init().then(callback, done).then(null, done);
}
| mit |
ishani/InSiDe | SiDcore/SiDComponent.cs | 3084 | /**
* SiDcore ~ a C# class library for creating and manipulating data for Jason Rohrer's Sleep Is Death (http://sleepisdeath.net/)
*
* Written by Harry Denholm (Ishani) April 2010
* http://www.ishani.org/
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Drawing;
using System.Security.Cryptography;
namespace SiDcore
{
public abstract class SiDComponent
{
#region NameAndType
private String componentName = "nothing";
// generic component name, 10 character maximum
public String Name
{
set
{
// maximum allowed component name length is 10 - SiD stores names as 11 byte arrays (inc null terminator)
componentName = value.Substring(0, Math.Min(value.Length, 10));
}
get { return componentName; }
}
virtual public String ResourceTypeName
{
get
{
return getResourceTypeName(this.GetType());
}
}
// used to identify this component in a Resource Pack (or used in factory function)
public static String getResourceTypeName(Type t)
{
ResourceTypeAttribute[] attributes = (ResourceTypeAttribute[])t.GetCustomAttributes(typeof(ResourceTypeAttribute), false);
if (attributes.Length == 0)
{
throw (new InvalidDataException("trying to get resource type name of unsupported component type (Blob?)"));
}
return attributes[0].RTName;
}
#endregion
/**
* Load data from an unpacked SiD resource (eg. "SleepIsDeath_v13\resourceCache\sprite\0D7DF32654AF")
*/
public void LoadFromFile(String filename)
{
FileStream fs = File.Open(filename, FileMode.Open);
using (fs)
{
using (BinaryReader b = new BinaryReader(fs))
{
LoadFromByteStream(b, (Int32)b.BaseStream.Length);
}
}
}
public void SaveToFile(String filename)
{
FileStream fs = File.Open(filename, FileMode.Create);
using (fs)
{
using (BinaryWriter b = new BinaryWriter(fs))
{
byte[] rawBytes = SaveToByteStream();
b.Write(rawBytes, 0, rawBytes.Length);
}
}
}
#region Abstracts
// load component data from a byte stream
abstract public void LoadFromByteStream(BinaryReader br, Int32 streamLength);
// serialize component data to a byte stream
abstract public byte[] SaveToByteStream();
// render the component to a bitmap; we must pass in an RP for any dependant-asset look-up
abstract public Bitmap RenderToBitmap(ResourcePack rp);
#endregion
#region UID
// default UID is the SHA1 of the byte stream representing this resource
public virtual UID getUID()
{
byte[] buffer = SaveToByteStream();
SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
byte[] hashResult = cryptoTransformSHA1.ComputeHash(buffer);
// UID is only the first 6 bytes of the SHA1
UID uid = new UID(hashResult);
return uid;
}
#endregion
}
}
| mit |
jschoolcraft/urlagg | vendor/plugins/typus/test/functional/admin/resources_controller_posts_views_test.rb | 3451 | require "test/test_helper"
class Admin::PostsControllerTest < ActionController::TestCase
context "Index" do
setup do
get :index
end
should "render index and validates_presence_of_custom_partials" do
assert_match "posts#_index.html.erb", @response.body
end
should "render_index_and_verify_page_title" do
assert_select "title", "Posts"
end
should "render index_and_show_add_entry_link" do
assert_select "#sidebar ul" do
assert_select "li", "Add new"
end
end
should "render_index_and_show_trash_item_image" do
assert_response :success
assert_select '.trash', 'Trash'
end
end
context "New" do
setup do
get :new
end
should "render new and partials_on_new" do
assert_match "posts#_new.html.erb", @response.body
end
should "render new and verify page title" do
assert_select "title", "New Post"
end
end
context "Edit" do
setup do
get :edit, { :id => Factory(:post).id }
end
should "render_edit_and_verify_presence_of_custom_partials" do
assert_match "posts#_edit.html.erb", @response.body
end
should "render_edit_and_verify_page_title" do
assert_select "title", "Edit Post"
end
end
context "Show" do
setup do
get :show, { :id => Factory(:post).id }
end
should "render_show_and_verify_presence_of_custom_partials" do
assert_match "posts#_show.html.erb", @response.body
end
should "render_show_and_verify_page_title" do
assert_select "title", "Show Post"
end
end
should "get_index_and_render_edit_or_show_links" do
%w(edit show).each do |action|
Typus::Resource.expects(:default_action_on_item).at_least_once.returns(action)
get :index
Post.all.each do |post|
assert_match "/posts/#{action}/#{post.id}", @response.body
end
end
end
context "Designer" do
setup do
@typus_user = Factory(:typus_user, :email => "[email protected]", :role => "designer")
@request.session[:typus_user_id] = @typus_user.id
end
should "render_index_and_not_show_add_entry_link" do
get :index
assert_response :success
assert_no_match /Add Post/, @response.body
end
should "render_index_and_not_show_trash_image" do
get :index
assert_response :success
assert_select ".trash", false
end
end
context "Editor" do
setup do
@typus_user = Factory(:typus_user, :email => "[email protected]", :role => "editor")
@request.session[:typus_user_id] = @typus_user.id
end
should "get_index_and_render_edit_or_show_links_on_owned_records" do
get :index
Post.all.each do |post|
action = post.owned_by?(@typus_user) ? "edit" : "show"
assert_match "/posts/#{action}/#{post.id}", @response.body
end
end
should "get_index_and_render_edit_or_show_on_only_user_items" do
%w(edit show).each do |action|
Typus::Resource.stubs(:only_user_items).returns(true)
Typus::Resource.stubs(:default_action_on_item).returns(action)
get :index
Post.all.each do |post|
if post.owned_by?(@typus_user)
assert_match "/posts/#{action}/#{post.id}", @response.body
else
assert_no_match /\/posts\/#{action}\/#{post.id}/, @response.body
end
end
end
end
end
end
| mit |
cpoff/static-charge | routes/index.js | 1685 | var express = require('express');
var router = express.Router();
var fs = require('fs');
var marked = require('marked');
var moment = require('moment');
moment().format();
var postsDir = __dirname + '/../posts/';
fs.readdir(postsDir, function(error, directoryContents) {
if (error) {
throw new Error(error);
}
var posts = directoryContents.map(function(filename) {
var now = moment();
var postName = filename.replace('.md', '');
var contents = fs.readFileSync(postsDir + filename, {encoding: 'utf-8'});
var metaString = contents.split('---\n')[1];
var content = contents.split('---\n')[2];
var more = contents.split('---\n')[3];
var lines = metaString.split('\n');
var metaData = {};
lines.forEach(function(line) {
var array = line.split(': ');
var key = array[0];
var value = array[1];
if(key) {
metaData[key] = value;
}
});
var timestamp = moment(metaData.date).format('X');
// console.log(timestamp);
return {postName: postName, contents: content, postTitle: metaData.title, postAuthor: metaData.author, postDate: metaData.date};
});
// SORT FUNCTION HERE
posts.sort(function (var1, var2) {
var a = var1.postDate,
b = var2.postDate;
if (a > b) return 1;
if (a < b) return -1;
else return 0;
});
console.log(posts);
// END SORT FUNCTION
router.get('/', function(request, response) {
response.render('index', {posts: posts, title: 'all posts'} )
});
posts.forEach(function(post) {
router.get('/' + post.postName, function(request, response) {
response.render('post', post);
});
});
});
module.exports = router;
| mit |
dustinmoris/Lanem | Lanem/ErrorFilters/NoErrorFilter.cs | 205 | using System;
namespace Lanem.ErrorFilters
{
public class NoErrorFilter : IErrorFilter
{
public bool SkipError(Exception exception)
{
return false;
}
}
} | mit |
tang85718/quickframework | src/main/java/com/lidroid/xutils/HttpUtils.java | 14806 | /*
* Copyright (c) 2013. wyouflf ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lidroid.xutils;
import android.text.TextUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.*;
import com.lidroid.xutils.http.callback.HttpRedirectHandler;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.DefaultSSLSocketFactory;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.RetryHandler;
import com.lidroid.xutils.http.client.entity.GZipDecompressingEntity;
import com.lidroid.xutils.task.PriorityExecutor;
import com.lidroid.xutils.util.OtherUtils;
import org.apache.http.*;
import org.apache.http.client.CookieStore;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import java.io.File;
import java.io.IOException;
@SuppressWarnings("unused")
public class HttpUtils {
public final static HttpCache sHttpCache = new HttpCache();
private final static int DEFAULT_CONN_TIMEOUT = 1000 * 15; // 15s
private final static int DEFAULT_RETRY_TIMES = 3;
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";
private final static int DEFAULT_POOL_SIZE = 3;
private final static PriorityExecutor EXECUTOR = new PriorityExecutor(DEFAULT_POOL_SIZE);
private final DefaultHttpClient httpClient;
// ************************************ default settings & fields ****************************
private final HttpContext httpContext = new BasicHttpContext();
private HttpRedirectHandler httpRedirectHandler;
private String responseTextCharset = HTTP.UTF_8;
private long currentRequestExpiry = HttpCache.getDefaultExpiryTime();
public HttpUtils() {
this(HttpUtils.DEFAULT_CONN_TIMEOUT, null);
}
public HttpUtils(int connTimeout) {
this(connTimeout, null);
}
public HttpUtils(String userAgent) {
this(HttpUtils.DEFAULT_CONN_TIMEOUT, userAgent);
}
public HttpUtils(int connTimeout, String userAgent) {
HttpParams params = new BasicHttpParams();
ConnManagerParams.setTimeout(params, connTimeout);
HttpConnectionParams.setSoTimeout(params, connTimeout);
HttpConnectionParams.setConnectionTimeout(params, connTimeout);
if (TextUtils.isEmpty(userAgent)) {
userAgent = OtherUtils.getUserAgent(null);
}
HttpProtocolParams.setUserAgent(params, userAgent);
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443));
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext) throws org.apache.http.HttpException, IOException {
if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
}
});
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext httpContext) throws org.apache.http.HttpException, IOException {
final HttpEntity entity = response.getEntity();
if (entity == null) {
return;
}
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GZipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
}
public HttpClient getHttpClient() {
return this.httpClient;
}
// ***************************************** config *******************************************
public HttpUtils configResponseTextCharset(String charSet) {
if (!TextUtils.isEmpty(charSet)) {
this.responseTextCharset = charSet;
}
return this;
}
public HttpUtils configHttpRedirectHandler(HttpRedirectHandler httpRedirectHandler) {
this.httpRedirectHandler = httpRedirectHandler;
return this;
}
public HttpUtils configHttpCacheSize(int httpCacheSize) {
sHttpCache.setCacheSize(httpCacheSize);
return this;
}
public HttpUtils configDefaultHttpCacheExpiry(long defaultExpiry) {
HttpCache.setDefaultExpiryTime(defaultExpiry);
currentRequestExpiry = HttpCache.getDefaultExpiryTime();
return this;
}
public HttpUtils configCurrentHttpCacheExpiry(long currRequestExpiry) {
this.currentRequestExpiry = currRequestExpiry;
return this;
}
public HttpUtils configCookieStore(CookieStore cookieStore) {
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
return this;
}
public HttpUtils configUserAgent(String userAgent) {
HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
return this;
}
public HttpUtils configTimeout(int timeout) {
final HttpParams httpParams = this.httpClient.getParams();
ConnManagerParams.setTimeout(httpParams, timeout);
HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
return this;
}
public HttpUtils configSoTimeout(int timeout) {
final HttpParams httpParams = this.httpClient.getParams();
HttpConnectionParams.setSoTimeout(httpParams, timeout);
return this;
}
public HttpUtils configRegisterScheme(Scheme scheme) {
this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
return this;
}
public HttpUtils configSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
Scheme scheme = new Scheme("https", sslSocketFactory, 443);
this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
return this;
}
public HttpUtils configRequestRetryCount(int count) {
this.httpClient.setHttpRequestRetryHandler(new RetryHandler(count));
return this;
}
public HttpUtils configRequestThreadPoolSize(int threadPoolSize) {
HttpUtils.EXECUTOR.setPoolSize(threadPoolSize);
return this;
}
// ***************************************** send request *******************************************
public <T> HttpHandler<T> send(HttpRequest.HttpMethod method, String url, RequestCallBack<T> callBack) {
return send(method, url, null, callBack);
}
public <T> HttpHandler<T> send(HttpRequest.HttpMethod method, String url, RequestParams params, RequestCallBack<T> callBack) {
if (url == null) throw new IllegalArgumentException("url may not be null");
HttpRequest request = new HttpRequest(method, url);
return sendRequest(request, params, callBack);
}
public ResponseStream sendSync(HttpRequest.HttpMethod method, String url) throws HttpException {
return sendSync(method, url, null);
}
public ResponseStream sendSync(HttpRequest.HttpMethod method, String url, RequestParams params) throws HttpException {
if (url == null) throw new IllegalArgumentException("url may not be null");
HttpRequest request = new HttpRequest(method, url);
return sendSyncRequest(request, params);
}
// ***************************************** download *******************************************
public HttpHandler<File> download(HttpRequest.HttpMethod get, String url, String target,
boolean b, boolean b1, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, null, false, false, callback);
}
public HttpHandler<File> download(String url, String target,
boolean autoResume, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, null, autoResume, false, callback);
}
public HttpHandler<File> download(String url, String target,
boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, null, autoResume, autoRename, callback);
}
public HttpHandler<File> download(String url, String target,
RequestParams params, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, params, false, false, callback);
}
public HttpHandler<File> download(String url, String target,
RequestParams params, boolean autoResume, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, params, autoResume, false, callback);
}
public HttpHandler<File> download(String url, String target,
RequestParams params, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, params, autoResume, autoRename, callback);
}
public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,
RequestParams params, RequestCallBack<File> callback) {
return download(method, url, target, params, false, false, callback);
}
public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,
RequestParams params, boolean autoResume, RequestCallBack<File> callback) {
return download(method, url, target, params, autoResume, false, callback);
}
public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,
RequestParams params, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {
if (url == null) throw new IllegalArgumentException("url may not be null");
if (target == null) throw new IllegalArgumentException("target may not be null");
HttpRequest request = new HttpRequest(method, url);
// add default provider for ANY HOST
CredentialsProvider provider = request.getCredentials();
if (provider != null) {
httpClient.setCredentialsProvider(provider);
}
HttpHandler<File> handler = new HttpHandler<File>(httpClient, httpContext, responseTextCharset, callback);
handler.setExpiry(currentRequestExpiry);
handler.setHttpRedirectHandler(httpRedirectHandler);
if (params != null) {
request.setRequestParams(params, handler);
handler.setPriority(params.getPriority());
}
handler.executeOnExecutor(EXECUTOR, request, target, autoResume, autoRename);
return handler;
}
////////////////////////////////////////////////////////////////////////////////////////////////
private <T> HttpHandler<T> sendRequest(HttpRequest request, RequestParams params, RequestCallBack<T> callBack) {
// add default provider for ANY HOST
CredentialsProvider provider = request.getCredentials();
if (provider != null) {
httpClient.setCredentialsProvider(provider);
}
HttpHandler<T> handler = new HttpHandler<T>(httpClient, httpContext, responseTextCharset, callBack);
handler.setExpiry(currentRequestExpiry);
handler.setHttpRedirectHandler(httpRedirectHandler);
request.setRequestParams(params, handler);
if (params != null) {
handler.setPriority(params.getPriority());
}
handler.executeOnExecutor(EXECUTOR, request);
return handler;
}
private ResponseStream sendSyncRequest(HttpRequest request, RequestParams params) throws HttpException {
// add default provider for ANY HOST
CredentialsProvider provider = request.getCredentials();
if (provider != null) {
httpClient.setCredentialsProvider(provider);
}
SyncHttpHandler handler = new SyncHttpHandler(httpClient, httpContext, responseTextCharset);
handler.setExpiry(currentRequestExpiry);
handler.setHttpRedirectHandler(httpRedirectHandler);
request.setRequestParams(params);
return handler.sendRequest(request);
}
}
| mit |
twar59/ember-jquery-datatables | config/environment.js | 880 | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// LOG_MODULE_RESOLVER is needed for pre-1.6.0
ENV.LOG_MODULE_RESOLVER = false;
ENV.APP.LOG_RESOLVER = false;
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_MODULE_RESOLVER = false;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = false;
}
if (environment === 'production') {
}
return ENV;
};
| mit |
SoftMetalicana/RogueMetalicana | RogueMetalicana/RogueMetalicana/UnitsInterfaces/IFightable.cs | 364 | namespace RogueMetalicana.UnitsInterfaces
{
/// <summary>
/// For the units that are going to battle.
/// </summary>
public interface IFightable
{
double Health { get; set; }
int Defense { get; set; }
int Damage { get; set; }
bool IsAlive { get; set; }
void TakeDamage(double damageToTake);
}
}
| mit |
xylsxyls/xueyelingshuang | src/QSQLite/QSQLite/src/QSQLitePrepareStatement.cpp | 2338 | #include "QSQLitePrepareStatement.h"
#include <QSqlQuery>
#include <QVariant>
#include <QSqlDatabase>
QSQLitePrepareStatement::QSQLitePrepareStatement(QSqlDatabase* dataBase) :
m_spSqlQuery(nullptr)
{
m_spSqlQuery.reset(new QSqlQuery(*dataBase));
}
bool QSQLitePrepareStatement::empty()
{
return m_spSqlQuery == nullptr;
}
bool QSQLitePrepareStatement::prepare(const std::string& sqlString)
{
if (m_spSqlQuery == nullptr)
{
return false;
}
try
{
return m_spSqlQuery->prepare(sqlString.c_str());
}
catch (...)
{
return false;
}
}
void QSQLitePrepareStatement::setBlob(uint32_t pos, const std::string& value)
{
if (value.empty() || m_spSqlQuery == nullptr)
{
return;
}
try
{
m_spSqlQuery->bindValue(pos, QByteArray(&value[0], (int32_t)value.size()));
}
catch (...)
{
}
}
void QSQLitePrepareStatement::setBoolean(uint32_t pos, bool value)
{
if (m_spSqlQuery == nullptr)
{
return;
}
try
{
m_spSqlQuery->bindValue(pos, value);
}
catch (...)
{
}
}
void QSQLitePrepareStatement::setInt(uint32_t pos, int32_t value)
{
if (m_spSqlQuery == nullptr)
{
return;
}
try
{
m_spSqlQuery->bindValue(pos, value);
}
catch (...)
{
}
}
void QSQLitePrepareStatement::setDouble(uint32_t pos, double value)
{
if (m_spSqlQuery == nullptr)
{
return;
}
try
{
m_spSqlQuery->bindValue(pos, value);
}
catch (...)
{
}
}
void QSQLitePrepareStatement::setString(uint32_t pos, const std::string& value)
{
if (m_spSqlQuery == nullptr)
{
return;
}
try
{
m_spSqlQuery->bindValue(pos, value.c_str());
}
catch (...)
{
}
}
void QSQLitePrepareStatement::setUnsignedInt(uint32_t pos, uint32_t value)
{
if (m_spSqlQuery == nullptr)
{
return;
}
try
{
m_spSqlQuery->bindValue(pos, value);
}
catch (...)
{
}
}
void QSQLitePrepareStatement::setLongLong(uint32_t pos, int64_t value)
{
if (m_spSqlQuery == nullptr)
{
return;
}
try
{
m_spSqlQuery->bindValue(pos, value);
}
catch (...)
{
}
}
void QSQLitePrepareStatement::setUnsignedLongLong(uint32_t pos, uint64_t value)
{
if (m_spSqlQuery == nullptr)
{
return;
}
try
{
m_spSqlQuery->bindValue(pos, value);
}
catch (...)
{
}
}
bool QSQLitePrepareStatement::exec()
{
if (m_spSqlQuery == nullptr)
{
return false;
}
try
{
return m_spSqlQuery->exec();
}
catch (...)
{
return false;
}
} | mit |
jonathanaraul/donde-quiero2 | src/Project/BackBundle/Entity/ContactoRepository.php | 748 | <?php
namespace Project\BackBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* ContactoRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ContactoRepository extends EntityRepository
{
public function findAllOrderedById()
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM ProjectBackBundle:Contacto p ORDER BY p.id DESC'
)
->getResult();
}
public function getAllLength()
{
return $this->getEntityManager()
->createQuery(
'SELECT COUNT(u.id) FROM ProjectBackBundle:Contacto u'
)
->getSingleScalarResult();
}
}
| mit |
fgrid/iso20022 | InvestmentAccount45.go | 2163 | package iso20022
// Account between an investor(s) and a fund manager or a fund. The account can contain holdings in any investment fund or investment fund class managed (or distributed) by the fund manager, within the same fund family.
type InvestmentAccount45 struct {
// Unique and unambiguous identification for the account between the account owner and the account servicer.
AccountIdentification *AccountIdentification1 `xml:"AcctId"`
// Name of the account. It provides an additional means of identification, and is designated by the account servicer in agreement with the account owner.
AccountName *Max35Text `xml:"AcctNm,omitempty"`
// Supplementary registration information applying to a specific block of units for dealing and reporting purposes. The supplementary registration information may be used when all the units are registered, for example, to a funds supermarket, but holdings for each investor have to reconciled individually.
AccountDesignation *Max35Text `xml:"AcctDsgnt,omitempty"`
// Identification of the owner of the account.
OwnerIdentification *OwnerIdentification1Choice `xml:"OwnrId,omitempty"`
// Party that manages the account on behalf of the account owner, that is manages the registration and booking of entries on the account, calculates balances on the account and provides information about the account.
AccountServicer *PartyIdentification2Choice `xml:"AcctSvcr,omitempty"`
}
func (i *InvestmentAccount45) AddAccountIdentification() *AccountIdentification1 {
i.AccountIdentification = new(AccountIdentification1)
return i.AccountIdentification
}
func (i *InvestmentAccount45) SetAccountName(value string) {
i.AccountName = (*Max35Text)(&value)
}
func (i *InvestmentAccount45) SetAccountDesignation(value string) {
i.AccountDesignation = (*Max35Text)(&value)
}
func (i *InvestmentAccount45) AddOwnerIdentification() *OwnerIdentification1Choice {
i.OwnerIdentification = new(OwnerIdentification1Choice)
return i.OwnerIdentification
}
func (i *InvestmentAccount45) AddAccountServicer() *PartyIdentification2Choice {
i.AccountServicer = new(PartyIdentification2Choice)
return i.AccountServicer
}
| mit |
kevinly7/jumo | js/logout.js | 276 | $(document).ready(function(){
$('.logout1').click(function(){
$.ajax({
type: "POST",
url: 'logout.php',
data:{action:'call_this'},
success:function(html) {
// alert(html);
}
});
});
}); | mit |
DreamHacks/dreamdota | DreamWarcraft/Build Tools/PackFiles.py | 860 | import xml.etree.ElementTree as ET
import checkmod
DEBUG = 0
if DEBUG:
XMLPath = '../../Package.xml'
EmbedFile = '../../DreamInstaller/Embed.inc'
CodeFile = '../../DreamInstaller/Files.inc'
else:
XMLPath = '../Package.xml'
EmbedFile = 'Embed.inc'
CodeFile = 'Files.inc'
def Init():
# XML Data
root = ET.parse(XMLPath).getroot();
f = open(EmbedFile, 'w')
fc = open(CodeFile, 'w')
i = 0
for file in root:
i = i + 1
name = file.get('name')
path = file.text
f.write('%d\tRCDATA\t"%s"\n' % (i, path))
fc.write('{L"%s", %d},\n' % (name, i));
fc.close()
f.close()
def Main():
Init()
if __name__ == '__main__':
if (not checkmod.check(XMLPath) and not DEBUG):
print('PackFiles: No change on xml, skip.')
else:
Main()
| mit |
cosminrentea/gobbler | server/connector/request.go | 453 | package connector
import "github.com/cosminrentea/gobbler/protocol"
type Request interface {
Subscriber() Subscriber
Message() *protocol.Message
}
type request struct {
subscriber Subscriber
message *protocol.Message
}
func NewRequest(s Subscriber, m *protocol.Message) Request {
return &request{s, m}
}
func (r *request) Subscriber() Subscriber {
return r.subscriber
}
func (r *request) Message() *protocol.Message {
return r.message
}
| mit |
spaceify/app-lightcontrol | application/www/src/app/app.component.ts | 3344 | import { ChangeDetectionStrategy, Component, OnInit, HostListener } from '@angular/core';
import { LightControlComponent } from './lightcontrol.component';
import { LightControlService } from './lightcontrol.service';
import {Light} from './light'
import {Gateway} from './gateway'
//import { TreeModule } from 'angular2-tree-component';
@Component({
selector: 'app-root',
//changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: 'app.component.html',
styles: [`
.center {
padding: 20px;
width: 300px;
margin: 0 auto;
//background-color: lightgray;
//background: linear-gradient(to bottom, darkgray, lightgray);
}
`],
//providers: [LightControlService]
})
export class AppComponent implements OnInit{
//lights : Lig
selectedLight : Light;
lights : Light[] = null;
lightdata : Gateway[] = null;
public tabs:Array<any> = [
{title: 'Light 1', content: '1'},
{title: 'Light 2', content: '2', disabled: false},
{title: 'Light 3', content: '3', removable: false}
];
@HostListener('window:load', ['$event'])
spaceifyReady(){
console.log("spaceifyReady from app.component");
this.lightService.spaceifyReady();;
}
/*
nodes = [
{
id: 1,
name: 'root1',
children: [
{ id: 2, name: 'child1' },
{ id: 3, name: 'child2' }
]
},
{
id: 4,
name: 'root2',
children: [
{ id: 5, name: 'child2.1' },
{
id: 6,
name: 'child2.2',
children: [
{ id: 7, name: 'subsub' }
]
}
]
}
];
*/
nodes : any = [];
//public activeTab : number;
//public selectedLight : Light = null;
constructor(private lightService: LightControlService){
//this.lights.push( new LightControlComponent());
}
public buildTree(){
let unique_id = 0;
function uuid(){
return unique_id++;
};
for(let gateway of this.lightService.getLightTree()){
var children : any;
for(let light of gateway.lights){
var child = {id : uuid(), name: light.name};
children.push(child);
}
var gw = {id : uuid(), name: gateway.name, isExpanded: true, children : children};
this.nodes.push(gw);
}
/*
[
{
id: 1,
name: 'root1',
isExpanded: true,
children: [
{
id: 2,
name: 'child1'
}, {
id: 3,
name: 'child2'
}
]
}
]
*/
}
public selectLight(light : Light){
this.selectedLight = light;
}
public setActiveTab(index:number):void {
this.tabs[index].active = true;
};
public ngOnInit(){
this.lights = this.lightService.getLights();
//console.log(this.lights);
// this.selectedLight = this.lights[1];
//this.lightdata = this.lightService.getLightTree();
this.buildTree();
console.log(this.nodes);
}
}
| mit |
theganyo/usergrid-objects-node | lib/usergrid/usergrid_entity.js | 6179 | 'use strict';
// usergrid entity instance methods
var _ = require('lodash');
var ValidationErrors = require('./validation_errors');
var helpers = require('./helpers');
var translateSDKCallback = helpers.translateSDKCallback;
var usergrid_sdk = require('usergrid');
var async = require('async');
var inflection = require('inflection');
var UsergridEntity = function() {
// persistence
this.getUUID = function() {
return this.uuid;
};
this.isPersisted = function() {
return !!this.uuid;
};
this.save = function(cb) {
if (!this.isValid()) { return cb(this.getErrors()); }
var self = this;
var connectedEntities;
_.each(this._class._usergrid.connections, function(connectionClass, connectionName) {
var items = self.get(connectionName);
if (items) {
if (!_.isArray(items) || items.length === 0) {
items = null;
} else {
items = _.map(items, function(item) {
if (connectionClass.isInstance(item)) { return item; }
return connectionClass.new(item);
});
if (!connectedEntities) { connectedEntities = []; }
connectedEntities.push({ name: connectionName, items: items });
}
delete(self._data[connectionName]);
}
});
// validate connected entities
// todo: capture all entities errors?
if (connectedEntities) {
for (var i = 0; i < connectedEntities.length; i++) {
var connection = connectedEntities[i];
var EntityClass = self._class._usergrid.connections[connection.name];
for (var j = 0; j < connection.items.length; j++) {
var item = connection.items[j];
var entity = (EntityClass.isInstance(item)) ? item : EntityClass.new(item);
if (!entity.isValid()) {
return cb(entity.getErrors());
}
}
}
}
// this deletes and replaces all connected entities that are included in the request
// todo: this heuristic is heavy-handed and may not work in all cases
usergrid_sdk.entity.prototype.save.call(this, translateSDKCallback(function(err, reply) { // super.save()
if (err || !connectedEntities) { return cb(err, self); }
async.each(connectedEntities,
function(connection, cb) {
async.waterfall([
function(cb) { // delete all connected entities of this type
var functionName = 'deleteAll' + inflection.camelize(connection.name);
self[functionName].call(self, cb);
},
function(reply, cb) { // optimize to single remote call for multiple-create case
var EntityClass = self._class._usergrid.connections[connection.name];
EntityClass.create(connection.items, cb);
},
function(entities, cb) { // create connections
var func = self['add' + inflection.singularize(inflection.camelize(connection.name))];
async.each(entities,
function(entity, cb) {
func.call(self, entity, cb);
}, cb);
}
], cb);
}, function(err) {
cb(err, self);
}
);
}));
};
this.delete = function(cb) {
var self = this;
this.destroy(translateSDKCallback(function(err, reply) {
cb(err, self);
}));
};
// updateAttributes locally and save to server
this.update = function(attributes, cb) {
this.assignAttributes(attributes);
this.save(cb);
};
// updates locally, no call to server
this.assignAttributes = function(attributes) {
if (!this._data) { this._data = {}; }
var self = this;
_.forOwn(attributes, function(v, k) {
self.set(k, v);
});
return this;
};
// defines a property for a persistent attribute on this instance
this.attr = function(name, readOnly) {
var funcs = {};
funcs.get = function() { return this.get(name); };
if (!readOnly) {
funcs.set = function(v) { this.set(name, v); };
}
Object.defineProperty(this, name, funcs);
};
// connections
// connectedType is the defined() type of the connected entity
this.getConnectedEntities = function(name, connectedType, options, cb) {
if (_.isFunction(options)) { cb = options; options = undefined; }
// call up to the sdk getConnections
this.getConnections(name, options, function(err, reply) {
if (err) { return translateSDKCallback(cb); }
var entities = _.map(reply.entities, function(entity) {
return connectedType.new(entity);
});
cb(null, entities);
});
};
// hash of (plural) name -> path
this.getConnectingPaths = function() {
return this._data.metadata ? this._data.metadata.connecting : undefined;
};
// hash of (plural) name -> path
this.getConnectionPaths = function() {
return this._data.metadata ? this._data.metadata.connected : undefined;
};
// validation
this.addError = function(attribute, error) {
if (!this._errors) { this._errors = new ValidationErrors(); }
this._errors.addError(attribute, error);
};
this.clearErrors = function() {
this._errors = new ValidationErrors();
};
this.getErrors = function() {
return this._errors;
};
this.validate = function() {
var self = this;
self.clearErrors();
var validations = this._class._usergrid.validations;
_.each(validations, function(validations, name) {
var value = self.get(name);
_.each(validations, function(validator) {
var err = validator(value);
if (err) { self.addError(name, err); }
});
});
return self._errors;
};
this.isValid = function() {
return !(this.validate().hasErrors());
};
// utility
this.toString = function() {
var str = '';
if (this._data) {
if (this._data.type) {
str += this._data.type;
}
if (this._data.name) {
str += '[' + this._data.name + ']';
} else {
str += '[' + this._data.uuid + ']';
}
} else {
str = '{}';
}
return str;
};
this.toJSON = function() {
return this._data;
};
};
module.exports = UsergridEntity;
| mit |
Camilochemane/Teste2 | public/modules/filmes/controllers/filmes.client.controller.js | 1714 | 'use strict';
// Filmes controller
angular.module('filmes').controller('FilmesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Filmes',
function($scope, $stateParams, $location, Authentication, Filmes) {
$scope.authentication = Authentication;
// Create new Filme
$scope.create = function() {
// Create new Filme object
var filme = new Filmes ({
titulo: this.titulo,
sinopse: this.sinopse,
categoria: this.categoria,
actorPrincipal: this.actorPrincipal,
actor: this.actor,
estado: this.estado
});
// Redirect after save
filme.$save(function(response) {
$location.path('filmes/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.direct= function(){
$location.path('filmes/create');
};
// Remove existing Filme
$scope.remove = function(filme) {
if ( filme ) {
filme.$remove();
for (var i in $scope.filmes) {
if ($scope.filmes [i] === filme) {
$scope.filmes.splice(i, 1);
}
}
} else {
$scope.filme.$remove(function() {
$location.path('filmes');
});
}
};
// Update existing Filme
$scope.update = function() {
var filme = $scope.filme;
filme.$update(function() {
$location.path('filmes/' + filme._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Filmes
$scope.find = function() {
$scope.filmes = Filmes.query();
};
// Find existing Filme
$scope.findOne = function() {
$scope.filme = Filmes.get({
filmeId: $stateParams.filmeId
});
};
}
]); | mit |
mikeyrichardson/kyburz | app/main/views.py | 2027 | from flask import render_template, redirect, url_for, flash
from flask.ext.login import login_required, current_user
from . import main
from .forms import EditProfileForm, EditProfileAdminForm
from .. import db
from ..models import Role, User
from ..decorators import admin_required
@main.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
@main.route('/profile')
def profile():
return render_template('profile.html', user=current_user)
@main.route('/lessons')
def lessons():
return render_template('profile.html', user=current_user)
@main.route('/edit-profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm()
if form.validate_on_submit():
current_user.first_name = form.first_name.data
current_user.last_name = form.last_name.data
db.session.add(current_user)
flash('Your profile has been updated.')
return redirect(url_for('.profile', user_id=current_user.id))
form.first_name.data = current_user.first_name
form.last_name.data = current_user.last_name
return render_template('edit_profile.html', form=form)
@main.route('/edit-profile/<int:id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_profile_admin(id):
user = User.query.get_or_404(id)
form = EditProfileAdminForm(user=user)
if form.validate_on_submit():
user.email = form.email.data
user.confirmed = form.confirmed.data
user.role = Role.query.get(form.role.data)
user.first_name = form.first_name.data
user.last_name = form.last_name.data
db.session.add(user)
flash('The profile has been updated.')
return redirect(url_for('.profile', user_id=user.id))
form.email.data = user.email
form.confirmed.data = user.confirmed
form.role.data = user.role_id
form.first_name.data = user.first_name
form.last_name.data = user.last_name
return render_template('edit_profile.html', form=form, user=user) | mit |
Koriyama-City/papamama | js/v3.0.0/ol/ol/format/polylineformat.js | 10548 | goog.provide('ol.format.Polyline');
goog.require('goog.asserts');
goog.require('ol.Feature');
goog.require('ol.format.Feature');
goog.require('ol.format.TextFeature');
goog.require('ol.geom.LineString');
goog.require('ol.geom.flat.inflate');
goog.require('ol.proj');
/**
* @constructor
* @extends {ol.format.TextFeature}
* @param {olx.format.PolylineOptions=} opt_options
* Optional configuration object.
* @api stable
*/
ol.format.Polyline = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this);
/**
* @inheritDoc
*/
this.defaultDataProjection = ol.proj.get('EPSG:4326');
/**
* @private
* @type {number}
*/
this.factor_ = goog.isDef(options.factor) ? options.factor : 1e5;
};
goog.inherits(ol.format.Polyline, ol.format.TextFeature);
/**
* Encode a list of n-dimensional points and return an encoded string
*
* Attention: This function will modify the passed array!
*
* @param {Array.<number>} numbers A list of n-dimensional points.
* @param {number} stride The number of dimension of the points in the list.
* @param {number=} opt_factor The factor by which the numbers will be
* multiplied. The remaining decimal places will get rounded away.
* Default is `1e5`.
* @return {string} The encoded string.
* @api
*/
ol.format.Polyline.encodeDeltas = function(numbers, stride, opt_factor) {
var factor = goog.isDef(opt_factor) ? opt_factor : 1e5;
var d;
var lastNumbers = new Array(stride);
for (d = 0; d < stride; ++d) {
lastNumbers[d] = 0;
}
var i, ii;
for (i = 0, ii = numbers.length; i < ii;) {
for (d = 0; d < stride; ++d, ++i) {
var num = numbers[i];
var delta = num - lastNumbers[d];
lastNumbers[d] = num;
numbers[i] = delta;
}
}
return ol.format.Polyline.encodeFloats(numbers, factor);
};
/**
* Decode a list of n-dimensional points from an encoded string
*
* @param {string} encoded An encoded string.
* @param {number} stride The number of dimension of the points in the
* encoded string.
* @param {number=} opt_factor The factor by which the resulting numbers will
* be divided. Default is `1e5`.
* @return {Array.<number>} A list of n-dimensional points.
* @api
*/
ol.format.Polyline.decodeDeltas = function(encoded, stride, opt_factor) {
var factor = goog.isDef(opt_factor) ? opt_factor : 1e5;
var d;
/** @type {Array.<number>} */
var lastNumbers = new Array(stride);
for (d = 0; d < stride; ++d) {
lastNumbers[d] = 0;
}
var numbers = ol.format.Polyline.decodeFloats(encoded, factor);
var i, ii;
for (i = 0, ii = numbers.length; i < ii;) {
for (d = 0; d < stride; ++d, ++i) {
lastNumbers[d] += numbers[i];
numbers[i] = lastNumbers[d];
}
}
return numbers;
};
/**
* Encode a list of floating point numbers and return an encoded string
*
* Attention: This function will modify the passed array!
*
* @param {Array.<number>} numbers A list of floating point numbers.
* @param {number=} opt_factor The factor by which the numbers will be
* multiplied. The remaining decimal places will get rounded away.
* Default is `1e5`.
* @return {string} The encoded string.
* @api
*/
ol.format.Polyline.encodeFloats = function(numbers, opt_factor) {
var factor = goog.isDef(opt_factor) ? opt_factor : 1e5;
var i, ii;
for (i = 0, ii = numbers.length; i < ii; ++i) {
numbers[i] = Math.round(numbers[i] * factor);
}
return ol.format.Polyline.encodeSignedIntegers(numbers);
};
/**
* Decode a list of floating point numbers from an encoded string
*
* @param {string} encoded An encoded string.
* @param {number=} opt_factor The factor by which the result will be divided.
* Default is `1e5`.
* @return {Array.<number>} A list of floating point numbers.
* @api
*/
ol.format.Polyline.decodeFloats = function(encoded, opt_factor) {
var factor = goog.isDef(opt_factor) ? opt_factor : 1e5;
var numbers = ol.format.Polyline.decodeSignedIntegers(encoded);
var i, ii;
for (i = 0, ii = numbers.length; i < ii; ++i) {
numbers[i] /= factor;
}
return numbers;
};
/**
* Encode a list of signed integers and return an encoded string
*
* Attention: This function will modify the passed array!
*
* @param {Array.<number>} numbers A list of signed integers.
* @return {string} The encoded string.
*/
ol.format.Polyline.encodeSignedIntegers = function(numbers) {
var i, ii;
for (i = 0, ii = numbers.length; i < ii; ++i) {
var num = numbers[i];
numbers[i] = (num < 0) ? ~(num << 1) : (num << 1);
}
return ol.format.Polyline.encodeUnsignedIntegers(numbers);
};
/**
* Decode a list of signed integers from an encoded string
*
* @param {string} encoded An encoded string.
* @return {Array.<number>} A list of signed integers.
*/
ol.format.Polyline.decodeSignedIntegers = function(encoded) {
var numbers = ol.format.Polyline.decodeUnsignedIntegers(encoded);
var i, ii;
for (i = 0, ii = numbers.length; i < ii; ++i) {
var num = numbers[i];
numbers[i] = (num & 1) ? ~(num >> 1) : (num >> 1);
}
return numbers;
};
/**
* Encode a list of unsigned integers and return an encoded string
*
* @param {Array.<number>} numbers A list of unsigned integers.
* @return {string} The encoded string.
*/
ol.format.Polyline.encodeUnsignedIntegers = function(numbers) {
var encoded = '';
var i, ii;
for (i = 0, ii = numbers.length; i < ii; ++i) {
encoded += ol.format.Polyline.encodeUnsignedInteger(numbers[i]);
}
return encoded;
};
/**
* Decode a list of unsigned integers from an encoded string
*
* @param {string} encoded An encoded string.
* @return {Array.<number>} A list of unsigned integers.
*/
ol.format.Polyline.decodeUnsignedIntegers = function(encoded) {
var numbers = [];
var current = 0;
var shift = 0;
var i, ii;
for (i = 0, ii = encoded.length; i < ii; ++i) {
var b = encoded.charCodeAt(i) - 63;
current |= (b & 0x1f) << shift;
if (b < 0x20) {
numbers.push(current);
current = 0;
shift = 0;
} else {
shift += 5;
}
}
return numbers;
};
/**
* Encode one single unsigned integer and return an encoded string
*
* @param {number} num Unsigned integer that should be encoded.
* @return {string} The encoded string.
*/
ol.format.Polyline.encodeUnsignedInteger = function(num) {
var value, encoded = '';
while (num >= 0x20) {
value = (0x20 | (num & 0x1f)) + 63;
encoded += String.fromCharCode(value);
num >>= 5;
}
value = num + 63;
encoded += String.fromCharCode(value);
return encoded;
};
/**
* Read the feature from the Polyline source.
*
* @function
* @param {ArrayBuffer|Document|Node|Object|string} source Source.
* @param {olx.format.ReadOptions=} opt_options Read options.
* @return {ol.Feature} Feature.
* @api stable
*/
ol.format.Polyline.prototype.readFeature;
/**
* @inheritDoc
*/
ol.format.Polyline.prototype.readFeatureFromText = function(text, opt_options) {
var geometry = this.readGeometryFromText(text, opt_options);
return new ol.Feature(geometry);
};
/**
* Read the feature from the source. As Polyline sources contain a single
* feature, this will return the feature in an array.
*
* @function
* @param {ArrayBuffer|Document|Node|Object|string} source Source.
* @param {olx.format.ReadOptions=} opt_options Read options.
* @return {Array.<ol.Feature>} Features.
* @api stable
*/
ol.format.Polyline.prototype.readFeatures;
/**
* @inheritDoc
*/
ol.format.Polyline.prototype.readFeaturesFromText =
function(text, opt_options) {
var feature = this.readFeatureFromText(text, opt_options);
return [feature];
};
/**
* Read the geometry from the source.
*
* @function
* @param {ArrayBuffer|Document|Node|Object|string} source Source.
* @param {olx.format.ReadOptions=} opt_options Read options.
* @return {ol.geom.Geometry} Geometry.
* @api stable
*/
ol.format.Polyline.prototype.readGeometry;
/**
* @inheritDoc
*/
ol.format.Polyline.prototype.readGeometryFromText =
function(text, opt_options) {
var flatCoordinates = ol.format.Polyline.decodeDeltas(text, 2, this.factor_);
var coordinates = ol.geom.flat.inflate.coordinates(
flatCoordinates, 0, flatCoordinates.length, 2);
return /** @type {ol.geom.Geometry} */ (
ol.format.Feature.transformWithOptions(
new ol.geom.LineString(coordinates), false,
this.adaptOptions(opt_options)));
};
/**
* Read the projection from a Polyline source.
*
* @function
* @param {ArrayBuffer|Document|Node|Object|string} source Source.
* @return {ol.proj.Projection} Projection.
* @api stable
*/
ol.format.Polyline.prototype.readProjection;
/**
* @inheritDoc
*/
ol.format.Polyline.prototype.readProjectionFromText = function(text) {
return this.defaultDataProjection;
};
/**
* @inheritDoc
*/
ol.format.Polyline.prototype.writeFeatureText = function(feature, opt_options) {
var geometry = feature.getGeometry();
if (goog.isDefAndNotNull(geometry)) {
return this.writeGeometryText(geometry, opt_options);
} else {
goog.asserts.fail();
return '';
}
};
/**
* @inheritDoc
*/
ol.format.Polyline.prototype.writeFeaturesText =
function(features, opt_options) {
goog.asserts.assert(features.length == 1);
return this.writeFeatureText(features[0], opt_options);
};
/**
* Write a single geometry in Polyline format.
*
* @function
* @param {ol.geom.Geometry} geometry Geometry.
* @param {olx.format.WriteOptions=} opt_options Write options.
* @return {string} Geometry.
* @api stable
*/
ol.format.Polyline.prototype.writeGeometry;
/**
* @inheritDoc
*/
ol.format.Polyline.prototype.writeGeometryText =
function(geometry, opt_options) {
goog.asserts.assertInstanceof(geometry, ol.geom.LineString);
geometry = /** @type {ol.geom.LineString} */
(ol.format.Feature.transformWithOptions(
geometry, true, this.adaptOptions(opt_options)));
var flatCoordinates = geometry.getFlatCoordinates();
var stride = geometry.getStride();
return ol.format.Polyline.encodeDeltas(flatCoordinates, stride, this.factor_);
};
| mit |
begedin/ember-gdriveTodoMVC | app/controllers/login.js | 172 | import Ember from 'ember';
import LoginControllerMixin from 'ember-gdrive/mixins/login-controller-mixin';
export default Ember.Controller.extend(LoginControllerMixin, {}); | mit |
joshrendek/sshpot-com | test/models/login_count_test.rb | 124 | require 'test_helper'
class LoginCountTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| mit |
akhokhar/eProcurement-Application | includes/admin/js/charts.js | 22936 | var Charts = function () {
//function to initiate jQRangeSlider
//There are plenty of options you can set to control the precise looks of your plot.
//You can control the ticks on the axes, the legend, the graph type, etc.
//For more information, please visit http://www.flotcharts.org/
var runCharts = function () {
// Basic Chart
var d1 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25) {
d1.push([i, Math.sin(i)]);
}
var d2 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25) {
d2.push([i, Math.cos(i)]);
}
var d3 = [];
for (var i = 0; i < Math.PI * 2; i += 0.1) {
d3.push([i, Math.tan(i)]);
}
$.plot("#placeholder", [{
label: "sin(x)",
data: d1
}, {
label: "cos(x)",
data: d2
}, {
label: "tan(x)",
data: d3
}], {
series: {
lines: {
show: true
},
points: {
show: true
}
},
xaxis: {
ticks: [0, [Math.PI / 2, "\u03c0/2"],
[Math.PI, "\u03c0"],
[Math.PI * 3 / 2, "3\u03c0/2"],
[Math.PI * 2, "2\u03c0"]
]
},
yaxis: {
ticks: 10,
min: -2,
max: 2,
tickDecimals: 3
},
grid: {
backgroundColor: {
colors: ["#fff", "#eee"]
},
borderWidth: {
top: 1,
right: 1,
bottom: 2,
left: 2
}
}
});
// Toggling Series
var datasets = {
"usa": {
label: "USA",
data: [
[1988, 483994],
[1989, 479060],
[1990, 457648],
[1991, 401949],
[1992, 424705],
[1993, 402375],
[1994, 377867],
[1995, 357382],
[1996, 337946],
[1997, 336185],
[1998, 328611],
[1999, 329421],
[2000, 342172],
[2001, 344932],
[2002, 387303],
[2003, 440813],
[2004, 480451],
[2005, 504638],
[2006, 528692]
]
},
"russia": {
label: "Russia",
data: [
[1988, 218000],
[1989, 203000],
[1990, 171000],
[1992, 42500],
[1993, 37600],
[1994, 36600],
[1995, 21700],
[1996, 19200],
[1997, 21300],
[1998, 13600],
[1999, 14000],
[2000, 19100],
[2001, 21300],
[2002, 23600],
[2003, 25100],
[2004, 26100],
[2005, 31100],
[2006, 34700]
]
},
"uk": {
label: "UK",
data: [
[1988, 62982],
[1989, 62027],
[1990, 60696],
[1991, 62348],
[1992, 58560],
[1993, 56393],
[1994, 54579],
[1995, 50818],
[1996, 50554],
[1997, 48276],
[1998, 47691],
[1999, 47529],
[2000, 47778],
[2001, 48760],
[2002, 50949],
[2003, 57452],
[2004, 60234],
[2005, 60076],
[2006, 59213]
]
},
"germany": {
label: "Germany",
data: [
[1988, 55627],
[1989, 55475],
[1990, 58464],
[1991, 55134],
[1992, 52436],
[1993, 47139],
[1994, 43962],
[1995, 43238],
[1996, 42395],
[1997, 40854],
[1998, 40993],
[1999, 41822],
[2000, 41147],
[2001, 40474],
[2002, 40604],
[2003, 40044],
[2004, 38816],
[2005, 38060],
[2006, 36984]
]
},
"denmark": {
label: "Denmark",
data: [
[1988, 3813],
[1989, 3719],
[1990, 3722],
[1991, 3789],
[1992, 3720],
[1993, 3730],
[1994, 3636],
[1995, 3598],
[1996, 3610],
[1997, 3655],
[1998, 3695],
[1999, 3673],
[2000, 3553],
[2001, 3774],
[2002, 3728],
[2003, 3618],
[2004, 3638],
[2005, 3467],
[2006, 3770]
]
},
"sweden": {
label: "Sweden",
data: [
[1988, 6402],
[1989, 6474],
[1990, 6605],
[1991, 6209],
[1992, 6035],
[1993, 6020],
[1994, 6000],
[1995, 6018],
[1996, 3958],
[1997, 5780],
[1998, 5954],
[1999, 6178],
[2000, 6411],
[2001, 5993],
[2002, 5833],
[2003, 5791],
[2004, 5450],
[2005, 5521],
[2006, 5271]
]
},
"norway": {
label: "Norway",
data: [
[1988, 4382],
[1989, 4498],
[1990, 4535],
[1991, 4398],
[1992, 4766],
[1993, 4441],
[1994, 4670],
[1995, 4217],
[1996, 4275],
[1997, 4203],
[1998, 4482],
[1999, 4506],
[2000, 4358],
[2001, 4385],
[2002, 5269],
[2003, 5066],
[2004, 5194],
[2005, 4887],
[2006, 4891]
]
}
};
// hard-code color indices to prevent them from shifting as
// countries are turned on/off
var i = 0;
$.each(datasets, function (key, val) {
val.color = i;
++i;
});
// insert checkboxes
var choiceContainer = $("#choices");
$.each(datasets, function (key, val) {
choiceContainer.append("<label for='id" + key + "' class='checkbox'><input type='checkbox' name='" + key + "' checked='checked' id='id" + key + "'>" + val.label + "</label>");
});
choiceContainer.find("input").iCheck({
checkboxClass: 'icheckbox_minimal-grey',
radioClass: 'iradio_minimal-grey',
increaseArea: '10%' // optional
}).on('ifClicked', function (event) {
$(this).iCheck('toggle');
plotAccordingToChoices();
});
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function () {
var key = $(this).attr("name");
if (key && datasets[key]) {
data.push(datasets[key]);
}
});
if (data.length > 0) {
$.plot("#placeholder2", data, {
yaxis: {
min: 0
},
xaxis: {
tickDecimals: 0
}
});
}
}
plotAccordingToChoices();
// Interactivity
function randValue() {
return (Math.floor(Math.random() * (1 + 40 - 20))) + 20;
}
var pageviews = [
[1, randValue()],
[2, randValue()],
[3, 2 + randValue()],
[4, 3 + randValue()],
[5, 5 + randValue()],
[6, 10 + randValue()],
[7, 15 + randValue()],
[8, 20 + randValue()],
[9, 25 + randValue()],
[10, 30 + randValue()],
[11, 35 + randValue()],
[12, 25 + randValue()],
[13, 15 + randValue()],
[14, 20 + randValue()],
[15, 45 + randValue()],
[16, 50 + randValue()],
[17, 65 + randValue()],
[18, 70 + randValue()],
[19, 85 + randValue()],
[20, 80 + randValue()],
[21, 75 + randValue()],
[22, 80 + randValue()],
[23, 75 + randValue()],
[24, 70 + randValue()],
[25, 65 + randValue()],
[26, 75 + randValue()],
[27, 80 + randValue()],
[28, 85 + randValue()],
[29, 90 + randValue()],
[30, 95 + randValue()]
];
var visitors = [
[1, randValue() - 5],
[2, randValue() - 5],
[3, randValue() - 5],
[4, 6 + randValue()],
[5, 5 + randValue()],
[6, 20 + randValue()],
[7, 25 + randValue()],
[8, 36 + randValue()],
[9, 26 + randValue()],
[10, 38 + randValue()],
[11, 39 + randValue()],
[12, 50 + randValue()],
[13, 51 + randValue()],
[14, 12 + randValue()],
[15, 13 + randValue()],
[16, 14 + randValue()],
[17, 15 + randValue()],
[18, 15 + randValue()],
[19, 16 + randValue()],
[20, 17 + randValue()],
[21, 18 + randValue()],
[22, 19 + randValue()],
[23, 20 + randValue()],
[24, 21 + randValue()],
[25, 14 + randValue()],
[26, 24 + randValue()],
[27, 25 + randValue()],
[28, 26 + randValue()],
[29, 27 + randValue()],
[30, 31 + randValue()]
];
var plot = $.plot($("#placeholder3"), [{
data: pageviews,
label: "Unique Visits"
}, {
data: visitors,
label: "Page Views"
}], {
series: {
lines: {
show: true,
lineWidth: 2,
fill: true,
fillColor: {
colors: [{
opacity: 0.05
}, {
opacity: 0.01
}]
}
},
points: {
show: true
},
shadowSize: 2
},
grid: {
hoverable: true,
clickable: true,
tickColor: "#eee",
borderWidth: 0
},
colors: ["#d12610", "#37b7f3", "#52e136"],
xaxis: {
ticks: 11,
tickDecimals: 0
},
yaxis: {
ticks: 11,
tickDecimals: 0
}
});
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css({
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 15,
border: '1px solid #333',
padding: '4px',
color: '#fff',
'border-radius': '3px',
'background-color': '#333',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#placeholder3").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y);
}
} else {
$("#tooltip").remove();
previousPoint = null;
}
});
//Real Time
// We use an inline data source in the example, usually data would
// be fetched from a server
var data = [],
totalPoints = 300;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
// Do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50,
y = prev + Math.random() * 10 - 5;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
data.push(y);
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]]);
}
return res;
}
// Set up the control widget
var updateInterval = 30;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1) {
updateInterval = 1;
} else if (updateInterval > 2000) {
updateInterval = 2000;
}
$(this).val("" + updateInterval);
}
});
var plot = $.plot("#placeholder4", [getRandomData()], {
series: {
shadowSize: 0 // Drawing is faster without shadows
},
yaxis: {
min: 0,
max: 100
},
xaxis: {
show: false
}
});
function update() {
plot.setData([getRandomData()]);
// Since the axes don't change, we don't need to call plot.setupGrid()
plot.draw();
setTimeout(update, updateInterval);
}
update();
//Categories
var data_category = [
["January", 10],
["February", 8],
["March", 4],
["April", 13],
["May", 17],
["June", 9]
];
$.plot("#placeholder5", [data_category], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center",
fillColor: "#4DBEF4",
lineWidth: 0,
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
// Annotations
var d_1 = [];
for (var i = 0; i < 20; ++i) {
d_1.push([i, Math.sin(i)]);
}
var data_annotation = [{
data: d_1,
label: "Pressure",
color: "#333"
}];
var markings = [{
color: "#f6f6f6",
yaxis: {
from: 1
}
}, {
color: "#f6f6f6",
yaxis: {
to: -1
}
}, {
color: "#000",
lineWidth: 1,
xaxis: {
from: 2,
to: 2
}
}, {
color: "#000",
lineWidth: 1,
xaxis: {
from: 8,
to: 8
}
}];
var placeholder = $("#placeholder6");
var plot_annotation = $.plot(placeholder, data_annotation, {
bars: {
show: true,
barWidth: 0.5,
fill: 0.9
},
xaxis: {
ticks: [],
autoscaleMargin: 0.02
},
yaxis: {
min: -2,
max: 2
},
grid: {
markings: markings
}
});
var o = plot_annotation.pointOffset({
x: 2,
y: -1.2
});
// Append it to the placeholder that Flot already uses for positioning
placeholder.append("<div style='position:absolute;left:" + (o.left + 4) + "px;top:" + o.top + "px;color:#666;font-size:smaller'>Warming up</div>");
o = plot_annotation.pointOffset({
x: 8,
y: -1.2
});
placeholder.append("<div style='position:absolute;left:" + (o.left + 4) + "px;top:" + o.top + "px;color:#666;font-size:smaller'>Actual measurements</div>");
// Draw a little arrow on top of the last label to demonstrate canvas
// drawing
var ctx = plot_annotation.getCanvas().getContext("2d");
ctx.beginPath();
o.left += 4;
ctx.moveTo(o.left, o.top);
ctx.lineTo(o.left, o.top - 10);
ctx.lineTo(o.left + 10, o.top - 5);
ctx.lineTo(o.left, o.top);
ctx.fillStyle = "#000";
ctx.fill();
// Default Pie
var data_pie = [],
series = Math.floor(Math.random() * 6) + 3;
for (var i = 0; i < series; i++) {
data_pie[i] = {
label: "Series" + (i + 1),
data: Math.floor(Math.random() * 100) + 1
};
}
$.plot('#placeholder7', data_pie, {
series: {
pie: {
show: true
}
}
});
// Label Formatter
$.plot('#placeholder8', data_pie, {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 1,
formatter: labelFormatter,
background: {
opacity: 0.8
}
}
}
},
legend: {
show: false
}
});
// Label Style
$.plot('#placeholder9', data_pie, {
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 3 / 4,
formatter: labelFormatter,
background: {
opacity: 0.5,
color: '#000'
}
}
}
},
legend: {
show: false
}
});
// Rectangular Pie
$.plot('#placeholder10', data_pie, {
series: {
pie: {
show: true,
radius: 500,
label: {
show: true,
formatter: labelFormatter,
threshold: 0.1
}
}
},
legend: {
show: false
}
});
// Tilted Pie
$.plot('#placeholder11', data_pie, {
series: {
pie: {
show: true,
radius: 1,
tilt: 0.5,
label: {
show: true,
radius: 1,
formatter: labelFormatter,
background: {
opacity: 0.8
}
},
combine: {
color: '#999',
threshold: 0.1
}
}
},
legend: {
show: false
}
});
// Interactivity Pie
$.plot('#placeholder12', data_pie, {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true,
clickable: true
}
});
$("#placeholder12").bind("plotclick", function (event, pos, obj) {
if (!obj) {
return;
}
percent = parseFloat(obj.series.percent).toFixed(2);
alert("" + obj.series.label + ": " + percent + "%");
});
function labelFormatter(label, series) {
return "<div style='font-size:8pt; text-align:center; padding:2px; color:white;'>" + label + "<br/>" + Math.round(series.percent) + "%</div>";
}
};
return {
//main function to initiate template pages
init: function () {
runCharts();
}
};
}(); | mit |
ObjectInk/orchard-alias-redirects | Controllers/RedirectController.cs | 1102 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orchard.Alias.Redirects.Services;
using Orchard;
using Orchard.Localization;
using Orchard.Alias.Redirects.Models;
using System.Web.Routing;
namespace Orchard.Alias.Redirects.Controllers
{
public class RedirectController : Controller
{
private readonly IRedirectService _redirectService;
public RedirectController(IRedirectService redirectService)
{
_redirectService = redirectService;
}
public ActionResult Index(string alias, string alias2 = "")
{
if (string.IsNullOrEmpty(alias))
throw new HttpException(404, "Page cannot be found");
if (!string.IsNullOrEmpty(alias2))
alias = String.Format("{0}/{1}", alias, alias2);
var entity = _redirectService.GetByAlias(alias);
if (entity == null)
throw new HttpException(404, "Page cannot be found");
return Redirect(entity.Url);
}
}
} | mit |
Juliaandavid/react-native-alerts | temp/index.android.js | 1246 | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Button,
View
} from 'react-native';
import RNAlerts from 'react-native-alerts'
const buttonTest = () => {
RNAlerts.testParameters({
param1: "Parameter"
}, (res) => {
console.log(res);
});
};
const buttonAlert = () => {
RNAlerts.alert({
title: "Title",
message: "This is a testing message",
button: "Accept"
}, (res) => {
console.log(res);
});
};
export default class testing extends Component {
render() {
return (
<View style={styles.container}>
<Button
onPress={buttonTest}
title="Testing" />
<Button
onPress={onButtonPress}
title="Alert" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('testing', () => testing);
| mit |
kedarmhaswade/impatiently-j8 | src/main/java/practice/PointerComparisonTraversal.java | 4102 | package practice;
/** <p> It is possible to <i>iteratively </i>traverse a {@code Binary Tree} by using a comparison of pointers or
* references. </p>
* This class demonstrates such a traversal. This idea is from Pat Morin's Open Data Structures.
* Created by kmhaswade on 6/6/16.
*/
public class PointerComparisonTraversal<T> {
private static class Node<T> {
T key;
Node<T> left;
Node<T> right;
Node<T> parent;
public Node(T key) {
this.key = key;
}
public Node<T> setLeft(Node<T> left) {
this.left = left;
left.parent = this;
return left;
}
public Node<T> setRight(Node<T> right) {
this.right = right;
right.parent = this;
return right;
}
@Override
public String toString() {
String l, r, p;
l = left == null ? "null" : left.key.toString();
r = right == null ? "null" : right.key.toString();
p = parent == null ? "null" : parent.key.toString();
// return "[key: " + key + ", left: " + l + ", right: " + r + ", parent: " + p + "]";
return "[key: " + key + "]";
}
public static <T> Node<T> createBasicIntegerTree(T... values) {
Node<T> root = new Node<>(values[0]);
Node<T> left = new Node<>(values[1]);
root.setLeft(left);
Node<T> right = new Node<>(values[2]);
root.setRight(right);
return root;
}
public static <T> Node<T> tree1(T value) {
Node<T> root = new Node<>(value);
return root;
}
public static <T> Node<T> tree5(T... values) {
Node<T> root = new Node<>(values[0]);
Node<T> left = new Node<>(values[1]);
root.setLeft(left);
Node<T> right = new Node<>(values[2]);
root.setRight(right);
Node<T> t = new Node<>(values[3]);
left.setRight(t);
t = new Node<>(values[4]);
right.setLeft(t);
return root;
}
public static <T> Node<T> justRight(T v1, T v2) {
Node<T> root = new Node<>(v1);
Node<T> right = new Node<>(v2);
root.setRight(right);
return root;
}
}
public void traverse(Node<T> node) {
if (node == null)
return;
Node<T> curr = node, prev = node.parent, next = node.left;
while (true) {
if (prev == curr.parent) {
next = curr.left;
if (next == null)
next = curr.right;
if (next == null)
next = curr.parent;
} else if (prev == curr.left) {
next = curr.right;
if (next == null)
next = curr.parent;
} else if (prev == curr.right) {
next = curr.parent;
} else {
System.out.println("interesting case, is that a bug? : " + curr);
}
if (next == curr.parent)
System.out.println("visited: " + curr);
if (prev == node.right && next == node.parent)
break;
// System.out.println("curr: " + curr + ", prev: " + prev + ", next: " + next);
prev = curr;
curr = next;
}
}
public static void main(String[] args) {
PointerComparisonTraversal t = new PointerComparisonTraversal();
System.out.println("==============================================");
Node<String> r1 = Node.tree1("foo");
t.traverse(r1);
System.out.println("==============================================");
Node<Integer> r2 = Node.tree5(1, 2, 3, 4, 5);
t.traverse(r2);
System.out.println("==============================================");
Node<Integer> r3 = Node.justRight(1, 2);
t.traverse(r3);
System.out.println("==============================================");
}
}
| mit |
sporchia/alttp_vt_randomizer | app/Region/Standard/LightWorld/NorthWest.php | 7993 | <?php
namespace ALttP\Region\Standard\LightWorld;
use ALttP\Item;
use ALttP\Location;
use ALttP\Region;
use ALttP\Shop;
use ALttP\Support\LocationCollection;
use ALttP\Support\ShopCollection;
use ALttP\World;
/**
* North West Light World Region and it's Locations contained within
*/
class NorthWest extends Region
{
protected $name = 'Light World';
/**
* Create a new Light World Region and initalize it's locations
*
* @param World $world World this Region is part of
*
* @return void
*/
public function __construct(World $world)
{
parent::__construct($world);
$this->locations = new LocationCollection([
new Location\Pedestal("Master Sword Pedestal", [0x289B0], null, $this),
new Location\Chest("King's Tomb", [0xE97A], null, $this),
new Location\Chest("Kakariko Tavern", [0xE9CE], null, $this),
new Location\Chest("Chicken House", [0xE9E9], null, $this),
new Location\Chest("Kakariko Well - Top", [0xEA8E], null, $this),
new Location\Chest("Kakariko Well - Left", [0xEA91], null, $this),
new Location\Chest("Kakariko Well - Middle", [0xEA94], null, $this),
new Location\Chest("Kakariko Well - Right", [0xEA97], null, $this),
new Location\Chest("Kakariko Well - Bottom", [0xEA9A], null, $this),
new Location\Chest("Blind's Hideout - Top", [0xEB0F], null, $this),
new Location\Chest("Blind's Hideout - Left", [0xEB12], null, $this),
new Location\Chest("Blind's Hideout - Right", [0xEB15], null, $this),
new Location\Chest("Blind's Hideout - Far Left", [0xEB18], null, $this),
new Location\Chest("Blind's Hideout - Far Right", [0xEB1B], null, $this),
new Location\Chest("Pegasus Rocks", [0xEB3F], null, $this),
new Location\Npc("Bottle Merchant", [0x2EB18], null, $this),
new Location\Npc("Magic Bat", [0x180015], null, $this),
new Location\Npc\BugCatchingKid("Sick Kid", [0x339CF], null, $this),
new Location\Standing("Lost Woods Hideout", [0x180000], null, $this),
new Location\Standing("Lumberjack Tree", [0x180001], null, $this),
new Location\Standing("Graveyard Ledge", [0x180004], null, $this),
new Location\Standing("Mushroom", [0x180013], null, $this),
]);
$this->locations->setChecksForWorld($world->id);
$this->shops = new ShopCollection([
new Shop("Light World Kakariko Shop", 0x03, 0xA0, 0x011F, 0x46, $this),
// Single entrance caves with no items in them ;)
new Shop\TakeAny("Fortune Teller (Light)", 0x83, 0xA0, 0x011F, 0x65, $this, [0xDBBD7 => [0x46]]),
new Shop\TakeAny("Bush Covered House", 0x83, 0xA0, 0x011F, 0x44, $this, [0xDBBB6 => [0x46]]),
new Shop\TakeAny("Lost Woods Gamble", 0x83, 0xA0, 0x0112, 0x3C, $this, [0xDBBAE => [0x58]]),
new Shop\TakeAny("Lumberjack House", 0x83, 0xA0, 0x011F, 0x76, $this, [0xDBBE8 => [0x46]]),
new Shop\TakeAny("Snitch Lady East", 0x83, 0xA0, 0x011F, 0x3E, $this, [0xDBBB0 => [0x46]]),
new Shop\TakeAny("Snitch Lady West", 0x83, 0xA0, 0x011F, 0x3F, $this, [0xDBBB1 => [0x46]]),
new Shop\TakeAny("Bomb Hut", 0x83, 0xA0, 0x011F, 0x4A, $this, [0xDBBBC => [0x46]]),
]);
$this->shops["Light World Kakariko Shop"]->clearInventory()
->addInventory(0, Item::get('RedPotion', $world), 150)
->addInventory(1, Item::get('Heart', $world), 10)
->addInventory(2, Item::get('TenBombs', $world), 50);
}
/**
* Initalize the requirements for Entry and Completetion of the Region as well as access to all Locations contained
* within for No Glitches
*
* @return $this
*/
public function initalize()
{
$this->shops["Bomb Hut"]->setRequirements(function ($locations, $items) {
return $items->canBombThings();
});
$this->locations["Master Sword Pedestal"]->setRequirements(function ($locations, $items) {
return ($this->world->config('itemPlacement') !== 'basic' || $items->has('BookOfMudora'))
&& $items->has('PendantOfPower')
&& $items->has('PendantOfWisdom')
&& $items->has('PendantOfCourage');
});
$this->locations["King's Tomb"]->setRequirements(function ($locations, $items) {
return $items->has('PegasusBoots')
&& ($this->world->config('canBootsClip', false)
|| $items->canLiftDarkRocks()
|| $this->world->config('canOneFrameClipOW', false)
|| ($this->world->config('canSuperSpeed', false) && $items->canSpinSpeed())
|| ($items->has('MagicMirror') && $this->world->getRegion('North West Dark World')->canEnter($locations, $items)
&& ($items->has('MoonPearl') || ($items->hasABottle() && $this->world->config('canOWYBA', false))
|| ($this->world->config('canBunnyRevive', false) && $items->canBunnyRevive($this->world)))));
});
$this->locations["Pegasus Rocks"]->setRequirements(function ($locations, $items) {
return $items->has('PegasusBoots');
});
$this->locations["Magic Bat"]->setRequirements(function ($locations, $items) {
return $items->has('Powder')
&& ($items->has('Hammer')
|| ((($this->world->config('canBootsClip', false) && $items->has('PegasusBoots'))
|| $this->world->config('canOneFrameClipOW', false))
&& ($items->has('Flippers') || $this->world->config('canFakeFlipper', false)))
|| ($items->has('MagicMirror')
&& (($this->world->config('canMirrorWrap', false) && $this->world->getRegion('North West Dark World')->canEnter($locations, $items))
|| (($items->has('MoonPearl') || ($items->hasABottle() && $this->world->config('canOWYBA', false))
|| ($this->world->config('canBunnyRevive', false) && $items->canBunnyRevive($this->world)))
&& (($items->canLiftDarkRocks() && $this->world->getRegion('North West Dark World')->canEnter($locations, $items))
|| ($this->world->config('canSuperSpeed', false) && $items->canSpinSpeed()
&& ($items->has('Flippers') || $this->world->config('canFakeFlipper', false))
&& $this->world->getRegion('North East Dark World')->canEnter($locations, $items)))))));
});
$this->locations["Sick Kid"]->setRequirements(function ($locations, $items) {
return $items->hasABottle();
});
$this->locations["Lumberjack Tree"]->setRequirements(function ($locations, $items) {
return $items->has('DefeatAgahnim') && $items->has('PegasusBoots');
});
$this->locations["Graveyard Ledge"]->setRequirements(function ($locations, $items) {
return ($this->world->config('canBootsClip', false) && $items->has('PegasusBoots'))
|| ($this->world->config('canSuperSpeed', false) && $items->canSpinSpeed())
|| $this->world->config('canOneFrameClipOW', false)
|| ($items->has('MagicMirror') && $this->world->getRegion('North West Dark World')->canEnter($locations, $items)
&& ($items->has('MoonPearl') || ($items->hasABottle() && $this->world->config('canOWYBA', false))
|| ($this->world->config('canBunnyRevive', false) && $items->canBunnyRevive($this->world))));
});
$this->can_enter = function ($locations, $items) {
return $items->has('RescueZelda');
};
return $this;
}
}
| mit |
resec/superhero | extends/torndsession/driver.py | 1390 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 Mitchell Chu
class SessionDriver(object):
'''
abstact class for all real session driver implements.
'''
def __init__(self, **settings):
self.settings = settings
def get(self, session_id):
raise NotImplementedError()
def save(self, session_id, session_data, expires=None):
raise NotImplementedError()
def clear(self, session_id):
raise NotImplementedError()
def remove_expires(self):
raise NotImplementedError()
class SessionDriverFactory(object):
'''
session driver factory
use input settings to return suitable driver's instance
'''
@staticmethod
def create_driver(driver, **setings):
module_name = 'extends.torndsession.%ssession' % driver.lower()
module = __import__(module_name, globals(), locals(), ['object'])
# must use this form.
# use __import__('torndsession.' + driver.lower()) just load torndsession.__init__.pyc
cls = getattr(module, '%sSession' % driver.capitalize())
if not 'SessionDriver' in [base.__name__ for base in cls.__bases__]:
raise InvalidSessionDriverException('%s not found in current driver implements ' % driver)
return cls # just return driver class.
class InvalidSessionDriverException(Exception):
pass
| mit |
olliebennett/helpy | app/controllers/admin/users_controller.rb | 3391 | # == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# login :string
# identity_url :string
# name :string
# admin :boolean default(FALSE)
# bio :text
# signature :text
# role :string default("user")
# home_phone :string
# work_phone :string
# cell_phone :string
# company :string
# street :string
# city :string
# state :string
# zip :string
# title :string
# twitter :string
# linkedin :string
# thumbnail :string
# medium_image :string
# large_image :string
# language :string default("en")
# assigned_ticket_count :integer default(0)
# topics_count :integer default(0)
# active :boolean default(TRUE)
# created_at :datetime not null
# updated_at :datetime not null
# email :string default(""), not null
# encrypted_password :string default(""), not null
# reset_password_token :string
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :inet
# last_sign_in_ip :inet
# provider :string
# uid :string
#
class Admin::UsersController < Admin::BaseController
before_action :verify_agent
before_action :fetch_counts, :only => ['show']
respond_to :html, :js
def index
@users = User.all.page params[:page]
@user = User.new
end
def show
@user = User.where(id: params[:id]).first
@topics = Topic.where(user_id: @user.id).page params[:page]
# We still have to grab the first topic for the user to use the same user partial
@topic = Topic.where(user_id: @user.id).first
@tracker.event(category: "Agent: #{current_user.name}", action: "Viewed User Profile", label: @user.name)
render 'admin/topics/index'
end
def edit
@user = User.where(id: params[:id]).first
@tracker.event(category: "Agent: #{current_user.name}", action: "Editing User Profile", label: @user.name)
end
def update
@user = User.find(params[:id])
@user.update(user_params)
fetch_counts
# update role if admin only
@user.update_attribute(:role, params[:user][:role]) if current_user.is_admin?
@topics = @user.topics.page params[:page]
@topic = Topic.where(user_id: @user.id).first
@tracker.event(category: "Agent: #{current_user.name}", action: "Edited User Profile", label: @user.name)
# TODO: Refactor this to use an index method/view on the users model
render 'admin/topics/index'
end
private
def user_params
params.require(:user).permit(
:name,
:bio,
:signature,
:work_phone,
:cell_phone,
:email,
:company,
:street,
:city,
:state,
:zip,
:title,
:twitter,
:linkedin,
:language,
:active
)
end
end
| mit |
shonshampain/StreamRecord | app/src/main/java/com/shonshampain/streamrecorder/events/SeekEvent.java | 180 | package com.shonshampain.streamrecorder.events;
public class SeekEvent {
public float percent;
public SeekEvent(float percent) {
this.percent = percent;
}
}
| mit |
Silencer2K/wow-lib-s2k-mounts | LibS2kMounts-1.0.lua | 9010 | local MAJOR, MINOR = "LibS2kMounts-1.0", 201512051
local lib, oldMinor = LibStub:NewLibrary(MAJOR, MINOR)
if not lib then return end
S2K_MOUNTS_ID_TO_SPELL = {
[6] = 458, [7] = 459, [8] = 468, [9] = 470, [11] = 472,
[12] = 578, [13] = 579, [14] = 580, [15] = 581, [17] = 5784,
[18] = 6648, [19] = 6653, [20] = 6654, [21] = 6777, [22] = 6896,
[24] = 6898, [25] = 6899, [26] = 8394, [27] = 8395, [28] = 8980,
[31] = 10789, [34] = 10793, [35] = 10795, [36] = 10796, [38] = 10799,
[39] = 10873, [40] = 10969, [41] = 13819, [42] = 15779, [43] = 15780,
[45] = 16055, [46] = 16056, [50] = 16080, [51] = 16081, [52] = 16082,
[53] = 16083, [54] = 16084, [55] = 17229, [56] = 17450, [57] = 17453,
[58] = 17454, [62] = 17459, [63] = 17460, [64] = 17461, [65] = 17462,
[66] = 17463, [67] = 17464, [68] = 17465, [69] = 17481, [70] = 18363,
[71] = 18989, [72] = 18990, [73] = 18991, [74] = 18992, [75] = 22717,
[76] = 22718, [77] = 22719, [78] = 22720, [79] = 22721, [80] = 22722,
[81] = 22723, [82] = 22724, [83] = 23161, [84] = 23214, [85] = 23219,
[87] = 23221, [88] = 23222, [89] = 23223, [90] = 23225, [91] = 23227,
[92] = 23228, [93] = 23229, [94] = 23238, [95] = 23239, [96] = 23240,
[97] = 23241, [98] = 23242, [99] = 23243, [100] = 23246, [101] = 23247,
[102] = 23248, [103] = 23249, [104] = 23250, [105] = 23251, [106] = 23252,
[107] = 23338, [108] = 23509, [109] = 23510, [110] = 24242, [111] = 24252,
[116] = 25863, [117] = 25953, [118] = 26054, [119] = 26055, [120] = 26056,
[121] = 26655, [122] = 26656, [123] = 28828, [125] = 30174, [129] = 32235,
[130] = 32239, [131] = 32240, [132] = 32242, [133] = 32243, [134] = 32244,
[135] = 32245, [136] = 32246, [137] = 32289, [138] = 32290, [139] = 32292,
[140] = 32295, [141] = 32296, [142] = 32297, [145] = 33630, [146] = 33660,
[147] = 34406, [149] = 34767, [150] = 34769, [151] = 34790, [152] = 34795,
[153] = 34896, [154] = 34897, [155] = 34898, [156] = 34899, [157] = 35018,
[158] = 35020, [159] = 35022, [160] = 35025, [161] = 35027, [162] = 35028,
[163] = 35710, [164] = 35711, [165] = 35712, [166] = 35713, [167] = 35714,
[168] = 36702, [169] = 37015, [170] = 39315, [171] = 39316, [172] = 39317,
[173] = 39318, [174] = 39319, [176] = 39798, [177] = 39800, [178] = 39801,
[179] = 39802, [180] = 39803, [183] = 40192, [185] = 41252, [186] = 41513,
[187] = 41514, [188] = 41515, [189] = 41516, [190] = 41517, [191] = 41518,
[196] = 42776, [197] = 42777, [199] = 43688, [201] = 43899, [202] = 43900,
[203] = 43927, [204] = 44151, [205] = 44153, [206] = 44317, [207] = 44744,
[211] = 46197, [212] = 46199, [213] = 46628, [219] = 48025, [220] = 48027,
[221] = 48778, [222] = 48954, [223] = 49193, [224] = 49322, [225] = 49378,
[226] = 49379, [230] = 51412, [236] = 54729, [237] = 54753, [238] = 55164,
[240] = 55531, [241] = 58615, [243] = 58983, [246] = 59567, [247] = 59568,
[248] = 59569, [249] = 59570, [250] = 59571, [251] = 59572, [253] = 59650,
[254] = 59785, [255] = 59788, [256] = 59791, [257] = 59793, [258] = 59797,
[259] = 59799, [262] = 59961, [263] = 59976, [264] = 59996, [265] = 60002,
[266] = 60021, [267] = 60024, [268] = 60025, [269] = 60114, [270] = 60116,
[271] = 60118, [272] = 60119, [273] = 60136, [274] = 60140, [275] = 60424,
[276] = 61229, [277] = 61230, [278] = 61294, [279] = 61309, [280] = 61425,
[284] = 61447, [285] = 61451, [286] = 61465, [287] = 61467, [288] = 61469,
[289] = 61470, [291] = 61996, [292] = 61997, [293] = 62048, [294] = 63232,
[295] = 63635, [296] = 63636, [297] = 63637, [298] = 63638, [299] = 63639,
[300] = 63640, [301] = 63641, [302] = 63642, [303] = 63643, [304] = 63796,
[305] = 63844, [306] = 63956, [307] = 63963, [308] = 64656, [309] = 64657,
[310] = 64658, [311] = 64659, [312] = 64731, [313] = 64927, [314] = 64977,
[317] = 65439, [318] = 65637, [319] = 65638, [320] = 65639, [321] = 65640,
[322] = 65641, [323] = 65642, [324] = 65643, [325] = 65644, [326] = 65645,
[327] = 65646, [328] = 65917, [329] = 66087, [330] = 66088, [331] = 66090,
[332] = 66091, [333] = 66122, [334] = 66123, [335] = 66124, [336] = 66846,
[337] = 66847, [338] = 66906, [340] = 67336, [341] = 67466, [342] = 68056,
[343] = 68057, [344] = 68187, [345] = 68188, [349] = 69395, [350] = 69820,
[351] = 69826, [352] = 71342, [358] = 71810, [363] = 72286, [364] = 72807,
[365] = 72808, [366] = 73313, [367] = 73629, [368] = 73630, [371] = 74856,
[372] = 74918, [373] = 75207, [375] = 75596, [376] = 75614, [382] = 75973,
[386] = 84751, [388] = 87090, [389] = 87091, [391] = 88331, [392] = 88335,
[393] = 88718, [394] = 88741, [395] = 88742, [396] = 88744, [397] = 88746,
[398] = 88748, [399] = 88749, [400] = 88750, [401] = 88990, [403] = 90621,
[404] = 92155, [405] = 92231, [406] = 92232, [407] = 93326, [408] = 93623,
[409] = 93644, [410] = 96491, [411] = 96499, [412] = 96503, [413] = 97359,
[415] = 97493, [416] = 97501, [417] = 97560, [418] = 97581, [419] = 98204,
[420] = 98718, [421] = 98727, [422] = 100332, [423] = 100333, [424] = 101282,
[425] = 101542, [426] = 101573, [428] = 101821, [429] = 102346, [430] = 102349,
[431] = 102350, [432] = 102488, [433] = 102514, [434] = 103081, [435] = 103195,
[436] = 103196, [439] = 107203, [440] = 107516, [441] = 107517, [442] = 107842,
[443] = 107844, [444] = 107845, [445] = 110039, [446] = 110051, [447] = 113120,
[448] = 113199, [449] = 118089, [450] = 118737, [451] = 120043, [452] = 120395,
[453] = 120822, [454] = 171847, [455] = 121820, [456] = 121836, [457] = 121837,
[458] = 121838, [459] = 121839, [460] = 122708, [462] = 123182, [463] = 123886,
[464] = 123992, [465] = 123993, [466] = 124408, [467] = 124550, [468] = 124659,
[469] = 126507, [470] = 126508, [471] = 127154, [472] = 127156, [473] = 127158,
[474] = 127161, [475] = 127164, [476] = 127165, [477] = 127169, [478] = 127170,
[479] = 127174, [480] = 127176, [481] = 127177, [484] = 127209, [485] = 127213,
[486] = 127216, [487] = 127220, [488] = 127271, [492] = 127286, [493] = 127287,
[494] = 127288, [495] = 127289, [496] = 127290, [497] = 127293, [498] = 127295,
[499] = 127302, [500] = 127308, [501] = 127310, [503] = 129552, [504] = 129918,
[505] = 129932, [506] = 129934, [507] = 129935, [508] = 130086, [509] = 130092,
[510] = 130137, [511] = 130138, [515] = 130965, [516] = 130985, [517] = 132036,
[518] = 132117, [519] = 132118, [520] = 132119, [521] = 133023, [522] = 134359,
[523] = 134573, [526] = 135416, [527] = 135418, [528] = 136163, [529] = 136164,
[530] = 136400, [531] = 136471, [532] = 136505, [533] = 138423, [534] = 138424,
[535] = 138425, [536] = 138426, [537] = 138640, [538] = 138641, [539] = 138642,
[540] = 138643, [541] = 139407, [542] = 139442, [543] = 139448, [544] = 139595,
[545] = 140249, [546] = 140250, [547] = 142073, [548] = 142266, [549] = 142478,
[550] = 142641, [551] = 142878, [552] = 142910, [554] = 146615, [555] = 146622,
[557] = 148392, [558] = 148396, [559] = 148417, [560] = 148428, [561] = 148476,
[562] = 148618, [563] = 148619, [564] = 148620, [566] = 148970, [567] = 148972,
[568] = 149801, [571] = 153489, [593] = 163024, [594] = 163025, [600] = 155741,
[603] = 169952, [606] = 170347, [607] = 171436, [608] = 171616, [609] = 171617,
[611] = 171619, [612] = 171620, [613] = 171621, [614] = 171622, [615] = 171623,
[616] = 171624, [617] = 171625, [618] = 171626, [619] = 171627, [620] = 171628,
[621] = 171629, [622] = 171630, [623] = 171632, [624] = 171633, [625] = 171634,
[626] = 171635, [627] = 171636, [628] = 171637, [629] = 171638, [630] = 171824,
[631] = 171826, [632] = 171825, [634] = 171828, [635] = 171829, [636] = 171830,
[637] = 171831, [638] = 171832, [639] = 171833, [640] = 171834, [641] = 171835,
[642] = 171836, [643] = 171837, [644] = 171838, [645] = 171839, [647] = 171841,
[648] = 171842, [649] = 171843, [650] = 171844, [651] = 171845, [652] = 171846,
[654] = 171848, [655] = 171849, [657] = 171851, [664] = 175700, [678] = 179244,
[679] = 179245, [682] = 179478, [741] = 180545, [751] = 182912, [753] = 183117,
[755] = 183889, [756] = 185052, [758] = 186305, [759] = 186828, [760] = 189043,
[761] = 189044, [762] = 189364, [763] = 189998, [764] = 189999, [765] = 190690,
[768] = 190977, [769] = 191314, [772] = 191633, [776] = 194046, [778] = 194464,
[781] = 201098,
}
function lib:GetSpellIdByMountId(mountId)
return S2K_MOUNTS_ID_TO_SPELL[mountId]
end
| mit |
jitendrac/wp-theme-framework | application/extensions/Customize.php | 2009 | <?php
class ThemeControllerExtensionCustomize {
protected static $_instance;
/**
* @return ThemeControllerExtensionCustomize
*/
public static function getInstance() {
if(is_null(self::$_instance))
self::$_instance = new self();
return self::$_instance;
}
private $_customizeDirectory = array(
'theme-support' => 'add_theme_support',
'theme-customization' => 'add_action|customize_register',
);
public $customizeExtensionsPath;
public function __construct() {
$this->customizeExtensionsPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'customize' . DIRECTORY_SEPARATOR;
add_action( 'after_setup_theme', array($this, 'afterThemeSetup') );
}
public function afterThemeSetup() {
foreach($this->_customizeDirectory as $directoryName => $directoryHandler) {
$currentDirectoryClassPrefix =
'ThemeControllerExtension' .
(str_replace(' ', '', ucwords(str_replace('-', ' ', $directoryName))));
$currentDirectoryPath = $this->customizeExtensionsPath . $directoryName;
$currentDirectoryFiles = ThemeControllerLoader::getInstance()->getLoaded($currentDirectoryPath);
foreach($currentDirectoryFiles as $file) {
$className = $currentDirectoryClassPrefix . substr($file, strlen($currentDirectoryPath) + 1, -4);
$instanceObject = new $className();
$instanceParams = $instanceObject->setupParams();
if(strpos($directoryHandler, '|') !== false) {
$params = explode(
'|',
substr($directoryHandler, strpos($directoryHandler, '|') + 1)
);
$directoryHandler = substr($directoryHandler, 0, strpos($directoryHandler, '|'));
$instanceParams = array_merge($params, $instanceParams);
}
call_user_func_array($directoryHandler, $instanceParams);
}
}
}
}
ThemeControllerExtensionCustomize::getInstance(); | mit |
lbryio/lbry-app | ui/component/viewers/videoViewer/internal/plugins/videojs-mobile-ui/touchOverlay.js | 4764 | /**
* @file touchOverlay.js
* Touch UI component
*/
import videojs from 'video.js';
import window from 'global/window';
const Component = videojs.getComponent('Component');
const dom = videojs.dom || videojs;
/**
* The `TouchOverlay` is an overlay to capture tap events.
*
* @extends Component
*/
class TouchOverlay extends Component {
/**
* Creates an instance of the this class.
*
* @param {Player} player
* The `Player` that this class should be attached to.
*
* @param {Object} [options]
* The key/value store of player options.
*/
constructor(player, options) {
super(player, options);
this.seekSeconds = options.seekSeconds;
this.tapTimeout = options.tapTimeout;
// Add play toggle overlay
this.addChild('playToggle', {});
// Clear overlay when playback starts or with control fade
player.on(['playing', 'userinactive'], e => {
if (!this.player_.paused()) {
this.removeClass('show-play-toggle');
}
});
// A 0 inactivity timeout won't work here
if (this.player_.options_.inactivityTimeout === 0) {
this.player_.options_.inactivityTimeout = 5000;
}
this.enable();
}
/**
* Builds the DOM element.
*
* @return {Element}
* The DOM element.
*/
createEl() {
const el = dom.createEl('div', {
className: 'vjs-touch-overlay',
// Touch overlay is not tabbable.
tabIndex: -1,
});
return el;
}
/**
* Debounces to either handle a delayed single tap, or a double tap
*
* @param {Event} event
* The touch event
*
*/
handleTap(event) {
// Don't handle taps on the play button
if (event.target !== this.el_) {
return;
}
event.preventDefault();
if (this.firstTapCaptured) {
this.firstTapCaptured = false;
if (this.timeout) {
window.clearTimeout(this.timeout);
}
this.handleDoubleTap(event);
} else {
this.firstTapCaptured = true;
this.timeout = window.setTimeout(() => {
this.firstTapCaptured = false;
this.handleSingleTap(event);
}, this.tapTimeout);
}
}
/**
* Toggles display of play toggle
*
* @param {Event} event
* The touch event
*
*/
handleSingleTap(event) {
this.removeClass('skip');
this.toggleClass('show-play-toggle');
// At the moment, we only have one <video> tag at a time, but just loops it
// all to somewhat future-proof it.
const videos = document.getElementsByTagName('video');
for (let video of videos) {
// The Android-Chrome cast button appears when you tap directly on the
// video. If anything exists above it, such as our mobile-ui overlay, the
// action will be absorbed, causing the button to not appear. So, I've
// tried to pass on the tap event by manually dispatching one, but it
// didn't work.
// Peeking at the Android-Chrome code, the cast button is refreshed when
// the 'controllist' is updated. Since we don't use this attribute as we
// are using the videojs controls, I'm "toggling" this attribute to force
// the cast button to be refreshed.
const attr = video.getAttribute('controlslist');
if (!attr || attr.indexOf('dummy') === -1) {
video.setAttribute('controlslist', 'dummy');
} else {
video.removeAttribute('controlslist');
}
}
}
/**
* Seeks by configured number of seconds if left or right part of video double tapped
*
* @param {Event} event
* The touch event
*
*/
handleDoubleTap(event) {
const rect = this.el_.getBoundingClientRect();
const x = event.changedTouches[0].clientX - rect.left;
// Check if double tap is in left or right area
if (x < rect.width * 0.4) {
this.player_.currentTime(Math.max(0, this.player_.currentTime() - this.seekSeconds));
this.addClass('reverse');
} else if (x > rect.width - rect.width * 0.4) {
this.player_.currentTime(Math.min(this.player_.duration(), this.player_.currentTime() + this.seekSeconds));
this.removeClass('reverse');
} else {
return;
}
// Remove play toggle if showing
this.removeClass('show-play-toggle');
// Remove and readd class to trigger animation
this.removeClass('skip');
window.requestAnimationFrame(() => {
this.addClass('skip');
});
}
/**
* Enables touch handler
*/
enable() {
this.firstTapCaptured = false;
this.on('touchend', this.handleTap);
}
/**
* Disables touch handler
*/
disable() {
this.off('touchend', this.handleTap);
}
}
Component.registerComponent('TouchOverlay', TouchOverlay);
export default TouchOverlay;
| mit |
2fort/touhou-test-jsx | src/js/reducers/index.js | 205 | import { combineReducers } from 'redux';
import test from './test';
import characters from './characters';
const rootReducer = combineReducers({
test,
characters,
});
export default rootReducer;
| mit |
fravello/phpSymfony2 | app/cache/dev/twig/d9/28/ba794481d335b138adb4272422d3.php | 2508 | <?php
/* @WebProfiler/Profiler/table.html.twig */
class __TwigTemplate_d928ba794481d335b138adb4272422d3 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<table ";
if (array_key_exists("class", $context)) {
echo "class='";
echo twig_escape_filter($this->env, (isset($context["class"]) ? $context["class"] : $this->getContext($context, "class")), "html", null, true);
echo "'";
}
echo " >
<thead>
<tr>
<th scope=\"col\">Key</th>
<th scope=\"col\">Value</th>
</tr>
</thead>
<tbody>
";
// line 9
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable(twig_sort_filter(twig_get_array_keys_filter((isset($context["data"]) ? $context["data"] : $this->getContext($context, "data")))));
foreach ($context['_seq'] as $context["_key"] => $context["key"]) {
// line 10
echo " <tr>
<th>";
// line 11
echo twig_escape_filter($this->env, (isset($context["key"]) ? $context["key"] : $this->getContext($context, "key")), "html", null, true);
echo "</th>
<td>";
// line 12
echo twig_escape_filter($this->env, twig_jsonencode_filter($this->getAttribute((isset($context["data"]) ? $context["data"] : $this->getContext($context, "data")), (isset($context["key"]) ? $context["key"] : $this->getContext($context, "key")), array(), "array")), "html", null, true);
echo "</td>
</tr>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['key'], $context['_parent'], $context['loop']);
$context = array_merge($_parent, array_intersect_key($context, $_parent));
// line 15
echo " </tbody>
</table>
";
}
public function getTemplateName()
{
return "@WebProfiler/Profiler/table.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 55 => 15, 46 => 12, 42 => 11, 39 => 10, 35 => 9, 19 => 1,);
}
}
| mit |
tommartensen/arion-backend | arionBackend/serializers/__init__.py | 49 | """
This module contains all serializers.
"""
| mit |
venugopalvivek/productreview | src/main/java/com/intuit/vivek/rest/StatusResource.java | 541 | package com.intuit.vivek.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
/**
* Created by vvenugopal on 3/28/17.
*/
@Component
@Path("/status")
@Api(value = "/status", description = "Status api")
public class StatusResource {
@GET
@ApiOperation(value = "Status api")
public Response status() {
return Response.ok("Status Fine").build();
}
}
| mit |
Pigeoncraft/Aurora | Project-Aurora/Profiles/Payday 2/GSI/Nodes/WeaponsNode.cs | 1294 | using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace Aurora.Profiles.Payday_2.GSI.Nodes
{
public class WeaponsNode : Node
{
private List<WeaponNode> _Weapons = new List<WeaponNode>();
public int Count { get { return _Weapons.Count; } }
public WeaponNode SelectedWeapon
{
get
{
foreach (WeaponNode weapon in _Weapons)
{
if (weapon.IsSelected)
return weapon;
}
return new WeaponNode("");
}
}
internal WeaponsNode(string JSON) : base(JSON)
{
foreach (JToken jt in _ParsedData.Children())
{
_Weapons.Add(new WeaponNode(jt.First.ToString()));
}
}
/// <summary>
/// Gets the weapon with index <index>
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public WeaponNode this[int index]
{
get
{
if (index > _Weapons.Count - 1)
{
return new WeaponNode("");
}
return _Weapons[index];
}
}
}
}
| mit |
Edimartin/edk-source | edk/LUT/LUT3D.cpp | 22850 | #include "LUT3D.h"
/*
Library C++ LUT - Create, save and load LUT (Look Up Table) 3D
Copyright 2013 Eduardo Moura Sales Martins ([email protected])
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.
*/
edk::LUT3D::LUT3D(){
//
this->cube=NULL;
this->size=0u;
this->imageSize = 0u;
}
edk::LUT3D::~LUT3D(){
//
this->deleteTable();
}
//calculate the imageSize
edk::size2ui32 edk::LUT3D::calcImageSize(edk::uint16 size){
edk::uint32 vecSize = size*size*size;
edk::uint32 result = (edk::uint32)edk::Math::squareRootInt64(vecSize);
edk::uint8 increment=0u;
if(vecSize%result){
increment=1u;
}
edk::size2ui32 ret = edk::size2ui32(result,(vecSize/result) + increment);
return ret;
}
//create a new table
bool edk::LUT3D::newTable(edk::uint16 size){
//test the size
if(size){
if(size!=this->size){
//test the size
if(size<=256 && size>1u){
//delete the table and create a new one
this->deleteTable();
//
this->size = size;
this->imageSize = this->calcImageSize(this->size);
//create a new table
this->cube = new edk::color3ui8**[this->size];
if(this->cube){
//clean the values
for(edk::uint16 x = 0u;x<this->size;x++){
this->cube[x] = NULL;
}
//
for(edk::uint16 x = 0u;x<this->size;x++){
this->cube[x] = new edk::color3ui8*[this->size];
if(this->cube[x]){
//clean the values
for(edk::uint16 y = 0u;y<this->size;y++){
this->cube[x][y] = NULL;
}
for(edk::uint16 y = 0u;y<this->size;y++){
this->cube[x][y] = new edk::color3ui8[this->size];
if(!this->cube[x][y]){
//delete all anothers
for(edk::uint16 yd = 0u;yd<y;yd++){
if(this->cube[x][yd]){
delete[] this->cube[x][yd];
this->cube[x][yd]=NULL;
}
}
//delete the r
delete[] this->cube[x];
this->cube[x] = NULL;
break;
}
}
}
if(!this->cube[x]){
//else delete
for(edk::uint16 xd = 0u;xd<x;xd++){
if(this->cube[xd]){
//delete all inside
for(edk::uint16 y = 0u;y<this->size;y++){
if(this->cube[xd][y]){
delete[] this->cube[xd][y];
this->cube[xd][y]=NULL;
}
}
delete[] this->cube[xd];
this->cube[xd] = NULL;
}
}
//delete the cube
delete[] this->cube;
this->cube=NULL;
this->size = 0u;
this->imageSize = 0u;
break;
}
}
}
}
}
//test if have the table
if(this->cube){
//
return this->cleanTable();
}
}
//delete the table
return false;
}
//delete the table
bool edk::LUT3D::deleteTable(){
if(this->cube && this->size){
for(edk::uint16 x = 0u;x<size;x++){
for(edk::uint16 y = 0u;y<size;y++){
delete[] this->cube[x][y];
}
delete[] this->cube[x];
}
delete[] this->cube;
this->cube = NULL;
this->size = 0u;
this->imageSize = 0u;
return true;
}
this->cube = NULL;
this->size = 0u;
this->imageSize = 0u;
return false;
}
//clean the table values
bool edk::LUT3D::cleanTable(){
//test if have the table
edk::uint16 multiply = 256/(this->size - 1);
edk::uint16 value = 0u;
if(this->cube && this->size){
for(edk::uint16 x = 0u;x<size;x++){
for(edk::uint16 y = 0u;y<size;y++){
for(edk::uint16 z = 0u;z<size;z++){
value = x * multiply;
if(value>=255)value=255;
this->cube[x][y][z].r = value;
value = y * multiply;
if(value>=255)value=255;
this->cube[x][y][z].g = value;
value = z * multiply;
if(value>=255)value=255;
this->cube[x][y][z].b = value;
}
}
}
return true;
}
return false;
}
//print the table for debug
bool edk::LUT3D::printTable(){
//test if have the table
if(this->cube && this->size){
printf("\nTable size %u (%u)"
,this->getSize()
,this->getVectorSize()
);
for(edk::uint16 x = 0u;x<size;x++){
for(edk::uint16 y = 0u;y<size;y++){
for(edk::uint16 z = 0u;z<size;z++){
printf("\n[%u][%u][%u] == (%u,%u,%u)"
,x
,y
,z
,this->cube[x][y][z].r
,this->cube[x][y][z].g
,this->cube[x][y][z].b
);
}
}
}
return true;
}
return false;
}
//return the size of the table. As a cube it only need return one value
edk::uint16 edk::LUT3D::getSize(){
return this->size;
}
//return the vector size
edk::uint32 edk::LUT3D::getVectorSize(){
return (edk::uint32)this->size*this->size*this->size;
}
//return the size of the image in pixels
edk::size2ui32 edk::LUT3D::getImageSize(){
return this->imageSize;
}
edk::uint32 edk::LUT3D::getImageWidth(){
return this->imageSize.width;
}
edk::uint32 edk::LUT3D::getImageHeight(){
return this->imageSize.height;
}
//save the table into a .cube file
bool edk::LUT3D::saveTo(edk::char8* fileName){
//create the file
edk::File file;
if(file.createAndOpenTextFile(fileName)){
//Write the fileTitle
file.writeText("TITLE \"");
file.writeText(fileName);
file.writeText("\"\n");
//write the size of the file
file.writeText("LUT_3D_SIZE ");
file.writeText(this->size);
file.writeText("\n");
edk::float32 percent=0.f;
if(this->cube && this->size){
for(edk::uint16 z = 0u;z<size;z++){
for(edk::uint16 y = 0u;y<size;y++){
for(edk::uint16 x = 0u;x<size;x++){
//get the value percent
percent = this->cube[x][y][z].r/255.f;
file.writeText(percent);
file.writeText(" ");
percent = this->cube[x][y][z].g/255.f;
file.writeText(percent);
file.writeText(" ");
percent = this->cube[x][y][z].b/255.f;
file.writeText(percent);
file.writeText("\n");
}
}
}
file.closeFile();
return true;
}
file.closeFile();
}
return false;
}
bool edk::LUT3D::saveTo(const edk::char8* fileName){
return this->saveTo((edk::char8*) fileName);
}
//load from file
bool edk::LUT3D::loadFrom(edk::char8* fileName){
bool ret = false;
edk::File file;
if(file.openTextFile(fileName)){
edk::char8* line = NULL;
edk::uint32 size = 0u;
edk::char8* title = NULL;
edk::char8* sizeTableStr = NULL;
edk::uint32 sizeTable = 0u;
//read the first part
while(!file.endOfFile() && file.isOpened()){
//read the line
line = file.readTextString("\n",false);
if(line){
//test the string size
if((size = edk::String::strSize(line))){
//test if is NOT a comment
if(*line!='#'){
//test if it's a TITLE
if(size>sizeof("TITLE \"\"")){
//test if it's a TITLE
if(line[0u]=='T'){
if(line[1u]=='I'){
if(line[2u]=='T'){
if(line[3u]=='L'){
if(line[4u]=='E'){
if(line[5u]==' '){
if(line[6u]=='"'){
if(line[size-1u]=='"'){
if(!title){
line[size-1u]='\0';
//read the title
title = edk::String::strCopy(&line[7u]);
}
else{
//else close the file
file.closeFile();
}
}
}
}
}
}
}
}
}
}
//test if it's a LUT_3D_SIZE
if(size>sizeof("LUT_3D_SIZE ")){
if(line[0u]=='L'){
if(line[1u]=='U'){
if(line[2u]=='T'){
if(line[3u]=='_'){
if(line[4u]=='3'){
if(line[5u]=='D'){
if(line[6u]=='_'){
if(line[7u]=='S'){
if(line[8u]=='I'){
if(line[9u]=='Z'){
if(line[10u]=='E'){
if(line[11u]==' '){
//test if dont have the tableSize
if(!sizeTableStr){
//12u
//read the sizeTableStr
sizeTableStr = edk::String::strCopy(&line[12u]);
if(sizeTableStr){
//read the sizeTableStr
sizeTable = edk::String::strToInt32(sizeTableStr);
}
}
else{
//else close the file
file.closeFile();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
//delete the line
delete[] line;
//test if have the title and the sizeTableStr
if(title && sizeTableStr){
//break
break;
}
}
}
//test if have the title and the size
if(title && sizeTableStr && sizeTable && file.isOpened()){
//create the new table
if(this->newTable(sizeTable)){
edk::uint32 position2 = 0u;
edk::uint32 position3 = 0u;
edk::float32 percent=0.f;
bool haveEnd = false;
//read the values
for(edk::uint16 z = 0u;z<this->size;z++){
for(edk::uint16 y = 0u;y<this->size;y++){
for(edk::uint16 x = 0u;x<this->size;x++){
//get the value percent
//test if the file is opened and are not in the end of the file
while(file.isOpened() && !file.endOfFile()){
//read the line
line = file.readTextString("\n",false);
if(line){
//test the string size
if((size = edk::String::strSize(line))){
//test if is NOT a comment
if(*line!='#'){
//read the values
if((position2 = edk::String::stringHaveChar(line,' '))){
//read the x
percent = edk::String::strToFloat32(line);
this->cube[x][y][z].r = (edk::uint8)(percent*255.f)+1u;
if((position3 = edk::String::stringHaveChar(&line[position2],' '))){
//
position3 += position2;
//read the y
percent = edk::String::strToFloat32(&line[position2]);
this->cube[x][y][z].g = (edk::uint8)(percent*255.f)+1u;
//read the z
percent = edk::String::strToFloat32(&line[position3]);
this->cube[x][y][z].b = (edk::uint8)(percent*255.f)+1u;
}
else{
haveEnd=true;
}
}
else{
haveEnd=true;
}
}
//delete the line readed
delete[] line;
break;
}
//delete the line readed
delete[] line;
}
}
if(!file.isOpened() || file.endOfFile()){
haveEnd=true;
}
if(haveEnd)
break;
}
if(haveEnd)
break;
}
if(haveEnd)
break;
//test if copy all the values
if(z>=this->size-1u){
//return true
ret = true;
break;
}
}
}
}
//delete the title
if(title)
delete[] title;
if(sizeTableStr){
delete[] sizeTableStr;
}
//test if is not returning true
if(!ret){
//delete the table
this->deleteTable();
}
//read the lines
file.closeFile();
}
return ret;
}
bool edk::LUT3D::loadFrom(const edk::char8* fileName){
return this->loadFrom((edk::char8*) fileName);
}
//save to an image file
bool edk::LUT3D::saveToImage(edk::char8* fileName){
if(this->cube && this->size){
//test the fileName
if(fileName){
//create the image
edk::Image2D image;
edk::uint8* vec = NULL;
if(image.newImage(fileName,this->getImageSize(),3u)){
if((vec = image.getPixels())){
//copy the pixels
for(edk::uint16 z = 0u;z<size;z++){
for(edk::uint16 y = 0u;y<size;y++){
for(edk::uint16 x = 0u;x<size;x++){
//get the value percent
vec[0u] = this->cube[x][y][z].r;
vec[1u] = this->cube[x][y][z].g;
vec[2u] = this->cube[x][y][z].b;
vec+=3u;
}
}
}
//save the image
if(image.saveToFile(fileName)){
image.deleteImage();
return true;
}
}
image.deleteImage();
}
}
}
return false;
}
bool edk::LUT3D::saveToImage(const edk::char8* fileName){
return this->saveToImage((edk::char8*) fileName);
}
//load from an imageFile
bool edk::LUT3D::loadFromImage(edk::uint16 size,edk::char8* fileName){
//create the new table
if(this->newTable(size)){
if(this->cube && this->size){
//test the fileName
if(fileName){
//load the imageFile
edk::Image2D image;
edk::uint8* vec = NULL;
edk::uint8 channels = 0u;
if(image.loadFromFile(fileName)){
if((vec = image.getPixels())){
//get the channels
channels = image.getChannels();
if(channels==3u || channels==4u){
if(this->imageSize.width == image.getWidth()
&&
this->imageSize.height == image.getHeight()
){
//copy the pixels
for(edk::uint16 z = 0u;z<size;z++){
for(edk::uint16 y = 0u;y<size;y++){
for(edk::uint16 x = 0u;x<size;x++){
//get the value percent
this->cube[x][y][z].r = vec[0u];
this->cube[x][y][z].g = vec[1u];
this->cube[x][y][z].b = vec[2u];
vec+=channels;
}
}
}
image.deleteImage();
return true;
}
}
}
image.deleteImage();
}
}
}
//else delete the table
this->deleteTable();
}
return false;
}
bool edk::LUT3D::loadFromImage(edk::uint16 size,const edk::char8* fileName){
return this->loadFromImage(size,(edk::char8*) fileName);
}
| mit |
wizzardo/Tools | modules/tools-misc/src/main/java/com/wizzardo/tools/misc/UTF8Writer.java | 2273 | package com.wizzardo.tools.misc;
import com.wizzardo.tools.reflection.StringReflection;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
/**
* Created by wizzardo on 31.08.15.
*/
public class UTF8Writer extends Writer {
private static final byte[] CHARS_TRUE = new byte[]{'t', 'r', 'u', 'e'};
private static final byte[] CHARS_FALSE = new byte[]{'f', 'a', 'l', 's', 'e'};
private static final byte[] CHARS_NULL = new byte[]{'n', 'u', 'l', 'l'};
protected OutputStream out;
protected int batchSize = 1024;
protected byte[] bytes = new byte[batchSize * 4];
public UTF8Writer(OutputStream out) {
this.out = out;
}
@Override
public void write(char[] chars, int off, int len) throws IOException {
int limit = len + off;
for (int i = off; i < limit; i += batchSize) {
int l = UTF8.encode(chars, off, Math.min(limit - off, batchSize), bytes);
out.write(bytes, 0, l);
}
}
public void write(int i) throws IOException {
int l = NumberToChars.toChars(i, bytes, 0);
out.write(bytes, 0, l);
}
public void write(long i) throws IOException {
int l = NumberToChars.toChars(i, bytes, 0);
out.write(bytes, 0, l);
}
public void write(String s) throws IOException {
if (s == null)
out.write(CHARS_NULL);
else
write(s, 0, s.length());
}
public void write(String s, int off, int l) throws IOException {
int offset = StringReflection.offset(s) + off;
char[] chars = StringReflection.chars(s);
write(chars, offset, l);
}
public void write(boolean b) throws IOException {
if (b)
out.write(CHARS_TRUE, 0, 4);
else
out.write(CHARS_FALSE, 0, 5);
}
@Override
public Writer append(char c) throws IOException {
if (c < 128) {
out.write((byte) c);
} else {
int l = UTF8.encode(c, bytes, 0);
out.write(bytes, 0, l);
}
return this;
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
flush();
}
}
| mit |
Thatsmusic99/HeadsPlus | src/main/java/io/github/thatsmusic99/headsplus/util/DebugManager.java | 3136 | package io.github.thatsmusic99.headsplus.util;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.UUID;
public class DebugManager {
public static void checkForConditions(String name, HashMap<String, String> conditions) {
for (UUID uuid : DebugConditions.openDebugTrackers.keySet()) {
DebugConditions debugging = DebugConditions.openDebugTrackers.get(uuid);
if (debugging.listener.equals(name)) {
for (String key : debugging.conditions.keySet()) {
if (!conditions.get(key).equals(debugging.conditions.get(key))) {
return;
}
}
CommandSender listener = getSender(uuid);
listener.sendMessage(ChatColor.GRAY + "━━━━━━━━━━━━" + ChatColor.DARK_GRAY + " ❰ " + ChatColor.RED +
"HEADSPLUS OUTPUT" + ChatColor.DARK_GRAY + " ❱ " + ChatColor.GRAY + "━━━━━━━━━━━━");
listener.sendMessage(ChatColor.RED + "Event " + ChatColor.DARK_GRAY + "» " + ChatColor.GRAY + name);
for (String key : conditions.keySet()) {
listener.sendMessage(ChatColor.RED + key + ChatColor.DARK_GRAY + " » " + ChatColor.GRAY + conditions.get(key));
}
listener.sendMessage(ChatColor.GRAY + "━━━━━━━━━━━━" + ChatColor.DARK_GRAY + " ❰ " + ChatColor.RED +
"OUTPUT END" + ChatColor.DARK_GRAY + " ❱ " + ChatColor.GRAY + "━━━━━━━━━━━━");
}
}
}
public static void addListener(CommandSender listener, String listenerClass, HashMap<String, String> conditions) {
new DebugConditions(getUUID(listener), listenerClass, conditions);
}
public static void removeListener(CommandSender listener) {
DebugConditions.openDebugTrackers.remove(getUUID(listener));
}
public static class DebugConditions {
private final String listener;
private final HashMap<String, String> conditions;
protected static final HashMap<UUID, DebugConditions> openDebugTrackers = new HashMap<>();
public DebugConditions(UUID sender, String listener, HashMap<String, String> conditions) {
this.listener = listener;
this.conditions = conditions;
openDebugTrackers.put(sender, this);
}
}
private static UUID getUUID(CommandSender listener) {
UUID uuid;
if (listener instanceof Player) {
uuid = ((Player) listener).getUniqueId();
} else {
uuid = UUID.fromString("00000000-0000-0000-0000-000000000001");
}
return uuid;
}
private static CommandSender getSender(UUID uuid) {
if (uuid.toString().equals("00000000-0000-0000-0000-000000000001")) {
return Bukkit.getConsoleSender();
} else {
return Bukkit.getPlayer(uuid);
}
}
}
| mit |
farukca/nimbos | db/migrate/20130817183906_create_nimbos_tasks.rb | 620 | class CreateNimbosTasks < ActiveRecord::Migration
def change
create_table :nimbos_tasks do |t|
t.integer :todolist_id, null: false
t.integer :user_id, null: false
t.string :task_text, null: false, limit: 255
t.string :task_code, limit: 50
t.string :i18n_code, limit: 50
t.integer :cruser_id
t.string :status, limit: 10, default: "active"
t.date :due_date
t.date :closed_date
t.string :close_text, limit: 255
t.boolean :system_task, default: false
t.integer :patron_id, null: false
t.timestamps
end
end
end
| mit |
ProtonMail/WebClient | packages/components/containers/account/AccountEasySwitchSection.tsx | 2671 | import { c } from 'ttag';
import { ImportType, PROVIDER_INSTRUCTIONS } from '@proton/shared/lib/interfaces/EasySwitch';
import { useAddresses, useModals } from '../../hooks';
import { ProviderCard } from '../../components';
import SettingsSectionWide from './SettingsSectionWide';
import SettingsParagraph from './SettingsParagraph';
import { ImportAssistantOauthModal } from '../easySwitch';
import ImportMailModal from '../easySwitch/mail/modals/ImportMailModal';
import { ImportProvider } from '../../components/easySwitch/ProviderCard';
const { GOOGLE, OUTLOOK, YAHOO, OTHER } = ImportProvider;
const AccountEasySwitchSection = () => {
const { createModal } = useModals();
const [addresses, loadingAddresses] = useAddresses();
const handleOAuthClick = () => {
createModal(
<ImportAssistantOauthModal
addresses={addresses}
defaultCheckedTypes={[ImportType.MAIL, ImportType.CALENDAR, ImportType.CONTACTS]}
/>
);
};
const handleIMAPClick = (instructions?: PROVIDER_INSTRUCTIONS) =>
createModal(<ImportMailModal addresses={addresses} providerInstructions={instructions} />);
return (
<SettingsSectionWide>
<SettingsParagraph>
{c('Info')
.t`Effortlessly and securely move your emails from your current provider to Proton. If you use Google, we also support calendar, and contacts imports.`}
</SettingsParagraph>
<div className="mb1 text-bold">{c('Info').t`Select a service provider to get started`}</div>
<div className="mt0-5">
<ProviderCard
provider={GOOGLE}
onClick={handleOAuthClick}
disabled={loadingAddresses}
className="mb1 mr1"
/>
<ProviderCard
provider={YAHOO}
onClick={() => handleIMAPClick(PROVIDER_INSTRUCTIONS.YAHOO)}
disabled={loadingAddresses}
className="mb1 mr1"
/>
<ProviderCard
provider={OUTLOOK}
onClick={() => handleIMAPClick()}
disabled={loadingAddresses}
className="mb1 mr1"
/>
<ProviderCard
provider={OTHER}
onClick={() => handleIMAPClick()}
disabled={loadingAddresses}
className="mb1"
/>
</div>
</SettingsSectionWide>
);
};
export default AccountEasySwitchSection;
| mit |
vcsjones/AuthenticodeLint | AuthenticodeLint/Rules/10007-TrustedSignatureRule.cs | 917 | using AuthenticodeExaminer;
namespace AuthenticodeLint.Rules
{
public class TrustedSignatureRule : IAuthenticodeFileRule
{
public int RuleId => 10007;
public string RuleName => "Valid Signature";
public string ShortDescription => "Validates the file has correct signatures.";
public RuleSet RuleSet => RuleSet.All;
public RuleResult Validate(string file, SignatureLogger verboseWriter, CheckConfiguration configuration)
{
var inspector = new FileInspector(file);
var result = inspector.Validate(configuration.RevocationMode);
if (result == SignatureCheckResult.Valid)
{
return RuleResult.Pass;
}
verboseWriter.LogMessage($"Authenticode signature validation failed with '{result}'.");
return RuleResult.Fail;
}
}
}
| mit |
VineRelay/VineRelayStore | server/store/models/orderModel.js | 2189 | import IoC from 'AppIoC';
import { Schema } from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';
import {
UNCONFIRMED,
CONFIRMED,
OUT_FOR_DELIVERY,
DELIVERED,
FAILED,
} from 'server/store/constants/orderStatuses';
const generateUniqueOrderNumber = async (orderModel) => {
let uniqueId = Math.random().toString(36).substr(2, 6).toUpperCase();
const result = await orderModel.find({ orderNumber: uniqueId });
if(result.length > 0) {
return generateUniqueOrderNumber(orderModel);
}
return uniqueId;
}
export const orderModel = (mongoose) => {
const orderStatuses = [
UNCONFIRMED,
CONFIRMED,
OUT_FOR_DELIVERY,
DELIVERED,
FAILED,
];
/**
* Order schema definition
* @type {Schema}
*/
const orderSchema = new Schema({
orderNumber: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
addressLine1: { type: String, required: true },
addressLine2: { type: String },
city: { type: String, required: true },
state: { type: String, required: true },
zipCode: { type: String, required: true },
phoneNumber: { type: String, required: true },
// Order status
status: {type: String, enum: orderStatuses, default: UNCONFIRMED},
});
/**
* Get readable status text for end users
* @return {string}
*/
orderSchema.method('getReadableStatusText', function() {
switch(this.status) {
case CONFIRMED:
return 'Confirmed';
case OUT_FOR_DELIVERY:
return 'Out for delivery';
case DELIVERED:
return 'Delivered';
case FAILED:
return 'Failed';
default:
return 'Unconfirmed';
}
});
orderSchema.pre("validate", async function(next) {
try {
if (! this.orderNumber) {
// Generate unique order number
this.orderNumber = await generateUniqueOrderNumber(this.constructor);
}
next();
} catch(err) {
next(err);
}
});
return mongoose.model('Order', orderSchema);
}
IoC.callable('orderModel', [
'connection',
], orderModel);
| mit |
dakstudios/auth-srv | main.go | 999 | package main
import (
"log"
"github.com/dakstudios/auth-srv/db"
"github.com/dakstudios/auth-srv/db/mongo"
"github.com/dakstudios/auth-srv/handler"
account "github.com/dakstudios/auth-srv/proto/account"
auth "github.com/dakstudios/auth-srv/proto/auth"
"github.com/micro/cli"
"github.com/micro/go-micro"
)
func main() {
service := micro.NewService(
micro.Name("org.dakstudios.srv.auth"),
micro.Flags(
cli.StringFlag{
Name: "database_url",
EnvVar: "DATABASE_URL",
Usage: "The Monogo database URL. Supports multiple hosts separated by comma",
},
),
micro.Action(func(c *cli.Context) {
if len(c.String("database_url")) > 0 {
mongo.Url = c.String("database_url")
}
}),
)
service.Init()
account.RegisterAccountServiceHandler(service.Server(), new(handler.Account))
auth.RegisterAuthHandler(service.Server(), new(handler.Auth))
if err := db.Init(); err != nil {
log.Fatal(err)
}
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
| mit |
plzen/ebay | lib/ebay_trading/types/charity_seller.rb | 884 | require 'ebay_trading/types/charity_affiliation'
module EbayTrading # :nodoc:
module Types # :nodoc:
# == Attributes
# text_node :charity_seller_status, 'CharitySellerStatus', :optional => true
# array_node :charity_affiliations, 'CharityAffiliation', :class => CharityAffiliation, :default_value => []
# boolean_node :terms_and_conditions_accepted, 'TermsAndConditionsAccepted', 'true', 'false', :optional => true
class CharitySeller
include XML::Mapping
include Initializer
root_element_name 'CharitySeller'
text_node :charity_seller_status, 'CharitySellerStatus', :optional => true
array_node :charity_affiliations, 'CharityAffiliation', :class => CharityAffiliation, :default_value => []
boolean_node :terms_and_conditions_accepted, 'TermsAndConditionsAccepted', 'true', 'false', :optional => true
end
end
end
| mit |
Expertime/debug-sharepoint-javascript-sources | background.js | 2536 | /** global constants */
const browser = chrome;
// key to store the 'enabled' flag value in localStorage
const enabledKey = 'SpJsDebug_enabled';
const requestFilters = {
'urls': [
'*://*.sharepointonline.com/*/_layouts/15/*/*.js',
'*://*.sharepoint.com/_layouts/15/*/*.js'
],
'types': ['script']
};
const keepPattern = /(\.debug|start)\.js$/;
/** startup actions */
localStorage.setItem(enabledKey, false); // disabling at startup
browser.browserAction.onClicked.addListener(setEnabled);
/**
* For changing the request listener status (that will give access to debug-version of js files).
*/
function setEnabled() {
// switching the actual 'enabled' flag value
const enabled = localStorage.getItem(enabledKey) != 'true';
if (enabled) {
// enabled -> add request listener
browser.webRequest.onBeforeRequest.addListener(onBeforeRequestListener, requestFilters, ['blocking']);
} else {
// disabled -> remove request listener
browser.webRequest.onBeforeRequest.removeListener(onBeforeRequestListener);
}
// setting icon according to enabled status
browser.browserAction.setIcon({
'path': `/icons/icon19${enabled ? '' : '_disabled'}.png`
});
// saving the enabled flag value
localStorage.setItem(enabledKey, enabled);
}
/**
* Request listener : will give access to debug-version of js files by performing redirection.
*
* @param {Object} request - The request that is being listened.
*/
function onBeforeRequestListener(request) {
const requestUrl = request.url;
const debugUrl = requestUrl.replace(/\.js$/, '.debug.js');
let response = {};
if (shouldRedirectUrl(requestUrl, debugUrl, keepPattern)) {
response.redirectUrl = debugUrl;
console.info(`redirecting ${requestUrl} to ${debugUrl}`);
} else {
console.warn(`not redirecting ${requestUrl}`);
}
return response;
}
/**
* Decide wether to perform redirection from originalUrl to redirectUrl.
*
* @param {url} originalUrl - Url to be redirected from.
* @param {url} redirectUrl - Url to redirect to.
* @param {pattern} pattern - If originalUrl matches this pattern, no redirection.
*/
function shouldRedirectUrl(originalUrl, redirectUrl, pattern) {
if (originalUrl.match(pattern)) return false; // if originalUrl matches pattern, keep originalUrl
const request = new XMLHttpRequest();
request.open('GET', redirectUrl, false); // 'false' makes the request synchronous
request.send(null);
return (request.status === 200); // if redirectUrl exists keep it, otherwise use originalUrl
}
| mit |
dejv78/ctc-react | src/components/layout-view/JunctionLyxelView.js | 1009 | import React from "react";
import {observer} from "mobx-react";
import {Rect, Line, Group} from "react-konva";
import TrackSegmentView, {generateTrackSegment} from "./TrackSegmentView";
import p from "../../model/Properties";
@observer
class JunctionLyxelView extends React.Component {
render() {
const l = this.props.lyxel;
const throwing = l.throwing;
const points = generateTrackSegment(l.w * p.d.lyxelSize, l.h * p.d.lyxelSize, l.segments[l.activeLeg].endpoints, 0.2);
return <Group x={l.x * p.d.lyxelSize} y={l.y * p.d.lyxelSize}>
<Rect width={l.w * p.d.lyxelSize} height={l.h * p.d.lyxelSize} fill={throwing ? p.c.prelocked : p.c.bkg}/>
<TrackSegmentView lyxel={l} segment={l.segments[(l.activeLeg === 0) ? 1 : 0]} hidden={throwing}/>
<Line points={points} closed="true" fill="black" visible={!throwing}/>
<TrackSegmentView lyxel={l} segment={l.segments[(l.activeLeg === 0) ? 0 : 1]} hidden={throwing}/>
</Group>
}
}
export default JunctionLyxelView; | mit |
gslee071/georgetown-classifier | setup.py | 1807 | #!/usr/bin/env python
# setup
# Setup script for gtml
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Fri Mar 28 15:50:39 2014 -0400
#
# Copyright (C) 2014 Georgetown University
# For license information, see LICENSE.txt
#
# ID: setup.py [] [email protected] $
"""
Setup script for gtml
"""
##########################################################################
## Imports
##########################################################################
try:
from setuptools import setup
from setuptools import find_packages
except ImportError:
raise ImportError("Could not import \"setuptools\"."
"Please install the setuptools package.")
##########################################################################
## Package Information
##########################################################################
packages = find_packages(where=".", exclude=("tests", "bin", "docs", "fixtures",))
requires = []
with open('requirements.txt', 'r') as reqfile:
for line in reqfile:
requires.append(line.strip())
classifiers = (
# TODO: Add classifiers
# See: https://pypi.python.org/pypi?%3Aaction=list_classifiers
)
config = {
"name": "GtML",
"version": "0.1",
"description": "A simple classifier",
"author": "Benjamin Bengfort",
"author_email": "[email protected]",
"url": "https://github.com/bbengfort/georgetown-classifier",
"packages": packages,
"install_requires": requires,
"classifiers": classifiers,
"zip_safe": False,
"scripts": ["bin/classify.py",],
}
##########################################################################
## Run setup script
##########################################################################
if __name__ == '__main__':
setup(**config)
| mit |
fbfeix/react-icons | icons/AndroidRestaurant.js | 963 | 'use strict';
var React = require('react');
var IconBase = require(__dirname + 'components/IconBase/IconBase');
var AndroidRestaurant = React.createClass({
displayName: 'AndroidRestaurant',
render: function render() {
return React.createElement(
IconBase,
null,
React.createElement(
'g',
{ id: 'Icon_38_' },
React.createElement(
'g',
null,
React.createElement(
'g',
null,
React.createElement('path', { d: 'M164.852,279.939l61.834-60.251L73.72,71.706c-33.626,32.764-33.626,86.677,0,119.44L164.852,279.939z' }),
React.createElement('path', { d: 'M312.389,241.88c33.636,14.802,80.283,4.232,113.91-29.593c41.222-40.165,49.909-98.303,17.363-128.96 c-31.465-31.71-91.131-23.245-132.354,16.921c-34.718,33.825-45.566,79.276-30.374,110.986 C233.195,258.802,69.382,418.407,69.382,418.407L99.759,448l149.71-145.866L399.177,448l30.374-29.593L279.842,272.538 L312.389,241.88z' })
)
)
)
);
}
}); | mit |
wmzy/hiskyCrm | app/controllers/installation.js | 3788 | /**
* Module dependencies.
*/
var mongoose = require('mongoose');
var utils = require('../../lib/utils');
var extend = require('util')._extend;
var winston = require('winston');
var async = require('async');
var Installation = mongoose.model('Installation');
var User = mongoose.model('User');
exports.task = function (req, res, next) {
Installation.find()
.populate('creator', 'name')
.exec(function (err, installations) {
if (err) {
winston.error(err);
return next(err);
}
res.render('installation/task', {installations: installations});
});
};
exports.newLog = function (req, res) {
res.render('installation/newLog', {_id: req.params.installationId});
};
exports.viewLog = function (req, res, next) {
Installation.findById(req.params.installationId)
.populate('log.attachments','originalname')
.exec(function (err, installation) {
if (err) {
return next(err);
}
if (!installation.log) {
return next(new Error('not found'));
}
res.render('installation/viewLog', {log: installation.log});
});
};
exports.addLog = function (req, res, next) {
Installation.findById(req.params.installationId, function (err, installation) {
if (err) {
winston.error(err);
return next(err);
}
installation.log = extend(installation.log, req.body);
installation.state = '完成';
installation.task.to = new Date();
installation.save(function (err) {
if (err) {
winston.error(err);
req.flash('err', err);
}
res.redirect('/machine/installation/task');
});
});
};
exports.newTask = function (req, res) {
res.render('installation/newTask');
};
exports.createTask = function (req, res) {
req.body.creator = req.user;
var installation = new Installation(req.body);
installation.save(function (err) {
if (err) {
winston.error(err);
req.flash('err', err);
}
res.redirect('/machine/installation/task');
});
};
exports.edit = function (req, res, next) {
async.parallel([function (callback) {
User.find(callback);
}, function (callback) {
Installation.findById(req.params.installationId, callback);
}], function (err, results) {
if (err) {
winston.error(err);
return next(err);
}
res.render('installation/edit', {installation: results[1], users: results[0]});
});
};
exports.updateTask = function (req, res, next) {
Installation.findById(req.params.installationId, function (err, installation) {
if (err) {
winston.error(err);
return next(err);
}
installation = extend(installation, req.body);
installation.save(function (err) {
if (err) {
winston.error(err);
req.flash('err', err);
}
res.redirect('/installation');
});
});
};
exports.startTask = function (req, res, next) {
async.waterfall([function (callback) {
Installation.findById(req.params.taskId, callback);
}, function (installation, callback) {
if (installation.state !== '未开始') {
return callback(new Error('任务已经开始!'));
}
installation.state = '开始';
installation.task.from = new Date();
installation.save(callback);
}], function (err, installation) {
if (err) {
return next(err);
}
res.json(installation);
});
};
exports.deleteTask = function (req, res, next) {
async.waterfall([function (callback) {
Installation.findById(req.params.taskId, callback);
}, function (installation, callback) {
if (installation.state !== '未开始') {
return callback(new Error('只能删除未开始任务!'));
}
installation.remove(callback);
}], function (err) {
if (err) {
return next(err);
}
res.json(200);
});
};
exports.delete = function (req, res, next) {
Installation.findByIdAndRemove(req.params.installationId)
.exec(function (err) {
if (err) {
return next(err);
}
res.json(200);
});
};
| mit |
Numerico-Informatic-Systems-Pvt-Ltd/asha | asha/public_html/app/Test/Fixture/LandOwnerFixture.php | 1977 | <?php
/**
* LandOwnerFixture
*
*/
class LandOwnerFixture extends CakeTestFixture {
/**
* Fields
*
* @var array
*/
public $fields = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
'user_id' => array('type' => 'integer', 'null' => false, 'default' => null),
'owner_id' => array('type' => 'integer', 'null' => false, 'default' => null),
'land_id' => array('type' => 'integer', 'null' => false, 'default' => null),
'shared_area' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 200, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
'portion' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 200, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
'police_station' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 100, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
'charset' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 50, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
'created' => array('type' => 'datetime', 'null' => false, 'default' => null),
'modified' => array('type' => 'datetime', 'null' => false, 'default' => null),
'active' => array('type' => 'boolean', 'null' => false, 'default' => null),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1)
),
'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'InnoDB')
);
/**
* Records
*
* @var array
*/
public $records = array(
array(
'id' => 1,
'user_id' => 1,
'owner_id' => 1,
'land_id' => 1,
'shared_area' => 'Lorem ipsum dolor sit amet',
'portion' => 'Lorem ipsum dolor sit amet',
'police_station' => 'Lorem ipsum dolor sit amet',
'charset' => 'Lorem ipsum dolor sit amet',
'created' => '2013-10-17 10:17:37',
'modified' => '2013-10-17 10:17:37',
'active' => 1
),
);
}
| mit |
podgito/DataTableMapper | DataTableMapper.Tests/Mapping/TypeHelperTests.cs | 1573 | using DataTableMapper.Mapping;
using NUnit.Framework;
using Shouldly;
using System;
using System.Collections.Generic;
namespace DataTableMapper.Tests.Mapping
{
[TestFixture]
public class TypeHelperTests
{
[Test]
[TestCase(0, true)]
[TestCase(1, true)]
[TestCase(2.99f, true)]
[TestCase(2.99d, true)]
[TestCase("hello", true)]
public void IsSimpleTypeTests(object obj, bool expectedIsSimpleType)
{
//Act
var isSimpleType = TypeHelper.IsSimpleType(obj.GetType());
//Assert
Assert.AreEqual(expectedIsSimpleType, isSimpleType);
}
[Test]
[TestCase(typeof(IEnumerable<string>))]
[TestCase(typeof(List<int>))]
[TestCase(typeof(double[]))]
public void EnumerableTypesTest(Type type)
{
TypeHelper.IsEnumerable(type).ShouldBeTrue();
}
[Test]
[TestCase(typeof(string))]
[TestCase(typeof(int))]
public void NonEnumerableTypesTest(Type type)
{
TypeHelper.IsEnumerable(type).ShouldBeFalse();
}
[Test]
[TestCase(typeof(DateTime?))]
[TestCase(typeof(int?))]
public void IsNullableType(Type type)
{
TypeHelper.IsNullable(type).ShouldBeTrue();
}
[Test]
[TestCase(typeof(int))]
[TestCase(typeof(DateTime))]
public void NonNullableTypes(Type type)
{
TypeHelper.IsNullable(type).ShouldBeFalse();
}
}
} | mit |
Fullscreen/generator-redux-feature | generators/app/index.js | 1293 | 'use strict';
var Generator = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
module.exports = Generator.extend({
initializing: function () {
this.argument('featureName', {
desc: 'The name of the redux feature. This will be the folder name.',
type: String,
required: true,
default: 'feature'
});
},
prompting: function () {
var featureName = this.options.featureName;
// Have Yeoman greet the user.
this.log(yosay(
'Welcome to the rad ' + chalk.red('generator-redux-feature') + ' generator!'
));
var prompts = [{
type: 'confirm',
name: 'shouldCreate',
message: 'Create ' + featureName + ' folder in ' + this.destinationRoot() + ' ?',
default: true
}];
return this.prompt(prompts)
.then(function (props) {
if (!props.shouldCreate) {
console.log('Generator cancelled.');
process.exit(1);
}
// To access props later use this.props.`property`;
this.props = props;
}.bind(this));
},
writing: function () {
var featureName = this.options.featureName;
this.fs.copyTpl(
this.templatePath('feature'),
this.destinationPath(featureName),
{ featureName: featureName }
);
}
});
| mit |
cuckata23/wurfl-data | data/mot_k1t_ver1.php | 474 | <?php
return array (
'id' => 'mot_k1t_ver1',
'fallback' => 'mot_k1_ver1',
'capabilities' =>
array (
'softkey_support' => 'true',
'columns' => '17',
'rows' => '11',
'resolution_width' => '176',
'resolution_height' => '220',
'colors' => '65536',
'max_deck_size' => '10000',
'mms_max_size' => '307200',
'mms_max_width' => '1600',
'mms_max_height' => '1200',
'uaprof2' => 'http://uaprof.movistar.mx/Motorola/k1.rdf',
),
);
| mit |
arifah17/iDollykppl | application/views/admin/pro_update.php | 4358 | <?php
if($this->session->userdata('role')!="admin"){
redirect('Admin/index');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Update product Panel</title>
<!-- Bootstrap Core CSS -->
<link href="<?php echo base_url();?>assets/adm/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="<?php echo base_url();?>assets/adm/vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="<?php echo base_url();?>assets/adm/dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="<?php echo base_url();?>assets/adm/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Product</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
Update Product
<a style="float: right;" href="<?php echo base_url()."index.php/product/readProduct"; ?>">Show Product</a>
</div>
<div class="panel-body">
<form method="POST" action="<?php echo base_url()."index.php/product/Updatedata/$id"; ?>" enctype="multipart/form-data">
<div class="form-group">
<label>ID.product</label>
<input name="id" class="form-control" value="<?php echo $id;?>" readonly>
</div>
<div class="form-group">
<label>Product Name</label>
<input name="nama_product" class="form-control" value="<?php echo $nama_product;?>" readonly>
</div>
<div class="form-group">
<label>Deskripsi</label>
<textarea name="deskripsi" class="form-control" rows="3" value=""><?php echo $deskripsi;?></textarea>
</div>
<div class="form-group">
<label>Harga</label>
<input name="harga" class="form-control" value="<?php echo $harga;?>">
</div>
<div class="form-group">
<label>Gambar</label>
<img style="width: 250px; height: 200px;" src="<?php echo base_url()."upload/".$gambar;?>">
<input name="gambar" type="file">
</div>
<button type="submit">Add Product</button>
</form>
</div>
</div>
</div>
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="../vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="../vendor/metisMenu/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>
</body>
</html>
| mit |
logust79/phenopolis | tests/helper.py | 137 |
def login(app):
return app.post('/login', data=dict(
name='demo',
password='demo123'
), follow_redirects=True)
| mit |
Seeed-Studio/ArduinoPhone | Libraries/ArduinoPhone/phone.cpp | 3243 | /*
phone.cpp
Author:Loovee
2013-9-10
The MIT License (MIT)
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 "phone.h"
#include <TimerOne.h>
#if PHONESOFTSERIAL
#include <SoftwareSerial.h>
#endif
#include <Arduino.h>
#include "UI_ArduinoPhone.h"
#if PHONESOFTSERIAL
SoftwareSerial mySerial(7, 8);
#endif
void phone::init()
{
#if PHONESOFTSERIAL
mySerial.begin(19200); // the Serial1 baud rate
#else
Serial.begin(19200);
#endif
Serial.println("ATH");
}
void phone::msgSend()
{
Serial.print("AT+CMGF=1\r");
delay(100);
// Serial.println("AT + CMGS = \"+8613425171053\"");
Serial.print("AT + CMGS = \"");
Serial.print(UI.msgNum);
Serial.println("\"");
delay(100);
Serial.println(UI.msg);
Serial.println((char)26);
//delay(100);
Serial.println();
}
void phone::makeCall()
{
#if PHONESOFTSERIAL
mySerial.print("ATD + ");
#else
// Serial.print("ATD + ");
Serial.print("ATD");
#endif
#if PHONESOFTSERIAL
mySerial.println(UI.callNum);
#else
Serial.println(UI.callNum);
#endif
//delay(100);
#if PHONESOFTSERIAL
mySerial.println();
#else
Serial.println();
#endif
}
bool phone::isMsg(char *str) // check if get some message
{
if(strCmp(8, str, "CMTI: \"SM\","))return 1;
else return 0;
}
bool phone::isMsgSendOver()
{
// add code here
delay(1000);
return 1;
}
bool phone::strCmp(unsigned char n, char *p1, const char *p2)
{
char *pt = p1;
while(*(pt)<'A' || *(pt)>'Z')
{
pt++;
}
for(int i = 0; i<n; i++)
{
if(*(pt+i) == *(p2+i))continue;
else return 0;
}
return 1;
}
bool phone::isCall(char *str) // check if some one call
{
if(strCmp(4, str, "RING"))return 1;
return 0;
}
bool phone::isCallOver(char *str) // check if call over
{
// add code here
if(strCmp(5, str, "NO CARRIER"))return 1;
return 0;
}
// hand up a call
void phone::handUpCall()
{
#if PHONESOFTSERIAL
mySerial.println("ATH");
#else
Serial.println("ATH");
#endif
}
void phone::acceptCall()
{
#if PHONESOFTSERIAL
mySerial.println("ATA");
#else
Serial.println("ATA");
#endif
}
phone Phone; | mit |
CoasterPoll/CoasterPoll | resources/views/sharing/sidebar.blade.php | 194 | @auth
<a href="{{ route('links.submit') }}" class="btn btn-outline-primary btn-block @isset($submitBtnActive) @if($submitBtnActive) active disabled @endif @endisset">Submit New</a>
@endauth | mit |
ioBroker/ioBroker.admin | src-rx/src/components/JsonConfigComponent/ConfigCustomEasyAccess.js | 5573 | import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Checkbox from '@material-ui/core/Checkbox';
import I18n from '@iobroker/adapter-react/i18n';
import ConfigGeneric from './ConfigGeneric';
const styles = theme => ({
table: {
minWidth: 400
},
header: {
fontSize: 16,
fontWeight: 'bold'
}
});
class ConfigCustomEasyAccess extends ConfigGeneric {
componentDidMount() {
super.componentDidMount();
this.props.socket.getAdapterInstances()
.then(instances => {
instances = instances
.filter(instance =>
instance?.common?.adminUI && (instance.common.adminUI.config !== 'none' || instance.common.adminUI.tab))
.map(instance => ({
id: instance._id.replace(/^system\.adapter\./, ''),
config: instance.common.adminUI.config !== 'none',
adminTab: instance.common.adminTab
}))
.sort((a, b) => a.id > b.id ? 1 : (a.id < b.id ? -1 : 0));
this.setState({instances});
});
}
renderItem(error, disabled, defaultValue) {
if (!this.state.instances) {
return null;
} else {
const accessAllowedConfigs = ConfigGeneric.getValue(this.props.data, 'accessAllowedConfigs') || [];
const accessAllowedTabs = ConfigGeneric.getValue(this.props.data, 'accessAllowedTabs') || [];
return <TableContainer>
<Table className={this.props.classes.table} size="small">
<TableHead>
<TableRow>
<TableCell className={this.props.classes.header}>{I18n.t('Instance')}</TableCell>
<TableCell className={this.props.classes.header}>{I18n.t('Config')}</TableCell>
<TableCell className={this.props.classes.header}>{I18n.t('Tab')}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.instances.map((row) => (
<TableRow key={row.id}>
<TableCell component="th" scope="row">{row.id}</TableCell>
<TableCell>
{row.config ?
<Checkbox checked={accessAllowedConfigs.includes(row.id)}
onClick={() => {
const _accessAllowedConfigs = [...accessAllowedConfigs];
const pos = _accessAllowedConfigs.indexOf(row.id);
if (pos !== -1) {
_accessAllowedConfigs.splice(pos, 1);
} else {
_accessAllowedConfigs.push(row.id);
_accessAllowedConfigs.sort();
}
this.onChange('accessAllowedConfigs', _accessAllowedConfigs);
}}
/>
: null}</TableCell>
<TableCell>
{row.adminTab ?
<Checkbox
checked={accessAllowedTabs.includes(row.id)}
onClick={() => {
const _accessAllowedTabs = [...accessAllowedTabs];
const pos = _accessAllowedTabs.indexOf(row.id);
if (pos !== -1) {
_accessAllowedTabs.splice(pos, 1);
} else {
_accessAllowedTabs.push(row.id);
_accessAllowedTabs.sort();
}
this.onChange('accessAllowedTabs', _accessAllowedTabs);
}}
/> : null}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>;
}
}
}
ConfigCustomEasyAccess.propTypes = {
socket: PropTypes.object.isRequired,
themeType: PropTypes.string,
themeName: PropTypes.string,
style: PropTypes.object,
className: PropTypes.string,
data: PropTypes.object.isRequired,
schema: PropTypes.object,
onError: PropTypes.func,
onChange: PropTypes.func,
};
export default withStyles(styles)(ConfigCustomEasyAccess); | mit |
anton23/gpanalyser | src-jexpressions/uk/ac/imperial/doc/jexpressions/expressions/IntegerExpression.java | 807 | package uk.ac.imperial.doc.jexpressions.expressions;
/**
* An expression for integer valued numerical constants.
*
* @author Anton Stefanek
*
*/
public class IntegerExpression extends AbstractExpression {
private int value;
public IntegerExpression(int value) {
super();
this.value = value;
}
public int getValue() {
return value;
}
@Override
public void accept(IExpressionVisitor v) {
v.visit(this);
}
@Override
public String toString() {
return value + "";
}
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
IntegerExpression other = (IntegerExpression) obj;
if (value != other.value)
return false;
return true;
}
}
| mit |
jgarverick/sample-chart-widget | WidgetTest/scripts/app.js | 816 | /// <reference path='../node_modules/vss-web-extension-sdk/typings/VSS.d.ts' />
var Greeter = (function () {
function Greeter(element) {
this.element = element;
this.element.innerHTML += "The time is: ";
this.span = document.createElement('span');
this.element.appendChild(this.span);
this.span.innerText = new Date().toUTCString();
}
Greeter.prototype.start = function () {
var _this = this;
this.timerToken = setInterval(function () { return _this.span.innerHTML = new Date().toUTCString(); }, 500);
};
Greeter.prototype.stop = function () {
clearTimeout(this.timerToken);
};
return Greeter;
}());
var el = document.getElementById('content');
var greeter = new Greeter(el);
greeter.start();
//# sourceMappingURL=app.js.map | mit |
davidsantoso/active_merchant | test/remote/gateways/remote_psl_card_test.rb | 3329 | require 'test_helper'
class RemotePslCardTest < Test::Unit::TestCase
def setup
@gateway = PslCardGateway.new(fixtures(:psl_card))
@uk_maestro = CreditCard.new(fixtures(:psl_maestro))
@uk_maestro_address = fixtures(:psl_maestro_address)
@solo = CreditCard.new(fixtures(:psl_solo))
@solo_address = fixtures(:psl_solo_address)
@visa = CreditCard.new(fixtures(:psl_visa))
@visa_address = fixtures(:psl_visa_address)
@visa_debit = CreditCard.new(fixtures(:psl_visa_debit))
@visa_address = fixtures(:psl_visa_debit_address)
# The test results are determined by the amount of the transaction
@accept_amount = 1000
@referred_amount = 6000
@declined_amount = 11000
@keep_card_amount = 15000
end
def test_successful_visa_purchase
response = @gateway.purchase(@accept_amount, @visa,
:billing_address => @visa_address
)
assert_success response
assert response.test?
end
def test_successful_visa_debit_purchase
response = @gateway.purchase(@accept_amount, @visa_debit,
:billing_address => @visa_debit_address
)
assert_success response
end
# Fix regression discovered in production
def test_visa_debit_purchase_should_not_send_debit_info_if_present
@visa_debit.start_month = '07'
response = @gateway.purchase(@accept_amount, @visa_debit,
:billing_address => @visa_debit_address
)
assert_success response
end
def test_successful_visa_purchase_specifying_currency
response = @gateway.purchase(@accept_amount, @visa,
:billing_address => @visa_address,
:currency => 'GBP'
)
assert_success response
assert response.test?
end
def test_successful_solo_purchase
response = @gateway.purchase(@accept_amount, @solo,
:billing_address => @solo_address
)
assert_success response
assert response.test?
end
def test_referred_purchase
response = @gateway.purchase(@referred_amount, @uk_maestro,
:billing_address => @uk_maestro_address
)
assert_failure response
assert response.test?
end
def test_declined_purchase
response = @gateway.purchase(@declined_amount, @uk_maestro,
:billing_address => @uk_maestro_address
)
assert_failure response
assert response.test?
end
def test_declined_keep_card_purchase
response = @gateway.purchase(@keep_card_amount, @uk_maestro,
:billing_address => @uk_maestro_address
)
assert_failure response
assert response.test?
end
def test_successful_authorization
response = @gateway.authorize(@accept_amount, @visa,
:billing_address => @visa_address
)
assert_success response
assert response.test?
end
def test_no_login
@gateway = PslCardGateway.new(
:login => ''
)
response = @gateway.authorize(@accept_amount, @uk_maestro,
:billing_address => @uk_maestro_address
)
assert_failure response
assert response.test?
end
def test_successful_authorization_and_capture
authorization = @gateway.authorize(@accept_amount, @visa,
:billing_address => @visa_address
)
assert_success authorization
assert authorization.test?
capture = @gateway.capture(@accept_amount, authorization.authorization)
assert_success capture
assert capture.test?
end
end
| mit |
Fuzzapi/fuzzapi | config/application.rb | 1176 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module FuzzerApp
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.autoload_paths += %w(#{config.root}/app/workers)
end
end
| mit |
Yarduddles/ISO-3166 | PHP/ISO-3166-2-BZ.php | 223 | <?php
$ISO_3166_2 = array();
$ISO_3166_2['BZ'] = "Belize";
$ISO_3166_2['CY'] = "Cayo";
$ISO_3166_2['CZL'] = "Corozal";
$ISO_3166_2['OW'] = "Orange Walk";
$ISO_3166_2['SC'] = "Stann Creek";
$ISO_3166_2['TOL'] = "Toledo";
?>
| mit |
owenbutler/gamedev | planetesimal/src/main/java/org/owenbutler/planetesimal/renderables/Asteroid1.java | 1170 | package org.owenbutler.planetesimal.renderables;
import org.owenbutler.planetesimal.constants.AssetConstants;
import org.owenbutler.planetesimal.constants.GameConstants;
public class Asteroid1
extends BaseAsteroid {
public Asteroid1(float x, float y) {
super(AssetConstants.gfx_asteroid1, x, y, GameConstants.ASTEROID1_WIDTH, GameConstants.ASTEROID1_HEIGHT);
setCollidable(true);
setCollisionRadius(25.0f);
setRandomRotation();
getSurface().enableAnimation(null, 4, 4);
getSurface().selectAnimationFrame(0);
endFrame = 10;
setHealth(GameConstants.ASTEROID1_HEALTH);
setSmokes(3);
dustSpawnMod = 50;
}
public void think() {
baseDrawableThink();
}
protected void killed() {
destroy();
for (int i = 0; i < GameConstants.ASTEROID1_DEBRI; ++i) {
Asteroid2 asteroid2 = new Asteroid2(x, y);
asteroid2.setVelocityFromParent(velX, velY);
gameEngine.addGameObject(asteroid2);
}
gameEngine.getAudioManager().loadOrGetSample(AssetConstants.snd_asteroidDestroy).playSample();
}
}
| mit |
gsteacy/ts-loader | examples/vanilla-jsts/webpack.config.js | 350 | 'use strict';
module.exports = {
devtool: 'inline-source-map',
entry: './src/index.js',
output: { filename: 'dist/index.js' },
module: {
rules: [
{
test: /\.(ts|js)?$/,
loader: 'ts-loader'
}
]
},
resolve: {
extensions: [ '.ts', '.js' ]
}
};
| mit |
inoyyth/proderma | application/modules/md_manage_product/views/edit.php | 3855 | <link rel="stylesheet" href="<?php echo base_url('themes/assets/plugin/Trumbowyg-master/dist/ui/trumbowyg.min.css');?>">
<style>
.trumbowyg-box.trumbowyg-editor-visible {
min-height: 150px;
}
.trumbowyg-editor {
min-height: 150px;
}
</style>
<div class="row">
<form action="<?php echo base_url("manage-product-save"); ?>" method="post" enctype="multipart/form-data" parsley-validate novalidate>
<div class="col-lg-12">
<div class="block-web">
<div class="porlets-content">
<div class="row">
<div class="col-lg-6">
<input type="hidden" name="id_product" value="<?php echo $data['id'];?>">
<input type="hidden" name="id" value="<?php echo $detail['id'];?>">
<div class="form-group">
<label>Product Name</label>
<input type="text" value="<?php echo $data['product_name'];?>" readonly class="form-control">
</div>
<div class="form-group">
<label>Transaction Status</label>
<select name="update_status" parsley-trigger="change" required class="form-control">
<option value="I" <?php echo ($detail['update_status']== 'I' ? 'selected' :'');?>>IN</option>
<option value="O" <?php echo ($detail['update_status']== 'O' ? 'selected' :'');?>>OUT</option>
</select>
</div>
<div class="form-group">
<label>Qty</label>
<input type="text" name="qty" parsley-trigger="change" value="<?php echo $detail['qty'];?>" parsley-type="digits" required placeholder="Ex. 10" class="form-control">
</div>
<div class="form-group">
<label>Description</label>
<textarea name="description" parsley-trigger="change" required placeholder="Ex. Barang Tambahan Dari Gudang A" class="form-control trumbowyg"><?php echo $detail['description'];?></textarea>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Save</button>
<a href="<?php echo site_url('manage-product-list-'.$data['id']); ?>" class="btn btn-default">Cancel</a>
</div>
</div>
</div>
</form>
</div>
<div class="modal fade bs-example-modal-lg" id="product-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
</div>
<div class="modal-footer">
<button class="btn btn-primary btn-sm" id="btn-select-modal">Select</button>
<button class="btn btn-danger btn-sm" id="btn-cancel-modal">Cancel</button>
</div>
</div>
</div>
<script src="<?php echo base_url('themes/assets/plugin/Trumbowyg-master/dist/trumbowyg.min.js');?>"></script>
<script>
$(document).ready(function (){
$('.trumbowyg').trumbowyg({
btns: [
['viewHTML'],
//['formatting'],
'btnGrp-semantic',
['superscript', 'subscript'],
//['link'],
//['insertImage'],
'btnGrp-justify',
'btnGrp-lists',
//['horizontalRule'],
['removeformat'],
['fullscreen']
],
autogrow: true,
autoAjustHeight: false,
});
});
</script> | mit |
bbc/react-bootstrap | test/NavBrandSpec.js | 905 | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
// import Navbar from '../src/Navbar';
import NavBrand from '../src/NavBrand';
describe('Navbrand', () => {
it('Should create navbrand SPAN element', () => {
let instance = ReactTestUtils.renderIntoDocument(
<NavBrand>Brand</NavBrand>
);
let brand = React.findDOMNode(instance);
assert.equal(brand.nodeName, 'SPAN');
assert.ok(brand.className.match(/\bnavbar-brand\b/));
assert.equal(brand.innerText, 'Brand');
});
it('Should create navbrand A (link) element', () => {
let instance = ReactTestUtils.renderIntoDocument(
<NavBrand><a href>BrandLink</a></NavBrand>
);
let brand = React.findDOMNode(instance);
assert.equal(brand.nodeName, 'A');
assert.ok(brand.className.match(/\bnavbar-brand\b/));
assert.equal(brand.innerText, 'BrandLink');
});
});
| mit |
twsouthwick/SourceCodeSerializer | src/SourceCodeSerializer/Converters/DateTimeConverter.cs | 458 | using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace SourceCodeSerializer.Converters
{
public sealed class DateTimeConverter : ExpressionConverter<DateTime>
{
public override ExpressionSyntax ConvertToExpression(Type type, DateTime obj, SourceCodeSerializer serializer)
{
return ParseExpression($"new DateTime({obj.Ticks})");
}
}
}
| mit |
e1cerebro/smartlib | application/views/front/contact.php | 6010 |
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Us | Smart Library</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Google Fonts -->
<link href='http://fonts.googleapis.com/css?family=Roboto:400,900italic,700italic,900,700,500italic,500,400italic,300italic,300,100italic,100|Open+Sans:400,300,400italic,300italic,600,600italic,700italic,700,800|Source+Sans+Pro:400,200,200italic,300,300italic,400italic,600,600italic,700' rel='stylesheet' type='text/css'>
<!-- Styles -->
<link href="<?= cssPath("bootstrap.css") ?>" rel="stylesheet" type="text/css" />
<link href="<?= fontPath("css/font-awesome.css") ?>" rel="stylesheet" type="text/css" />
<link href="<?= cssPath("style.css") ?>" rel="stylesheet" type="text/css" />
<link href="<?= cssPath("responsive.css") ?>" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="<?= layersliderPath("css/layerslider.css") ?>" type="text/css">
<link rel="icon" type="image/png" sizes="16x16" href="<?= imagePath("favicon.png"); ?>">
<link href="<?= cssPath("contact.css") ?>" rel="stylesheet" type="text/css" /> <!-- AJAX Contact Form Stylesheet -->
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="css/ie.css" />
<script type="text/javascript" language="javascript" src="js/html5shiv.js"></script>
<![endif]-->
<!-- Scripts -->
<script src="<?= jsPath("jquery.1.9.1.js") ?>" type="text/javascript"></script>
<script src='<?= jsPath("testimonials.js") ?>'></script>
<script src="<?= jsPath("jquery.carouFredSel-6.2.1-packed.js") ?>" type="text/javascript"></script>
<script src='<?= jsPath("script.js") ?>'></script>
<script src='<?= jsPath("bootstrap.js") ?>'></script>
<script src="<?= jsPath("html5lightbox.js") ?>"></script>
<script src="<?= jsPath("jquery.countdown.js") ?>"></script>
<script type="text/javascript" src="<?= jsPath("jquery.jigowatt.js") ?>"></script><!-- AJAX Form Submit -->
<script defer src="<?= jsPath("jquery.flexslider.js") ?>"></script>
<script defer src="<?= jsPath("jquery.mousewheel.js") ?>"></script>
<script defer src="<?= jsPath("myjs/testing.js") ?>"></script>
<!-- Scripts For Layer Slider -->
<script src="<?= layersliderPath("JQuery/jquery-easing-1.3.js") ?>" type="text/javascript"></script>
<script src="<?= layersliderPath("JQuery/jquery-easing-1.3.js") ?>" type="text/javascript"></script>
<script src="<?= layersliderPath("js/layerslider.transitions.js") ?>" type="text/javascript"></script>
<script src="<?= layersliderPath("js/layerslider.kreaturamedia.jquery.js") ?>" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#layerslider').layerSlider({
skinsPath : base_url()+'resources/layerslider/skins/',
skin : 'defaultskin',
responsive: true,
responsiveUnder: 1200,
pauseOnHover: false,
showCircleTimer: false,
navStartStop:false,
navButtons:false,
}); // LAYER SLIDER
});
</script>
<script>
$(window).load(function(){
$('.causes-carousel').flexslider({
animation: "slide",
animationLoop: false,
controlNav: false,
pausePlay: false,
mousewheel:true,
start: function(slider){
$('body').removeClass('loading');
}
});
$('.footer_carousel').flexslider({
animation: "slide",
animationLoop: false,
slideShow:false,
controlNav: true,
maxItems: 1,
pausePlay: false,
mousewheel:true,
start: function(slider){
$('body').removeClass('loading');
}
});
});
</script>
<script>
$(window).load(function(){
});
</script>
</head><!-- Head -->
<body>
<div class="theme-layout">
<?php $this->load->view("_partials/header");?>
<section class="page switch" >
<div class="container" style="width: 100%; height: auto; margin: 0px auto; min-height:420px;">
<div class="page-title">
<h1>Contact<span> Us</span></h1>
</div><!-- Page Title -->
<div class="row">
<div class="col-md-6">
<div class="contact-info">
<h3 class="sub-head">CONTACT INFORMATION</h3>
<p>Below is our contact information.</p>
<ul class="contact-details">
<li>
<span><i class="icon-home"></i>ADDRESS</span>
<p>University of windsor, group 20 (Advanced software engineering topics)</p>
</li>
<li>
<span><i class="icon-phone-sign"></i>PHONE NO</span>
<p>Not availbale</p>
</li>
<li>
<span><i class="icon-envelope-alt"></i>EMAIL ID</span>
<p>[email protected]</p>
</li>
<li>
<span><i class="icon-link"></i>WEB ADDRESS</span>
<p>https://smartlib-e1cerebro.c9users.io/</p>
</li>
</ul>
</div>
</div> <!-- Contact Info -->
<div class="col-md-6 pull-right">
<div id="message"></div>
<div class="form">
<h3 class="sub-head">CONTACT US BY MESSAGE</h3>
<p>we love to hear from you. <span>*</span></p>
<form method="post" action="#" name="contactform" id="contactform">
<strong><p id="infoM" class="text-center text-danger"></p></strong>
<label for="name" accesskey="U">Full name <span>*</span></label>
<input name="name" id="name" required = "required" class="form-control input-field" type="text" id="name" size="30" value="" />
<label for="email" accesskey="E">Email Address <span>*</span></label>
<input name="email" id="email" required = "required" class="form-control input-field" type="email" id="email" size="30" value="" />
<label for="comments" accesskey="C">Message <span>*</span></label>
<textarea name="comments" required = "required" rows="9" id="comments" rows="7" class="form-control input-field"></textarea>
<input type="button" class="form-button submit" id="submit" value="SEND MESSAGE" />
</form>
</div>
</div> <!-- Message Form -->
</div>
</div>
</div>
</section>
</div>
<?php $this->load->view("_partials/footer");?>
<script src="<?= base_url() ?>resources/js/myjs/contact.js" type="text/javascript"></script>
</body>
</html>
| mit |
ignaciocases/hermeneumatics | node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/collection/convert/Wrappers$SeqWrapper$.js | 4096 | /** @constructor */
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$ = (function() {
ScalaJS.c.java_lang_Object.call(this);
this.$$outer$1 = null
});
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype = new ScalaJS.inheritable.java_lang_Object();
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.constructor = ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$;
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.toString__T = (function() {
return "SeqWrapper"
});
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.apply__Lscala_collection_Seq__Lscala_collection_convert_Wrappers$SeqWrapper = (function(underlying) {
return new ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper().init___Lscala_collection_convert_Wrappers__Lscala_collection_Seq(this.$$outer$1, underlying)
});
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.unapply__Lscala_collection_convert_Wrappers$SeqWrapper__Lscala_Option = (function(x$0) {
if (ScalaJS.anyRefEqEq(x$0, null)) {
return ScalaJS.modules.scala_None()
} else {
return new ScalaJS.c.scala_Some().init___O(x$0.underlying__Lscala_collection_Seq())
}
});
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.readResolve__p1__O = (function() {
return this.$$outer$1.SeqWrapper__Lscala_collection_convert_Wrappers$SeqWrapper$()
});
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.init___Lscala_collection_convert_Wrappers = (function($$outer) {
if (($$outer === null)) {
throw new ScalaJS.c.java_lang_NullPointerException().init___()
} else {
this.$$outer$1 = $$outer
};
ScalaJS.c.java_lang_Object.prototype.init___.call(this);
return this
});
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.unapply__Lscala_collection_convert_Wrappers$SeqWrapper__ = (function(x$0) {
return this.unapply__Lscala_collection_convert_Wrappers$SeqWrapper__Lscala_Option(x$0)
});
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.apply__Lscala_collection_Seq__ = (function(underlying) {
return this.apply__Lscala_collection_Seq__Lscala_collection_convert_Wrappers$SeqWrapper(underlying)
});
/** @constructor */
ScalaJS.inheritable.scala_collection_convert_Wrappers$SeqWrapper$ = (function() {
/*<skip>*/
});
ScalaJS.inheritable.scala_collection_convert_Wrappers$SeqWrapper$.prototype = ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype;
ScalaJS.is.scala_collection_convert_Wrappers$SeqWrapper$ = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_convert_Wrappers$SeqWrapper$)))
});
ScalaJS.as.scala_collection_convert_Wrappers$SeqWrapper$ = (function(obj) {
if ((ScalaJS.is.scala_collection_convert_Wrappers$SeqWrapper$(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.collection.convert.Wrappers$SeqWrapper")
}
});
ScalaJS.isArrayOf.scala_collection_convert_Wrappers$SeqWrapper$ = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_convert_Wrappers$SeqWrapper$)))
});
ScalaJS.asArrayOf.scala_collection_convert_Wrappers$SeqWrapper$ = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_collection_convert_Wrappers$SeqWrapper$(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.collection.convert.Wrappers$SeqWrapper;", depth)
}
});
ScalaJS.data.scala_collection_convert_Wrappers$SeqWrapper$ = new ScalaJS.ClassTypeData({
scala_collection_convert_Wrappers$SeqWrapper$: 0
}, false, "scala.collection.convert.Wrappers$SeqWrapper$", ScalaJS.data.java_lang_Object, {
scala_collection_convert_Wrappers$SeqWrapper$: 1,
scala_Serializable: 1,
java_io_Serializable: 1,
java_lang_Object: 1
});
ScalaJS.c.scala_collection_convert_Wrappers$SeqWrapper$.prototype.$classData = ScalaJS.data.scala_collection_convert_Wrappers$SeqWrapper$;
//@ sourceMappingURL=Wrappers$SeqWrapper$.js.map
| mit |
razens/vets4pet | server/core/admin/chip.py | 481 | from django.contrib import admin
from core.models import Chip, Color, Cat
class ChipAdmin(admin.ModelAdmin):
list_display = ['number', 'address', 'creation_date', 'last_update_date']
admin.site.register(Chip, ChipAdmin)
class ColorAdmin(admin.ModelAdmin):
list_display = ['name', 'code']
admin.site.register(Color, ColorAdmin)
class CatAdmin(admin.ModelAdmin):
list_display = ['name', 'breed', 'weight', 'color', 'chip']
admin.site.register(Cat, CatAdmin)
| mit |
diirt/diirt | pvmanager/datasource-test/src/test/java/org/diirt/datasource/CompositeDataSourceTest.java | 10004 | /**
* Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.datasource;
import org.diirt.datasource.test.MockDataSource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
/**
* Tests CompositeDataSource.
*
* @author carcassi
*/
public class CompositeDataSourceTest {
@Before
public void setUp() {
mock1 = new MockDataSource();
mock2 = new MockDataSource();
}
@After
public void tearDown() {
}
MockDataSource mock1;
MockDataSource mock2;
@Test
public void testAllDefault() {
// Setup composite
CompositeDataSource composite = new CompositeDataSource();
composite.putDataSource("mock1", mock1);
composite.putDataSource("mock2", mock2);
composite.setConfiguration(new CompositeDataSourceConfiguration().defaultDataSource("mock1"));
// Call only default
ReadRecipeBuilder builder = new ReadRecipeBuilder();
builder.addChannel("pv01", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("pv03", new ValueCacheImpl<Double>(Double.class));
ReadRecipe recipe = builder.build(new ValueCacheImpl<Exception>(Exception.class), new ConnectionCollector());
// Call and check
composite.connectRead(recipe);
assertThat(mock1.getReadRecipe().getChannelReadRecipes(), equalTo(recipe.getChannelReadRecipes()));
assertThat(mock2.getReadRecipe(), nullValue());
}
@Test
public void testMixedCall() {
// Setup composite
CompositeDataSource composite = new CompositeDataSource();
composite.putDataSource("mock1", mock1);
composite.putDataSource("mock2", mock2);
composite.setConfiguration(new CompositeDataSourceConfiguration().defaultDataSource("mock1"));
// Call only default
ReadRecipeBuilder builder = new ReadRecipeBuilder();
builder.addChannel("pv01", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("pv03", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("mock1://pv02", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("mock2://pv04", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("mock1://pv05", new ValueCacheImpl<Double>(Double.class));
ReadRecipe recipe = builder.build(new ValueCacheImpl<Exception>(Exception.class), new ConnectionCollector());
// Call and check
composite.connectRead(recipe);
Collection<ChannelReadRecipe> mock1Caches = mock1.getReadRecipe().getChannelReadRecipes();
Collection<ChannelReadRecipe> mock2Caches = mock2.getReadRecipe().getChannelReadRecipes();
assertThat(mock1Caches.size(), equalTo(4));
assertThat(mock2Caches.size(), equalTo(1));
assertThat(channelNames(mock1Caches), hasItems("pv01", "pv02", "pv03", "pv05"));
assertThat(channelNames(mock2Caches), hasItem("pv04"));
// Check close
ReadRecipe mock1Connect = mock1.getReadRecipe();
ReadRecipe mock2Connect = mock2.getReadRecipe();
composite.disconnectRead(recipe);
assertEquals(mock1Connect, mock1.getReadRecipe());
assertEquals(mock2Connect, mock2.getReadRecipe());
}
private Set<String> channelNames(Collection<ChannelReadRecipe> channelRecipes) {
Set<String> names = new HashSet<String>();
for (ChannelReadRecipe channelRecipe : channelRecipes) {
names.add(channelRecipe.getChannelName());
}
return names;
}
private Set<String> channelWriteNames(Collection<ChannelWriteRecipe> channelWriteBuffers) {
Set<String> names = new HashSet<String>();
for (ChannelWriteRecipe channelWriteBuffer : channelWriteBuffers) {
names.add(channelWriteBuffer.getChannelName());
}
return names;
}
@Test(expected=IllegalArgumentException.class)
public void testNoDefault() {
// Setup composite
CompositeDataSource composite = new CompositeDataSource();
composite.putDataSource("mock1", mock1);
composite.putDataSource("mock2", mock2);
// Call only default
ReadRecipeBuilder builder = new ReadRecipeBuilder();
builder.addChannel("pv01", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("pv03", new ValueCacheImpl<Double>(Double.class));
ReadRecipe recipe = builder.build(new ValueCacheImpl<Exception>(Exception.class), new ConnectionCollector());
// Should cause error
composite.connectRead(recipe);
}
@Test(expected=IllegalArgumentException.class)
public void testDefaultDoesntExist() {
// Setup composite
CompositeDataSource composite = new CompositeDataSource();
composite.putDataSource("mock1", mock1);
composite.putDataSource("mock2", mock2);
composite.setConfiguration(new CompositeDataSourceConfiguration().defaultDataSource("wrong"));
// Call only default
ReadRecipeBuilder builder = new ReadRecipeBuilder();
builder.addChannel("pv01", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("pv03", new ValueCacheImpl<Double>(Double.class));
ReadRecipe recipe = builder.build(new ValueCacheImpl<Exception>(Exception.class), new ConnectionCollector());
// Should cause error
composite.connectRead(recipe);
}
@Test
public void testDifferentDelimiter() {
// Setup composite
CompositeDataSource composite = new CompositeDataSource();
composite.putDataSource("mock1", mock1);
composite.putDataSource("mock2", mock2);
composite.setConfiguration(new CompositeDataSourceConfiguration().defaultDataSource("mock1").delimiter("?"));
// Call only default
ReadRecipeBuilder builder = new ReadRecipeBuilder();
builder.addChannel("pv01", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("pv03", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("mock1?pv02", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("mock2?pv04", new ValueCacheImpl<Double>(Double.class));
builder.addChannel("mock1?pv05", new ValueCacheImpl<Double>(Double.class));
ReadRecipe recipe = builder.build(new ValueCacheImpl<Exception>(Exception.class), new ConnectionCollector());
// Call and check
composite.connectRead(recipe);
Collection<ChannelReadRecipe> mock1Caches = mock1.getReadRecipe().getChannelReadRecipes();
Collection<ChannelReadRecipe> mock2Caches = mock2.getReadRecipe().getChannelReadRecipes();
assertThat(mock1Caches.size(), equalTo(4));
assertThat(mock2Caches.size(), equalTo(1));
assertThat(channelNames(mock1Caches), hasItems("pv01", "pv02", "pv03", "pv05"));
assertThat(channelNames(mock2Caches), hasItem("pv04"));
}
@Test (expected=IllegalArgumentException.class)
public void testReadEmpty() {
// Setup composite
CompositeDataSource composite = new CompositeDataSource();
ReadRecipeBuilder builder = new ReadRecipeBuilder();
builder.addChannel("mock://pv03", new ValueCacheImpl<Double>(Double.class));
ReadRecipe recipe = builder.build(new ValueCacheImpl<Exception>(Exception.class), new ConnectionCollector());
// Should cause error
composite.connectRead(recipe);
}
@Test (expected=IllegalArgumentException.class)
public void testWriteEmpty() {
// Setup composite
CompositeDataSource composite = new CompositeDataSource();
// Write pv with no datasource match
WriteRecipeBuilder builder = new WriteRecipeBuilder();
builder.addChannel("mock://pv03", new WriteCache<>("mock://pv03"));
WriteRecipe buffer = builder.build(new ValueCacheImpl<Exception>(Exception.class), new ConnectionCollector());
// Should cause error
composite.connectWrite(buffer);
}
@Test
public void testWriteMixedCall() {
// Setup composite
CompositeDataSource composite = new CompositeDataSource();
composite.putDataSource("mock1", mock1);
composite.putDataSource("mock2", mock2);
composite.setConfiguration(new CompositeDataSourceConfiguration().defaultDataSource("mock1"));
WriteRecipeBuilder builder = new WriteRecipeBuilder();
builder.addChannel("pv01", new WriteCache<>("pv01"));
builder.addChannel("pv03", new WriteCache<>("pv03"));
builder.addChannel("mock1://pv02", new WriteCache<>("mock1://pv02"));
builder.addChannel("mock2://pv04", new WriteCache<>("mock2://pv04"));
builder.addChannel("mock1://pv05", new WriteCache<>("mock1://pv05"));
WriteRecipe buffer = builder.build(new ValueCacheImpl<Exception>(Exception.class), new ConnectionCollector());
// Call and check
composite.connectWrite(buffer);
Collection<ChannelWriteRecipe> mock1Buffers = mock1.getWriteRecipe().getChannelWriteRecipes();
Collection<ChannelWriteRecipe> mock2Buffers = mock2.getWriteRecipe().getChannelWriteRecipes();
assertThat(mock1Buffers.size(), equalTo(4));
assertThat(mock2Buffers.size(), equalTo(1));
assertThat(channelWriteNames(mock1Buffers), hasItems("pv01", "pv02", "pv03", "pv05"));
assertThat(channelWriteNames(mock2Buffers), hasItem("pv04"));
// Check close
WriteRecipe mock1Connect = mock1.getWriteRecipe();
WriteRecipe mock2Connect = mock2.getWriteRecipe();
composite.disconnectWrite(buffer);
assertEquals(mock1Connect, mock1.getWriteRecipe());
assertEquals(mock2Connect, mock2.getWriteRecipe());
}
} | mit |
leeh/wiziq-ruby | test/helper.rb | 426 | require 'rubygems'
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'test/unit'
require 'shoulda'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'wiziq'
class Test::Unit::TestCase
end
| mit |
Squidex/squidex | backend/src/Squidex.Domain.Apps.Entities/Contents/GraphQL/Types/Primitives/JsonNoopGraphType.cs | 1132 | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using GraphQL.Language.AST;
using GraphQL.Types;
namespace Squidex.Domain.Apps.Entities.Contents.GraphQL.Types.Primitives
{
public class JsonNoopGraphType : ScalarGraphType
{
public JsonNoopGraphType()
{
// The name is used for equal comparison. Therefore it is important to treat it as readonly.
Name = "JsonScalar";
Description = "Unstructured Json object";
}
public override object? ParseLiteral(IValue value)
{
return value.Value;
}
public override object? ParseValue(object? value)
{
return value;
}
public override object? Serialize(object? value)
{
return value;
}
}
}
| mit |
sandhje/vscode-phpmd | server/service/logger/RemoteConsoleLogger.ts | 2865 | import { RemoteConsole, IConnection, ClientCapabilities, ServerCapabilities } from "vscode-languageserver";
import ILogger from "./ILogger";
/**
* Remote console implementation of ILogger
*
* @module vscode-phpmd/service/logger
* @author Sandhjé Bouw ([email protected])
*/
class RemoteConsoleLogger implements ILogger {
/**
* Remote console logger constructor
*
* @param {RemoteConsole} remoteConsole
* @param {boolean} verbose
*/
constructor(private remoteConsole: RemoteConsole, private verbose: boolean = false) {}
/**
* Attach the remote to the given connection.
*
* @param connection The connection this remote is operating on.
*/
attach(connection: IConnection): void {
throw new Error("Method not implemented.");
};
/**
* The connection this remote is attached to.
*/
connection: IConnection;
/**
* Called to initialize the remote with the given
* client capabilities
*
* @param capabilities The client capabilities
*/
initialize(capabilities: ClientCapabilities): void {
throw new Error("Method not implemented.");
}
/**
* Called to fill in the server capabilities this feature implements.
*
* @param capabilities The server capabilities to fill.
*/
fillServerCapabilities(capabilities: ServerCapabilities): void {
throw new Error("Method not implemented.");
}
/**
* @see ILogger::setVerbose
*/
public setVerbose(verbose: boolean): this {
this.verbose = verbose;
return this;
}
/**
* @see ILogger::getVerbose
*/
public getVerbose(): boolean {
return this.verbose;
}
/**
* @see ILogger::error
*/
public error(message: string, isVerbose?: boolean): this {
if (!isVerbose || this.getVerbose() === true) {
this.remoteConsole.error(message);
}
return this;
}
/**
* @see ILogger::warn
*/
public warn(message: string, isVerbose?: boolean): this {
if (!isVerbose || this.getVerbose() === true) {
this.remoteConsole.warn(message);
}
return this;
}
/**
* @see ILogger::info
*/
public info(message: string, isVerbose?: boolean): this {
if (!isVerbose || this.getVerbose() === true) {
this.remoteConsole.info(message);
}
return this;
}
/**
* @see ILogger::log
*/
public log(message: string, isVerbose?: boolean): this {
if (!isVerbose || this.getVerbose() === true) {
this.remoteConsole.log(message);
}
return this;
}
}
export default RemoteConsoleLogger;
| mit |
YFSS/jfm | src/test/java/com/ikaihuo/model/testing/JFMQueryDemo.java | 811 | package com.ikaihuo.model.testing;
import java.math.BigInteger;
import org.junit.Test;
import com.ikaihuo.gp.storage.dc.jfinal.plugin.activerecord.Consts;
import com.ikaihuo.gp.storage.dc.jfinal.plugin.activerecord.Model.Match;
import com.ikaihuo.monkey.model.User;
import com.jfinal.kit.JsonKit;
public class JFMQueryDemo {
@Test
public void test() {
User user = new User();
BigInteger start = new BigInteger("1");
BigInteger end = new BigInteger("111");
user.setId(Match.BW(start, end));
user.setName(Match.AND("zcq"));
user.setName(Match.EQ("zcq"));
System.out.println(user);
System.out.println("DB=\n" + JsonKit.toJson(user.dcExport().get(Consts.ATTR_KEY)) + "\n");
System.out.println(user.efficientAttrs());
}
}
| mit |
Symfony-Plugins/sfToolsPlugin | modules/sfTools/templates/_file_tools.php | 416 | <h3>::sanitizeFilename</h3>
<h4>echo sfFileTools::sanitizeFilename('--logö _ __ ___ ora@@ñ--~gé--.gif');</h4>
<pre><?php echo sfFileTools::sanitizeFilename('--logö _ __ ___ ora@@ñ--~gé--.gif'); ?></pre>
<h4>echo sfFileTools::sanitizeFilename('--LOgÖ _ __ ___ ORA@@Ñ--~GË--.gif');</h4>
<pre><?php echo sfFileTools::sanitizeFilename('--LOgÖ _ __ ___ ORA@@Ñ--~GË--.gif'); ?></pre> | mit |
PerplexInternetmarketing/Perplex-Umbraco-Forms | Perplex.Umbraco.Forms/App_Plugins/PerplexUmbracoForms/backoffice/common/settingtypes/perplexcheckboxlist.controller.js | 2306 | angular.module("umbraco")
.controller("SettingTypes.PerplexcheckboxlistController",
function ($scope, $routeParams, $q, pickerResource, perplexFormResource, perplexConstants) {
var self = this;
$scope.selectedValues = [];
// Load saved values
if (typeof $scope.setting.value === 'string') {
$scope.selectedValues = $scope.setting.value.split(',');
}
// Possible checkbox values
self.values = [];
// The values are configurable and depend upon the FieldType
var field = $scope.model && $scope.model.field;
if (field) {
var fieldTypeId = field.fieldTypeId.toLowerCase();
// Values for the checkboxlist should be provided in a function returning a promise
// such as an $http.get call.
var promiseFn = null;
switch(fieldTypeId) {
case perplexConstants.fieldTypeIds.PerplexFileUpload:
promiseFn = perplexFormResource.getFileUploadAllowedExtensions;
break;
case perplexConstants.fieldTypeIds.PerplexImageUpload:
promiseFn = perplexFormResource.getImageUploadAllowedExtensions;
break;
default: break;
}
if (typeof promiseFn === 'function') {
promiseFn().then(function (response) {
self.values = response.data;
// Make sure the $selectedValues does not contain any
// values that are not currently configured anymore
$scope.selectedValues = _.filter($scope.selectedValues, function (selectedValue) {
return _.contains(self.values, selectedValue);
});
// And update the setting value itself
setValue();
});
}
}
$scope.updateCheckboxValue = function (value) {
if (removeFromArray($scope.selectedValues, value) === false) {
$scope.selectedValues.push(value);
}
setValue();
};
function removeFromArray(array, object) {
var index = array.indexOf(object);
if (index > -1) {
array.splice(index, 1);
return true;
}
return false;
}
// Sets the value as a comma separated list of values
function setValue() {
$scope.setting.value = $scope.selectedValues.join(',');
}
}); | mit |
vijayasankar/ML2.0 | src/routes/UserManagement/container.js | 849 | import { connect } from 'react-redux'
import UserManagement from './components/index.js'
import {
formReset,
formSubmit,
formSubmitError,
formSubmitSuccess,
loadUserManagementRegisteredUsersList
} from 'modules/actions'
export const mapDispatchToProps = {
formReset,
formSubmit,
formSubmitError,
formSubmitSuccess,
loadUserManagementRegisteredUsersList
}
export const mapStateToProps = (state) => {
return ({
currentProviderLinks: state.myProviders.currentProviderDetails.links || '',
currentProviderName: state.myProviders.currentProviderDetails.name || '',
listOfInvitedUsers: state.userManagement.listOfInvitedUsers || '',
listOfUsers: state.userManagement.listOfUsers || '',
token: state.oidc.user.access_token || ''
})
}
export default connect(mapStateToProps, mapDispatchToProps)(UserManagement)
| mit |
qvazzler/Flexget | tests/test_series_api.py | 11965 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
from mock import patch
from flexget.manager import Session
from flexget.plugins.filter import series
from flexget.utils import json
class TestSeriesAPI(object):
config = """
tasks: {}
"""
@patch.object(series, 'get_series_summary')
def test_series_list_get(self, mock_series_list, api_client):
def search(*args, **kwargs):
if 'count' in kwargs:
return 0
else:
with Session() as session:
return session.query(series.Series)
mock_series_list.side_effect = search
# No params
rsp = api_client.get('/series/')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
# Default params
rsp = api_client.get('/series/?max=100&sort_by=show_name&in_config=configured&order=desc&page=1')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
# Changed params
rsp = api_client.get('/series/?status=new&max=10&days=4&sort_by=last_download_date&in_config=all'
'&premieres=true&order=asc&page=2')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
# Negative test, invalid parameter
rsp = api_client.get('/series/?status=bla&max=10&days=4&sort_by=last_download_date&in_config=all'
'&premieres=true&order=asc&page=2')
assert rsp.status_code == 400, 'Response code is %s' % rsp.status_code
assert mock_series_list.call_count == 6, 'Should have 3 calls, is actually %s' % mock_series_list.call_count
@patch.object(series, 'new_eps_after')
@patch.object(series, 'get_latest_release')
@patch.object(series, 'shows_by_name')
def test_series_search(self, mocked_series_search, mock_latest_release, mock_new_eps_after, api_client):
show = series.Series()
episode = series.Episode()
release = series.Release()
release.downloaded = True
episode.releases.append(release)
mock_latest_release.return_value = episode
mock_new_eps_after.return_value = 0
mocked_series_search.return_value = [show]
rsp = api_client.get('/series/search/the%20big%20bang%20theory')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_latest_release.called
assert mock_new_eps_after.called
assert mocked_series_search.called
@patch.object(series, 'new_eps_after')
@patch.object(series, 'get_latest_release')
@patch.object(series, 'show_by_id')
def test_series_get(self, mock_show_by_id, mock_latest_release, mock_new_eps_after, api_client):
show = series.Series()
episode = series.Episode()
release = series.Release()
release.downloaded = True
episode.releases.append(release)
mock_show_by_id.return_value = show
mock_latest_release.return_value = episode
mock_new_eps_after.return_value = 0
rsp = api_client.get('/series/1')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_latest_release.called
assert mock_new_eps_after.called
assert mock_show_by_id.called
@patch.object(series, 'remove_series')
@patch.object(series, 'show_by_id')
def test_series_delete(self, mock_show_by_id, mock_forget_series, api_client):
show = series.Series()
show.name = 'Some name'
mock_show_by_id.return_value = show
rsp = api_client.delete('/series/1')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.called
assert mock_forget_series.called
@patch.object(series, 'new_eps_after')
@patch.object(series, 'get_latest_release')
@patch.object(series, 'set_series_begin')
@patch.object(series, 'show_by_id')
def test_series_begin(self, mock_show_by_id, mock_series_begin, mock_latest_release, mock_new_eps_after,
api_client):
show = series.Series()
episode = series.Episode()
release = series.Release()
release.downloaded = True
episode.releases.append(release)
ep_id = {"episode_identifier": "s01e01"}
mock_show_by_id.return_value = show
mock_latest_release.return_value = episode
mock_new_eps_after.return_value = 0
rsp = api_client.json_put('/series/1', data=json.dumps(ep_id))
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.called
def test_new_series_begin(self, execute_task, api_client):
show = 'Test Show'
new_show = {
"series_name": show,
"episode_identifier": "s01e01",
"alternate_names": ['show1', 'show2']
}
rsp = api_client.json_post(('/series/'), data=json.dumps(new_show))
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
@patch.object(series, 'show_by_id')
def test_series_get_episodes(self, mock_show_by_id, api_client):
show = series.Series()
episode = series.Episode()
release = series.Release()
release.downloaded = True
episode.releases.append(release)
show.episodes.append(episode)
mock_show_by_id.return_value = show
rsp = api_client.get('/series/1/episodes')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.called
def test_series_delete_episodes(self, api_client):
show = 'Test Show'
new_show = {
"series_name": show,
"episode_identifier": "s01e01",
"alternate_names": ['show1', 'show2']
}
rsp = api_client.json_post(('/series/'), data=json.dumps(new_show))
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
rsp = api_client.delete('/series/1/episodes')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
@patch.object(series, 'episode_in_show')
@patch.object(series, 'episode_by_id')
@patch.object(series, 'show_by_id')
def test_series_get_episode(self, mock_show_by_id, mock_episode_by_id, mock_episode_in_show, api_client):
show = series.Series()
episode = series.Episode()
mock_show_by_id.return_value = show
mock_episode_by_id.return_value = episode
rsp = api_client.get('/series/1/episodes/1')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.called
assert mock_episode_by_id.called
assert mock_episode_in_show.called
@patch.object(series, 'remove_series_episode')
@patch.object(series, 'episode_in_show')
@patch.object(series, 'episode_by_id')
@patch.object(series, 'show_by_id')
def test_series_delete_episode(self, mock_show_by_id, mock_episode_by_id, mock_episode_in_show,
mock_remove_series_episode, api_client):
show = series.Series()
episode = series.Episode()
mock_show_by_id.return_value = show
mock_episode_by_id.return_value = episode
rsp = api_client.delete('/series/1/episodes/1')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.called
assert mock_episode_by_id.called
assert mock_episode_in_show.called
assert mock_remove_series_episode.called
@patch.object(series, 'episode_in_show')
@patch.object(series, 'episode_by_id')
@patch.object(series, 'show_by_id')
def test_series_get_episode_releases(self, mock_show_by_id, mock_episode_by_id, mock_episode_in_show, api_client):
show = series.Series()
episode = series.Episode()
mock_show_by_id.return_value = show
mock_episode_by_id.return_value = episode
rsp = api_client.get('/series/1/episodes/1/releases')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
rsp = api_client.get('/series/1/episodes/1/releases?downloaded=true')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
rsp = api_client.get('/series/1/episodes/1/releases?downloaded=false')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.call_count == 3
assert mock_episode_by_id.call_count == 3
assert mock_episode_in_show.call_count == 3
@patch.object(series, 'episode_in_show')
@patch.object(series, 'episode_by_id')
@patch.object(series, 'show_by_id')
def test_series_delete_episode_releases(self, mock_show_by_id, mock_episode_by_id, mock_episode_in_show,
api_client):
show = series.Series()
episode = series.Episode()
mock_show_by_id.return_value = show
mock_episode_by_id.return_value = episode
rsp = api_client.delete('/series/1/episodes/1/releases')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
rsp = api_client.delete('/series/1/episodes/1/releases?downloaded=true')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
rsp = api_client.delete('/series/1/episodes/1/releases?downloaded=false')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.call_count == 3
assert mock_episode_by_id.call_count == 3
assert mock_episode_in_show.call_count == 3
@patch.object(series, 'release_in_episode')
@patch.object(series, 'release_by_id')
@patch.object(series, 'episode_in_show')
@patch.object(series, 'episode_by_id')
@patch.object(series, 'show_by_id')
def test_series_get_release(self, mock_show_by_id, mock_episode_by_id, mock_episode_in_show, mock_release_by_id,
mock_release_in_episode, api_client):
show = series.Series()
episode = series.Episode()
release = series.Release()
mock_show_by_id.return_value = show
mock_episode_by_id.return_value = episode
mock_release_by_id.return_value = release
rsp = api_client.get('/series/2/episodes/653/releases/1551/')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.called
assert mock_episode_by_id.called
assert mock_episode_in_show.called
assert mock_release_by_id.called
assert mock_release_in_episode.called
@patch.object(series, 'delete_release_by_id')
@patch.object(series, 'release_in_episode')
@patch.object(series, 'release_by_id')
@patch.object(series, 'episode_in_show')
@patch.object(series, 'episode_by_id')
@patch.object(series, 'show_by_id')
def test_series_delete_release(self, mock_show_by_id, mock_episode_by_id, mock_episode_in_show, mock_release_by_id,
mock_release_in_episode, mock_delete_release_by_id, api_client):
show = series.Series()
episode = series.Episode()
release = series.Release()
mock_show_by_id.return_value = show
mock_episode_by_id.return_value = episode
mock_release_by_id.return_value = release
rsp = api_client.delete('/series/2/episodes/653/releases/1551/')
assert rsp.status_code == 200, 'Response code is %s' % rsp.status_code
assert mock_show_by_id.called
assert mock_episode_by_id.called
assert mock_episode_in_show.called
assert mock_release_by_id.called
assert mock_release_in_episode.called
assert mock_delete_release_by_id.called
| mit |
elmiko/data-goblin | datagoblin/manage.py | 253 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "datagoblin.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| mit |
Tamitras/TradingCenter | TradingCenter/TradingCenter/Forms/MainForm.cs | 7096 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TradingCenter.Forms
{
public partial class MainForm : Form
{
#region Attribute
/// <summary>
/// MainProvider für Datenbankzugriffe
/// </summary>
TradingCenter.Provider.MainProvider MainProvider { get; set; }
/// <summary>
/// UserControl für den Button "Suche"
/// </summary>
UserControls.NavBar.Buttons.UCButtonSuche UCButtonSuche { get; set; }
/// <summary>
/// UserControl für den Button "TradingList"
/// </summary>
UserControls.NavBar.Buttons.UCButtonTradingList UCButtonTradingList { get; set; }
/// <summary>
/// UserControl für die Anzeige von ButtonSucheSpieler
/// </summary>
UserControls.MainForm.Sites.UCFormSucheSpieler UCFormSucheSpieler { get; set; }
#endregion
#region Events
#endregion
#region Konstruktor
public MainForm()
{
InitializeComponent();
InitPanelMainForm();
InitPanelNavBar();
//Events werden regestriert
UCButtonSuche.ButtonSpielerIsClicked += UCButtonSuche_ButtonSpielerIsClicked;
}
#endregion
#region Initialisierung
/// <summary>
/// Initialisiert das Panel für die MainForm
/// </summary>
private void InitPanelMainForm()
{
UCFormSucheSpieler = new UserControls.MainForm.Sites.UCFormSucheSpieler();
UCFormSucheSpieler.Name = "UCFormSucheSpieler";
this.panelMainForm.Controls.Add(UCFormSucheSpieler);
}
/// <summary>
/// Initialisiert das Panel für die NavBar
/// </summary>
private void InitPanelNavBar()
{
UCButtonSuche = new UserControls.NavBar.Buttons.UCButtonSuche();
UCButtonTradingList = new UserControls.NavBar.Buttons.UCButtonTradingList();
this.panelNavBar.Controls.Add(UCButtonSuche);
this.panelNavBar.Controls.Add(UCButtonTradingList);
// Es wird unsichtbar gemacht
UCButtonSuche.Visible = false;
UCButtonTradingList.Visible = false;
}
/// <summary>
/// Initialisiert das Panel für die StatusBar
/// </summary>
private void InitPanelStatusBar()
{
}
#endregion
#region EventHandler
/// <summary>
/// Eventhandler für ButtonSpieler im UserControl ButtonSuche
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void UCButtonSuche_ButtonSpielerIsClicked(object sender, EventArgs e)
{
this.panelMainForm.Controls["UCFormSucheSpieler"].Show();
}
/// <summary>
/// Methode zum Initialisieren des Programmes
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MainForm_Load(object sender, EventArgs e)
{
//Check for Updates
MainProvider = new Provider.MainProvider();
if (MainProvider.CheckForUpdates())
{
//Update wird installiert
}
else
{
// Kein Update
}
}
/// <summary>
/// Klick auf ButtonSuche
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSuche_Click(object sender, EventArgs e)
{
if (!UCButtonSuche.IsOpen)
{
ResetUserContols();
UCButtonSuche.Location = new Point(btnSuche.Location.X, btnSuche.Location.Y + btnSuche.Height);
btnTradingListe.Location = new Point(btnSuche.Location.X, btnTradingListe.Location.Y + UCButtonSuche.Height);
btnLiveTrading.Location = new Point(btnSuche.Location.X, btnTradingListe.Location.Y + btnTradingListe.Height);
btnForum.Location = new Point(btnSuche.Location.X, btnLiveTrading.Location.Y + btnLiveTrading.Height);
btnProfil.Location = new Point(btnSuche.Location.X, btnForum.Location.Y + btnForum.Height);
btnSupoort.Location = new Point(btnSuche.Location.X, btnProfil.Location.Y + btnProfil.Height);
UCButtonSuche.IsOpen = true;
UCButtonSuche.Visible = true;
}
else
{
ResetUserContols();
}
}
/// <summary>
/// Klick auf ButtonTradingList
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnTradingListe_Click(object sender, EventArgs e)
{
if (!UCButtonTradingList.IsOpen)
{
ResetUserContols();
UCButtonTradingList.Location = new Point(btnTradingListe.Location.X, btnTradingListe.Location.Y + btnTradingListe.Height);
btnLiveTrading.Location = new Point(btnTradingListe.Location.X, btnLiveTrading.Location.Y + UCButtonTradingList.Height);
btnForum.Location = new Point(btnTradingListe.Location.X, btnLiveTrading.Location.Y + btnLiveTrading.Height);
btnProfil.Location = new Point(btnTradingListe.Location.X, btnForum.Location.Y + btnForum.Height);
btnSupoort.Location = new Point(btnTradingListe.Location.X, btnProfil.Location.Y + btnProfil.Height);
UCButtonTradingList.IsOpen = true;
UCButtonTradingList.Visible = true;
}
else
{
ResetUserContols();
}
}
#endregion
#region private Methoden
private void ResetUserContols()
{
// IsOpen wird auf false gesetzt
UCButtonSuche.IsOpen = false;
UCButtonTradingList.IsOpen = false;
// Es wird unsichtbar gemacht
UCButtonSuche.Visible = false;
UCButtonTradingList.Visible = false;
btnTradingListe.Location = new Point(btnSuche.Location.X, btnSuche.Location.Y + btnSuche.Height);
btnLiveTrading.Location = new Point(btnTradingListe.Location.X, btnTradingListe.Location.Y + btnTradingListe.Height);
btnForum.Location = new Point(btnLiveTrading.Location.X, btnLiveTrading.Location.Y + btnLiveTrading.Height);
btnProfil.Location = new Point(btnForum.Location.X, btnForum.Location.Y + btnForum.Height);
btnSupoort.Location = new Point(btnProfil.Location.X, btnProfil.Location.Y + btnProfil.Height);
}
#endregion
#region public Methoden
#endregion
}
}
| mit |
azharari/teskerja | application/modules/admin/views/excel.php | 1036 | <html>
<head>
</head>
<body>
<?php
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Report.xls");//ganti nama sesuai keperluan
header("Pragma: no-cache");
header("Expires: 0");
?>
<h2> Laporan Data Mobil Hazard Car Rent </h2>
<table border="1" style="padding:3px; margin:3px;">
<tr>
<td>No</td>
<td>Id Mobil</td>
<td>Nama Mobil</td>
<td>No Polisi</td>
<td>Harga Sewa</td>
<td>Status</td>
<td>Diinput Oleh</td>
<td>Jabatan</td>
</tr>
<?php
$no=1;
foreach($hasil as $row)
{
?>
<tr>
<td><?php echo $no++ ?></td>
<td><?php echo $row->Id_Mobil ?></td>
<td><?php echo $row->Nama_Mobil ?></td>
<td><?php echo $row->No_Polisi ?></td>
<td><?php echo $row->Harga ?></td>
<td><?php echo $row->Status ?></td>
<td><?php echo $row->Nama ?></td>
<td><?php echo $row->Jabatan ?></td>
</tr>
<?php
}
?>
</table>
</body>
</html> | mit |
Karasiq/scalajs-highcharts | src/main/scala/com/highstock/config/SeriesCciPointEvents.scala | 12331 | /**
* Automatically generated file. Please do not edit.
* @author Highcharts Config Generator by Karasiq
* @see [[http://api.highcharts.com/highstock]]
*/
package com.highstock.config
import scalajs.js, js.`|`
import com.highcharts.CleanJsObject
import com.highcharts.HighchartsUtils._
/**
* @note JavaScript name: <code>series<cci>-point-events</code>
*/
@js.annotation.ScalaJSDefined
class SeriesCciPointEvents extends com.highcharts.HighchartsGenericObject {
/**
* <p>Callback that fires when starting to drag a point. The mouse event object is
* passed in as an argument. If a drag handle is used, <code>e.updateProp</code> is set to
* the data property being dragged. The <code>this</code> context is the point. See
* <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>
* <p>Requires the <code>draggable-points</code> module.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/dragdrop/drag-xrange">Drag events</a>
* @since 6.2.0
*/
val dragStart: js.UndefOr[js.Function] = js.undefined
/**
* <p>Callback that fires while dragging a point. The mouse event is passed in as
* parameter. The original data can be accessed from <code>e.origin</code>, and the new
* point values can be accessed from <code>e.newPoints</code>. If there is only a single
* point being updated, it can be accessed from <code>e.newPoint</code> for simplicity, and
* its ID can be accessed from <code>e.newPointId</code>. The <code>this</code> context is the point
* being dragged. To stop the default drag action, return false.
* See <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>
* <p>Requires the <code>draggable-points</code> module.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/dragdrop/drag-xrange">Drag events</a>
* @since 6.2.0
*/
val drag: js.UndefOr[js.Function] = js.undefined
/**
* <p>Callback that fires when the point is dropped. The parameters passed are the
* same as for <a href="#plotOptions.series.point.events.drag">drag</a>. To stop the
* default drop action, return false. See
* <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>
* <p>Requires the <code>draggable-points</code> module.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/dragdrop/drag-xrange">Drag events</a>
* @since 6.2.0
*/
val drop: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when a point is clicked. One parameter, <code>event</code>, is passed
* to the function, containing common event information.</p>
* <p>If the <code>series.allowPointSelect</code> option is true, the default
* action for the point's click event is to toggle the point's
* select state. Returning <code>false</code> cancels this action.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-click/">Click marker to alert values</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-click-column/">Click column</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-click-url/">Go to URL</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-point-events-click/">Click marker to display values</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-point-events-click-url/">Go to URL</a>
* @since 6.0.0
*/
val click: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the mouse leaves the area close to the point. One
* parameter, <code>event</code>, is passed to the function, containing common
* event information.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-mouseover/">Show values in the chart's corner on mouse over</a>
* @since 6.0.0
*/
val mouseOut: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the mouse enters the area close to the point. One
* parameter, <code>event</code>, is passed to the function, containing common
* event information.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-mouseover/">Show values in the chart's corner on mouse over</a>
* @since 6.0.0
*/
val mouseOver: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the point is removed using the <code>.remove()</code> method. One
* parameter, <code>event</code>, is passed to the function. Returning <code>false</code>
* cancels the operation.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-remove/">Remove point and confirm</a>
* @since 1.2.0
*/
val remove: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the point is selected either programmatically or
* following a click on the point. One parameter, <code>event</code>, is passed
* to the function. Returning <code>false</code> cancels the operation.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-select/">Report the last selected point</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-allowpointselect/">Report select and unselect</a>
* @since 1.2.0
*/
val select: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the point is unselected either programmatically or
* following a click on the point. One parameter, <code>event</code>, is passed
* to the function.
* Returning <code>false</code> cancels the operation.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-unselect/">Report the last unselected point</a>
<a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/maps/plotoptions/series-allowpointselect/">Report select and unselect</a>
* @since 1.2.0
*/
val unselect: js.UndefOr[js.Function] = js.undefined
/**
* <p>Fires when the point is updated programmatically through the
* <code>.update()</code> method. One parameter, <code>event</code>, is passed to the
* function. The new point options can be accessed through
* <code>event.options</code>. Returning <code>false</code> cancels the operation.</p>
* @example <a href="https://jsfiddle.net/gh/library/pure/highcharts/highcharts/tree/master/samples/highcharts/plotoptions/series-point-events-update/">Confirm point updating</a>
* @since 1.2.0
*/
val update: js.UndefOr[js.Function] = js.undefined
}
object SeriesCciPointEvents {
/**
* @param dragStart <p>Callback that fires when starting to drag a point. The mouse event object is. passed in as an argument. If a drag handle is used, <code>e.updateProp</code> is set to. the data property being dragged. The <code>this</code> context is the point. See. <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>. <p>Requires the <code>draggable-points</code> module.</p>
* @param drag <p>Callback that fires while dragging a point. The mouse event is passed in as. parameter. The original data can be accessed from <code>e.origin</code>, and the new. point values can be accessed from <code>e.newPoints</code>. If there is only a single. point being updated, it can be accessed from <code>e.newPoint</code> for simplicity, and. its ID can be accessed from <code>e.newPointId</code>. The <code>this</code> context is the point. being dragged. To stop the default drag action, return false.. See <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>. <p>Requires the <code>draggable-points</code> module.</p>
* @param drop <p>Callback that fires when the point is dropped. The parameters passed are the. same as for <a href="#plotOptions.series.point.events.drag">drag</a>. To stop the. default drop action, return false. See. <a href="plotOptions.series.dragDrop">drag and drop options</a>.</p>. <p>Requires the <code>draggable-points</code> module.</p>
* @param click <p>Fires when a point is clicked. One parameter, <code>event</code>, is passed. to the function, containing common event information.</p>. <p>If the <code>series.allowPointSelect</code> option is true, the default. action for the point's click event is to toggle the point's. select state. Returning <code>false</code> cancels this action.</p>
* @param mouseOut <p>Fires when the mouse leaves the area close to the point. One. parameter, <code>event</code>, is passed to the function, containing common. event information.</p>
* @param mouseOver <p>Fires when the mouse enters the area close to the point. One. parameter, <code>event</code>, is passed to the function, containing common. event information.</p>
* @param remove <p>Fires when the point is removed using the <code>.remove()</code> method. One. parameter, <code>event</code>, is passed to the function. Returning <code>false</code>. cancels the operation.</p>
* @param select <p>Fires when the point is selected either programmatically or. following a click on the point. One parameter, <code>event</code>, is passed. to the function. Returning <code>false</code> cancels the operation.</p>
* @param unselect <p>Fires when the point is unselected either programmatically or. following a click on the point. One parameter, <code>event</code>, is passed. to the function.. Returning <code>false</code> cancels the operation.</p>
* @param update <p>Fires when the point is updated programmatically through the. <code>.update()</code> method. One parameter, <code>event</code>, is passed to the. function. The new point options can be accessed through. <code>event.options</code>. Returning <code>false</code> cancels the operation.</p>
*/
def apply(dragStart: js.UndefOr[js.Function] = js.undefined, drag: js.UndefOr[js.Function] = js.undefined, drop: js.UndefOr[js.Function] = js.undefined, click: js.UndefOr[js.Function] = js.undefined, mouseOut: js.UndefOr[js.Function] = js.undefined, mouseOver: js.UndefOr[js.Function] = js.undefined, remove: js.UndefOr[js.Function] = js.undefined, select: js.UndefOr[js.Function] = js.undefined, unselect: js.UndefOr[js.Function] = js.undefined, update: js.UndefOr[js.Function] = js.undefined): SeriesCciPointEvents = {
val dragStartOuter: js.UndefOr[js.Function] = dragStart
val dragOuter: js.UndefOr[js.Function] = drag
val dropOuter: js.UndefOr[js.Function] = drop
val clickOuter: js.UndefOr[js.Function] = click
val mouseOutOuter: js.UndefOr[js.Function] = mouseOut
val mouseOverOuter: js.UndefOr[js.Function] = mouseOver
val removeOuter: js.UndefOr[js.Function] = remove
val selectOuter: js.UndefOr[js.Function] = select
val unselectOuter: js.UndefOr[js.Function] = unselect
val updateOuter: js.UndefOr[js.Function] = update
com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesCciPointEvents {
override val dragStart: js.UndefOr[js.Function] = dragStartOuter
override val drag: js.UndefOr[js.Function] = dragOuter
override val drop: js.UndefOr[js.Function] = dropOuter
override val click: js.UndefOr[js.Function] = clickOuter
override val mouseOut: js.UndefOr[js.Function] = mouseOutOuter
override val mouseOver: js.UndefOr[js.Function] = mouseOverOuter
override val remove: js.UndefOr[js.Function] = removeOuter
override val select: js.UndefOr[js.Function] = selectOuter
override val unselect: js.UndefOr[js.Function] = unselectOuter
override val update: js.UndefOr[js.Function] = updateOuter
})
}
}
| mit |
neubt/ershou | app/models/ershou/topic.rb | 1134 | require 'ipaddr'
module Ershou
class Topic < ActiveRecord::Base
attr_accessible :title, :content
attr_accessible :price, :phone, :qq
belongs_to :user
belongs_to :node, :counter_cache => true
has_many :comments, :dependent => :destroy
has_many :attachments, :dependent => :destroy
accepts_nested_attributes_for :attachments
attr_accessible :attachments_attributes
validates :title, :presence => true
validates :price, :presence => true
#validates :phone, :presence => true
#validates :qq, :presence => true
acts_as_paranoid
state_machine :initial => :open do
event 'open' do
transition all => :open
end
event 'close' do
transition all => :closed
end
end
acts_as_readable :on => :updated_at
#before_create do |topic|
# remote_ip = IPAddr.new topic.remote_ip || "0.0.0.0"
# Location.all.each do |location|
# prefix = IPAddr.new location.prefix || "0.0.0.0"
# if prefix.include?(remote_ip)
# topic.node = location.node
# break
# end
# end
#end
end
end
| mit |
GitRat2340/gitrat | app/src/main/java/a2340/m4_login/User.java | 507 | package a2340.m4_login;
import java.io.Serializable;
public class User implements Serializable{
private String name, user, password;
private boolean admin;
public User(String nam, boolean adm, String id, String pass) {
name = nam;
admin = adm;
user = id;
password = pass;
}
public String getName() {
return name;
}
public String getUser() {
return user;
}
public String getPass() {
return password;
}
}
| mit |
bruery/platform-core | src/bundles/UserSecurityBundle/Component/Listener/RouteRefererListener.php | 1355 | <?php
/**
* This file is part of the Bruery Platform.
*
* (c) Viktore Zara <[email protected]>
* (c) Mell Zamora <[email protected]>
*
* Copyright (c) 2016. For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Bruery\UserSecurityBundle\Component\Listener;
use Bruery\UserSecurityBundle\Component\Listener\RouteRefererListener as BaseRouteRefererListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class RouteRefererListener extends BaseRouteRefererListener
{
public function onKernelRequest(GetResponseEvent $event)
{
// Abort if we are dealing with some symfony2 internal requests.
if ($event->getRequestType() !== \Symfony\Component\HttpKernel\HttpKernel::MASTER_REQUEST) {
return;
}
// Get the route from the request object.
$request = $event->getRequest();
$route = $request->get('_route');
if (in_array($route, $this->routeIgnoreList)) {
return;
}
// Check for any internal routes.
if ($route[0] == '_') {
return;
}
// Get the session and assign it the url we are at presently.
$session = $request->getSession();
$session->set('referer', $request->getRequestUri());
}
}
| mit |
sachinB94/rentolas | routes/ownerhome.js | 2407 | exports.ownerhome = function (req, res, db, db_static, redis) {
if (req.session.listId) {
req.session.listId = null;
}
if (req.session.ownerId) {
var async = require('async');
async.parallel({
locality: function (callback) {
db_static.collection('locality').find().toArray(function (err, locality) {
callback(err,locality);
});
},
owner: function (callback) {
redis.hgetall('owner', function (err, owner) {
callback(err,owner);
});
},
lists: function (callback) {
db.collection('postlisting').find({'ownerId': req.session.ownerId}).toArray(function (err, lists) {
callback(err,lists);
});
},
messages: function (callback) {
db.collection('ownermessage').find({'ownerId': req.session.ownerId}).toArray(function (err, messages) {
callback(err,messages);
});
}
}, function (err, result) {
if (!err) {
var messageCount = 0;
result.messages.forEach(function (message, index) {
if (new Date(message.ISODate) > new Date(result.owner.lastAccess)) messageCount++;
});
res.render('ownerhome', {
'locality': result.locality,
'user': result.owner,
'lists': result.lists,
'messageCount': messageCount,
'isOwner': true,
'isStudent': false
});
} else {
res.redirect('/error/1/' + err);
}
});
} else {
res.redirect('/');
}
}
// exports.ownerhome = function (req, res, db, db_static, redis) {
// if (req.session.listId) {
// req.session.listId = null;
// }
// if (req.session.ownerId) {
// db_static.collection('locality').find().toArray(function (err, locality) {
// if (locality != null) {
// redis.hgetall('owner', function (err, owner) {
// if (!err) {
// db.collection('postlisting').find({'ownerId': req.session.ownerId}).toArray(function (err, lists) {
// if (!err) {
// res.render('ownerhome', {'locality': locality, 'owner': owner, 'lists': lists});
// } else {
// console.log('ERROR: ' + err);
// res.end();
// }
// });
// } else {
// console.log('ERROR: ' + err);
// res.end();
// }
// });
// } else {
// console.log('ERROR: ' + err);
// //res.redirect('errorHandle/1');
// res.end();
// }
// });
// } else {
// res.redirect('/');
// }
// } | mit |
tmolina27/prototipo | application/views/View_login.php | 704 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Loogin</title>
</head>
<body>
<div style="align-content: center">
<h1>Debes iniciar sesion</h1>
<?php echo validation_errors(); ?>
<?php echo form_open('validar_login'); ?>
<label for="username">Username:</label>
<input type="text" size="20" id="username" name="username"/>
<br/>
<label for="password">Password:</label>
<input type="password" size="20" id="passowrd" name="password"/>
<br/>
<input type="submit" value="Login"/>
</form>
</div>
</body>
</html> | mit |
bogdanostojic/slim | app/Middleware/CsrfViewMiddleware.php | 731 | <?php
namespace App\Middleware;
class CsrfViewMiddleware extends Middleware
{
public function __invoke($request, $response, $next)
{
$this->container->view->getEnvironment()->addGlobal('csrf', [ //Ovaj middleware nam pomaze da sprecimo CrossSiteRequestForgery (CSRF), i za svaku POST formu, treba nam csrf token da bi nam to uspelo i csrf token value key
'field' => '
<input type="hidden" name="'.$this->container->csrf->getTokenNameKey().'" value="'.$this->container->csrf->getTokenName().'">
<input type="hidden" name="'.$this->container->csrf->getTokenValueKey().'" value="'. $this->container->csrf->getTokenvalue().'">
',
]);
$response = $next($request, $response);
return $response;
}
} | mit |
loskutov/deadbeef-lyricbar | src/ui.cpp | 4321 | #include "ui.h"
#include <memory>
#include <vector>
#include <glibmm/main.h>
#include <gtkmm/main.h>
#include <gtkmm/scrolledwindow.h>
#include <gtkmm/textbuffer.h>
#include <gtkmm/textview.h>
#include <gtkmm/widget.h>
#include "debug.h"
#include "gettext.h"
#include "utils.h"
using namespace std;
using namespace Gtk;
using namespace Glib;
// TODO: eliminate all the global objects, as their initialization is not well defined
static TextView *lyricView;
static ScrolledWindow *lyricbar;
static RefPtr<TextBuffer> refBuffer;
static RefPtr<TextTag> tagItalic, tagBold, tagLarge, tagCenter;
static vector<RefPtr<TextTag>> tagsTitle, tagsArtist;
void set_lyrics(DB_playItem_t *track, ustring lyrics) {
signal_idle().connect_once([track, lyrics = move(lyrics)] {
ustring artist, title;
{
pl_lock_guard guard;
if (!is_playing(track))
return;
artist = deadbeef->pl_find_meta(track, "artist") ?: _("Unknown Artist");
title = deadbeef->pl_find_meta(track, "title") ?: _("Unknown Title");
}
refBuffer->erase(refBuffer->begin(), refBuffer->end());
refBuffer->insert_with_tags(refBuffer->begin(), title, tagsTitle);
refBuffer->insert_with_tags(refBuffer->end(), ustring{"\n"} + artist + "\n\n", tagsArtist);
bool italic = false;
bool bold = false;
size_t prev_mark = 0;
vector<RefPtr<TextTag>> tags;
while (prev_mark != ustring::npos) {
size_t italic_mark = lyrics.find("''", prev_mark);
if (italic_mark == ustring::npos) {
refBuffer->insert(refBuffer->end(), lyrics.substr(prev_mark));
break;
}
size_t bold_mark = ustring::npos;
if (italic_mark < lyrics.size() - 2 && lyrics[italic_mark + 2] == '\'')
bold_mark = italic_mark;
tags.clear();
if (italic) tags.push_back(tagItalic);
if (bold) tags.push_back(tagBold);
refBuffer->insert_with_tags(refBuffer->end(),
lyrics.substr(prev_mark, min(bold_mark, italic_mark) - prev_mark),
tags);
if (bold_mark == ustring::npos) {
prev_mark = italic_mark + 2;
italic = !italic;
} else {
prev_mark = bold_mark + 3;
bold = !bold;
}
}
last = track;
});
}
Justification get_justification() {
int align = deadbeef->conf_get_int("lyricbar.lyrics.alignment", 1);
switch (align) {
case 0:
return JUSTIFY_LEFT;
case 2:
return JUSTIFY_RIGHT;
default:
return JUSTIFY_CENTER;
}
}
extern "C"
GtkWidget *construct_lyricbar() {
Gtk::Main::init_gtkmm_internals();
refBuffer = TextBuffer::create();
tagItalic = refBuffer->create_tag();
tagItalic->property_style() = Pango::STYLE_ITALIC;
tagBold = refBuffer->create_tag();
tagBold->property_weight() = Pango::WEIGHT_BOLD;
tagLarge = refBuffer->create_tag();
tagLarge->property_scale() = Pango::SCALE_LARGE;
tagCenter = refBuffer->create_tag();
tagCenter->property_justification() = JUSTIFY_CENTER;
tagsTitle = {tagLarge, tagBold, tagCenter};
tagsArtist = {tagItalic, tagCenter};
lyricView = new TextView(refBuffer);
lyricView->set_editable(false);
lyricView->set_can_focus(false);
lyricView->set_justification(get_justification());
lyricView->set_wrap_mode(WRAP_WORD_CHAR);
if (get_justification() == JUSTIFY_LEFT) {
lyricView->set_left_margin(20);
}
lyricView->show();
lyricbar = new ScrolledWindow();
lyricbar->add(*lyricView);
lyricbar->set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC);
return GTK_WIDGET(lyricbar->gobj());
}
extern "C"
int message_handler(struct ddb_gtkui_widget_s*, uint32_t id, uintptr_t ctx, uint32_t, uint32_t) {
auto event = reinterpret_cast<ddb_event_track_t *>(ctx);
switch (id) {
case DB_EV_CONFIGCHANGED:
debug_out << "CONFIG CHANGED\n";
signal_idle().connect_once([]{ lyricView->set_justification(get_justification()); });
break;
case DB_EV_SONGSTARTED:
debug_out << "SONG STARTED\n";
case DB_EV_TRACKINFOCHANGED:
if (!event->track || event->track == last || deadbeef->pl_get_item_duration(event->track) <= 0)
return 0;
auto tid = deadbeef->thread_start(update_lyrics, event->track);
deadbeef->thread_detach(tid);
break;
}
return 0;
}
extern "C"
void lyricbar_destroy() {
delete lyricbar;
delete lyricView;
tagsArtist.clear();
tagsTitle.clear();
tagLarge.reset();
tagBold.reset();
tagItalic.reset();
refBuffer.reset();
}
| mit |
alphagov/vcloud-ruby | lib/vcloud/user/catalog_item.rb | 338 | module VCloud
# Contains a reference to a VAppTemplate or Media object and related
# metadata.
class CatalogItem < BaseVCloudEntity
has_type VCloud::Constants::ContentType::CATALOG_ITEM
tag 'CatalogItem'
has_default_attributes
has_links
has_one :entity_reference, 'VCloud::Reference', :tag => 'Entity'
end
end
| mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.