repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
FunTimeCoding/scala-skeleton
src/LanguageExample/Boilerplate.scala
9857
import scala.collection.mutable.ArrayBuffer import scala.io.StdIn.readLine import scala.math.log10 import java.io.PrintWriter import scala.io.Source object Boilerplate { def main(args: Array[String]) { // Loops var i = 0 while (i <= 10) { println(i) i += 1 } for (i <- 1 to 10) { println(i) } val randomLetters = "WORD" for (i <- 0 until randomLetters.length) { println(randomLetters(i)) } val aList = List(1, 2, 3, 4, 5) for (i <- aList) { println("Item: " + i) } // List filter val evenList = for { i <- 1 to 20 if (i % 2) == 0 } yield i for (i <- evenList) { println("Item: " + i) } for (i <- 1 to 5; j <- 6 to 10) { println(i + " " + j) } // There is no break and continue statement. def printPrimes() { val primeList = List(1, 2, 3, 5, 7, 11) for (i <- primeList) { if (i == 11) { // simulated break return } if (i != 1) { // simulated continue println(i) } } } printPrimes() var numberGuess = 0 do { print("Guess a number ") numberGuess = readLine().toInt // readInt, readDouble, readByte, readShort, readLong } while (numberGuess != 15) printf("Guessed the secret number %d.\n", 15) // Strings val name = "Mary" val age = 1 val weight = 1.5 println(s"Hello $name") println(f"I am ${age + 1} and weigh $weight%.2f") // %c Character // %d Integer // %f Float // %s String printf("'%5d'\n", 5) // right justification printf("'%-5d'\n", 5) // left justification printf("'%05d'\n", 5) // zero fill printf("'%.5f'\n", 3.14) // five decimal places printf("'%-5s'\n", "hi") // string justification // Special characters // \b backspace // \\ escaped backslash // \a alert sound val randomSentence = "I saw a dragon fly by" println("index 3: " + randomSentence(3)) println("length: " + randomSentence.length) println(randomSentence.concat(" and explode")) println("Are strings equal " + "I saw a dragon".equals(randomSentence)) println(randomSentence.indexOf("dragon")) val randomSentenceArray = randomSentence.toArray for (v <- randomSentenceArray) { println(v) } // Functions /* def functionName(param1:dataType, param2:dataType) : returnType = { function body return result } */ def getSum(num1: Int = 1, num2: Int = 1): Int = { num1 + num2 // return keywords is optional } println(getSum(5, 4)) println(getSum(num2 = 5, num1 = 4)) // named arguments // functions without return values are called procedures def sayHi(): Unit = { println("Hello friend.") } sayHi() // Variable arguments def getSumVariable(args: Int*): Int = { var sum: Int = 0 for (num <- args) { sum += num } sum } println(getSumVariable(1, 2, 3, 4, 5)) // Recursion def factorial(num: BigInt): BigInt = { if (num <= 1) { 1 } else { num * factorial(num - 1) } } println(factorial(4)) // Arrays val favouriteNumbers = new Array[Int](20) val friends = Array("Bob", "Tom") friends(0) = "Sue" println(friends(0)) val friends2 = ArrayBuffer[String]() // changeable length friends2.insert(0, "Phil") friends2 += "Mark" // next slot friends2 ++= Array("Susy", "Paul") // add multiple at end friends2.insert(1, "Mike", "Marry", "Sally") // insert multiple in the middle friends2.remove(1, 2) var friend: String = " " for (friend <- friends2) { println(friend) } for (j <- favouriteNumbers.indices) { favouriteNumbers(j) = j println(favouriteNumbers(j)) } val favouriteNumbersTimes2 = for (num <- favouriteNumbers) yield 2 * num // Print all elements favouriteNumbersTimes2.foreach(println) val favouriteNumbersDividedBy4 = for (num <- favouriteNumbers if num % 4 == 0) yield num favouriteNumbersDividedBy4.foreach(println) val multiplicationTable = Array.ofDim[Int](10, 10) for (i <- 0 to 9) { for (j <- 0 to 9) { multiplicationTable(i)(j) = i * j } } for (i <- 0 to 9) { for (j <- 0 to 9) { printf("%d : %d = %d\n", i, j, multiplicationTable(i)(j)) } } println("Sum: " + favouriteNumbers.sum) // sum of all elements // More: min, max val sortedNumbers = favouriteNumbers.sortWith(_ > _) // sort descending println(sortedNumbers.deep.mkString(", ")) // Maps val employees = Map("Manager" -> "Bob Smith", "Secretary" -> "Sue Brown") if (employees.contains("Manager")) { printf("Manager: %s\n", employees("Manager")) } val customers = collection.mutable.Map(100 -> "Paul Smith", 101 -> "Sally Smith") printf("Customer 1: %s\n", customers(100)) customers(100) = "Tom Marks" customers(102) = "Megan Swift" for ((k, v) <- customers) { printf("%d : %s\n", k, v) } // Tuple val tupleMarge = (103, "Marge Simpson", 10.25) printf("%s owes us $%.2f\n", tupleMarge._2, tupleMarge._3) tupleMarge.productIterator.foreach { i => println(i) } println(tupleMarge.toString()) // Classes // var = mutable class Animal(var name: String, var sound: String) { // Constructor parameters in () this.setName(name) // constructor // scala has no static methods or variables val id = Animal.newIdNum // getter def getName: String = name def getSound: String = sound // setter def setName(name: String) { // if it contains any decimal number, not. if (!name.matches(".*\\d+.*")) { this.name = name } else { this.name = "No Name" } } def setSound(sound: String) { this.sound = sound } // constructor only with name def this(name: String) { this("No Name", "No Sound") this.setName(name) } // constructor with no argument def this() { this("No Name", "No Sound") } override def toString: String = { "%s with the id %d says %s".format(this.name, this.id, this.sound) } } // companion object object Animal { // simulate static field private var idNumber = 0 // simulate static function private def newIdNum = { idNumber += 1 idNumber } } val rover = new Animal rover.setName("Rover") rover.setSound("Woof") printf("%s says %s\n", rover.getName, rover.getSound) val whiskers = new Animal("Whiskers", "Meow") println(s"${whiskers.getName} with id ${whiskers.id} says ${whiskers.sound}") println(whiskers.toString) // Inheritance class Dog(name: String, sound: String, growl: String) extends Animal(name, sound) { def this(name: String, sound: String) { this("No Name", sound, "No Growl") this.setName(name) } def this(name: String) { this("No Name", "No Sound", "No Growl") this.setName(name) } def this() { this("No Name", "No Sound", "No Growl") } override def toString: String = { "%s with the id %d says %s or %s".format(this.name, this.id, this.sound, this.growl) } } val spike = new Dog("Spike", "Woof", "Grrrrr") spike.setName("Spike") println(spike.toString) // Abstract classes abstract class Mammal(val name: String) { var moveSpeed: Double def move: String } class Wolf(name: String) extends Mammal(name) { var moveSpeed = 35.0 def move = "The wolf %s runs %.2f mph".format(this.name, this.moveSpeed) } val fang = new Wolf("Fang") fang.moveSpeed = 36.0 println(fang.move) // Trait // You can extend multiple traits. trait Flyable { def fly: String } trait BulletProof { def hitByBullet: String def ricochet(startSpeed: Double): String = { "The bullet ricochets at a speed of %.1f ft/sec".format(startSpeed * 0.75) } } class Superhero(val name: String) extends Flyable with BulletProof { def fly = "%s flys through the air".format(this.name) def hitByBullet = "The bullet bounces off of %s".format(this.name) } val superman = new Superhero("Superman") println(superman.fly) println(superman.hitByBullet) println(superman.ricochet(2500)) // Higher order functions val log10Func = log10 _ println(log10Func(1000)) List(1000.0, 10000.0).map(log10Func).foreach(println) List(1, 2, 3, 4, 5).map((x: Int) => x * 50).foreach(println) List(1, 2, 3, 4, 5).filter(_ % 2 == 0).foreach(println) def times3(num: Int) = num * 3 def times4(num: Int) = num * 4 def multiplyIt(func: (Int) => Double, num: Int) = { func(num) } printf("%.1f\n", multiplyIt(times3, 100)) printf("%.1f\n", multiplyIt(times4, 100)) // Closure val divisorValue = 5 val divisor5 = (num: Double) => num / divisorValue print(divisor5(5.0)) // File IO val writer = new PrintWriter("test.txt") writer.write("Just some random text.\nMore random text") writer.close() val textFromFile = Source.fromFile("test.txt", "UTF-8") val lineIterator = textFromFile.getLines() for (line <- lineIterator) { println(line) } textFromFile.close() // Handle exceptions def divideNumbers(number1: Int, number2: Int) = try { number1 / number2 } catch { case ex: java.lang.ArithmeticException => "Can't divide by zero" } finally { // clean up after exception } println(divideNumbers(3, 0)) } }
mit
go-id/learning
ch1-basics/read-line/main.go
213
//package declarate package main import ( "fmt" "bufio" "os" ) func main(){ read := bufio.NewReader(os.Stdin) fmt.Print("Name : ") name, _ := read.ReadString('\n') fmt.Printf("Hello %s",name) }
mit
M1nistry/Cartogram
src/Cartogram/App.xaml.cs
295
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace Cartogram { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
mit
1751634419/SharpJVM
SharpJVM/SharpJVM/Runtime/InstructionType.cs
17492
using System; using SharpJVM.SharpJVM.Runtime.Instructions.Base; using SharpJVM.SharpJVM.Runtime.Instructions.Loads; using SharpJVM.SharpJVM.Runtime.Instructions.Math; using SharpJVM.SharpJVM.Runtime.Instructions.Store; using SharpJVM.SharpJVM.Runtime.Instructions.Comparisons; using SharpJVM.SharpJVM.Runtime.Instructions.Constants; using SharpJVM.SharpJVM.Runtime.Instructions.Control; using SharpJVM.SharpJVM.Runtime.Instructions.Conversions; using SharpJVM.SharpJVM.Runtime.Instructions.Extended; using SharpJVM.SharpJVM.Runtime.Instructions.Stack; using SharpJVM.SharpJVM.Runtime.Instructions.References; using SharpJVM.SharpJVM.Runtime.Instructions.Reserved; namespace SharpJVM.SharpJVM.Runtime { public class InstructionType { //Constants. private readonly Nop Nop = new Nop(); private readonly AConst_NULL AConst_NULL = new AConst_NULL(); private readonly IConst_M1 IConst_M1 = new IConst_M1(); private readonly IConst0 IConst0 = new IConst0(); private readonly IConst1 IConst1 = new IConst1(); private readonly IConst2 IConst2 = new IConst2(); private readonly IConst3 IConst3 = new IConst3(); private readonly IConst4 IConst4 = new IConst4(); private readonly IConst5 IConst5 = new IConst5(); private readonly LConst0 LConst0 = new LConst0(); private readonly LConst1 LConst1 = new LConst1(); private readonly FConst0 FConst0 = new FConst0(); private readonly FConst1 FConst1 = new FConst1(); private readonly FConst2 FConst2 = new FConst2(); private readonly DConst0 DConst0 = new DConst0(); private readonly DConst1 DConst1 = new DConst1(); private readonly Bipush Bipush = new Bipush(); private readonly Sipush Sipush = new Sipush(); private readonly Ldc Ldc = new Ldc(); private readonly LdcW LdcW = new LdcW(); private readonly Ldc2W Ldc2W = new Ldc2W(); //Loads. private readonly ILoad ILoad = new ILoad(); private readonly LLoad LLoad = new LLoad(); private readonly FLoad FLoad = new FLoad(); private readonly DLoad DLoad = new DLoad(); private readonly ALoad ALoad = new ALoad(); private readonly ILoad0 ILoad0 = new ILoad0(); private readonly ILoad1 ILoad1 = new ILoad1(); private readonly ILoad2 ILoad2 = new ILoad2(); private readonly ILoad3 ILoad3 = new ILoad3(); private readonly LLoad0 LLoad0 = new LLoad0(); private readonly LLoad1 LLoad1 = new LLoad1(); private readonly LLoad2 LLoad2 = new LLoad2(); private readonly LLoad3 LLoad3 = new LLoad3(); private readonly FLoad0 FLoad0 = new FLoad0(); private readonly FLoad1 FLoad1 = new FLoad1(); private readonly FLoad2 FLoad2 = new FLoad2(); private readonly FLoad3 FLoad3 = new FLoad3(); private readonly DLoad0 DLoad0 = new DLoad0(); private readonly DLoad1 DLoad1 = new DLoad1(); private readonly DLoad2 DLoad2 = new DLoad2(); private readonly DLoad3 DLoad3 = new DLoad3(); private readonly ALoad0 ALoad0 = new ALoad0(); private readonly ALoad1 ALoad1 = new ALoad1(); private readonly ALoad2 ALoad2 = new ALoad2(); private readonly ALoad3 ALoad3 = new ALoad3(); private readonly IALoad IALoad = new IALoad(); private readonly LALoad LALoad = new LALoad(); private readonly FALoad FALoad = new FALoad(); private readonly DALoad DALoad = new DALoad(); private readonly AALoad AALoad = new AALoad(); private readonly BALoad BALoad = new BALoad(); private readonly CALoad CALoad = new CALoad(); private readonly SALoad SALoad = new SALoad(); //Store. private readonly IStore IStore = new IStore(); private readonly LStore LStore = new LStore(); private readonly FStore FStore = new FStore(); private readonly DStore DStore = new DStore(); private readonly AStore AStore = new AStore(); private readonly IStore0 IStore0 = new IStore0(); private readonly IStore1 IStore1 = new IStore1(); private readonly IStore2 IStore2 = new IStore2(); private readonly IStore3 IStore3 = new IStore3(); private readonly LStore0 LStore0 = new LStore0(); private readonly LStore1 LStore1 = new LStore1(); private readonly LStore2 LStore2 = new LStore2(); private readonly LStore3 LStore3 = new LStore3(); private readonly FStore0 FStore0 = new FStore0(); private readonly FStore1 FStore1 = new FStore1(); private readonly FStore2 FStore2 = new FStore2(); private readonly FStore3 FStore3 = new FStore3(); private readonly DStore0 DStore0 = new DStore0(); private readonly DStore1 DStore1 = new DStore1(); private readonly DStore2 DStore2 = new DStore2(); private readonly DStore3 DStore3 = new DStore3(); private readonly AStore0 AStore0 = new AStore0(); private readonly AStore1 AStore1 = new AStore1(); private readonly AStore2 AStore2 = new AStore2(); private readonly AStore3 AStore3 = new AStore3(); private readonly IAStore IAStore = new IAStore(); private readonly LAStore LAStore = new LAStore(); private readonly FAStore FAStore = new FAStore(); private readonly DAStore DAStore = new DAStore(); private readonly AAStore AAStore = new AAStore(); private readonly BAStore BAStore = new BAStore(); private readonly CAStore CAStore = new CAStore(); private readonly SAStore SAStore = new SAStore(); //Stack. private readonly Pop Pop = new Pop(); private readonly Pop2 Pop2 = new Pop2(); private readonly Dup Dup = new Dup(); private readonly Dup_X1 Dup_X1 = new Dup_X1(); private readonly Dup_X2 Dup_X2 = new Dup_X2(); private readonly Dup2 Dup2 = new Dup2(); private readonly Dup2_X1 Dup2_X1 = new Dup2_X1(); private readonly Dup2_X2 Dup2_X2 = new Dup2_X2(); private readonly Swap Swap = new Swap(); //Math. private readonly IAdd IAdd = new IAdd(); private readonly LAdd LAdd = new LAdd(); private readonly FAdd FAdd = new FAdd(); private readonly DAdd DAdd = new DAdd(); private readonly ISub ISub = new ISub(); private readonly LSub LSub = new LSub(); private readonly FSub FSub = new FSub(); private readonly DSub DSub = new DSub(); private readonly IMul IMul = new IMul(); private readonly LMul LMul = new LMul(); private readonly FMul FMul = new FMul(); private readonly DMul DMul = new DMul(); private readonly IDiv IDiv = new IDiv(); private readonly LDiv LDiv = new LDiv(); private readonly DDiv DDiv = new DDiv(); private readonly IRem IRem = new IRem(); private readonly LRem LRem = new LRem(); private readonly FRem FRem = new FRem(); private readonly DRem DRem = new DRem(); private readonly INeg INeg = new INeg(); private readonly LNeg LNeg = new LNeg(); private readonly FNeg FNeg = new FNeg(); private readonly DNeg DNeg = new DNeg(); private readonly IShL IShL = new IShL(); private readonly LShL LShL = new LShL(); private readonly IShR IShR = new IShR(); private readonly LShR LShR = new LShR(); private readonly IUShR IUShR = new IUShR(); private readonly LUShR LUShR = new LUShR(); private readonly IAnd IAnd = new IAnd(); private readonly LAnd LAnd = new LAnd(); private readonly IOr IOr = new IOr(); private readonly LOr LOr = new LOr(); private readonly IXor IXor = new IXor(); private readonly LXor LXor = new LXor(); private readonly Iinc Iinc = new Iinc(); //Conversions. private readonly I2L I2L = new I2L(); private readonly I2F I2F = new I2F(); private readonly I2D I2D = new I2D(); private readonly L2I L2I = new L2I(); private readonly L2D L2D = new L2D(); private readonly F2I F2I = new F2I(); private readonly F2L F2L = new F2L(); private readonly F2D F2D = new F2D(); private readonly D2I D2I = new D2I(); private readonly D2L D2L = new D2L(); private readonly D2F D2F = new D2F(); private readonly I2B I2B = new I2B(); private readonly I2C I2C = new I2C(); private readonly I2S I2S = new I2S(); //Comparisons. private readonly Lcmp Lcmp = new Lcmp(); private readonly Fcmpl Fcmpl = new Fcmpl(); private readonly Fcmpg Fcmpg = new Fcmpg(); private readonly Dcmpl Dcmpl = new Dcmpl(); private readonly Dcmpg Dcmpg = new Dcmpg(); private readonly IfEQ IfEQ = new IfEQ(); private readonly IfNE IfNE = new IfNE(); private readonly IfLT IfLT = new IfLT(); private readonly IfGE IfGE = new IfGE(); private readonly IfGT IfGT = new IfGT(); private readonly IfLE IfLE = new IfLE(); private readonly IfIcmpEQ IfIcmpEQ = new IfIcmpEQ(); private readonly IfIcmpNE IfIcmpNE = new IfIcmpNE(); private readonly IfIcmpLT IfIcmpLT = new IfIcmpLT(); private readonly IfIcmpGE IfIcmpGE = new IfIcmpGE(); private readonly IfIcmpGT IfIcmpGT = new IfIcmpGT(); private readonly IfIcmpLE IfIcmpLE = new IfIcmpLE(); private readonly IfAcmpEQ IfAcmpEQ = new IfAcmpEQ(); private readonly IfAcmpNE IfAcmpNE = new IfAcmpNE(); //Control. private readonly Goto Goto = new Goto(); private readonly TableSwitch TableSwitch = new TableSwitch(); private readonly LookupSwitch LookupSwitch = new LookupSwitch(); private readonly IReturn IReturn = new IReturn(); private readonly LReturn LReturn = new LReturn(); private readonly FReturn FReturn = new FReturn(); private readonly DReturn DReturn = new DReturn(); private readonly AReturn AReturn = new AReturn(); private readonly Return Return = new Return(); //References. private readonly GetStatic GetStatic = new GetStatic(); private readonly PutStatic PutStatic = new PutStatic(); private readonly GetField GetField = new GetField(); private readonly PutField PutField = new PutField(); private readonly InvokeVirtual InvokeVirtual = new InvokeVirtual(); private readonly InvokeSpecial InvokeSpecial = new InvokeSpecial(); private readonly InvokeStatic InvokeStatic = new InvokeStatic(); private readonly InvokeInterface InvokeInterface = new InvokeInterface(); private readonly New New = new New(); private readonly NewArray NewArray = new NewArray(); private readonly AnewArray AnewArray = new AnewArray(); private readonly ArrayLength ArrayLength = new ArrayLength(); private readonly CheckCast CheckCast = new CheckCast(); private readonly Instanceof Instanceof = new Instanceof(); //Extended. private readonly Wide Wide = new Wide(); private readonly MultiAnewArray MultiAnewArray = new MultiAnewArray(); private readonly IfNull IfNull = new IfNull(); private readonly IfNonNull IfNonNull = new IfNonNull(); private readonly Goto_W Goto_W = new Goto_W(); //Reserved. private readonly InvokeNative InvokeNative = new InvokeNative(); public Instruction GetInstruction(byte OpCode) { switch (OpCode) { //Constants. case 0x00: return Nop; case 0x01: return AConst_NULL; case 0x02: return IConst_M1; case 0x03: return IConst0; case 0x04: return IConst1; case 0x05: return IConst2; case 0x06: return IConst3; case 0x07: return IConst4; case 0x08: return IConst5; case 0x09: return LConst0; case 0x0a: return LConst1; case 0x0b: return FConst0; case 0x0c: return FConst1; case 0x0d: return FConst2; case 0x0e: return DConst0; case 0x0f: return DConst1; case 0x10: return Bipush; case 0x11: return Sipush; case 0x12: return Ldc; case 0x13: return LdcW; case 0x14: return Ldc2W; //Loads. case 0x15: return ILoad; case 0x16: return LLoad; case 0x17: return FLoad; case 0x18: return DLoad; case 0x19: return ALoad; case 0x1a: return ILoad0; case 0x1b: return ILoad1; case 0x1c: return ILoad2; case 0x1d: return ILoad3; case 0x1e: return LLoad0; case 0x1f: return LLoad1; case 0x20: return LLoad2; case 0x21: return LLoad3; case 0x22: return FLoad0; case 0x23: return FLoad1; case 0x24: return FLoad2; case 0x25: return FLoad3; case 0x26: return DLoad0; case 0x27: return DLoad1; case 0x28: return DLoad2; case 0x29: return DLoad3; case 0x2a: return ALoad0; case 0x2b: return ALoad1; case 0x2c: return ALoad2; case 0x2d: return ALoad3; case 0x2e: return IALoad; case 0x2f: return LALoad; case 0x30: return FALoad; case 0x31: return DALoad; case 0x32: return AALoad; case 0x33: return BALoad; case 0x34: return CALoad; case 0x35: return SALoad; //Store. case 0x36: return IStore; case 0x37: return LStore; case 0x38: return FStore; case 0x39: return DStore; case 0x3a: return AStore; case 0x3b: return IStore0; case 0x3c: return IStore1; case 0x3d: return IStore2; case 0x3e: return IStore3; case 0x3f: return LStore0; case 0x40: return LStore1; case 0x41: return LStore2; case 0x42: return LStore3; case 0x43: return FStore0; case 0x44: return FStore1; case 0x45: return FStore2; case 0x46: return FStore3; case 0x47: return DStore0; case 0x48: return DStore1; case 0x49: return DStore2; case 0x4a: return DStore3; case 0x4b: return AStore0; case 0x4c: return AStore1; case 0x4d: return AStore2; case 0x4e: return AStore3; case 0x4f: return IAStore; case 0x50: return LAStore; case 0x51: return FAStore; case 0x52: return DAStore; case 0x53: return AAStore; case 0x54: return BAStore; case 0x55: return CAStore; case 0x56: return SAStore; //Stack. case 0x57: return Pop; case 0x58: return Pop2; case 0x59: return Dup; case 0x5a: return Dup_X1; case 0x5b: return Dup_X2; case 0x5c: return Dup2; case 0x5d: return Dup2_X1; case 0x5e: return Dup2_X2; case 0x5f: return Swap; //Math. case 0x60: return IAdd; case 0x61: return LAdd; case 0x62: return FAdd; case 0x63: return DAdd; case 0x64: return ISub; case 0x65: return LSub; case 0x66: return FSub; case 0x67: return DSub; case 0x68: return IMul; case 0x69: return LMul; case 0x6a: return FMul; case 0x6b: return DMul; case 0x6c: return IDiv; case 0x6d: return LDiv; case 0x6f: return DDiv; case 0x70: return IRem; case 0x71: return LRem; case 0x72: return FRem; case 0x73: return DRem; case 0x74: return INeg; case 0x75: return LNeg; case 0x76: return FNeg; case 0x77: return DNeg; case 0x78: return IShL; case 0x79: return LShL; case 0x7a: return IShR; case 0x7b: return LShR; case 0x7c: return IUShR; case 0x7d: return LUShR; case 0x7e: return IAnd; case 0x7f: return LAnd; case 0x80: return IOr; case 0x81: return LOr; case 0x82: return IXor; case 0x83: return LXor; case 0x84: return Iinc; //Conversions. case 0x85: return I2L; case 0x86: return I2F; case 0x87: return I2D; case 0x88: return L2I; case 0x89: return I2F; case 0x8a: return L2D; case 0x8b: return F2I; case 0x8c: return F2L; case 0x8d: return F2D; case 0x8e: return D2I; case 0x8f: return D2L; case 0x90: return D2F; case 0x91: return I2B; case 0x92: return I2C; case 0x93: return I2S; //Comparisons. case 0x94: return Lcmp; case 0x95: return Fcmpl; case 0x96: return Fcmpg; case 0x97: return Dcmpl; case 0x98: return Dcmpg; case 0x99: return IfEQ; case 0x9a: return IfNE; case 0x9b: return IfLT; case 0x9c: return IfGE; case 0x9d: return IfGT; case 0x9e: return IfLE; case 0x9f: return IfIcmpEQ; case 0xa0: return IfIcmpNE; case 0xa1: return IfIcmpLT; case 0xa2: return IfIcmpGE; case 0xa3: return IfIcmpGT; case 0xa4: return IfIcmpLE; case 0xa5: return IfAcmpEQ; case 0xa6: return IfAcmpNE; //Control. case 0xa7: return Goto; case 0xaa: return TableSwitch; case 0xab: return LookupSwitch; case 0xac: return IReturn; case 0xad: return LReturn; case 0xae: return FReturn; case 0xaf: return DReturn; case 0xb0: return AReturn; case 0xb1: return Return; //References. case 0xb2: return GetStatic; case 0xb3: return PutStatic; case 0xb4: return GetField; case 0xb5: return PutField; case 0xb6: return InvokeVirtual; case 0xb7: return InvokeSpecial; case 0xb8: return InvokeStatic; case 0xb9: return InvokeInterface; case 0xbb: return New; case 0xbc: return NewArray; case 0xbd: return AnewArray; case 0xbe: return ArrayLength; case 0xbf: return null; case 0xc0: return CheckCast; case 0xc1: return Instanceof; //Extended. case 0xc4: return Wide; case 0xc5: return MultiAnewArray; case 0xc6: return IfNull; case 0xc7: return IfNonNull; case 0xc8: return Goto_W; //Reserved. case 0xfe: return InvokeNative; default: return null; } } } }
mit
danieldeveloper001/Learning
Ruby/02_DesignPatterns/Behavioral/ChainOfResponsibility/Program.rb
366
require './ChainLink1' require './ChainLink2' require './ChainLink3' def main c1 = ChainLink1.new c2 = ChainLink2.new c3 = ChainLink3.new c1.next_link = c2 c2.next_link = c3 result = c1.process_request 'Request1' puts result result = c1.process_request 'Request2' puts result result = c1.process_request 'Request3' puts result end main()
mit
plribeiro3000/fog-google
tests/requests/dns/managed_zone_tests.rb
2289
Shindo.tests("Fog::DNS[:google] | managed_zone requests", ["google"]) do @google = Fog::DNS[:google] @managed_zone_schema = { "kind" => String, "id" => String, "creationTime" => String, "name" => String, "dnsName" => String, "description" => String, "nameServers" => [String] } @list_managed_zones_schema = { "kind" => String, "managedZones" => [@managed_zone_schema] } tests("success") do zone_name = "new-zone-test" DEFAULT_ZONE_DNS_NAME = "fog-test.your-own-domain.com." # Google requires confirmation of ownership for created domains in some # cases. If you want to run tests in non-mocked mode, set the environment # variable to a domain you own. zone_dns_name = ENV["FOG_TEST_GOOGLE_DNS_ZONE"] || DEFAULT_ZONE_DNS_NAME unless Fog.mocking? || zone_dns_name != DEFAULT_ZONE_DNS_NAME tests("Needs a verified domain, set $FOG_TEST_GOOGLE_DNS_ZONE").pending end tests("$FOG_TEST_GOOGLE_DNS_ZONE ends with dot").pending unless zone_dns_name.end_with?(".") tests("#create_managed_zone").data_matches_schema( @managed_zone_schema, :allow_extra_keys => false) do @google.create_managed_zone(zone_name, zone_dns_name, "Fog test domain").body end tests("#get_managed_zone") do response = @google.get_managed_zone(zone_name).body tests("schema").data_matches_schema(@managed_zone_schema, :allow_extra_keys => false) { response } tests("test zone present").returns(zone_name) { response["name"] } end tests("#list_managed_zones") do response = @google.list_managed_zones.body tests("schema").data_matches_schema(@list_managed_zones_schema, :allow_extra_keys => false) { response } tests("test zone present").returns(true) { response["managedZones"].one? { |zone| zone["name"] == zone_name } } end tests("#delete_managed_zone").returns(nil) do @google.delete_managed_zone(zone_name).body end end tests("failure") do tests("#delete_managed_zone").raises(Fog::Errors::NotFound) do @google.delete_managed_zone("zone-which-does-not-exist").body end tests("#get_managed_zone").raises(Fog::Errors::NotFound) do @google.get_managed_zone("zone-which-does-not-exist").body end end end
mit
chinxianjun/autorepair
test/unit/company_workflow_test.rb
129
require 'test_helper' class CompanyWorkflowTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
mit
emrizaal/bgg
application/views/admin/detail_facilities.php
646
<?php $this->load->view("admin/header"); ?> <!-- /. NAV SIDE --> <div id="page-wrapper" > <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2 align="center"><?=$data['name']?></h2> <hr> </div> </div> <div class="row"> <div class="col-md-12"> <?=$data['content']?> </div> </div> <hr> <a href="<?=base_url()?>admin/facilities"><button class="btn btn-primary">Back</button></a> </div> <!-- /. PAGE INNER --> </div> <?php $this->load->view('admin/footer'); ?>
mit
bamlab/generator-rn-toolbox
generators/circleci/index.js
6215
const Base = require('yeoman-generator'); require('colors'); const glob = require('glob'); const analytics = require('../../analytics'); // Command creators const getPassphraseAliasForEnvironment = environment => `${environment.envName.toUpperCase()}_SECRETS_PASSPHRASE`; const getUnpackCommandForEnvironment = environment => `sudo yarn unpack-secrets -e ${ environment.envName } -p \${${getPassphraseAliasForEnvironment(environment)}}`; const getCodePushCommandForEnvironment = environment => `yarn deploy -t soft -e ${environment.envName}`; const getAndroidHardDeployCommandForEnvironment = environment => `yarn deploy -t hard -o android -e ${environment.envName}`; const getIosHardDeployCommandForEnvironment = environment => `yarn deploy -t hard -o ios -e ${environment.envName}`; class CircleGenerator extends Base { initializing() { analytics.pageview('/circleci').send(); this.composeWith('rn-toolbox:checkversion'); if (!this.config.get('fastlane')) this.log.error( 'You need to run `yo rn-toolbox:fastlane` first.'.red.bold ); if (!this.config.get('circleci-ready')) this.log.error( 'You need to have the deployment script and secrets archive from fastlane-setup to use this generator. Get them by running yo rn-toolbox:fastlane-setup.' .red.bold ); } prompting() { const config = this.fs.readJSON(this.destinationPath('package.json')); const envFilepaths = glob.sync('fastlane/.env.*', { ignore: 'fastlane/.env.*.*', }); const environments = envFilepaths.map(filePath => { const split = filePath.split('/'); const envName = split[split.length - 1].split('.')[2]; const fileString = this.fs.read(filePath); const envGitBranch = fileString .split("REPO_GIT_BRANCH='")[1] .split("'")[0]; return { envName, envGitBranch, }; }); if (environments.length === 0) this.log.error( 'You need at least one environment setup with fastlane-env to run this generator. Run yo rn-toolbox:fastlane-env.' .red.bold ); const prompts = [ { type: 'input', name: 'projectName', message: 'Please confirm the react-native project name (as in react-native-init <PROJECT_NAME>)', required: true, default: config.name, }, { type: 'input', name: 'reactNativeDirectory', message: 'Path to the React Native project relative to the root of the repository (no trailing slash)', required: true, default: '.', }, ]; return this.prompt(prompts).then(answers => { this.answers = answers; this.environments = environments; }); } writing() { // Command creators const numberOfEnvironments = this.environments.length; const getPerEnvironmentCommand = commandGetter => { let switchString = ''; this.environments.forEach((environment, index) => { const prefix = index === 0 ? 'if' : 'elif'; const suffix = index === numberOfEnvironments - 1 ? 'fi' : ''; if (index > 0) switchString += ''; switchString += `${prefix} [ "\${CIRCLE_BRANCH}" == "${ environment.envGitBranch }" ]; then ${commandGetter(environment)} ${suffix}`; }); return switchString; }; const getForAllEnvironmentsCommand = command => { let ifStatement = `if [ "\${CIRCLE_BRANCH}" == "${ this.environments[0].envGitBranch }" ]`; this.environments.slice(1).forEach(environment => { ifStatement += `|| [ "\${CIRCLE_BRANCH}" == "${environment.envName}" ]`; }); ifStatement += ';'; return `${ifStatement} then ${command} fi`; }; // Commands const unpackSecretsCommand = getPerEnvironmentCommand( getUnpackCommandForEnvironment ); const installAppcenterCommand = getForAllEnvironmentsCommand(`echo 'export PATH=$(yarn global bin):$PATH' >> $BASH_ENV source $BASH_ENV yarn global add appcenter-cli appcenter login --token \${FL_APPCENTER_API_TOKEN} --quiet`); const codepushCommand = getPerEnvironmentCommand( getCodePushCommandForEnvironment ); const androidHardDeployCommand = getPerEnvironmentCommand( getAndroidHardDeployCommandForEnvironment ); const iosHardDeployCommand = getPerEnvironmentCommand( getIosHardDeployCommandForEnvironment ); let branchesOnlyCommand = ''; this.environments.forEach(environment => { branchesOnlyCommand += ` - ${environment.envGitBranch}`; }); // Create final config.yml file :-) this.fs.copyTpl( this.templatePath('config.yml'), this.destinationPath('.circleci/config.yml'), { ...this.answers, prefixRN: path => `${this.answers.reactNativeDirectory}/${path || ''}`, unpackSecretsCommand, installAppcenterCommand, codepushCommand, androidHardDeployCommand, iosHardDeployCommand, branchesOnlyCommand, } ); } end() { this.log( `Custom config.yml created. Re-run yo rn-toolbox:circleci anytime to re-generate the file with latest environments information.` .green.bold ); this.log( `Please make sure that CircleCI has access to your MATCH repo using 'Checkout ssh Keys' section in settings. Good practice: Github account should have readonly access and only to this repo.` .magenta.bold ); this.log( `Please make sure that all of the following environment variables have been added in the Circle-CI console's Environment Variables section:` .magenta.bold ); this.log( [ 'FL_APPCENTER_API_TOKEN', 'MATCH_PASSWORD', 'FASTLANE_PASSWORD (<- password of AppstoreConnect Apple ID)', ] .concat(this.environments.map(getPassphraseAliasForEnvironment)) .join(', ').magenta.bold ); this.config.set('circleci', true); this.config.save(); } } module.exports = CircleGenerator;
mit
p2pu/learning-circles
studygroups/migrations/0001_initial.py
2548
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=128)), ('provider', models.CharField(max_length=256)), ('link', models.URLField()), ('start_date', models.DateField()), ('duration', models.CharField(max_length=128)), ('prerequisite', models.TextField()), ('time_required', models.CharField(max_length=128)), ('caption', models.TextField()), ('description', models.TextField()), ('created_at', models.DateTimeField(auto_now_add=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='StudyGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('location', models.CharField(max_length=128)), ('location_link', models.URLField()), ('time', models.CharField(max_length=128)), ('max_size', models.IntegerField()), ('description', models.TextField()), ('created_at', models.DateTimeField(auto_now_add=True)), ('course', models.ForeignKey(to='studygroups.Course', on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='StudyGroupSignup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('username', models.CharField(max_length=128)), ('email', models.EmailField(max_length=75)), ('created_at', models.DateTimeField(auto_now_add=True)), ('study_group', models.ForeignKey(to='studygroups.StudyGroup', on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='studygroupsignup', unique_together=set([('email', 'study_group')]), ), ]
mit
izonder/labyrinth
src/core/storage.js
1246
'use strict'; var MongoClient = require('mongodb').MongoClient; class Storage { /** * MongoDB storage driver * @param config * @param logger */ constructor(config, logger) { this.config = config || {}; this.logger = logger; this.dsn = this._getDsn(); this.db = null; } /** * Storage initialization * @returns {Promise} */ init() { return new Promise((resolve, reject) => { MongoClient.connect(this.dsn) .then((db) => { this.db = db; this.logger.info('[Storage] MongoDB successfully connected'); resolve(this.db); }) .catch((e) => { this.logger.error('[Storage] MongoDB driver failed'); reject(e); }); }); } /** * DSN calculation * @returns {string} * @private */ _getDsn() { return [ 'mongodb://', this.config.host || 'localhost', ':', this.config.port || '27017', '/', this.config.db || 'test' ].join(''); } } module.exports = Storage;
mit
bmcminn/electron-har
src/index.js
2903
var tmp = require('tmp'); var assign = require('object-assign'); var fs = require('fs'); var crossExecFile = require('cross-exec-file'); /** * @param {string} url url (e.g. http://google.com) * @param {object} o CLI options (NOTE: only properties not present in (or different from) CLI are described below) * @param {object|string} o.user either object with 'name' and 'password' properties or a string (e.g. 'username:password') * @param {string} o.user.name username * @param {string} o.user.password password * @param {string} o.user-agent user device profile name * @param {string} o.limit-rate network throttling profile name * @param {string} o.landscape force device profile to be landscape * @param {function(err, json)} callback callback (NOTE: if err != null err.code will be the exit code (e.g. 3 - wrong usage, * 4 - timeout, below zero - http://src.chromium.org/svn/trunk/src/net/base/net_error_list.h)) */ module.exports = function electronHAR(url, options, callback) { typeof options === 'function' && (callback = options, options = {}); // using temporary file to prevent messages like "Xlib: extension ...", // "libGL error ..." from cluttering stdout in a headless env (as in Xvfb). tmp.file(function (err, path, fd, cleanup) { if (err) { return callback(err); } callback = (function (callback) { return function () { process.nextTick(Function.prototype.bind.apply(callback, [null].concat(Array.prototype.slice.call(arguments)) )); cleanup(); }; })(callback); console.log(options); // map options into config object var config = assign({}, options, { output: path, user: options.user === Object(options.user) ? options.user.name + ':' + options.user.password : options.user, 'user-agent': options['user-agent'] ? options['user-agent'] : null, 'limit-rate': options['limit-rate'] ? options['limit-rate'] : null, landscape: options['landscape'] ? options['landscape'] : null }); // initialize electron-har process crossExecFile( __dirname + '/../bin/electron-har', [url].concat( Object .keys(config) .reduce(function (n, flag) { var argvs = config[flag]; argvs !== null && argvs.push(flag.length === 1 ? '-' + flag : '--' + flag, argvs); return argvs; }, []) ), function (err, stdout, stderr) { if (err) { if (stderr) { err.message = stderr.trim(); } return callback(err); } fs.readFile(path, 'utf8', function (err, data) { if (err) { return callback(err); } try { callback(null, JSON.parse(data)); } catch (e) { return callback(e); } }); }); }); };
mit
bluepangolin55/IMP
src/functionality/Shape.java
984
package functionality; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Set; /** * Created by dimitri on 27/01/16. * A shape efficiently stores the information of an image, that is not rectangular. * It can be used for example to represent image layers that only cover parts of the * full image or to save the parts of an image that have been changed during an * operations, so that they can be undone. * The History class is implemented as a stack of shapes. * * Implementation: * A shape is implemented as a vector that stores all pixels in * left-to-right, top-to-bottom order, a vector that stores all the rows * that contain pixels and a vector that stores the start end end points of * pixel arrays for each column. * * A shape can be constructed using a selection and an image. */ public class Shape { private int[] data; private int[] rows; private int[] columns; public Shape(BufferedImage image, SelectionMap selection){ } }
mit
lastzero/symlex-core
src/Tests/Kernel/AppTest.php
1829
<?php namespace Symlex\Tests\Kernel; use TestTools\TestCase\UnitTestCase; use Symlex\Tests\Kernel\App\App; /** * @author Michael Mayer <michael@liquidbytes.net> * @license MIT */ class AppTest extends UnitTestCase { /** * @var App */ protected $app; public function setUp(): void { $this->app = new App('symlex_test', __DIR__ . '/App', true); } public function testGetName() { $result = $this->app->getName(); $this->assertEquals('App', $result); } public function testGetVersion() { $result = $this->app->getVersion(); $this->assertEquals('1.0', $result); } public function testGetEnvironment() { $result = $this->app->getEnvironment(); $this->assertEquals('symlex_test', $result); } public function testGetCharset() { $result = $this->app->getCharset(); $this->assertEquals('UTF-8', $result); } public function testGetAppParameters() { $result = $this->app->getContainerParameters(); $this->assertIsArray($result); $this->assertArrayHasKey('app.name', $result); $this->assertArrayHasKey('app.version', $result); $this->assertArrayHasKey('app.environment', $result); $this->assertArrayHasKey('app.debug', $result); $this->assertArrayHasKey('app.charset', $result); $this->assertArrayHasKey('app.path', $result); $this->assertArrayHasKey('app.cache_path', $result); $this->assertArrayHasKey('app.log_path', $result); $this->assertArrayHasKey('app.config_path', $result); } public function testGetContainer() { $result = $this->app->getContainer(); $this->assertInstanceOf('\Symfony\Component\DependencyInjection\Container', $result); } }
mit
CalPolyIEEE/parts.calpolyieee.org
js/Part.js
2779
"use strict"; parts.Part = function (skel) { var self = this; this.skel = skel; if (!skel.quantity) { this.skel.quantity = 1; } this.$liQuantity = $("<input type=\"text\">"); this.$liRemove = $("<i class=\"fa fa-times fa-lg\">"); this.$liQuantity.keyup(function () { self.skel.quantity = parseInt($(this).val(), 10); }); }; parts.Part.prototype.renderToKit = function () { return $("<div class='item'>").html(this.skel.quantity + " x " + this); }; parts.Part.prototype.toString = function () { return this.skel.category + " " + parts.Part.toHuman(this.skel.main_info) + " " + this.skel.addtl_info.reduce(function (str, pair) { return str + parts.Part.toHuman(pair) + " "; }, "") + " " + (this.skel.chip_type || "") + " " + (this.skel.mftr || "") + " " + (this.skel.name || "") + " "; }; parts.Part.prototype.renderToFinal = function () { return $("<div>").append( this.skel.quantity + " x " + this + "@ " + utils.toMoney(this.skel.price) + "<span> = " + utils.toMoney(this.skel.quantity * this.skel.price) + "</span>" ); }; parts.Part.prototype.renderToLineItem = function () { return utils.toTr( this.$liQuantity.val(this.skel.quantity), this.skel.id || "<em>n/a</em>", this.skel.category, parts.Part.toHuman(this.skel.main_info), this.skel.price && utils.toMoney(this.skel.price) || "<em>n/a</em>", this.$liRemove ); }; parts.Part.toSymbol = function (unit) { switch (unit) { case "Ohm": return "&Omega;"; case "Farad": return "F"; case "Watt": return "W"; case "Hertz": return "Hz"; case "Volt": return "V"; case "Henry": return "H"; case "meter": return "m"; default: return unit; } }; parts.Part.toHuman = function (pair) { //positive magnitude prefixes var posMags = ["", "k", "M", "G", "T", "P"]; //negative magnitude prefixes var negMags = ["", "m", "&micro;", "n", "p", "f", "a"]; var mag = 0, unit, value; if(!pair.hasOwnProperty("value")) { return pair.name; } value = pair.value = parseFloat(pair.value); if (pair.value && pair.value > 999) { while (value > 1000) { value /= 1000; mag++; } unit = posMags[mag] + parts.Part.toSymbol(pair.name); } else if(pair.value && pair.value < 1) { while (value < 1) { value *= 1000; mag++; } unit = negMags[mag] + parts.Part.toSymbol(pair.name); } else { unit = parts.Part.toSymbol(pair.name); } //the extra '+' before value removes trailing zeros return +value.toFixed(2) + unit; };
mit
geea-develop/geea-wedding-planner
config/database.php
4501
<?php return [ /* |-------------------------------------------------------------------------- | PDO Fetch Style |-------------------------------------------------------------------------- | | By default, database results will be returned as instances of the PHP | stdClass object; however, you may desire to retrieve records in an | array format for simplicity. Here you can tweak the fetch style. | */ 'fetch' => PDO::FETCH_CLASS, /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => env('DB_CONNECTION', 'mongodb'), /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => [ 'sqlite' => [ 'driver' => 'sqlite', 'database' => database_path('database.sqlite'), 'prefix' => '', ], 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, 'engine' => null, ], 'pgsql' => [ 'driver' => 'pgsql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ], 'sqlsrv' => [ 'driver' => 'sqlsrv', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', ], 'mongodb' => [ 'host' => 'localhost', 'port' => 27017, 'database' => 'weddb', 'username' => '', 'password' => '' ] ], /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk haven't actually been run in the database. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => [ 'cluster' => false, 'default' => [ 'host' => env('REDIS_HOST', 'localhost'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 0, ], ], ];
mit
Twiknight/tiny
test/request/acceptCharsets.js
1617
'use strict' const expect = require('chai').expect; const Request = require('../../lib/request'); const httpMocks = require('node-mocks-http'); describe('request.acceptCharsets', function () { it('should return single accept charset', function(done){ let requestOpts = { method: 'PUT', url: '/user/tobi', headers:{ 'content-length': 3000, host:'google.com:80', 'accept-charset':'utf-8' } }; let req = httpMocks.createRequest(requestOpts); let request = new Request(req); expect(request.acceptCharsets).to.have.property('utf-8',1); done(); }); it('should return multiple accept charsets', function(done){ let requestOpts = { method: 'PUT', url: '/user/tobi', headers:{ host:'google.com:80', 'accept-charset': 'iso-8859-5, unicode-1-1;q=0.8' } }; let req = httpMocks.createRequest(requestOpts); let request = new Request(req); expect(request.acceptCharsets).to.have.property('iso-8859-5',1); expect(request.acceptCharsets).to.have.property('unicode-1-1',0.8); done(); }); it('should return default if not fixed', function(done){ let requestOpts = { method: 'PUT', url: '/user/tobi', headers:{ host:'google.com:80' } }; let req = httpMocks.createRequest(requestOpts); let request = new Request(req); expect(request.acceptCharsets).to.have.property('*',1); done(); }); });
mit
Credit-Jeeves/Heartland
src/Payum2/Heartland/Soap/Base/ActivateMachine.php
1105
<?php namespace Payum2\Heartland\Soap\Base; /** * This class is generated from the following WSDL: * https://heartlandpaymentservices.net/BillingDataManagement/v3/BillingDataManagementService.svc?xsd=xsd0 */ class ActivateMachine { /** * ActivateMachineRequest * * The property has the following characteristics/restrictions: * - SchemaType: q7:ActivateMachineRequest * * @var ActivateMachineRequest */ protected $ActivateMachineRequest = null; /** * @param ActivateMachineRequest $activateMachineRequest * * @return ActivateMachine */ public function setActivateMachineRequest(ActivateMachineRequest $activateMachineRequest) { $this->ActivateMachineRequest = $activateMachineRequest; return $this; } /** * @return ActivateMachineRequest */ public function getActivateMachineRequest() { if (null === $this->ActivateMachineRequest) { $this->ActivateMachineRequest = new ActivateMachineRequest(); } return $this->ActivateMachineRequest; } }
mit
wjwu/Settlement-React
SettlementWeb/webpack.config.prd.js
2599
var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var config = { 'API_HOST': 'http://120.24.244.98:9001/api/', 'NODE_ENV': process.env.NODE_ENV } module.exports = { externals: { 'react': 'React', 'react-dom': 'ReactDOM', 'moment': 'moment' }, entry: { 'app': [ './src/app/index.js', 'whatwg-fetch' ], 'login': [ './src/login/index.js', 'whatwg-fetch' ], 'print': [ './src/print/index.js', 'whatwg-fetch' ], 'vendor': ['babel-polyfill', 'react-redux', 'antd', 'numeral', 'echarts-for-react'] }, output: { path: __dirname + '/dist', filename: '[name].[hash].js', publicPath: '/', chunkFilename: '[name].chunk.[hash].js' }, module: { rules: [{ test: /\.js$/, exclude: /node_modules/, use: 'babel-loader' }, { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader!postcss', use: 'css-loader?modules&localIdentName=[name]__[local]-[hash:base64:5]!sass-loader' }) }, { test: /\.less$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader!postcss', use: 'css-loader!less-loader' }) }, { test: /\.(jpg|gif)$/, use: 'url-loader?limit=8192' }, { test: /\.css$/, use: 'file-loader?name=[path][name].[ext]' }, { test: /\.html$/, use: 'html-loader' }] }, devtool: false, plugins: [ new HtmlWebpackPlugin({ filename: __dirname + '/dist/login.html', template: __dirname + '/src/login/index.tpl.html', minify: false, inject: 'body', hash: false, chunks: ['login'] }), new HtmlWebpackPlugin({ filename: __dirname + '/dist/index.html', template: __dirname + '/src/app/index.tpl.html', minify: false, inject: 'body', hash: false, chunks: ['app', 'vendor'] }), new HtmlWebpackPlugin({ filename: __dirname + '/dist/print.html', template: __dirname + '/src/print/index.tpl.html', minify: false, inject: 'body', hash: false, chunks: ['print'] }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, mangle: { except: ['$', 'exports', 'require'] }, comments: false }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', chunks: ['app'] }), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new ExtractTextPlugin({ filename: '[name].[hash].css', disable: false, allChunks: true }), new webpack.DefinePlugin({ 'process.env': JSON.stringify(config) }) ] };
mit
wicak29/takon-seek
assets/tinymce/js/tinymce/plugins/imagetools/src/main/js/CropRect.js
7087
/** * CropRect.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * ... */ define("tinymce/imagetoolsplugin/CropRect", [ "global!tinymce.dom.DomQuery", "global!tinymce.ui.DragHelper", "global!tinymce.geom.Rect", "global!tinymce.util.Tools", "global!tinymce.util.Observable", "global!tinymce.util.VK" ], function($, DragHelper, Rect, Tools, Observable, VK) { var count = 0; return function(currentRect, viewPortRect, clampRect, containerElm, action) { var instance, handles, dragHelpers, blockers, prefix = 'mce-', id = prefix + 'crid-' + (count++); handles = [ {name: 'move', xMul: 0, yMul: 0, deltaX: 1, deltaY: 1, deltaW: 0, deltaH: 0, label: 'Crop Mask'}, {name: 'nw', xMul: 0, yMul: 0, deltaX: 1, deltaY: 1, deltaW: -1, deltaH: -1, label: 'Top Left Crop Handle'}, {name: 'ne', xMul: 1, yMul: 0, deltaX: 0, deltaY: 1, deltaW: 1, deltaH: -1, label: 'Top Right Crop Handle'}, {name: 'sw', xMul: 0, yMul: 1, deltaX: 1, deltaY: 0, deltaW: -1, deltaH: 1, label: 'Bottom Left Crop Handle'}, {name: 'se', xMul: 1, yMul: 1, deltaX: 0, deltaY: 0, deltaW: 1, deltaH: 1, label: 'Bottom Right Crop Handle'} ]; blockers = ["top", "right", "bottom", "left"]; function getAbsoluteRect(outerRect, relativeRect) { return { x: relativeRect.x + outerRect.x, y: relativeRect.y + outerRect.y, w: relativeRect.w, h: relativeRect.h }; } function getRelativeRect(outerRect, innerRect) { return { x: innerRect.x - outerRect.x, y: innerRect.y - outerRect.y, w: innerRect.w, h: innerRect.h }; } function getInnerRect() { return getRelativeRect(clampRect, currentRect); } function moveRect(handle, startRect, deltaX, deltaY) { var x, y, w, h, rect; x = startRect.x; y = startRect.y; w = startRect.w; h = startRect.h; x += deltaX * handle.deltaX; y += deltaY * handle.deltaY; w += deltaX * handle.deltaW; h += deltaY * handle.deltaH; if (w < 20) { w = 20; } if (h < 20) { h = 20; } rect = currentRect = Rect.clamp({x: x, y: y, w: w, h: h}, clampRect, handle.name == 'move'); rect = getRelativeRect(clampRect, rect); instance.fire('updateRect', {rect: rect}); setInnerRect(rect); } function render() { function createDragHelper(handle) { var startRect; return new DragHelper(id, { document: containerElm.ownerDocument, handle: id + '-' + handle.name, start: function() { startRect = currentRect; }, drag: function(e) { moveRect(handle, startRect, e.deltaX, e.deltaY); } }); } $( '<div id="' + id + '" class="' + prefix + 'croprect-container"' + ' role="grid" aria-dropeffect="execute">' ).appendTo(containerElm); Tools.each(blockers, function(blocker) { $('#' + id, containerElm).append( '<div id="' + id + '-' + blocker + '"class="' + prefix + 'croprect-block" style="display: none" data-mce-bogus="all">' ); }); Tools.each(handles, function(handle) { $('#' + id, containerElm).append( '<div id="' + id + '-' + handle.name + '" class="' + prefix + 'croprect-handle ' + prefix + 'croprect-handle-' + handle.name + '"' + 'style="display: none" data-mce-bogus="all" role="gridcell" tabindex="-1"' + ' aria-label="' + handle.label + '" aria-grabbed="false">' ); }); dragHelpers = Tools.map(handles, createDragHelper); repaint(currentRect); $(containerElm).on('focusin focusout', function(e) { $(e.target).attr('aria-grabbed', e.type === 'focus'); }); $(containerElm).on('keydown', function(e) { var activeHandle; Tools.each(handles, function(handle) { if (e.target.id == id + '-' + handle.name) { activeHandle = handle; return false; } }); function moveAndBlock(evt, handle, startRect, deltaX, deltaY) { evt.stopPropagation(); evt.preventDefault(); moveRect(activeHandle, startRect, deltaX, deltaY); } switch (e.keyCode) { case VK.LEFT: moveAndBlock(e, activeHandle, currentRect, -10, 0); break; case VK.RIGHT: moveAndBlock(e, activeHandle, currentRect, 10, 0); break; case VK.UP: moveAndBlock(e, activeHandle, currentRect, 0, -10); break; case VK.DOWN: moveAndBlock(e, activeHandle, currentRect, 0, 10); break; case VK.ENTER: case VK.SPACEBAR: e.preventDefault(); action(); break; } }); } function toggleVisibility(state) { var selectors; selectors = Tools.map(handles, function(handle) { return '#' + id + '-' + handle.name; }).concat(Tools.map(blockers, function(blocker) { return '#' + id + '-' + blocker; })).join(','); if (state) { $(selectors, containerElm).show(); } else { $(selectors, containerElm).hide(); } } function repaint(rect) { function updateElementRect(name, rect) { if (rect.h < 0) { rect.h = 0; } if (rect.w < 0) { rect.w = 0; } $('#' + id + '-' + name, containerElm).css({ left: rect.x, top: rect.y, width: rect.w, height: rect.h }); } Tools.each(handles, function(handle) { $('#' + id + '-' + handle.name, containerElm).css({ left: rect.w * handle.xMul + rect.x, top: rect.h * handle.yMul + rect.y }); }); updateElementRect('top', {x: viewPortRect.x, y: viewPortRect.y, w: viewPortRect.w, h: rect.y - viewPortRect.y}); updateElementRect('right', {x: rect.x + rect.w, y: rect.y, w: viewPortRect.w - rect.x - rect.w + viewPortRect.x, h: rect.h}); updateElementRect('bottom', { x: viewPortRect.x, y: rect.y + rect.h, w: viewPortRect.w, h: viewPortRect.h - rect.y - rect.h + viewPortRect.y }); updateElementRect('left', {x: viewPortRect.x, y: rect.y, w: rect.x - viewPortRect.x, h: rect.h}); updateElementRect('move', rect); } function setRect(rect) { currentRect = rect; repaint(currentRect); } function setViewPortRect(rect) { viewPortRect = rect; repaint(currentRect); } function setInnerRect(rect) { setRect(getAbsoluteRect(clampRect, rect)); } function setClampRect(rect) { clampRect = rect; repaint(currentRect); } function destroy() { Tools.each(dragHelpers, function(helper) { helper.destroy(); }); dragHelpers = []; } render(containerElm); instance = Tools.extend({ toggleVisibility: toggleVisibility, setClampRect: setClampRect, setRect: setRect, getInnerRect: getInnerRect, setInnerRect: setInnerRect, setViewPortRect: setViewPortRect, destroy: destroy }, Observable); return instance; }; });
mit
ryaan-anthony/eco-breed
www/content/howto/2.php
62128
<button num='2a' class='sub-tab sub-howto'><span class='subCap'>a</span> Actions</button> <button num='2b' class='sub-tab sub-howto'><span class='subCap'>b</span> Names</button> <button num='2c' class='sub-tab sub-howto'><span class='subCap'>c</span> Lifespan</button> <button num='2d' class='sub-tab sub-howto'><span class='subCap'>d</span> Growth</button> <button num='2e' class='sub-tab sub-howto'><span class='subCap'>e</span> Hunger</button> <button num='2f' class='sub-tab sub-howto'><span class='subCap'>f</span> Breeding</button> <button num='2g' class='sub-tab sub-howto'><span class='subCap'>g</span> Rebuild</button> <!--Start--> <div class='sub-content sub-default'> <?php print subButton('2a','Explore the Action Object'); ?> <?php print wttabline('lifecycle and <strong>behavior</strong>.','add, modify, or disable core events',true); ?> <?php print insertlogo(); ?> <div class='sub-info'> <p>This section covers...</p> <ul> <li num='2a'>How to use <strong>Actions</strong>.</li> <li num='2b'>How to set the <strong>name</strong> of your breed.</li> <li num='2c'>How to define <strong>life</strong> and <strong>death</strong>.</li> <li num='2d'>How to make the breed <strong>grow</strong>.</li> <li num='2e'>Working up an <strong>appetite</strong>.</li> <li num='2f'>How to establish <strong>mating</strong> behaviors of a species.</li> <li num='2g'>How to <strong>rebuild</strong> existing breeds.</li> </ul> </div> </div> <!--Actions--> <div num='2a' class='sub-content' style='display:none;'> <!--Summary Start--> <div class='frame-2a'> <?php print subButton('2b','Naming the Breed'); ?> <?php print wtheadline('The Action object','is a multifunctional access point for the eco-Breeds. The action scripts can be configured for a variety of purposes including as a limited or public food source, breeding nest, home object, toy or game, with the ability to rebuild lost, missing, or hidden breeds. The number of interactions can be limited per Action, and breeds can be configured to ignore certain types of Actions. Additional functionality is defined using eco "methods" which are triggered by a series of "events" defined in the Actions list. Each event is a chance to give your breed unique interactions and functionality.'); ?> <div style='padding:20px;'> <p class='sub-in'><strong>Breakdown of the Actions list:</strong> <button num='1' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>Understanding native events:</strong> <button num='2' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>How methods work and how to use them:</strong> <button num='3' class='sub-in-btn'>Try It</button></p> <hr /> <p class='sub-in'><strong>Easy events to bind to your breeds:</strong> <button num='4' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>Customize your action touch events:</strong> <button num='5' class='sub-in-btn'>Try It</button></p> <hr /> <p class='sub-in'><strong>Syncing breeds with action objects:</strong> <button num='6' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>More event binding for smarter simulations:</strong> <button num='7' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>Extending the Action list:</strong> <button num='8' class='sub-in-btn'>Try It</button></p> </div> </div> <!--Formatting Actions--> <div num='1' class='frame-2a' style='display:none;'> <?php print backButton('Go Back',2); ?> <?php print wtheadline('The Actions list','is found in the \'action-settings\' script inside of the action object. This list is where functionality is defined is populated by combining an "event" identifier with a string of "methods" in a strided list. Events <span style=\'color:red;\'>can not</span> be listed twice in the same script.'); ?> <div style='padding:0 20px;'> <?php print actions_comment('Use the following','','format:');?> <?php print actions_code('"event 1", "method()", "event 2", "method()"');?> <?php print actions_comment('Also ','','acceptable:');?> <?php print actions_code('"event-3", "method() method(value) method(value, value)", "event_4", "method(value) method(value, value)"');?> <p class='sub-in'>Spaces, tabs, and other whitespace <strong>will be removed</strong> during processing.</p> <p class='sub-in'>If the script displays an error when saving, it's usually because <strong>this list was improperly formatted.</strong></p> </div> </div> <!--Native Events--> <div num='2' class='frame-2a' style='display:none;'> <?php print backButton('Go Back',3); ?> <?php print wtheadline('Native events','are reserved \'event\' names which are toggled automatically at the end of a core event or when specific conditions are met.'); ?> <div style='padding:20px;'> <div class='entry sub-pad'> <?php print actions_comment('When a breed or action is rezzed, a','"start"','event is toggled.');?> <?php print actions_code('"start", "say(Hello, %owner%!)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Each time the breed completes a','"growth"',' stage, this event is toggled.');?> <?php print actions_code('"growth", "say(%MyName% has %Growth_Stages% remaining!)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('When the breed eats ','"food"',', this event is toggled.');?> <?php print actions_code('"food", "say(%MyName% just ate. [Health: %MyHunger%])"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('If the mother becomes ','"pregnant"',', this event is raised prior to "birth".');?> <?php print actions_code('"pregnant", "say(%MyName% is going to have a baby in %Pregnant%.)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('If a breed gives ','"birth"',', this event is toggled for the mother.');?> <?php print actions_code('"birth", "say(%MyName% just gave birth.)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('If death occurs from age, hunger, or other causes, the ','"dead"',' event is called.');?> <?php print actions_code('"dead", "say(Goodbye, %owner%!)" ');?> </div> </div> </div> <!--How Methods Work--> <div num='3' class='frame-2a' style='display:none;'> <?php print backButton('Go Back',4); ?> <?php print wtheadline('Methods','are used to trigger built-in functions. With each event that is called, you can run dozens of methods for your simulation.'); ?> <div style='padding:20px;'> <div class='entry sub-pad'> <?php print actions_comment('Methods are run in order','', 'from first to last.');?> <?php print actions_code('"start", "say(One) say(Two) say(Three)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('This order continues based on','', 'the methods you use.');?> <?php print actions_code('"start", "say(One) toggle(next) say(Three)", "next", "say(Two)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Now try a more advanced ','', ' event flow.');?> <?php print actions_code('"start", "say(Start) toggle(One|Two|Three) say(End)", "One", "say(%this%)", "Two", "say(%this%)", "Three", "say(%this%)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Now to include filters ','', 'and custom values.');?> <?php print actions_code('"start", "say(%this%) prop(Num,1) toggle(say|next)", "say", "say(%Num%)", "next", "prop(Num,+1) filter(%Num%<3, end) toggle(say|next)", "end", "toggle(say) say(%this%)"');?> </div> </div> </div> <!--Bind Events--> <div num='4' class='frame-2a' style='display:none;'> <?php print backButton('Go Back',5); ?> <?php print wtheadline('Events can be created','for activities such as touch, timer, listen, and a variety of other conditions. Each event is a chance to insert unique functionality.'); ?> <div style='padding:20px;'> <div class='entry sub-pad'> <?php print actions_comment('To repeat actions in regular intervals use a ','timer','event.');?> <?php print actions_code('"start", "bind(timer, 5, actions)", "actions", "prop(Counter,+1) say(This event has triggered %Counter% times.)"');?> <?php print actions_comment('or create a random','timer',' and add random points.');?> <?php print actions_code('"start", "bind(timer, 10r, actions)", "actions", "prop(Bonus, ~10) prop(Points, +%Bonus%) text(Score: %Points%)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Filter results from a','touch','event.');?> <?php print actions_code('"start", "bind(touch, owner, owner actions) bind(touch, notowner, public actions)", "owner actions", "prop(Owner,+1) text(Last Touch: Owner \n Owner: %Owner% \n Public: %Public%)", "public actions", "prop(Public,+1) text(Last Touch: Public \n Owner: %Owner% \n Public: %Public%)"');?> <?php print actions_comment('You can even combine events such as the','touch','event.');?> <?php print actions_code('"start", "prop(extra-info, Click me again!) bind(touch, owner, actions|remove)", "remove", "prop(extra-info)", "actions", "say(Welcome to eco-Breeds Walkthrough! /%extra-info%/)"');?> <?php print actions_comment('Require users to touch and','hold','to trigger the event.');?> <?php print actions_code('"start", "bind(hold, all, give menu)", "give menu", "say(Hello, %toucher%.) menu(%touchkey%, This is a test:, Okay=results)", "results", "say(Goodbye, %chatname%.)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('The breed can also','listen','to local chat.');?> <?php print actions_code('"start", "bind(listen, owner, actions)", "actions", "prop(Counter,+1) text(%owner% spoke %Counter% times.)"');?> <?php print actions_comment('or even','listen','to a specific channel.');?> <?php print actions_code('"start", "bind(listen|2, all, actions)", "actions", "say(%chatname% said \'%chatmsg%\' on channel 2)"');?> <?php print actions_comment('You can also try to','listen','for specific words or phrases.');?> <?php print actions_code('"start", "bind(listen, all, actions)", "actions", "rfilter(%chatmsg%~Whisper, listen-Whisper, %chatmsg%~Shout, listen-Shout) say(Type \'Whisper\' or \'Shout\')", "listen-Whisper", "whisper(Whispering..)", "listen-Shout", "shout(Shouting..)"');?> </div> </div> </div> <!--Action Touch Events--> <div num='5' class='frame-2a' style='display:none;'> <?php print backButton('Go Back',6); ?> <?php print wtheadline('Action Touch Events',' can be created and toggled based on the name or description of the prim touched or it\'s link number; find the action setting \'Touch_Events\' to enable them. This event will trigger all breeds synced with this action object.'); ?> <div style='padding:20px;'> <div class='entry sub-pad'> <?php print actions_comment('Name one of the prims in your action object','"Help"','and click it.');?> <?php print actions_code('"touch-Help", "say(Help touched!)"','Touch_Events = 1;');?> <?php print actions_comment('Set <strong>Touch_Events</strong> to','1','to detect the touched prim\'s name.');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Also try','"Say", "Shout","Whisper"','in the object descriptions and click each one.');?> <?php print actions_code('"touch-Say", "say(%action% touched!)", "touch-Shout", "shout(%action% touched!)", "touch-Whisper", "whisper(%action% touched!)"','Touch_Events = 2;');?> <?php print actions_comment('Set <strong>Touch_Events</strong> to','2','to detect the touched prim\'s description.');?> </div> <div class='entry sub-pad'> <?php print actions_comment('If you want to use the','link number','just try the following.');?> <?php print actions_code('"touch-0", "say(%this%)", "touch-1", "say(%this%)", "touch-2", "say(%this%)", "touch-3", "say(%this%)"','Touch_Events = 3;');?> <?php print actions_comment('Set <strong>Touch_Events</strong> to','3','to detect the touched prim\'s link number.');?> </div> </div> </div> <!--Syncing \ Throttles--> <div num='6' class='frame-2a' style='display:none;'> <?php print backButton('Go Back',7); ?> <?php print wtheadline('Syncing is easy!','Throttles, limits, and filters provide a wide range of tools to allow you to decide how the breeds interact with their actions. Limit the total number of breeds, sync by comparing keywords, and even by matching object descriptions.'); ?> <div style='padding:20px;'> <h3>Add or change these <span class='title inline sub-up'>action.settings</span> values:</h3> <?php print breedSetting( 'Breed_Limit', '-1', 'Limit the number of breeds that can interact with this object.', 'Breed_Limit = 5;', 'Allows access for the first 5 breeds to interact with this object.' ); ?> <?php print breedSetting( 'Breed_Timeout', '60', 'Time in seconds for a breed to respond before allowing other breeds to interact.', 'Breed_Timeout = 300;', 'Breed must send a request to this action object every 5 minutes (300 seconds) from any timed request or lose it\'s position.' ); ?> <?php print breedSetting( 'Desc_Filter', 'null', 'Optional: Ignore breeds that do not have a matching keyword in their object description field. Leave blank to disable this filter. Or use the value "%desc%" to only communicate with breeds that have matching descriptions.', 'Desc_Filter = "Friendly";', 'Now only breed objects with the word "Friendly" in their object description will be able to use this action object.' ); ?> <?php print breedSetting( 'Action_Type', 'null', 'Define each Action Object with a single word or short phrase. Breeds will be limited to one of each type unless blank.', 'Action_Type = "Food";', 'Now breed objects will only be able to communicate with just one action object with this <strong>Action_Type</strong>.' ); ?> <h3>Add or change these <span class='title inline sub-up'>breed.settings</span> values:</h3> <?php print breedSetting( 'Allow_Throttling', 'FALSE', 'TRUE or FALSE : Sync communications with Action Objects?', 'Allow_Throttling = TRUE;', 'Syncing allows you to focus communications with a select range of action objects.' ); ?> <?php print breedSetting( 'Sync_Timeout', '0', 'If action object is removed, set a timeout for breed to look for replacement.', 'Sync_Timeout = 300;', 'If the last response from each action object is older than 5 minutes (300 seconds), expire the connection.' ); ?> <?php print breedSetting( 'Retry_Timeout', '20', 'If all connections fail, retry the connection after this many seconds.', 'Retry_Timeout = 300;', 'If the last failed attempt to connect to an action object is older than 5 minutes (300 seconds), retry the connection.' ); ?> <?php print breedSetting( 'Allowed_Types', 'null', 'Allow types that contain these keywords (may contain expressions)', 'Allowed_Types = [ "Friendly", "Happy" ];', 'Useful for having multiple groups of breeds. <p class="sub-in sit">Assuming you have a <strong>food source</strong> with:</p>'. big_code('Action_Type = "Friendly Food";','action').' <p class="sub-in sit">And a <strong>home object</strong> with: </p>'. big_code('Action_Type = "Happy Home";','action').' <p class="sub-in hang">The breed object will interact with both of the above action objects, but it will ignore types like "Regular Food". However, a breed would eat both foods and use any \'Home\' object if it was configured with:</p>'. big_code('Allowed_Types = [ "Food", "Home" ];','breed').' <p class="sub-in hang">This is very useful for segregating breeds from certain types of action objects.</p>' ); ?> <h3>This value is optional in <span class='title inline sub-up'>both scripts</span>:</h3> <?php print normalSetting( 'Owner_Only', 'TRUE', 'TRUE or FALSE : Only interact with same-owner action-objects?', 'Owner_Only = FALSE;', 'Allows multi-owner objects within the same species to interact.' ); ?> </div> </div> <!--More Bind Events--> <div num='7' class='frame-2a' style='display:none;'> <?php print backButton('Go Back',8); ?> <?php print wtheadline('Bind all the things!','Binding is the easiest way to define even more events for your breeds. Consider the possibilities of the following events:'); ?> <div style='padding:20px;'> <div class='entry sub-pad'> <?php print actions_comment('Check for ','"region"','changes.');?> <?php print actions_code('"start", "bind(region, null, change-event)", "change-event", "message(%ownerkey%, I am now in %region%.)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Detect if breed and owner ','"collide"','.');?> <?php print actions_code('"start", "bind(collide, owner, change-event)", "change-event", "say(%owner% bumped %name%)"');?> <?php print actions_comment('Detect if an object named "Bullet" and breed object ','"collide"','.');?> <?php print actions_code('"start", "bind(collide, Bullet, change-event)", "change-event", "prop(Hits,+1) say(I\'ve been hit %Hits% times.)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Detect if anyone is around using ','"sensor" <span style="font-size:0.75em;color:black;">&</span> "nosensor"','events.');?> <?php print actions_code('"start", "bind(sensor, 10, found) bind(nosensor, 10, not-found)", "found", "text(Someone is near me!)", "not-found", "text(No one is around.)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Detect if owner is ','"online" <span style="font-size:0.75em;color:black;">or</span> "offline"','.');?> <?php print actions_code('"start", "bind(timer, 10, text) bind(online, null, online) bind(offline, null, offline)", "online", "prop(Online,+1) say(%owner% is online)", "offline", "prop(Offline,+1) say(%owner% is offline)", "text", "text(Owner: %owner% \n Logins: %Online% \n Logoffs: %Offline%)"');?> <p class='sub-in sit'>Add or set this value to the <strong>breed.settings</strong> script:</p> <?php print big_code('Globals = [ "Online", 0, "Offline", 0 ];','breed');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Your breeds know when it\'s ','"day" <span style="font-size:0.75em;color:black;">or</span> "night"',' in <strong>"SL"</strong> time or <strong>"RL"</strong> PST time.');?> <?php print actions_code('"start", "bind(timer, 10, text) bind(day, SL, awake) bind(night, SL, sleeping)", "awake", "prop(status, Awake!)", "sleeping", "prop(status, zzZZzz)", "text", "text(Status: %status%)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Trigger a callback when ','"attach" <span style="font-size:0.75em;color:black;">&</span> "detach"','events occur.');?> <?php print actions_code('"start", "bind(touch, owner, come) bind(attach, null, on) bind(detach, null, off)", "come", "move(%ownerpos%,<0,0,0>,walk,normal,arrived)", "arrived", "attach()", "on", "anim(Sitting,10)" , "off", "anim(Sitting,-1)"');?> <p class='sub-in'> Requires an animation called <strong>"Sitting"</strong>.</p> </div> <div class='entry sub-pad'> <?php print actions_comment('You can also trigger a callback when ','"sit" <span style="font-size:0.75em;color:black;">&</span> "unsit"','events occur.');?> <?php print actions_code('"start", "toggle(text) bind(sit, null, sitting) bind(unsit, null, stand)", "text", "text(Sit to ride:)", "sitting", "text() anim(sit) move(%actionpos%,<0,0,0>,walk)", "stand", "toggle(text) anim(sit,-1)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('You can also bind an event for when the breed is ','"moving" <span style="font-size:0.75em;color:black;">&</span> "stopped"','.');?> <?php print actions_code('"start", "text(Unchanged.) bind(moving, null, moved) bind(stopped, null, stop) bind(touch, owner, come)", "come", "move(%ownerpos%, <0,0,0>, walk)", "moved", "text(Moving..)", "stop", "text(Stopped.)"');?> </div> <div class='entry sub-pad'> <?php print actions_comment('Trigger a callback when breed is in ','"water" <span style="font-size:0.75em;color:black;"> or back on </span> "land"','.');?> <?php print actions_code('"start", "bind(water, 1.0, swim) bind(land, 1.0, walk) bind(timer, 5, wander)", "wander", "move(%actionpos%, <5i,5i,0>, %type%)", "moved", "prop(type,walk) toggle(wander)", "stop", "text(Stopped.)"');?> <p class='sub-in sit'>Add or set this value to the <strong>breed.settings</strong> script:</p> <?php print big_code('Globals = [ "type", "walk" ];','breed');?> </div> </div> </div> <!--Extending the Actions List--> <div num='8' class='frame-2a' style='display:none;'> <?php print backButton('Go Back'); ?> <?php print wtheadline('Extend your capabilities','with additional Actions scripts if you run out of room or need a way to organize complex Actions lists.'); ?> <div style='padding:20px;'> <h3>Create a <span class='title inline sub-up'>new script</span> and insert this code:</h3> <?php print normal_code('list Actions = [ ]; e(integer a,string b){integer f=llListFindList(Actions,[b]); string d=llList2String(Actions,f+1);if(a==-201){g(200,"");} else if(a==-202){if(f!=-1){g(201,d);}else{g(243,"");}}}g(integer n,string b){ llMessageLinked(-4,n,b,"");}default{state_entry(){g(205,"");} link_message(integer n,integer a,string b,key c){if(a&lt;200){e(a,b);}}}');?> <p>And now you can <strong>better organize</strong> long Actions lists!</p> </div> </div> </div> <!--Names--> <div num='2b' class='sub-content' style='display:none;'> <div class='frame-2b'> <?php print subButton('2c','Continue to Lifespan'); ?> <?php print wtheadline('Names','can be given automatically or defined by the user later. Names can even be \'earned\' and traded. The "breed name" is the name of the individual and the "object name" is the name of the prim. When changed, breed names can be instantly applied to the object\'s name or description. The following are example uses for breed names:'); ?> <div style='padding:60px;'> <p class='sub-in'><strong>Configure the Name Generator:</strong> <button num='1' class='sub-in-btn'>Try It</button></p> <hr /> <p class='sub-in'><strong>Changing the breed's name:</strong> <button num='2' class='sub-in-btn'>Try It</button></p> </div> </div> <div num='1' class='frame-2b' style='display:none;'> <?php print backButton('Go Back',2); ?> <?php print wtheadline('The Name Generator','automatically creates a unique name when the breed is first created by picking a random prefix, middle, and suffix from a series of lists. If the generator is set for gender specific names, it chooses from either male or female suffixes based on it\'s gender. This name can also be applied to the object\'s name or description for easy identification.'); ?> <div style='padding:20px;'> <h3>Add or change these <span class='title inline sub-up'>breed.settings</span> values:</h3> <?php print breedSetting( 'Name_Generator', 'TRUE', 'TRUE or FALSE : Enable/Disable name generator?', 'Name_Generator = FALSE;', 'The name generator is now disabled.' ); ?> <?php print breedSetting( 'Gender_Specific', 'TRUE', 'TRUE or FALSE : Create gender specific names?', 'Gender_Specific = FALSE;', 'Names will be created randomly, instead of based on gender.' ); ?> <?php print breedSetting( 'Set_Object', 'null', 'When the breed name is changed or reset, the name can be inserted into the object\'s name or description field. Use the %name% or %desc% expression to insert the breed\'s name into the string. Assuming the breed\'s name is "Ralph":', 'Set_Object = "eco-%name%";', 'The object\'s name will now be labeled: eco-Ralph', 'Set_Object = "eco-%desc%";', 'The object\'s description will now be labeled: eco-Ralph' ); ?> </div> </div> <div num='2' class='frame-2b' style='display:none;'> <?php print backButton('Go Back'); ?> <?php print wtheadline('Changing the name','can be enabled for your users at any time. This would require a user interaction such as a chat command, a feature in a menu system, or even by rezzable objects.'); ?> <div style='padding:20px;'> <div class='entry expand sub-pad'> <?php print videolink('Set the breed name using an <strong style="font-size:1.1em;">input menu</strong>', 'ChJVUTm1Kko');?> <?php print actions_code('"start", "bind(touch, owner, input_menu)", "input_menu", "textbox(%ownerkey%, \nSet name and click \'Send\':, set_name)", "set_name", "val(MyName,%chatmsg%) say(My name is now %MyName%)"');?> </div> <div class='entry expand sub-pad'> <?php print videolink('Set the breed name using an <strong style="font-size:1.1em;">chat commands</strong>', 'ChJVUTm1Kko');?> <?php print actions_code('"start", "bind(touch, owner, start_listen)", "start_listen", "say(Type new name in chat:) bind(listen, owner, listen_name, remove_listen)", "listen_name", "unbind(remove_listen) val(MyName,%chatmsg%) say(My name is now %MyName%)"');?> </div> <div class='entry expand sub-pad'> <?php print videolink('Set the breed name using an <strong style="font-size:1.1em;">rezzable objects</strong>', 'ChJVUTm1Kko');?> <?php print actions_code('"start", "bind(touch, owner, set_name)", "set_name", "val(MyName, Roger) say(My name is now %MyName%) @destroy()"');?> <p class='sub-in'>The rezzable objects example requires <strong style='font-size:1.1em;'>the <tag class='bool'>@destroy()</tag> extension:</strong></p> <?php print normal_code('_extend(string function, string attributes){ if(function=="@destroy"){ llDie();llRemoveInventory("action-comm"); } } default{ link_message(integer a, integer b, string c, key d){ if(b==-220){_extend(c,(string)d);} } }');?> </div> </div> </div> </div> <!--Lifespan--> <div num='2c' class='sub-content' style='display:none;'> <div class='frame-2c'> <?php print subButton('2d','Continue to Growth'); ?> <?php print wtheadline('Lifespan','refers to life, the ageing process, and death for the breeds. Age can be used to affect functionality and even physical appearance.'); ?> <div style='padding:20px;'> <p class='sub-in'><strong>The Ageing Process:</strong> <button num='1' class='sub-in-btn'>Try It</button></p> <hr /> <p class='sub-in'><strong>Reviving a Dead Breed:</strong> <button num='2' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>Ageing Physical Features:</strong> <button num='3' class='sub-in-btn'>Try It</button></p> </div> </div> <div num='1' class='frame-2c' style='display:none;'> <?php print backButton('Go Back',2); ?> <?php print wtheadline('The breed object\'s age','is determined by user-defined \'years\'. The lifespan cycle occurs every \'year\' and is checked every 60 seconds to determine if the cycle has expired. If multiple \'years\' have passed since the last time it was checked, the breed will age accordingly.'); ?> <div style='padding:20px;'> <h3>Add or change these <span class='title inline sub-up'>breed.settings</span> values:</h3> <p><strong>STEP 1: </strong><em>Set the speed of <span style='font-size:1.3em;'>life</span> for your breed.</em></p> <?php print breedSetting( 'Lifespan', 'TRUE', 'TRUE or FALSE : Enable ageing?', 'Lifespan = FALSE;', 'Disables ageing.' ); ?> <?php print breedSetting( 'Year', '1440', 'Length of a year in minutes.', 'Year = 43000;', 'Sets length of year to one month (30 days)' ); ?> <?php print breedSetting( 'Age_Start', '0', 'Starting age when created/born.', 'Age_Start = 100;', 'Breeds are born at 100 years old.' ); ?> <p><strong>STEP 2: </strong>Define the odds of <span style='font-size:1.3em;'>death</span> once the breed is within the min and max age.</p> <?php print breedSetting( 'Age_Min', '15', 'Minimum age before death from old age can occur.', 'Age_Min = 0;', 'Allows death to occur time of birth; requires Survival_Odds to be set.' ); ?> <?php print breedSetting( 'Age_Max', '-1', 'Minimum age before death from old age can occur.', 'Age_Max = 20;', 'Breed will only live to age 20.' ); ?> <?php print breedSetting( 'Survival_Odds', '-1', 'Odds of death within min/max age : 0 = Instant Death or -1 = No Death', 'Survival_Odds = 1;', 'Breed has a 50% chance of death with each age cycle.' ); ?> <p>Now your breed is set to <span style='font-size:1.3em;'>age</span>!</p> </div> </div> <div num='2' class='frame-2c' style='display:none;'> <?php print backButton('Go Back',3); ?> <?php print wtheadline('Death','occurs from old age, hunger, or can be triggered by a user-defined event.'); ?> <div style='padding:0 20px;'> <?php print videolink('Use revive() to bring a breed back to life', 'YgsQR2AfFSA');?> <?php print method_profile( 'revive', '[ years [ , hunger ] ]', array( 'years','additional "years" to add to it\'s min/max age', 'hunger', 'Set MyHunger level (0-100).' ), actions_code('"start", "revive(10,50)"'), 'This revives the breed with 10 additional years and a starting hunger of 50.' );?> <h3 align='center'>Revival Tool</h3> <?php print actions_code('// Revival Tool "start", "bind(touch,owner,revive,remove_revive)", "revive", "say(Added 1 Year to %MyName%\'s Lifespan) unbind(remove_revive) revive(1) @destroy()"');?> <?php print normal_code('// Revival Tool (Extension Script) _extend(string function, string attributes){ if(function=="@destroy"){ llDie(); } } default{ link_message(integer a, integer b, string c, key d){if(b==-220){_extend(c,(string)d);}} }');?> <hr /> <h3 align='center'>Home Object</h3> <?php print actions_code('// Home Object "start", "bind(timer,7,text_stats)", "text_stats", "filter(%Dead%=false,dead_stats) val(Text_Color,<0.3, 0.9, 0.5>) text(Name: %MyName% \n Age: %MyAge% \n Gender: %MyGender% \n Skin: %Body%)", "dead_stats", "val(Text_Color,<1,0.2,0.2>) text(DEAD \n Name: %MyName% \n Gender: %MyGender% \n Skin: %Body%)"');?> </div> </div> <div num='3' class='frame-2c' style='display:none;'> <?php print backButton('Go Back'); ?> <?php print wtheadline('Age shows character',' and is demonstrated by visual growth. This snippet shows how easy it is to apply visual features to breeds based on age:'); ?> <div style='padding:0 20px;'> <?php print videolink('Ageing features', 'kRoyw_j-7cA');?> <p class='sub-in'>When the breed ages and grows, this video shows you how to set age-based physical features for your breed.</p> <?php print actions_code('"start", "text(Age: %MyAge%) cache(Child,Teen,Adult) bind(timer,10,age_check)", "age_check", "text(Age: %MyAge%) filter(%MyAge%=1,not1) set(Child) uncache(Child)", "not1", "filter(%MyAge%=2,not2) set(Teen) uncache(Teen)", "not2", "filter(%MyAge%=3) set(Adult) uncache(Adult)"');?> </div> </div> </div> <!--Growth--> <div num='2d' class='sub-content' style='display:none;'> <div class='frame-2d'> <?php print subButton('2e','Continue to Appetite'); ?> <?php print wtheadline('Growth',' is the re-sizing and re-positioning of all prims in a linkset. The difference is applied to animations, rebuilt breeds, as well as sit and camera positions. Once growth has completed it\'s last stage, the growth timer deactivates and the object remains a static size unless re-enabled. <strong>Growth is disabled by default.</strong>'); ?> <div style='padding:20px;'> <p class='sub-in'><strong>Establish a Growth Sequence:</strong> <button num='1' class='sub-in-btn'>Try It</button></p> <hr /> <p class='sub-in'><strong>Hungry Breeds have Stunted Growth:</strong> <button num='2' class='sub-in-btn'>Try It</button></p> </div> </div> <div num='1' class='frame-2d' style='display:none;'> <?php print backButton('Go Back',2); ?> <?php print wtheadline('Establish a growth cycle','by plugging in the following values.'); ?> <div style='padding:20px;'> <h3>Add or change these <span class='title inline sub-up'>breed.settings</span> values:</h3> <?php print breedSetting( 'Growth_Stages', '0', 'How many growth stages?', 'Growth_Stages = 10;', 'The breed with have 10 growth stages throughout it\'s life.' ); ?> <?php print breedSetting( 'Growth_Scale', '1.05', 'This value must be greater than \'1.0\' for increasing the size, where 1.0 equals 100% of current size and 1.2 equals 120% of current size. This value can also be less than 1.0 for objects that shrink throughout it\'s lifespan', 'Growth_Scale = 1.5;', 'The breed will now grow 1.5x it\'s current size every cycle.' ); ?> <?php print breedSetting( 'Growth_Timescale', '1440', 'Length of time in minutes between each growth cycle.', 'Growth_Timescale = 720;', 'Growth would occur every 12 hours (720 minutes).' ); ?> </div> </div> <div num='2' class='frame-2d' style='display:none;'> <?php print backButton('Go Back'); ?> <?php print wtheadline('Stunted growth','can be set to randomly occur using the "Growth_Odds" setting, you can also inhibit growth based on other breed conditions, such as the built in hunger level.'); ?> <div style='padding:20px;'> <h3>Add or change these <span class='title inline sub-up'>breed.settings</span> values:</h3> <?php print breedSetting( 'Growth_Odds', '0', 'This value defines the odds of skipping a growth cycle. If a cycle is skipped, a growth stage is subtracted and no growth occurs. Set this value to \'0\' to never skip a growth stage. The higher the number, the more likely the growth stage will be skipped.', 'Growth_Odds = 1;', 'There is now a 50% chance of stunted growth.' ); ?> <h3>Or use the <span class='title inline sub-up'>filter method</span> to detect hunger:</h3> <?php print actions_code('"start", "bind(timer, 600, check-hunger)", "check-hunger", "filter(%MyHunger%<20) prop(Growth, %Growth_Stages%) filter(%Growth%>0) prop(Growth, -1) val(Growth_Stages,%Growth%)"');?> <p class='sub-in'>This method allows us to inhibit growth by reducing the remaining Growth_Stages value over time. Not as a random occurance, but as a result of poor nutrition.</p> </div> </div> </div> <!--Hunger--> <div num='2e' class='sub-content' style='display:none;'> <div class='frame-2e'> <?php print subButton('2f','Continue to Breeding'); ?> <?php print wtheadline('The hunger level',' is part of the built-in point system. Food consumption is precise and secure with built in logic to handle multiple food sources. <strong>Hunger is disabled by default.</strong>'); ?> <div style='padding:20px;'> <p class='sub-in'><strong>Setting up the appetite:</strong> <button num='1' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>Creating a food source:</strong> <button num='2' class='sub-in-btn'>Try It</button></p> <hr /> <p class='sub-in'><strong>Growing Plants as a Food Source:</strong> <button num='3' class='sub-in-btn'>Try It</button></p> </div> </div> <div num='1' class='frame-2e' style='display:none;'> <?php print backButton('Go Back',2); ?> <?php print wtheadline('A breed\'s appetite',' can range from predictable to finicky. Every hunger cycle, hunger points are lost to simulate a progressive appetite. Make sure the amount lost due to digestion is less than the minimum amount consumed.'); ?> <div style='padding:20px;'> <h3>Add or change these <span class='title inline sub-up'>breed.settings</span> values:</h3> <?php print breedSetting( 'Hunger_Timescale', '0', '0 = Disabled : How often to check for food.', 'Hunger_Timescale = 480;', 'The hunger cycle would occur 3 times a day (every 480 minutes).' ); ?> <?php print breedSetting( 'Hunger_Start', '40', 'Hunger level when first born/created.', 'Hunger_Start = 0;', 'Breed is born hungry.', 'Hunger_Start = 100;', 'Breed will not need food when first born/created.' ); ?> <?php print breedSetting( 'Hunger_Odds', '0', 'Odds of eating : 0 = Always Eat', 'Hunger_Odds = 1;', 'The higher the number, the less likely it will eat.' ); ?> <?php print breedSetting( 'Hunger_Min', '1', 'Minimum food units consumed per cycle.', 'Hunger_Min = 5;', 'Breed will consume at least 5 food units per serving.' ); ?> <?php print breedSetting( 'Hunger_Max', '5', 'Maximum food units consumed per cycle.', 'Hunger_Max = 10;', 'Breed will consume up to 10 food units per serving.' ); ?> <hr /> <?php print breedSetting( 'Hunger_Lost', '1', 'Hunger points lost each hunger cycle.', 'Hunger_Lost = 5;', 'The MyHunger level will be reduced by 5 points every cycle.' ); ?> <?php print breedSetting( 'Starvation_Threshold', '10', 'Hunger death threshold.', 'Starvation_Threshold = 0;', 'Hunger levels must not be at zero for death to occur.' ); ?> <?php print breedSetting( 'Starvation_Odds', '-1', 'Odds of death when below starvation threshold : 0 = Always Die | -1 = Never Die', 'Starvation_Odds = 0;', 'Always dies when below starvation threshold.' ); ?> </div> </div> <div num='2' class='frame-2e' style='display:none;'> <?php print backButton('Go Back',3); ?> <?php print wtheadline('A food source',' is created by defining food quality and levels in an action object:'); ?> <div style='padding:20px;'> <?php print actionSetting( 'Food_Level', '0', '0 = None | -1 = Unlimited Food : Units of food.', 'Food_Level = 10;', 'Food source with 10 units available.' ); ?> <?php print actionSetting( 'Food_Quality', '5', 'How many points each food unit is worth.', 'Food_Quality = 1;', 'Each food unit is worth 1 point.' ); ?> </div> </div> <div num='3' class='frame-2e' style='display:none;'> <?php print backButton('Go Back'); ?> <?php print wtheadline('Growing food','is an alternative to store bought foods. In this simulation, corn seed is planted and the stalks grow until it reaches maturity and produces corn. The corn is then harvested to supply a food trough for the goat. A watering can is used to keep the gardens watered, otherwise the corn turns brown and dies:'); ?> <div style='padding:20px;'> <?php print videolink('Growing Plants as a Food Source', 'qGmjxFwbl60');?> <?php print listItem('The corn <strong>seed</strong>.', 'A Breed object w/ growth and hunger enabled.'); ?> <?php print listItem('Plant bed (<strong>dirt</strong>).', 'Action object with food enabled; "Food Level" script, "Plant Bed" actions.'); ?> <?php print toggle_example('Plant Bed Water Level (extension)',normal_code('integer Extension_Channel = -999666; integer Water_Channel = -666999; _extend(string function, string attributes){ if(function=="@foodlevel"){ if((integer)attributes>90){llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.15, 4.456, 3.298>]);} else if((integer)attributes>80){llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.13, 4.456, 3.298>]);} else if((integer)attributes>70){llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.11, 4.456, 3.298>]);} else if((integer)attributes>60){llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.09, 4.456, 3.298>]);} else if((integer)attributes>50){llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.07, 4.456, 3.298>]);} else if((integer)attributes>40){llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.05, 4.456, 3.298>]);} else if((integer)attributes>30){llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.03, 4.456, 3.298>]);} else if((integer)attributes>20){llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.02, 4.456, 3.298>]);} else{llSetLinkPrimitiveParamsFast(0,[PRIM_SIZE, <0.010, 4.456, 3.298>]);} } if(function=="@fillTrough"){ llRegionSay(Extension_Channel,"harvest"); } } toggle(string class){_link(211,class);} _link(integer n, string str){llMessageLinked(LINK_THIS, n, str, "");} food_level(integer amt){_link(221,(string)amt);} default{ on_rez(integer n){llResetScript();} state_entry(){llListen(Water_Channel,"",llGetOwner(),"");} link_message(integer a, integer b, string c, key d){if(b==-220){_extend(c,(string)d);}} listen(integer ch, string name, key id, string msg){if(msg=="water"){food_level(10);}} }'),'script'); ?> <?php print toggle_example('Plant Bed Actions',actions_code('"start", "filter(%Dead%=false) bind(timer,20,text_stats) toggle(text_stats)", "text_stats", "val(Text_Color,<0.3, 0.9, 0.5>) text(/%harvest% \n/Name: %MyName% \n Age: %MyAge% \n Healthiness: %MyHunger%) filter(%MyAge%>5) prop(harvest,Ready for Harvest) bind(touch,owner,harvest,null,%actionid%)", "dead", "unbind() val(Text_Color,<1,0,0>) text(DEAD)", "harvest", "filter(%MyAge%>5,null,%Dead%=false) unbind() @fillTrough() pause(1) die()"'),'actions'); ?> <?php print listItem('A <strong>package</strong> to sell young corn seeds.', 'Contains: "Seed Package" script and seeds.'); ?> <?php print toggle_example('Seed Package',normal_code('string seed = "Corn"; default{ state_entry(){ llSetText("Touch to plant seed",<0.3, 0.9, 0.5>,1); } touch_start(integer n){ if(llDetectedKey(0)!=llGetOwner()){return;} rotation rot = llEuler2Rot(<0,0,125>*DEG_TO_RAD); llRezObject(seed,llGetPos()+<.25,.25,-.25>,ZERO_VECTOR,rot,0); llRezObject(seed,llGetPos()+<-.25,.25,-.25>,ZERO_VECTOR,rot,0); llRezObject(seed,llGetPos()+<.25,-.25,-.25>,ZERO_VECTOR,rot,0); llRezObject(seed,llGetPos()+<-.25,-.25,-.25>,ZERO_VECTOR,rot,0); llRemoveInventory(seed);//if object is NO COPY, remove this line llDie(); } }'),'script'); ?> <?php print listItem('Create a <strong>watering can</strong>', 'Contains: "Watering Can" script only.'); ?> <?php print toggle_example('Watering Can',normal_code('integer Water_Channel = -666999; default{ touch_start(integer total_number){ if(llGetOwner()==llDetectedKey(0)){ llRegionSay(Water_Channel,"water"); llSleep(10); } } } '),'script'); ?> <?php print listItem('A <strong>goat</strong>.', 'A Breed object w/ growth and hunger enabled.'); ?> <?php print listItem('A <strong>food trough</strong> for the goat.', 'Action object with food enabled: "Food Trough" script and actions.'); ?> <?php print toggle_example('Food Trough Show Corn (extension)',normal_code('integer Extension_Channel = -362223; _extend(string function, string attributes){ if(function=="@foodlevel"){ list prims = [1,18]; if((integer)attributes>90){prims = [1,18,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,2];} else if((integer)attributes>80){prims = [1,18,5,6,7,8,9,10,11,12,13,14,15,16,17,2];} else if((integer)attributes>70){prims = [1,18,7,8,9,10,11,12,13,14,15,16,17,2];} else if((integer)attributes>60){prims = [1,18,9,10,11,12,13,14,15,16,17,2];} else if((integer)attributes>50){prims = [1,18,11,12,13,14,15,16,17,2];} else if((integer)attributes>40){prims = [1,18,13,14,15,16,17,2];} else if((integer)attributes>30){prims = [1,18,15,16,17,2];} else if((integer)attributes>20){prims = [1,18,17,2];} else if((integer)attributes>10){prims = [1,18,2];} integer i; for(i=0;i<llGetNumberOfPrims();i++){ if(llListFindList(prims,[i])==-1){llSetLinkAlpha(i,0,-1);} else{llSetLinkAlpha(i,1,-1);} } } } toggle(string class){_link(211,class);} _link(integer n, string str){llMessageLinked(LINK_THIS, n, str, "");} food_level(integer amt){_link(221,(string)amt);} default{ state_entry(){llListen(Extension_Channel,"","","");} listen(integer ch, string name, key id, string msg){food_level(10);toggle("setLevel");} link_message(integer a, integer b, string c, key d){if(b==-220){_extend(c,(string)d);}} }'),'script'); ?> <?php print toggle_example('Food Trough Actions',actions_code('"start", "@foodlevel(%Food_Level%)", "food", "@foodlevel(%Food_Level%)", "setLevel", "@foodlevel(%Food_Level%)"'),'actions'); ?> </div> </div> </div> <!--Breeding--> <div num='2f' class='sub-content' style='display:none;'> <div class='frame-2f'> <?php print subButton('2g','Continue to Rebuilding'); ?> <?php print wtheadline('Breeding','is the act of mating and/or producing offspring where parents pass on unique information such as skin preferences or other traits to their offspring, thus creating a unique lineage. <strong>Breeding is disabled by default.</strong>'); ?> <div style='padding:20px;'> <p class='sub-in'><strong>Explore the breeding behaviors:</strong> <button num='1' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>Produce offspring from a nest object:</strong> <button num='2' class='sub-in-btn'>Try It</button></p> <hr /> <p class='sub-in'><?php print premium_stamp(); ?><strong>Setting up the eco-crate:</strong> <button num='3' class='sub-in-btn'>Try It</button></p> <p class='sub-in'><strong>Hatching from an egg:</strong> <button num='4' class='sub-in-btn'>Try It</button></p> </div> </div> <div num='1' class='frame-2f' style='display:none;'> <?php print backButton('Go Back',2); ?> <?php print wtheadline('Partnership, sexuality, and pregnancy','are individually configured to define the overall breeding behavior of your species.'); ?> <div style = 'padding:20px;'> <h2 align='center'>Genders</h2> <?php print breedSetting( 'Genders', 'TRUE', 'TRUE or FALSE : Establish two genders?', 'Genders = FALSE;', 'Now breeds are unisex.' ); ?> <?php print breedSetting( 'Gender_Ratio', '1', 'Ratio of gender selection upon creation. Where 1 is a 1:1 gender ratio, higher positive numbers create a higher male population and higher negative numbers create a higher female population.', 'Gender_Ratio = 0; // always female // or Gender_Ratio = -1; // always male', 'Always male or always female. Useful for \'Starter Kits\'.', 'Gender_Ratio = -5; //1 in 5 births are male. // or Gender_Ratio = 5; //1 in 5 births are female', 'This is how to set rare genders.' ); ?> <hr /> <h2 align='center'>Partners</h2> <?php print breedSetting( 'Require_Partners', 'TRUE', 'TRUE or FALSE : Require partners to breed?', 'Require_Partners = FALSE;', 'The breed is now asexual and self replicates.' ); ?> <?php print breedSetting( 'Unique_Partner', 'TRUE', 'TRUE or FALSE : Disallow breeding among siblings and parents?', 'Unique_Partner = FALSE;', 'Allow incest.' ); ?> <?php print breedSetting( 'Keep_Partners', 'TRUE', 'TRUE or FALSE : Keep the same partners each breeding cycle?', 'Keep_Partners = FALSE;', 'Disables monogamy.' ); ?> <?php print breedSetting( 'Partner_Timeout', '0', 'How many breeding cycles without a partner before looking for new partner?', 'Partner_Timeout = 2;', 'If just one is skipped, the breed will look for new partner. Setting to 1 is not recommended.' ); ?> <hr /> <h2 align='center'>Breed Cycle</h2> <?php print breedSetting( 'Breed_Time', '0', 'How often to look for a mate in minutes : 0 = Disabled', 'Breed_Time = 1440;', 'Breed looks for a mate or breeds every day (1440 minutes).' ); ?> <?php print breedSetting( 'Breed_Age_Min', '0', ' Minimum age for breeding to occur.', 'Breed_Age_Min = 18;', 'Will not breed until 18 years old.' ); ?> <?php print breedSetting( 'Breed_Age_Max', '-1', 'Maximum breeding age : -1 = Always Breeds', 'Breed_Age_Max = 40;', 'Will stop breeding after 40 years old.' ); ?> <hr /> <h2 align='center'>Pregnancy</h2> <?php print breedSetting( 'Pregnancy_Timeout', '0', 'Time in minutes between breeding and birth : 0 = Instant Birth', 'Pregnancy_Timeout = 10000;', 'Gives birth 1 week (10,000 minutes) after breeding.' ); ?> <?php print breedSetting( 'Litter_Min', '1', 'Minimum number of breeds in each litter.', 'Litter_Min = 5;', 'Always at least 5 offspring in every birth sequence.' ); ?> <?php print breedSetting( 'Litter_Max', '3', 'Maximum number of breeds in each litter.', 'Litter_Min = 1; Litter_Max = 1;', 'With both limits set to 1, only one breed will be born each birth sequence.' ); ?> <?php print breedSetting( 'Litter_Rare', 'FALSE', 'TRUE or FALSE : Larger litters are more rare?', 'Litter_Rare = TRUE;', 'Higher number of litters less likely.' ); ?> <?php print breedSetting( 'Litters', '-1', 'Total number of litters a breed can have over a lifespan : -1 = Unlimited', 'Litters = 5;', 'Breeds stop giving birth after five successful birth sequences.' ); ?> <?php print breedSetting( 'Breed_Failed_Odds', '0', 'Odds of failed birth : 0 = No Failed Births', 'Breed_Failed_Odds = 1;', 'This sets failed births to 50%.' ); ?> </div> </div> <div num='2' class='frame-2f' style='display:none;'> <?php print backButton('Go Back',3); ?> <?php print wtheadline('Now that you have configured your breeds',' to mate, configure the offspring to be created. Offspring are born directly from action objects. The child object must be installed in the action object and be properly configured for the breeding sequence to be successful.'); ?> <div style='padding:20px;'> <h3>Set this value for the <span class='title inline sub-up'>child</span> breed:</h3> <?php print big_code('Activation_Param = 0;','breed');?> <p class='sub-in hang'>Activates when rezzed as a child <strong>from an action object.</strong></p> <h3 class='hang'>...and for the <span class='title inline sub-up'>parent</span> breeds:</h3> <?php print big_code('Activation_Param = 1;','breed');?> <p class='sub-in hang'>Activates when first rezzed <strong>by the next owner.</strong></p> </div> <div style='padding:20px;'> <h2 align='center'>Breeding Options</h2> <?php print actionSetting( 'Allow_Breeding', 'FALSE', 'TRUE or FALSE : Allow this object to be used as a breeding source.', 'Allow_Breeding = TRUE;', 'Enable breeding for this action object.' ); ?> <?php print actionSetting( 'Limit_Rezzed', '-1', 'Limit the total number of breeds that can be created : -1 = Unlimited', 'Limit_Rezzed = 5;', 'Only 5 breeds will be allowed to be created.' ); ?> <?php print actionSetting( 'Breed_Maxed_Die', 'FALSE', 'TRUE or FALSE : Destroy this object when \'Limit_Rezzed\' reaches zero?', 'Breed_Maxed_Die = TRUE;', 'Action object dies when \'Limit_Rezzed\' reaches zero.' ); ?> <hr /> <h2 align='center'>Child Object Options</h2> <?php print actionSetting( 'Breed_Any_Object', 'TRUE', 'TRUE or FALSE : Rez any object in contents as offspring?', 'Breed_Any_Object = FALSE; Breed_Object="child";', 'Now requires an object named "child".' ); ?> <?php print actionSetting( 'Breed_Object', 'null', 'The name of object to be rezzed from contents.', 'Breed_Object="child"; Breed_Any_Object = FALSE;', 'Now requires an object named "child".' ); ?> <hr /> <h2 align='center'>Limited-Use Filters</h2> <?php print actionSetting( 'Breed_One_Family', 'FALSE', 'TRUE or FALSE : Allow only one breeding pair?', 'Breed_One_Family = TRUE;', 'Only one breeding pair can use this as a breeding source.' ); ?> <?php print actionSetting( 'Reserve_Breeding', 'FALSE', 'TRUE or FALSE : Allow breeding to occur by extension only?', 'Reserve_Breeding = TRUE;', 'Disables breeding but reserves it for use with extension scripts.' ); ?> </div> </div> <div num='3' class='frame-2f' style='display:none;'> <?php print backButton('Go Back',4); ?> <?php print wtheadline('The eco-crate','is an OPTIONAL add-on for the eco-breed project. This tutorial shows you how to set up crates and explains the many uses of the crate system. '); ?> <div style='padding:20px;'> <?php print videolink('SETTING UP THE ECO-CRATE (11:26)', 'mjV_Cm-Dycs');?> <div align='center'> <p><a href="https://marketplace.secondlife.com/p/eco/2999424" target="_blank">Get this Premium Extension!</a></p> <img style='height:200px;' src='img/eco-crate.png' /> </div> </div> </div> <div num='4' class='frame-2f' style='display:none;'> <?php print backButton('Go Back'); ?> <?php print wtheadline('Hatch your breed',' from an egg. You can use this example to have a more advanced birth sequence. Breeds will display stats but will not age, grow, get hungry, or breed until \'hatched\'.'); ?> <div style='padding:20px;'> <?php print videolink('STARTING FROM AN EGG (9:40)', 'xPd12IWLJv0');?> <h4 align='center'>Please watch the video before continuing.</h4> <?php print actions_code('"start", "filter(!%BORN%) cache(Hatched) text(Name: %MyName% \n Gender: %MyGender%) bind(timer,20,hatch,remove_hatch)", "hatch", "unbind(remove_hatch) text(Hatching..) set(Hatched) uncache(Hatched) prop(BORN,true) val(Lifespan,1) bind(timer,15,text_stats)", "text_stats", "text(Name: %MyName% \n Age: %MyAge% \n Gender: %MyGender%)"');?> <p class='sub-in hang'>This example requires an animation named <strong>"Hatched"</strong> to be created. This simulation <strong>enables Lifespan</strong> after the timer expires and sets the "Hatched" animations, essentially shrinking the 'Egg' prim.</p> </div> </div> </div> <!--Rebuild--> <div num='2g' class='sub-content' style='display:none;'> <div class='frame-2g'> <?php print pageButton('e-howto3','Continue to Prim Methods'); ?> <?php print wtheadline('Rebuilding breeds','that are lost/missing is vital for maintaining the value of individuals. All of the values that make a breed a unique individual are hosted externally. This enables users to recreate existing breeds with all core values appropriately adjusted. If an older copy of that breed attempts to re-activate, it will automatically delete (destroy) itself.'); ?> <div style='padding:20px;'> <p class='sub-in'><strong>How to enable rebuilding:</strong> <button num='1' class='sub-in-btn'>Try It</button></p> <hr /> <p class='sub-in'><strong>Re-defining the rebuild menu:</strong> <button num='2' class='sub-in-btn'>Try It</button></p> </div> </div> <div num='1' class='frame-2g' style='display:none;'> <?php print backButton('Go Back',2); ?> <?php print wtheadline('Rebuilding is easy!','Any breed with Save_Records = TRUE is able to be rebuilt from an action object. Follow these few steps to get set up:'); ?> <div style='padding:20px;'> <?php print listItem('Configure the child object', 'This breed object will be rezzed from the action object and used to recreate an existing breed.'); ?> <?php print breedSetting( 'Activation_Param', '1', 'The activation param indicates how the breed is activated : 0 = child and 1 = parent', 'Activation_Param = 0;', 'Can now be used to recreate other breeds.' ); ?> <?php print listItem('Install the child breed into an action object', 'Put the breed object you just configured into the contents of an action o bject.'); ?> <?php print listItem('Enable rebuilding', 'Turn it on with just one configuration.'); ?> <?php print actionSetting( 'Allow_Rebuild', 'FALSE', 'FALSE = Disable | TRUE = Enable | 2 = Extensions Only', 'Allow_Rebuild = TRUE;', 'Rebuilding is now enabled.' ); ?> <?php print listItem('OPTIONAL: Designate the name of the child object', 'Use the following configuration to assign which object to use as child.'); ?> <?php print actionSetting( 'Rebuild_Object', 'null', 'Name of object to be rezzed : "Rebuild_Any_Object" must be FALSE', 'Rebuild_Object = "Object";', 'Rezzes "Object" as child when rebuilding is triggered.' ); ?> </div> </div> <div num='2' class='frame-2g' style='display:none;'> <?php print backButton('Go Back'); ?> <?php print wtheadline('The rebuild menu','is highly configurable! Define what type of breeds can be rebuilt and supply custom messages.'); ?> <div style='padding:20px;'> <?php print actionSetting( 'Breed_Max', '10', 'How many breeds to provide rebuild support for : 200 = Max', 'Breed_Max = 30;', 'The rebuild menu will show up to 30 breed names ' ); ?> <h3>Decide <strong>what type</strong> of breed can be rebuilt.</h3> <?php print actionSetting( 'Status', '1', 'Use this value to filter breeds by status:<br> 0 = Active Breeds | 1 = Inactive Breeds | 2 = All Breeds', 'Status = 2;', 'All breeds owned by same owner will appear in the rebuild menu. Useful for updating customers with new scripts or configurations by allowing them to rebuild any of their breeds regardless of status (with the exception of the \'Dead_Breeds\' setting).' ); ?> <?php print actionSetting( 'Dead_Breeds', '0', 'Use this value to filter out dead breeds:<br>0 = Not Dead | 1 = All Breeds | 2 = Dead Breeds', 'Dead_Breeds = 2;', 'This example allows only dead breeds to be rebuilt.' ); ?> <h3>Now to define <strong>the menu</strong> buttons and messages.</h3> <?php print actionSetting( 'Touch_Length', '2', 'Time in seconds a user must touch and hold to trigger menu.', 'Touch_Length = 0;', 'Menu appears instantly when clicked.' ); ?> <?php print actionSetting( 'Message', '"\nSelect a breed:"', 'Message in the breed selection menu.', '', '' ); ?> <?php print actionSetting( 'Button_Next', '"NEXT >"', 'Define the \'NEXT\' button.', '', '' ); ?> <?php print actionSetting( 'Button_Prev', '"< PREV"', 'Define the \'PREV\' button.', '', '' ); ?> <?php print actionSetting( 'Confirm_Message', '"\nAre you sure?"', 'Message in the confirmation popup.', '', '' ); ?> <?php print actionSetting( 'Button_Confirm', '"Yes"', 'Define the \'CONFIRM\' button.', '', '' ); ?> <?php print actionSetting( 'Button_Cancel', '"Cancel"', 'Define the \'CANCEL\' button.', '', '' ); ?> </div> </div> </div>
mit
jocode/android-remind
12-fragment-staticos/app/src/main/java/com/example/a12_fragment_staticos/One.java
3552
package com.example.a12_fragment_staticos; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link One.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link One#newInstance} factory method to * create an instance of this fragment. */ public class One extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public One() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment One. */ // TODO: Rename and change types and number of parameters public static One newInstance(String param1, String param2) { One fragment = new One(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_one, container, false); } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
mit
t-recx/Rothko
Rothko/Interfaces/Components/IRangeable.cs
166
using System; namespace Rothko.Interfaces.Components { public interface IRangeable { int RangePoints { get; set; } int DeadZoneRangePoints { get; set; } } }
mit
ryfeus/lambda-packs
HDF4_H5_NETCDF/source2.7/pyhdf/test_SD.py
752
#!/usr/bin/env python import numpy as np import os import pyhdf.SD import tempfile from nose.tools import eq_ from pyhdf.SD import SDC def test_long_varname(): sds_name = 'a'*255 _, path = tempfile.mkstemp(suffix='.hdf', prefix='pyhdf_') try: # create a file with a long variable name sd = pyhdf.SD.SD(path, SDC.WRITE|SDC.CREATE|SDC.TRUNC) sds = sd.create(sds_name, SDC.FLOAT32, (3,)) sds[:] = range(10, 13) sds.endaccess() sd.end() # check we can read the variable name sd = pyhdf.SD.SD(path) sds = sd.select(sds_name) name, _, _, _, _ = sds.info() sds.endaccess() sd.end() eq_(sds_name, name) finally: os.unlink(path)
mit
JuanKRuiz/Estrategias-de-Codigo-Portable
WinPhoneAppT/Properties/AssemblyInfo.cs
1439
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WinPhoneAppT")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WinPhoneAppT")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d2a62a1b-7581-46d0-afb6-ba2c1b73c335")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
mit
voanna/Deep-Features-or-Not
experiments/finetune-temperature/generic_regression/launch_caffe.py
2787
# 'source /home/voanna/TimePrediction/src/bash/gpu_caffe_env_variables ') import os import time_to_label import glob import math import numpy as np import scipy.io np.random.seed(6) CAFFE_PATH = '/home/voanna/caffe_gpu' CAFFE_MODEL = 'VGG_ILSVRC_16_layers.caffemodel' GPU_ID = 0 DATA_ROOT = os.path.expanduser('~/TimePrediction/data/hot_or_not/data') EXPERIMENT_ROOT = os.path.expanduser('~/TimePrediction/experiments/2016-02-04-hon-finetune/') webcams = ['00000090', '00000156', '00000204', '00000338', '00000484', '00000842', '00004181', '00004556', '00015767', '00017603'] training_frac = 0.8 with open(os.path.join(EXPERIMENT_ROOT, 'train.txt'), 'w') as ftrain, \ open(os.path.join(EXPERIMENT_ROOT, 'val.txt'), 'w') as fval: for webcam in webcams: matfile = os.path.join(DATA_ROOT, webcam, 'train_data_aligned.mat') labels = scipy.io.loadmat(matfile) labels = labels['y'] labels = labels[~np.isnan(labels)] img_path = os.path.join(DATA_ROOT, webcam, 'imgs_align') train_val_imgs = glob.glob(os.path.join(img_path, '*train*.png')) train_val_imgs = sorted(train_val_imgs) # train on past, validate on future, test on even more future ??? num_training = int(math.ceil(len(train_val_imgs)) * training_frac) train_imgs = train_val_imgs[:num_training] val_imgs = train_val_imgs[num_training:] train_labels = labels[:num_training] val_labels = labels[num_training:] assert train_imgs + val_imgs == train_val_imgs assert list(train_labels) + list(val_labels) == list(labels) for i in range(len(train_imgs)): ftrain.write(train_imgs[i] + ' ' + str(train_labels[i]) + '\n') for i in range(len(val_imgs)): fval.write(val_imgs[i] + ' ' + str(val_labels[i]) + '\n') snapshots = glob.glob(os.path.join(EXPERIMENT_ROOT, '*solverstate')) if snapshots != []: idx = [int(snapshot[len(os.path.join(EXPERIMENT_ROOT, "model_iter_")):-len(".solverstate")]) for snapshot in snapshots] last = sorted(idx)[-1] os.system("{} train -solver {} -snapshot {} -gpu {} 2>&1 | tee --append {}".format( os.path.join(CAFFE_PATH, "build/tools/caffe"), os.path.join(EXPERIMENT_ROOT, 'solver.prototxt'), os.path.join(EXPERIMENT_ROOT, "model_iter_" + str(last) + ".solverstate"), GPU_ID, os.path.join(EXPERIMENT_ROOT, "log.log") )) else: os.system("{} train -solver {} -weights {} -gpu {} 2>&1 | tee {}".format( os.path.join(CAFFE_PATH, "build/tools/caffe"), os.path.join(EXPERIMENT_ROOT, 'solver.prototxt'), os.path.join(EXPERIMENT_ROOT, CAFFE_MODEL), GPU_ID, os.path.join(EXPERIMENT_ROOT, "log.log") ))
mit
ramdesh/vcat
src/com/virtusa/vcat/main/GeneratorHelper.java
5139
package com.virtusa.vcat.main; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.logging.Logger; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; import com.virtusa.vcat.templates.ConnectorComponentDescriptor; import com.virtusa.vcat.templates.ConnectorDescriptor; import com.virtusa.vcat.templates.ConnectorMethodDescriptor; import com.virtusa.vcat.templates.GeneratorUtility; public class GeneratorHelper { private static VelocityEngine velocityEngine; private Logger log; public GeneratorHelper() { velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); velocityEngine.init(); log = Logger.getLogger("VCAT"); } private void buildSynapseTemplate(VelocityContext velocityContext, File templateFolderPath, ConnectorMethodDescriptor method) throws IOException { log.info("Building Synapse Template for " + method.getName()); velocityContext.put("method", method); Template methodVelocityTemplate = velocityEngine.getTemplate(VCatConstants.SYNAPSE_TEMPLATE_NAME); BufferedWriter writer = new BufferedWriter(new FileWriter( templateFolderPath.getAbsoluteFile() + File.separator + method.getName() + ".xml")); methodVelocityTemplate.merge(velocityContext, writer); writer.flush(); writer.close(); log.info("...Done"); } public void buildProxyFile(VelocityContext velocityContext, File proxyFolderPath, ConnectorDescriptor connector) throws IOException { if (!proxyFolderPath.exists()) { proxyFolderPath.mkdirs(); } log.info("Building proxy for " + connector.getMethod().getName()); Template proxyVelocityTemplate = velocityEngine.getTemplate(VCatConstants.PROXY_TEMPLATE_NAME); BufferedWriter writer = new BufferedWriter(new FileWriter( proxyFolderPath.getAbsoluteFile() + File.separator + connector.getName() + "_" + connector.getMethod().getName() + ".xml")); proxyVelocityTemplate.merge(velocityContext, writer); writer.flush(); writer.close(); log.info("...Done"); } public void buildRequestFile(VelocityContext velocityContext, File requestFolderPath, ConnectorDescriptor connector) throws IOException { if (!requestFolderPath.exists()) { requestFolderPath.mkdirs(); } log.info("Building request file for " + connector.getMethod().getName()); Template requestVelocityTemplate = null; String fileExtension = ".xml"; if (connector.getMessageType().equalsIgnoreCase("j")) { requestVelocityTemplate = velocityEngine.getTemplate(VCatConstants.JSON_REQUEST_TEMPLATE_NAME); fileExtension = ".json"; } else if (connector.getMessageType().equalsIgnoreCase("x")) { requestVelocityTemplate = velocityEngine.getTemplate(VCatConstants.XML_REQUEST_TEMPLATE_NAME); } else { requestVelocityTemplate = velocityEngine.getTemplate(VCatConstants.SOAP_REQUEST_TEMPLATE_NAME); } BufferedWriter writer = new BufferedWriter(new FileWriter( requestFolderPath.getAbsoluteFile() + File.separator + connector.getMethod().getName() + fileExtension)); requestVelocityTemplate.merge(velocityContext, writer); writer.flush(); writer.close(); log.info("...Done"); } public void buildJavaClass(VelocityContext velocityContext, File javaClassFolderPath, ConnectorDescriptor connector, GeneratorUtility utility) throws IOException { if (!javaClassFolderPath.exists()) { javaClassFolderPath.mkdirs(); } log.info("Building Java Class for " + connector.getMethod().getName()); Template javaClassVelocityTemplate = velocityEngine.getTemplate(VCatConstants.JAVA_CLASS_TEMPLATE_NAME); BufferedWriter writer = new BufferedWriter(new FileWriter( javaClassFolderPath.getAbsoluteFile() + File.separator + utility.firstToUpperCase(connector.getMethod().getName()) + ".java")); javaClassVelocityTemplate.merge(velocityContext, writer); writer.flush(); writer.close(); log.info("...Done"); } public void buildComponent(VelocityContext velocityContext, File componentFolderPath, ConnectorComponentDescriptor component) throws IOException { if (!componentFolderPath.exists()) { componentFolderPath.mkdirs(); } log.info("Building component " + component.getName()); velocityContext.put("component", component); Template componentVelocityTemplate = velocityEngine.getTemplate(VCatConstants.COMPONENT_TEMPLATE_NAME); BufferedWriter writer = new BufferedWriter(new FileWriter( componentFolderPath.getAbsoluteFile() + File.separator + "component.xml")); componentVelocityTemplate.merge(velocityContext, writer); writer.flush(); writer.close(); log.info("...Done"); for (int i = 0; i < component.getMethods().size(); i++) { buildSynapseTemplate(velocityContext, componentFolderPath, component.getMethods().get(i)); } } }
mit
GleicyKellenDevelopment/Projeto_1
Horus/src/test/java/br/com/horus/dao/ClienteDAOTest.java
2427
package br.com.horus.dao; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.List; import org.junit.Ignore; import org.junit.Test; import br.com.horus.dao.ClienteDAO; import br.com.horus.dao.PessoaDAO; import br.com.horus.model.Cliente; import br.com.horus.model.Pessoa; public class ClienteDAOTest { @Test @Ignore public void salvar() throws ParseException { PessoaDAO pessoaDAO = new PessoaDAO(); Pessoa pessoa = pessoaDAO.buscar(4L); Cliente cliente = new Cliente(); // cliente.setDataCadastro(new Date()); // DATA PADRÃO BRASILEIRO // cliente.setDataCadastro(new SimpleDateFormat("dd/MM/yyyy").parse("22/05/2017")); cliente.setPessoa(pessoa); cliente.setAtivo(true); ClienteDAO clienteDAO = new ClienteDAO(); clienteDAO.salvar(cliente); } @Test @Ignore public void listar() { ClienteDAO clienteDAO = new ClienteDAO(); List<Cliente> listarCLientes = clienteDAO.listar(); if (listarCLientes == null) { System.out.println("NENHUM REGISTRO ENCONTRADO"); } else { for (Cliente cliente : listarCLientes) { System.out.println( cliente.getPessoa().getNome() + " - " + cliente.getAtivo() + " - " + cliente.getDataCadastro()); } } } @Test @Ignore public void buscar() { Long id = 2L; ClienteDAO clienteDAO = new ClienteDAO(); Cliente cliente = clienteDAO.buscar(id); if (cliente == null) { System.out.println("NENHUM REGISTRO ENCONTRADO"); } else { System.out.println( cliente.getPessoa().getNome() + " - " + cliente.getAtivo() + " - " + cliente.getDataCadastro()); } } @Test @Ignore public void editar() throws ParseException { Long idPessoa = 2L; Long idCliente = 1L; PessoaDAO pessoaDAO = new PessoaDAO(); Pessoa pessoa = pessoaDAO.buscar(idPessoa); ClienteDAO clienteDAO = new ClienteDAO(); Cliente cliente = clienteDAO.buscar(idCliente); if (pessoa == null || cliente == null) { System.out.println("NENHUM REGISTRO ENCONTRADO"); } cliente.setAtivo(true); cliente.setPessoa(pessoa); cliente.setDataCadastro(new SimpleDateFormat("dd/MM/yyyy").parse("22/05/2015")); clienteDAO.editar(cliente); } @Test @Ignore public void excluir() { Long id = 2L; ClienteDAO clienteDAO = new ClienteDAO(); Cliente cliente = clienteDAO.buscar(id); if (cliente == null) { System.out.println("NENHUM REGISTRO ENCONTRADO"); } clienteDAO.excluir(cliente); } }
mit
goodwinxp/Yorozuya
library/ATF/_POINTFLOAT.hpp
260
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct _POINTFLOAT { float x; float y; }; END_ATF_NAMESPACE
mit
mvxxx/MV-Engine
MV-Engine/source/MV/loader/Loader.hpp
873
#pragma once #include <fstream> #include <string> #include <SFML/System/Vector2.hpp> #include "MV/config/Config.hpp" #include "MV/logger/Logger.hpp" namespace mv { class Loader final { /* ===Objects=== */ public: //title of the window std::string title; //dimensions of single cell sf::Vector2f cellDimensions; //ammount of cells on the map sf::Vector2i ammount; //speed of camera(view) float moveSpeed; protected: private: static Loader* instance; /* ===Methods=== */ public: static Loader& getInstance(); static void createInstance(); //Loads data from file //title //dimensions //amount //speed of camera(view) void loadData(); protected: private: Loader() = default; Loader(Loader const& copy) = delete; // Not Implemented Loader& operator=(Loader const& copy) = delete; // Not Implemented }; }
mit
rprouse/ChessSharp
Alteridem.Engine/PieceType.cs
335
namespace Alteridem.Engine { /// <summary> /// The type of the piece, for example, pawn, knight, etc. /// </summary> public enum PieceType : byte { None = 0x00, WhitePawn = 0x01, BlackPawn = 0x02, Knight = 0x04, Bishop = 0x05, Rook = 0x06, Queen = 0x07, King = 0x08 } }
mit
pkazmier/luahue
src/hue.lua
5642
--- Lua Hue API -- -- Copyright Pete Kazmier 2013 local M = {} local json = require 'json' local http = require 'socket.http' local ltn12 = require 'ltn12' local tablex = require 'pl.tablex' local stringx = require 'pl.stringx' --- Discovers any local Hue bridges on the network -- @return a list of IP addresses function M.discover() local r = M.json_request('http://www.meethue.com/api/nupnp') if r then return tablex.imap(function(b) return b.internalipaddress end, r) end end --- Register a username with the devicetype to the bridge. -- NOTE: you must press the link button on your bridge before this -- call is made, else it will fail. -- @param host the IP address of the bridge -- @param username the username to register -- @param devicetype a textual description of your application -- @return a table showing success or error function M.register(host, username, devicetype) assert(username,'username is nil') assert(devicetype,'devicetype is nil') local body = { devicetype=devicetype, username=username } return M.json_request('http://'..host..'/api', 'POST', body) end -- Bridge object definition M.Bridge = {} --- Creates a new bridge object. Upon creation, the bridge is queried -- for the valid lights that are registered to it. -- @param host the IP address of the bridge -- @param username the username to authenticate with -- @param o optional table containing initial state -- @return instantiated Bridge object function M.Bridge:new(host, username, o) assert(host,'hostname is nil') assert(username,'username is nil') o = o or {} o.host = host o.username = username setmetatable(o, self) self.__index = self if not o:lights() then return nil else return o end end --- Returns the list of lights registered with the bridge. -- @param no_cache if true, do not return previously cached results -- @return array of lights function M.Bridge:lights(no_cache) if not no_cache and self.ids then return self.ids,self.names end local r = self:request('/lights') if not r then return nil end self.ids,self.names = {}, {} for k,v in pairs(r) do self.ids[k] = v.name self.names[v.name] = k end return self.ids,self.names end --- Returns the id of the specified light -- @param light a string representing the id or name assigned to a light -- @return the id as a string or nil if the light does not exist function M.Bridge:lookup_id(light) return self.ids[light] and light or self.names[light] end --- Sets the state of the specified lights. State is specified as a table -- of items specified from http://developers.meethue.com/1_lightsapi.html. -- @param lights a list of lights specified by id or name -- @param state a table containing the desired state -- @return true if successful, else a nil and a table of errors keyed -- by light where the values are a list of errors function M.Bridge:set_state(lights, state) resources,invalid = self:resource_uris(lights, '/state', '/action') local errors = {} -- keyed by light, value is a list of errors for _,light in ipairs(invalid) do errors[light] = { 'light not found' } end for light,uri in pairs(resources) do local status = self:request(uri,'PUT',state) for _,retval in ipairs(status) do if retval.error then if not errors[light] then errors[light] = {} end table.insert(errors[light], retval.error.description) end end end if next(errors) then return nil, errors else return true end end --- Gets the state of the specified lights. State is specified as a table -- of items specified from http://developers.meethue.com/1_lightsapi.html. -- @param lights a list of lights specified by id or name -- @param path dotted string path of attribute to get -- @return a table showing status of specified resources, if a light -- does not exist, there will be no result in the table. function M.Bridge:get_state(lights, path) resources = self:resource_uris(lights) local results = {} for light,uri in pairs(resources) do results[light] = M.table_path(self:request(uri), path) end return results end function M.Bridge:resource_uris(lights, light_suffix, group_suffix) light_suffix = light_suffix or '' group_suffix = group_suffix or '' if #lights == 0 then return {'/groups/0'..group_suffix}, {} end local resources,invalid = {},{} for _,l in ipairs(lights) do local id = self:lookup_id(l) if id then resources[l]='/lights/'..id..light_suffix else invalid[#invalid+1]=l end end return resources,invalid end function M.Bridge:request(resource, method, body) resource = resource or '/' local url = 'http://'..self.host..'/api/'..self.username..resource return M.json_request(url, method, body) end -- Utility functions function M.table_path(t, path) if not path then return t end for _,p in ipairs(stringx.split(path,'.')) do if t[p] == nil then return t else t = t[p] end end return t end function M.json_request(url, method, body) assert(url) method = method or 'GET' if body then body = json.encode(body) end local results = {} local _, code = http.request { url = url, method = method, headers = { ['content-type']='application/json', ['content-length']=body and #body or 0}, source = ltn12.source.string(body), sink = ltn12.sink.table(results), } if string.sub(code,1,2) ~= "20" then return nil, code end results = table.concat(results) return json.decode(results), code end -- End of module return M
mit
thinkingmik/acl-manager-laravel
src/Queries/AclQueryUtils.php
5217
<?php /** * @package thinkingmik/acl-manager-laravel * @author Michele Andreoli <michi.andreoli[at]gmail.com> * @copyright Copyright (c) Michele Andreoli * @license http://mit-license.org/ * @link https://github.com/thinkingmik/acl-manager-laravel */ namespace ThinKingMik\AclManager\Queries; use ThinKingMik\AclManager\Exceptions\AclServerErrorException; class AclQueryUtils { public static function getArray($item) { try { if (!is_array($item)) { $item = array($item); } return $item; } catch (\Exception $ex) { throw new AclServerErrorException($ex->getMessage()); } } public static function getIdsFromObjects($objects, $idProperty = 'id') { try { $objects = self::getArray($objects); $ids = array(); $max = count($objects); for ($i = 0; $i < $max; $i++) { if (gettype($objects[$i]) === 'object') { array_push($ids, $objects[$i]->$idProperty); } else { array_push($ids, $objects[$i]); } } return $ids; } catch (\Exception $ex) { throw new AclServerErrorException($ex->getMessage()); } } public static function arraysPolicyPermutations($subjectField, $subjects, $resources, $permissions, $expires) { try { $array = array(); $date = (new \DateTime())->format('Y-m-d H:i:s'); $maxA = count($subjects); for ($i = 0; $i < $maxA; $i++) { $maxB = count($resources); for ($k = 0; $k < $maxB; $k++) { $maxC = count($permissions); for ($j = 0; $j < $maxC; $j++) { array_push($array, array( $subjectField => $subjects[$i], 'resource_id' => $resources[$k], 'permission_id' => $permissions[$j], 'expiration' => $expires, 'created_at' => $date, 'updated_at' => $date )); } } } return $array; } catch (\Exception $ex) { throw new AclServerErrorException($ex->getMessage()); } } public static function arraysRolesPermutations($users, $roles, $main) { try { $array = array(); $date = (new \DateTime())->format('Y-m-d H:i:s'); $maxA = count($users); for ($i = 0; $i < $maxA; $i++) { $maxB = count($roles); for ($k = 0; $k < $maxB; $k++) { array_push($array, array( 'user_id' => $users[$i], 'role_id' => $roles[$k], 'main' => $main, 'created_at' => $date, 'updated_at' => $date )); } } return $array; } catch (\Exception $ex) { throw new AclServerErrorException($ex->getMessage()); } } public static function getPoliciesFromFilter($policy) { try { $list = self::convertString2Array($policy, ';'); $policies = array(); $max = count($list); for ($i = 0; $i < $max; $i++) { $policy = $list[$i]; $split = explode('.', $policy); $role = self::validatePolicy($split, 0); $resource = self::validatePolicy($split, 1); $permission = self::validatePolicy($split, 2); if (!array_key_exists($role, $policies)) { $policies[$role] = array(); } if (!array_key_exists($resource, $policies[$role])) { $policies[$role][$resource] = array(); } if (!array_key_exists($permission, $policies[$role][$resource])) { $policies[$role][$resource][$permission] = true; } } return $policies; } catch (\Exception $ex) { throw new AclServerErrorException($ex->getMessage()); } } private static function validatePolicy($part, $index) { try { if (array_key_exists($index, $part)) { return trim($part[$index]); } return null; } catch (\Exception $ex) { throw new AclServerErrorException($ex->getMessage()); } } private static function convertString2Array($text, $separator) { try { $ret = array(); $split = explode($separator, $text); $max = count($split); for ($i = 0; $i < $max; $i++) { if (trim($split[$i]) !== '') { $ret[$i] = trim($split[$i]); } } return $ret; } catch (\Exception $ex) { throw new AclServerErrorException($ex->getMessage()); } } }
mit
sweetlandj/Platibus
Source/Platibus.SampleWebApp/Controllers/SubmitActionAttribute.cs
1354
using System; using System.Reflection; using System.Web.Mvc; namespace Platibus.SampleWebApp.Controllers { [AttributeUsage(AttributeTargets.Method)] public class SubmitActionAttribute : ActionNameSelectorAttribute { private readonly string _parameterName; private readonly string _parameterValue; public SubmitActionAttribute(string parameterName) { _parameterName = parameterName; } public SubmitActionAttribute(string parameterName, string parameterValue) { _parameterName = parameterName; _parameterValue = parameterValue; } public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { var isValidName = false; var result = controllerContext.Controller.ValueProvider.GetValue(_parameterName); if (result != null) { var value = result.AttemptedValue; isValidName = string.IsNullOrWhiteSpace(_parameterValue) || string.Equals(value, _parameterValue, StringComparison.OrdinalIgnoreCase); controllerContext.Controller.ControllerContext.RouteData.Values[_parameterName] = value; } return isValidName; } } }
mit
zbigniewcichanski/reserve
core/tests/Service/App/CategoryServiceTest.php
2525
<?php /** * Created by PhpStorm. * @author: Zbyszek Cichanski * Date: 27.12.2016 * Time: 22:29 */ namespace Tests\Owner\App; use Core\Service\App\Command\CategoryCommand; use Core\Service\App\CategoryService; class CategoryServiceTest extends \PHPUnit_Framework_TestCase { /** * @var CategoryService $service */ private $service; public function setUp() { $c = require_once "../../../config/container.php"; $this->service =$c->get('service-app-category-service'); parent::setUp(); // TODO: Change the autogenerated stub } public function testCreateCategoryWithParent() { $categoryCommand = new CategoryCommand(); $categoryCommand->name = 'Francuski'; $categoryCommand->idParent = '1'; $result = $this->service->createCategory($categoryCommand); var_dump($result); $this->assertNotNull($result); $this->assertInstanceOf('\Core\Core\MessageInterface', $result); $this->assertTrue($result->getStatus()); $this->assertNotEmpty($result); } public function testCreateCategory() { $categoryCommand = new CategoryCommand(); $categoryCommand->name = 'Francuski'; $result = $this->service->createCategory($categoryCommand); var_dump($result); $this->assertNotNull($result); $this->assertInstanceOf('\Core\Core\MessageInterface', $result); $this->assertTrue($result->getStatus()); $this->assertNotEmpty($result); } public function testChangeCategoryname() { $categoryCommand = new CategoryCommand(); $categoryCommand->name = 'Francus'; $categoryCommand->id = '88735a8be62a9ca02ab87a8fa573faef'; $result = $this->service->changeCategoryName($categoryCommand); var_dump($result); $this->assertNotNull($result); $this->assertInstanceOf('\Core\Core\MessageInterface', $result); $this->assertTrue($result->getStatus()); $this->assertNotEmpty($result); } public function testRemoveCategory() { $categoryCommand = new CategoryCommand(); $categoryCommand->id = '88735a8be62a9ca02ab87a8fa573faef'; $result = $this->service->removeCategory($categoryCommand); var_dump($result); $this->assertNotNull($result); $this->assertInstanceOf('\Core\Core\MessageInterface', $result); $this->assertTrue($result->getStatus()); $this->assertNotEmpty($result); } }
mit
larsonjj/generator-pistacheo
app/templates/grunt/config/util/clean.js
302
// Configuration for Clean task(s) // Deletes specified folders/files 'use strict'; var taskConfig = function(grunt) { grunt.config.set('clean', { build: ['<%%= pistacheo.directories.destination %>'], tmp: ['<%%= pistacheo.directories.temporary %>'] }); }; module.exports = taskConfig;
mit
MaksimPW/ImgD
app/models/user.rb
308
class User < ActiveRecord::Base has_many :words, dependent: :destroy # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end
mit
bsas/rails-services
test/rails_app_v3/config/application.rb
1928
require File.expand_path('../boot', __FILE__) require 'rails/all' # If you have a Gemfile, require the gems listed there, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) if defined?(Bundler) module RailsAppV3 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. # Custom directories with classes and modules you want to be autoloadable. # config.autoload_paths += %W(#{config.root}/extras) # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Activate observers that should always be running. # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # 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 # JavaScript files you want as :defaults (application.js is always included). # config.action_view.javascript_expansions[:defaults] = %w(jquery rails) # Configure the default encoding used in templates for Ruby 1.9. config.encoding = "utf-8" # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] end end
mit
webaio/tracker
src/Event/Handler/EventHandler.ts
76
export interface EventHandler { handle(dataLayerElementPayload: any); }
mit
shendepu/react-ssr-starter-kit
src/routes/Auth/modules/moqui/moquiModule.js
826
import { login as loginMoqui } from 'lib/moqui/moquiLogin' import { username, password } from 'lib/moqui/config' const MOQUI_REST_API_LOGIN_IN_S = 'MOQUI_REST_API_LOGIN_IN_S' export const login = () => dispatch => { return loginMoqui(username, password).then((apiKey) => { dispatch({ type: MOQUI_REST_API_LOGIN_IN_S, payload: { apiKey } }) return apiKey }) } const initialState = { loggedIn: false, apiKey: null } export default function moquiReducer (state = initialState, action) { let payload = action.payload switch (action.type) { case MOQUI_REST_API_LOGIN_IN_S: console.log('handle action MOQUI_REST_API_LOGIN_IN_S') console.log(payload) let o = Object.assign({}, state, { loggedIn: true, apiKey: payload.apiKey }) console.log(o) return o } return state }
mit
colw/cowpat
src/js/components.js
115
import React from 'react'; export const LinkExt = (props) => ( <a {...props} target="_blank" rel="noopener"/> )
mit
delete/estofadora
estofadora/core/migrations/0001_initial.py
1106
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, serialize=False, primary_key=True, verbose_name='ID')), ('name', models.CharField(verbose_name='Nome', max_length=200)), ('email', models.CharField(verbose_name='Email', blank=True, null=True, max_length=200)), ('telephone', models.CharField(verbose_name='Telefone', blank=True, null=True, max_length=15)), ('subject', models.CharField(verbose_name='Assunto', max_length=30)), ('description', models.TextField(verbose_name='')), ('created_at', models.DateTimeField(verbose_name='Criado em', auto_now_add=True)), ], options={ 'verbose_name': 'Contact', 'verbose_name_plural': 'Contacts', }, ), ]
mit
worldwidewat/TicksToDateTime
Web/Properties/AssemblyInfo.cs
1370
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("OverDrive, Inc")] [assembly: AssemblyProduct("Web")] [assembly: AssemblyCopyright("Copyright © OverDrive, Inc 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7fa8c0a4-232a-4846-b7c8-9dc22f195db9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
airslie/renalware-core
spec/controllers.legacy/renalware/problems_controller_spec.rb
1340
# frozen_string_literal: true require "rails-controller-testing" require "rails_helper" module Renalware::Problems describe ProblemsController, type: :controller do routes { Renalware::Engine.routes } let(:user) { @current_user } let(:patient) { create(:patient, by: user) } let(:problem) { create(:problem, patient: patient, by: user) } describe "GET index" do it "responds with success" do get :index, params: { patient_id: patient } expect(response).to be_successful end end describe "PUT update" do context "with valid attributes" do it "redirects to the problem index" do put :update, params: { patient_id: patient, id: problem, problems_problem: { description: "testing" } } expect(response).to redirect_to(patient_problem_path(patient, problem)) end end context "with invalid attributes" do it "redirects to the problem index as invalid problems are rejected" do put :update, params: { patient_id: patient, id: problem, problems_problem: { description: "" } } expect(response).to be_successful end end end end end
mit
prat0318/dbms
mini_dbms/je-5.0.103/src/com/sleepycat/je/utilint/LongStat.java
1684
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved. * */ package com.sleepycat.je.utilint; import com.sleepycat.je.utilint.StatDefinition.StatType; /** * A long JE stat. */ public class LongStat extends Stat<Long> { private static final long serialVersionUID = 1L; protected long counter; public LongStat(StatGroup group, StatDefinition definition) { super(group, definition); } public LongStat(StatGroup group, StatDefinition definition, long counter) { super(group, definition); this.counter = counter; } @Override public Long get() { return counter; } @Override public void set(Long newValue) { counter = newValue; } public void increment() { counter++; } public void add(long count) { counter += count; } @Override public void add(Stat<Long> other) { counter += other.get(); } @Override public Stat<Long> computeInterval(Stat<Long> base) { Stat<Long> ret = copy(); if (definition.getType() == StatType.INCREMENTAL) { ret.set(counter - base.get()); } return ret; } @Override public void negate () { if (definition.getType() == StatType.INCREMENTAL) { counter = -counter; } } @Override public void clear() { counter = 0L; } @Override protected String getFormattedValue() { return Stat.FORMAT.format(counter); } @Override public boolean isNotSet() { return (counter == 0); } }
mit
akoken/Jirabox
src/Jirabox/Common/LiveTiles/ImageTile.xaml.cs
2485
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; namespace Jirabox.Common.LiveTiles { public partial class ImageTile : UserControl { public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } // Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc... public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ImageTile), new PropertyMetadata(string.Empty, OnTitleChanged)); private static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var imageTileControl = d as ImageTile; imageTileControl.txt1.Text = e.NewValue.ToString(); } public BitmapImage DisplayPicture { get { return (BitmapImage)GetValue(DisplayPictureProperty); } set { SetValue(DisplayPictureProperty, value); } } // Using a DependencyProperty as the backing store for Source. This enables animation, styling, binding, etc... public static readonly DependencyProperty DisplayPictureProperty = DependencyProperty.Register("DisplayPicture", typeof(BitmapImage), typeof(ImageTile), new PropertyMetadata(null)); public ImageTile() { InitializeComponent(); Storyboard anim = (Storyboard)FindName("liveTileAnim1_Part1"); anim.Begin(); } private void liveTileAnim1_Part1_Completed_1(object sender, EventArgs e) { Storyboard anim = (Storyboard)FindName("liveTileAnim1_Part2"); anim.Begin(); } private void liveTileAnim1_Part2_Completed_1(object sender, EventArgs e) { Storyboard anim = (Storyboard)FindName("liveTileAnim2_Part1"); anim.Begin(); } private void liveTileAnim2_Part1_Completed_1(object sender, EventArgs e) { Storyboard anim = (Storyboard)FindName("liveTileAnim2_Part2"); anim.Begin(); } private void liveTileAnim2_Part2_Completed_1(object sender, EventArgs e) { Storyboard anim = (Storyboard)FindName("liveTileAnim1_Part1"); anim.Begin(); } } }
mit
simark/pygdbmi
pygdbmi/cli/pprint.py
2376
# The MIT License (MIT) # # Copyright (c) 2015 Simon Marchi <simon.marchi@polymtl.ca> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys import argparse from pygdbmi import parser from pygdbmi import visitors def main(): argparser = argparse.ArgumentParser(description='Pretty-print some GDB MI records') argparser.add_argument('input_file', metavar='input-file', type=str, help='The file from which to read the MI data. Use - for stdin.') argparser.add_argument('-c', '--colors', action='store_true', help='Enable colored output, if possible') args = argparser.parse_args() input_file = args.input_file if input_file == '-': mi_output = sys.stdin.read() else: try: with open(input_file) as f: mi_output = f.read() except FileNotFoundError as e: print('Error: file not found: {}'.format(e), file=sys.stderr) sys.exit(1) try: tree = parser.parse(mi_output, False) except parser.ParseError as e: print('Error: parse error: {}'.format(e), file=sys.stderr) sys.exit(1) visitor = visitors.PrettyPrintVisitor(en_colors=args.colors) visitor.visit(tree) if __name__ == '__main__': main()
mit
djfoxer/dp.notification
djfoxer.dp.notification/djfoxer.dp.notification.App/Design/DesignDataService.cs
216
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace djfoxer.dp.notification.App.Design { public class DesignDataService { } }
mit
Azure/azure-sdk-for-java
sdk/deviceprovisioningservices/azure-resourcemanager-deviceprovisioningservices/src/main/java/com/azure/resourcemanager/deviceprovisioningservices/models/IotDpsSkuDefinitionListResult.java
1965
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.deviceprovisioningservices.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.deviceprovisioningservices.fluent.models.IotDpsSkuDefinitionInner; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** List of available SKUs. */ @Fluent public final class IotDpsSkuDefinitionListResult { @JsonIgnore private final ClientLogger logger = new ClientLogger(IotDpsSkuDefinitionListResult.class); /* * The list of SKUs */ @JsonProperty(value = "value") private List<IotDpsSkuDefinitionInner> value; /* * The next link. */ @JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY) private String nextLink; /** * Get the value property: The list of SKUs. * * @return the value value. */ public List<IotDpsSkuDefinitionInner> value() { return this.value; } /** * Set the value property: The list of SKUs. * * @param value the value value to set. * @return the IotDpsSkuDefinitionListResult object itself. */ public IotDpsSkuDefinitionListResult withValue(List<IotDpsSkuDefinitionInner> value) { this.value = value; return this; } /** * Get the nextLink property: The next link. * * @return the nextLink value. */ public String nextLink() { return this.nextLink; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (value() != null) { value().forEach(e -> e.validate()); } } }
mit
Azure/azure-sdk-for-go
services/apimanagement/mgmt/2020-12-01/apimanagement/tenantsettings.go
10315
package apimanagement // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // TenantSettingsClient is the apiManagement Client type TenantSettingsClient struct { BaseClient } // NewTenantSettingsClient creates an instance of the TenantSettingsClient client. func NewTenantSettingsClient(subscriptionID string) TenantSettingsClient { return NewTenantSettingsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewTenantSettingsClientWithBaseURI creates an instance of the TenantSettingsClient client using a custom endpoint. // Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewTenantSettingsClientWithBaseURI(baseURI string, subscriptionID string) TenantSettingsClient { return TenantSettingsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get get tenant settings. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. func (client TenantSettingsClient) Get(ctx context.Context, resourceGroupName string, serviceName string) (result TenantSettingsContract, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TenantSettingsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.TenantSettingsClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, serviceName) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client TenantSettingsClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "settingsType": autorest.Encode("path", "public"), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2020-12-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/settings/{settingsType}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client TenantSettingsClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client TenantSettingsClient) GetResponder(resp *http.Response) (result TenantSettingsContract, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListByService public settings. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // filter - not used func (client TenantSettingsClient) ListByService(ctx context.Context, resourceGroupName string, serviceName string, filter string) (result TenantSettingsCollectionPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TenantSettingsClient.ListByService") defer func() { sc := -1 if result.tsc.Response.Response != nil { sc = result.tsc.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.TenantSettingsClient", "ListByService", err.Error()) } result.fn = client.listByServiceNextResults req, err := client.ListByServicePreparer(ctx, resourceGroupName, serviceName, filter) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "ListByService", nil, "Failure preparing request") return } resp, err := client.ListByServiceSender(req) if err != nil { result.tsc.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "ListByService", resp, "Failure sending request") return } result.tsc, err = client.ListByServiceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "ListByService", resp, "Failure responding to request") return } if result.tsc.hasNextLink() && result.tsc.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListByServicePreparer prepares the ListByService request. func (client TenantSettingsClient) ListByServicePreparer(ctx context.Context, resourceGroupName string, serviceName string, filter string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2020-12-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/settings", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByServiceSender sends the ListByService request. The method will close the // http.Response Body if it receives an error. func (client TenantSettingsClient) ListByServiceSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListByServiceResponder handles the response to the ListByService request. The method always // closes the http.Response Body. func (client TenantSettingsClient) ListByServiceResponder(resp *http.Response) (result TenantSettingsCollection, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByServiceNextResults retrieves the next set of results, if any. func (client TenantSettingsClient) listByServiceNextResults(ctx context.Context, lastResults TenantSettingsCollection) (result TenantSettingsCollection, err error) { req, err := lastResults.tenantSettingsCollectionPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "listByServiceNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByServiceSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "listByServiceNextResults", resp, "Failure sending next results request") } result, err = client.ListByServiceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.TenantSettingsClient", "listByServiceNextResults", resp, "Failure responding to next results request") } return } // ListByServiceComplete enumerates all values, automatically crossing page boundaries as required. func (client TenantSettingsClient) ListByServiceComplete(ctx context.Context, resourceGroupName string, serviceName string, filter string) (result TenantSettingsCollectionIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/TenantSettingsClient.ListByService") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListByService(ctx, resourceGroupName, serviceName, filter) return }
mit
cyclosproject/cyclos4-ui
src/app/shared/focused.directive.ts
1242
import { AfterViewInit, ChangeDetectorRef, Directive, ElementRef, Inject, Input, Optional } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { BaseFieldDirective } from 'app/shared/base-field.directive'; import { focus, truthyAttr } from 'app/shared/helper'; import { LayoutService } from 'app/core/layout.service'; /** * Input fields with this directive will receive an initial focus */ @Directive({ selector: '[focused]', }) export class FocusedDirective extends BaseFieldDirective implements AfterViewInit { constructor( private layout: LayoutService, @Optional() el: ElementRef, @Optional() @Inject(NG_VALUE_ACCESSOR) valueAccessor: any, private changeDetector: ChangeDetectorRef, ) { super(el, valueAccessor); } _focused: boolean | string = false; @Input() get focused(): boolean | string { return this._focused; } set focused(focused: boolean | string) { this._focused = truthyAttr(focused); } ngAfterViewInit(): void { if (this._focused && this.layout.gtxs) { const field = this.field; if (field) { setTimeout(() => { focus(field); this.changeDetector.detectChanges(); }, 100); } } } }
mit
dicarlosystems/laravel-permission
tests/CacheTest.php
3197
<?php namespace Spatie\Permission\Test; use Illuminate\Support\Facades\DB; use Spatie\Permission\Contracts\Role; use Spatie\Permission\PermissionRegistrar; use Spatie\Permission\Contracts\Permission; class CacheTest extends TestCase { protected $registrar; public function setUp() { parent::setUp(); $this->registrar = app(PermissionRegistrar::class); $this->registrar->forgetCachedPermissions(); DB::connection()->enableQueryLog(); $this->assertCount(0, DB::getQueryLog()); $this->registrar->registerPermissions(); $this->assertCount(2, DB::getQueryLog()); DB::flushQueryLog(); } /** @test */ public function it_can_cache_the_permissions() { $this->registrar->registerPermissions(); $this->assertCount(0, DB::getQueryLog()); } /** @test */ public function permission_creation_and_updating_should_flush_the_cache() { $permission = app(Permission::class)->create(['name' => 'new']); $this->assertCount(1, DB::getQueryLog()); $this->registrar->registerPermissions(); $this->assertCount(3, DB::getQueryLog()); $permission->name = 'other name'; $permission->save(); $this->assertCount(4, DB::getQueryLog()); $this->registrar->registerPermissions(); $this->assertCount(6, DB::getQueryLog()); } /** @test */ public function role_creation_and_updating_should_flush_the_cache() { $role = app(Role::class)->create(['name' => 'new']); $this->assertCount(2, DB::getQueryLog()); $this->registrar->registerPermissions(); $this->assertCount(4, DB::getQueryLog()); $role->name = 'other name'; $role->save(); $this->assertCount(5, DB::getQueryLog()); $this->registrar->registerPermissions(); $this->assertCount(7, DB::getQueryLog()); } /** @test */ public function user_creation_should_not_flush_the_cache() { User::create(['email' => 'new']); $this->assertCount(1, DB::getQueryLog()); $this->registrar->registerPermissions(); $this->assertCount(1, DB::getQueryLog()); } /** @test */ public function adding_a_permission_to_a_role_should_flush_the_cache() { $this->testUserRole->givePermissionTo($this->testUserPermission); $this->assertCount(1, DB::getQueryLog()); $this->registrar->registerPermissions(); $this->assertCount(3, DB::getQueryLog()); } /** @test */ public function has_permission_to_should_use_the_cache() { $this->testUserRole->givePermissionTo(['edit-articles', 'edit-news']); $this->testUser->assignRole('testRole'); $this->assertCount(4, DB::getQueryLog()); $this->assertTrue($this->testUser->hasPermissionTo('edit-articles')); $this->assertCount(8, DB::getQueryLog()); $this->assertTrue($this->testUser->hasPermissionTo('edit-news')); $this->assertCount(8, DB::getQueryLog()); $this->assertTrue($this->testUser->hasPermissionTo('edit-articles')); $this->assertCount(8, DB::getQueryLog()); } }
mit
l33tdaima/l33tdaima
p021e/merge_two_lists.js
1068
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ const List = require('list'); /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function (l1, l2) { let sentinel = new List.ListNode(0); let p = sentinel; while (l1 && l2) { if (l1.val < l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } p = p.next; } p.next = l1 ? l1 : l2; return sentinel.next; }; // TEST [ [[], [], []], [[1], [2], [1, 2]], [[], [0], [0]], [ [1, 1, 1], [1, 1, 2], [1, 1, 1, 1, 1, 2], ], [ [1, 2, 4], [1, 3, 4], [1, 1, 2, 3, 4, 4], ], [ [1, 3, 9], [2, 4, 6, 8, 10], [1, 2, 3, 4, 6, 8, 9, 10], ], ].forEach(([l1, l2, expected]) => { const actual = List.toArray( mergeTwoLists(List.fromArray(l1), List.fromArray(l2)) ); console.log('Merge', l1, 'and', l2, '->', actual); console.assert(actual.toString() === expected.toString()); });
mit
ozataman/polymorphic_attacher
test/polymorphic_attacher_test.rb
166
require 'test_helper' class PolymorphicAttacherTest < ActiveSupport::TestCase # Replace this with your real tests. test "the truth" do assert true end end
mit
jSherz/lsd-members
frontend/src/app/utils/index.ts
56
export { CustomValidators } from "./custom-validators";
mit
deniszykov/msgpack-unity3d
src/GameDevWare.Serialization.Tests/ValueContainer.cs
102
namespace GameDevWare.Serialization.Tests { public class ValueContainer<T> { public T Value; } }
mit
bfriesen/garply
src/garply/ExecutionContext.cs
729
using System; using System.Collections.Generic; using System.Diagnostics; namespace Garply { internal class ExecutionContext : ErrorContext { private readonly Stack<Value> _evaluationStack = new Stack<Value>(); private Scope _scope; public ExecutionContext(Scope scope) { Debug.Assert(scope != null); _scope = scope; } public Value Pop() => _evaluationStack.Pop(); public void Push(Value value) => _evaluationStack.Push(value); public int Size => _evaluationStack.Count; public Scope Scope { get { return _scope; } set { Debug.Assert(value != null); _scope = value; } } } }
mit
sotownsend/flok
spec/kern/assets/vm/vm_transaction_diff_pages.js
4287
//Page Factor ////////////////////////////////////////////////////////////////////////////////////////// function PageFactory(head, next) { this.head = head; this.next = next; this.entries = []; } //Add an entry PageFactory.prototype.addEntry = function(eid, value) { this.entries.push({_id: eid, _sig: value, value: value}); } //This adds up to four entrys that can be represented as a square: //------------- //| id0 | id1 | //------------- //| id2 | id3 | //------------- //Leaving out parts of the values array will not add those entries, e.g. ["Square", null, null, "Triangle"] //--------------------| //| Square | null | //--------------------| //| null | Triangle | //--------------------| //Where 'Square' is id0 and 'Triangle' is id3 PageFactory.prototype.addEntryFourSquare = function(values) { if (values.length != 4) { throw "FourSquare requires for values. Make values null if you don't need them" } for (var i = 0; i < values.length; ++i) { if (values[i]) { this.addEntry("id"+i, values[i]); } } } //Same as addEntryFourSquare but takes an index parameter before the //value that sets the id of each element //e.g. addEntryFourSquareCustomIds([["id0, "A"], ["id2, "B"], ["id1, "C"], ["id3, "D"]]). //[ // {_id: "id0", value: "A", _sig: "A"}, // {_id: "id3", value: "D", _sig: "D"}, // {_id: "id2", value: "C", _sig: "C"}, // {_id: "id1", value: "B", _sig: "B"}, //] PageFactory.prototype.addEntryFourSquareCustomIds = function(values) { for (var i = 0; i < values.length; ++i) { //Get pair var pair = values[i]; if (pair.length != 2) { throw "FourSquareShuffle accepts pairs. E.g. ['id0', 'A']" } var id = pair[0]; var value = pair[1]; this.addEntry(id, value); } } //Returns a page PageFactory.prototype.compile = function(page_id) { if (page_id === undefined) { var page = vm_create_page("default"); } else { var page = vm_create_page(page_id); } page._head = this.head; page._next = this.next; page.entries = this.entries; vm_rehash_page(page); vm_reindex_page(page); return page; } ////////////////////////////////////////////////////////////////////////////////////////// var pf = new PageFactory(); pf.addEntryFourSquare(["Triangle", "Square", "Z", null]); triangle_square_z_null = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["Triangle", "Circle", null, "Q"]); triangle_circle_null_q = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["Triangle", "Circle", null, "Q"]); triangle_circle_null_q = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["Q", null, "Circle", "Square"]); q_null_circle_square = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["P", "Circle", null, "Q"]); p_circle_null_q = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["P", "Circle", null, null]); p_circle_null_null = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["P", null, null, "Q"]); p_null_null_q = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["P", "Square", null, null]); p_square_null_null = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["Triangle", null, "A", "M"]); triangle_null_a_m = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["Triangle", "Square", null, null]); triangle_square_null_null = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquare(["Triangle", "Z", "Q", null]); triangle_z_q_null = pf.compile(); var pf = new PageFactory(null); head_null = pf.compile(); var pf = new PageFactory("world"); head_world = pf.compile(); var pf = new PageFactory(null); next_null = pf.compile(); var pf = new PageFactory(null, "world"); next_world = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquareCustomIds([["id1", "Square"], ["id0", "Triangle"], ["id2", "Z"]]); triangle_square_z_null_moved_square_triangle_z = pf.compile(); var pf = new PageFactory(); pf.addEntryFourSquareCustomIds([["id2", "Z"], ["id1", "Square"], ["id0", "Triangle"]]); triangle_square_z_null_moved_z_square_triangle = pf.compile(); //Seperate page var pf = new PageFactory(); pf.addEntryFourSquare(["P", "Square", null, null]); default2_square_null_null = pf.compile("default2");
mit
uutils/coreutils
src/uu/ln/src/ln.rs
16022
// * This file is part of the uutils coreutils package. // * // * (c) Joseph Crail <jbcrail@gmail.com> // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. // spell-checker:ignore (ToDO) srcpath targetpath EEXIST #[macro_use] extern crate uucore; use clap::{crate_version, App, AppSettings, Arg}; use uucore::display::Quotable; use uucore::error::{UError, UResult}; use std::borrow::Cow; use std::error::Error; use std::ffi::{OsStr, OsString}; use std::fmt::Display; use std::fs; use std::io::{stdin, Result}; #[cfg(any(unix, target_os = "redox"))] use std::os::unix::fs::symlink; #[cfg(windows)] use std::os::windows::fs::{symlink_dir, symlink_file}; use std::path::{Path, PathBuf}; use uucore::backup_control::{self, BackupMode}; use uucore::fs::{canonicalize, MissingHandling, ResolveMode}; pub struct Settings { overwrite: OverwriteMode, backup: BackupMode, suffix: String, symbolic: bool, relative: bool, target_dir: Option<String>, no_target_dir: bool, no_dereference: bool, verbose: bool, } #[derive(Clone, Debug, Eq, PartialEq)] pub enum OverwriteMode { NoClobber, Interactive, Force, } #[derive(Debug)] enum LnError { TargetIsDirectory(PathBuf), SomeLinksFailed, FailedToLink(String), MissingDestination(PathBuf), ExtraOperand(OsString), } impl Display for LnError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::TargetIsDirectory(s) => write!(f, "target {} is not a directory", s.quote()), Self::FailedToLink(e) => write!(f, "failed to link: {}", e), Self::SomeLinksFailed => write!(f, "some links failed to create"), Self::MissingDestination(s) => { write!(f, "missing destination file operand after {}", s.quote()) } Self::ExtraOperand(s) => write!( f, "extra operand {}\nTry '{} --help' for more information.", s.quote(), uucore::execution_phrase() ), } } } impl Error for LnError {} impl UError for LnError { fn code(&self) -> i32 { match self { Self::TargetIsDirectory(_) | Self::SomeLinksFailed | Self::FailedToLink(_) | Self::MissingDestination(_) | Self::ExtraOperand(_) => 1, } } } fn usage() -> String { format!( "{0} [OPTION]... [-T] TARGET LINK_NAME (1st form) {0} [OPTION]... TARGET (2nd form) {0} [OPTION]... TARGET... DIRECTORY (3rd form) {0} [OPTION]... -t DIRECTORY TARGET... (4th form)", uucore::execution_phrase() ) } fn long_usage() -> String { String::from( " In the 1st form, create a link to TARGET with the name LINK_NAME. In the 2nd form, create a link to TARGET in the current directory. In the 3rd and 4th forms, create links to each TARGET in DIRECTORY. Create hard links by default, symbolic links with --symbolic. By default, each destination (name of new link) should not already exist. When creating hard links, each TARGET must exist. Symbolic links can hold arbitrary text; if later resolved, a relative link is interpreted in relation to its parent directory. ", ) } static ABOUT: &str = "change file owner and group"; mod options { pub const FORCE: &str = "force"; pub const INTERACTIVE: &str = "interactive"; pub const NO_DEREFERENCE: &str = "no-dereference"; pub const SYMBOLIC: &str = "symbolic"; pub const TARGET_DIRECTORY: &str = "target-directory"; pub const NO_TARGET_DIRECTORY: &str = "no-target-directory"; pub const RELATIVE: &str = "relative"; pub const VERBOSE: &str = "verbose"; } static ARG_FILES: &str = "files"; #[uucore::main] pub fn uumain(args: impl uucore::Args) -> UResult<()> { let usage = usage(); let long_usage = long_usage(); let matches = uu_app() .override_usage(&usage[..]) .after_help(&*format!( "{}\n{}", long_usage, backup_control::BACKUP_CONTROL_LONG_HELP )) .get_matches_from(args); /* the list of files */ let paths: Vec<PathBuf> = matches .values_of(ARG_FILES) .unwrap() .map(PathBuf::from) .collect(); let overwrite_mode = if matches.is_present(options::FORCE) { OverwriteMode::Force } else if matches.is_present(options::INTERACTIVE) { OverwriteMode::Interactive } else { OverwriteMode::NoClobber }; let backup_mode = backup_control::determine_backup_mode(&matches)?; let backup_suffix = backup_control::determine_backup_suffix(&matches); let settings = Settings { overwrite: overwrite_mode, backup: backup_mode, suffix: backup_suffix, symbolic: matches.is_present(options::SYMBOLIC), relative: matches.is_present(options::RELATIVE), target_dir: matches .value_of(options::TARGET_DIRECTORY) .map(String::from), no_target_dir: matches.is_present(options::NO_TARGET_DIRECTORY), no_dereference: matches.is_present(options::NO_DEREFERENCE), verbose: matches.is_present(options::VERBOSE), }; exec(&paths[..], &settings) } pub fn uu_app<'a>() -> App<'a> { App::new(uucore::util_name()) .version(crate_version!()) .about(ABOUT) .setting(AppSettings::InferLongArgs) .arg(backup_control::arguments::backup()) .arg(backup_control::arguments::backup_no_args()) // TODO: opts.arg( // Arg::new(("d", "directory", "allow users with appropriate privileges to attempt \ // to make hard links to directories"); .arg( Arg::new(options::FORCE) .short('f') .long(options::FORCE) .help("remove existing destination files"), ) .arg( Arg::new(options::INTERACTIVE) .short('i') .long(options::INTERACTIVE) .help("prompt whether to remove existing destination files"), ) .arg( Arg::new(options::NO_DEREFERENCE) .short('n') .long(options::NO_DEREFERENCE) .help( "treat LINK_NAME as a normal file if it is a \ symbolic link to a directory", ), ) // TODO: opts.arg( // Arg::new(("L", "logical", "dereference TARGETs that are symbolic links"); // // TODO: opts.arg( // Arg::new(("P", "physical", "make hard links directly to symbolic links"); .arg( Arg::new(options::SYMBOLIC) .short('s') .long("symbolic") .help("make symbolic links instead of hard links") // override added for https://github.com/uutils/coreutils/issues/2359 .overrides_with(options::SYMBOLIC), ) .arg(backup_control::arguments::suffix()) .arg( Arg::new(options::TARGET_DIRECTORY) .short('t') .long(options::TARGET_DIRECTORY) .help("specify the DIRECTORY in which to create the links") .value_name("DIRECTORY") .conflicts_with(options::NO_TARGET_DIRECTORY), ) .arg( Arg::new(options::NO_TARGET_DIRECTORY) .short('T') .long(options::NO_TARGET_DIRECTORY) .help("treat LINK_NAME as a normal file always"), ) .arg( Arg::new(options::RELATIVE) .short('r') .long(options::RELATIVE) .help("create symbolic links relative to link location") .requires(options::SYMBOLIC), ) .arg( Arg::new(options::VERBOSE) .short('v') .long(options::VERBOSE) .help("print name of each linked file"), ) .arg( Arg::new(ARG_FILES) .multiple_occurrences(true) .takes_value(true) .required(true) .min_values(1), ) } fn exec(files: &[PathBuf], settings: &Settings) -> UResult<()> { // Handle cases where we create links in a directory first. if let Some(ref name) = settings.target_dir { // 4th form: a directory is specified by -t. return link_files_in_dir(files, &PathBuf::from(name), settings); } if !settings.no_target_dir { if files.len() == 1 { // 2nd form: the target directory is the current directory. return link_files_in_dir(files, &PathBuf::from("."), settings); } let last_file = &PathBuf::from(files.last().unwrap()); if files.len() > 2 || last_file.is_dir() { // 3rd form: create links in the last argument. return link_files_in_dir(&files[0..files.len() - 1], last_file, settings); } } // 1st form. Now there should be only two operands, but if -T is // specified we may have a wrong number of operands. if files.len() == 1 { return Err(LnError::MissingDestination(files[0].clone()).into()); } if files.len() > 2 { return Err(LnError::ExtraOperand(files[2].clone().into()).into()); } assert!(!files.is_empty()); match link(&files[0], &files[1], settings) { Ok(_) => Ok(()), Err(e) => Err(LnError::FailedToLink(e.to_string()).into()), } } fn link_files_in_dir(files: &[PathBuf], target_dir: &Path, settings: &Settings) -> UResult<()> { if !target_dir.is_dir() { return Err(LnError::TargetIsDirectory(target_dir.to_owned()).into()); } let mut all_successful = true; for srcpath in files.iter() { let targetpath = if settings.no_dereference && matches!(settings.overwrite, OverwriteMode::Force) { // In that case, we don't want to do link resolution // We need to clean the target if is_symlink(target_dir) { if target_dir.is_file() { if let Err(e) = fs::remove_file(target_dir) { show_error!("Could not update {}: {}", target_dir.quote(), e); }; } if target_dir.is_dir() { // Not sure why but on Windows, the symlink can be // considered as a dir // See test_ln::test_symlink_no_deref_dir if let Err(e) = fs::remove_dir(target_dir) { show_error!("Could not update {}: {}", target_dir.quote(), e); }; } } target_dir.to_path_buf() } else { match srcpath.as_os_str().to_str() { Some(name) => { match Path::new(name).file_name() { Some(basename) => target_dir.join(basename), // This can be None only for "." or "..". Trying // to create a link with such name will fail with // EEXIST, which agrees with the behavior of GNU // coreutils. None => target_dir.join(name), } } None => { show_error!("cannot stat {}: No such file or directory", srcpath.quote()); all_successful = false; continue; } } }; if let Err(e) = link(srcpath, &targetpath, settings) { show_error!( "cannot link {} to {}: {}", targetpath.quote(), srcpath.quote(), e ); all_successful = false; } } if all_successful { Ok(()) } else { Err(LnError::SomeLinksFailed.into()) } } fn relative_path<'a>(src: &Path, dst: &Path) -> Result<Cow<'a, Path>> { let src_abs = canonicalize(src, MissingHandling::Normal, ResolveMode::Logical)?; let mut dst_abs = canonicalize( dst.parent().unwrap(), MissingHandling::Normal, ResolveMode::Logical, )?; dst_abs.push(dst.components().last().unwrap()); let suffix_pos = src_abs .components() .zip(dst_abs.components()) .take_while(|(s, d)| s == d) .count(); let src_iter = src_abs.components().skip(suffix_pos).map(|x| x.as_os_str()); let mut result: PathBuf = dst_abs .components() .skip(suffix_pos + 1) .map(|_| OsStr::new("..")) .chain(src_iter) .collect(); if result.as_os_str().is_empty() { result.push("."); } Ok(result.into()) } fn link(src: &Path, dst: &Path, settings: &Settings) -> Result<()> { let mut backup_path = None; let source: Cow<'_, Path> = if settings.relative { relative_path(src, dst)? } else { src.into() }; if is_symlink(dst) || dst.exists() { match settings.overwrite { OverwriteMode::NoClobber => {} OverwriteMode::Interactive => { print!("{}: overwrite {}? ", uucore::util_name(), dst.quote()); if !read_yes() { return Ok(()); } fs::remove_file(dst)?; } OverwriteMode::Force => fs::remove_file(dst)?, }; backup_path = match settings.backup { BackupMode::NoBackup => None, BackupMode::SimpleBackup => Some(simple_backup_path(dst, &settings.suffix)), BackupMode::NumberedBackup => Some(numbered_backup_path(dst)), BackupMode::ExistingBackup => Some(existing_backup_path(dst, &settings.suffix)), }; if let Some(ref p) = backup_path { fs::rename(dst, p)?; } } if settings.symbolic { symlink(&source, dst)?; } else { fs::hard_link(&source, dst)?; } if settings.verbose { print!("{} -> {}", dst.quote(), source.quote()); match backup_path { Some(path) => println!(" (backup: {})", path.quote()), None => println!(), } } Ok(()) } fn read_yes() -> bool { let mut s = String::new(); match stdin().read_line(&mut s) { Ok(_) => match s.char_indices().next() { Some((_, x)) => x == 'y' || x == 'Y', _ => false, }, _ => false, } } fn simple_backup_path(path: &Path, suffix: &str) -> PathBuf { let mut p = path.as_os_str().to_str().unwrap().to_owned(); p.push_str(suffix); PathBuf::from(p) } fn numbered_backup_path(path: &Path) -> PathBuf { let mut i: u64 = 1; loop { let new_path = simple_backup_path(path, &format!(".~{}~", i)); if !new_path.exists() { return new_path; } i += 1; } } fn existing_backup_path(path: &Path, suffix: &str) -> PathBuf { let test_path = simple_backup_path(path, ".~1~"); if test_path.exists() { return numbered_backup_path(path); } simple_backup_path(path, suffix) } #[cfg(windows)] pub fn symlink<P1: AsRef<Path>, P2: AsRef<Path>>(src: P1, dst: P2) -> Result<()> { if src.as_ref().is_dir() { symlink_dir(src, dst) } else { symlink_file(src, dst) } } pub fn is_symlink<P: AsRef<Path>>(path: P) -> bool { match fs::symlink_metadata(path) { Ok(m) => m.file_type().is_symlink(), Err(_) => false, } }
mit
ConsenSys/truffle
packages/db-kit/src/cli/decodeAddress/Splash.tsx
3802
import React from "react"; import { Box, Text } from "ink"; import Spinner from "ink-spinner"; import Divider from "ink-divider"; import type TruffleConfig from "@truffle/config"; import type { Db, Resources } from "@truffle/db"; import { useDecoder } from "@truffle/db-kit/cli/hooks"; import { DecodeAddressResult as Result } from "./Result"; export interface Props { config: TruffleConfig; db: Db; project: Resources.IdObject<"projects">; address: string; } export const DecodeAddressSplash = ({ config, db, project, address }: Props) => { const { decoder, statusByAddress } = useDecoder({ config, db, project, network: { name: config.network }, addresses: [address] }); const spinners = Object.entries(statusByAddress).map(([address, status]) => { switch (status) { case "querying": return ( <Box key={`address-${address}`}> <Box paddingLeft={1} paddingRight={1}> <Text dimColor color="green"> <Spinner /> </Text> </Box> <Text dimColor bold> {address} </Text> <Text dimColor color="red"> {" "} ::{" "} </Text> <Text dimColor color="gray"> Querying @truffle/db... </Text> </Box> ); case "fetching": return ( <Box key={`address-${address}`}> <Box paddingLeft={1} paddingRight={1}> <Text dimColor color="green"> <Spinner /> </Text> </Box> <Text dimColor bold> {address} </Text> <Text dimColor color="red"> {" "} ::{" "} </Text> <Text dimColor color="gray"> Fetching external... </Text> </Box> ); case "ok": return ( <Box key={`address-${address}`}> <Box paddingLeft={1} paddingRight={1}> <Text dimColor color="green"> ✓ </Text> </Box> <Text dimColor bold> {address} </Text> <Text dimColor color="red"> {" "} ::{" "} </Text> <Text dimColor color="gray"> OK </Text> </Box> ); case "failed": return ( <Box key={`address-${address}`}> <Box paddingLeft={1} paddingRight={1}> <Text dimColor color="yellow"> ⚠ </Text> </Box> <Text dimColor bold> {address} </Text> <Text dimColor color="red"> {" "} ::{" "} </Text> <Text dimColor color="gray"> Could not find </Text> </Box> ); } }); const showLoaders = Object.values(statusByAddress).find( status => status !== "ok" ); const body = decoder && ( <Box flexDirection="column"> <Box justifyContent="center" marginBottom={1}> <Divider width={10} /> </Box> <Result decoder={decoder} address={address} /> </Box> ); return ( <Box flexDirection="column"> {showLoaders && ( <Box key="loaders" flexDirection="column" borderStyle="round" borderColor="dim" > <Box paddingX={1}> <Text dimColor bold> Related addresses: </Text> </Box> <Box paddingX={2} flexDirection="column"> {...spinners} </Box> </Box> )} {body} </Box> ); };
mit
teoreteetik/api-snippets
rest/taskrouter/taskqueues/instance/post/example-1/example-1.3.x.js
627
// Download the Node helper library from twilio.com/docs/node/install // These consts are your accountSid and authToken from https://www.twilio.com/console const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const authToken = 'your_auth_token'; const workspaceSid = 'WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const taskQueueSid = 'WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; const client = require('twilio')(accountSid, authToken); client.taskrouter.v1 .workspaces(workspaceSid) .taskQueues(taskQueueSid) .update({ target_workers: 'languages HAS "english"', }) .then(taskQueue => console.log(taskQueue.targetWorkers));
mit
implico/frontend-starter
gulpfile.js
9545
/** Frontend-starter @author Bartosz Sak https://github.com/implico/frontend-starter The MIT License (MIT) ******************* API frs default task, equals to frs watch frs clean cleans dist dir frs start runs build and watch frs build cleans and builds the app (with -p: optimized for production) frs watch runs watch with Browsersync options: -p production mode -r restart mode (blocked opening new browserSync window) */ 'use strict'; var path = require('upath'), fs = require('fs'); //gett app root dir var appDir; if (!process.env.FRS_BASE_DIR) { console.log('Frontend-starter: FRS_BASE_DIR env variable not set - module called directly from the command line.'); // process.exit(); appDir = path.normalize(__dirname + '/../'); } else { appDir = path.normalize(process.env.FRS_BASE_DIR + '/'); } console.log('Frontend-starter: Project base dir set to ' + appDir); /* VARS */ var dirs = require('./gulpfile.dirs')(appDir), Injector = require(dirs.lib.main + 'injector'), browserSync = require('browser-sync'), gulp = require('gulp'), debug = require('gulp-debug'); // add global node_modules process.env.NODE_PATH = dirs.rootModules; //terminate Browsersync when the main process sends closing string (or the data is not a string) process.stdin.on('data', function(data) { if ((!data.indexOf) || (data.indexOf('_FRS_CLOSE_') >= 0)) { browserSync.exit(); process.exit(); } }); //core tasks container var tasks = {}; //task registry var taskReg = {}; var app = { init() { this.taskUtils.init(); }, //a mix of utilities used by tasks taskUtils: { invokedTask: 'default', init() { this.setInvokedTask(); this.sprites.init(); }, //sets current cli task setInvokedTask() { var args = process.argv.slice(2), task; args.some((arg) => { if (arg.charAt(0) != '-') { task = arg; return true; } }); if (task) { this.invokedTask = task; } }, //exits if current cli task is equal to the passed one quitIfInvoked(taskName, cb) { if (cb) { cb(); } if (this.invokedTask == taskName) { process.exit(); } }, //converts stream to promise streamToPromise(stream) { if (!(stream instanceof Promise)) { return new Promise((resolve, reject) => { stream.on('finish', resolve); }); } return stream; }, //dummy workaround for not accepting empty globs by gulp.src sanitizeGlob(glob) { if ((glob instanceof Array) && (glob.length === 0)) { glob = ['_835e99fa880c36c1828e55361d228fab/*']; //non-existing dir } return glob; }, //fills undefined sprite properties as defaults, adds undefined dirs sprites: { init() { var _this = this; //add undefined dirs if (config.sprites.auto) { var spritesDirExists = true; try { fs.accessSync(dirs.src.sprites); } catch(ex) { spritesDirExists = false; } if (spritesDirExists) { config.sprites.items = config.sprites.items.concat(fs.readdirSync(dirs.src.sprites).filter(function(dir) { var ret; if (ret = fs.statSync(path.join(dirs.src.sprites, dir)).isDirectory()) { config.sprites.items.every(function(item, index) { if (item.name == dir) { ret = false; return false; } else return true; }); } return ret; }).map(function(dir) { return { name: dir }; })); } } //indexes to be deleted (dest is null) let deleteIndex = []; config.sprites.items.forEach(function(item, index) { if (typeof item.name === 'undefined') { console.err('Frontend-starter error: unspecified sprite item name (index: ' + index + ')'); process.exit(1); } if (item.dest === null) { deleteIndex.push(index); return; } let name = item.name; _this.setIfUndef(item, 'varPrepend', name.length ? (name + '-') : ''); _this.setIfUndef(item, 'src', dirs.src.sprites + name + '/**/*.*'); _this.setIfUndef(item, 'dest', dirs.dist.sprites.main); _this.setIfUndef(item, 'options', {}); _this.setIfUndef(item.options, 'imgName', name + '.png'); _this.setIfUndef(item.options, 'imgPath', '../img/' + name + '.png'); _this.setIfUndef(item.options, 'cssName', '_' + name + '.scss'); _this.setIfUndef(item.options, 'cssSpritesheetName', item.varPrepend + 'spritesheet'); _this.setIfUndef(item.options, 'cssVarMap', function(sprite) { sprite.name = item.varPrepend + sprite.name; }); _this.setIfUndef(item.options, 'algorithm', 'diagonal'); }); config.sprites.items = config.sprites.items.filter((v, i) => { return deleteIndex.indexOf(i) < 0; }); }, setIfUndef(item, index, val) { if (typeof item[index] === 'undefined') { item[index] = val; } } } }, //taskReg utilities taskRegUtils: { addDep(taskName, targetTaskName, relatedDepName, isBefore) { if (taskReg[targetTaskName]) { taskReg[targetTaskName].deps = this.addDepArray(taskReg[targetTaskName].deps, taskName, relatedDepName, isBefore); } else { console.err('Frontend-starter error: task to add dependency not found (' + targetTaskName + ')'); exit(1); } }, //removes task from target task deps //targetTaskNames: string (single task), array or true for all tasks removeDep(taskName, targetTaskNames) { var _this = this; if (targetTaskNames === true) { targetTaskNames = []; for (var i in taskReg) { if (taskReg.hasOwnProperty(i)) { targetTaskNames.push(i); } } } else if (!(targetTaskNames instanceof Array)) { targetTaskNames = [targetTaskNames]; } targetTaskNames.forEach((targetTaskName) => { var deps = taskReg[targetTaskName].deps; if (deps instanceof Array) { taskReg[targetTaskName].deps = deps = _this.removeDepArray(taskName, deps); deps.forEach((dep, index) => { deps[index] = _this.removeDepArray(taskName, dep); }); } }); }, removeTask: function(taskName) { if (taskReg[taskName]) { delete taskReg[taskName]; this.removeDep(taskName, true); if (['styles', 'fonts', 'sprites', 'js', 'images', 'views', 'lint'].indexOf(taskName) >= 0) { if (config.watch.inject[taskName] === true) { config.watch.inject[taskName] = false; } if (config.watch.dev && config.watch.dev.inject && config.watch.dev.inject[taskName] === true) { config.watch.dev.inject[taskName] = false; } if (config.watch.prod && config.watch.prod.inject && config.watch.prod.inject[taskName] === true) { config.watch.prod.inject[taskName] = false; } } } else { console.error('Frontend-starter error: task to remove not found (' + taskName + ')'); process.exit(1); } }, //helper for removeDep() removeDepArray(taskName, array) { if (array instanceof Array) { var index = array.indexOf(taskName); if (index >= 0) { delete array[index]; array = array.filter((dep) => { return typeof dep !== 'undefined'; }); } } return array; }, //helper for addDep() addDepArray(deps, taskName, relatedDepName, isBefore, startIndex) { var _this = this; //depsCopy = deps.slice(0); startIndex = startIndex || 0; deps.every((dep, index) => { if (index >= startIndex) { //add at the beginning if (relatedDepName === true) { deps.splice(0, 0, taskName); return false; } //add at the end else if (relatedDepName === false) { if (index == (deps.length - 1)) { deps.splice(index + 1, 0, taskName); return false; } } else if (dep instanceof Array) { deps[index] = _this.addDepArray(deps[index], taskName, relatedDepName, isBefore); } else if (dep == relatedDepName) { deps.splice(index + (isBefore ? 0 : 1), 0, taskName); deps = _this.addDepArray(deps, taskName, relatedDepName, isBefore, index + 2); return false; } return true; } }); return deps; } } } var appData = { dirs, app, tasks, taskReg, gulp, browserSync, Injector }; var config = appData.config = require('./gulpfile.config')(dirs, appData); app.init(); //autoload core tasks var tasksList = ['watch', 'js', 'styles', 'fonts', 'sprites', 'images', 'views', 'customDirs', 'lint', 'browserSync', 'clean']; tasksList.forEach((t) => { require(dirs.lib.tasks + t + '.js')(appData); }); require('./gulpfile.tasks.js')(appData);
mit
bpe78/WpfExamples
src/WpfApplication4/WpfApplication4/TotalSumConverter.cs
661
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; using System.Globalization; namespace WpfApplication4 { public class TotalSumConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var users = value as IEnumerable<object>; if (users == null) return "$0.00"; double sum = users.Sum(user => ((User)user).Total); return sum.ToString("c"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new System.NotImplementedException(); } } }
mit
krainboltgreene/authn
lib/authn/model.rb
1410
module AuthN module Model def self.included(object) object.extend ClassMethods end module ClassMethods def has_authentication(options = {}) merge_config_with options end def config=(options) @@config = options end def config @@config ||= AuthN::Config.new end def authenticate(identifiers = {}) # Extract the password from the identifiers password = identifiers.delete AuthN.config.login_password_key # Find the documents that match the criteria criteria = send AuthN.config.model_critera_method, identifiers # Get the first document that matches the criteria instance = criteria.first # Check to see if the instance exists and if a password was given if instance && password # Check to see if the instance can authenticate with password instance.authenticate(password) ? instance : false end # Return instance if account was found and password matched # Return false if account was found and password didn't match # Return nil if account wasn't found OR password wasn't given end private def merge_config_with(options) options[:account_klass] = name unless options.has_key? :account_klass config.merge! AuthN.config.dump.merge options end end end end
mit
dadansetiadi/kedaibeauty.com
application/controllers/Produk.php
2373
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Produk extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('produk_model'); //$this->load->model('user_model'); } public function index() { $data['sql1'] = $this->produk_model->get_produk(); //$this->load->view('user_view',$data); $this->load->view('backend/header'); $this->load->view('backend/menu'); $this->load->view('backend/body',$data); $this->load->view('backend/footer'); } public function show() { $data['sql1'] = $this->produk_model->get_produk(); //$this->load->view('user_view',$data); $this->load->view('backend/header'); $this->load->view('backend/menu'); $this->load->view('backend/body',$data); $this->load->view('backend/footer'); } public function add() { $data['op'] = 'tambah'; $this->load->view('backend/header'); $this->load->view('backend/menu'); $this->load->view('produk/insert_produk',$data); $this->load->view('backend/footer'); } public function simpan() { $op = $this->input->post('op'); $id = $this->input->post('id'); $nama_produk = $this->input->post('nama_produk'); $merk = $this->input->post('merk'); $kode_produk = $this->input->post('kode_produk'); $deskripsi = $this->input->post('deskripsi'); $harga = $this->input->post('harga'); $discount = $this->input->post('discount'); $harga_discount = $this->input->post('harga_discount'); $gambar1 = $this->input->post('gambar1'); $gambar2 = $this->input->post('gambar2'); $gambar3 = $this->input->post('gambar3'); $status = $this->input->post('status'); $data = array( 'nama_produk' => $nama_produk, 'merk' => $merk, 'kode_produk' => $kode_produk, 'deskripsi' => $deskripsi, 'harga' => $harga, 'discount' => $discount, 'harga_discount' => $harga_discount, 'gambar1' => $gambar1, 'gambar2' => $gambar2, 'gambar3' => $gambar3, 'status' => $status ); if ($op=="tambah") { $this->produk_model->simpan($data); } else{ $this->produk_model->update($id,$data); } redirect('produk/show'); } }
mit
ruben-ayrapetyan/coreclr
tests/src/JIT/HardwareIntrinsics/X86/Avx/TestNotZAndNotC.Int16.cs
12893
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestNotZAndNotCInt16() { var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanTwoComparisonOpTest__TestNotZAndNotCInt16 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int16); private const int Op2ElementCount = VectorSize / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private BooleanTwoComparisonOpTest__DataTable<Int16, Int16> _dataTable; static BooleanTwoComparisonOpTest__TestNotZAndNotCInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); } public BooleanTwoComparisonOpTest__TestNotZAndNotCInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } _dataTable = new BooleanTwoComparisonOpTest__DataTable<Int16, Int16>(_data1, _data2, VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.TestNotZAndNotC( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Avx.TestNotZAndNotC( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Avx.TestNotZAndNotC( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() {var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Avx.TestNotZAndNotC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt16(); var result = Avx.TestNotZAndNotC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Avx.TestNotZAndNotC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "") { var expectedResult1 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult1 &= (((left[i] & right[i]) == 0)); } var expectedResult2 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult2 &= (((~left[i] & right[i]) == 0)); } if (((expectedResult1 == false) && (expectedResult2 == false)) != result) { Succeeded = false; Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
mit
jlumijarvi/excelimporter
ExcelImporter/Account/TwoFactorAuthenticationSignIn.aspx.cs
2830
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using ExcelImporter.Models; namespace ExcelImporter.Account { public partial class TwoFactorAuthenticationSignIn : System.Web.UI.Page { private ApplicationSignInManager signinManager; private ApplicationUserManager manager; public TwoFactorAuthenticationSignIn() { manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>(); } protected void Page_Load(object sender, EventArgs e) { var userId = signinManager.GetVerifiedUserId<ApplicationUser, string>(); if (userId == null) { Response.Redirect("/Account/Error", true); } var userFactors = manager.GetValidTwoFactorProviders(userId); Providers.DataSource = userFactors.Select(x => x).ToList(); Providers.DataBind(); } protected void CodeSubmit_Click(object sender, EventArgs e) { bool rememberMe = false; bool.TryParse(Request.QueryString["RememberMe"], out rememberMe); var result = signinManager.TwoFactorSignIn<ApplicationUser, string>(SelectedProvider.Value, Code.Text, isPersistent: rememberMe, rememberBrowser: RememberBrowser.Checked); switch (result) { case SignInStatus.Success: IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); break; case SignInStatus.LockedOut: Response.Redirect("/Account/Lockout"); break; case SignInStatus.Failure: default: FailureText.Text = "Invalid code"; ErrorMessage.Visible = true; break; } } protected void ProviderSubmit_Click(object sender, EventArgs e) { if (!signinManager.SendTwoFactorCode(Providers.SelectedValue)) { Response.Redirect("/Account/Error"); } var user = manager.FindById(signinManager.GetVerifiedUserId<ApplicationUser, string>()); if (user != null) { var code = manager.GenerateTwoFactorToken(user.Id, Providers.SelectedValue); } SelectedProvider.Value = Providers.SelectedValue; sendcode.Visible = false; verifycode.Visible = true; } } }
mit
Pulgama/supriya
supriya/ugens/NumControlBuses.py
543
import collections from supriya import CalculationRate from supriya.typing import UGenInputMap from supriya.ugens.InfoUGenBase import InfoUGenBase class NumControlBuses(InfoUGenBase): """ A number of control buses info unit generator. :: >>> supriya.ugens.NumControlBuses.ir() NumControlBuses.ir() """ ### CLASS VARIABLES ### __documentation_section__ = "Info UGens" _ordered_input_names: UGenInputMap = collections.OrderedDict([]) _valid_calculation_rates = (CalculationRate.SCALAR,)
mit
enettolima/magento-training
magento2ce/app/code/Magento/Bundle/Setup/InstallSchema.php
33660
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Bundle\Setup; use Magento\Framework\Setup\InstallSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; /** * @codeCoverageIgnore */ class InstallSchema implements InstallSchemaInterface { /** * {@inheritdoc} * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) { $installer = $setup; $installer->startSetup(); /** * Create table 'catalog_product_bundle_option' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_bundle_option')) ->addColumn( 'option_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], 'Option Id' ) ->addColumn( 'parent_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false], 'Parent Id' ) ->addColumn( 'required', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'default' => '0'], 'Required' ) ->addColumn( 'position', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'default' => '0'], 'Position' ) ->addColumn( 'type', \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 255, [], 'Type' ) ->addIndex( $installer->getIdxName('catalog_product_bundle_option', ['parent_id']), ['parent_id'] ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_option', 'parent_id', 'catalog_product_entity', 'entity_id' ), 'parent_id', $installer->getTable('catalog_product_entity'), 'entity_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->setComment('Catalog Detail Bundle Option'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_bundle_option_value' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_bundle_option_value')) ->addColumn( 'value_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], 'Value Id' ) ->addColumn( 'option_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false], 'Option Id' ) ->addColumn( 'store_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false], 'Store Id' ) ->addColumn( 'title', \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 255, [], 'Title' ) ->addIndex( $installer->getIdxName( 'catalog_product_bundle_option_value', ['option_id', 'store_id'], \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE ), ['option_id', 'store_id'], ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE] ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_option_value', 'option_id', 'catalog_product_bundle_option', 'option_id' ), 'option_id', $installer->getTable('catalog_product_bundle_option'), 'option_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->setComment('Catalog Detail Bundle Option Value'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_bundle_selection' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_bundle_selection')) ->addColumn( 'selection_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], 'Selection Id' ) ->addColumn( 'option_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false], 'Option Id' ) ->addColumn( 'parent_product_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false], 'Parent Detail Id' ) ->addColumn( 'product_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false], 'Detail Id' ) ->addColumn( 'position', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'default' => '0'], 'Position' ) ->addColumn( 'is_default', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'default' => '0'], 'Is Default' ) ->addColumn( 'selection_price_type', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'default' => '0'], 'Selection Price Type' ) ->addColumn( 'selection_price_value', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', ['nullable' => false, 'default' => '0.0000'], 'Selection Price Value' ) ->addColumn( 'selection_qty', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Selection Qty' ) ->addColumn( 'selection_can_change_qty', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['nullable' => false, 'default' => '0'], 'Selection Can Change Qty' ) ->addIndex( $installer->getIdxName('catalog_product_bundle_selection', ['option_id']), ['option_id'] ) ->addIndex( $installer->getIdxName('catalog_product_bundle_selection', ['product_id']), ['product_id'] ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_selection', 'option_id', 'catalog_product_bundle_option', 'option_id' ), 'option_id', $installer->getTable('catalog_product_bundle_option'), 'option_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_selection', 'product_id', 'catalog_product_entity', 'entity_id' ), 'product_id', $installer->getTable('catalog_product_entity'), 'entity_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->setComment('Catalog Detail Bundle Selection'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_bundle_selection_price' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_bundle_selection_price')) ->addColumn( 'selection_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Selection Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'selection_price_type', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'default' => '0'], 'Selection Price Type' ) ->addColumn( 'selection_price_value', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', ['nullable' => false, 'default' => '0.0000'], 'Selection Price Value' ) ->addIndex( $installer->getIdxName('catalog_product_bundle_selection_price', ['website_id']), ['website_id'] ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_selection_price', 'website_id', 'store_website', 'website_id' ), 'website_id', $installer->getTable('store_website'), 'website_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_selection_price', 'selection_id', 'catalog_product_bundle_selection', 'selection_id' ), 'selection_id', $installer->getTable('catalog_product_bundle_selection'), 'selection_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->setComment('Catalog Detail Bundle Selection Price'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_bundle_price_index' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_bundle_price_index')) ->addColumn( 'entity_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Entity Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'customer_group_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Customer Group Id' ) ->addColumn( 'min_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', ['nullable' => false], 'Min Price' ) ->addColumn( 'max_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', ['nullable' => false], 'Max Price' ) ->addIndex( $installer->getIdxName('catalog_product_bundle_price_index', ['website_id']), ['website_id'] ) ->addIndex( $installer->getIdxName('catalog_product_bundle_price_index', ['customer_group_id']), ['customer_group_id'] ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_price_index', 'customer_group_id', 'customer_group', 'customer_group_id' ), 'customer_group_id', $installer->getTable('customer_group'), 'customer_group_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_price_index', 'entity_id', 'catalog_product_entity', 'entity_id' ), 'entity_id', $installer->getTable('catalog_product_entity'), 'entity_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->addForeignKey( $installer->getFkName( 'catalog_product_bundle_price_index', 'website_id', 'store_website', 'website_id' ), 'website_id', $installer->getTable('store_website'), 'website_id', \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE ) ->setComment('Catalog Detail Bundle Price Index'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_bundle_stock_index' */ $table = $installer->getConnection() ->newTable( $installer->getTable('catalog_product_bundle_stock_index') ) ->addColumn( 'entity_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Entity Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'stock_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Stock Id' ) ->addColumn( 'option_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true, 'default' => '0'], 'Option Id' ) ->addColumn( 'stock_status', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['default' => '0'], 'Stock Status' ) ->setComment('Catalog Detail Bundle Stock Index'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_index_price_bundle_idx' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_index_price_bundle_idx')) ->addColumn( 'entity_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Entity Id' ) ->addColumn( 'customer_group_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Customer Group Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'tax_class_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'default' => '0'], 'Tax Class Id' ) ->addColumn( 'price_type', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false], 'Price Type' ) ->addColumn( 'special_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Special Price' ) ->addColumn( 'tier_percent', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Tier Percent' ) ->addColumn( 'orig_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Orig Price' ) ->addColumn( 'price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Price' ) ->addColumn( 'min_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Min Price' ) ->addColumn( 'max_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Max Price' ) ->addColumn( 'tier_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Tier Price' ) ->addColumn( 'base_tier', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Base Tier' ) ->setComment('Catalog Detail Index Price Bundle Idx'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_index_price_bundle_tmp' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_index_price_bundle_tmp')) ->addColumn( 'entity_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Entity Id' ) ->addColumn( 'customer_group_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Customer Group Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'tax_class_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'default' => '0'], 'Tax Class Id' ) ->addColumn( 'price_type', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false], 'Price Type' ) ->addColumn( 'special_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Special Price' ) ->addColumn( 'tier_percent', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Tier Percent' ) ->addColumn( 'orig_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Orig Price' ) ->addColumn( 'price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Price' ) ->addColumn( 'min_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Min Price' ) ->addColumn( 'max_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Max Price' ) ->addColumn( 'tier_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Tier Price' ) ->addColumn( 'base_tier', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Base Tier' ) ->setOption( 'type', \Magento\Framework\DB\Adapter\Pdo\Mysql::ENGINE_MEMORY ) ->setComment('Catalog Detail Index Price Bundle Tmp'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_index_price_bundle_sel_idx' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_index_price_bundle_sel_idx')) ->addColumn( 'entity_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Entity Id' ) ->addColumn( 'customer_group_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Customer Group Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'option_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true, 'default' => '0'], 'Option Id' ) ->addColumn( 'selection_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true, 'default' => '0'], 'Selection Id' ) ->addColumn( 'group_type', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'default' => '0'], 'Group Type' ) ->addColumn( 'is_required', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'default' => '0'], 'Is Required' ) ->addColumn( 'price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Price' ) ->addColumn( 'tier_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Tier Price' ) ->setComment('Catalog Detail Index Price Bundle Sel Idx'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_index_price_bundle_sel_tmp' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_index_price_bundle_sel_tmp')) ->addColumn( 'entity_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Entity Id' ) ->addColumn( 'customer_group_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Customer Group Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'option_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true, 'default' => '0'], 'Option Id' ) ->addColumn( 'selection_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true, 'default' => '0'], 'Selection Id' ) ->addColumn( 'group_type', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'default' => '0'], 'Group Type' ) ->addColumn( 'is_required', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'default' => '0'], 'Is Required' ) ->addColumn( 'price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Price' ) ->addColumn( 'tier_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Tier Price' ) ->setOption( 'type', \Magento\Framework\DB\Adapter\Pdo\Mysql::ENGINE_MEMORY ) ->setComment('Catalog Detail Index Price Bundle Sel Tmp'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_index_price_bundle_opt_idx' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_index_price_bundle_opt_idx')) ->addColumn( 'entity_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Entity Id' ) ->addColumn( 'customer_group_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Customer Group Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'option_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true, 'default' => '0'], 'Option Id' ) ->addColumn( 'min_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Min Price' ) ->addColumn( 'alt_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Alt Price' ) ->addColumn( 'max_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Max Price' ) ->addColumn( 'tier_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Tier Price' ) ->addColumn( 'alt_tier_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Alt Tier Price' ) ->setComment('Catalog Detail Index Price Bundle Opt Idx'); $installer->getConnection()->createTable($table); /** * Create table 'catalog_product_index_price_bundle_opt_tmp' */ $table = $installer->getConnection() ->newTable($installer->getTable('catalog_product_index_price_bundle_opt_tmp')) ->addColumn( 'entity_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Entity Id' ) ->addColumn( 'customer_group_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Customer Group Id' ) ->addColumn( 'website_id', \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, null, ['unsigned' => true, 'nullable' => false, 'primary' => true], 'Website Id' ) ->addColumn( 'option_id', \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, null, ['unsigned' => true, 'nullable' => false, 'primary' => true, 'default' => '0'], 'Option Id' ) ->addColumn( 'min_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Min Price' ) ->addColumn( 'alt_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Alt Price' ) ->addColumn( 'max_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Max Price' ) ->addColumn( 'tier_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Tier Price' ) ->addColumn( 'alt_tier_price', \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, '12,4', [], 'Alt Tier Price' ) ->setOption( 'type', \Magento\Framework\DB\Adapter\Pdo\Mysql::ENGINE_MEMORY ) ->setComment('Catalog Detail Index Price Bundle Opt Tmp'); $installer->getConnection()->createTable($table); $installer->endSetup(); } }
mit
flagholder/php_ci_test
system/libraries/Upload.php
36917
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2017, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link https://codeigniter.com * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /** * File Uploading Class * * @package CodeIgniter * @subpackage Libraries * @category Uploads * @author EllisLab Dev Team * @link https://codeigniter.com/user_guide/libraries/file_uploading.html */ class CI_Upload { /** * Maximum file size * * @var int */ public $max_size = 0; /** * Maximum image width * * @var int */ public $max_width = 0; /** * Maximum image height * * @var int */ public $max_height = 0; /** * Minimum image width * * @var int */ public $min_width = 0; /** * Minimum image height * * @var int */ public $min_height = 0; /** * Maximum filename length * * @var int */ public $max_filename = 0; /** * Maximum duplicate filename increment ID * * @var int */ public $max_filename_increment = 100; /** * Allowed file types * * @var string */ public $allowed_types = ''; /** * Temporary filename * * @var string */ public $file_temp = ''; /** * Filename * * @var string */ public $file_name = ''; /** * Original filename * * @var string */ public $orig_name = ''; /** * File type * * @var string */ public $file_type = ''; /** * File size * * @var int */ public $file_size = NULL; /** * Filename extension * * @var string */ public $file_ext = ''; /** * Force filename extension to lowercase * * @var string */ public $file_ext_tolower = FALSE; /** * Upload path * * @var string */ public $upload_path = ''; /** * Overwrite flag * * @var bool */ public $overwrite = FALSE; /** * Obfuscate filename flag * * @var bool */ public $encrypt_name = FALSE; /** * Is image flag * * @var bool */ public $is_image = FALSE; /** * Image width * * @var int */ public $image_width = NULL; /** * Image height * * @var int */ public $image_height = NULL; /** * Image type * * @var string */ public $image_type = ''; /** * Image size string * * @var string */ public $image_size_str = ''; /** * Error messages list * * @var array */ public $error_msg = array(); /** * Remove spaces flag * * @var bool */ public $remove_spaces = TRUE; /** * MIME detection flag * * @var bool */ public $detect_mime = TRUE; /** * XSS filter flag * * @var bool */ public $xss_clean = FALSE; /** * Apache mod_mime fix flag * * @var bool */ public $mod_mime_fix = TRUE; /** * Temporary filename prefix * * @var string */ public $temp_prefix = 'temp_file_'; /** * Filename sent by the client * * @var bool */ public $client_name = ''; // -------------------------------------------------------------------- /** * Filename override * * @var string */ protected $_file_name_override = ''; /** * MIME types list * * @var array */ protected $_mimes = array(); /** * CI Singleton * * @var object */ protected $_CI; // -------------------------------------------------------------------- /** * Constructor * * @param array $config * @return void */ public function __construct($config = array()) { empty($config) OR $this->initialize($config, FALSE); $this->_mimes =& get_mimes(); $this->_CI =& get_instance(); log_message('info', 'Upload Class Initialized'); } // -------------------------------------------------------------------- /** * Initialize preferences * * @param array $config * @param bool $reset * @return CI_Upload */ public function initialize(array $config = array(), $reset = TRUE) { $reflection = new ReflectionClass($this); if ($reset === TRUE) { $defaults = $reflection->getDefaultProperties(); foreach (array_keys($defaults) as $key) { if ($key[0] === '_') { continue; } if (isset($config[$key])) { if ($reflection->hasMethod('set_' . $key)) { $this->{'set_' . $key}($config[$key]); } else { $this->$key = $config[$key]; } } else { $this->$key = $defaults[$key]; } } } else { foreach ($config as $key => &$value) { if ($key[0] !== '_' && $reflection->hasProperty($key)) { if ($reflection->hasMethod('set_' . $key)) { $this->{'set_' . $key}($value); } else { $this->$key = $value; } } } } // if a file_name was provided in the config, use it instead of the user input // supplied file name for all uploads until initialized again $this->_file_name_override = $this->file_name; return $this; } // -------------------------------------------------------------------- /** * Perform the file upload * * @param string $field * @return bool */ public function do_upload($field = 'userfile') { // Is $_FILES[$field] set? If not, no reason to continue. if (isset($_FILES[$field])) { $_file = $_FILES[$field]; } // Does the field name contain array notation? elseif (($c = preg_match_all('/(?:^[^\[]+)|\[[^]]*\]/', $field, $matches)) > 1) { $_file = $_FILES; for ($i = 0; $i < $c; $i++) { // We can't track numeric iterations, only full field names are accepted if (($field = trim($matches[0][$i], '[]')) === '' OR !isset($_file[$field])) { $_file = NULL; break; } $_file = $_file[$field]; } } if (!isset($_file)) { $this->set_error('upload_no_file_selected', 'debug'); return FALSE; } // Is the upload path valid? if (!$this->validate_upload_path()) { // errors will already be set by validate_upload_path() so just return FALSE return FALSE; } // Was the file able to be uploaded? If not, determine the reason why. if (!is_uploaded_file($_file['tmp_name'])) { $error = isset($_file['error']) ? $_file['error'] : 4; switch ($error) { case UPLOAD_ERR_INI_SIZE: $this->set_error('upload_file_exceeds_limit', 'info'); break; case UPLOAD_ERR_FORM_SIZE: $this->set_error('upload_file_exceeds_form_limit', 'info'); break; case UPLOAD_ERR_PARTIAL: $this->set_error('upload_file_partial', 'debug'); break; case UPLOAD_ERR_NO_FILE: $this->set_error('upload_no_file_selected', 'debug'); break; case UPLOAD_ERR_NO_TMP_DIR: $this->set_error('upload_no_temp_directory', 'error'); break; case UPLOAD_ERR_CANT_WRITE: $this->set_error('upload_unable_to_write_file', 'error'); break; case UPLOAD_ERR_EXTENSION: $this->set_error('upload_stopped_by_extension', 'debug'); break; default: $this->set_error('upload_no_file_selected', 'debug'); break; } return FALSE; } // Set the uploaded data as class variables $this->file_temp = $_file['tmp_name']; $this->file_size = $_file['size']; // Skip MIME type detection? if ($this->detect_mime !== FALSE) { $this->_file_mime_type($_file); } $this->file_type = preg_replace('/^(.+?);.*$/', '\\1', $this->file_type); $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); $this->file_name = $this->_prep_filename($_file['name']); $this->file_ext = $this->get_extension($this->file_name); $this->client_name = $this->file_name; // Is the file type allowed to be uploaded? if (!$this->is_allowed_filetype()) { $this->set_error('upload_invalid_filetype', 'debug'); return FALSE; } // if we're overriding, let's now make sure the new name and type is allowed if ($this->_file_name_override !== '') { $this->file_name = $this->_prep_filename($this->_file_name_override); // If no extension was provided in the file_name config item, use the uploaded one if (strpos($this->_file_name_override, '.') === FALSE) { $this->file_name .= $this->file_ext; } else { // An extension was provided, let's have it! $this->file_ext = $this->get_extension($this->_file_name_override); } if (!$this->is_allowed_filetype(TRUE)) { $this->set_error('upload_invalid_filetype', 'debug'); return FALSE; } } // Convert the file size to kilobytes if ($this->file_size > 0) { $this->file_size = round($this->file_size / 1024, 2); } // Is the file size within the allowed maximum? if (!$this->is_allowed_filesize()) { $this->set_error('upload_invalid_filesize', 'info'); return FALSE; } // Are the image dimensions within the allowed size? // Note: This can fail if the server has an open_basedir restriction. if (!$this->is_allowed_dimensions()) { $this->set_error('upload_invalid_dimensions', 'info'); return FALSE; } // Sanitize the file name for security $this->file_name = $this->_CI->security->sanitize_filename($this->file_name); // Truncate the file name if it's too long if ($this->max_filename > 0) { $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); } // Remove white spaces in the name if ($this->remove_spaces === TRUE) { $this->file_name = preg_replace('/\s+/', '_', $this->file_name); } if ($this->file_ext_tolower && ($ext_length = strlen($this->file_ext))) { // file_ext was previously lower-cased by a get_extension() call $this->file_name = substr($this->file_name, 0, -$ext_length) . $this->file_ext; } /* * Validate the file name * This function appends an number onto the end of * the file if one with the same name already exists. * If it returns false there was a problem. */ $this->orig_name = $this->file_name; if (FALSE === ($this->file_name = $this->set_filename($this->upload_path, $this->file_name))) { return FALSE; } /* * Run the file through the XSS hacking filter * This helps prevent malicious code from being * embedded within a file. Scripts can easily * be disguised as images or other file types. */ if ($this->xss_clean && $this->do_xss_clean() === FALSE) { $this->set_error('upload_unable_to_write_file', 'error'); return FALSE; } /* * Move the file to the final destination * To deal with different server configurations * we'll attempt to use copy() first. If that fails * we'll use move_uploaded_file(). One of the two should * reliably work in most environments */ if (!@copy($this->file_temp, $this->upload_path . $this->file_name)) { if (!@move_uploaded_file($this->file_temp, $this->upload_path . $this->file_name)) { $this->set_error('upload_destination_error', 'error'); return FALSE; } } /* * Set the finalized image dimensions * This sets the image width/height (assuming the * file was an image). We use this information * in the "data" function. */ $this->set_image_properties($this->upload_path . $this->file_name); return TRUE; } // -------------------------------------------------------------------- /** * Finalized Data Array * * Returns an associative array containing all of the information * related to the upload, allowing the developer easy access in one array. * * @param string $index * @return mixed */ public function data($index = NULL) { $data = array( 'file_name' => $this->file_name, 'file_type' => $this->file_type, 'file_path' => $this->upload_path, 'full_path' => $this->upload_path . $this->file_name, 'raw_name' => substr($this->file_name, 0, -strlen($this->file_ext)), 'orig_name' => $this->orig_name, 'client_name' => $this->client_name, 'file_ext' => $this->file_ext, 'file_size' => $this->file_size, 'is_image' => $this->is_image(), 'image_width' => $this->image_width, 'image_height' => $this->image_height, 'image_type' => $this->image_type, 'image_size_str' => $this->image_size_str, ); if (!empty($index)) { return isset($data[$index]) ? $data[$index] : NULL; } return $data; } // -------------------------------------------------------------------- /** * Set Upload Path * * @param string $path * @return CI_Upload */ public function set_upload_path($path) { // Make sure it has a trailing slash $this->upload_path = rtrim($path, '/') . '/'; return $this; } // -------------------------------------------------------------------- /** * Set the file name * * This function takes a filename/path as input and looks for the * existence of a file with the same name. If found, it will append a * number to the end of the filename to avoid overwriting a pre-existing file. * * @param string $path * @param string $filename * @return string */ public function set_filename($path, $filename) { if ($this->encrypt_name === TRUE) { $filename = md5(uniqid(mt_rand())) . $this->file_ext; } if ($this->overwrite === TRUE OR !file_exists($path . $filename)) { return $filename; } $filename = str_replace($this->file_ext, '', $filename); $new_filename = ''; for ($i = 1; $i < $this->max_filename_increment; $i++) { if (!file_exists($path . $filename . $i . $this->file_ext)) { $new_filename = $filename . $i . $this->file_ext; break; } } if ($new_filename === '') { $this->set_error('upload_bad_filename', 'debug'); return FALSE; } else { return $new_filename; } } // -------------------------------------------------------------------- /** * Set Maximum File Size * * @param int $n * @return CI_Upload */ public function set_max_filesize($n) { $this->max_size = ($n < 0) ? 0 : (int)$n; return $this; } // -------------------------------------------------------------------- /** * Set Maximum File Size * * An internal alias to set_max_filesize() to help with configuration * as initialize() will look for a set_<property_name>() method ... * * @param int $n * @return CI_Upload */ protected function set_max_size($n) { return $this->set_max_filesize($n); } // -------------------------------------------------------------------- /** * Set Maximum File Name Length * * @param int $n * @return CI_Upload */ public function set_max_filename($n) { $this->max_filename = ($n < 0) ? 0 : (int)$n; return $this; } // -------------------------------------------------------------------- /** * Set Maximum Image Width * * @param int $n * @return CI_Upload */ public function set_max_width($n) { $this->max_width = ($n < 0) ? 0 : (int)$n; return $this; } // -------------------------------------------------------------------- /** * Set Maximum Image Height * * @param int $n * @return CI_Upload */ public function set_max_height($n) { $this->max_height = ($n < 0) ? 0 : (int)$n; return $this; } // -------------------------------------------------------------------- /** * Set minimum image width * * @param int $n * @return CI_Upload */ public function set_min_width($n) { $this->min_width = ($n < 0) ? 0 : (int)$n; return $this; } // -------------------------------------------------------------------- /** * Set minimum image height * * @param int $n * @return CI_Upload */ public function set_min_height($n) { $this->min_height = ($n < 0) ? 0 : (int)$n; return $this; } // -------------------------------------------------------------------- /** * Set Allowed File Types * * @param mixed $types * @return CI_Upload */ public function set_allowed_types($types) { $this->allowed_types = (is_array($types) OR $types === '*') ? $types : explode('|', $types); return $this; } // -------------------------------------------------------------------- /** * Set Image Properties * * Uses GD to determine the width/height/type of image * * @param string $path * @return CI_Upload */ public function set_image_properties($path = '') { if ($this->is_image() && function_exists('getimagesize')) { if (FALSE !== ($D = @getimagesize($path))) { $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); $this->image_width = $D[0]; $this->image_height = $D[1]; $this->image_type = isset($types[$D[2]]) ? $types[$D[2]] : 'unknown'; $this->image_size_str = $D[3]; // string containing height and width } } return $this; } // -------------------------------------------------------------------- /** * Set XSS Clean * * Enables the XSS flag so that the file that was uploaded * will be run through the XSS filter. * * @param bool $flag * @return CI_Upload */ public function set_xss_clean($flag = FALSE) { $this->xss_clean = ($flag === TRUE); return $this; } // -------------------------------------------------------------------- /** * Validate the image * * @return bool */ public function is_image() { // IE will sometimes return odd mime-types during upload, so here we just standardize all // jpegs or pngs to the same file type. $png_mimes = array('image/x-png'); $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); if (in_array($this->file_type, $png_mimes)) { $this->file_type = 'image/png'; } elseif (in_array($this->file_type, $jpeg_mimes)) { $this->file_type = 'image/jpeg'; } $img_mimes = array('image/gif', 'image/jpeg', 'image/png'); return in_array($this->file_type, $img_mimes, TRUE); } // -------------------------------------------------------------------- /** * Verify that the filetype is allowed * * @param bool $ignore_mime * @return bool */ public function is_allowed_filetype($ignore_mime = FALSE) { if ($this->allowed_types === '*') { return TRUE; } if (empty($this->allowed_types) OR !is_array($this->allowed_types)) { $this->set_error('upload_no_file_types', 'debug'); return FALSE; } $ext = strtolower(ltrim($this->file_ext, '.')); if (!in_array($ext, $this->allowed_types, TRUE)) { return FALSE; } // Images get some additional checks if (in_array($ext, array('gif', 'jpg', 'jpeg', 'jpe', 'png'), TRUE) && @getimagesize($this->file_temp) === FALSE) { return FALSE; } if ($ignore_mime === TRUE) { return TRUE; } if (isset($this->_mimes[$ext])) { return is_array($this->_mimes[$ext]) ? in_array($this->file_type, $this->_mimes[$ext], TRUE) : ($this->_mimes[$ext] === $this->file_type); } return FALSE; } // -------------------------------------------------------------------- /** * Verify that the file is within the allowed size * * @return bool */ public function is_allowed_filesize() { return ($this->max_size === 0 OR $this->max_size > $this->file_size); } // -------------------------------------------------------------------- /** * Verify that the image is within the allowed width/height * * @return bool */ public function is_allowed_dimensions() { if (!$this->is_image()) { return TRUE; } if (function_exists('getimagesize')) { $D = @getimagesize($this->file_temp); if ($this->max_width > 0 && $D[0] > $this->max_width) { return FALSE; } if ($this->max_height > 0 && $D[1] > $this->max_height) { return FALSE; } if ($this->min_width > 0 && $D[0] < $this->min_width) { return FALSE; } if ($this->min_height > 0 && $D[1] < $this->min_height) { return FALSE; } } return TRUE; } // -------------------------------------------------------------------- /** * Validate Upload Path * * Verifies that it is a valid upload path with proper permissions. * * @return bool */ public function validate_upload_path() { if ($this->upload_path === '') { $this->set_error('upload_no_filepath', 'error'); return FALSE; } if (realpath($this->upload_path) !== FALSE) { $this->upload_path = str_replace('\\', '/', realpath($this->upload_path)); } if (!is_dir($this->upload_path)) { $this->set_error('upload_no_filepath', 'error'); return FALSE; } if (!is_really_writable($this->upload_path)) { $this->set_error('upload_not_writable', 'error'); return FALSE; } $this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path); return TRUE; } // -------------------------------------------------------------------- /** * Extract the file extension * * @param string $filename * @return string */ public function get_extension($filename) { $x = explode('.', $filename); if (count($x) === 1) { return ''; } $ext = ($this->file_ext_tolower) ? strtolower(end($x)) : end($x); return '.' . $ext; } // -------------------------------------------------------------------- /** * Limit the File Name Length * * @param string $filename * @param int $length * @return string */ public function limit_filename_length($filename, $length) { if (strlen($filename) < $length) { return $filename; } $ext = ''; if (strpos($filename, '.') !== FALSE) { $parts = explode('.', $filename); $ext = '.' . array_pop($parts); $filename = implode('.', $parts); } return substr($filename, 0, ($length - strlen($ext))) . $ext; } // -------------------------------------------------------------------- /** * Runs the file through the XSS clean function * * This prevents people from embedding malicious code in their files. * I'm not sure that it won't negatively affect certain files in unexpected ways, * but so far I haven't found that it causes trouble. * * @return string */ public function do_xss_clean() { $file = $this->file_temp; if (filesize($file) == 0) { return FALSE; } if (memory_get_usage() && ($memory_limit = ini_get('memory_limit')) > 0) { $memory_limit = str_split($memory_limit, strspn($memory_limit, '1234567890')); if (!empty($memory_limit[1])) { switch ($memory_limit[1][0]) { case 'g': case 'G': $memory_limit[0] *= 1024 * 1024 * 1024; break; case 'm': case 'M': $memory_limit[0] *= 1024 * 1024; break; default: break; } } $memory_limit = (int)ceil(filesize($file) + $memory_limit[0]); ini_set('memory_limit', $memory_limit); // When an integer is used, the value is measured in bytes. - PHP.net } // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an // attempted XSS attack. if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) { if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary { return FALSE; // Couldn't open the file, return FALSE } $opening_bytes = fread($file, 256); fclose($file); // These are known to throw IE into mime-type detection chaos // <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title // title is basically just in SVG, but we filter it anyhow // if it's an image or no "triggers" detected in the first 256 bytes - we're good return !preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes); } if (($data = @file_get_contents($file)) === FALSE) { return FALSE; } return $this->_CI->security->xss_clean($data, TRUE); } // -------------------------------------------------------------------- /** * Set an error message * * @param string $msg * @return CI_Upload */ public function set_error($msg, $log_level = 'error') { $this->_CI->lang->load('upload'); is_array($msg) OR $msg = array($msg); foreach ($msg as $val) { $msg = ($this->_CI->lang->line($val) === FALSE) ? $val : $this->_CI->lang->line($val); $this->error_msg[] = $msg; log_message($log_level, $msg); } return $this; } // -------------------------------------------------------------------- /** * Display the error message * * @param string $open * @param string $close * @return string */ public function display_errors($open = '<p>', $close = '</p>') { return (count($this->error_msg) > 0) ? $open . implode($close . $open, $this->error_msg) . $close : ''; } // -------------------------------------------------------------------- /** * Prep Filename * * Prevents possible script execution from Apache's handling * of files' multiple extensions. * * @link http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext * * @param string $filename * @return string */ protected function _prep_filename($filename) { if ($this->mod_mime_fix === FALSE OR $this->allowed_types === '*' OR ($ext_pos = strrpos($filename, '.')) === FALSE) { return $filename; } $ext = substr($filename, $ext_pos); $filename = substr($filename, 0, $ext_pos); return str_replace('.', '_', $filename) . $ext; } // -------------------------------------------------------------------- /** * File MIME type * * Detects the (actual) MIME type of the uploaded file, if possible. * The input array is expected to be $_FILES[$field] * * @param array $file * @return void */ protected function _file_mime_type($file) { // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; /** * Fileinfo extension - most reliable method * * Apparently XAMPP, CentOS, cPanel and who knows what * other PHP distribution channels EXPLICITLY DISABLE * ext/fileinfo, which is otherwise enabled by default * since PHP 5.3 ... */ if (function_exists('finfo_file')) { $finfo = @finfo_open(FILEINFO_MIME); if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system { $mime = @finfo_file($finfo, $file['tmp_name']); finfo_close($finfo); /* According to the comments section of the PHP manual page, * it is possible that this function returns an empty string * for some files (e.g. if they don't exist in the magic MIME database) */ if (is_string($mime) && preg_match($regexp, $mime, $matches)) { $this->file_type = $matches[1]; return; } } } /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better * than mime_content_type() as well, hence the attempts to try calling the command line with * three different functions. * * Notes: * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system * - many system admins would disable the exec(), shell_exec(), popen() and similar functions * due to security concerns, hence the function_usable() checks */ if (DIRECTORY_SEPARATOR !== '\\') { $cmd = function_exists('escapeshellarg') ? 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1' : 'file --brief --mime ' . $file['tmp_name'] . ' 2>&1'; if (function_usable('exec')) { /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. * However, we only need the last line, which is the actual return value of exec(), and as such - it overwrites * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy * value, which is only put to allow us to get the return status code. */ $mime = @exec($cmd, $mime, $return_status); if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) { $this->file_type = $matches[1]; return; } } if (!ini_get('safe_mode') && function_usable('shell_exec')) { $mime = @shell_exec($cmd); if (strlen($mime) > 0) { $mime = explode("\n", trim($mime)); if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) { $this->file_type = $matches[1]; return; } } } if (function_usable('popen')) { $proc = @popen($cmd, 'r'); if (is_resource($proc)) { $mime = @fread($proc, 512); @pclose($proc); if ($mime !== FALSE) { $mime = explode("\n", trim($mime)); if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) { $this->file_type = $matches[1]; return; } } } } } // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) if (function_exists('mime_content_type')) { $this->file_type = @mime_content_type($file['tmp_name']); if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string { return; } } $this->file_type = $file['type']; } }
mit
jimbo1299/gcmPushDemo
gen/com/example/pushtester/BuildConfig.java
164
/** Automatically generated file. DO NOT MODIFY */ package com.example.pushtester; public final class BuildConfig { public final static boolean DEBUG = true; }
mit
hivsuper/study
study-parent/jersey2demo/src/main/java/org/lxp/service/CommentService.java
980
package org.lxp.service; import java.util.Date; import javax.annotation.Resource; import org.lxp.mapper.CommentMapper; import org.lxp.model.Comment; import org.lxp.vo.CommentStateEnum; import org.springframework.stereotype.Service; @Service public class CommentService { @Resource private CommentMapper commentMapper; public boolean add(int postId, String name, String text) { Comment comment = new Comment(); comment.setPostId(postId); comment.setName(name); comment.setText(text); comment.setState(CommentStateEnum.NOMARL); comment.setCreateTime(new Date()); return commentMapper.insert(comment) > 0; } public boolean update(int commentId, CommentStateEnum state) { Comment comment = new Comment(); comment.setId(commentId); comment.setState(state); return commentMapper.updateByPrimaryKeySelective(comment) > 0; } public Comment get(int commentId) { return commentMapper.selectByPrimaryKey(commentId); } }
mit
rogeruiz/fly-notify
test/test.js
81
const test = require("tape").test test("fly-notify", function (t) { t.end() })
mit
i5okie/redress_old
config/initializers/devise.rb
12412
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. config.secret_key = '32756fb663e63e62a7fa033ed63cdd3aa51a5539decaead0829f925422b96ec8dd7c997685d996ccc9c57824dd8d1bb633c96f6ef3dde0f11359714df3dd398c' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'support@ibcworld.net' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [ :email ] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :email ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [ :email ] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If http headers should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing :skip => :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = '2a8c567192c520b5705d0a966169cf9153d1004ba8e8ffef49fdd9ea51bc1fd4611e11b40c78d8e8174b9a60cd736d3f25bc5304579ee65621872a2b25c54855' # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming his account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming his account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming his account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed new email is stored in # unconfirmed email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [ :email ] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # :secure => true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. Default is 8..128. config.password_length = 8..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # If true, expires auth token on session timeout. # config.expire_auth_token_on_timeout = false # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [ :email ] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = false # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [ :email ] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(:scope => :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using omniauth, Devise cannot automatically set Omniauth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end
mit
solr-express/solr-express
test/SolrExpress.Solr5.IntegrationTests/Properties/AssemblyInfo.cs
682
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("SolrExpress.Solr5.IntegrationTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SolrExpress.Solr5.IntegrationTests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("6c2c7876-2760-4095-b3c0-41f0133f06a5")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] #if STRONGNAME [assembly: AssemblyKeyFile("SolrExpress.Solr5.IntegrationTests.snk")] #endif
mit
stefanhoth/ropasclisp
mobile/src/main/java/com/stefanhoth/ropasclisp/CircularFrameDrawable.java
3076
package com.stefanhoth.ropasclisp; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; public class CircularFrameDrawable extends Drawable { private final Drawable content; private final RectF bounds; private final Paint backgroundPaint; private final Paint contentPaint; private final Paint outlinePaint; public CircularFrameDrawable(Drawable content, @ColorInt int backgroundColor, @ColorInt int outlineColor) { this.content = content; this.bounds = new RectF(); this.backgroundPaint = getBackgroundPaint(backgroundColor); this.contentPaint = new Paint(); this.outlinePaint = getOutlinePaint(outlineColor); } private Paint getBackgroundPaint(@ColorInt int backgroundColor) { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(backgroundColor); paint.setStyle(Paint.Style.FILL); return paint; } private Paint getOutlinePaint(@ColorInt int outlineColor) { Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(outlineColor); paint.setStyle(Paint.Style.STROKE); return paint; } @Override protected void onBoundsChange(Rect bounds) { this.bounds.set(bounds); content.setBounds(bounds); outlinePaint.setStrokeWidth(bounds.width() * .05f); contentPaint.setShader(null); } @Override public int getIntrinsicWidth() { return content.getIntrinsicWidth(); } @Override public int getIntrinsicHeight() { return content.getIntrinsicHeight(); } @Override public void draw(Canvas canvas) { if (contentPaint.getShader() == null) { updateContentPaint(content); } canvas.drawOval(bounds, backgroundPaint); canvas.drawOval(bounds, contentPaint); canvas.drawOval(bounds, outlinePaint); } private void updateContentPaint(Drawable content) { Rect bounds = getBounds(); Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888); content.draw(new Canvas(bitmap)); contentPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)); } @Override public void setAlpha(int alpha) { backgroundPaint.setAlpha(alpha); contentPaint.setAlpha(alpha); outlinePaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter colorFilter) { backgroundPaint.setColorFilter(colorFilter); contentPaint.setColorFilter(colorFilter); outlinePaint.setColorFilter(colorFilter); } @Override public int getOpacity() { return PixelFormat.UNKNOWN; } }
mit
MarkBorcherding/trigger-tasks
lib/trigger-tasks.rb
63
module TriggerTasks end require 'trigger_tasks/trigger_tasks'
mit
Karasiq/scalajs-highcharts
src/main/scala/com/highmaps/config/PathfinderMarker.scala
5284
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highmaps]] */ package com.highmaps.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>pathfinder-marker</code> */ @js.annotation.ScalaJSDefined class PathfinderMarker extends com.highcharts.HighchartsGenericObject { /** * <p>Enable markers for the connectors.</p> * @since 6.2.0 */ val enabled: js.UndefOr[Boolean] = js.undefined /** * <p>Horizontal alignment of the markers relative to the points.</p> * @since 6.2.0 */ val align: js.UndefOr[String] = js.undefined /** * <p>Vertical alignment of the markers relative to the points.</p> * @since 6.2.0 */ val verticalAlign: js.UndefOr[String] = js.undefined /** * <p>Whether or not to draw the markers inside the points.</p> * @since 6.2.0 */ val inside: js.UndefOr[Boolean] = js.undefined /** * <p>Set the line/border width of the pathfinder markers.</p> * @since 6.2.0 */ val lineWidth: js.UndefOr[Double] = js.undefined /** * <p>Set the radius of the pathfinder markers. The default is * automatically computed based on the algorithmMargin setting.</p> * <p>Setting marker.width and marker.height will override this * setting.</p> * @since 6.2.0 */ val radius: js.UndefOr[Double] = js.undefined /** * <p>Set the width of the pathfinder markers. If not supplied, this * is inferred from the marker radius.</p> * @since 6.2.0 */ val width: js.UndefOr[Double] = js.undefined /** * <p>Set the height of the pathfinder markers. If not supplied, this * is inferred from the marker radius.</p> * @since 6.2.0 */ val height: js.UndefOr[Double] = js.undefined /** * <p>Set the color of the pathfinder markers. By default this is the * same as the connector color.</p> * @since 6.2.0 */ val color: js.UndefOr[String | js.Object] = js.undefined /** * <p>Set the line/border color of the pathfinder markers. By default * this is the same as the marker color.</p> * @since 6.2.0 */ val lineColor: js.UndefOr[String | js.Object] = js.undefined } object PathfinderMarker { /** * @param enabled <p>Enable markers for the connectors.</p> * @param align <p>Horizontal alignment of the markers relative to the points.</p> * @param verticalAlign <p>Vertical alignment of the markers relative to the points.</p> * @param inside <p>Whether or not to draw the markers inside the points.</p> * @param lineWidth <p>Set the line/border width of the pathfinder markers.</p> * @param radius <p>Set the radius of the pathfinder markers. The default is. automatically computed based on the algorithmMargin setting.</p>. <p>Setting marker.width and marker.height will override this. setting.</p> * @param width <p>Set the width of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p> * @param height <p>Set the height of the pathfinder markers. If not supplied, this. is inferred from the marker radius.</p> * @param color <p>Set the color of the pathfinder markers. By default this is the. same as the connector color.</p> * @param lineColor <p>Set the line/border color of the pathfinder markers. By default. this is the same as the marker color.</p> */ def apply(enabled: js.UndefOr[Boolean] = js.undefined, align: js.UndefOr[String] = js.undefined, verticalAlign: js.UndefOr[String] = js.undefined, inside: js.UndefOr[Boolean] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, radius: js.UndefOr[Double] = js.undefined, width: js.UndefOr[Double] = js.undefined, height: js.UndefOr[Double] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined): PathfinderMarker = { val enabledOuter: js.UndefOr[Boolean] = enabled val alignOuter: js.UndefOr[String] = align val verticalAlignOuter: js.UndefOr[String] = verticalAlign val insideOuter: js.UndefOr[Boolean] = inside val lineWidthOuter: js.UndefOr[Double] = lineWidth val radiusOuter: js.UndefOr[Double] = radius val widthOuter: js.UndefOr[Double] = width val heightOuter: js.UndefOr[Double] = height val colorOuter: js.UndefOr[String | js.Object] = color val lineColorOuter: js.UndefOr[String | js.Object] = lineColor com.highcharts.HighchartsGenericObject.toCleanObject(new PathfinderMarker { override val enabled: js.UndefOr[Boolean] = enabledOuter override val align: js.UndefOr[String] = alignOuter override val verticalAlign: js.UndefOr[String] = verticalAlignOuter override val inside: js.UndefOr[Boolean] = insideOuter override val lineWidth: js.UndefOr[Double] = lineWidthOuter override val radius: js.UndefOr[Double] = radiusOuter override val width: js.UndefOr[Double] = widthOuter override val height: js.UndefOr[Double] = heightOuter override val color: js.UndefOr[String | js.Object] = colorOuter override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter }) } }
mit
JWroe/BloomFilter
BloomFilters/BloomFilter.cs
4152
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; namespace BloomFilters { public class BloomFilter : IHashedDataStore { private LargeBitArray[] BitArray { get; } public int NumBits => NumSlices * BitsPerSlice; public int Capacity { get; set; } public int BitsPerSlice { get; set; } public int NumSlices { get; set; } public double ErrorRate { get; set; } public Func<string, IEnumerable<uint>> HashFunc { get; } public Func<string, IEnumerable<uint>> CreateHashingAlgorithm() { const int chunkSize = 4; var totalHashBits = 8 * NumSlices * chunkSize; var algorithm = ChooseHashAlgorithm(totalHashBits); var count = (int)Math.Floor((double)algorithm.HashSize / chunkSize); var numSalts = NumSlices / count; var extra = NumSlices % count; if (extra != 0) { numSalts++; } var hashFuncCreator = HashFunction.CreateHashFunction(algorithm); var salts = Enumerable.Range(start: 0, count: numSalts).Select(i => hashFuncCreator(hashFuncCreator(i.ToString().GetBytes()).Digest())); return key => Hash(salts, key); } private IEnumerable<uint> Hash(IEnumerable<HashFunction> salts, string key) { return salts.Select(salt => { var h = salt.Copy(); h.Update(key); return h.Digest() .UnpackToUInt() .Select(num => num % (uint)BitsPerSlice) .ToList(); }) .Aggregate((uints, uints2) => uints.Combine(uints2)) .Take(NumSlices); } private static HashAlgorithm ChooseHashAlgorithm(long totalHashBits) { HashAlgorithm algorithm; if (totalHashBits > 384) { algorithm = SHA512.Create(); } else if (totalHashBits > 256) { algorithm = SHA384.Create(); } else if (totalHashBits > 160) { algorithm = SHA256.Create(); } else if (totalHashBits > 128) { algorithm = SHA1.Create(); } else { algorithm = MD5.Create(); } return algorithm; } public BloomFilter(int capacity, double errorRate = 0.001) { var numSlices = (int)Math.Ceiling(Math.Log(1.0 / errorRate, newBase: 2)); BitsPerSlice = CalculateBitsPerSlice(capacity, errorRate, numSlices); ErrorRate = errorRate; NumSlices = numSlices; Capacity = capacity; HashFunc = CreateHashingAlgorithm(); BitArray = Enumerable.Range(start: 0, count: NumSlices).Select(i => new LargeBitArray(BitsPerSlice)).ToArray(); } private static int CalculateBitsPerSlice(int capacity, double errorRate, int numSlices) { var bitsNumerator = capacity * Math.Abs(Math.Log(errorRate)); var bitsDenominator = numSlices * Math.Pow(Math.Log(2), y: 2); return (int)Math.Ceiling(bitsNumerator / bitsDenominator); } public void Add(string input) { var hashed = HashFunc(input).ToList(); for (var i = 0; i < NumSlices; i++) { BitArray[i].Set(hashed.ElementAt(i)); } } public bool Contains(string input) { var hashed = HashFunc(input).ToList(); var result = false; for (var i = 0; i < NumSlices; i++) { result |= BitArray[i].Get(hashed.ElementAt(i)); } return result; } } }
mit
WIZUT-PAI/31d
src/AppBundle/Controller/UserController.php
553
<?php namespace AppBundle\Controller; use FOS\RestBundle\Controller\FOSRestController; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; class UserController extends FOSRestController { /** * @Security("has_role('ROLE_USER')") */ public function getMeAction(){ $data = $this->get('security.token_storage')->getToken()->getUser(); //$data = $this->getDoctrine()->getRepository('AppBundle\Entity\ParcelOrder')->findAll(); $view = $this->view($data, 200); return $this->handleView($view); } }
mit
accurat/slush-angular-gulp
tasks/controller.js
3990
/** * Controller Task * This is the main task that is invoked for the processing of the slushfile.js */ (function() { var gulp = require('gulp'), install = require('gulp-install'), conflict = require('gulp-conflict'), template = require('gulp-template'), rename = require('gulp-rename'), inquirer = require('inquirer') _ = require('underscore.string'); //Local dependencies var util = require('../util'); module.exports = function(gulp) { 'use strict'; gulp.task('controller', function(done) { var _this = this; var name = util.getDefaultOption(_this.args, 0); var options = util.getGlobalOptions(); var modules = util.getModuleProposal(options.appDir); if (modules.length === 0) { throw new Error('Controller must be created in a module, but no modules exist. Create a module using "slush angular-gulp:module <module-Name>".'); } inquirer.prompt([{ type: 'input', name: 'fileName', message: 'What is the name of your controller?' }, { type: 'list', name: 'module', message: 'What is your AngularJS module name?', choices: modules }, { type: 'confirm', name: 'spec', message: 'Do you want to include unit testing?', default: true }], function(answers) { //Init answers.nameDashed = _.slugify(util.getNameProposal()); answers.scriptAppName = _.camelize(answers.nameDashed) + '.' + answers.module; answers.classedName = _.capitalize(_.camelize(answers.fileName)); // console.log('answers:', answers); // test if (answers.spec === true) { gulp.src(__dirname + '/../templates/controller/controller.spec.js') .pipe(template(answers)) .pipe(rename(answers.fileName + '-controller.spec.js')) .pipe(conflict(options.base + options.appDir + '/' + answers.module)) .pipe(gulp.dest(options.base + options.appDir + '/' + answers.module)); gulp.src(__dirname + '/../templates/controller/controller.js') .pipe(template(answers)) .pipe(rename(answers.fileName + '-controller.js')) .pipe(conflict(options.base + options.appDir + '/' + answers.module)) .pipe(gulp.dest(options.base + options.appDir + '/' + answers.module)) .on('finish', function() { done(); }); } else { gulp.src(__dirname + '/../templates/controller/controller.js') .pipe(template(answers)) .pipe(rename(answers.fileName + '-controller.js')) .pipe(conflict(options.base + options.appDir + '/' + answers.module)) .pipe(gulp.dest(options.base + options.appDir + '/' + answers.module)) .on('finish', function() { done(); }); } // //Source // gulp.src(__dirname + '/../templates/controller/controller.js') // .pipe(template(answers)) // .pipe(rename(answers.fileName + '-controller.js')) // .pipe(conflict(options.base + options.appDir + '/' + answers.module)) // .pipe(gulp.dest(options.base + options.appDir + '/' + answers.module)) // .on('finish', function() { // done(); // }); }); }); } })();
mit
mongodb-utils/oid-sort-ids
index.js
775
// this algorithm assumes that `.toHexString()` is the expensive operation. // i don't know if it actually is. module.exports = function (docs, oids) { // we precalculate the array lengths // because we expect to use them all var docids = docs.map(toID) var indexes = docs.map(toIndex) var out = [] var index for (var i = 0; i < oids.length; i++) { index = docids.indexOf(oids[i].toHexString()) if (!~index) continue out.push(docs[indexes[index]]) // never lookup this doc again docids.splice(index, 1) indexes.splice(index, 1) // return early if all docs are accounted for if (!docids.length) return out } return out } function toID(x) { return (x._id || x).toHexString() } function toIndex(a, i) { return i }
mit
tauren/tmpl-precompile
examples/output/templates.js
2545
var templates = templates || {}; templates.level1 = templates.level1 || {}; templates.level1.level2 = templates.level1.level2 || {}; templates.level1.level2.level3 = templates.level1.level2.level3 || {}; function attrs(obj){ var buf = [] , terse = obj.terse; delete obj.terse; var keys = Object.keys(obj) , len = keys.length; if (len) { buf.push(''); for (var i = 0; i < len; ++i) { var key = keys[i] , val = obj[key]; if ('boolean' == typeof val || null == val) { if (val) { terse ? buf.push(key) : buf.push(key + '="' + key + '"'); } } else if ('class' == key && Array.isArray(val)) { buf.push(key + '="' + escape(val.join(' ')) + '"'); } else { buf.push(key + '="' + escape(val) + '"'); } } } return buf.join(' '); } function escape(html){ return String(html) .replace(/&(?!\w+;)/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;'); } var jade = { attrs: attrs, escape: escape }; templates.layout = function anonymous(locals) { var attrs = jade.attrs, escape = jade.escape; var buf = []; with (locals || {}) { var interp; buf.push('<div'); buf.push(attrs({ 'id':('content') })); buf.push('>'); buf.push('<h1>'); buf.push('Hello world!'); buf.push('</h1>'); buf.push('</div>'); } return buf.join(""); }; templates.root = function anonymous(locals) { var attrs = jade.attrs, escape = jade.escape; var buf = []; with (locals || {}) { var interp; buf.push('<h2>'); buf.push('Hello'); buf.push('</h2>'); buf.push('<p>'); buf.push('World!'); buf.push('</p>'); } return buf.join(""); }; templates.level1.root = function anonymous(locals) { var attrs = jade.attrs, escape = jade.escape; var buf = []; with (locals || {}) { var interp; buf.push('<h2>'); buf.push('Hello'); buf.push('</h2>'); buf.push('<p>'); buf.push('World!'); buf.push('</p>'); } return buf.join(""); }; templates.level1.level2.root = function anonymous(locals) { var attrs = jade.attrs, escape = jade.escape; var buf = []; with (locals || {}) { var interp; buf.push('<h2>'); buf.push('Hello'); buf.push('</h2>'); buf.push('<p>'); buf.push('World!'); buf.push('</p>'); } return buf.join(""); }; templates.level1.level2.level3.root = function anonymous(locals) { var attrs = jade.attrs, escape = jade.escape; var buf = []; with (locals || {}) { var interp; buf.push('<h2>'); buf.push('Hello'); buf.push('</h2>'); buf.push('<p>'); buf.push('World!'); buf.push('</p>'); } return buf.join(""); };
mit
guusw/fx2
FX2.Game/Database/DatabaseEventType.cs
356
// Copyright(c) 2016 Guus Waals (guus_waals@live.nl) // Licensed under the MIT License(MIT) // See "LICENSE.txt" for more information namespace FX2.Game.Database { /// <summary> /// The type of change that occured in the database /// </summary> public enum DatabaseEventType { Added, Removed, Changed } }
mit
ecmas/cocos2d
extensions/GUI/CCControlExtension/CCControlSwitch.cpp
13511
/* * Copyright (c) 2012 cocos2d-x.org * http://www.cocos2d-x.org * * Copyright 2012 Yannick Loriot. All rights reserved. * http://yannickloriot.com * * Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. * * 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 "CCControlSwitch.h" #include "2d/CCSprite.h" #include "2d/CCActionTween.h" #include "2d/CCLabel.h" #include "2d/CCClippingNode.h" #include "renderer/ccShaders.h" #include "2d/CCRenderTexture.h" NS_CC_EXT_BEGIN // ControlSwitchSprite class ControlSwitchSprite : public Sprite, public ActionTweenDelegate { public: /** creates an autorelease instance of ControlSwitchSprite */ static ControlSwitchSprite* create( Sprite *maskSprite, Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, Label* onLabel, Label* offLabel); /** * @js NA * @lua NA */ void needsLayout(); /** * @js NA * @lua NA */ void setSliderXPosition(float sliderXPosition); /** * @js NA * @lua NA */ float getSliderXPosition() {return _sliderXPosition;} /** * @js NA * @lua NA */ float onSideWidth(); /** * @js NA * @lua NA */ float offSideWidth(); /** * @js NA * @lua NA */ virtual void updateTweenAction(float value, const std::string& key) override; /** Contains the position (in x-axis) of the slider inside the receiver. */ float _sliderXPosition; CC_SYNTHESIZE(float, _onPosition, OnPosition) CC_SYNTHESIZE(float, _offPosition, OffPosition) CC_SYNTHESIZE_RETAIN(Texture2D*, _maskTexture, MaskTexture) CC_SYNTHESIZE(GLuint, _textureLocation, TextureLocation) CC_SYNTHESIZE(GLuint, _maskLocation, MaskLocation) CC_SYNTHESIZE_RETAIN(Sprite*, _onSprite, OnSprite) CC_SYNTHESIZE_RETAIN(Sprite*, _offSprite, OffSprite) CC_SYNTHESIZE_RETAIN(Sprite*, _thumbSprite, ThumbSprite) CC_SYNTHESIZE_RETAIN(Label*, _onLabel, OnLabel) CC_SYNTHESIZE_RETAIN(Label*, _offLabel, OffLabel) Sprite* _clipperStencil; protected: /** * @js NA * @lua NA */ ControlSwitchSprite(); /** * @js NA * @lua NA */ virtual ~ControlSwitchSprite(); /** * @js NA * @lua NA */ bool initWithMaskSprite( Sprite *maskSprite, Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, Label* onLabel, Label* offLabel); private: CC_DISALLOW_COPY_AND_ASSIGN(ControlSwitchSprite); }; ControlSwitchSprite* ControlSwitchSprite::create(Sprite *maskSprite, Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, Label* onLabel, Label* offLabel) { auto ret = new (std::nothrow) ControlSwitchSprite(); ret->initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel); ret->autorelease(); return ret; } ControlSwitchSprite::ControlSwitchSprite() : _sliderXPosition(0.0f) , _onPosition(0.0f) , _offPosition(0.0f) , _maskTexture(nullptr) , _textureLocation(0) , _maskLocation(0) , _onSprite(nullptr) , _offSprite(nullptr) , _thumbSprite(nullptr) , _onLabel(nullptr) , _offLabel(nullptr) , _clipperStencil(nullptr) { } ControlSwitchSprite::~ControlSwitchSprite() { CC_SAFE_RELEASE(_onSprite); CC_SAFE_RELEASE(_offSprite); CC_SAFE_RELEASE(_thumbSprite); CC_SAFE_RELEASE(_onLabel); CC_SAFE_RELEASE(_offLabel); CC_SAFE_RELEASE(_maskTexture); CC_SAFE_RELEASE(_clipperStencil); } bool ControlSwitchSprite::initWithMaskSprite( Sprite *maskSprite, Sprite *onSprite, Sprite *offSprite, Sprite *thumbSprite, Label* onLabel, Label* offLabel) { if (Sprite::initWithTexture(maskSprite->getTexture())) { // Sets the default values _onPosition = 0; _offPosition = -onSprite->getContentSize().width + thumbSprite->getContentSize().width / 2; _sliderXPosition = _onPosition; setOnSprite(onSprite); setOffSprite(offSprite); setThumbSprite(thumbSprite); setOnLabel(onLabel); setOffLabel(offLabel); ClippingNode* clipper = ClippingNode::create(); _clipperStencil = Sprite::createWithTexture(maskSprite->getTexture()); _clipperStencil->retain(); clipper->setAlphaThreshold(0.1f); clipper->setStencil(_clipperStencil); clipper->addChild(onSprite); clipper->addChild(offSprite); if (onLabel) { clipper->addChild(onLabel); // might be null } if (offLabel) { clipper->addChild(offLabel); // might be null } clipper->addChild(thumbSprite); addChild(clipper); // Set up the mask with the Mask shader setMaskTexture(maskSprite->getTexture()); setContentSize(_maskTexture->getContentSize()); needsLayout(); return true; } return false; } void ControlSwitchSprite::updateTweenAction(float value, const std::string& key) { CCLOGINFO("key = %s, value = %f", key.c_str(), value); setSliderXPosition(value); } void ControlSwitchSprite::needsLayout() { _onSprite->setPosition(_onSprite->getContentSize().width / 2 + _sliderXPosition, _onSprite->getContentSize().height / 2); _offSprite->setPosition(_onSprite->getContentSize().width + _offSprite->getContentSize().width / 2 + _sliderXPosition, _offSprite->getContentSize().height / 2); _thumbSprite->setPosition(_onSprite->getContentSize().width + _sliderXPosition, _maskTexture->getContentSize().height / 2); _clipperStencil->setPosition(_maskTexture->getContentSize().width/2, _maskTexture->getContentSize().height / 2); if (_onLabel) { _onLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE); _onLabel->setPosition(_onSprite->getPosition().x - _thumbSprite->getContentSize().width / 6, _onSprite->getContentSize().height / 2); } if (_offLabel) { _offLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE); _offLabel->setPosition(_offSprite->getPosition().x + _thumbSprite->getContentSize().width / 6, _offSprite->getContentSize().height / 2); } setFlippedY(true); } void ControlSwitchSprite::setSliderXPosition(float sliderXPosition) { if (sliderXPosition <= _offPosition) { // Off sliderXPosition = _offPosition; } else if (sliderXPosition >= _onPosition) { // On sliderXPosition = _onPosition; } _sliderXPosition = sliderXPosition; needsLayout(); } float ControlSwitchSprite::onSideWidth() { return _onSprite->getContentSize().width; } float ControlSwitchSprite::offSideWidth() { return _offSprite->getContentSize().height; } // ControlSwitch ControlSwitch::ControlSwitch() : _switchSprite(nullptr) , _initialTouchXPosition(0.0f) , _moved(false) , _on(false) { } ControlSwitch::~ControlSwitch() { CC_SAFE_RELEASE(_switchSprite); } bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite) { return initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, nullptr, nullptr); } ControlSwitch* ControlSwitch::create(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite) { ControlSwitch* pRet = new (std::nothrow) ControlSwitch(); if (pRet && pRet->initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, nullptr, nullptr)) { pRet->autorelease(); } else { CC_SAFE_DELETE(pRet); } return pRet; } bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, Label* onLabel, Label* offLabel) { if (Control::init()) { CCASSERT(maskSprite, "Mask must not be nil."); CCASSERT(onSprite, "onSprite must not be nil."); CCASSERT(offSprite, "offSprite must not be nil."); CCASSERT(thumbSprite, "thumbSprite must not be nil."); _on = true; _switchSprite = ControlSwitchSprite::create(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel); _switchSprite->retain(); _switchSprite->setPosition(_switchSprite->getContentSize().width / 2, _switchSprite->getContentSize().height / 2); addChild(_switchSprite); setIgnoreAnchorPointForPosition(false); setAnchorPoint(Vec2(0.5f, 0.5f)); setContentSize(_switchSprite->getContentSize()); return true; } return false; } ControlSwitch* ControlSwitch::create(Sprite *maskSprite, Sprite * onSprite, Sprite * offSprite, Sprite * thumbSprite, Label* onLabel, Label* offLabel) { ControlSwitch* pRet = new (std::nothrow) ControlSwitch(); if (pRet && pRet->initWithMaskSprite(maskSprite, onSprite, offSprite, thumbSprite, onLabel, offLabel)) { pRet->autorelease(); } else { CC_SAFE_DELETE(pRet); } return pRet; } void ControlSwitch::setOn(bool isOn) { setOn(isOn, false); } void ControlSwitch::setOn(bool isOn, bool animated) { _on = isOn; if (animated) { _switchSprite->runAction ( ActionTween::create ( 0.2f, "sliderXPosition", _switchSprite->getSliderXPosition(), (_on) ? _switchSprite->getOnPosition() : _switchSprite->getOffPosition() ) ); } else { _switchSprite->setSliderXPosition((_on) ? _switchSprite->getOnPosition() : _switchSprite->getOffPosition()); } sendActionsForControlEvents(Control::EventType::VALUE_CHANGED); } void ControlSwitch::setEnabled(bool enabled) { _enabled = enabled; if (_switchSprite != nullptr) { _switchSprite->setOpacity((enabled) ? 255 : 128); } } Vec2 ControlSwitch::locationFromTouch(Touch* pTouch) { Vec2 touchLocation = pTouch->getLocation(); // Get the touch position touchLocation = this->convertToNodeSpace(touchLocation); // Convert to the node space of this class return touchLocation; } bool ControlSwitch::onTouchBegan(Touch *pTouch, Event* /*pEvent*/) { if (!isTouchInside(pTouch) || !isEnabled() || !isVisible()) { return false; } _moved = false; Vec2 location = this->locationFromTouch(pTouch); _initialTouchXPosition = location.x - _switchSprite->getSliderXPosition(); _switchSprite->getThumbSprite()->setColor(Color3B::GRAY); _switchSprite->needsLayout(); return true; } void ControlSwitch::onTouchMoved(Touch *pTouch, Event* /*pEvent*/) { Vec2 location = this->locationFromTouch(pTouch); location = Vec2(location.x - _initialTouchXPosition, 0); _moved = true; _switchSprite->setSliderXPosition(location.x); } void ControlSwitch::onTouchEnded(Touch *pTouch, Event* /*pEvent*/) { Vec2 location = this->locationFromTouch(pTouch); _switchSprite->getThumbSprite()->setColor(Color3B::WHITE); if (hasMoved()) { setOn(!(location.x < _switchSprite->getContentSize().width / 2), true); } else { setOn(!_on, true); } } void ControlSwitch::onTouchCancelled(Touch *pTouch, Event* /*pEvent*/) { Vec2 location = this->locationFromTouch(pTouch); _switchSprite->getThumbSprite()->setColor(Color3B::WHITE); if (hasMoved()) { setOn(!(location.x < _switchSprite->getContentSize().width / 2), true); } else { setOn(!_on, true); } } NS_CC_EXT_END
mit
maartenbreddels/vaex
bin/make_dropbox_uploader_conf.py
293
__author__ = 'maartenbreddels' import os import sys content = """APPKEY={DB_APPKEY} APPSECRET={DB_APPSECRET} ACCESS_LEVEL=sandbox OAUTH_ACCESS_TOKEN={DB_OAUTH_ACCESS_TOKEN} OAUTH_ACCESS_TOKEN_SECRET={DB_OAUTH_ACCESS_TOKEN_SECRET} """.format(**os.environ) open(sys.argv[1], "w").write(content)
mit
scheuk/somecode2
lib/versioner/simple_version_file_manager.rb
1060
require 'thor' require 'versioner/util' module Versioner class SimpleVersionFileManager < Thor include Versioner::Util attr_accessor :version_file, :related_version_files, :extra_flags def initialize(options) self.version_file = options[:version_file] self.related_version_files = options[:related_version_files] self.extra_flags = options[:extra_flags] end no_commands do def get_version default(File.read(self.version_file), "0.0.0").strip end def set_version(next_release_version) all_version_files.each { |version_file| _set_version(version_file, next_release_version) say "Bumped #{version_file} to #{next_release_version}" } end def _set_version(version_file, next_release_version) File.open(version_file, 'w') { |f| f.write(next_release_version) } end def all_version_files ([self.version_file] + self.related_version_files) end def extra_version_files [] end end end end
mit
inch-ci/inch_ci-web
lib/inch_ci/worker/project/update_info.rb
2001
require 'inch_ci/git_hub_info' module InchCI module Worker module Project # The UpdateInfo worker is responsible for updating a project's # meta information, like homepage and documentation URLs. class UpdateInfo include Sidekiq::Worker # @param uid [String] # @return [void] def self.enqueue(uid) perform_async(uid) end # @api private # @param github_repo_object [] used to directly update a project def perform(uid, github_repo_object = nil) project = Store::FindProject.call(uid) arr = uid.split(':') service_name = arr[0] user_repo_name = arr[1] if service_name == "github" update_via_github(project, user_repo_name, github_repo_object) end end private def update_via_github(project, user_repo_name, github_repo_object = nil) github = github_repo_object || GitHubInfo.repo(user_repo_name) project.name = github.name project.description = github.description project.fork = github.fork? project.homepage_url = github.homepage_url project.source_code_url = github.source_code_url project.documentation_url = github.documentation_url unless project.documentation_url project.language = github.language unless project.language project.languages = github.languages Store::SaveProject.call(project) default_branch = ensure_branch(project, github.default_branch) Store::UpdateDefaultBranch.call(project, default_branch) github.branches.each do |branch_name| ensure_branch(project, branch_name) end rescue Octokit::NotFound end def ensure_branch(project, branch_name) Store::FindBranch.call(project, branch_name) || Store::CreateBranch.call(project, branch_name) end end end end end
mit
agelinazf/egb
time.go
2702
package egb import ( "fmt" "strconv" "time" ) //TimeYear return now year string. //eg:2016 func TimeYear() string { now := time.Now() year, _, _ := now.Date() return fmt.Sprintf("%d", year) } //TimeMonth return now month string. //eg:8 func TimeMonth() string { now := time.Now() _, month, _ := now.Date() return fmt.Sprintf("%d", month) } //TimeDay return now day string. //eg:5 func TimeDay() string { now := time.Now() _, _, day := now.Date() return fmt.Sprintf("%d", day) } //TimeWeekDay return now week day string. //eg:Friday func TimeWeekDay() string { now := time.Now() return fmt.Sprintf("%s", now.Weekday().String()) } //TimeFromUnix return normal format time from unix time string. func TimeFromUnix(unix string) string { i, _ := strconv.ParseInt(unix, 10, 64) str_time := time.Unix(i, 0).Format("2006-01-02 15:04:05") return str_time } //TimeFromUnixNano return normal format time from unix nano time string. func TimeFromUnixNano(unix string) string { i, _ := strconv.ParseInt(unix, 10, 64) str_time := time.Unix(0, i).Format("2006-01-02 15:04:05") return str_time } //TimeNowDate return now date time string. //eg:2016-08-05 15:04:05 func TimeNowDate() string { return time.Now().Format("2006-01-02 15:04:05") } //TimeNowDateDay return now date day time string. //eg:2016-08-05 func TimeNowDateDay() string { return time.Now().Format("2006-01-02") } //TimeNowUnix return now unix time string. func TimeNowUnix() string { return strconv.FormatInt(time.Now().Unix(), 10) } //TimeNowUnixMs return now unix ms time string. func TimeNowUnixMs() string { return StringSubStr(TimeNowUnixNano(), 0, 13) } //TimeNowUnixNano return now unix nano time string. //eg:1471226178 882 997 341 func TimeNowUnixNano() string { return strconv.FormatInt(time.Now().UnixNano(), 10) } //TimeDayToUnix return unix time string by given format-time. //input:2016-08-05 output:1470355200 func TimeDayToUnix(daytime string) string { timeLayout := "2006-01-02" loc, _ := time.LoadLocation("Local") //重要:获取时区 theTime, _ := time.ParseInLocation(timeLayout, daytime, loc) //使用模板在对应时区转化为time.time类型 unix := theTime.Unix() return strconv.FormatInt(unix, 10) } //TimeSecondToUnix return unix time string by given format-time. //input:2016/8/5 15:04:02 output:1470380642 func TimeSecondToUnix(stime string) string { timeLayout := "2006-01-02 15:04:05" loc, _ := time.LoadLocation("Local") //重要:获取时区 theTime, _ := time.ParseInLocation(timeLayout, stime, loc) //使用模板在对应时区转化为time.time类型 unix := theTime.Unix() return strconv.FormatInt(unix, 10) }
mit
Onefootball/onefootball-angular-components
src/components.module.js
254
angular .module('onefootball.components', [ 'onefootball.components.config', 'onefootball.components.services', 'onefootball.components.filters', 'onefootball.components.directives' ]);
mit
bemiriq/schoolsystem
application/views/admin/adminHeader.php
8330
<!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>SB Admin - Bootstrap Admin Template</title> <!-- Bootstrap Core CSS --> <link href="<?=base_url('public/css/bootstrap.min.css')?>" rel="stylesheet"> <!-- Custom CSS --> <link href="<?=base_url('public/css/sb-admin.css')?>" rel="stylesheet"> <!-- Morris Charts CSS --> <link href="<?=base_url('public/css/plugins/morris.css')?>" rel="stylesheet"> <!-- Custom Fonts --> <link href="<?=base_url('public/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> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">SB Admin</a> </div> <!-- Top Menu Items --> <ul class="nav navbar-right top-nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-bell"></i> <b class="caret"></b></a> <ul class="dropdown-menu alert-dropdown"> <li> <a href="#">Alert Name <span class="label label-default">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-primary">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-success">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-info">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-warning">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-danger">Alert Badge</span></a> </li> <li class="divider"></li> <li> <a href="#">View All</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> Admin <b class="caret"></b></a> <ul class="dropdown-menu"> <!-- <li class="divider"></li> --> <li> <a href="<?=site_url('school/logout')?>"><i class="fa fa-fw fa-power-off"></i> Log Out</a> </li> </ul> </li> </ul> <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens --> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <li class="active"> <a href="<?=site_url('school/adminDashboard')?>"><i class="fa fa-fw fa-dashboard"></i> Admin Dashboard</a> </li> <!-- <li> <a href="charts.html"><i class="fa fa-fw fa-bar-chart-o"></i> Charts</a> </li> <li> <a href="tables.html"><i class="fa fa-fw fa-table"></i> Tables</a> </li> <li> <a href="forms.html"><i class="fa fa-fw fa-edit"></i> Forms</a> </li> <li> <a href="bootstrap-elements.html"><i class="fa fa-fw fa-desktop"></i> Bootstrap Elements</a> </li> <li> <a href="bootstrap-grid.html"><i class="fa fa-fw fa-wrench"></i> Bootstrap Grid</a> </li> --> <li> <a href="javascript:;" data-toggle="collapse" data-target="#demo"><i class="fa fa-fw fa-arrows-v"></i> Fee Management <i class="fa fa-fw fa-caret-down"></i></a> <ul id="demo" class="collapse"> <li> <a href="<?=site_url('school/addFee')?>">Add Fee</a> </li> <li> <a href="<?=site_url('school/viewFee')?>">Update & Delete</a> </li> </ul> </li> <li> <a href="javascript:;" data-toggle="collapse" data-target="#demo1"><i class="fa fa-fw fa-arrows-v"></i> Course Management <i class="fa fa-fw fa-caret-down"></i></a> <ul id="demo1" class="collapse"> <li> <a href="<?=site_url('school/addCourse')?>">Add Course</a> </li> <li> <a href="<?=site_url('school/viewCourse')?>">Update & Delete</a> </li> </ul> </li> <li> <a href="javascript:;" data-toggle="collapse" data-target="#demo2"><i class="fa fa-fw fa-arrows-v"></i> Transportation<i class="fa fa-fw fa-caret-down"></i></a> <ul id="demo2" class="collapse"> <li> <a href="<?=site_url('school/addTrans')?>">Add Transportation</a> </li> <li> <a href="<?=site_url('school/viewTrans')?>">Update & Delete</a> </li> </ul> </li> <li> <a href="javascript:;" data-toggle="collapse" data-target="#demo3"><i class="fa fa-fw fa-arrows-v"></i> Hostel Management <i class="fa fa-fw fa-caret-down"></i></a> <ul id="demo3" class="collapse"> <li> <a href="<?=site_url('school/addHostel')?>">Add Hostel</a> </li> <li> <a href="<?=site_url('school/viewHostel')?>">Update & Delete</a> </li> </ul> </li> <li> <a href="<?=site_url('school/information')?>"><i class="fa fa-fw fa-wrench"></i> Information </a> </li> <!-- <li> <a href="blank-page.html"><i class="fa fa-fw fa-file"></i> Blank Page</a> </li> <li> <a href="index-rtl.html"><i class="fa fa-fw fa-dashboard"></i> RTL Dashboard</a> </li> --> </ul> </div> <!-- /.navbar-collapse --> </nav>
mit
tanapi/FirmataTest
app/src/main/java/com/example/firmatatest/ArduinoScenario.java
20341
package com.example.firmatatest; import android.util.Log; import android.util.Xml; import org.shokai.firmata.ArduinoFirmata; import org.xmlpull.v1.XmlPullParser; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Stack; public class ArduinoScenario { final static String TAG = "ArduinoScenario"; public interface ArduinoScenarioCallbacks { public void callbackMethod(int parm); } private ArduinoScenarioCallbacks _ArduinoScenarioCallbacksCallbacks; public void setCallbacks(ArduinoScenarioCallbacks myClassCallbacks){ _ArduinoScenarioCallbacksCallbacks = myClassCallbacks; } public static final int NOP = 0; public static final int RESET = 1; public static final int PIN_MODE = 10; public static final int DIGITAL_WRITE = 100; public static final int DIGITAL_READ = 101; public static final int ANALOG_WRITE = 200; public static final int ANALOG_READ = 201; public static final int SLEEP = 1001; public static final int CALLBACK = 1002; public static final int GOTO = 1003; public static final int LOOP = 1004; public static final int LOOP_END = 1005; public static final int SET = 1051; public static final int SET_ADD = 1052; public static final int SET_SUB = 1053; public static final int SET_MLT = 1054; public static final int SET_DIV = 1055; public static final int SET_MOD = 1056; public static final int IF_EQ = 1100; public static final int IF_NE = 1101; public static final int IF_GT = 1102; public static final int IF_GTE = 1103; public static final int IF_LT = 1104; public static final int IF_LTE = 1105; public static final int ELSE = 1151; public static final int ENDIF = 1152; public static final int DIGITAL_PIN = 0x40000000; public static final int ANALOG_PIN = 0x20000000; public static final int PROGRAM_COUNT = 0x10000000; public static final int LOOP_COUNT = 0x10000001; public static final int LOOP_MAX = 0x10000002; public static final int LOOP_PC = 0x10000003; public static final int ADD = 0x10000004; public static final int SUB = 0x10000005; public static final int MLT = 0x10000006; public static final int DIV = 0x10000007; public static final int MOD = 0x10000008; public static final int VAR = 0x10000010; public static final int VALUE_MASK = 0x0FFFFFFF; private class ScenarioData { public int Command; public int Parm1; public int Parm2; public ScenarioData(int com, int p1, int p2){ this.Command = com; this.Parm1 = p1; this.Parm2 = p2; } } //変数管理クラス private class ScenarioVariable { public int pc; public int loopCnt; public int loopMax; public int loopPc; public Stack<Integer> loopCntStk; public Stack<Integer> loopMaxStk; public Stack<Integer> loopPcStk; public int Add; public int Sub; public int Mlt; public int Div; public int Mod; public ArrayList<Integer> vars = new ArrayList<Integer>(); public ScenarioVariable(){ Clear(); } public void Clear(){ pc = 0; loopCnt = 0; loopMax = 0; loopPc = 0; loopCntStk= new Stack<Integer>(); loopMaxStk = new Stack<Integer>(); loopPcStk = new Stack<Integer>(); Add = 0; Sub = 0; Mlt = 0; Div = 0; Mod = 0; vars.clear(); for(int i=0;i<15;i++){ vars.add(0); } } public int getVar(ArduinoFirmata arduino, int parm){ int val = parm & VALUE_MASK; if(parm>=DIGITAL_PIN + 1 && parm<=DIGITAL_PIN+15){ val = (arduino.digitalRead(parm - DIGITAL_PIN))?1:0; }else if(parm>=ANALOG_PIN+1 && parm<=ANALOG_PIN+15){ val =arduino.analogRead(parm - ANALOG_PIN); }else if(parm>=VAR+1 && parm <=VAR+15) { val = vars.get(parm - (VAR + 1)); }else if(parm == PROGRAM_COUNT){ val = pc; }else if(parm == LOOP_COUNT){ val = loopCnt; }else if(parm == LOOP_MAX){ val = loopMax; }else if(parm == LOOP_PC){ val = loopPc; }else if(parm == ADD){ val = Add; }else if(parm == SUB){ val = Sub; }else if(parm == MLT){ val = Mlt; }else if(parm == DIV){ val = Div; }else if(parm == MOD){ val = Mod; } return val; } public void setVar(int parm, int val){ if(parm>=VAR+1 && parm <=VAR+15) { vars.set(parm - (VAR + 1), val); }else if(parm == ADD){ Add = val; }else if(parm == SUB){ Sub = val; }else if(parm == MLT){ Mlt = val; }else if(parm == DIV){ Div = val; }else if(parm == MOD){ Mod = val; } } public void loopPush(){ loopCntStk.push(loopCnt); loopMaxStk.push(loopMax); loopPcStk.push(loopPc); } public void loopPop(){ loopCnt = loopCntStk.pop(); loopMax = loopMaxStk.pop(); loopPc = loopPcStk.pop(); } } private ArrayList<ScenarioData> ScenarioList = new ArrayList<ScenarioData>(); private ScenarioVariable varStack = new ScenarioVariable(); public ArduinoScenario() { } public void SetScenarioNumber(int No){ //あとでやる } private int com_trans(String txt){ int com = 0; switch (txt) { case "RESET": com = RESET; break; case "PIN_MODE": com = PIN_MODE; break; case "DIGITAL_WRITE": com = DIGITAL_WRITE; break; case "DIGITAL_READ": com = DIGITAL_READ; break; case "ANALOG_WRITE": com = ANALOG_WRITE; break; case "ANALOG_READ": com = ANALOG_READ; break; case "SLEEP": com = SLEEP; break; case "CALLBACK": com = CALLBACK; break; case "GOTO": com = GOTO; break; case "LOOP": com = LOOP; break; case "LOOP_END": com = LOOP_END; break; case "SET": com = SET; break; case "SET_ADD": com = SET_ADD; break; case "SET_SUB": com = SET_SUB; break; case "SET_MLT": com = SET_MLT; break; case "SET_DIV": com = SET_DIV; break; case "SET_MOD": com = SET_MOD; break; case "IF_EQ": com = IF_EQ; break; case "IF_NE": com = IF_NE; break; case "IF_GT": com = IF_GT; break; case "IF_GTE": com = IF_GTE; break; case "IF_LT": com = IF_LT; break; case "IF_LTE": com = IF_LTE; break; case "ELSE": com = ELSE; break; case "ENDIF": com = ENDIF; break; default: com = NOP; break; } return com; } private int parm_trans(String txt){ int p = 0; switch (txt) { case "DIGITAL": p = 100; break; case "OUT": p = 1; break; case "ON": p = 1; break; case "OFF": p = 0; break; case "DIGITAL1": p = DIGITAL_PIN + 1; break; case "DIGITAL2": p = DIGITAL_PIN + 2; break; case "DIGITAL3": p = DIGITAL_PIN + 3; break; case "DIGITAL4": p = DIGITAL_PIN + 4; break; case "DIGITAL5": p = DIGITAL_PIN + 5; break; case "DIGITAL6": p = DIGITAL_PIN + 6; break; case "DIGITAL7": p = DIGITAL_PIN + 7; break; case "DIGITAL8": p = DIGITAL_PIN + 8; break; case "DIGITAL9": p = DIGITAL_PIN + 9; break; case "DIGITAL10": p = DIGITAL_PIN + 10; break; case "DIGITAL11": p = DIGITAL_PIN + 11; break; case "DIGITAL12": p = DIGITAL_PIN + 12; break; case "DIGITAL13": p = DIGITAL_PIN + 13; break; case "DIGITAL14": p = DIGITAL_PIN + 14; break; case "DIGITAL15": p = DIGITAL_PIN + 15; break; case "ANALOG1": p = ANALOG_PIN + 1; break; case "ANALOG2": p = ANALOG_PIN + 2; break; case "ANALOG3": p = ANALOG_PIN + 3; break; case "ANALOG4": p = ANALOG_PIN + 4; break; case "ANALOG5": p = ANALOG_PIN + 5; break; case "ANALOG6": p = ANALOG_PIN + 6; break; case "ANALOG7": p = ANALOG_PIN + 7; break; case "ANALOG8": p = ANALOG_PIN + 8; break; case "ANALOG9": p = ANALOG_PIN + 9; break; case "ANALOG10": p = ANALOG_PIN + 10; break; case "ANALOG11": p = ANALOG_PIN + 11; break; case "ANALOG12": p = ANALOG_PIN + 12; break; case "ANALOG13": p = ANALOG_PIN + 13; break; case "ANALOG14": p = ANALOG_PIN + 14; break; case "ANALOG15": p = ANALOG_PIN + 15; break; case "PROGRAM_COUNT": p = PROGRAM_COUNT; break; case "LOOP_COUNT": p = LOOP_COUNT; break; case "ADD": p = ADD; break; case "SUB": p = SUB; break; case "MLT": p = MLT; break; case "DIV": p = DIV; break; case "MOD": p = MOD; break; case "VAR1": p = VAR + 1; break; case "VAR2": p = VAR + 2; break; case "VAR3": p = VAR + 3; break; case "VAR4": p = VAR + 4; break; case "VAR5": p = VAR + 5; break; case "VAR6": p = VAR + 6; break; case "VAR7": p = VAR + 7; break; case "VAR8": p = VAR + 8; break; case "VAR9": p = VAR + 9; break; case "VAR10": p = VAR + 10; break; case "VAR11": p = VAR + 11; break; case "VAR12": p = VAR + 12; break; case "VAR13": p = VAR + 13; break; case "VAR14": p = VAR + 14; break; case "VAR15": p = VAR + 15; break; default: try { p = Integer.parseInt(txt); } catch (Exception e) { p = 0; } } return p; } public boolean LoadScenario(String xmlStrings){ boolean result = true; ScenarioList.clear(); try { XmlPullParser xpp = Xml.newPullParser(); xpp.setInput(new StringReader(xmlStrings)); int com = 0; int p1 = 0; int p2 = 0; int tagType = 0; for(int xe = xpp.getEventType(); xe != XmlPullParser.END_DOCUMENT; xe = xpp.next()){ switch(xe){ case XmlPullParser.START_TAG: switch(xpp.getName()){ case "command": com = 0; p1 = 0; p2 = 0; tagType = 1; break; case "parm1": tagType = 2; break; case "parm2": tagType = 3; break; case "line": tagType = 999; break; default: tagType = 0; break; } break; case XmlPullParser.TEXT: String txt = xpp.getText(); switch(tagType) { case 1: com = com_trans(txt); break; case 2: p1 = parm_trans(txt); break; case 3: p2 = parm_trans(txt); break; default: break; } break; case XmlPullParser.END_TAG: if(xpp.getName().equals("line")) { ScenarioList.add(new ScenarioData(com, p1, p2)); } tagType = 0; break; default: break; } } } catch (Exception e) { e.printStackTrace(); result = false; } //読み込んだら変数の初期化 varStack.Clear(); return result; } private void jumpIfEnd(){ int nextPc; for(nextPc=varStack.pc+1;nextPc<ScenarioList.size();nextPc++){ if(ScenarioList.get(nextPc).Command == ELSE || ScenarioList.get(nextPc).Command == ENDIF){ break; } } varStack.pc = nextPc; } public boolean ExecScenario(ArduinoFirmata arduino){ if(ScenarioList == null){ return false; } if(ScenarioList.size() > varStack.pc){ ScenarioData sc = ScenarioList.get(varStack.pc); int p1 = varStack.getVar(arduino, sc.Parm1); int p2 = varStack.getVar(arduino, sc.Parm2); Log.v(TAG, "Exec pc=" + varStack.pc +"["+sc.Command+","+p1+","+p2+"]"); switch (sc.Command) { case RESET: arduino.reset(); break; case PIN_MODE: if(p2 == 0) { arduino.pinMode(p1, arduino.INPUT); }else{ arduino.pinMode(p1, arduino.OUTPUT); } break; case DIGITAL_WRITE: arduino.digitalWrite(p1, (p2==0)?false:true); break; case SLEEP: long st = System.currentTimeMillis(); while(true){ if(System.currentTimeMillis() - st > p1){ break; } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } break; case CALLBACK: _ArduinoScenarioCallbacksCallbacks.callbackMethod(p1); break; case GOTO: varStack.pc = p1 -1; break; case LOOP: varStack.loopPush(); varStack.loopCnt = 0; varStack.loopMax = p1; varStack.loopPc = varStack.pc; break; case LOOP_END: if(varStack.loopCnt < varStack.loopMax -1){ varStack.pc = varStack.loopPc; varStack.loopCnt++; }else{ varStack.loopPop(); } break; case SET: varStack.setVar(sc.Parm1, p2); break; case SET_ADD: varStack.setVar(ADD, p1 + p2); break; case SET_SUB: varStack.setVar(SUB, p1 - p2); break; case SET_MLT: varStack.setVar(MLT, p1 * p2); break; case SET_DIV: varStack.setVar(DIV, p1 / p2); break; case SET_MOD: varStack.setVar(MOD, p1 % p2); break; case IF_EQ: if(p1 == p2){ }else{ jumpIfEnd(); } break; case IF_NE: if(p1 != p2){ }else{ jumpIfEnd(); } break; case IF_GT: if(p1 > p2){ }else{ jumpIfEnd(); } break; case IF_GTE: if(p1 >= p2){ }else{ jumpIfEnd(); } break; case IF_LT: if(p1 < p2){ }else{ jumpIfEnd(); } break; case IF_LTE: if(p1 <= p2){ }else{ jumpIfEnd(); } break; case ELSE: jumpIfEnd(); break; case ENDIF: break; default: break; } varStack.pc++; return true; }else{ varStack.pc=0; return false; } } }
mit
wwwbruno/monefy
lib/monefy.rb
2599
require "monefy/converter" require "monefy/matchers" require "monefy/arithmetic" require "monefy/version" # Monefy instance with two attr_reader # # @attr_reader amount [Float] is the quantiy of a currency. # @attr_reader currency [String] is the string correspondent to the currency. class Monefy include Monefy::Converter include Monefy::Matchers include Monefy::Arithmetic attr_reader :amount, :currency # To create a new instance, pass amout and current as parameters # # @param amount [Integer, Float] quantiy of a currency. # @param currency [String] currency key created on `conversion_rates` method. # # @return [Monefy] all currencies conversion rate. # # @example # Monefy.new(50, 'EUR') # => #<Monefy:0x... @amount=50.0, @currency="EUR"> # # See 'self.conversion_rates' methdo before initializa a new instance def initialize(amount, currency) validate_currencies_rates validate_currency(currency) @amount = amount.round(2) @currency = currency self end # Set default currencies and conversion rates # used to calculate conversions. # # Use this method on your initilizer application # config # # @param main_currency [String] main currency. # @param other_currencies [Hash] currencies relatives to main currency with # key with other currency and value with conversion rate. # # @return [Hash] all currencies conversion rate. # # @example # Monefy.conversion_rates('EUR', { # 'USD' => 1.11, # 'Bitcoin' => 0.0047 # }) # => {"USD"=>1.11, "Bitcoin"=>0.0047, "EUR"=>1} def self.conversion_rates(main_currency, other_currencies) @@currencies_rates = other_currencies.merge({ main_currency => 1 }) end # Return Monefy instance string value # # @return [String] currency and amout string. # # @example # Monefy.new(50, 'EUR').to_s # => "50.00 EUR" # "#{Monefy.new(50, 'EUR')}" # => "50.00 EUR" def to_s "#{'%.02f' % amount} #{currency}" end private def validate_currencies_rates return if defined?(@@currencies_rates) && @@currencies_rates.present? raise StandardError, "No conversion rates set" end def validate_currency(currency) return if @@currencies_rates.key? currency raise StandardError, "Invalid currency" end def validate_monefy_instance(monefy) return if monefy.instance_of? Monefy raise StandardError, "Not a Monefy instance" end def currencies_rates @@currencies_rates end def create_new_instace(new_amount, new_currency) self.class.new(new_amount, new_currency) end end
mit
jugstalt/gViewGisOS
gView.Offline.UI/Framework/Offline/UI/Tools/FormSolveConflicts.Designer.cs
7341
namespace gView.Framework.Offline.UI.Tools { partial class FormSolveConflicts { /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom Windows Form-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormSolveConflicts)); this.tvConflicts = new System.Windows.Forms.TreeView(); this.splitter1 = new System.Windows.Forms.Splitter(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.conflictControl1 = new gView.Framework.Offline.UI.Tools.ConflictControl(); this.btnSolve = new System.Windows.Forms.ToolStripButton(); this.btnRemove = new System.Windows.Forms.ToolStripButton(); this.btnHighlight = new System.Windows.Forms.ToolStripButton(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // tvConflicts // this.tvConflicts.AccessibleDescription = null; this.tvConflicts.AccessibleName = null; resources.ApplyResources(this.tvConflicts, "tvConflicts"); this.tvConflicts.BackgroundImage = null; this.tvConflicts.Font = null; this.tvConflicts.HideSelection = false; this.tvConflicts.Name = "tvConflicts"; this.tvConflicts.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvConflicts_AfterSelect); // // splitter1 // this.splitter1.AccessibleDescription = null; this.splitter1.AccessibleName = null; resources.ApplyResources(this.splitter1, "splitter1"); this.splitter1.BackgroundImage = null; this.splitter1.Font = null; this.splitter1.Name = "splitter1"; this.splitter1.TabStop = false; // // toolStrip1 // this.toolStrip1.AccessibleDescription = null; this.toolStrip1.AccessibleName = null; resources.ApplyResources(this.toolStrip1, "toolStrip1"); this.toolStrip1.BackgroundImage = null; this.toolStrip1.Font = null; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnSolve, this.btnRemove, this.toolStripSeparator1, this.btnHighlight}); this.toolStrip1.Name = "toolStrip1"; // // toolStripSeparator1 // this.toolStripSeparator1.AccessibleDescription = null; this.toolStripSeparator1.AccessibleName = null; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); this.toolStripSeparator1.Name = "toolStripSeparator1"; // // conflictControl1 // this.conflictControl1.AccessibleDescription = null; this.conflictControl1.AccessibleName = null; resources.ApplyResources(this.conflictControl1, "conflictControl1"); this.conflictControl1.BackColor = System.Drawing.Color.White; this.conflictControl1.BackgroundImage = null; this.conflictControl1.Conflict = null; this.conflictControl1.Font = null; this.conflictControl1.Name = "conflictControl1"; // // btnSolve // this.btnSolve.AccessibleDescription = null; this.btnSolve.AccessibleName = null; resources.ApplyResources(this.btnSolve, "btnSolve"); this.btnSolve.BackgroundImage = null; this.btnSolve.Image = global::gView.Offline.UI.Properties.Resources.arrow_join; this.btnSolve.Name = "btnSolve"; this.btnSolve.Click += new System.EventHandler(this.btnSolve_Click); // // btnRemove // this.btnRemove.AccessibleDescription = null; this.btnRemove.AccessibleName = null; resources.ApplyResources(this.btnRemove, "btnRemove"); this.btnRemove.BackgroundImage = null; this.btnRemove.Image = global::gView.Offline.UI.Properties.Resources.arrow_divide; this.btnRemove.Name = "btnRemove"; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnHighlight // this.btnHighlight.AccessibleDescription = null; this.btnHighlight.AccessibleName = null; resources.ApplyResources(this.btnHighlight, "btnHighlight"); this.btnHighlight.BackgroundImage = null; this.btnHighlight.Image = global::gView.Offline.UI.Properties.Resources.asterisk_yellow; this.btnHighlight.Name = "btnHighlight"; this.btnHighlight.Click += new System.EventHandler(this.btnHighlight_Click); // // FormSolveConflicts // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = null; this.Controls.Add(this.conflictControl1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.splitter1); this.Controls.Add(this.tvConflicts); this.Font = null; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.Icon = null; this.Name = "FormSolveConflicts"; this.Load += new System.EventHandler(this.FormSolveConflicts_Load); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TreeView tvConflicts; private System.Windows.Forms.Splitter splitter1; private ConflictControl conflictControl1; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton btnSolve; private System.Windows.Forms.ToolStripButton btnRemove; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton btnHighlight; } }
mit
Chunfang/defmod-swpc
example/HF3D/HF3D_fd_plot.py
4766
#!/usr/bin/env python import numpy as np import os, sys, netCDF4 from subprocess import call import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.patches as patches from matplotlib import gridspec font = {'weight' : 'normal', 'size' : 12} matplotlib.rc('font', **font) #fin='out/swpc.fs.v.nc' #nc=netCDF4.Dataset(fin) #x=nc.variables['x'][:] #y=nc.variables['y'][:] #vx=nc.variables['Vx'][:] #vy=nc.variables['Vy'][:] #vz=nc.variables['Vz'][:] #fin='out/swpc.fs.u.nc' #nc=netCDF4.Dataset(fin) #ux=nc.variables['Ux'][:] #uy=nc.variables['Uy'][:] #uz=nc.variables['Uz'][:] #ax=plt.subplot(gs[0]) #plt.contourf(x,y,-vz[it,:,:],20, cmap=plt.cm.rainbow, vmax=1E-2, vmin=-1E-2) #ax=plt.subplot(gs[1]) #plt.contourf(x,y,-uz[it,:,:],20, cmap=plt.cm.rainbow, vmax=1E-3, vmin=-1E-3) path='HF3D_snp' fin=path+'/swpc.xy.v.nc' nc=netCDF4.Dataset(fin) x=nc.variables['x'][:] y=nc.variables['y'][:] t=nc.variables['t'][:] vx_xy=nc.variables['Vx'][:] vy_xy=nc.variables['Vy'][:] vz_xy=nc.variables['Vz'][:] fin=path+'/swpc.xy.u.nc' nc=netCDF4.Dataset(fin) ux_xy=nc.variables['Ux'][:] uy_xy=nc.variables['Uy'][:] uz_xy=nc.variables['Uz'][:] fin=path+'/swpc.xz.v.nc' nc=netCDF4.Dataset(fin) z=nc.variables['z'][:] vx_xz=nc.variables['Vx'][:] vy_xz=nc.variables['Vy'][:] vz_xz=nc.variables['Vz'][:] fin=path+'/swpc.xz.u.nc' nc=netCDF4.Dataset(fin) ux_xz=nc.variables['Ux'][:] uy_xz=nc.variables['Uy'][:] uz_xz=nc.variables['Uz'][:] # Aspect ratios rangex=x.max()-x.min() rangey=y.max()-y.min() rangez=z.max()-z.min() gs = gridspec.GridSpec(2, 2, width_ratios=[1,1],height_ratios=[rangey,rangez]) w=rangex+rangez h=2*rangex width=6.4 height=width*h/w fig=plt.figure() vmax=1.; vmin=1E-5 umax=2.; umin=1E-5 i_scale=5 nplot=vx_xy.shape[0];t_play=15 for it in range(nplot): mappablev = cm.ScalarMappable(cmap=plt.get_cmap('gray'), norm=matplotlib.colors.Normalize(vmin=0, vmax=vmax)) mappableu = cm.ScalarMappable(cmap=plt.get_cmap('gray'), norm=matplotlib.colors.Normalize(vmin=0, vmax=umax)) mappablev.set_array(np.sqrt(vx_xy[i_scale,:,:]**2+vy_xy[i_scale,:,:]**2+vz_xy[i_scale,:,:]**2)-vmin) mappableu.set_array(np.sqrt(ux_xy[i_scale,:,:]**2+uy_xy[i_scale,:,:]**2+uz_xy[i_scale,:,:]**2)-vmin) fig.set_size_inches(height,width, forward=True) ax=plt.subplot(gs[0]) plt.xlabel('x [km]') plt.ylabel('y [km]') plt.contourf(x,y,np.sqrt(vx_xy[it,:,:]**2+vy_xy[it,:,:]**2+vz_xy[it,:,:]**2)-vmin,40, cmap=plt.get_cmap('gray'), vmax=vmax, vmin=0.) ax.xaxis.set_ticks_position('none') ax.add_patch(patches.Rectangle((-24., -32.), 48., 64., fill=False,edgecolor="white",linestyle='dotted')) if True: cbax1 = fig.add_axes([0.08, 1.0, 0.4, 0.02]) plt.colorbar(mappablev,orientation='horizontal',cax=cbax1,format='%1.2g') else: plt.axis('off') #ax.add_patch(patches.Rectangle((-1., -.6), 2.0, 1.2, fill=False,edgecolor="white",linestyle='dotted')) plt.title(r'$||\mathbf{v}||$ [m/s], t=%1.2f [s]'%(t[it])) ax=plt.subplot(gs[1]) #plt.xlabel('x [km]') #plt.ylabel('y [km]') plt.contourf(x,y,np.sqrt(ux_xy[it,:,:]**2+uy_xy[it,:,:]**2+uz_xy[it,:,:]**2)-umin,40, cmap=plt.get_cmap('gray'), vmax=umax, vmin=0.) if True: cbax2 = fig.add_axes([.56, 1.0, 0.4, 0.02]) plt.colorbar(mappableu,orientation='horizontal',cax=cbax2,format='%1.2g') else: plt.axis('off') ax.xaxis.set_ticks_position('none') plt.title(r'$||\mathbf{u}||$ [m], t=%1.2f [s]'%(t[it])) ax=plt.subplot(gs[2]) plt.xlabel('x [km]') plt.ylabel('z [km]') if False: plt.axis('off') plt.contourf(x,-z,np.sqrt(vx_xz[it,:,:]**2+vy_xz[it,:,:]**2+vz_xz[it,:,:]**2)-vmin,40, cmap=plt.get_cmap('gray'), vmax=vmax, vmin=0.) ax.xaxis.set_ticks_position('none') ax.add_patch(patches.Rectangle((-24., -32.), 48., 33., fill=False,edgecolor="white",linestyle='dotted')) #plt.colorbar(mappablev,orientation='vertical') #ax.add_patch(patches.Rectangle((-1., -3.7), 2.0, .7, fill=False,edgecolor="white",linestyle='dotted')) ax=plt.subplot(gs[3]) #plt.xlabel('x [km]') #plt.ylabel('z [km]') if False: plt.axis('off') plt.contourf(x,-z,np.sqrt(ux_xz[it,:,:]**2+uy_xz[it,:,:]**2+uz_xz[it,:,:]**2)-umin,40, cmap=plt.get_cmap('gray'), vmax=umax, vmin=0.) ax.xaxis.set_ticks_position('none') #plt.colorbar(mappableu,orientation='vertical') if it==0: plt.tight_layout() fig.savefig(path+'/wav_%d.png'%(it),bbox_inches='tight') plt.clf() os.chdir(path) call(['avconv','-r',str(nplot/t_play),'-i','wav_%d.png','-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2','fd_wav.mov']) call(['mv', 'fd_wav.mov', '../HF3D_fd_wav.mov']) call(['mv', 'wav_0.png', '../'+'HF3D_fd_wav.png']) os.chdir('../')
mit
debasishdebs/Scarlett-PA
ScarlettHome/AlwaysOnKeyboard.py
381
from brain import brain name = "Debasish" class AlwaysOnKeyboard(object): def __init__(self): pass def listen_keyboard(self): message = raw_input("Hi {}. How can I help you?") return message def start(self): msg = self.listen_keyboard() ret = brain(name, msg) if not ret: return ret return msg
mit
intel-hpdd/GUI
source/iml/user/user-reducer.js
540
// @flow // // Copyright (c) 2018 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. export const ADD_USER_ITEMS = "ADD_USER_ITEMS"; import Immutable from "seamless-immutable"; import type { ActionT } from "../store/store-module.js"; export default function(state: Array<Object> = Immutable([]), { type, payload }: ActionT): Array<Object> { switch (type) { case ADD_USER_ITEMS: return Immutable(payload); default: return state; } }
mit
neolfdev/dlscxx
java_core_src/src/cn/org/rapid_framework/util/holder/BeanValidatorHolder.java
3326
package cn.org.rapid_framework.util.holder; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.Validator; import javax.validation.metadata.BeanDescriptor; import org.springframework.beans.factory.InitializingBean; /** * 用于持有JSR303 Validator(Hibernate Validator),使调用Validator可以当静态方法使用. * * <pre> * static 方法调用: * BeanValidatorHolder.validate(object); * </pre> * <pre> * spring配置: * &lt;bean class="cn.org.rapid_framework.beanvalidation.BeanValidatorHolder"> * &lt;preperty name="validator" ref="validator"/> * &lt;/bean> * </pre> * @author badqiu * */ public class BeanValidatorHolder implements InitializingBean{ private static Validator validator; public void afterPropertiesSet() throws Exception { if(validator == null) throw new IllegalStateException("not found JSR303(HibernateValidator) 'validator' for BeanValidatorHolder "); } public void setValidator(Validator v) { if(validator != null) { throw new IllegalStateException("BeanValidatorHolder already holded 'validator'"); } validator = v; } public static Validator getValidator() { if(validator == null) throw new IllegalStateException("'validator' property is null,BeanValidatorHolder not yet init."); return validator; } public static final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) { return getValidator().validate(object, groups); } public static final <T> void validate(T object) throws ConstraintViolationException { Set constraintViolations = getValidator().validate(object); String msg = "validate failure on object:"+object.getClass().getSimpleName(); throw new ConstraintViolationException(msg,constraintViolations); } public static final <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) { return getValidator().validateProperty(object, propertyName,groups); } public static final <T> void validateProperty(T object, String propertyName) throws ConstraintViolationException { Set constraintViolations = getValidator().validateProperty(object, propertyName); String msg = "validate property failure on object:"+object.getClass().getSimpleName()+"."+propertyName+""; throw new ConstraintViolationException(msg,constraintViolations); } public static final <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) { return getValidator().validateValue(beanType, propertyName,value,groups); } public static final <T> void validateValue(Class<T> beanType, String propertyName, Object value) throws ConstraintViolationException { Set constraintViolations = getValidator().validateValue(beanType, propertyName,value); String msg = "validate value failure on object:"+beanType.getSimpleName()+"."+propertyName+" value:"+value; throw new ConstraintViolationException(msg,constraintViolations); } public static final BeanDescriptor getConstraintsForClass(Class<?> clazz) { return getValidator().getConstraintsForClass(clazz); } public static final <T> T unwrap(Class<T> type) { return getValidator().unwrap(type); } public static void cleanHolder() { validator = null; } }
mit
molinch/SQLite.Net-PCL
src/SQLite.Net/SQLiteConnection.cs
69665
// // Copyright (c) 2012 Krueger Systems, Inc. // Copyright (c) 2013 Øystein Krog (oystein.krog@gmail.com) // // 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. // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading; using JetBrains.Annotations; using SQLite.Net.Attributes; using SQLite.Net.Interop; namespace SQLite.Net { /// <summary> /// Represents an open connection to a SQLite database. /// </summary> [PublicAPI] public class SQLiteConnection : IDisposable { internal static readonly IDbHandle NullHandle = default(IDbHandle); /// <summary> /// Used to list some code that we want the MonoTouch linker /// to see, but that we never want to actually execute. /// </summary> #pragma warning disable 649 private static bool _preserveDuringLinkMagic; #pragma warning restore 649 private readonly Random _rand = new Random(); private readonly IDictionary<string, TableMapping> _tableMappings; private readonly object _tableMappingsLocks; private TimeSpan _busyTimeout; private long _elapsedMilliseconds; private IDictionary<TableMapping, ActiveInsertCommand> _insertCommandCache; private bool _open; private IStopwatch _sw; private int _transactionDepth; static SQLiteConnection() { if (_preserveDuringLinkMagic) { // ReSharper disable once UseObjectOrCollectionInitializer var ti = new ColumnInfo(); ti.Name = "magic"; } } /// <summary> /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. /// </summary> /// <param name="sqlitePlatform"></param> /// <param name="databasePath"> /// Specifies the path to the database file. /// </param> /// <param name="storeDateTimeAsTicks"> /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You /// absolutely do want to store them as Ticks in all new projects. The option to set false is /// only here for backwards compatibility. There is a *significant* speed advantage, with no /// down sides, when setting storeDateTimeAsTicks = true. /// </param> /// <param name="serializer"> /// Blob serializer to use for storing undefined and complex data structures. If left null /// these types will thrown an exception as usual. /// </param> /// <param name="tableMappings"> /// Exisiting table mapping that the connection can use. If its null, it creates the mappings, /// if and when required. The mappings are also created when an unknown type is used for the first /// time. /// </param> /// <param name="extraTypeMappings"> /// Any extra type mappings that you wish to use for overriding the default for creating /// column definitions for SQLite DDL in the class Orm (snake in Swedish). /// </param> /// <param name="resolver"> /// A contract resovler for resolving interfaces to concreate types during object creation /// </param> [PublicAPI] public SQLiteConnection([JetBrains.Annotations.NotNull] ISQLitePlatform sqlitePlatform, [JetBrains.Annotations.NotNull] string databasePath, bool storeDateTimeAsTicks = true, [CanBeNull] IBlobSerializer serializer = null, [CanBeNull] IDictionary<string, TableMapping> tableMappings = null, [CanBeNull] IDictionary<Type, string> extraTypeMappings = null, [CanBeNull] IContractResolver resolver = null) : this(sqlitePlatform, databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks, serializer, tableMappings, extraTypeMappings, resolver) { } /// <summary> /// Constructs a new SQLiteConnection and opens a SQLite database specified by databasePath. /// </summary> /// <param name="sqlitePlatform"></param> /// <param name="databasePath"> /// Specifies the path to the database file. /// </param> /// <param name="openFlags"></param> /// <param name="storeDateTimeAsTicks"> /// Specifies whether to store DateTime properties as ticks (true) or strings (false). You /// absolutely do want to store them as Ticks in all new projects. The option to set false is /// only here for backwards compatibility. There is a *significant* speed advantage, with no /// down sides, when setting storeDateTimeAsTicks = true. /// </param> /// <param name="serializer"> /// Blob serializer to use for storing undefined and complex data structures. If left null /// these types will thrown an exception as usual. /// </param> /// <param name="tableMappings"> /// Exisiting table mapping that the connection can use. If its null, it creates the mappings, /// if and when required. The mappings are also created when an unknown type is used for the first /// time. /// </param> /// <param name="extraTypeMappings"> /// Any extra type mappings that you wish to use for overriding the default for creating /// column definitions for SQLite DDL in the class Orm (snake in Swedish). /// </param> /// <param name="resolver"> /// A contract resovler for resolving interfaces to concreate types during object creation /// </param> [PublicAPI] public SQLiteConnection([JetBrains.Annotations.NotNull] ISQLitePlatform sqlitePlatform, string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true, [CanBeNull] IBlobSerializer serializer = null, [CanBeNull] IDictionary<string, TableMapping> tableMappings = null, [CanBeNull] IDictionary<Type, string> extraTypeMappings = null, IContractResolver resolver = null) { if (sqlitePlatform == null) { throw new ArgumentNullException("sqlitePlatform"); } ExtraTypeMappings = extraTypeMappings ?? new Dictionary<Type, string>(); Serializer = serializer; Platform = sqlitePlatform; Resolver = resolver ?? ContractResolver.Current; _tableMappings = tableMappings ?? new Dictionary<string, TableMapping>(); _tableMappingsLocks = new object(); if (string.IsNullOrEmpty(databasePath)) { throw new ArgumentException("Must be specified", "databasePath"); } DatabasePath = databasePath; IDbHandle handle; var databasePathAsBytes = GetNullTerminatedUtf8(DatabasePath); var r = Platform.SQLiteApi.Open(databasePathAsBytes, out handle, (int) openFlags, IntPtr.Zero); Handle = handle; if (r != Result.OK) { throw SQLiteException.New(r, string.Format("Could not open database file: {0} ({1})", DatabasePath, r)); } if (handle == null) { throw new NullReferenceException("Database handle is null"); } Handle = handle; _open = true; StoreDateTimeAsTicks = storeDateTimeAsTicks; BusyTimeout = TimeSpan.FromSeconds(0.1); } [CanBeNull, PublicAPI] public IBlobSerializer Serializer { get; private set; } [CanBeNull, PublicAPI] public IDbHandle Handle { get; private set; } [JetBrains.Annotations.NotNull, PublicAPI] public string DatabasePath { get; private set; } [PublicAPI] public bool TimeExecution { get; set; } [CanBeNull] [PublicAPI] public ITraceListener TraceListener { get; set; } [PublicAPI] public bool StoreDateTimeAsTicks { get; private set; } [JetBrains.Annotations.NotNull, PublicAPI] public IDictionary<Type, string> ExtraTypeMappings { get; private set; } [JetBrains.Annotations.NotNull, PublicAPI] public IContractResolver Resolver { get; private set; } /// <summary> /// Sets a busy handler to sleep the specified amount of time when a table is locked. /// The handler will sleep multiple times until a total time of <see cref="BusyTimeout" /> has accumulated. /// </summary> [PublicAPI] public TimeSpan BusyTimeout { get { return _busyTimeout; } set { _busyTimeout = value; if (Handle != NullHandle) { Platform.SQLiteApi.BusyTimeout(Handle, (int) _busyTimeout.TotalMilliseconds); } } } /// <summary> /// Returns the mappings from types to tables that the connection /// currently understands. /// </summary> [PublicAPI] [JetBrains.Annotations.NotNull] public IEnumerable<TableMapping> TableMappings { get { lock (_tableMappingsLocks) { return _tableMappings.Values.ToList(); } } } /// <summary> /// Whether <see cref="BeginTransaction" /> has been called and the database is waiting for a <see cref="Commit" />. /// </summary> [PublicAPI] public bool IsInTransaction { get { return _transactionDepth > 0; } } [JetBrains.Annotations.NotNull, PublicAPI] public ISQLitePlatform Platform { get; private set; } [PublicAPI] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [PublicAPI] public void EnableLoadExtension(int onoff) { var r = Platform.SQLiteApi.EnableLoadExtension(Handle, onoff); if (r != Result.OK) { var msg = Platform.SQLiteApi.Errmsg16(Handle); throw SQLiteException.New(r, msg); } } [JetBrains.Annotations.NotNull] private static byte[] GetNullTerminatedUtf8(string s) { var utf8Length = Encoding.UTF8.GetByteCount(s); var bytes = new byte[utf8Length + 1]; Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0); return bytes; } /// <summary> /// Retrieves the mapping that is automatically generated for the given type. /// </summary> /// <param name="type"> /// The type whose mapping to the database is returned. /// </param> /// <param name="createFlags"> /// Optional flags allowing implicit PK and indexes based on naming conventions /// </param> /// <returns> /// The mapping represents the schema of the columns of the database and contains /// methods to set and get properties of objects. /// </returns> [PublicAPI] public TableMapping GetMapping(Type type, CreateFlags createFlags = CreateFlags.None) { lock (_tableMappingsLocks) { TableMapping map; return _tableMappings.TryGetValue(type.FullName, out map) ? map : CreateAndSetMapping(type, createFlags, _tableMappings); } } private TableMapping CreateAndSetMapping(Type type, CreateFlags createFlags, IDictionary<string, TableMapping> mapTable) { var props = Platform.ReflectionService.GetPublicInstanceProperties(type); var map = new TableMapping(type, props, createFlags); mapTable[type.FullName] = map; return map; } /// <summary> /// Retrieves the mapping that is automatically generated for the given type. /// </summary> /// <returns> /// The mapping represents the schema of the columns of the database and contains /// methods to set and get properties of objects. /// </returns> [PublicAPI] public TableMapping GetMapping<T>() { return GetMapping(typeof (T)); } /// <summary> /// Executes a "drop table" on the database. This is non-recoverable. /// </summary> [PublicAPI] public int DropTable<T>() { return DropTable(typeof (T)); } /// <summary> /// Executes a "drop table" on the database. This is non-recoverable. /// </summary> [PublicAPI] public int DropTable(Type t) { var map = GetMapping(t); var query = string.Format("drop table if exists \"{0}\"", map.TableName); return Execute(query); } /// <summary> /// Executes a "create table if not exists" on the database. It also /// creates any specified indexes on the columns of the table. It uses /// a schema automatically generated from the specified type. You can /// later access this schema by calling GetMapping. /// </summary> /// <returns> /// The number of entries added to the database schema. /// </returns> [PublicAPI] public int CreateTable<T>(CreateFlags createFlags = CreateFlags.None) { return CreateTable(typeof (T), createFlags); } /// <summary> /// Executes a "create table if not exists" on the database. It also /// creates any specified indexes on the columns of the table. It uses /// a schema automatically generated from the specified type. You can /// later access this schema by calling GetMapping. /// </summary> /// <param name="ty">Type to reflect to a database table.</param> /// <param name="createFlags">Optional flags allowing implicit PK and indexes based on naming conventions.</param> /// <returns> /// The number of entries added to the database schema. /// </returns> [PublicAPI] public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None) { var map = GetMapping(ty, createFlags); var query = "create table if not exists \"" + map.TableName + "\"(\n"; var mapColumns = map.Columns; if (!mapColumns.Any()) { throw new Exception("Table has no (public) columns"); } var decls = mapColumns.Select(p => Orm.SqlDecl(p, StoreDateTimeAsTicks, Serializer, ExtraTypeMappings)); var decl = string.Join(",\n", decls.ToArray()); query += decl; query += ")"; var count = Execute(query); if (count == 0) { //Possible bug: This always seems to return 0? // Table already exists, migrate it MigrateTable(map); } var indexes = new Dictionary<string, IndexInfo>(); foreach (var c in mapColumns) { foreach (var i in c.Indices) { var iname = i.Name ?? map.TableName + "_" + c.Name; IndexInfo iinfo; if (!indexes.TryGetValue(iname, out iinfo)) { iinfo = new IndexInfo { IndexName = iname, TableName = map.TableName, Unique = i.Unique, Columns = new List<IndexedColumn>() }; indexes.Add(iname, iinfo); } if (i.Unique != iinfo.Unique) { throw new Exception( "All the columns in an index must have the same value for their Unique property"); } iinfo.Columns.Add(new IndexedColumn { Order = i.Order, ColumnName = c.Name }); } } foreach (var indexName in indexes.Keys) { var index = indexes[indexName]; var columns = index.Columns.OrderBy(i => i.Order).Select(i => i.ColumnName).ToArray(); count += CreateIndex(indexName, index.TableName, columns, index.Unique); } return count; } /// <summary> /// Creates an index for the specified table and columns. /// </summary> /// <param name="indexName">Name of the index to create</param> /// <param name="tableName">Name of the database table</param> /// <param name="columnNames">An array of column names to index</param> /// <param name="unique">Whether the index should be unique</param> [PublicAPI] public int CreateIndex(string indexName, string tableName, string[] columnNames, bool unique = false) { const string sqlFormat = "create {2} index if not exists \"{3}\" on \"{0}\"(\"{1}\")"; var sql = string.Format(sqlFormat, tableName, string.Join("\", \"", columnNames), unique ? "unique" : "", indexName); return Execute(sql); } /// <summary> /// Creates an index for the specified table and column. /// </summary> /// <param name="indexName">Name of the index to create</param> /// <param name="tableName">Name of the database table</param> /// <param name="columnName">Name of the column to index</param> /// <param name="unique">Whether the index should be unique</param> [PublicAPI] public int CreateIndex(string indexName, string tableName, string columnName, bool unique = false) { return CreateIndex(indexName, tableName, new[] {columnName}, unique); } /// <summary> /// Creates an index for the specified table and column. /// </summary> /// <param name="tableName">Name of the database table</param> /// <param name="columnName">Name of the column to index</param> /// <param name="unique">Whether the index should be unique</param> [PublicAPI] public int CreateIndex(string tableName, string columnName, bool unique = false) { return CreateIndex(tableName + "_" + columnName, tableName, columnName, unique); } /// <summary> /// Creates an index for the specified table and columns. /// </summary> /// <param name="tableName">Name of the database table</param> /// <param name="columnNames">An array of column names to index</param> /// <param name="unique">Whether the index should be unique</param> [PublicAPI] public int CreateIndex(string tableName, string[] columnNames, bool unique = false) { return CreateIndex(tableName + "_" + string.Join("_", columnNames), tableName, columnNames, unique); } /// <summary> /// Creates an index for the specified object property. /// e.g. CreateIndex{Client}(c => c.Name); /// </summary> /// <typeparam name="T">Type to reflect to a database table.</typeparam> /// <param name="property">Property to index</param> /// <param name="unique">Whether the index should be unique</param> [PublicAPI] public void CreateIndex<T>(Expression<Func<T, object>> property, bool unique = false) { MemberExpression mx; if (property.Body.NodeType == ExpressionType.Convert) { mx = ((UnaryExpression) property.Body).Operand as MemberExpression; } else { mx = (property.Body as MemberExpression); } if (mx == null) { throw new ArgumentException("Expression is not supported", "property"); } var propertyInfo = mx.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException("The lambda expression 'property' should point to a valid Property"); } var propName = propertyInfo.Name; var map = GetMapping<T>(); var colName = map.FindColumnWithPropertyName(propName).Name; CreateIndex(map.TableName, colName, unique); } [PublicAPI] public List<ColumnInfo> GetTableInfo(string tableName) { var query = "pragma table_info(\"" + tableName + "\")"; return Query<ColumnInfo>(query); } [PublicAPI] public void MigrateTable<T>() { MigrateTable(typeof(T)); } [PublicAPI] public void MigrateTable(Type t) { var map = GetMapping(t); MigrateTable(map); } private void MigrateTable(TableMapping map) { var existingCols = GetTableInfo(map.TableName); var toBeAdded = new List<TableMapping.Column>(); foreach (var p in map.Columns) { var found = false; foreach (var c in existingCols) { found = (string.Compare(p.Name, c.Name, StringComparison.OrdinalIgnoreCase) == 0); if (found) { break; } } if (!found) { toBeAdded.Add(p); } } foreach (var p in toBeAdded) { var addCol = "alter table \"" + map.TableName + "\" add column " + Orm.SqlDecl(p, StoreDateTimeAsTicks, Serializer, ExtraTypeMappings); Execute(addCol); } } /// <summary> /// Creates a new SQLiteCommand. Can be overridden to provide a sub-class. /// </summary> /// <seealso cref="SQLiteCommand.OnInstanceCreated" /> [PublicAPI] protected virtual SQLiteCommand NewCommand() { return new SQLiteCommand(Platform, this); } /// <summary> /// Creates a new SQLiteCommand given the command text with arguments. Place a '?' /// in the command text for each of the arguments. /// </summary> /// <param name="cmdText"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the command text. /// </param> /// <returns> /// A <see cref="SQLiteCommand" /> /// </returns> [PublicAPI] public SQLiteCommand CreateCommand(string cmdText, params object[] args) { if (!_open) { throw SQLiteException.New(Result.Error, "Cannot create commands from unopened database"); } var cmd = NewCommand(); cmd.CommandText = cmdText; foreach (var o in args) { cmd.Bind(o); } return cmd; } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// Use this method instead of Query when you don't expect rows back. Such cases include /// INSERTs, UPDATEs, and DELETEs. /// You can set the Trace or TimeExecution properties of the connection /// to profile execution. /// </summary> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// The number of rows modified in the database as a result of this execution. /// </returns> [PublicAPI] public int Execute(string query, params object[] args) { var cmd = CreateCommand(query, args); if (TimeExecution) { if (_sw == null) { _sw = Platform.StopwatchFactory.Create(); } _sw.Reset(); _sw.Start(); } var r = cmd.ExecuteNonQuery(); if (TimeExecution) { _sw.Stop(); _elapsedMilliseconds += _sw.ElapsedMilliseconds; TraceListener.WriteLine("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds/1000.0); } return r; } [PublicAPI] public T ExecuteScalar<T>(string query, params object[] args) { var cmd = CreateCommand(query, args); if (TimeExecution) { if (_sw == null) { _sw = Platform.StopwatchFactory.Create(); } _sw.Reset(); _sw.Start(); } var r = cmd.ExecuteScalar<T>(); if (TimeExecution) { _sw.Stop(); _elapsedMilliseconds += _sw.ElapsedMilliseconds; TraceListener.WriteLine("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds/1000.0); } return r; } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// It returns each row of the result using the mapping automatically generated for /// the given type. /// </summary> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// An enumerable with one result for each row returned by the query. /// </returns> [PublicAPI] public List<T> Query<T>(string query, params object[] args) where T : class { var cmd = CreateCommand(query, args); return cmd.ExecuteQuery<T>(); } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// It returns each row of the result using the mapping automatically generated for /// the given type. /// </summary> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// An enumerable with one result for each row returned by the query. /// The enumerator will call sqlite3_step on each call to MoveNext, so the database /// connection must remain open for the lifetime of the enumerator. /// </returns> [PublicAPI] public IEnumerable<T> DeferredQuery<T>(string query, params object[] args) where T : class { var cmd = CreateCommand(query, args); return cmd.ExecuteDeferredQuery<T>(); } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// It returns each row of the result using the specified mapping. This function is /// only used by libraries in order to query the database via introspection. It is /// normally not used. /// </summary> /// <param name="map"> /// A <see cref="TableMapping" /> to use to convert the resulting rows /// into objects. /// </param> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// An enumerable with one result for each row returned by the query. /// </returns> [PublicAPI] public List<object> Query(TableMapping map, string query, params object[] args) { var cmd = CreateCommand(query, args); return cmd.ExecuteQuery<object>(map); } /// <summary> /// Creates a SQLiteCommand given the command text (SQL) with arguments. Place a '?' /// in the command text for each of the arguments and then executes that command. /// It returns each row of the result using the specified mapping. This function is /// only used by libraries in order to query the database via introspection. It is /// normally not used. /// </summary> /// <param name="map"> /// A <see cref="TableMapping" /> to use to convert the resulting rows /// into objects. /// </param> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// An enumerable with one result for each row returned by the query. /// The enumerator will call sqlite3_step on each call to MoveNext, so the database /// connection must remain open for the lifetime of the enumerator. /// </returns> [PublicAPI] public IEnumerable<object> DeferredQuery(TableMapping map, string query, params object[] args) { var cmd = CreateCommand(query, args); return cmd.ExecuteDeferredQuery<object>(map); } /// <summary> /// Returns a queryable interface to the table represented by the given type. /// </summary> /// <returns> /// A queryable object that is able to translate Where, OrderBy, and Take /// queries into native SQL. /// </returns> [PublicAPI] public TableQuery<T> Table<T>() where T : class { return new TableQuery<T>(Platform, this); } /// <summary> /// Attempts to retrieve an object with the given primary key from the table /// associated with the specified type. Use of this method requires that /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). /// </summary> /// <param name="pk"> /// The primary key. /// </param> /// <returns> /// The object with the given primary key. Throws a not found exception /// if the object is not found. /// </returns> [PublicAPI] public T Get<T>(object pk) where T : class { var map = GetMapping(typeof (T)); return Query<T>(map.GetByPrimaryKeySql, pk).First(); } /// <summary> /// Attempts to retrieve the first object that matches the predicate from the table /// associated with the specified type. /// </summary> /// <param name="predicate"> /// A predicate for which object to find. /// </param> /// <returns> /// The object that matches the given predicate. Throws a not found exception /// if the object is not found. /// </returns> [PublicAPI] public T Get<T>(Expression<Func<T, bool>> predicate) where T : class { return Table<T>().Where(predicate).First(); } /// <summary> /// Attempts to retrieve an object with the given primary key from the table /// associated with the specified type. Use of this method requires that /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). /// </summary> /// <param name="pk"> /// The primary key. /// </param> /// <returns> /// The object with the given primary key or null /// if the object is not found. /// </returns> [PublicAPI] public T Find<T>(object pk) where T : class { var map = GetMapping(typeof (T)); return Query<T>(map.GetByPrimaryKeySql, pk).FirstOrDefault(); } /// <summary> /// Attempts to retrieve the first object that matches the query from the table /// associated with the specified type. /// </summary> /// <param name="query"> /// The fully escaped SQL. /// </param> /// <param name="args"> /// Arguments to substitute for the occurences of '?' in the query. /// </param> /// <returns> /// The object that matches the given predicate or null /// if the object is not found. /// </returns> [PublicAPI] public T FindWithQuery<T>(string query, params object[] args) where T : class { return Query<T>(query, args).FirstOrDefault(); } /// <summary> /// Attempts to retrieve an object with the given primary key from the table /// associated with the specified type. Use of this method requires that /// the given type have a designated PrimaryKey (using the PrimaryKeyAttribute). /// </summary> /// <param name="pk"> /// The primary key. /// </param> /// <param name="map"> /// The TableMapping used to identify the object type. /// </param> /// <returns> /// The object with the given primary key or null /// if the object is not found. /// </returns> [PublicAPI] public object Find(object pk, TableMapping map) { return Query(map, map.GetByPrimaryKeySql, pk).FirstOrDefault(); } /// <summary> /// Attempts to retrieve the first object that matches the predicate from the table /// associated with the specified type. /// </summary> /// <param name="predicate"> /// A predicate for which object to find. /// </param> /// <returns> /// The object that matches the given predicate or null /// if the object is not found. /// </returns> [PublicAPI] public T Find<T>(Expression<Func<T, bool>> predicate) where T : class { return Table<T>().Where(predicate).FirstOrDefault(); } /// <summary> /// Begins a new transaction. Call <see cref="Commit" /> to end the transaction. /// </summary> /// <example cref="System.InvalidOperationException">Throws if a transaction has already begun.</example> [PublicAPI] public void BeginTransaction() { // The BEGIN command only works if the transaction stack is empty, // or in other words if there are no pending transactions. // If the transaction stack is not empty when the BEGIN command is invoked, // then the command fails with an error. // Rather than crash with an error, we will just ignore calls to BeginTransaction // that would result in an error. if (Interlocked.CompareExchange(ref _transactionDepth, 1, 0) == 0) { try { Execute("begin transaction"); } catch (Exception ex) { var sqlExp = ex as SQLiteException; if (sqlExp != null) { // It is recommended that applications respond to the errors listed below // by explicitly issuing a ROLLBACK command. // TODO: This rollback failsafe should be localized to all throw sites. switch (sqlExp.Result) { case Result.IOError: case Result.Full: case Result.Busy: case Result.NoMem: case Result.Interrupt: RollbackTo(null, true); break; } } else { // Call decrement and not VolatileWrite in case we've already // created a transaction point in SaveTransactionPoint since the catch. Interlocked.Decrement(ref _transactionDepth); } throw; } } else { // Calling BeginTransaction on an already open transaction is invalid throw new InvalidOperationException("Cannot begin a transaction while already in a transaction."); } } /// <summary> /// Creates a savepoint in the database at the current point in the transaction timeline. /// Begins a new transaction if one is not in progress. /// Call <see cref="RollbackTo" /> to undo transactions since the returned savepoint. /// Call <see cref="Release" /> to commit transactions after the savepoint returned here. /// Call <see cref="Commit" /> to end the transaction, committing all changes. /// </summary> /// <returns>A string naming the savepoint.</returns> [PublicAPI] public string SaveTransactionPoint() { var depth = Interlocked.Increment(ref _transactionDepth) - 1; var retVal = "S" + _rand.Next(short.MaxValue) + "D" + depth; try { Execute("savepoint " + retVal); } catch (Exception ex) { var sqlExp = ex as SQLiteException; if (sqlExp != null) { // It is recommended that applications respond to the errors listed below // by explicitly issuing a ROLLBACK command. // TODO: This rollback failsafe should be localized to all throw sites. switch (sqlExp.Result) { case Result.IOError: case Result.Full: case Result.Busy: case Result.NoMem: case Result.Interrupt: RollbackTo(null, true); break; } } else { Interlocked.Decrement(ref _transactionDepth); } throw; } return retVal; } /// <summary> /// Rolls back the transaction that was begun by <see cref="BeginTransaction" /> or <see cref="SaveTransactionPoint" /> /// . /// </summary> [PublicAPI] public void Rollback() { RollbackTo(null, false); } /// <summary> /// Rolls back the savepoint created by <see cref="BeginTransaction" /> or SaveTransactionPoint. /// </summary> /// <param name="savepoint"> /// The name of the savepoint to roll back to, as returned by <see cref="SaveTransactionPoint" />. /// If savepoint is null or empty, this method is equivalent to a call to <see cref="Rollback" /> /// </param> [PublicAPI] public void RollbackTo(string savepoint) { RollbackTo(savepoint, false); } /// <summary> /// Rolls back the transaction that was begun by <see cref="BeginTransaction" />. /// </summary> /// <param name="savepoint">the savepoint name/key</param> /// <param name="noThrow">true to avoid throwing exceptions, false otherwise</param> private void RollbackTo(string savepoint, bool noThrow) { // Rolling back without a TO clause rolls backs all transactions // and leaves the transaction stack empty. try { if (string.IsNullOrEmpty(savepoint)) { if (Interlocked.Exchange(ref _transactionDepth, 0) > 0) { Execute("rollback"); } } else { DoSavePointExecute(savepoint, "rollback to "); } } catch (SQLiteException) { if (!noThrow) { throw; } } // No need to rollback if there are no transactions open. } /// <summary> /// Releases a savepoint returned from <see cref="SaveTransactionPoint" />. Releasing a savepoint /// makes changes since that savepoint permanent if the savepoint began the transaction, /// or otherwise the changes are permanent pending a call to <see cref="Commit" />. /// The RELEASE command is like a COMMIT for a SAVEPOINT. /// </summary> /// <param name="savepoint"> /// The name of the savepoint to release. The string should be the result of a call to /// <see cref="SaveTransactionPoint" /> /// </param> [PublicAPI] public void Release(string savepoint) { DoSavePointExecute(savepoint, "release "); } private void DoSavePointExecute(string savePoint, string cmd) { // Validate the savepoint var firstLen = savePoint.IndexOf('D'); if (firstLen >= 2 && savePoint.Length > firstLen + 1) { int depth; if (int.TryParse(savePoint.Substring(firstLen + 1), out depth)) { // TODO: Mild race here, but inescapable without locking almost everywhere. if (0 <= depth && depth < _transactionDepth) { Platform.VolatileService.Write(ref _transactionDepth, depth); Execute(cmd + savePoint); return; } } } throw new ArgumentException( "savePoint is not valid, and should be the result of a call to SaveTransactionPoint.", "savePoint"); } /// <summary> /// Commits the transaction that was begun by <see cref="BeginTransaction" />. /// </summary> [PublicAPI] public void Commit() { if (Interlocked.Exchange(ref _transactionDepth, 0) != 0) { Execute("commit"); } // Do nothing on a commit with no open transaction } /// <summary> /// Executes /// <paramref name="action" /> /// within a (possibly nested) transaction by wrapping it in a SAVEPOINT. If an /// exception occurs the whole transaction is rolled back, not just the current savepoint. The exception /// is rethrown. /// </summary> /// <param name="action"> /// The <see cref="Action" /> to perform within a transaction. /// <paramref name="action" /> /// can contain any number /// of operations on the connection but should never call <see cref="BeginTransaction" /> or /// <see cref="Commit" />. /// </param> [PublicAPI] public void RunInTransaction(Action action) { try { var savePoint = SaveTransactionPoint(); action(); Release(savePoint); } catch (Exception) { Rollback(); throw; } } /// <summary> /// Inserts all specified objects. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable" /> of the objects to insert. /// </param> /// <param name="runInTransaction">A boolean indicating if the inserts should be wrapped in a transaction.</param> /// <returns> /// The number of rows added to the table. /// </returns> [PublicAPI] public int InsertAll(IEnumerable objects, bool runInTransaction = true) { var c = 0; if (runInTransaction) { RunInTransaction(() => { foreach (var r in objects) { c += Insert(r); } }); } else { foreach (var r in objects) { c += Insert(r); } } return c; } /// <summary> /// Inserts all specified objects. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable" /> of the objects to insert. /// </param> /// <param name="extra"> /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... /// </param> /// <param name="runInTransaction">A boolean indicating if the inserts should be wrapped in a transaction.</param> /// <returns> /// The number of rows added to the table. /// </returns> [PublicAPI] public int InsertAll(IEnumerable objects, string extra, bool runInTransaction = true) { var c = 0; if (runInTransaction) { RunInTransaction(() => { foreach (var r in objects) { c += Insert(r, extra); } }); } else { foreach (var r in objects) { c += Insert(r, extra); } } return c; } /// <summary> /// Inserts all specified objects. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable" /> of the objects to insert. /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <param name="runInTransaction">A boolean indicating if the inserts should be wrapped in a transaction.</param> /// <returns> /// The number of rows added to the table. /// </returns> [PublicAPI] public int InsertAll(IEnumerable objects, Type objType, bool runInTransaction = true) { var c = 0; if (runInTransaction) { RunInTransaction(() => { foreach (var r in objects) { c += Insert(r, objType); } }); } else { foreach (var r in objects) { c += Insert(r, objType); } } return c; } [PublicAPI] public int InsertOrIgnoreAll (IEnumerable objects) { return InsertAll (objects, "OR IGNORE"); } [PublicAPI] public int InsertOrIgnore (object obj) { if (obj == null) { return 0; } return Insert (obj, "OR IGNORE", obj.GetType ()); } [PublicAPI] public int InsertOrIgnore (object obj, Type objType) { return Insert (obj, "OR IGNORE", objType); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <returns> /// The number of rows added to the table. /// </returns> [PublicAPI] public int Insert(object obj) { if (obj == null) { return 0; } return Insert(obj, "", obj.GetType()); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// If a UNIQUE constraint violation occurs with /// some pre-existing object, this function deletes /// the old object. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <returns> /// The number of rows modified. /// </returns> [PublicAPI] public int InsertOrReplace(object obj) { if (obj == null) { return 0; } return Insert(obj, "OR REPLACE", obj.GetType()); } /// <summary> /// Inserts all specified objects. /// For each insertion, if a UNIQUE /// constraint violation occurs with /// some pre-existing object, this function /// deletes the old object. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable" /> of the objects to insert or replace. /// </param> /// <returns> /// The total number of rows modified. /// </returns> [PublicAPI] public int InsertOrReplaceAll(IEnumerable objects) { var c = 0; RunInTransaction(() => { foreach (var r in objects) { c += InsertOrReplace(r); } }); return c; } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows added to the table. /// </returns> [PublicAPI] public int Insert(object obj, Type objType) { return Insert(obj, "", objType); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// If a UNIQUE constraint violation occurs with /// some pre-existing object, this function deletes /// the old object. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows modified. /// </returns> [PublicAPI] public int InsertOrReplace(object obj, Type objType) { return Insert(obj, "OR REPLACE", objType); } /// <summary> /// Inserts all specified objects. /// For each insertion, if a UNIQUE /// constraint violation occurs with /// some pre-existing object, this function /// deletes the old object. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable" /> of the objects to insert or replace. /// </param> /// <param name="objType"> /// The type of objects to insert or replace. /// </param> /// <returns> /// The total number of rows modified. /// </returns> [PublicAPI] public int InsertOrReplaceAll(IEnumerable objects, Type objType) { var c = 0; RunInTransaction(() => { foreach (var r in objects) { c += InsertOrReplace(r, objType); } }); return c; } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <param name="extra"> /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... /// </param> /// <returns> /// The number of rows added to the table. /// </returns> [PublicAPI] public int Insert(object obj, string extra) { if (obj == null) { return 0; } return Insert(obj, extra, obj.GetType()); } /// <summary> /// Inserts the given object and retrieves its /// auto incremented primary key if it has one. /// </summary> /// <param name="obj"> /// The object to insert. /// </param> /// <param name="extra"> /// Literal SQL code that gets placed into the command. INSERT {extra} INTO ... /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows added to the table. /// </returns> [PublicAPI] public int Insert(object obj, string extra, Type objType) { if (obj == null || objType == null) { return 0; } var map = GetMapping(objType); if (map.PK != null && map.PK.IsAutoGuid) { var prop = objType.GetRuntimeProperty(map.PK.PropertyName); if (prop != null) { if (prop.GetValue(obj, null).Equals(Guid.Empty)) { prop.SetValue(obj, Guid.NewGuid(), null); } } } var replacing = string.Compare(extra, "OR REPLACE", StringComparison.OrdinalIgnoreCase) == 0; var cols = replacing ? map.Columns : map.InsertColumns; var vals = new object[cols.Length]; for (var i = 0; i < vals.Length; i++) { vals[i] = cols[i].GetValue(obj); } var insertCmd = GetInsertCommand(map, extra); int count; try { count = insertCmd.ExecuteNonQuery(vals); } catch (SQLiteException ex) { if (Platform.SQLiteApi.ExtendedErrCode(Handle) == ExtendedResult.ConstraintNotNull) { throw NotNullConstraintViolationException.New(ex.Result, ex.Message, map, obj); } throw; } if (map.HasAutoIncPK) { var id = Platform.SQLiteApi.LastInsertRowid(Handle); map.SetAutoIncPK(obj, id); } return count; } private PreparedSqlLiteInsertCommand GetInsertCommand(TableMapping map, string extra) { ActiveInsertCommand cmd; if (_insertCommandCache == null) { _insertCommandCache = new Dictionary<TableMapping, ActiveInsertCommand>(); } if (!_insertCommandCache.TryGetValue(map, out cmd)) { cmd = new ActiveInsertCommand(map); _insertCommandCache[map] = cmd; } return cmd.GetCommand(this, extra); } /// <summary> /// Updates all of the columns of a table using the specified object /// except for its primary key. /// The object is required to have a primary key. /// </summary> /// <param name="obj"> /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. /// </param> /// <returns> /// The number of rows updated. /// </returns> [PublicAPI] public int Update(object obj) { if (obj == null) { return 0; } return Update(obj, obj.GetType()); } /// <summary> /// Updates all of the columns of a table using the specified object /// except for its primary key. /// The object is required to have a primary key. /// </summary> /// <param name="obj"> /// The object to update. It must have a primary key designated using the PrimaryKeyAttribute. /// </param> /// <param name="objType"> /// The type of object to insert. /// </param> /// <returns> /// The number of rows updated. /// </returns> [PublicAPI] public int Update(object obj, Type objType) { int rowsAffected; if (obj == null || objType == null) { return 0; } var map = GetMapping(objType); var pk = map.PK; if (pk == null) { throw new NotSupportedException("Cannot update " + map.TableName + ": it has no PK"); } var cols = from p in map.Columns where p != pk select p; var vals = from c in cols select c.GetValue(obj); var ps = new List<object>(vals) { pk.GetValue(obj) }; var q = string.Format("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join(",", (from c in cols select "\"" + c.Name + "\" = ? ").ToArray()), pk.Name); try { rowsAffected = Execute(q, ps.ToArray()); } catch (SQLiteException ex) { if (ex.Result == Result.Constraint && Platform.SQLiteApi.ExtendedErrCode(Handle) == ExtendedResult.ConstraintNotNull) { throw NotNullConstraintViolationException.New(ex, map, obj); } throw; } return rowsAffected; } /// <summary> /// Updates all specified objects. /// </summary> /// <param name="objects"> /// An <see cref="IEnumerable" /> of the objects to insert. /// </param> /// <param name="runInTransaction">A boolean indicating if the inserts should be wrapped in a transaction.</param> /// <returns> /// The number of rows modified. /// </returns> [PublicAPI] public int UpdateAll(IEnumerable objects, bool runInTransaction = true) { var c = 0; if (runInTransaction) { RunInTransaction(() => { foreach (var r in objects) { c += Update(r); } }); } else { foreach (var r in objects) { c += Update(r); } } return c; } /// <summary> /// Deletes the given object from the database using its primary key. /// </summary> /// <param name="objectToDelete"> /// The object to delete. It must have a primary key designated using the PrimaryKeyAttribute. /// </param> /// <returns> /// The number of rows deleted. /// </returns> [PublicAPI] public int Delete(object objectToDelete) { var map = GetMapping(objectToDelete.GetType()); var pk = map.PK; if (pk == null) { throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK"); } var q = string.Format("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); return Execute(q, pk.GetValue(objectToDelete)); } /// <summary> /// Deletes the object with the specified primary key. /// </summary> /// <param name="primaryKey"> /// The primary key of the object to delete. /// </param> /// <returns> /// The number of objects deleted. /// </returns> /// <typeparam name='T'> /// The type of object. /// </typeparam> [PublicAPI] public int Delete<T>(object primaryKey) { var map = GetMapping(typeof (T)); var pk = map.PK; if (pk == null) { throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK"); } var q = string.Format("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name); return Execute(q, primaryKey); } /// <summary> /// Deletes all the objects from the specified table. /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the /// specified table. Do you really want to do that? /// </summary> /// <returns> /// The number of objects deleted. /// </returns> /// <typeparam name='T'> /// The type of objects to delete. /// </typeparam> [PublicAPI] public int DeleteAll<T>() { return DeleteAll(typeof (T)); } /// <summary> /// Deletes all the objects from the specified table. /// WARNING WARNING: Let me repeat. It deletes ALL the objects from the /// specified table. Do you really want to do that? /// </summary> /// <returns> /// The number of objects deleted. /// </returns> /// <typeparam name='T'> /// The type of objects to delete. /// </typeparam> [PublicAPI] public int DeleteAll(Type t) { var map = GetMapping(t); var query = string.Format("delete from \"{0}\"", map.TableName); return Execute(query); } #region Backup public string CreateDatabaseBackup(ISQLitePlatform platform) { ISQLiteApiExt sqliteApi = platform.SQLiteApi as ISQLiteApiExt; if (sqliteApi == null) { return null; } string destDBPath = this.DatabasePath + "." + DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss-fff"); IDbHandle destDB; byte[] databasePathAsBytes = GetNullTerminatedUtf8(destDBPath); Result r = sqliteApi.Open(databasePathAsBytes, out destDB, (int) (SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite), IntPtr.Zero); if (r != Result.OK) { throw SQLiteException.New(r, String.Format("Could not open backup database file: {0} ({1})", destDBPath, r)); } /* Open the backup object used to accomplish the transfer */ IDbBackupHandle bHandle = sqliteApi.BackupInit(destDB, "main", this.Handle, "main"); if (bHandle == null) { // Close the database connection sqliteApi.Close(destDB); throw SQLiteException.New(r, String.Format("Could not initiate backup process: {0}", destDBPath)); } /* Each iteration of this loop copies 5 database pages from database ** pDb to the backup database. If the return value of backup_step() ** indicates that there are still further pages to copy, sleep for ** 250 ms before repeating. */ do { r = sqliteApi.BackupStep(bHandle, 5); if (r == Result.OK || r == Result.Busy || r == Result.Locked) { sqliteApi.Sleep(250); } } while (r == Result.OK || r == Result.Busy || r == Result.Locked); /* Release resources allocated by backup_init(). */ r = sqliteApi.BackupFinish(bHandle); if (r != Result.OK) { // Close the database connection sqliteApi.Close(destDB); throw SQLiteException.New(r, String.Format("Could not finish backup process: {0} ({1})", destDBPath, r)); } // Close the database connection sqliteApi.Close(destDB); return destDBPath; } #endregion ~SQLiteConnection() { Dispose(false); } [PublicAPI] protected virtual void Dispose(bool disposing) { Close(); } [PublicAPI] public void Close() { if (_open && Handle != NullHandle) { try { if (_insertCommandCache != null) { foreach (var sqlInsertCommand in _insertCommandCache.Values) { sqlInsertCommand.Dispose(); } } var r = Platform.SQLiteApi.Close(Handle); if (r != Result.OK) { var msg = Platform.SQLiteApi.Errmsg16(Handle); throw SQLiteException.New(r, msg); } } finally { Handle = NullHandle; _open = false; } } } public class ColumnInfo { // public int cid { get; set; } [PublicAPI] [Column("name")] public string Name { get; set; } // [Column ("type")] // public string ColumnType { get; set; } [PublicAPI] public int notnull { get; set; } // public string dflt_value { get; set; } // public int pk { get; set; } [PublicAPI] public override string ToString() { return Name; } } private struct IndexInfo { public List<IndexedColumn> Columns; public string IndexName; public string TableName; public bool Unique; } private struct IndexedColumn { public string ColumnName; public int Order; } } }
mit
UweKeim/ZetaResourceEditor
Source-Skinning/ExtendedControlsLibrary/Skinning/CustomComboBoxEdit/MyCheckedComboBoxEdit.cs
713
namespace ExtendedControlsLibrary.Skinning.CustomComboBoxEdit; using System.ComponentModel; using CustomForm; using DevExpress.XtraEditors; [Designer(@"System.Windows.Forms.Design.ButtonBaseDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public class MyCheckedComboBoxEdit : CheckedComboBoxEdit { protected override void OnCreateControl() { base.OnCreateControl(); ViewInfo.Appearance.Font = SkinHelper.StandardFont; } protected override void OnLoaded() { base.OnLoaded(); if (!DesignModeHelper.IsDesignMode) { MenuManager = MyXtraForm.CheckGetMenuBarManager(this); } } }
mit