label
int64
0
1
text
stringlengths
0
2.8M
0
// // UIColor+Tools.swift // ToolBox // // Created by Nicolas Berthelot on 03/02/2017. // Copyright © 2017 Berthelot Nicolas. All rights reserved. // import UIKit extension UIColor { open class var x_random: UIColor { return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0) } public var x_hexSting : String { var r = CGFloat(0) var g = CGFloat(0) var b = CGFloat(0) var a = CGFloat(0) getRed(&r, green: &g, blue: &b, alpha: &a) let red = (Int)(r*255)<<16 let gren = (Int)(g*255)<<8 let blue = (Int)(b*255)<<0 let rgb = red | gren | blue return String(format:"%06x", rgb) } public static func x_color(from hexString: String) -> UIColor? { let hexString = hexString.replacingOccurrences(of: "#", with: "") guard let intHex = UInt(hexString, radix: 16) else { return nil } let hasAlpha = hexString.count == 8 let r = (intHex >> (hasAlpha ? 24 : 16)) & 0xff let g = (intHex >> (hasAlpha ? 16 : 8)) & 0xff let b = (hasAlpha ? intHex >> 8 : intHex) & 0xff let a = hasAlpha ? intHex & 0xff : 255 return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a) / 255.0) } }
0
// // TestScript.swift // Bitcoin_Tests // // Created by Wolf McNally on 11/7/18. // // Copyright © 2018 Blockchain Commons. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import Bitcoin import WolfPipe import WolfFoundation class TestScript: XCTestCase { func testScriptDecode() { let f = tagBase16 >>> toData >>> scriptDecode XCTAssert(try! "76a91418c0bd8d1818f1bf99cb1df2269c645318ef7b7388ac" |> f == "dup hash160 [18c0bd8d1818f1bf99cb1df2269c645318ef7b73] equalverify checksig") XCTAssert(try! "04cf2e5b02d6f02340f5a9defbbf710c388b8451c82145b1419fe9696837b1cdefc569a2a79baa6da2f747c3b35a102a081dfd5e799abc41262103e0d17114770b" |> f == "[cf2e5b02] 0xd6 0xf0 [40f5a9defbbf710c388b8451c82145b1419fe9696837b1cdefc569a2a79baa6da2f747] 0xc3 nop4 10 [2a081dfd5e799abc41262103e0d17114] nip <invalid>") XCTAssert(try! "4730440220688fb2aef767f21127b375d50d0ab8f7a1abaecad08e7c4987f7305c90e5a02502203282909b7863149bf4c92589764df80744afb509b949c06bfbeb28864277d88d0121025334b571c11e22967452f195509260f6a6dd10357fc4ad76b1c0aa5981ac254e" |> f == "[30440220688fb2aef767f21127b375d50d0ab8f7a1abaecad08e7c4987f7305c90e5a02502203282909b7863149bf4c92589764df80744afb509b949c06bfbeb28864277d88d01] [025334b571c11e22967452f195509260f6a6dd10357fc4ad76b1c0aa5981ac254e]") XCTAssert(try! "" |> f == "") } func testScriptEncode() { let f = scriptEncode >>> toBase16 XCTAssert(try! "dup hash160 [18c0bd8d1818f1bf99cb1df2269c645318ef7b73] equalverify checksig" |> f == "76a91418c0bd8d1818f1bf99cb1df2269c645318ef7b7388ac") XCTAssertThrowsError(try "foo" |> f == "won't happen") // Invalid script XCTAssert(try! "" |> f == "") } func testScriptToAddress() { let s1 = "dup hash160 [89abcdefabbaabbaabbaabbaabbaabbaabbaabba] equalverify checksig" XCTAssert(try! s1 |> scriptToAddress(network: .mainnet) == "3F6i6kwkevjR7AsAd4te2YB2zZyASEm1HM") XCTAssert(try! s1 |> scriptToAddress(network: .testnet) == "2N6evAVsnGPEmJxViJCWWeVAJCvBLFehT7L") let s2 = ["2", "[048cdce248e9d30838a2b31ad7162195db0ef4c20517916fa371fd04b153c214eeb644dcda76a98d33b0180a949d521df1d75024587a28ef30f2906c266fbb360e]", "[04d34775baab521d7ba2bd43997312d5f663633484ae1a4d84246866b7088297715a049e2288ae16f168809d36e2da1162f03412bf23aa5f949f235eb2e7141783]", "[04534072a9a62226252917f3011082a429900bbc5d1e11386b16e64e1dc985259c1cbcea0bad66fa6f106ea617ddddb6de45ac9118a3dcfc29c0763c167d56290e]", "3", "checkmultisig"] |> joined(separator: " ") XCTAssert(try! s2 |> scriptToAddress(network: .mainnet) == "3CS58tZGJtjz4qBFyNgQRtneKaWUjeEZVM") XCTAssert(try! s2 |> scriptToAddress(network: .testnet) == "2N3zHCdVHvMFLGcooeWJH3qmuXvieWfEFKG") } let scriptReturn = "return" let scriptReturnEmpty = "return []" let scriptReturn80 = "return [0001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809]" let scriptReturn81 = "return [0001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809000102030405060708090001020304050607080900010203040506070809FF]" let script0Of3Multisig = "0 [03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] [02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] [03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] 3 checkmultisig" let script1Of3Multisig = "1 [03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] [02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] [03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] 3 checkmultisig" let script2Of3Multisig = "2 [03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] [02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] [03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] 3 checkmultisig" let script3Of3Multisig = "3 [03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] [02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] [03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] 3 checkmultisig" let script4Of3Multisig = "4 [03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] [02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] [03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] 3 checkmultisig" let script16Of16Multisig = "16 " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "16 checkmultisig" let script17Of17Multisig = "[17] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934] " + "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864] " + "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c] " + "16 checkmultisig" func test_script__one_hash__literal__same() { let hashOne = try! "0000000000000000000000000000000000000000000000000000000000000001" |> hashDecode let oneHash = try! Data([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) |> tagHashDigest XCTAssert(hashOne == oneHash) } func test_script__from_data__testnet_119058_invalid_op_codes__success() { let rawScript = "0130323066643366303435313438356531306633383837363437356630643265396130393739343332353534313766653139316438623963623230653430643863333030326431373463336539306366323433393231383761313037623634373337633937333135633932393264653431373731636565613062323563633534353732653302ae" |> dataLiteral XCTAssertNoThrow(try rawScript |> deserializeScript) } func test_script__from_data__parse__success() { let rawScript = "3045022100ff1fc58dbd608e5e05846a8e6b45a46ad49878aef6879ad1a7cf4c5a7f853683022074a6a10f6053ab3cddc5620d169c7374cd42c1416c51b9744db2c8d9febfb84d01" |> dataLiteral XCTAssertNoThrow(try Script.deserialize(rawScript, prefix: true)) } func test_script__from_data__to_data__roundtrips() { let normal_output_script = "3045022100ff1fc58dbd608e5e05846a8e6b45a46ad49878aef6879ad1a7cf4c5a7f853683022074a6a10f6053ab3cddc5620d169c7374cd42c1416c51b9744db2c8d9febfb84d01" |> dataLiteral var out_script: Script! XCTAssertNoThrow(out_script = try normal_output_script |> deserializeScript) let roundtrip = out_script |> serialize XCTAssert(roundtrip == normal_output_script) } func test_script__from_data__to_data_weird__roundtrips() { let weird_raw_script = ("0c49206c69656b20636174732e483045022100c7387f64e1f4" + "cf654cae3b28a15f7572106d6c1319ddcdc878e636ccb83845" + "e30220050ebf440160a4c0db5623e0cb1562f46401a7ff5b87" + "7aa03415ae134e8c71c901534d4f0176519c6375522103b124" + "c48bbff7ebe16e7bd2b2f2b561aa53791da678a73d2777cc1c" + "a4619ab6f72103ad6bb76e00d124f07a22680e39debd4dc4bd" + "b1aa4b893720dd05af3c50560fdd52af67529c63552103b124" + "c48bbff7ebe16e7bd2b2f2b561aa53791da678a73d2777cc1c" + "a4619ab6f721025098a1d5a338592bf1e015468ec5a8fafc1f" + "c9217feb5cb33597f3613a2165e9210360cfabc01d52eaaeb3" + "976a5de05ff0cfa76d0af42d3d7e1b4c233ee8a00655ed2103" + "f571540c81fd9dbf9622ca00cfe95762143f2eab6b65150365" + "bb34ac533160432102bc2b4be1bca32b9d97e2d6fb255504f4" + "bc96e01aaca6e29bfa3f8bea65d8865855af672103ad6bb76e" + "00d124f07a22680e39debd4dc4bdb1aa4b893720dd05af3c50" + "560fddada820a4d933888318a23c28fb5fc67aca8530524e20" + "74b1d185dbf5b4db4ddb0642848868685174519c6351670068") |> dataLiteral var weird: Script! XCTAssertNoThrow(weird = try weird_raw_script |> deserializeScript) let roundtrip_result = weird |> serialize XCTAssert(roundtrip_result == weird_raw_script) } func test_script__factory_chunk_test() { let raw = "76a914fc7b44566256621affb1541cc9d59f08336d276b88ac" |> dataLiteral let script = try! raw |> deserializeScript XCTAssert(script.isValid) } func test_script__from_string__empty__success() { let script = try! Script("") XCTAssert(script.operations.isEmpty) } func test_script__from_string__two_of_three_multisig__success() { let script = try! Script(script2Of3Multisig) let ops = script.operations XCTAssert(ops.count == 6) XCTAssert(ops[0].opcode == .pushPositive2) XCTAssert(ops[1] |> toString(rules: .noRules) == "[03dcfd9e580de35d8c2060d76dbf9e5561fe20febd2e64380e860a4d59f15ac864]") XCTAssert(ops[2] |> toString(rules: .noRules) == "[02440e0304bf8d32b2012994393c6a477acf238dd6adb4c3cef5bfa72f30c9861c]") XCTAssert(ops[3] |> toString(rules: .noRules) == "[03624505c6cc3967352cce480d8550490dd68519cd019066a4c302fdfb7d1c9934]") XCTAssert(ops[4].opcode == .pushPositive3) XCTAssert(ops[5].opcode == .checkmultisig) } func test_script__empty__default__true() { let script = Script() XCTAssert(script.isEmpty) } func test_script__empty__no_operations__true() { let script = Script([]) XCTAssert(script.isEmpty) } func test_script__empty__non_empty__false() { let data = "2a" |> dataLiteral let script = Script(Script.makePayNullDataPattern(data: data)) XCTAssertFalse(script.isEmpty) } func test_script__clear__non_empty__empty() { let data = "2a" |> dataLiteral var script = Script(Script.makePayNullDataPattern(data: data)) XCTAssertFalse(script.isEmpty) script.clear() XCTAssert(script.isEmpty) } func test_script__pattern() { func f(_ scriptString: String, outputPattern: ScriptPattern, inputPattern: ScriptPattern, pattern: ScriptPattern) -> Bool { let script = try! Script(scriptString) guard script.isValid else { return false } guard script.outputPattern == outputPattern else { return false } guard script.inputPattern == inputPattern else { return false } guard script.pattern == pattern else { return false } return true } XCTAssert(f(scriptReturn, outputPattern: .nonStandard, inputPattern: .nonStandard, pattern: .nonStandard)) XCTAssert(f(scriptReturnEmpty, outputPattern: .payNullData, inputPattern: .nonStandard, pattern: .payNullData)) XCTAssert(f(scriptReturn80, outputPattern: .payNullData, inputPattern: .nonStandard, pattern: .payNullData)) XCTAssert(f(scriptReturn81, outputPattern: .nonStandard, inputPattern: .nonStandard, pattern: .nonStandard)) XCTAssert(f(script0Of3Multisig, outputPattern: .nonStandard, inputPattern: .nonStandard, pattern: .nonStandard)) XCTAssert(f(script1Of3Multisig, outputPattern: .payMultisig, inputPattern: .nonStandard, pattern: .payMultisig)) XCTAssert(f(script2Of3Multisig, outputPattern: .payMultisig, inputPattern: .nonStandard, pattern: .payMultisig)) XCTAssert(f(script3Of3Multisig, outputPattern: .payMultisig, inputPattern: .nonStandard, pattern: .payMultisig)) XCTAssert(f(script4Of3Multisig, outputPattern: .nonStandard, inputPattern: .nonStandard, pattern: .nonStandard)) XCTAssert(f(script16Of16Multisig, outputPattern: .payMultisig, inputPattern: .nonStandard, pattern: .payMultisig)) XCTAssert(f(script17Of17Multisig, outputPattern: .nonStandard, inputPattern: .nonStandard, pattern: .nonStandard)) } struct ScriptTest { let input: String let output: String let description: String let inputSequence: UInt32 let lockTime: UInt32 let version: UInt32 init(_ input: String, _ output: String, _ description: String, _ inputSequence: UInt32 = 0, _ lockTime: UInt32 = 0, _ version: UInt32 = 0) { self.input = input self.output = output self.description = description self.inputSequence = inputSequence self.lockTime = lockTime self.version = version } } func makeTransaction(for test: ScriptTest) -> (Transaction, Script) { let inputScript = try! Script(test.input) let outputScript = try! Script(test.output) let outputPoint = OutputPoint() let input = Input(previousOutput: outputPoint, script: inputScript, sequence: test.inputSequence) let tx = Transaction(version: test.version, lockTime: test.lockTime, inputs: [input], outputs: []) return (tx, outputScript) } func verifyScript(_ test: ScriptTest, _ transaction: Transaction, _ prevoutScript: Script, _ rules: RuleFork, _ expectSuccess: Bool) -> Bool { let code = Script.verify(transaction: transaction, inputIndex: 0, rules: rules, prevoutScript: prevoutScript, value: 0) guard code.isSuccess == expectSuccess else { print("❌ \(test.description)") return false } return true } func test_script__bip16__valid() { let valid_bip16_scripts = [ ScriptTest("0 [51]", "hash160 [da1745e9b549bd0bfa1a569971c77eba30cd5a4b] equal", "trivial p2sh"), ScriptTest("[1.] [0.51]", "hash160 [da1745e9b549bd0bfa1a569971c77eba30cd5a4b] equal", "basic p2sh") ] for test in valid_bip16_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, true)) XCTAssert(verifyScript(test, tx, outputScript, .bip16Rule, true)) XCTAssert(verifyScript(test, tx, outputScript, .allRules, true)) } } func test_script__bip16__invalidated() { let invalidated_bip16_scripts = [ ScriptTest("nop [51]", "hash160 [da1745e9b549bd0bfa1a569971c77eba30cd5a4b] equal", "is_push_only fails under bip16"), ScriptTest("nop1 [51]", "hash160 [da1745e9b549bd0bfa1a569971c77eba30cd5a4b] equal", "is_push_only fails under bip16"), ScriptTest("0 [50]", "hash160 [ece424a6bb6ddf4db592c0faed60685047a361b1] equal", "op_reserved as p2sh serialized script fails"), ScriptTest("0 [62]", "hash160 [0f4d7845db968f2a81b530b6f3c1d6246d4c7e01] equal", "op_ver as p2sh serialized script fails") ] for test in invalidated_bip16_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, true)) XCTAssert(verifyScript(test, tx, outputScript, .bip16Rule, false)) XCTAssert(verifyScript(test, tx, outputScript, .allRules, false)) } } func test_script__bip65__valid() { let valid_bip65_scripts = [ ScriptTest("42", "checklocktimeverify", "valid cltv, true return", 42, 99), ScriptTest("42", "nop1 nop2 nop3 nop4 nop5 nop6 nop7 nop8 nop9 nop10 [2a] equal", "bip112 would fail nop3", 42, 99) ] for test in valid_bip65_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, true)) XCTAssert(verifyScript(test, tx, outputScript, .bip65Rule, true)) XCTAssert(verifyScript(test, tx, outputScript, .allRules |> remove(.bip112Rule), true)) } } func test_script__bip65__invalid() { let invalid_bip65_scripts = [ ScriptTest("", "nop2", "empty nop2", 42, 99 ), ScriptTest("", "checklocktimeverify", "empty cltv", 42, 99 ) ] for test in invalid_bip65_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, false)) XCTAssert(verifyScript(test, tx, outputScript, .bip65Rule, false)) XCTAssert(verifyScript(test, tx, outputScript, .allRules |> remove(.bip112Rule), false)) } } func test_script__bip65__invalidated() { let invalidated_bip65_scripts = [ ScriptTest("1 -1", "checklocktimeverify", "negative cltv", 42, 99), ScriptTest("1 100", "checklocktimeverify", "exceeded cltv", 42, 99), ScriptTest("1 500000000", "checklocktimeverify", "mismatched cltv", 42, 99), ScriptTest("'nop_1_to_10' nop1 nop2 nop3 nop4 nop5 nop6 nop7 nop8 nop9 nop10", "'nop_1_to_10' equal", "bip112 would fail nop3", 42, 99), ScriptTest("nop", "nop2 1", "", 42, 99) ] for test in invalidated_bip65_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, true)) XCTAssert(verifyScript(test, tx, outputScript, .bip65Rule, false)) XCTAssert(verifyScript(test, tx, outputScript, .allRules |> remove(.bip112Rule), false)) } } func test_script__multisig__valid() { let valid_multisig_scripts = [ ScriptTest("", "0 0 0 checkmultisig verify depth 0 equal", "checkmultisig is allowed to have zero keys and/or sigs"), ScriptTest("", "0 0 0 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 0 1 checkmultisig verify depth 0 equal", "zero sigs means no sigs are checked"), ScriptTest("", "0 0 0 1 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 2 checkmultisig verify depth 0 equal", "test from up to 20 pubkeys, all not checked"), ScriptTest("", "0 0 'a' 'b' 'c' 3 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 4 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 5 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 6 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 7 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 8 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 9 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 10 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 11 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 12 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 13 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 14 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 15 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 16 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 17 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 18 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 19 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig verify depth 0 equal", ""), ScriptTest("", "0 0 'a' 1 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 2 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 3 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 4 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 5 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 6 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 7 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 8 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 9 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 10 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 11 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 12 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 13 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 14 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 15 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 16 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 17 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 18 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 19 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify depth 0 equal", ""), ScriptTest("", "0 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig", "nopcount is incremented by the number of keys evaluated in addition to the usual one op per op. in this case we have zero keys, so we can execute 201 checkmultisigs"), ScriptTest("1", "0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify 0 0 0 checkmultisigverify", ""), ScriptTest("", "nop nop nop nop nop nop nop nop nop nop nop nop 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig", "even though there are no signatures being checked nopcount is incremented by the number of keys."), ScriptTest("1", "nop nop nop nop nop nop nop nop nop nop nop nop 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify", "") ] for test in valid_multisig_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, true)) XCTAssert(verifyScript(test, tx, outputScript, .bip66Rule, true)) XCTAssert(verifyScript(test, tx, outputScript, .allRules, true)) } } func test_script__multisig__invalid() { let invalid_multisig_scripts = [ ScriptTest("", "0 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig 0 0 checkmultisig", "202 checkmultisigs, fails due to 201 op limit"), ScriptTest("1", "0 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify 0 0 checkmultisigverify", ""), ScriptTest("", "nop nop nop nop nop nop nop nop nop nop nop nop nop 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisig", "fails due to 201 sig op limit"), ScriptTest("1", "nop nop nop nop nop nop nop nop nop nop nop nop nop 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify 0 0 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 20 checkmultisigverify", ""), ] for test in invalid_multisig_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, false)) XCTAssert(verifyScript(test, tx, outputScript, .bip66Rule, false)) XCTAssert(verifyScript(test, tx, outputScript, .allRules |> remove(.bip112Rule), false)) } } func test_script__context_free__valid() { let valid_context_free_scripts = [ ScriptTest("", "depth 0 equal", "test the test: we should have an empty stack after scriptsig evaluation"), ScriptTest(" ", "depth 0 equal", "and multiple spaces should not change that."), ScriptTest(" ", "depth 0 equal", ""), ScriptTest(" ", "depth 0 equal", ""), ScriptTest("1 2", "2 equalverify 1 equal", "similarly whitespace around and between symbols"), ScriptTest("1 2", "2 equalverify 1 equal", ""), ScriptTest(" 1 2", "2 equalverify 1 equal", ""), ScriptTest("1 2 ", "2 equalverify 1 equal", ""), ScriptTest(" 1 2 ", "2 equalverify 1 equal", ""), ScriptTest("1", "", ""), ScriptTest("[0b]", "11 equal", "push 1 byte"), ScriptTest("[417a]", "'Az' equal", "push 2 bytes"), ScriptTest("[417a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a]", "'Azzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz' equal", "push 75 bytes"), ScriptTest("[1.07]", "7 equal", "non-minimal op_pushdata1"), ScriptTest("[2.08]", "8 equal", "non-minimal op_pushdata2"), ScriptTest("[4.09]", "9 equal", "non-minimal op_pushdata4"), ScriptTest("0x4c", "0 equal", "0x4c is op_pushdata1"), ScriptTest("0x4d", "0 equal", "0x4d is op_pushdata2"), ScriptTest("0x4e", "0 equal", "0x4f is op_pushdata4"), ScriptTest("0x4f 1000 add", "999 equal", "1000 - 1 = 999"), ScriptTest("0", "if 0x50 endif 1", "0x50 is reserved (ok if not executed)"), ScriptTest("0x51", "0x5f add 0x60 equal", "0x51 through 0x60 push 1 through 16 onto stack"), ScriptTest("1", "nop", ""), ScriptTest("0", "if ver else 1 endif", "ver non-functional (ok if not executed)"), ScriptTest("0", "if reserved reserved1 reserved2 else 1 endif", "reserved ok in un-executed if"), ScriptTest("1", "dup if endif", ""), ScriptTest("1", "if 1 endif", ""), ScriptTest("1", "dup if else endif", ""), ScriptTest("1", "if 1 else endif", ""), ScriptTest("0", "if else 1 endif", ""), ScriptTest("1 1", "if if 1 else 0 endif endif", ""), ScriptTest("1 0", "if if 1 else 0 endif endif", ""), ScriptTest("1 1", "if if 1 else 0 endif else if 0 else 1 endif endif", ""), ScriptTest("0 0", "if if 1 else 0 endif else if 0 else 1 endif endif", ""), ScriptTest("1 0", "notif if 1 else 0 endif endif", ""), ScriptTest("1 1", "notif if 1 else 0 endif endif", ""), ScriptTest("1 0", "notif if 1 else 0 endif else if 0 else 1 endif endif", ""), ScriptTest("0 1", "notif if 1 else 0 endif else if 0 else 1 endif endif", ""), ScriptTest("0", "if 0 else 1 else 0 endif", "multiple else's are valid and executed inverts on each else encountered"), ScriptTest("1", "if 1 else 0 else endif", ""), ScriptTest("1", "if else 0 else 1 endif", ""), ScriptTest("1", "if 1 else 0 else 1 endif add 2 equal", ""), ScriptTest("'' 1", "if sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 endif [68ca4fec736264c13b859bac43d5173df6871682] equal", ""), ScriptTest("1", "notif 0 else 1 else 0 endif", "multiple else's are valid and execution inverts on each else encountered"), ScriptTest("0", "notif 1 else 0 else endif", ""), ScriptTest("0", "notif else 0 else 1 endif", ""), ScriptTest("0", "notif 1 else 0 else 1 endif add 2 equal", ""), ScriptTest("'' 0", "notif sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 else else sha1 endif [68ca4fec736264c13b859bac43d5173df6871682] equal", ""), ScriptTest("0", "if 1 if return else return else return endif else 1 if 1 else return else 1 endif else return endif add 2 equal", "nested else else"), ScriptTest("1", "notif 0 notif return else return else return endif else 0 notif 1 else return else 1 endif else return endif add 2 equal", ""), ScriptTest("0", "if return endif 1", "return only works if executed"), ScriptTest("1 1", "verify", ""), ScriptTest("10 0 11 toaltstack drop fromaltstack", "add 21 equal", ""), ScriptTest("'gavin_was_here' toaltstack 11 fromaltstack", "'gavin_was_here' equalverify 11 equal", ""), ScriptTest("0 ifdup", "depth 1 equalverify 0 equal", ""), ScriptTest("1 ifdup", "depth 2 equalverify 1 equalverify 1 equal", ""), ScriptTest("0 drop", "depth 0 equal", ""), ScriptTest("0", "dup 1 add 1 equalverify 0 equal", ""), ScriptTest("0 1", "nip", ""), ScriptTest("1 0", "over depth 3 equalverify", ""), ScriptTest("22 21 20", "0 pick 20 equalverify depth 3 equal", ""), ScriptTest("22 21 20", "1 pick 21 equalverify depth 3 equal", ""), ScriptTest("22 21 20", "2 pick 22 equalverify depth 3 equal", ""), ScriptTest("22 21 20", "0 roll 20 equalverify depth 2 equal", ""), ScriptTest("22 21 20", "1 roll 21 equalverify depth 2 equal", ""), ScriptTest("22 21 20", "2 roll 22 equalverify depth 2 equal", ""), ScriptTest("22 21 20", "rot 22 equal", ""), ScriptTest("22 21 20", "rot drop 20 equal", ""), ScriptTest("22 21 20", "rot drop drop 21 equal", ""), ScriptTest("22 21 20", "rot rot 21 equal", ""), ScriptTest("22 21 20", "rot rot rot 20 equal", ""), ScriptTest("25 24 23 22 21 20", "rot2 24 equal", ""), ScriptTest("25 24 23 22 21 20", "rot2 drop 25 equal", ""), ScriptTest("25 24 23 22 21 20", "rot2 drop2 20 equal", ""), ScriptTest("25 24 23 22 21 20", "rot2 drop2 drop 21 equal", ""), ScriptTest("25 24 23 22 21 20", "rot2 drop2 drop2 22 equal", ""), ScriptTest("25 24 23 22 21 20", "rot2 drop2 drop2 drop 23 equal", ""), ScriptTest("25 24 23 22 21 20", "rot2 rot2 22 equal", ""), ScriptTest("25 24 23 22 21 20", "rot2 rot2 rot2 20 equal", ""), ScriptTest("1 0", "swap 1 equalverify 0 equal", ""), ScriptTest("0 1", "tuck depth 3 equalverify swap drop2", ""), ScriptTest("13 14", "dup2 rot equalverify equal", ""), ScriptTest("-1 0 1 2", "dup3 depth 7 equalverify add add 3 equalverify drop2 0 equalverify", ""), ScriptTest("1 2 3 5", "over2 add add 8 equalverify add add 6 equal", ""), ScriptTest("1 3 5 7", "swap2 add 4 equalverify add 12 equal", ""), ScriptTest("0", "size 0 equal", ""), ScriptTest("1", "size 1 equal", ""), ScriptTest("127", "size 1 equal", ""), ScriptTest("128", "size 2 equal", ""), ScriptTest("32767", "size 2 equal", ""), ScriptTest("32768", "size 3 equal", ""), ScriptTest("8388607", "size 3 equal", ""), ScriptTest("8388608", "size 4 equal", ""), ScriptTest("2147483647", "size 4 equal", ""), ScriptTest("2147483648", "size 5 equal", ""), ScriptTest("549755813887", "size 5 equal", ""), ScriptTest("549755813888", "size 6 equal", ""), ScriptTest("9223372036854775807", "size 8 equal", ""), ScriptTest("-1", "size 1 equal", ""), ScriptTest("-127", "size 1 equal", ""), ScriptTest("-128", "size 2 equal", ""), ScriptTest("-32767", "size 2 equal", ""), ScriptTest("-32768", "size 3 equal", ""), ScriptTest("-8388607", "size 3 equal", ""), ScriptTest("-8388608", "size 4 equal", ""), ScriptTest("-2147483647", "size 4 equal", ""), ScriptTest("-2147483648", "size 5 equal", ""), ScriptTest("-549755813887", "size 5 equal", ""), ScriptTest("-549755813888", "size 6 equal", ""), ScriptTest("-9223372036854775807", "size 8 equal", ""), ScriptTest("'abcdefghijklmnopqrstuvwxyz'", "size 26 equal", ""), ScriptTest("2 -2 add", "0 equal", ""), ScriptTest("2147483647 -2147483647 add", "0 equal", ""), ScriptTest("-1 -1 add", "-2 equal", ""), ScriptTest("0 0", "equal", ""), ScriptTest("1 1 add", "2 equal", ""), ScriptTest("1 add1", "2 equal", ""), ScriptTest("111 sub1", "110 equal", ""), ScriptTest("111 1 add 12 sub", "100 equal", ""), ScriptTest("0 abs", "0 equal", ""), ScriptTest("16 abs", "16 equal", ""), ScriptTest("-16 abs", "-16 negate equal", ""), ScriptTest("0 not", "nop", ""), ScriptTest("1 not", "0 equal", ""), ScriptTest("11 not", "0 equal", ""), ScriptTest("0 nonzero", "0 equal", ""), ScriptTest("1 nonzero", "1 equal", ""), ScriptTest("111 nonzero", "1 equal", ""), ScriptTest("-111 nonzero", "1 equal", ""), ScriptTest("1 1 booland", "nop", ""), ScriptTest("1 0 booland", "not", ""), ScriptTest("0 1 booland", "not", ""), ScriptTest("0 0 booland", "not", ""), ScriptTest("16 17 booland", "nop", ""), ScriptTest("1 1 boolor", "nop", ""), ScriptTest("1 0 boolor", "nop", ""), ScriptTest("0 1 boolor", "nop", ""), ScriptTest("0 0 boolor", "not", ""), ScriptTest("16 17 boolor", "nop", ""), ScriptTest("11 10 1 add", "numequal", ""), ScriptTest("11 10 1 add", "numequalverify 1", ""), ScriptTest("11 10 1 add", "numnotequal not", ""), ScriptTest("111 10 1 add", "numnotequal", ""), ScriptTest("11 10", "lessthan not", ""), ScriptTest("4 4", "lessthan not", ""), ScriptTest("10 11", "lessthan", ""), ScriptTest("-11 11", "lessthan", ""), ScriptTest("-11 -10", "lessthan", ""), ScriptTest("11 10", "greaterthan", ""), ScriptTest("4 4", "greaterthan not", ""), ScriptTest("10 11", "greaterthan not", ""), ScriptTest("-11 11", "greaterthan not", ""), ScriptTest("-11 -10", "greaterthan not", ""), ScriptTest("11 10", "lessthanorequal not", ""), ScriptTest("4 4", "lessthanorequal", ""), ScriptTest("10 11", "lessthanorequal", ""), ScriptTest("-11 11", "lessthanorequal", ""), ScriptTest("-11 -10", "lessthanorequal", ""), ScriptTest("11 10", "greaterthanorequal", ""), ScriptTest("4 4", "greaterthanorequal", ""), ScriptTest("10 11", "greaterthanorequal not", ""), ScriptTest("-11 11", "greaterthanorequal not", ""), ScriptTest("-11 -10", "greaterthanorequal not", ""), ScriptTest("1 0 min", "0 numequal", ""), ScriptTest("0 1 min", "0 numequal", ""), ScriptTest("-1 0 min", "-1 numequal", ""), ScriptTest("0 -2147483647 min", "-2147483647 numequal", ""), ScriptTest("2147483647 0 max", "2147483647 numequal", ""), ScriptTest("0 100 max", "100 numequal", ""), ScriptTest("-100 0 max", "0 numequal", ""), ScriptTest("0 -2147483647 max", "0 numequal", ""), ScriptTest("0 0 1", "within", ""), ScriptTest("1 0 1", "within not", ""), ScriptTest("0 -2147483647 2147483647", "within", ""), ScriptTest("-1 -100 100", "within", ""), ScriptTest("11 -100 100", "within", ""), ScriptTest("-2147483647 -100 100", "within not", ""), ScriptTest("2147483647 -100 100", "within not", ""), ScriptTest("2147483647 2147483647 sub", "0 equal", ""), ScriptTest("2147483647 dup add", "4294967294 equal", ">32 bit equal is valid"), ScriptTest("2147483647 negate dup add", "-4294967294 equal", ""), ScriptTest("''", "ripemd160 [9c1185a5c5e9fc54612808977ee8f548b2258d31] equal", ""), ScriptTest("'a'", "ripemd160 [0bdc9d2d256b3ee9daae347be6f4dc835a467ffe] equal", ""), ScriptTest("'abcdefghijklmnopqrstuvwxyz'", "ripemd160 [f71c27109c692c1b56bbdceb5b9d2865b3708dbc] equal", ""), ScriptTest("''", "sha1 [da39a3ee5e6b4b0d3255bfef95601890afd80709] equal", ""), ScriptTest("'a'", "sha1 [86f7e437faa5a7fce15d1ddcb9eaeaea377667b8] equal", ""), ScriptTest("'abcdefghijklmnopqrstuvwxyz'", "sha1 [32d10c7b8cf96570ca04ce37f2a19d84240d3a89] equal", ""), ScriptTest("''", "sha256 [e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855] equal", ""), ScriptTest("'a'", "sha256 [ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb] equal", ""), ScriptTest("'abcdefghijklmnopqrstuvwxyz'", "sha256 [71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73] equal", ""), ScriptTest("''", "dup hash160 swap sha256 ripemd160 equal", ""), ScriptTest("''", "dup hash256 swap sha256 sha256 equal", ""), ScriptTest("''", "nop hash160 [b472a266d0bd89c13706a4132ccfb16f7c3b9fcb] equal", ""), ScriptTest("'a'", "hash160 nop [994355199e516ff76c4fa4aab39337b9d84cf12b] equal", ""), ScriptTest("'abcdefghijklmnopqrstuvwxyz'", "hash160 [1.c286a1af0947f58d1ad787385b1c2c4a976f9e71] equal", ""), ScriptTest("''", "hash256 [5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456] equal", ""), ScriptTest("'a'", "hash256 [bf5d3affb73efd2ec6c36ad3112dd933efed63c4e1cbffcfa88e2759c144f2d8] equal", ""), ScriptTest("'abcdefghijklmnopqrstuvwxyz'", "hash256 [1.ca139bc10c2f660da42666f72e89a225936fc60f193c161124a672050c434671] equal", ""), ScriptTest("1", "nop1 nop4 nop5 nop6 nop7 nop8 nop9 nop10 1 equal", ""), ScriptTest("'nop_1_to_10' nop1 nop4 nop5 nop6 nop7 nop8 nop9 nop10", "'nop_1_to_10' equal", ""), ScriptTest("0", "if 0xba else 1 endif", "opcodes above nop10 invalid if executed"), ScriptTest("0", "if 0xbb else 1 endif", ""), ScriptTest("0", "if 0xbc else 1 endif", ""), ScriptTest("0", "if 0xbd else 1 endif", ""), ScriptTest("0", "if 0xbe else 1 endif", ""), ScriptTest("0", "if 0xbf else 1 endif", ""), ScriptTest("0", "if 0xc0 else 1 endif", ""), ScriptTest("0", "if 0xc1 else 1 endif", ""), ScriptTest("0", "if 0xc2 else 1 endif", ""), ScriptTest("0", "if 0xc3 else 1 endif", ""), ScriptTest("0", "if 0xc4 else 1 endif", ""), ScriptTest("0", "if 0xc5 else 1 endif", ""), ScriptTest("0", "if 0xc6 else 1 endif", ""), ScriptTest("0", "if 0xc7 else 1 endif", ""), ScriptTest("0", "if 0xc8 else 1 endif", ""), ScriptTest("0", "if 0xc9 else 1 endif", ""), ScriptTest("0", "if 0xca else 1 endif", ""), ScriptTest("0", "if 0xcb else 1 endif", ""), ScriptTest("0", "if 0xcc else 1 endif", ""), ScriptTest("0", "if 0xcd else 1 endif", ""), ScriptTest("0", "if 0xce else 1 endif", ""), ScriptTest("0", "if 0xcf else 1 endif", ""), ScriptTest("0", "if 0xd0 else 1 endif", ""), ScriptTest("0", "if 0xd1 else 1 endif", ""), ScriptTest("0", "if 0xd2 else 1 endif", ""), ScriptTest("0", "if 0xd3 else 1 endif", ""), ScriptTest("0", "if 0xd4 else 1 endif", ""), ScriptTest("0", "if 0xd5 else 1 endif", ""), ScriptTest("0", "if 0xd6 else 1 endif", ""), ScriptTest("0", "if 0xd7 else 1 endif", ""), ScriptTest("0", "if 0xd8 else 1 endif", ""), ScriptTest("0", "if 0xd9 else 1 endif", ""), ScriptTest("0", "if 0xda else 1 endif", ""), ScriptTest("0", "if 0xdb else 1 endif", ""), ScriptTest("0", "if 0xdc else 1 endif", ""), ScriptTest("0", "if 0xdd else 1 endif", ""), ScriptTest("0", "if 0xde else 1 endif", ""), ScriptTest("0", "if 0xdf else 1 endif", ""), ScriptTest("0", "if 0xe0 else 1 endif", ""), ScriptTest("0", "if 0xe1 else 1 endif", ""), ScriptTest("0", "if 0xe2 else 1 endif", ""), ScriptTest("0", "if 0xe3 else 1 endif", ""), ScriptTest("0", "if 0xe4 else 1 endif", ""), ScriptTest("0", "if 0xe5 else 1 endif", ""), ScriptTest("0", "if 0xe6 else 1 endif", ""), ScriptTest("0", "if 0xe7 else 1 endif", ""), ScriptTest("0", "if 0xe8 else 1 endif", ""), ScriptTest("0", "if 0xe9 else 1 endif", ""), ScriptTest("0", "if 0xea else 1 endif", ""), ScriptTest("0", "if 0xeb else 1 endif", ""), ScriptTest("0", "if 0xec else 1 endif", ""), ScriptTest("0", "if 0xed else 1 endif", ""), ScriptTest("0", "if 0xee else 1 endif", ""), ScriptTest("0", "if 0xef else 1 endif", ""), ScriptTest("0", "if 0xf0 else 1 endif", ""), ScriptTest("0", "if 0xf1 else 1 endif", ""), ScriptTest("0", "if 0xf2 else 1 endif", ""), ScriptTest("0", "if 0xf3 else 1 endif", ""), ScriptTest("0", "if 0xf4 else 1 endif", ""), ScriptTest("0", "if 0xf5 else 1 endif", ""), ScriptTest("0", "if 0xf6 else 1 endif", ""), ScriptTest("0", "if 0xf7 else 1 endif", ""), ScriptTest("0", "if 0xf8 else 1 endif", ""), ScriptTest("0", "if 0xf9 else 1 endif", ""), ScriptTest("0", "if 0xfa else 1 endif", ""), ScriptTest("0", "if 0xfb else 1 endif", ""), ScriptTest("0", "if 0xfc else 1 endif", ""), ScriptTest("0", "if 0xfd else 1 endif", ""), ScriptTest("0", "if 0xfe else 1 endif", ""), ScriptTest("0", "if 0xff else 1 endif", ""), ScriptTest("nop", "'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'", "520 byte push"), ScriptTest("1", "0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61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6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f dup2 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61", "max-size (10,000-byte), max-push(520 bytes), max-opcodes(201), max stack size(1,000 items). 0x6f is dup3, 0x61 is nop"), ScriptTest("0", "if 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 0x50 endif 1", ">201 opcodes, but reserved (0x50) doesn't count towards opcode limit."), ScriptTest("nop", "1", ""), ScriptTest("1", "[01] equal", "the following is useful for checking implementations of bn_bn2mpi"), ScriptTest("127", "[7f] equal", ""), ScriptTest("128", "[8000] equal", "leave room for the sign bit"), ScriptTest("32767", "[ff7f] equal", ""), ScriptTest("32768", "[008000] equal", ""), ScriptTest("8388607", "[ffff7f] equal", ""), ScriptTest("8388608", "[00008000] equal", ""), ScriptTest("2147483647", "[ffffff7f] equal", ""), ScriptTest("2147483648", "[0000008000] equal", ""), ScriptTest("549755813887", "[ffffffff7f] equal", ""), ScriptTest("549755813888", "[000000008000] equal", ""), ScriptTest("9223372036854775807", "[ffffffffffffff7f] equal", ""), ScriptTest("-1", "[81] equal", "numbers are little-endian with the msb being a sign bit"), ScriptTest("-127", "[ff] equal", ""), ScriptTest("-128", "[8080] equal", ""), ScriptTest("-32767", "[ffff] equal", ""), ScriptTest("-32768", "[008080] equal", ""), ScriptTest("-8388607", "[ffffff] equal", ""), ScriptTest("-8388608", "[00008080] equal", ""), ScriptTest("-2147483647", "[ffffffff] equal", ""), ScriptTest("-2147483648", "[0000008080] equal", ""), ScriptTest("-4294967295", "[ffffffff80] equal", ""), ScriptTest("-549755813887", "[ffffffffff] equal", ""), ScriptTest("-549755813888", "[000000008080] equal", ""), ScriptTest("-9223372036854775807", "[ffffffffffffffff] equal", ""), ScriptTest("2147483647", "add1 2147483648 equal", "we can do math on 4-byte integers, and compare 5-byte ones"), ScriptTest("2147483647", "add1 1", ""), ScriptTest("-2147483647", "add1 1", ""), ScriptTest("1", "[0100] equal not", "not the same byte array..."), ScriptTest("1", "[0100] numequal", "... but they are numerically equal"), ScriptTest("11", "[1.0b0000] numequal", ""), ScriptTest("0", "[80] equal not", ""), ScriptTest("0", "[80] numequal", "zero numerically equals negative zero"), ScriptTest("0", "[0080] numequal", ""), ScriptTest("[000080]", "[00000080] numequal", ""), ScriptTest("[100080]", "[10000080] numequal", ""), ScriptTest("[100000]", "[10000000] numequal", ""), ScriptTest("nop", "nop 1", "the following tests check the if(stack.size() < n) tests in each opcode"), ScriptTest("1", "if 1 endif", "they are here to catch copy-and-paste errors"), ScriptTest("0", "notif 1 endif", "most of them are duplicated elsewhere,"), ScriptTest("1", "verify 1", "but, hey, more is always better, right?"), ScriptTest("0", "toaltstack 1", ""), ScriptTest("1", "toaltstack fromaltstack", ""), ScriptTest("0 0", "drop2 1", ""), ScriptTest("0 1", "dup2", ""), ScriptTest("0 0 1", "dup3", ""), ScriptTest("0 1 0 0", "over2", ""), ScriptTest("0 1 0 0 0 0", "rot2", ""), ScriptTest("0 1 0 0", "swap2", ""), ScriptTest("1", "ifdup", ""), ScriptTest("nop", "depth 1", ""), ScriptTest("0", "drop 1", ""), ScriptTest("1", "dup", ""), ScriptTest("0 1", "nip", ""), ScriptTest("1 0", "over", ""), ScriptTest("1 0 0 0 3", "pick", ""), ScriptTest("1 0", "pick", ""), ScriptTest("1 0 0 0 3", "roll", ""), ScriptTest("1 0", "roll", ""), ScriptTest("1 0 0", "rot", ""), ScriptTest("1 0", "swap", ""), ScriptTest("0 1", "tuck", ""), ScriptTest("1", "size", ""), ScriptTest("0 0", "equal", ""), ScriptTest("0 0", "equalverify 1", ""), ScriptTest("0", "add1", ""), ScriptTest("2", "sub1", ""), ScriptTest("-1", "negate", ""), ScriptTest("-1", "abs", ""), ScriptTest("0", "not", ""), ScriptTest("-1", "nonzero", ""), ScriptTest("1 0", "add", ""), ScriptTest("1 0", "sub", ""), ScriptTest("-1 -1", "booland", ""), ScriptTest("-1 0", "boolor", ""), ScriptTest("0 0", "numequal", ""), ScriptTest("0 0", "numequalverify 1", ""), ScriptTest("-1 0", "numnotequal", ""), ScriptTest("-1 0", "lessthan", ""), ScriptTest("1 0", "greaterthan", ""), ScriptTest("0 0", "lessthanorequal", ""), ScriptTest("0 0", "greaterthanorequal", ""), ScriptTest("-1 0", "min", ""), ScriptTest("1 0", "max", ""), ScriptTest("-1 -1 0", "within", ""), ScriptTest("0", "ripemd160", ""), ScriptTest("0", "sha1", ""), ScriptTest("0", "sha256", ""), ScriptTest("0", "hash160", ""), ScriptTest("0", "hash256", ""), ScriptTest("nop", "codeseparator 1", ""), ScriptTest("nop", "nop1 1", ""), ScriptTest("nop", "nop4 1", ""), ScriptTest("nop", "nop5 1", ""), ScriptTest("nop", "nop6 1", ""), ScriptTest("nop", "nop7 1", ""), ScriptTest("nop", "nop8 1", ""), ScriptTest("nop", "nop9 1", ""), ScriptTest("nop", "nop10 1", ""), ScriptTest("[42424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242]", "[2.42424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242] equal", "basic push signedness check"), ScriptTest("[1.42424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242]", "[2.42424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242] equal", "basic pushdata1 signedness check"), ScriptTest("0x00", "size 0 equal", "basic op_0 execution") ] for test in valid_context_free_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, true)) XCTAssert(verifyScript(test, tx, outputScript, .allRules, true)) } } func test_script__context_free__invalid() { let invalid_context_free_scripts = [ ScriptTest("", "depth", "test the test: we should have an empty stack after scriptsig evaluation"), ScriptTest(" ", "depth", "and multiple spaces should not change that."), ScriptTest(" ", "depth", ""), ScriptTest(" ", "depth", ""), ScriptTest("", "", ""), ScriptTest("", "nop", ""), ScriptTest("", "nop depth", ""), ScriptTest("nop", "", ""), ScriptTest("nop", "depth", ""), ScriptTest("nop", "nop", ""), ScriptTest("nop", "nop depth", ""), ScriptTest("depth", "", ""), // Reserved. ScriptTest("1", "if 0x50 endif 1", "0x50 is reserved"), ScriptTest("0x52", "0x5f add 0x60 equal", "0x51 through 0x60 push 1 through 16 onto stack"), ScriptTest("0", "nop", ""), // Reserved. ScriptTest("1", "if ver else 1 endif", "ver is reserved"), ScriptTest("0", "if verif else 1 endif", "verif illegal everywhere (but also reserved?)"), ScriptTest("0", "if else 1 else verif endif", "verif illegal everywhere (but also reserved?)"), ScriptTest("0", "if vernotif else 1 endif", "vernotif illegal everywhere (but also reserved?)"), ScriptTest("0", "if else 1 else vernotif endif", "vernotif illegal everywhere (but also reserved?)"), ScriptTest("1 if", "1 endif", "if/endif can't span scriptsig/scriptpubkey"), ScriptTest("1 if 0 endif", "1 endif", ""), ScriptTest("1 else 0 endif", "1", ""), ScriptTest("0 notif", "123", ""), ScriptTest("0", "dup if endif", ""), ScriptTest("0", "if 1 endif", ""), ScriptTest("0", "dup if else endif", ""), ScriptTest("0", "if 1 else endif", ""), ScriptTest("0", "notif else 1 endif", ""), ScriptTest("0 1", "if if 1 else 0 endif endif", ""), ScriptTest("0 0", "if if 1 else 0 endif endif", ""), ScriptTest("1 0", "if if 1 else 0 endif else if 0 else 1 endif endif", ""), ScriptTest("0 1", "if if 1 else 0 endif else if 0 else 1 endif endif", ""), ScriptTest("0 0", "notif if 1 else 0 endif endif", ""), ScriptTest("0 1", "notif if 1 else 0 endif endif", ""), ScriptTest("1 1", "notif if 1 else 0 endif else if 0 else 1 endif endif", ""), ScriptTest("0 0", "notif if 1 else 0 endif else if 0 else 1 endif endif", ""), ScriptTest("1", "if return else else 1 endif", "multiple elses"), ScriptTest("1", "if 1 else else return endif", ""), ScriptTest("1", "endif", "malformed if/else/endif sequence"), ScriptTest("1", "else endif", ""), ScriptTest("1", "endif else", ""), ScriptTest("1", "endif else if", ""), ScriptTest("1", "if else endif else", ""), ScriptTest("1", "if else endif else endif", ""), ScriptTest("1", "if endif endif", ""), ScriptTest("1", "if else else endif endif", ""), ScriptTest("1", "return", ""), ScriptTest("1", "dup if return endif", ""), ScriptTest("1", "return 'data'", "canonical prunable txout format"), ScriptTest("0 if", "return endif 1", "still prunable because if/endif can't span scriptsig/scriptpubkey"), ScriptTest("0", "verify 1", ""), ScriptTest("1", "verify", ""), ScriptTest("1", "verify 0", ""), ScriptTest("1 toaltstack", "fromaltstack 1", "alt stack not shared between sig/pubkey"), ScriptTest("ifdup", "depth 0 equal", ""), ScriptTest("drop", "depth 0 equal", ""), ScriptTest("dup", "depth 0 equal", ""), ScriptTest("1", "dup 1 add 2 equalverify 0 equal", ""), ScriptTest("nop", "nip", ""), ScriptTest("nop", "1 nip", ""), ScriptTest("nop", "1 0 nip", ""), ScriptTest("nop", "over 1", ""), ScriptTest("1", "over", ""), ScriptTest("0 1", "over depth 3 equalverify", ""), ScriptTest("19 20 21", "pick 19 equalverify depth 2 equal", ""), ScriptTest("nop", "0 pick", ""), ScriptTest("1", "-1 pick", ""), ScriptTest("19 20 21", "0 pick 20 equalverify depth 3 equal", ""), ScriptTest("19 20 21", "1 pick 21 equalverify depth 3 equal", ""), ScriptTest("19 20 21", "2 pick 22 equalverify depth 3 equal", ""), ScriptTest("nop", "0 roll", ""), ScriptTest("1", "-1 roll", ""), ScriptTest("19 20 21", "0 roll 20 equalverify depth 2 equal", ""), ScriptTest("19 20 21", "1 roll 21 equalverify depth 2 equal", ""), ScriptTest("19 20 21", "2 roll 22 equalverify depth 2 equal", ""), ScriptTest("nop", "rot 1", ""), ScriptTest("nop", "1 rot 1", ""), ScriptTest("nop", "1 2 rot 1", ""), ScriptTest("nop", "0 1 2 rot", ""), ScriptTest("nop", "swap 1", ""), ScriptTest("1", "swap 1", ""), ScriptTest("0 1", "swap 1 equalverify", ""), ScriptTest("nop", "tuck 1", ""), ScriptTest("1", "tuck 1", ""), ScriptTest("1 0", "tuck depth 3 equalverify swap drop2", ""), ScriptTest("nop", "dup2 1", ""), ScriptTest("1", "dup2 1", ""), ScriptTest("nop", "dup3 1", ""), ScriptTest("1", "dup3 1", ""), ScriptTest("1 2", "dup3 1", ""), ScriptTest("nop", "over2 1", ""), ScriptTest("1", "2 3 over2 1", ""), ScriptTest("nop", "swap2 1", ""), ScriptTest("1", "2 3 swap2 1", ""), // Disabled. ScriptTest("'a' 'b'", "cat", "cat disabled"), ScriptTest("'a' 'b' 0", "if cat else 1 endif", "cat disabled"), ScriptTest("'abc' 1 1", "substr", "substr disabled"), ScriptTest("'abc' 1 1 0", "if substr else 1 endif", "substr disabled"), ScriptTest("'abc' 2 0", "if left else 1 endif", "left disabled"), ScriptTest("'abc' 2 0", "if right else 1 endif", "right disabled"), ScriptTest("nop", "size 1", ""), // Disabled. ScriptTest("'abc'", "if invert else 1 endif", "invert disabled"), ScriptTest("1 2 0 if and else 1 endif", "nop", "and disabled"), ScriptTest("1 2 0 if or else 1 endif", "nop", "or disabled"), ScriptTest("1 2 0 if xor else 1 endif", "nop", "xor disabled"), ScriptTest("2 0 if 2mul else 1 endif", "nop", "2mul disabled"), ScriptTest("2 0 if 2div else 1 endif", "nop", "2div disabled"), ScriptTest("2 2 0 if mul else 1 endif", "nop", "mul disabled"), ScriptTest("2 2 0 if div else 1 endif", "nop", "div disabled"), ScriptTest("2 2 0 if mod else 1 endif", "nop", "mod disabled"), ScriptTest("2 2 0 if lshift else 1 endif", "nop", "lshift disabled"), ScriptTest("2 2 0 if rshift else 1 endif", "nop", "rshift disabled"), ScriptTest("0 1", "equal", ""), ScriptTest("1 1 add", "0 equal", ""), ScriptTest("11 1 add 12 sub", "11 equal", ""), ScriptTest("2147483648 0 add", "nop", "arithmetic operands must be in range [-2^31...2^31] "), ScriptTest("-2147483648 0 add", "nop", "arithmetic operands must be in range [-2^31...2^31] "), ScriptTest("2147483647 dup add", "4294967294 numequal", "numequal must be in numeric range"), ScriptTest("'abcdef' not", "0 equal", "not is an arithmetic operand"), // Disabled. ScriptTest("2 dup mul", "4 equal", "mul disabled"), ScriptTest("2 dup div", "1 equal", "div disabled"), ScriptTest("2 2mul", "4 equal", "2mul disabled"), ScriptTest("2 2div", "1 equal", "2div disabled"), ScriptTest("7 3 mod", "1 equal", "mod disabled"), ScriptTest("2 2 lshift", "8 equal", "lshift disabled"), ScriptTest("2 1 rshift", "1 equal", "rshift disabled"), ScriptTest("1", "nop1 nop2 nop3 nop4 nop5 nop6 nop7 nop8 nop9 nop10 2 equal", ""), ScriptTest("'nop_1_to_10' nop1 nop2 nop3 nop4 nop5 nop6 nop7 nop8 nop9 nop10", "'nop_1_to_11' equal", ""), // Reserved. ScriptTest("0x50", "1", "opcode 0x50 is reserved"), ScriptTest("1", "if 0xba else 1 endif", "opcode 0xba invalid if executed"), ScriptTest("1", "if 0xbb else 1 endif", "opcode 0xbb invalid if executed"), ScriptTest("1", "if 0xbc else 1 endif", "opcode 0xbc invalid if executed"), ScriptTest("1", "if 0xbd else 1 endif", "opcode 0xbd invalid if executed"), ScriptTest("1", "if 0xbe else 1 endif", "opcode 0xbe invalid if executed"), ScriptTest("1", "if 0xbf else 1 endif", "opcode 0xbf invalid if executed"), ScriptTest("1", "if 0xc0 else 1 endif", "opcode 0xc0 invalid if executed"), ScriptTest("1", "if 0xc1 else 1 endif", "opcode 0xc1 invalid if executed"), ScriptTest("1", "if 0xc2 else 1 endif", "opcode 0xc2 invalid if executed"), ScriptTest("1", "if 0xc3 else 1 endif", "opcode 0xc3 invalid if executed"), ScriptTest("1", "if 0xc4 else 1 endif", "opcode 0xc4 invalid if executed"), ScriptTest("1", "if 0xc5 else 1 endif", "opcode 0xc5 invalid if executed"), ScriptTest("1", "if 0xc6 else 1 endif", "opcode 0xc6 invalid if executed"), ScriptTest("1", "if 0xc7 else 1 endif", "opcode 0xc7 invalid if executed"), ScriptTest("1", "if 0xc8 else 1 endif", "opcode 0xc8 invalid if executed"), ScriptTest("1", "if 0xc9 else 1 endif", "opcode 0xc9 invalid if executed"), ScriptTest("1", "if 0xca else 1 endif", "opcode 0xca invalid if executed"), ScriptTest("1", "if 0xcb else 1 endif", "opcode 0xcb invalid if executed"), ScriptTest("1", "if 0xcc else 1 endif", "opcode 0xcc invalid if executed"), ScriptTest("1", "if 0xcd else 1 endif", "opcode 0xcd invalid if executed"), ScriptTest("1", "if 0xce else 1 endif", "opcode 0xce invalid if executed"), ScriptTest("1", "if 0xcf else 1 endif", "opcode 0xcf invalid if executed"), ScriptTest("1", "if 0xd0 else 1 endif", "opcode 0xd0 invalid if executed"), ScriptTest("1", "if 0xd1 else 1 endif", "opcode 0xd1 invalid if executed"), ScriptTest("1", "if 0xd2 else 1 endif", "opcode 0xd2 invalid if executed"), ScriptTest("1", "if 0xd3 else 1 endif", "opcode 0xd3 invalid if executed"), ScriptTest("1", "if 0xd4 else 1 endif", "opcode 0xd4 invalid if executed"), ScriptTest("1", "if 0xd5 else 1 endif", "opcode 0xd5 invalid if executed"), ScriptTest("1", "if 0xd6 else 1 endif", "opcode 0xd6 invalid if executed"), ScriptTest("1", "if 0xd7 else 1 endif", "opcode 0xd7 invalid if executed"), ScriptTest("1", "if 0xd8 else 1 endif", "opcode 0xd8 invalid if executed"), ScriptTest("1", "if 0xd9 else 1 endif", "opcode 0xd9 invalid if executed"), ScriptTest("1", "if 0xda else 1 endif", "opcode 0xda invalid if executed"), ScriptTest("1", "if 0xdb else 1 endif", "opcode 0xdb invalid if executed"), ScriptTest("1", "if 0xdc else 1 endif", "opcode 0xdc invalid if executed"), ScriptTest("1", "if 0xdd else 1 endif", "opcode 0xdd invalid if executed"), ScriptTest("1", "if 0xde else 1 endif", "opcode 0xde invalid if executed"), ScriptTest("1", "if 0xdf else 1 endif", "opcode 0xdf invalid if executed"), ScriptTest("1", "if 0xe0 else 1 endif", "opcode 0xe0 invalid if executed"), ScriptTest("1", "if 0xe1 else 1 endif", "opcode 0xe1 invalid if executed"), ScriptTest("1", "if 0xe2 else 1 endif", "opcode 0xe2 invalid if executed"), ScriptTest("1", "if 0xe3 else 1 endif", "opcode 0xe3 invalid if executed"), ScriptTest("1", "if 0xe4 else 1 endif", "opcode 0xe4 invalid if executed"), ScriptTest("1", "if 0xe5 else 1 endif", "opcode 0xe5 invalid if executed"), ScriptTest("1", "if 0xe6 else 1 endif", "opcode 0xe6 invalid if executed"), ScriptTest("1", "if 0xe7 else 1 endif", "opcode 0xe7 invalid if executed"), ScriptTest("1", "if 0xe8 else 1 endif", "opcode 0xe8 invalid if executed"), ScriptTest("1", "if 0xe9 else 1 endif", "opcode 0xe9 invalid if executed"), ScriptTest("1", "if 0xea else 1 endif", "opcode 0xea invalid if executed"), ScriptTest("1", "if 0xeb else 1 endif", "opcode 0xeb invalid if executed"), ScriptTest("1", "if 0xec else 1 endif", "opcode 0xec invalid if executed"), ScriptTest("1", "if 0xed else 1 endif", "opcode 0xed invalid if executed"), ScriptTest("1", "if 0xee else 1 endif", "opcode 0xee invalid if executed"), ScriptTest("1", "if 0xef else 1 endif", "opcode 0xef invalid if executed"), ScriptTest("1", "if 0xf0 else 1 endif", "opcode 0xf0 invalid if executed"), ScriptTest("1", "if 0xf1 else 1 endif", "opcode 0xf1 invalid if executed"), ScriptTest("1", "if 0xf2 else 1 endif", "opcode 0xf2 invalid if executed"), ScriptTest("1", "if 0xf3 else 1 endif", "opcode 0xf3 invalid if executed"), ScriptTest("1", "if 0xf4 else 1 endif", "opcode 0xf4 invalid if executed"), ScriptTest("1", "if 0xf5 else 1 endif", "opcode 0xf5 invalid if executed"), ScriptTest("1", "if 0xf6 else 1 endif", "opcode 0xf6 invalid if executed"), ScriptTest("1", "if 0xf7 else 1 endif", "opcode 0xf7 invalid if executed"), ScriptTest("1", "if 0xf8 else 1 endif", "opcode 0xf8 invalid if executed"), ScriptTest("1", "if 0xf9 else 1 endif", "opcode 0xf9 invalid if executed"), ScriptTest("1", "if 0xfa else 1 endif", "opcode 0xfa invalid if executed"), ScriptTest("1", "if 0xfb else 1 endif", "opcode 0xfb invalid if executed"), ScriptTest("1", "if 0xfc else 1 endif", "opcode 0xfc invalid if executed"), ScriptTest("1", "if 0xfd else 1 endif", "opcode 0xfd invalid if executed"), ScriptTest("1", "if 0xfe else 1 endif", "opcode 0xfe invalid if executed"), ScriptTest("1", "if 0xff else 1 endif", "opcode 0xff invalid if executed"), ScriptTest("1 if 1 else", "0xff endif", "invalid because scriptsig and scriptpubkey are processed separately"), ScriptTest("nop", "ripemd160", ""), ScriptTest("nop", "sha1", ""), ScriptTest("nop", "sha256", ""), ScriptTest("nop", "hash160", ""), ScriptTest("nop", "hash256", ""), ScriptTest("nop", "'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'", ">520 byte push"), ScriptTest("0", "if 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' endif 1", ">520 byte push in non-executed if branch"), ScriptTest("1", "0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61", ">201 opcodes executed. 0x61 is nop"), ScriptTest("0", "if 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 endif 1", ">201 opcodes including non-executed if branch. 0x61 is nop"), ScriptTest("1 2 3 4 5 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 0x6f 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0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61 0x61", "10,001-byte scriptpubkey"), ScriptTest("nop1", "nop10", ""), // Reserved. ScriptTest("1", "ver", "op_ver is reserved"), ScriptTest("1", "verif", "op_verif is reserved"), ScriptTest("1", "vernotif", "op_vernotif is reserved"), ScriptTest("1", "reserved", "op_reserved is reserved"), ScriptTest("1", "reserved1", "op_reserved1 is reserved"), ScriptTest("1", "reserved2", "op_reserved2 is reserved"), ScriptTest("1", "0xba", "0xba == op_nop10 + 1"), ScriptTest("2147483648", "add1 1", "we cannot do math on 5-byte integers"), ScriptTest("2147483648", "negate 1", "we cannot do math on 5-byte integers"), ScriptTest("-2147483648", "add1 1", "because we use a sign bit, -2147483648 is also 5 bytes"), ScriptTest("2147483647", "add1 sub1 1", "we cannot do math on 5-byte integers, even if the result is 4-bytes"), ScriptTest("2147483648", "sub1 1", "we cannot do math on 5-byte integers, even if the result is 4-bytes"), ScriptTest("1", "1 endif", "endif without if"), ScriptTest("1", "if 1", "if without endif"), ScriptTest("1 if 1", "endif", "ifs don't carry over"), ScriptTest("nop", "if 1 endif", "the following tests check the if(stack.size() < n) tests in each opcode"), ScriptTest("nop", "notif 1 endif", "they are here to catch copy-and-paste errors"), ScriptTest("nop", "verify 1", "most of them are duplicated elsewhere,"), ScriptTest("nop", "toaltstack 1", "but, hey, more is always better, right?"), ScriptTest("1", "fromaltstack", ""), ScriptTest("1", "drop2 1", ""), ScriptTest("1", "dup2", ""), ScriptTest("1 1", "dup3", ""), ScriptTest("1 1 1", "over2", ""), ScriptTest("1 1 1 1 1", "rot2", ""), ScriptTest("1 1 1", "swap2", ""), ScriptTest("nop", "ifdup 1", ""), ScriptTest("nop", "drop 1", ""), ScriptTest("nop", "dup 1", ""), ScriptTest("1", "nip", ""), ScriptTest("1", "over", ""), ScriptTest("1 1 1 3", "pick", ""), ScriptTest("0", "pick 1", ""), ScriptTest("1 1 1 3", "roll", ""), ScriptTest("0", "roll 1", ""), ScriptTest("1 1", "rot", ""), ScriptTest("1", "swap", ""), ScriptTest("1", "tuck", ""), ScriptTest("nop", "size 1", ""), ScriptTest("1", "equal 1", ""), ScriptTest("1", "equalverify 1", ""), ScriptTest("nop", "add1 1", ""), ScriptTest("nop", "sub1 1", ""), ScriptTest("nop", "negate 1", ""), ScriptTest("nop", "abs 1", ""), ScriptTest("nop", "not 1", ""), ScriptTest("nop", "nonzero 1", ""), ScriptTest("1", "add", ""), ScriptTest("1", "sub", ""), ScriptTest("1", "booland", ""), ScriptTest("1", "boolor", ""), ScriptTest("1", "numequal", ""), ScriptTest("1", "numequalverify 1", ""), ScriptTest("1", "numnotequal", ""), ScriptTest("1", "lessthan", ""), ScriptTest("1", "greaterthan", ""), ScriptTest("1", "lessthanorequal", ""), ScriptTest("1", "greaterthanorequal", ""), ScriptTest("1", "min", ""), ScriptTest("1", "max", ""), ScriptTest("1 1", "within", ""), ScriptTest("nop", "ripemd160 1", ""), ScriptTest("nop", "sha1 1", ""), ScriptTest("nop", "sha256 1", ""), ScriptTest("nop", "hash160 1", ""), ScriptTest("nop", "hash256 1", ""), ScriptTest("0x00", "'00' equal", "basic op_0 execution") ] for test in invalid_context_free_scripts { let (tx, outputScript) = makeTransaction(for: test) XCTAssert(tx.isValid) XCTAssert(verifyScript(test, tx, outputScript, .noRules, false)) XCTAssert(verifyScript(test, tx, outputScript, .allRules, false)) } } func test_script__checksig__single__uses_one_hash() { let transaction = try! "0100000002dc38e9359bd7da3b58386204e186d9408685f427f5e513666db735aa8a6b2169000000006a47304402205d8feeb312478e468d0b514e63e113958d7214fa572acd87079a7f0cc026fc5c02200fa76ea05bf243af6d0f9177f241caf606d01fcfd5e62d6befbca24e569e5c27032102100a1a9ca2c18932d6577c58f225580184d0e08226d41959874ac963e3c1b2feffffffffdc38e9359bd7da3b58386204e186d9408685f427f5e513666db735aa8a6b2169010000006b4830450220087ede38729e6d35e4f515505018e659222031273b7366920f393ee3ab17bc1e022100ca43164b757d1a6d1235f13200d4b5f76dd8fda4ec9fc28546b2df5b1211e8df03210275983913e60093b767e85597ca9397fb2f418e57f998d6afbbc536116085b1cbffffffff0140899500000000001976a914fcc9b36d38cf55d7d5b4ee4dddb6b2c17612f48c88ac00000000" |> dataLiteral |> deserializeTransaction let signature = try! "30450220087ede38729e6d35e4f515505018e659222031273b7366920f393ee3ab17bc1e022100ca43164b757d1a6d1235f13200d4b5f76dd8fda4ec9fc28546b2df5b1211e8df" |> dataLiteral |> tagDERSignature |> toECSignature let publicKey = try! "0275983913e60093b767e85597ca9397fb2f418e57f998d6afbbc536116085b1cb" |> dataLiteral |> toECPublicKey let script = try! "76a91433cef61749d11ba2adf091a5e045678177fe3a6d88ac" |> dataLiteral |> deserializeScript XCTAssert(checkSignature(signature, sigHashType: .single, publicKey: publicKey, script: script, transaction: transaction, inputIndex: 1)) } func test_script__checksig__normal__success() { let transaction = try! "0100000002dc38e9359bd7da3b58386204e186d9408685f427f5e513666db735aa8a6b2169000000006a47304402205d8feeb312478e468d0b514e63e113958d7214fa572acd87079a7f0cc026fc5c02200fa76ea05bf243af6d0f9177f241caf606d01fcfd5e62d6befbca24e569e5c27032102100a1a9ca2c18932d6577c58f225580184d0e08226d41959874ac963e3c1b2feffffffffdc38e9359bd7da3b58386204e186d9408685f427f5e513666db735aa8a6b2169010000006b4830450220087ede38729e6d35e4f515505018e659222031273b7366920f393ee3ab17bc1e022100ca43164b757d1a6d1235f13200d4b5f76dd8fda4ec9fc28546b2df5b1211e8df03210275983913e60093b767e85597ca9397fb2f418e57f998d6afbbc536116085b1cbffffffff0140899500000000001976a914fcc9b36d38cf55d7d5b4ee4dddb6b2c17612f48c88ac00000000" |> dataLiteral |> deserializeTransaction let signature = try! "304402205d8feeb312478e468d0b514e63e113958d7214fa572acd87079a7f0cc026fc5c02200fa76ea05bf243af6d0f9177f241caf606d01fcfd5e62d6befbca24e569e5c27" |> dataLiteral |> tagDERSignature |> toECSignature let publicKey = try! "02100a1a9ca2c18932d6577c58f225580184d0e08226d41959874ac963e3c1b2fe" |> dataLiteral |> toECPublicKey let script = try! "76a914fcc9b36d38cf55d7d5b4ee4dddb6b2c17612f48c88ac" |> dataLiteral |> deserializeScript XCTAssert(checkSignature(signature, sigHashType: .single, publicKey: publicKey, script: script, transaction: transaction, inputIndex: 0)) } func test_script__create_endorsement__single_input_single_output__expected() { let transaction = try! "0100000001b3807042c92f449bbf79b33ca59d7dfec7f4cc71096704a9c526dddf496ee0970100000000ffffffff01905f0100000000001976a91418c0bd8d1818f1bf99cb1df2269c645318ef7b7388ac00000000" |> dataLiteral |> deserializeTransaction let script = try! "dup hash160 [88350574280395ad2c3e2ee20e322073d94e5e40] equalverify checksig" |> toScript let privateKey = try! "ce8f4b713ffdd2658900845251890f30371856be201cd1f5b3d970f793634333" |> tagBitcoinHash |> toData |> toECPrivateKey let endorsement = try! createEndorsement(privateKey: privateKey, script: script, transaction: transaction, inputIndex: 0, sigHashType: .all) XCTAssert(endorsement® |> toBase16 == "3045022100e428d3cc67a724cb6cfe8634aa299e58f189d9c46c02641e936c40cc16c7e8ed0220083949910fe999c21734a1f33e42fca15fb463ea2e08f0a1bccd952aacaadbb801") } func test_script__create_endorsement__single_input_no_output__expected() { let transaction = try! "0100000001b3807042c92f449bbf79b33ca59d7dfec7f4cc71096704a9c526dddf496ee0970000000000ffffffff0000000000" |> dataLiteral |> deserializeTransaction let script = try! "dup hash160 [88350574280395ad2c3e2ee20e322073d94e5e40] equalverify checksig" |> toScript let privateKey = try! "ce8f4b713ffdd2658900845251890f30371856be201cd1f5b3d970f793634333" |> tagBitcoinHash |> toData |> toECPrivateKey let endorsement = try! createEndorsement(privateKey: privateKey, script: script, transaction: transaction, inputIndex: 0, sigHashType: .all) XCTAssert(endorsement® |> toBase16 == "3045022100ba57820be5f0b93a0d5b880fbf2a86f819d959ecc24dc31b6b2d4f6ed286f253022071ccd021d540868ee10ca7634f4d270dfac7aea0d5912cf2b104111ac9bc756b01") } func test_script__generate_signature_hash__all__expected() { let transaction = try! "0100000001b3807042c92f449bbf79b33ca59d7dfec7f4cc71096704a9c526dddf496ee0970000000000ffffffff0000000000" |> dataLiteral |> deserializeTransaction let script = try! "dup hash160 [88350574280395ad2c3e2ee20e322073d94e5e40] equalverify checksig" |> toScript let hash = generateSignatureHash(transaction: transaction, inputIndex: 0, script: script, sigHashType: .all) XCTAssert(hash® |> toBase16 == "f89572635651b2e4f89778350616989183c98d1a721c911324bf9f17a0cf5bf0") } func testEndorsementSize() { XCTAssertNoThrow(try "b34ae13c097ec7a206b515b0cc3ff4b2c2f4e0fce30298604be140cdc7a76b74" |> tagBase16 |> toData |> tagEndorsement) XCTAssertThrowsError(try "00112233" |> tagBase16 |> toData |> tagEndorsement) } }
0
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import UIKit class CarouselViewController_bis: UIViewController { // MARK: - Properties @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var pageControl: UIPageControl! var pageImages: [UIImage] = [] var pageViews: [UIImageView?] = [] var accessibilityLabels: [String] = [] var isAccessible = false // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() pageImages = [ UIImage(named: "carousel_img1.jpg")!, UIImage(named: "carousel_img2.jpg")!, UIImage(named: "carousel_img3.jpg")!, ] accessibilityLabels = [ "example_horizontalScroll_carousel_imageLabel1".localized, "example_horizontalScroll_carousel_imageLabel2".localized, "example_horizontalScroll_carousel_imageLabel3".localized ] pageControl.isHidden = !isAccessible pageControl.currentPage = 0 pageControl.numberOfPages = pageImages.count titleLabel.text = isAccessible ? "example_horizontalScroll_carousel_accessibleCarousel".localized : "example_horizontalScroll_carousel_nonAccessibleCarousel".localized } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setUpCarousel() } override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { for i:NSInteger in 0..<pageImages.count { pageViews[i]?.removeFromSuperview() } pageViews.removeAll() setUpCarousel() } // MARK: - Private methods func setUpCarousel() { for i:NSInteger in 0..<pageImages.count { let pageView = UIImageView(image: pageImages[i]) pageView.contentMode = .scaleAspectFit pageView.frame = CGRect( x: scrollView.frame.size.width * CGFloat(i), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height).insetBy(dx: 10.0, dy: 0.0) pageView.accessibilityLabel = accessibilityLabels[i] pageView.isAccessibilityElement = true if isAccessible && i == 1 || isAccessible && i == 2 { pageView.accessibilityTraits |= UIAccessibilityTraitButton } scrollView.addSubview(pageView) pageViews.append(pageView) } scrollView.contentSize = CGSize( width: scrollView.frame.size.width * CGFloat(pageImages.count), height: scrollView.frame.size.height) } func displayNextPage() { pageControl.currentPage = pageControl.currentPage+1 pageControlValueDidChange(pageControl) } @IBAction func pageControlValueDidChange(_ sender: UIPageControl) { if !isAccessible { return } let page = Int(floor((scrollView.contentOffset.x * 2.0 + scrollView.frame.size.width) / (scrollView.frame.size.width * 2.0))) scrollView.scrollRectToVisible(CGRect( x: scrollView.frame.size.width * CGFloat(sender.currentPage), y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: true) pageControl.currentPage = page } // MARK: - Scrollview delegate func scrollViewDidScroll(_ scrollView: UIScrollView) { let page = Int(floor((scrollView.contentOffset.x * 2.0 + scrollView.frame.size.width) / (scrollView.frame.size.width * 2.0))) // Update the page control pageControl.currentPage = page if isAccessible { UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, pageControl) } } }
0
import XCTest import Foundation //: Necessary code to make Learning Swift by Example work class SwiftExample<T : Equatable> { private var code : (() -> T) private var expectedResult : (() -> T)! init(code : @escaping () -> T){ self.code = code } func returns(expectedResult : @escaping () -> T) -> SwiftExample<T>{ self.expectedResult = expectedResult return self } func runExample() { XCTAssertEqual(code(), expectedResult()) } } func thisCode<T>(code : @escaping () -> T) -> SwiftExample<T>{ return SwiftExample<T>(code: code) } class SwiftExamplesTest : XCTestCase{ class func addTestForExample<T>(example : SwiftExample<T>, withName name : String){ let testToRun = { example.runExample() } let implementation = imp_implementationWithBlock(unsafeBitCast(testToRun as @convention(block) () -> (), to: AnyObject.self)) let methodName = Selector(name) let types = "v@:" class_addMethod(self, methodName, implementation, types) } } extension String { func forExample<T>(_ examples : SwiftExample<T>...){ forExample(examples) } func forInstance<T>(_ examples : SwiftExample<T>...){ forExample(examples) } func i_e<T>(_ examples : SwiftExample<T>...){ forExample(examples) } private func forExample<T>(_ examples : [SwiftExample<T>]){ for (index, example) in examples.enumerated(){ let methodName = getMethodName(index: index); SwiftExamplesTest.addTestForExample(example: example, withName: methodName) } } private func getMethodName(index : Int) -> String{ let charactersToRemove = NSCharacterSet.alphanumerics.inverted let strippedReplacement = self.components(separatedBy: charactersToRemove).joined(separator: "_") return "test\(strippedReplacement)_\(index)"; } } //: # Learning Swift by example /*: # Learn Swift by Example This is an attempt to teach the Swift Programming Language using itself and being able to execute it as a suite of Tests. The main goals are: 1. It should be easy to read, almost in plain English 2. It should be based in examples 3. Each example should be executable and self-tested */ //: ## Constants and variables "In Swift, we can define a constant by using the keyword let and specifying the type after the declaration".forExample( thisCode{ let constant : String = "Hello" return constant }.returns{ "Hello" } ) "Or we can define a variable by using the keyword var".forInstance( thisCode{ var variable : Int = 5 variable = 7 return variable }.returns{ 7 } ) "We don't even have to specify the type of a constant or variable since the compiler is able to infer it".i_e( thisCode{ var variable = 5 variable = 7 return variable }.returns{ 7 } ) "And crazily, we can name variables and constants with any Unicode characters - even emojis".forInstance( thisCode{ var 👍 = "Success" return 👍 }.returns{ "Success" } ) //: ## Numeric literals "We can write integer numbers using decimal, binary, octal or hexadecimal".i_e( thisCode{ 17 }.returns{ 17 }, thisCode{ 0b10001 }.returns{ 17 }, thisCode{ 0o21 }.returns{ 17 }, thisCode{ 0x11 }.returns{ 17 } ) "Also, we can improve readability of numbers by inserting underscores".forInstance( thisCode{ 1_000_000 }.returns{ 1000000 } ) //: ## Operations "In Swift, we have integer arithmetic operands".forExample( thisCode{ 2 + 2 }.returns{ 4 }, thisCode{ 5 - 8 }.returns{ -3 }, thisCode{ 4 * 6 }.returns{ 24 }, thisCode{ 30 / 5 }.returns{ 6 }, thisCode{ 39 % 7 }.returns{ 4 } ) "Operators are overloaded. + can concatenate two Strings".forInstance( thisCode{ "Hello " + "World" }.returns{ "Hello World" } ) "...or can add two numbers".i_e( thisCode{ 5 + 5 }.returns{ 10 } ) //: ## String manipulation "We can interpolate variables into strings".forExample( thisCode{ let salute = "World" return "Hello \(salute)" }.returns{ "Hello World" }, thisCode{ let age = 28 return "I am \(age) years old" }.returns{ "I am 28 years old" } ) //: ## Optionals "In Swift, if a variable can receive nil it has to be declared as optional (type followed by question mark) and we need to unwrap it before using it".forInstance( thisCode{ var optional : String? = nil if let unwrappedOptional = optional { return "Variable had a value" }else{ return "Variable was nil" } }.returns{ "Variable was nil" }, thisCode{ var optional : String? = "some value" if let unwrappedOptional = optional { return "Variable had a value" }else{ return "Variable was nil" } }.returns{ "Variable had a value" } ) //: Boilerplate to make the tests work class PlaygroundTestObserver : NSObject, XCTestObservation { @objc func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: UInt) { print("Test failed on line \(lineNumber): \(testCase.name), \(description)") } } let observer = PlaygroundTestObserver() let center = XCTestObservationCenter.shared() center.addTestObserver(observer) struct TestRunner { func runTests(testClass:AnyClass) { print("Running test suite \(testClass)") let tests = testClass as! XCTestCase.Type let testSuite = tests.defaultTestSuite() testSuite.run() let run = testSuite.testRun as! XCTestSuiteRun print("Ran \(run.executionCount) tests in \(run.testDuration)s with \(run.totalFailureCount) failures") } } //: Run your tests TestRunner().runTests(testClass: SwiftExamplesTest.self)
0
// /** * @Name: ObservableType+KakaJson.swift * @Description: * @Author: guoxiafei * @Date: 2020/5/11 * @Copyright: Copyright © 2020 China Electronic Intelligence System Technology Co., Ltd. All rights reserved. */ import Foundation import RxSwift import KakaJSON import Moya /// Extension for processing Responses into Convertible objects through KakaJSON public extension ObservableType where Element == Response { /// Maps data received from the signal into an object /// which implements the Convertible protocol and returns the result back /// If the conversion fails, the signal errors. func mapObject<T: Convertible>(_ type: T.Type) -> Observable<T> { return flatMap { response -> Observable<T> in Observable.just(try response.mapObject(type)) } } /// Maps data received from the signal into an array of objects /// which implement the Convertible protocol and returns the result back /// If the conversion fails, the signal errors. func mapArray<T: Convertible>(_ type: T.Type) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in Observable.just(try response.mapArray(type)) } } /// Maps data received from the signal into an object /// which implements the Convertible protocol and returns the result back /// If the conversion fails, the signal errors. func mapObject<T: Convertible>(_ type: T.Type, atKeyPath keyPath: String) -> Observable<T> { return flatMap { response -> Observable<T> in Observable.just(try response.mapObject(T.self, atKeyPath: keyPath)) } } /// Maps data received from the signal into an array of objects /// which implement the Convertible protocol and returns the result back /// If the conversion fails, the signal errors. func mapArray<T: Convertible>(_ type: T.Type, atKeyPath keyPath: String) -> Observable<[T]> { return flatMap { response -> Observable<[T]> in Observable.just(try response.mapArray(T.self, atKeyPath: keyPath)) } } }
0
import Foundation import os extension OSLog { static private let DEFAULT_BUNDLE_IDENTIFIER = "com.birdbraintechnologies.ble" convenience init(category: String) { self.init(subsystem: Bundle.main.bundleIdentifier ?? OSLog.DEFAULT_BUNDLE_IDENTIFIER, category: category) } }
0
// // JSONStringAide.swift // CICOPersistentTests // // Created by lucky.li on 2018/8/4. // Copyright © 2018 cico. All rights reserved. // import Foundation class JSONStringAide { static func jsonString(name: String) -> String { let bundle = Bundle.init(for: JSONStringAide.self) guard let path = bundle.path(forResource: name, ofType: "json") else { return "" } guard let jsonString = try? String(contentsOfFile: path, encoding: String.Encoding.utf8) else { return "" } return jsonString } }
0
import Vapor extension Droplet { func setupRoutes() throws { let remindersController = RemindersController() remindersController.addRoutes(to: self) let usersControler = UsersController() usersControler.addRoutes(to: self) let categoriesController = CategoriesController() categoriesController.addRoutes(to: self) get("lily") { req in return "I love you" } } }
0
// // EmailValidator.swift // SwiftKit // // Created by Daniel Saidi on 2020-06-09. // Copyright © 2020 Daniel Saidi. All rights reserved. // import Foundation /** This `Validator` can be used to validate e-mail addresses. */ public class EmailValidator: Validator { public init() {} public func validate(_ string: String) -> Bool { let regExp = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,} ?" let predicate = NSPredicate(format: "SELF MATCHES %@", regExp) return predicate.evaluate(with: string) } }
0
// // ConversionViewController.swift // WorldTrotter // // Created by Fernando Razon on 7/6/18. // Copyright © 2018 d182_fernando_r. All rights reserved. // import UIKit class ConversionViewController: UIViewController, UITextFieldDelegate { //Outles referenciando al storyboard @IBOutlet var celsiusLabel: UILabel! @IBOutlet var textField: UITextField! //Variables de conversion de unidades var fahrenheitValue: Measurement<UnitTemperature>? { didSet{ updateCelsiusLabel() } } var celsiusValue: Measurement<UnitTemperature>? { if let fahrenheitValue = fahrenheitValue { return fahrenheitValue.converted(to: .celsius) } else { return nil } } override func viewDidLoad() { super.viewDidLoad() print("ConversionViewController loaded its view.") updateCelsiusLabel() } //Funcion que actualiza al label y se llama en el setter del farenheitValue func updateCelsiusLabel() { if let celsiusValue = celsiusValue { celsiusLabel.text = numberFormatter.string(from: NSNumber(value: celsiusValue.value)) } else { celsiusLabel.text = "???" } } //La funcion que se dispara al cambiar el textField.text es un casteo @IBAction func fahrenheitFieldEditingChanged(_ textField: UITextField) { if let text = textField.text, let value = Double(text) { fahrenheitValue = Measurement(value: value, unit: .fahrenheit) } else { fahrenheitValue = nil } } //Esta funcion permite que al tocar el background, el textField deje de ser el primer responder @IBAction func dismissKeyboard(_ sender: UITapGestureRecognizer) { textField.resignFirstResponder() } //Formateo de los numeros let numberFormatter: NumberFormatter = { let nf = NumberFormatter() nf.numberStyle = .decimal nf.minimumFractionDigits = 0 nf.maximumFractionDigits = 1 return nf }() //Funcion propia del delegado del textField permite o impide que ciertos caracteres //Sean agregados en el textField.text func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { //print("Current text: \(String(describing: textField.text))") //print("Replacement text: \(string)") let existingTextHasDecimalSeparator = textField.text?.range(of: ".") let replacementTextHasDecimalSeparator = string.range(of: ".") if existingTextHasDecimalSeparator != nil, replacementTextHasDecimalSeparator != nil { return false } else { return true } } }
0
// // Palette.swift // Pailead // // Created by Patrick Metcalfe on 1/4/18. // import Foundation /// Takes swatches and organizes them into a palette public class Palette { /// The swatches from the base image let swatches : Set<Swatch> /// A possible swatch that's from darker but vibrant range of image public var darkVibrantSwatch : Swatch? /// A possible swatch that's from vibrant range of image public var vibrantSwatch : Swatch? /// A possible swatch that's from lighter and vibrant range of image public var lightVibrantSwatch : Swatch? /// A possible swatch that's from darker and muted range of image public var darkMutedSwatch : Swatch? /// A possible swatch that's from muted range of image public var mutedSwatch : Swatch? /// A possible swatch that's from lighter but muted range of image public var lightMutedSwatch : Swatch? /// The highest population of all the base image's swatches internal let highestPopulation : Int /// Make a new PaletteMaker from a collection of swatches /// /// - Parameter swatches: The base image's swatches public init(baseImageSwatches : Set<Swatch>) { self.swatches = baseImageSwatches self.highestPopulation = swatches.map({ $0.count }).max() ?? 0 guard highestPopulation > 0 else { return } organizeSwatches() } /// Finds colors for each of the palette's requested swatches /// and fill unfound ones with generated ones internal func organizeSwatches() { findSwatches() generateEmptySwatches() } /// Finds colors for each of the palette's requested swatches internal func findSwatches() { vibrantSwatch = findColor(targetLuma: 0.5, minLuma: 0.3, maxLuma: 0.7, targetSaturation: 1, minSaturation: 0.35, maxSaturation: 1) lightVibrantSwatch = findColor(targetLuma: 0.74, minLuma: 0.55, maxLuma: 1, targetSaturation: 1, minSaturation: 0.35, maxSaturation: 1) darkVibrantSwatch = findColor(targetLuma: 0.26, minLuma: 0, maxLuma: 0.45, targetSaturation: 1, minSaturation: 0.35, maxSaturation: 1) mutedSwatch = findColor(targetLuma: 0.5, minLuma: 0.3, maxLuma: 0.7, targetSaturation: 0.3, minSaturation: 0, maxSaturation: 0.4) lightMutedSwatch = findColor(targetLuma: 0.74, minLuma: 0.55, maxLuma: 1, targetSaturation: 0.3, minSaturation: 0, maxSaturation: 0.4) darkMutedSwatch = findColor(targetLuma: 0.26, minLuma: 0, maxLuma: 0.45, targetSaturation: 0.3, minSaturation: 0, maxSaturation: 0.4) } /// Checks that the swatch isn't already chosen as a palette swatch /// /// - Parameter swatch: The swatch to check /// - Returns: Is the swatch already chosen internal func isAlreadySelected(_ swatch : Swatch) -> Bool { return vibrantSwatch == swatch || darkVibrantSwatch == swatch || lightVibrantSwatch == swatch || mutedSwatch == swatch || darkMutedSwatch == swatch || lightMutedSwatch == swatch } /// Loop through image's swatches and find one that's close to a target /// luminance and saturation /// /// - Parameters: /// - targetLuma: The most ideal luminance /// - minLuma: The min luminance that's acceptable /// - maxLuma: The max luminance that's acceptable /// - targetSaturation: The most ideal saturation /// - minSaturation: The min saturation that's acceptable /// - maxSaturation: The max saturation that's acceptable /// - Returns: A swatch from the base image that fits into range internal func findColor(targetLuma : Float, minLuma : Float, maxLuma : Float, targetSaturation : Float, minSaturation : Float, maxSaturation : Float) -> Swatch? { var max : Swatch? = nil var maxValue : Float = 0 let converter = HSLConverter() swatches.forEach { swatch in let (_, sat, luma) = converter.hslFor(swatch.pixel) if (sat >= minSaturation && sat <= maxSaturation && luma >= minLuma && luma <= maxLuma && !isAlreadySelected(swatch)) { let thisValue : Float = findComparisonValue(saturation: sat, targetSaturation: targetSaturation, luma: luma, targetLuma: targetLuma, population: swatch.count, highestPopulation: highestPopulation) if (max == nil || thisValue > maxValue) { max = swatch maxValue = thisValue; } } } return max } /// Reduce the swatch and the target swatch to a comparable value /// /// - Note: The specific weights were taken from Android's Palette /// open source code. /// /// - Parameters: /// - saturation: The current swatch saturation /// - targetSaturation: The target swatch saturation /// - luma: The current swatch luminance /// - targetLuma: The target swatch luminance /// - population: The number of times a pixel appears in the base image /// - highestPopulation: The highest population found in the base image /// - Returns: A weighted average of the distances from current swatch's values /// to the target swatch's internal func findComparisonValue(saturation : Float, targetSaturation : Float, luma : Float, targetLuma : Float, population : Int, highestPopulation : Int) -> Float { return weightedMean((invertDiff(value: saturation, targetValue: targetSaturation), 3), (invertDiff(value: luma, targetValue: targetLuma), 6.5), (Float(population) / Float(highestPopulation), 0.5)) } /// Returns a number between from -∞ to 1 where values closer /// to 1 represent `value` and `targetValue` being closer. /// /// - Note: When used with luminance and saturation which /// are (0, 1) this function returns a number between (0, 1) /// where 1 means the values are the same. /// /// This is used to weight swatches with close target lum/sat /// as more ideal. /// /// - Parameters: /// - value: The value to check against target /// - targetValue: The most ideal value /// - Returns: A float on (0, 1) where 1 is equality internal func invertDiff(value : Float, targetValue : Float) -> Float { return 1.0 - abs(value - targetValue) } /// Finds the average of a collection where each element is /// weighted by another value /// /// Unlike a normal average the values are–in some sense–counted /// multiple times where the number of times is their weight. /// This helps unbalance the scale to favor particular values. /// /// - Parameter values: List of (Element, Weight) /// - Returns: The weighted mean internal func weightedMean(_ values : (Float, Float)...) -> Float { var sum : Float = 0 var sumWeight : Float = 0 values.forEach { entry in sum += (entry.0 * entry.1) sumWeight += entry.1 } return sum / sumWeight } /// If certain swatches couldn't be found then we take /// darker swatches and lighten then and also the /// reverse internal func generateEmptySwatches() { let hslConverter = HSLConverter() if (vibrantSwatch == nil) { if let darkVibrant = darkVibrantSwatch { let hslOfDarkVibrant = hslConverter.hslFor(darkVibrant.pixel) let newPixel = hslConverter.pixelFor(hue: hslOfDarkVibrant.0, saturation: hslOfDarkVibrant.1, lumience: 0.5) vibrantSwatch = Swatch(newPixel, count: 0) } } if (darkVibrantSwatch == nil) { if let vibrant = vibrantSwatch { let hslOfVibrant = hslConverter.hslFor(vibrant.pixel) let newPixel = hslConverter.pixelFor(hue: hslOfVibrant.0, saturation: hslOfVibrant.1, lumience: 0.26) darkVibrantSwatch = Swatch(newPixel, count: 0) } } } }
0
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import MaterialComponents import SDWebImage import Firebase protocol FPCardCollectionViewCellDelegate: class { func showProfile(_ author: FPUser) func showTaggedPhotos(_ hashtag: String) func showLightbox(_ index: Int) func viewComments(_ post: FPPost) func toogleLike(_ post: FPPost, label: UILabel) func optionPost(_ post: FPPost, _ button: UIButton, completion: (() -> Swift.Void)? ) } class FPCardCollectionViewCell: MDCCardCollectionCell { @IBOutlet weak private var authorImageView: UIImageView! @IBOutlet weak private var authorLabel: UILabel! @IBOutlet weak private var dateLabel: UILabel! @IBOutlet weak private var postImageView: UIImageView! @IBOutlet weak private var titleLabel: UILabel! @IBOutlet weak private var likesLabel: UILabel! @IBOutlet weak private var likeButton: UIButton! @IBOutlet weak private var comment1Label: UILabel! @IBOutlet weak private var comment2Label: UILabel! @IBOutlet weak private var viewAllCommentsLabel: UIButton! var commentLabels: [UILabel]? let attributes = [NSAttributedString.Key.font: UIFont.mdc_preferredFont(forMaterialTextStyle: .body2)] var post: FPPost! weak var delegate: FPCardCollectionViewCellDelegate? var labelConstraints: [NSLayoutConstraint]! public var imageConstraint: NSLayoutConstraint? override func awakeFromNib() { super.awakeFromNib() authorImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(profileTapped))) authorLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(profileTapped))) postImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTapped))) authorImageView.isAccessibilityElement = true authorImageView.accessibilityHint = "Double-tap to open profile." commentLabels = [comment1Label, comment2Label] comment1Label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapOnComment(recognizer:)))) comment2Label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapOnComment(recognizer:)))) titleLabel.preferredMaxLayoutWidth = self.bounds.width - 16 comment1Label.preferredMaxLayoutWidth = titleLabel.preferredMaxLayoutWidth comment2Label.preferredMaxLayoutWidth = titleLabel.preferredMaxLayoutWidth } private func convertCacheTypeToString(_ cacheType: SDImageCacheType) -> String { switch cacheType { case .none: return "none" case .disk: return "disk" case .memory: return "memory" case .all: return "all" } } func populateContent(post: FPPost, index: Int, isDryRun: Bool) { if Auth.auth().currentUser!.isAnonymous { likeButton.isEnabled = false } self.post = post let postAuthor = post.author if !isDryRun, let profilePictureURL = postAuthor.profilePictureURL { UIImage.circleImage(with: profilePictureURL, to: authorImageView) authorImageView.accessibilityLabel = postAuthor.fullname } authorLabel.text = postAuthor.fullname dateLabel.text = post.postDate.timeAgo() postImageView.tag = index if !isDryRun { let trace = Performance.startTrace(name: "post_load") postImageView?.sd_setImage(with: post.thumbURL, completed: { image, error, cacheType, url in trace?.incrementMetric(self.convertCacheTypeToString(cacheType), by: 1) trace?.stop() }) postImageView.accessibilityLabel = "Photo by \(postAuthor.fullname)" } let title = NSMutableAttributedString(string: postAuthor.fullname + " ", attributes: attributes) let attrString = NSMutableAttributedString(string: post.text) let regex = try? NSRegularExpression(pattern: "(#[a-zA-Z0-9_\\p{Arabic}\\p{N}]*)", options: []) if let matches = regex?.matches(in: post.text, options:[], range:NSMakeRange(0, post.text.count)) { for match in matches { attrString.addAttribute(NSAttributedString.Key.link, value: (post.text as NSString).substring(with: match.range), range: match.range) attrString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue , range: match.range) } } title.append(attrString) title.addAttribute(.paragraphStyle, value: MDCSelfSizingStereoCell.paragraphStyle, range: NSMakeRange(0, title.length)) titleLabel.attributedText = title titleLabel.accessibilityLabel = "\(post.text), posted by \(postAuthor.fullname)" titleLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTapOnProfileLabel(recognizer:)))) likesLabel.text = post.likeCount == 1 ? "1 like" : "\(post.likeCount) likes" likesLabel.font = UIFont.mdc_preferredFont(forMaterialTextStyle: .body2) if post.isLiked { likeButton.setImage(#imageLiteral(resourceName: "ic_favorite"), for: .normal) likeButton.accessibilityLabel = "you liked this post" likeButton.accessibilityHint = "double-tap to unlike" } else { likeButton.setImage(#imageLiteral(resourceName: "ic_favorite_border"), for: .normal) likeButton.accessibilityLabel = "you haven't liked this post" likeButton.accessibilityHint = "double-tap to like" } if labelConstraints != nil { NSLayoutConstraint.deactivate(labelConstraints) labelConstraints = nil } let betweenConstant: CGFloat = 2 let bottomConstant: CGFloat = 12 let commentCount = post.comments.count switch commentCount { case 0: labelConstraints = [contentView.bottomAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: bottomConstant)] viewAllCommentsLabel.isHidden = true comment1Label.isHidden = true comment1Label.text = nil comment2Label.isHidden = true comment2Label.text = nil case 1: labelConstraints = [comment1Label.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: betweenConstant), contentView.bottomAnchor.constraint(equalTo: comment1Label.bottomAnchor, constant: bottomConstant)] viewAllCommentsLabel.isHidden = true attributeComment(index: 0) comment2Label.isHidden = true comment2Label.text = nil case 2: labelConstraints = [comment1Label.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: betweenConstant), comment2Label.topAnchor.constraint(equalTo: comment1Label.bottomAnchor, constant: betweenConstant), contentView.bottomAnchor.constraint(equalTo: comment2Label.bottomAnchor, constant: bottomConstant)] viewAllCommentsLabel.isHidden = true attributeComment(index: 0) attributeComment(index: 1) default: labelConstraints = [viewAllCommentsLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: betweenConstant), comment1Label.topAnchor.constraint(equalTo: viewAllCommentsLabel.bottomAnchor, constant: betweenConstant), comment2Label.topAnchor.constraint(equalTo: comment1Label.bottomAnchor, constant: betweenConstant), contentView.bottomAnchor.constraint(equalTo: comment2Label.bottomAnchor, constant: bottomConstant)] viewAllCommentsLabel.isHidden = false viewAllCommentsLabel.setTitle("View all \(commentCount) comments", for: .normal) attributeComment(index: 0) attributeComment(index: 1) } NSLayoutConstraint.activate(labelConstraints) } private func attributeComment(index: Int) { if let commentLabel = commentLabels?[index] { let comment = post.comments[index] commentLabel.isHidden = false commentLabel.accessibilityLabel = "\(comment.from.fullname) said, \(comment.text)" let text = NSMutableAttributedString(string: comment.from.fullname, attributes: attributes) text.append(NSAttributedString(string: " " + comment.text)) text.addAttribute(.paragraphStyle, value: MDCSelfSizingStereoCell.paragraphStyle, range: NSMakeRange(0, text.length)) commentLabel.attributedText = text } } override func updateConstraints() { super.updateConstraints() let constant = MDCCeil((self.bounds.width - 2) * 0.65) if imageConstraint == nil { imageConstraint = postImageView.heightAnchor.constraint(equalToConstant: constant) imageConstraint?.isActive = true } imageConstraint?.constant = constant } @IBAction func toggledLike() { delegate?.toogleLike(post, label: likesLabel) } @IBAction func tappedOption(_ sender: UIButton) { delegate?.optionPost(post, sender, completion: nil) } override func prepareForReuse() { super.prepareForReuse() NSLayoutConstraint.deactivate(labelConstraints) labelConstraints = nil } @objc func profileTapped() { delegate?.showProfile(post.author) } @objc func imageTapped() { delegate?.showLightbox(postImageView.tag) } @objc func handleTapOnProfileLabel(recognizer: UITapGestureRecognizer) { let touchIndex = recognizer.touchIndexInLabel(label: titleLabel) if touchIndex < post.author.fullname.count { profileTapped() } else if let tag = titleLabel.attributedText?.attribute(NSAttributedString.Key.link, at: touchIndex, effectiveRange: nil) as? String { delegate?.showTaggedPhotos(String(tag.dropFirst())) } } @objc func handleTapOnComment(recognizer: UITapGestureRecognizer) { if let index = recognizer.view?.tag { let from = post.comments[index].from if recognizer.didTapAttributedTextInLabel(label: commentLabels![index], inRange: NSRange(location: 0, length: from.fullname.count)) { delegate?.showProfile(from) } } } @IBAction func viewAllComments(_ sender: Any) { delegate?.viewComments(post) } var layerClass: AnyClass { return MDCShadowLayer.self } } extension UITapGestureRecognizer { func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool { return NSLocationInRange(touchIndexInLabel(label: label), targetRange) } func touchIndexInLabel(label: UILabel) -> Int { // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage let layoutManager = NSLayoutManager() let textContainer = NSTextContainer(size: CGSize.zero) let textStorage = NSTextStorage(attributedString: label.attributedText!) // Configure layoutManager and textStorage layoutManager.addTextContainer(textContainer) textStorage.addLayoutManager(layoutManager) // Configure textContainer textContainer.lineFragmentPadding = 0.0 textContainer.lineBreakMode = label.lineBreakMode textContainer.maximumNumberOfLines = label.numberOfLines let labelSize = label.bounds.size textContainer.size = labelSize // Find the tapped character location and compare it to the specified range let locationOfTouchInLabel = self.location(in: label) let textBoundingBox = layoutManager.usedRect(for: textContainer) let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y) let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y) let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) return indexOfCharacter } }
0
// // AriaGlobal.swift // AriaM3U8Downloader // // Created by 神崎H亚里亚 on 2019/11/28. // Copyright © 2019 moxcomic. All rights reserved. // import UIKit import RxSwift struct baseError: Error { var desc = "" var localizedDescription: String { return desc } init(_ desc: String) { self.desc = desc } } @objc public enum AriaDownloadStatus: Int { case isNotReadyToDownload = 0 case isReadyToDownload case isStart case isPause case isStop case isDownloading case isComplete } enum AriaNotification: String { case DownloadTSSuccessNotification case DownloadM3U8ProgressNotification case DownloadM3U8StartNotification case DownloadM3U8PausedNotification case DownloadM3U8ResumeNotification case DownloadM3U8StopNotification case DownloadTSFailureNotification case DownloadM3U8CompleteNotification case DownloadM3U8StatusNotification var stringValue: String { return "Aria" + rawValue } var notificationName: NSNotification.Name { return NSNotification.Name(stringValue) } func notificationNameWithTag(_ tag: Int) -> NSNotification.Name { return NSNotification.Name("\(stringValue)-\(tag)") } } extension NotificationCenter { static func post(customeNotification name: AriaNotification, tag: Int = 0, object: Any? = nil) { NotificationCenter.default.post(name: name.notificationNameWithTag(tag), object: object) } } extension Reactive where Base: NotificationCenter { func notification(custom name: AriaNotification, tag: Int = 0, object: AnyObject? = nil) -> Observable<Notification> { return notification(name.notificationNameWithTag(tag), object: object) } }
0
// // Identifier.swift // Alarm-ios-swift // // Created by natsu1211 on 2017/02/02. // Copyright © 2017年 LongGames. All rights reserved. // import Foundation struct Id { static let stopIdentifier = "Alarm-ios-swift-stop" static let snoozeIdentifier = "Alarm-ios-swift-snooze" static let goalIdentifier = "Alarm-ios-swift-goal" static let addSegueIdentifier = "addSegue" static let editSegueIdentifier = "editSegue" static let saveSegueIdentifier = "saveEditSegue" static let soundSegueIdentifier = "soundSegue" static let labelSegueIdentifier = "labelEditSegue" static let goalSegueIdentifier = "goalSegue" static let weekdaysSegueIdentifier = "weekdaysSegue" static let settingIdentifier = "setting" static let musicIdentifier = "musicIdentifier" static let alarmCellIdentifier = "alarmCell" static let labelUnwindIdentifier = "labelUnwindSegue" static let soundUnwindIdentifier = "soundUnwindSegue" static let weekdaysUnwindIdentifier = "weekdaysUnwindSegue" }
0
// // DraggableInteger.swift // DragDrop // // Created by Deveesh on 21/10/19. // Copyright © 2019 MindfireSolutions. All rights reserved. // import Foundation import MobileCoreServices /// This class's object can be dragged and dropped. It wraps an Integer data inside it final class DraggableInteger: NSObject, Codable, NSItemProviderWriting, NSItemProviderReading{ var integerValue : Int? init(value val: Int) { self.integerValue = val } static var readableTypeIdentifiersForItemProvider: [String]{ return [(kUTTypeData) as String] } static var writableTypeIdentifiersForItemProvider: [String]{ return [(kUTTypeData) as String] } func loadData(withTypeIdentifier typeIdentifier: String, forItemProviderCompletionHandler completionHandler: @escaping (Data?, Error?) -> Void) -> Progress? { let progress = Progress(totalUnitCount: 100) do { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted let data = try encoder.encode(self) progress.completedUnitCount = 100 completionHandler(data, nil) } catch { completionHandler(nil, error) } return progress } static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> Self { let decoder = JSONDecoder() do { let myJSON = try decoder.decode(DraggableInteger.self, from: data) return myJSON as! Self } catch { fatalError("Err") } } }
0
// // IssueManager.swift // IssueReporter // // Created by Hakon Hanesand on 10/6/16. // Copyright © 2017 abello. All rights reserved. // // import Foundation import UIKit internal let kABECompressionRatio: CGFloat = 5 internal protocol IssueManagerDelegate: class { func issueManagerUploadingStateDidChange(issueManager: IssueManager) func issueManager(_ issueManager: IssueManager, didFailToUploadImage image: Image, error: IssueReporterError) func issueManager(_ issueManager: IssueManager, didFailToUploadFile file: File, error: IssueReporterError) func issueManager(_ issueManager: IssueManager, didFailToUploadIssueWithError error: IssueReporterError) } internal class IssueManager { weak var delegate: IssueManagerDelegate? { didSet { delegate?.issueManagerUploadingStateDidChange(issueManager: self) } } var issue: Issue = Issue() var isUploading: Bool { let imageUploadingCount = images.filter { $0.state == .uploading }.count let fileUploadingCount = files.filter { $0.state == .uploading }.count return (fileUploadingCount + imageUploadingCount) > 0 } var images: [Image] { return issue.images } var files: [File] { return issue.files } init(referenceView: UIView, delegate: IssueManagerDelegate? = nil) { self.delegate = delegate let referenceImage = drawSnapshotOf(referenceView: referenceView) add(image: referenceImage) Reporter.delegate?.debugFiles(for: issue.identifier) { files in for (name, contents) in files { self.addFile(name: name, with: contents) } self.persist(files: self.files) } } private func drawSnapshotOf(referenceView view: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0) view.drawHierarchy(in: view.bounds, afterScreenUpdates: false) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } func add(image: UIImage) { let image = Image(image: image) issue.images.append(image) persist(image: image) } func retrySaving(image: Image) { assert(image.state == .errored, "Can not retry a image that has not errored.") guard let data = image.imageData else { print("can not retry saving image that has no data") return } persistToCloud(image: image, with: data) } func addFile(name: String, with contents: Data) { let file = File(name: name, data: contents) file.state = .uploading issue.files.append(file) } // MARK : File Persistance func persist(files: [File]) { var files = files guard let next = files.popLast() else { return } persist(file: next) { self.persist(files: files) } } func persist(file: File, completion: @escaping () -> ()) { GithubAPIClient.shared.upload(file: file.data, for: issue, at: file.name, success: { [weak self] (url) in guard let strongSelf = self else { return } file.htmlURL = url file.state = .done strongSelf.delegate?.issueManagerUploadingStateDidChange(issueManager: strongSelf) completion() }) { [weak self] (error) in guard let strongSelf = self else { return } file.state = .errored strongSelf.delegate?.issueManager(strongSelf, didFailToUploadFile: file, error: error) strongSelf.delegate?.issueManagerUploadingStateDidChange(issueManager: strongSelf) completion() } } // MARK : Image Persistance private func persist(image: Image) { image.compressionCompletionBlock = { [weak self] image in guard let data = image.imageData, let strongSelf = self else { return } strongSelf.persistToDisk(image: image, with: data) strongSelf.persistToCloud(image: image, with: data) } } private func persistToDisk(image: Image, with data: Data) { DispatchQueue.global(qos: .default).async { FileManager.write(data: data, completion: { url in image.localImageURL = url }, errorBlock: { error in print("Error saving image or screenshot to disk. Error : \(error)") }) } } private func persistToCloud(image: Image, with data: Data) { image.state = .uploading delegate?.issueManagerUploadingStateDidChange(issueManager: self) ImgurAPIClient.shared.upload(data: data, success: { [weak self] (url) in guard let strongSelf = self else { return } image.cloudImageURL = url image.state = .done strongSelf.delegate?.issueManagerUploadingStateDidChange(issueManager: strongSelf) }, failure: { [weak self] (error) in guard let strongSelf = self else { return } image.state = .errored strongSelf.delegate?.issueManager(strongSelf, didFailToUploadImage: image, error: error) strongSelf.delegate?.issueManagerUploadingStateDidChange(issueManager: strongSelf) }) } func saveIssue(completion: @escaping () -> ()) { GithubAPIClient.shared.save(issue: self.issue, success: completion) { [weak self] error in guard let strongSelf = self else { return } strongSelf.delegate?.issueManager(strongSelf, didFailToUploadIssueWithError: error) } } }
0
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse struct c { var e: A? = A> Int = { } protocol A : a { class func a()
0
// // Tree.swift // // // Created by Georg Tuparev on 17/06/2020. // import Foundation //MARK: - The Node - public protocol TreeNodeProtocol: NodeProtocol { var parent: Self? { get } var children: [Self]? { get } } final public class TreeNode<T>: Node<T>, TreeNodeProtocol where T: Equatable { public internal(set) weak var parent: TreeNode? public internal(set) var children: [TreeNode]? } //MARK: - Tree - public protocol TreeProtocol { associatedtype AnyType: Equatable var root: TreeNode<AnyType>? { get } func addChild(_ newNode: TreeNode<AnyType>) } public class Tree<T>: AbstractGraph, TreeProtocol where T: Equatable { public typealias AnyType = T public internal(set) var root: TreeNode<AnyType>? //MARK: - Basic operations - public func addChild(_ newNode: TreeNode<AnyType>) { //TODO: Implement me! } }
0
import Foundation import XCTest class FixtureClass34: XCTestCase { override static func setUp() { super.setUp() } override func setUp() { super.setUp() } func testSomething() {} } class FixtureClass34Subclass: FixtureClass34 { func testSubclass() {} }
1
// RUN: not %target-swift-frontend %s -typecheck // Crash type: memory error ("Invalid read of size 2") class A{func b->Self{{{}}class B<n{let a=self
0
// // URLTransform.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-27. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // 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 Foundation open class URLTransform: TransformType { public typealias Object = URL public typealias JSON = String private let shouldEncodeURLString: Bool private let allowedCharacterSet: CharacterSet /** Initializes the URLTransform with an option to encode URL strings before converting them to an NSURL - parameter shouldEncodeUrlString: when true (the default) the string is encoded before passing to `NSURL(string:)` - returns: an initialized transformer */ public init(shouldEncodeURLString: Bool = false, allowedCharacterSet: CharacterSet = .urlQueryAllowed) { self.shouldEncodeURLString = shouldEncodeURLString self.allowedCharacterSet = allowedCharacterSet } open func transformFromJSON(_ value: Any?) -> URL? { guard let URLString = value as? String else { return nil } if !self.shouldEncodeURLString { return URL(string: URLString) } guard let escapedURLString = URLString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) else { return nil } return URL(string: escapedURLString) } open func transformToJSON(_ value: URL?) -> String? { if let URL = value { return URL.absoluteString } return nil } }
0
// // Vehicle.swift // // // Created by Flatiron School on 7/16/16. // // import Foundation class Vehicle { let name: String let weight: Double let maxSpeed: Double var speed: Double = 0.0 var heading: Double = 0.0 //just fact to know if you do not set a value for you immutable properties by setting in the designated initializer you will solve it that way init(name: String, weight: Double, maxSpeed: Double) { self.name = name self.weight = weight self.maxSpeed = maxSpeed } func goFast() { speed = maxSpeed } func halt() { speed = 0 } func accelerate() { if speed < maxSpeed { speed += (0.10 * maxSpeed) } } func decelerate() { if speed > 0 { speed -= (0.10 * maxSpeed) } } func turnRight() { if speed != 0 { if heading == 0 || heading == 360 { heading = 90 speed *= 0.50 } else if heading == 90 { heading = 180 speed *= 0.50 } else if heading == 180 { heading = 270 speed *= 0.50 } } } func turnLeft() { if speed != 0 { if heading == 0 || heading == 360 { heading = 270 speed *= 0.50 } else if heading == 270 { heading = 180 speed *= 0.50 } else if heading == 180 { heading = 90 speed *= 0.50 } } } }
0
// // SemanticAnalyzer+Components.swift // SemanticAnalyzer // // Created by Hails, Daniel J R on 21/08/2018. // import Foundation import AST import Lexer import Diagnostic import Source extension SemanticAnalyzer { /// The set of characters for identifiers which can only be used in the stdlib. var stdlibReservedCharacters: CharacterSet { return CharacterSet(charactersIn: "$") } var identifierReservedCharacters: CharacterSet { return CharacterSet(charactersIn: "@") } public func process(identifier: Identifier, passContext: ASTPassContext) -> ASTPassResult<Identifier> { let environment = passContext.environment! var identifier = identifier var passContext = passContext var diagnostics = [Diagnostic]() // Disallow identifiers from containing special characters. if let char = identifier.name.first(where: { return identifierReservedCharacters.contains($0.unicodeScalars.first!) }) { diagnostics.append(.invalidCharacter(identifier, character: char)) } // Only allow stdlib files to include special characters, such as '$'. if !identifier.sourceLocation.isFromStdlib, let char = identifier.name.first(where: { return stdlibReservedCharacters.contains($0.unicodeScalars.first!) }) { diagnostics.append(.invalidCharacter(identifier, character: char)) } let inFunctionDeclaration = passContext.functionDeclarationContext != nil let inInitializerDeclaration = passContext.specialDeclarationContext != nil let inFunctionOrInitializer = inFunctionDeclaration || inInitializerDeclaration if passContext.isPropertyDefaultAssignment, !environment.isStructDeclared(identifier.name) { if environment.isPropertyDefined(identifier.name, enclosingType: passContext.enclosingTypeIdentifier!.name) { diagnostics.append(.statePropertyUsedWithinPropertyInitializer(identifier)) } else { diagnostics.append(.useOfUndeclaredIdentifier(identifier)) } } if passContext.isFunctionCall || passContext.isFunctionCallArgumentLabel { // If the identifier is the name of a function call or a function call argument label, // do nothing. The function call will be matched in `process(functionCall:passContext:)`, // or the other checks should not take place for argument labels. } else if inFunctionOrInitializer, !passContext.isInBecome, !passContext.isInEmit { // The identifier is used within the body of a function or an initializer // The identifier is used an l-value (the left-hand side of an assignment). let asLValue = passContext.asLValue ?? false if identifier.enclosingType == nil { // The identifier has no explicit enclosing type, such as in the expression `foo` instead of `a.foo`. let scopeContext = passContext.scopeContext! if let variableDeclaration = scopeContext.declaration(for: identifier.name) { if variableDeclaration.isConstant, !variableDeclaration.type.rawType.isInout, asLValue, !passContext.isInSubscript { // The variable is a constant but is attempted to be reassigned. diagnostics.append(.reassignmentToConstant(identifier, variableDeclaration.sourceLocation)) } } else if !passContext.environment!.isEnumDeclared(identifier.name) { // If the variable is not declared locally and doesn't refer to an enum, // assign its enclosing type to the struct or contract behavior // declaration in which the function appears. identifier.enclosingType = passContext.enclosingTypeIdentifier!.name } else if !(passContext.isEnclosing) { // Checking if we are refering to 'foo' in 'a.foo' diagnostics.append(.invalidReference(identifier)) } } if let enclosingType = identifier.enclosingType, enclosingType != RawType.errorType.name { if !passContext.environment!.isPropertyDefined(identifier.name, enclosingType: enclosingType) { // The property is not defined in the enclosing type. diagnostics.append(.useOfUndeclaredIdentifier(identifier)) passContext.environment!.addUsedUndefinedVariable(identifier, enclosingType: enclosingType) } else if asLValue, !passContext.isInSubscript { if passContext.environment!.isPropertyConstant(identifier.name, enclosingType: enclosingType) { // Retrieve the source location of that property's declaration. let declarationSourceLocation = passContext.environment!.propertyDeclarationSourceLocation(identifier.name, enclosingType: enclosingType)! if !inInitializerDeclaration || passContext.environment!.isPropertyAssignedDefaultValue(identifier.name, enclosingType: enclosingType) { // The state property is a constant but is attempted to be reassigned. diagnostics.append(.reassignmentToConstant(identifier, declarationSourceLocation)) } } // In initializers or fallback if passContext.specialDeclarationContext != nil { // Check if the property has been marked as assigned yet. if let first = passContext.unassignedProperties!.index(where: { $0.identifier.name == identifier.name && $0.identifier.enclosingType == identifier.enclosingType }) { // Mark the property as assigned. passContext.unassignedProperties!.remove(at: first) } } if let functionDeclarationContext = passContext.functionDeclarationContext { // The variable is being mutated in a function. if !functionDeclarationContext.isMutating { // The function is declared non-mutating. diagnostics.append(.useOfMutatingExpressionInNonMutatingFunction( .identifier(identifier), functionDeclaration: functionDeclarationContext.declaration)) } // Record the mutating expression in the context. addMutatingExpression(.identifier(identifier), passContext: &passContext) } } } } else if passContext.isInBecome { if let functionDeclarationContext = passContext.functionDeclarationContext { // The variable is being mutated in a function. if !functionDeclarationContext.isMutating { // The function is declared non-mutating. diagnostics.append( .useOfMutatingExpressionInNonMutatingFunction(.identifier(identifier), functionDeclaration: functionDeclarationContext.declaration)) } // Record the mutating expression in the context. addMutatingExpression(.identifier(identifier), passContext: &passContext) } } return ASTPassResult(element: identifier, diagnostics: diagnostics, passContext: passContext) } public func process(parameter: Parameter, passContext: ASTPassContext) -> ASTPassResult<Parameter> { var diagnostics = [Diagnostic]() checkWhetherSolidityTypesAreAllowedInContext(type: parameter.type, passContext: passContext, diagnostics: &diagnostics) if parameter.type.rawType.isUserDefinedType, !parameter.isInout, !(parameter.type.isCurrencyType && parameter.isImplicit) { // Ensure all structs are passed by reference, for now. diagnostics.append(Diagnostic(severity: .error, sourceLocation: parameter.sourceLocation, message: "Structs cannot be passed by value yet, and have to be passed inout")) } else if passContext.traitDeclarationContext == nil && parameter.type.rawType.isSelfType { diagnostics.append(.useOfSelfOutsideTrait(at: parameter.sourceLocation)) } return ASTPassResult(element: parameter, diagnostics: diagnostics, passContext: passContext) } func checkWhetherSolidityTypesAreAllowedInContext(type: Type, passContext: ASTPassContext, diagnostics: inout [Diagnostic]) { if let kind = passContext.traitDeclarationContext?.traitKind.kind, kind == .external { if case .solidityType = type.rawType {} else { // typeAnnotation is describing a Flint type but we are in an external trait declaration diagnostics.append(.flintTypeUsedInExternalTrait(type, at: type.sourceLocation)) } } else if case .solidityType = type.rawType { // type annotation is describing a Solidity type but we are not in an external trait declaration diagnostics.append(.solidityTypeUsedOutsideExternalTrait(type, at: type.sourceLocation)) } } public func process(callerProtection: CallerProtection, passContext: ASTPassContext) -> ASTPassResult<CallerProtection> { let contractBehaviorDeclarationContext = passContext.contractBehaviorDeclarationContext! let environment = passContext.environment! var diagnostics = [Diagnostic]() if !callerProtection.isAny && !environment.containsCallerProtection(callerProtection, enclosingType: contractBehaviorDeclarationContext.contractIdentifier.name) { // The caller protection is neither `any` or a valid property in the enclosing contract. diagnostics.append( .undeclaredCallerProtection(callerProtection, contractIdentifier: contractBehaviorDeclarationContext.contractIdentifier)) } return ASTPassResult(element: callerProtection, diagnostics: diagnostics, passContext: passContext) } public func process(typeState: TypeState, passContext: ASTPassContext) -> ASTPassResult<TypeState> { // TODO: Check that type state exists, etc. return ASTPassResult(element: typeState, diagnostics: [], passContext: passContext) } public func process(conformance: Conformance, passContext: ASTPassContext) -> ASTPassResult<Conformance> { let environment = passContext.environment! let contractDeclarationContext = passContext.contractStateDeclarationContext! var diagnostics = [Diagnostic]() if !environment.isTraitDeclared(conformance.name) { diagnostics.append(.contractUsesUndeclaredTraits(conformance, in: contractDeclarationContext.contractIdentifier)) } return ASTPassResult(element: conformance, diagnostics: diagnostics, passContext: passContext) } public func process(token: Token, passContext: ASTPassContext) -> ASTPassResult<Token> { var diagnostics = [Diagnostic]() if case .literal(let tokenKind) = token.kind, case .address(let address) = tokenKind, address.count != 42 { diagnostics.append(.invalidAddressLiteral(token)) } return ASTPassResult(element: token, diagnostics: diagnostics, passContext: passContext) } }
0
import Foundation import Domain enum URLScheme { case addApps(ids: [AppID]) case viewApp(id: AppID) case export case deleteAll } // MARK: - RawRepresentable extension URLScheme: RawRepresentable { var rawValue: URL { var urlComponents = URLComponents() urlComponents.scheme = "appdates" switch self { case .addApps(let ids): urlComponents.host = "add" urlComponents.queryItems = [ URLQueryItem(name: "id", value: ids.map { String($0.rawValue) }.joined(separator: ",")) ] case .viewApp(let id): urlComponents.host = "view" urlComponents.queryItems = [ URLQueryItem(name: "id", value: String(id.rawValue)) ] case .export: urlComponents.host = "export" case .deleteAll: urlComponents.host = "deleteAll" } return urlComponents.url! } init?(rawValue url: URL) { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return nil } switch components.host { case "add": guard let appIDs = components.queryItems?.first(where: { $0.name == "id" })?.value else { return nil } let ids = appIDs.split(separator: ",").compactMap { Int($0, radix: 10) } guard !ids.isEmpty else { return nil } self = .addApps(ids: ids.map(AppID.init(rawValue:))) case "view": guard let appID = components.queryItems?.first(where: { $0.name == "id" })?.value, let id = Int(appID, radix: 10) else { return nil } self = .viewApp(id: AppID(rawValue: id)) case "export": self = .export case "deleteAll": self = .deleteAll default: return nil } } } // MARK: - Codable extension URLScheme: Codable { private struct MalformedURLSchemeError: Error {} init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let url = try container.decode(URL.self) guard let urlScheme = URLScheme(rawValue: url) else { throw MalformedURLSchemeError() } self = urlScheme } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } }
0
// // TransactionView.swift // Prory // // Created by edwin on 19/07/2020. // Copyright © 2020 edwin. All rights reserved. // import SwiftUI struct TransactionView: View { @State private var showInvoice = false @ObservedObject private var viewModel = TransactionViewModel() var body: some View { ZStack { Color("background") .edgesIgnoringSafeArea(.all) VStack(spacing: 15) { HStack(spacing: 10){ Text("Transactions") .font(.title) .fontWeight(.bold) Spacer() } .padding(.top, (UIApplication.shared.windows.first?.safeAreaInsets.top)!) .padding() .background(Color.white) ScrollView(.vertical, showsIndicators: false) { VStack(spacing: 15) { VStack(spacing: 0) { HStack() { VStack(alignment: .leading) { VStack(alignment: .leading, spacing: 2) { Text("B-1402") .font(.caption) Text("Lodha Aurum Grande") .font(.subheadline) .bold() Text("Versova, Mumbai") .font(.caption) } HStack { VStack(alignment: .leading, spacing: 2) { Text("Ramesh Morya") .font(.subheadline) .bold() Text("Property Manager") .font(.caption) } Spacer() Image(systemName: "message.circle.fill") .resizable() .frame(width: 35, height: 35) .foregroundColor(Color.blue) Image(systemName: "phone.circle.fill") .resizable() .frame(width: 35, height: 35) .foregroundColor(Color.blue) } Text("Leased from July 2019 - 2019") .font(.subheadline) HStack() { VStack(alignment: .leading) { Button(action: {}) { HStack() { Text("Owner Details") .font(.footnote) .bold() Spacer() Image(systemName: "info.circle") } } } } } Spacer() }.padding([.top, .leading, .trailing, .bottom]) } .background( Color.white) .cornerRadius(10) .padding(.leading) .padding(.trailing) Button(action: { self.showInvoice.toggle() }) { HStack() { Spacer() Text("Request Rent Receipt".uppercased()) .font(.subheadline) .bold() .foregroundColor(.white) Image(systemName: "arrow.right") .foregroundColor(.white) Spacer() } }.sheet(isPresented: $showInvoice) { InvoiceView() } .padding() .foregroundColor(.white) .background(Color.yellow) .cornerRadius(10) .padding(.leading) .padding(.trailing) ForEach(viewModel.transactions) { transaction in VStack(spacing: 0) { HStack() { VStack(alignment: .leading, spacing: 5) { HStack { Text(transaction.rent) .font(.system(size: 23)) .bold() Spacer() Text(transaction.status.uppercased()) .font(.caption) .bold() .padding(5) .background((transaction.status == "pending") ? Color.orange : Color.green) .foregroundColor(.white) .cornerRadius(5) } Text(transaction.description) .font(.caption) HStack { Image(systemName: "calendar") Text(transaction.date) .font(.footnote) } } Spacer() } .padding() HStack() { VStack(alignment: .leading) { HStack() { VStack(alignment: .leading) { Button(action: {}) { HStack() { Spacer() Image(systemName: "eye") Text("View Details") .font(.footnote) .bold() Spacer() } } } } } Spacer() } .padding() .overlay( RoundedRectangle(cornerRadius: 0) .stroke(Color("background"), lineWidth: 2) ) } .background(Color.white) .cornerRadius(10) .padding(.leading) .padding(.trailing) } } } } } .edgesIgnoringSafeArea(.top) } } struct TransactionView_Previews: PreviewProvider { static var previews: some View { TransactionView() } }
0
// // AddNetworkVC+TextFieldDelegate.swift // Franklin // // Created by Anton on 07/03/2019. // Copyright © 2019 Matter Inc. All rights reserved. // import UIKit extension AddNetworkViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let currentText = (textField.text ?? "") as NSString let futureString = currentText.replacingCharacters(in: range, with: string) as String isEnterButtonEnabled(afterChanging: textField, with: futureString) updateEnterButtonAlpha() textField.returnKeyType = enterButton.isEnabled ? UIReturnKeyType.done : .next return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField.tag == TextFieldsTags.name.rawValue && !enterButton.isEnabled { endpointTextField.becomeFirstResponder() return false } else if textField.tag == TextFieldsTags.endpoint.rawValue && !enterButton.isEnabled { nameTextField.becomeFirstResponder() return false } else if enterButton.isEnabled { textField.resignFirstResponder() return true } return false } func textFieldDidBeginEditing(_ textField: UITextField) { self.showLabels(true) } func textFieldDidEndEditing(_ textField: UITextField) { self.showLabels(true) } }
0
// // Keystore.swift // Keystore // // Created by Koray Koska on 27.06.18. // Copyright © 2018 Boilertalk. All rights reserved. // import Foundation import CryptoSwift public struct Keystore: Codable { // MARK: - Public API /// Creates a new keystore for the given private key and password. /// /// - parameter privateKey: The private key to encrypt. /// - parameter password: The password to use for the encryption. /// /// - throws: Error if any step fails. public init(privateKey: [UInt8], password: String, kdf: Keystore.Crypto.KDFType = .scrypt, cipher: IVBlockModeType = .ctr, rounds: Int? = nil) throws { self = try KeystoreFactory.keystore(from: privateKey, password: password, kdf: kdf, cipher: cipher, rounds: rounds) } /// Extracts the private key from this keystore with the given password. /// /// - parameter public func privateKey(password: String) throws -> [UInt8] { return try KeystoreFactory.privateKey(from: self, password: password) } // MARK: - Internal stuff init(version: Int, id: String, address: String, crypto: Crypto) { self.version = version self.id = id self.address = address self.crypto = crypto } public let version: Int public let id: String public let address: String public let crypto: Crypto public struct Crypto: Codable { public let ciphertext: String public let cipherparams: Cipherparams public struct Cipherparams: Codable { public let iv: String } public let cipher: String public let kdf: KDFType public enum KDFType: String, Codable { case scrypt case pbkdf2 } public let kdfparams: KDFParams public struct KDFParams: Codable { public let salt: String public let dklen: Int // *** Scrypt params *** public let n: Int? public let r: Int? public let p: Int? // *** End Scrypt params *** // *** PBKDF2 params *** public let prf: String? public let c: Int? // *** End PBKDF2 params *** /// Scrypt init init(salt: String, dklen: Int, n: Int, r: Int, p: Int) { self.salt = salt self.dklen = dklen self.n = n self.r = r self.p = p self.prf = nil self.c = nil } /// PBKDF2 init init(salt: String, dklen: Int, prf: String, c: Int) { self.salt = salt self.dklen = dklen self.prf = prf self.c = c self.n = nil self.r = nil self.p = nil } } public let mac: String } public enum CodingKeys: String, CodingKey { case version case id case address case crypto case oldCrypto = "Crypto" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let version = try (try? container.decode(Int.self, forKey: .version)) ?? Int(container.decode(String.self, forKey: .version)) ?? container.decode(Int.self, forKey: .version) let id = try container.decode(String.self, forKey: .id) let address = try container.decode(String.self, forKey: .address) let crypto = try container.decodeIfPresent(Crypto.self, forKey: .crypto) ?? container.decode(Crypto.self, forKey: .oldCrypto) self.init(version: version, id: id, address: address, crypto: crypto) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(version, forKey: .version) try container.encode(id, forKey: .id) try container.encode(address, forKey: .address) try container.encode(crypto, forKey: .crypto) } }
0
import Foundation import simd /// A unitless vector representing distances, sizes or scales in three dimensions /// /// ## Examples /// ```swift /// let v1 = Vector3D(x: 10, y: 15, z: 5) /// let v2: Vector3D = [10, 15, 5] /// ``` public struct Vector3D: ExpressibleByArrayLiteral, SCADValue, Hashable { public let x: Double public let y: Double public let z: Double public static let zero = Vector3D(x: 0, y: 0, z: 0) public init(x: Double, y: Double, z: Double) { precondition(x.isFinite, "Vector elements can't be NaN or infinite") precondition(y.isFinite, "Vector elements can't be NaN or infinite") precondition(z.isFinite, "Vector elements can't be NaN or infinite") self.x = x self.y = y self.z = z } public init(_ x: Double, _ y: Double, _ z: Double) { self.init(x: x, y: y, z: z) } public init(_ xy: Vector2D, z: Double = 0) { self.init(x: xy.x, y: xy.y, z: z) } public init(arrayLiteral: Double...) { precondition(arrayLiteral.count == 3, "Vector3D requires exactly three elements") self.init(x: arrayLiteral[0], y: arrayLiteral[1], z: arrayLiteral[2]) } public var scadString: String { [x, y, z].scadString } } public extension Vector3D { /// Create a vector where some axes are set to a given value and the others are zero /// - Parameters: /// - axis: The axes to set /// - value: The value to use /// - default: The value to use for the other axes init(axis: Axis3D, value: Double, default defaultValue: Double = 0) { let x = (axis == .x) ? value : defaultValue let y = (axis == .y) ? value : defaultValue let z = (axis == .z) ? value : defaultValue self.init(x, y, z) } /// Make a new vector where some of the dimensions are set to a new value /// - Parameters: /// - axes: The axes to set /// - value: The new value /// - Returns: A modified vector func setting(axes: Axes3D, to value: Double) -> Vector3D { Vector3D( x: axes.contains(.x) ? value : x, y: axes.contains(.y) ? value : y, z: axes.contains(.z) ? value : z ) } subscript(_ axis: Axis3D) -> Double { switch axis { case .x: return x case .y: return y case .z: return z } } } public extension Vector3D { static func /(_ v: Vector3D, _ d: Double) -> Vector3D { return Vector3D( x: v.x / d, y: v.y / d, z: v.z / d ) } static func *(_ v: Vector3D, _ d: Double) -> Vector3D { return Vector3D( x: v.x * d, y: v.y * d, z: v.z * d ) } static prefix func -(_ v: Vector3D) -> Vector3D { return Vector3D( x: -v.x, y: -v.y, z: -v.z ) } static func +(_ v1: Vector3D, _ v2: Vector3D) -> Vector3D { return Vector3D( x: v1.x + v2.x, y: v1.y + v2.y, z: v1.z + v2.z ) } static func -(_ v1: Vector3D, _ v2: Vector3D) -> Vector3D { return Vector3D( x: v1.x - v2.x, y: v1.y - v2.y, z: v1.z - v2.z ) } static func *(_ v1: Vector3D, _ v2: Vector3D) -> Vector3D { return Vector3D( x: v1.x * v2.x, y: v1.y * v2.y, z: v1.z * v2.z ) } static func /(_ v1: Vector3D, _ v2: Vector3D) -> Vector3D { return Vector3D( x: v1.x / v2.x, y: v1.y / v2.y, z: v1.z / v2.z ) } static func +(_ v: Vector3D, _ s: Double) -> Vector3D { return Vector3D( x: v.x + s, y: v.y + s, z: v.z + s ) } static func -(_ v: Vector3D, _ s: Double) -> Vector3D { return Vector3D( x: v.x - s, y: v.y - s, z: v.z - s ) } var xy: Vector2D { Vector2D(x:x, y:y) } } public extension Vector3D { /// Calculate the distance from this point to another point in 3D space func distance(to other: Vector3D) -> Double { sqrt(pow(x - other.x, 2) + pow(y - other.y, 2) + pow(z - other.z, 2)) } /// Calculate a point at a given fraction along a straight line to another point func point(alongLineTo other: Vector3D, at fraction: Double) -> Vector3D { self + (other - self) * fraction } } internal extension Vector3D { var simd4: SIMD4<Double> { SIMD4(x, y, z, 1.0) } init(simd4 v: SIMD4<Double>) { self.init(v[0], v[1], v[2]) } }
0
// // PageContentView.swift // DYSwift // // Created by CXTretar on 2020/1/2. // Copyright © 2020 CXTretar. All rights reserved. // import UIKit private let ContentCellID: String = "ContentCellID" protocol PageContentViewDelegate : class { func pageContentViewScroll(_ contentView: PageContentView, _ progress: CGFloat, _ sourceIndex: Int, _ targetIndex: Int) } class PageContentView: UIView { private var childVCs: [UIViewController] private weak var parentViewController : UIViewController? private var startOffsetX: CGFloat = 0 private var isForbidScrollDelegate : Bool = false weak var delegate : PageContentViewDelegate? fileprivate lazy var collectionView : UICollectionView = { [weak self] in // 1.创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0; layout.minimumInteritemSpacing = 0; layout.scrollDirection = .horizontal // 2.创建UICollectionView let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() init(frame: CGRect, childVCs: [UIViewController], parentViewController: UIViewController?) { self.childVCs = childVCs self.parentViewController = parentViewController super.init(frame: frame) setupUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView { private func setupUI() { // 1.将所有的子控制器添加父控制器中 for childVC in childVCs { parentViewController?.addChild(childVC) } // 2.添加UICollectionView,用于在Cell中存放控制器的View addSubview(collectionView) collectionView.frame = bounds } } // MARK:- 遵守UICollectionViewDataSource extension PageContentView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVCs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVC = childVCs[indexPath.item] childVC.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVC.view) return cell; } } // MARK:- UICollectionViewDelegate extension PageContentView: UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 0.判断是否是点击事件 if isForbidScrollDelegate { return } // 1.定义获取需要的数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 1.计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVCs.count { targetIndex = childVCs.count - 1 } // 4.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1.0 targetIndex = sourceIndex } } else { // 右滑 progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVCs.count { sourceIndex = childVCs.count - 1 } } // 通知代理 delegate?.pageContentViewScroll(self, progress, sourceIndex, targetIndex) } } // MARK:- 对外暴露的方法 extension PageContentView { func setCurrentIndex(_ currentIndex: Int) { isForbidScrollDelegate = true let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
0
// // PersistentConversationDataItem+CoreDataClass.swift // ConversationsApp // // Copyright © Twilio, Inc. All rights reserved. // // import CoreData @objc(PersistentConversationDataItem) public class PersistentConversationDataItem: NSManagedObject { convenience init(with conversationDataItem: ConversationDataItem, insertInto context: NSManagedObjectContext = CoreDataManager.shared.viewContext) { self.init(context: context) update(with: conversationDataItem) } func update(with conversationDataItem: ConversationDataItem) { self.sid = conversationDataItem.sid self.friendlyName = conversationDataItem.friendlyName self.uniqueName = conversationDataItem.uniqueName self.dateUpdated = Date(timeIntervalSince1970: conversationDataItem.dateUpdated) if let creationDate = conversationDataItem.dateCreated { self.dateCreated = Date(timeIntervalSince1970: creationDate) } self.createdBy = conversationDataItem.createdBy self.participantsCount = Int64(conversationDataItem.participantsCount ) self.messagesCount = Int64(conversationDataItem.messagesCount) self.unreadMessagesCount = Int64(conversationDataItem.unreadMessagesCount) self.notificationLevel = Int64(conversationDataItem.notificationLevel.rawValue) self.lastMessageDate = Date(timeIntervalSince1970: conversationDataItem.lastMessageDate) } }
0
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-2020 Datadog, Inc. */ import XCTest @testable import Datadog #if canImport(UIKit) import UIKit #endif class MobileDeviceTests: XCTestCase { #if canImport(UIKit) func testWhenRunningOnMobile_itReturnsDevice() { XCTAssertNotNil(MobileDevice.current) } func testWhenRunningOnMobile_itUsesUIDeviceInfo() { let uiDevice = UIDeviceMock( model: "model mock", systemName: "system name mock", systemVersion: "system version mock" ) let mobileDevice = MobileDevice(uiDevice: uiDevice, processInfo: ProcessInfoMock()) XCTAssertEqual(mobileDevice.model, uiDevice.model) XCTAssertEqual(mobileDevice.osName, uiDevice.systemName) XCTAssertEqual(mobileDevice.osVersion, uiDevice.systemVersion) } func testWhenRunningOnMobile_itUsesUIDeviceBatteryState() { XCTAssertEqual( MobileDevice(uiDevice: UIDeviceMock(batteryState: .full), processInfo: ProcessInfoMock()).currentBatteryStatus().state, .full ) XCTAssertEqual( MobileDevice(uiDevice: UIDeviceMock(batteryState: .charging), processInfo: ProcessInfoMock()).currentBatteryStatus().state, .charging ) XCTAssertEqual( MobileDevice(uiDevice: UIDeviceMock(batteryState: .unplugged), processInfo: ProcessInfoMock()).currentBatteryStatus().state, .unplugged ) XCTAssertEqual( MobileDevice(uiDevice: UIDeviceMock(batteryState: .unknown), processInfo: ProcessInfoMock()).currentBatteryStatus().state, .unknown ) } func testWhenRunningOnMobile_itUsesUIDeviceBatteryLevel() { XCTAssertEqual( MobileDevice(uiDevice: UIDeviceMock(batteryLevel: 0.12), processInfo: ProcessInfoMock()).currentBatteryStatus().level, 0.12 ) } func testWhenRunningOnMobile_itUsesProcessInfoPowerMode() { XCTAssertTrue( MobileDevice(uiDevice: UIDeviceMock(), processInfo: ProcessInfoMock(isLowPowerModeEnabled: true)).currentBatteryStatus().isLowPowerModeEnabled ) XCTAssertFalse( MobileDevice(uiDevice: UIDeviceMock(), processInfo: ProcessInfoMock(isLowPowerModeEnabled: false)).currentBatteryStatus().isLowPowerModeEnabled ) } func testWhenRunningOnMobile_itTogglesBatteryMonitoring() { let uiDevice = UIDeviceMock(isBatteryMonitoringEnabled: false) let mobileDevice = MobileDevice(uiDevice: uiDevice, processInfo: ProcessInfoMock()) XCTAssertFalse(uiDevice.isBatteryMonitoringEnabled) mobileDevice.enableBatteryStatusMonitoring() XCTAssertTrue(uiDevice.isBatteryMonitoringEnabled) mobileDevice.resetBatteryStatusMonitoring() XCTAssertFalse(uiDevice.isBatteryMonitoringEnabled) } #else func testWhenRunningOnOtherPlatforms_itReturnsNil() { XCTAssertNil(MobileDevice.current) } #endif }
0
// // NSObject+Deinit.swift // ReactKit // // Created by Yasuhiro Inami on 2014/09/14. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import Foundation private var deinitSignalKey: UInt8 = 0 public extension NSObject { private var _deinitSignal: Signal<AnyObject?>? { get { return objc_getAssociatedObject(self, &deinitSignalKey) as? Signal<AnyObject?> } set { objc_setAssociatedObject(self, &deinitSignalKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN)) // not OBJC_ASSOCIATION_RETAIN_NONATOMIC } } public var deinitSignal: Signal<AnyObject?> { var signal: Signal<AnyObject?>? = self._deinitSignal if signal == nil { signal = Signal<AnyObject?> { (progress, fulfill, reject, configure) in // do nothing }.name("\(NSStringFromClass(self.dynamicType))-deinitSignal") #if DEBUG signal?.then { value, errorInfo -> Void in println("[internal] deinitSignal finished") } #endif self._deinitSignal = signal } return signal! } }
0
// // AppTheme.swift // FillMeUp // // Created by Varun Rathi on 23/11/17. // Copyright © 2017 vrat28. All rights reserved. // import UIKit import ChameleonFramework struct AppTheme { // Colors static let kColorCorrectAnswer:UIColor = UIColor.green static let kColorCorrectWrong:UIColor = UIColor.red static let kBackgroundColorLightGray = UIColor(red: 231/255, green: 231/255, blue: 231/255, alpha: 0.7) static let kActivityIndColor:UIColor = FlatTeal() // Size static let kIndicatorWidth:CGFloat = 60 static let kIndicatorHeight:CGFloat = 60 }
0
import XCTest @testable import Async @available(macOS 12.0, *) class AsyncTests: XCTestCase { func testAsync() async { } @MainActor func testMainActor() async { XCTAssertTrue(Thread.isMainThread) } func testNotAsync() { XCTAssertTrue(Thread.isMainThread) } }
0
// // TYSegmentItem.swift // RCTTest // // Created by 童万华 on 2017/8/18. // Copyright © 2017年 童万华. All rights reserved. // import UIKit class TYSegmentItem: UIButton { var indexInSegmentView = 0 init(title:String,normalColor:UIColor,selectedColor:UIColor) { super.init(frame: CGRect.zero) setTitle(title, for: .normal) setTitleColor(normalColor, for: .normal) setTitleColor(selectedColor, for: .selected) } convenience init(title:String,nc:UIColor,sc:UIColor) { self.init(title: title, normalColor: nc, selectedColor: sc) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
0
// swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SwiftyHUDView", platforms: [ .iOS(.v13) ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "SwiftyHUDView", targets: ["SwiftyHUDView"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "SwiftyHUDView", dependencies: []), .testTarget( name: "SwiftyHUDViewTests", dependencies: ["SwiftyHUDView"]), ] )
0
// // SuperHeroesDetector.swift // iOSBasicTraining // // Created by Pedro Vicente Gomez on 24/06/16. // Copyright © 2016 GoKarumi. All rights reserved. // import Foundation import Result class SuperHeroesDetector { private let superHeroesRepository: SuperHeroesRepository init(superHeroesRepository: SuperHeroesRepository) { self.superHeroesRepository = superHeroesRepository } func getSuperHeroes(completion: (Result<[SuperHero], SuperHeroesDetectorError>) -> Void) { superHeroesRepository.getAll { result in completion(result) } } func captureSuperHero(id: String) -> Result<String, SuperHeroesDetectorError> { guard !id.isEmpty else { return Result(error: SuperHeroesDetectorError.SuperHeroNotFound) } return superHeroesRepository.markSuperHeroAsCaptured(id) } }
0
// Copyright 2022 Espressif Systems // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Calendar+GMT.swift // ESPRainMaker // import UIKit extension Calendar { static func gmtCalendar() -> Calendar { var calendar = Calendar.current calendar.timeZone = TimeZone.current return calendar } }
0
import PlaygroundSupport import SpriteKit /// Represents an item (e.g. food) that can be transported on a conveyor or operated on. final class Item { let node = SKNode() // MARK: - Life Cycle init(title: String) { node.zPosition = 1 label.text = title label.fontSize = fontSize(forTextLength: title.characters.count) label.verticalAlignmentMode = .center node.addChild(label) } convenience init?(_ configuration: Configuration?) { guard let title = configuration?["title"]?.string else { return nil } self.init(title: title) } // MARK: - Nodes lazy var label = SKLabelNode(fontNamed: "Menlo-Bold") // MARK: - Helpers /// Converts a dictionary of item configurations to an array of items. static func multipleFrom(configuration: Configuration?) -> [Int: Item] { return (configuration ?? [:]) .mapPairs { (Int($0)!, Item($1.dictionary)) } .filterPairs { $1 != nil } .mapPairs { ($0, $1!) } } var size: CGSize { return CGSize(width: conveyorWidth, height: conveyorWidth) } func fontSize(forTextLength textLength: Int) -> CGFloat { switch textLength { case 0...1: return size.height * 0.6 case 2...4: return size.height * 0.4 case 5...6: return size.height * 0.25 default: return size.height * 0.2 } } }
0
// // Copyright 2011 - 2020 Schibsted Products & Technology AS. // Licensed under the terms of the MIT license. See LICENSE in the project root. // import Foundation class TaskManager { struct TaskData { let operation: TaskOperation let errorCallback: ((ClientError) -> Void)? let taskDidCancelCallback: (() -> Void)? let retryCount: Int let taskReference: AnyObject } private var pendingTasks: [OwnedTaskHandle: TaskData] = [:] private let operationQueue = OperationQueue() private let lock = NSLock() private weak var user: User? private var operationsToReAdd: [TaskOperation] = [] func waitForRequestsToFinish() { operationQueue.waitUntilAllOperationsAreFinished() } var willStartRefresh = EventEmitter<TaskHandle>(description: "TaskManager.willStartRefresh") init(for user: User) { self.user = user } func add<T: TaskProtocol>(task: T, completion: ((Result<T.SuccessType, ClientError>) -> Void)? = nil) -> TaskHandle { let handle = OwnedTaskHandle(owner: self) let executor: (@escaping () -> Void) -> Void = { [weak self, weak handle, weak task] done in defer { done() } guard self != nil else { log(level: .debug, from: self, "executor() => task manager dead") return } guard let task = task else { log(level: .debug, from: self, "executor() => task dead") return } guard let handle = handle else { log(level: .debug, from: self, "executor() => handle died") return } log(level: .verbose, from: self, "will execute \(handle)") task.execute { [weak self, weak task, weak handle] result in guard let strongSelf = self else { log(level: .debug, from: self, "task.execute => task manager dead") return } guard let handle = handle else { log(level: .debug, from: self, "task.execute => handle dead") return } log(level: .verbose, from: self, "did execute \(handle) with result: \(result)") guard let task = task else { log(level: .debug, from: self, "task.execute => task for \(handle) died") return } if task.shouldRefresh(result: result) { log(level: .verbose, from: self, "task.execute => need to refresh on \(handle)") strongSelf.refresh(handle: handle) return } log(level: .verbose, from: self, "done with \(handle) (\(T.self))") strongSelf.lock.scope { // // It's possible here that the refresh call above fails and the queue is restarted while the tasks // are being cancelled. So check here that the handle we want to remove is actually still there. // if strongSelf.pendingTasks.removeValue(forKey: handle) != nil { log(level: .debug, from: self, "removed \(handle)") DispatchQueue.main.async { completion?(result) } #if DEBUG if SDKConfiguration.shared.invalidateteAuthTokenAfterSuccessfullRequest { if let oldTokens = self?.user?.tokens { var string = Array(oldTokens.accessToken) if string.count > 2 { string.swapAt(0, string.count - 1) } let invalidAccessToken = String(string) let badTokens = TokenData( accessToken: invalidAccessToken, refreshToken: oldTokens.refreshToken, idToken: oldTokens.idToken, userID: oldTokens.userID ) self?.user?.tokens = badTokens log( level: .debug, from: self, "invalidated access token: \(oldTokens.accessToken.shortened) to: \(invalidAccessToken.shortened)" ) } } #endif } else { log(level: .debug, from: self, "did not find \(handle)") } } } } let taskData = TaskData( operation: TaskOperation(executor: executor), errorCallback: { completion?(.failure($0)) }, taskDidCancelCallback: { [weak task] in task?.didCancel() }, retryCount: 0, taskReference: task ) lock.scope { self.operationQueue.addOperation(taskData.operation) self.pendingTasks[handle] = taskData log(level: .verbose, from: self, "added \(handle) (\(T.self))") } return handle } func refresh(handle: OwnedTaskHandle) { guard let user = self.user else { log(level: .debug, from: self, "user dead. kthxbye.") return } do { lock.lock() defer { self.lock.unlock() } // If it was cancelled and removed there's no need to refresh guard let taskData = pendingTasks[handle] else { log(level: .debug, from: self, "\(handle) gone. No need to refresh") return } // If retry count exceeded, cancel it, we're done if let maxRetryCount = SDKConfiguration.shared.refreshRetryCount, taskData.retryCount >= maxRetryCount, let data = pendingTasks.removeValue(forKey: handle) { log(level: .warn, from: self, "refresh retry count for \(handle) exceeeded") DispatchQueue.main.async { let userInfo: [AnyHashable: Any] = [ NSLocalizedDescriptionKey: "Refresh retry count exceeded", ] let error = NSError( domain: ClientError.domain, code: ClientError.RefreshRetryExceededCode, userInfo: userInfo as? [String: Any] ) data.errorCallback?(.userRefreshFailed(error)) } return } let refreshInProgress = operationQueue.isSuspended log(level: .debug, from: self, refreshInProgress ? "refresh already in progress" : "suspending queue") operationQueue.isSuspended = true log(level: .debug, from: self, "re-adding \(handle)") let newOperation = TaskOperation(executor: taskData.operation.executor) let newData = TaskData( operation: newOperation, errorCallback: taskData.errorCallback, taskDidCancelCallback: taskData.taskDidCancelCallback, retryCount: taskData.retryCount + 1, taskReference: taskData.taskReference ) pendingTasks[handle] = newData operationsToReAdd.append(newOperation) guard !refreshInProgress else { return } } #if DEBUG // This is just used for running tests, lets not call it in release code willStartRefresh.emitSync(handle) #endif log(from: self, "refreshing tokens for for user \(user)") user.refresh { [weak self] result in guard let strongSelf = self else { return } do { try result.materialize() strongSelf.lock.lock() defer { strongSelf.lock.unlock() } log(level: .debug, from: self, "unsuspending queue") strongSelf.operationQueue.isSuspended = false strongSelf.operationQueue.addOperations(strongSelf.operationsToReAdd, waitUntilFinished: false) strongSelf.operationsToReAdd.removeAll() } catch { strongSelf.lock.lock() log(level: .debug, from: strongSelf, "removing \(strongSelf.pendingTasks.count) pending tasks") let allHandles = strongSelf.pendingTasks strongSelf.pendingTasks.removeAll() strongSelf.operationsToReAdd.removeAll() strongSelf.operationQueue.isSuspended = false strongSelf.lock.unlock() allHandles.forEach { $1.operation.cancel() } DispatchQueue.main.async { [weak self] in log(level: .error, from: self, "calling \(allHandles.count) error callbacks") for (_, state) in allHandles { state.errorCallback?(.userRefreshFailed(error)) } } if let clientError = error as? ClientError { switch clientError { case let .networkingError(internaleError): let logoutCodes = [401, 403] if case let NetworkingError.unexpectedStatus(status, _) = internaleError, logoutCodes.contains(status) { strongSelf.user?.logout() } case .invalidClientCredentials: strongSelf.user?.logout() // // HACK HACK HACK! // // this is a hack for now. oauth/token returns invalid_grant when the grant type is authorization_code // and the code is wrong, and it returns invalid_grant when the authorization_type is refresh_token // and the token is invalid. They are parsed as invalidCode inside IdentityAPI error handling, but invalidCode // is for a client to see, where as a refresh failure should not have a corresponding ClientError and there's // no way (short of if-else hacks on the form_data that is passed to the requstor) to distinguish the two // cases. So for now we handle it here until someone thinks of a better way // case .invalidCode: strongSelf.user?.logout() default: break } } } } } func cancel(handle handleToCancel: OwnedTaskHandle) { let maybeData = lock.scope { self.pendingTasks.removeValue(forKey: handleToCancel) } guard let taskData = maybeData else { log(from: self, "\(handleToCancel) not found") return } log(level: .verbose, from: self, "cancelling \(handleToCancel)") taskData.operation.cancel() taskData.taskDidCancelCallback?() } }
0
// // UIView+PopupOverlay.swift // PopupOverlay // // Created by Alexander Solis on 6/2/19. // Copyright © 2019 MellonTec. All rights reserved. // import UIKit extension UIView { static func popupView(size: CGSize, cornerRadius: CGFloat, color: UIColor) -> UIView { let containerViewRect = CGRect(origin: .zero, size: size) let view = UIView(frame: containerViewRect) let overlay = UIView.createOverlay(backgroundColor: color) view.center = CGPoint( x: overlay.bounds.size.width/2, y: overlay.bounds.size.height/2 ) view.layer.cornerRadius = cornerRadius view.backgroundColor = color overlay.addSubview(view) view.centerViewInSuperview() return view } private static func createOverlay(backgroundColor: UIColor) -> UIView { let window = UIApplication.shared.delegate!.window!! let overlay = UIView(frame: window.bounds) overlay.backgroundColor = backgroundColor overlay.translatesAutoresizingMaskIntoConstraints = false window.addSubview(overlay) let viewsDictionary = ["blocker": overlay] // Add constraints to handle orientation change let constraintsV = NSLayoutConstraint.constraints( withVisualFormat: "V:|-0-[blocker]-0-|", options: [], metrics: nil, views: viewsDictionary ) let constraintsH = NSLayoutConstraint.constraints( withVisualFormat: "|-0-[blocker]-0-|", options: [], metrics: nil, views: viewsDictionary ) window.addConstraints(constraintsV + constraintsH) return overlay } private func centerViewInSuperview() { assert(self.superview != nil, "`view` should have a superview") self.translatesAutoresizingMaskIntoConstraints = false let constraintH = NSLayoutConstraint( item: self, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.superview, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0 ) let constraintV = NSLayoutConstraint( item: self, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.superview, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0 ) let constraintWidth = NSLayoutConstraint( item: self, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: self.frame.size.width ) let constraintHeight = NSLayoutConstraint( item: self, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: self.frame.size.height ) self.superview!.addConstraints([constraintV, constraintH, constraintWidth, constraintHeight]) } }
0
// swift-tools-version: 5.7 import PackageDescription let package = Package( name: "Library", products: [ .library(name: "Library", targets: ["Library"]), ], dependencies: [ .package(path: "../PluginOnly") ], targets: [ .target(name: "Library", plugins: [.plugin(name: "MyPlugin", package: "PluginOnly")]), ] )
0
// // UIKitRenderer.swift // TemplateKit // // Created by Matias Cudich on 9/3/16. // Copyright © 2016 Matias Cudich. All rights reserved. // import Foundation public enum ElementType: ElementRepresentable { case box case button case text case textField case image case table case collection case activityIndicator case view(UIView) case component(ComponentCreation.Type) public var tagName: String { switch self { case .box: return "box" case .text: return "text" case .textField: return "textfield" case .image: return "image" case .button: return "button" case .table: return "table" case .collection: return "collection" case .activityIndicator: return "activityindicator" case .component(let ComponentType): return "\(ComponentType)" default: fatalError("Unknown element type") } } public func make(_ element: Element, _ owner: Node?, _ context: Context?) -> Node { switch (self, element) { case (.box, let element as ElementData<Box.PropertiesType>): return NativeNode<Box>(element: element, children: element.children?.map { $0.build(withOwner: owner, context: nil) }, owner: owner, context: context) case (.text, let element as ElementData<Text.PropertiesType>): return NativeNode<Text>(element: element, owner: owner, context: context) case (.textField, let element as ElementData<TextField.PropertiesType>): return NativeNode<TextField>(element: element, owner: owner, context: context) case (.image, let element as ElementData<Image.PropertiesType>): return NativeNode<Image>(element: element, owner: owner, context: context) case (.button, _): return Button(element: element, children: nil, owner: owner, context: context) case (.table, let element as ElementData<TableProperties>): return Table(element: element, children: nil, owner: owner, context: context) case (.collection, let element as ElementData<CollectionProperties>): return Collection(element: element, children: nil, owner: owner, context: context) case (.activityIndicator, let element as ElementData<ActivityIndicator.PropertiesType>): return NativeNode<ActivityIndicator>(element: element, owner: owner, context: context) case (.view(let view), let element as ElementData<DefaultProperties>): return ViewNode(view: view, element: element, owner: owner, context: context) case (.component(let ComponentType), _): return ComponentType.init(element: element, children: nil, owner: owner, context: context) default: fatalError("Supplied element \(element) does not match type \(self)") } } public func equals(_ other: ElementRepresentable) -> Bool { guard let otherType = other as? ElementType else { return false } return self == otherType } } public func ==(lhs: ElementType, rhs: ElementType) -> Bool { switch (lhs, rhs) { case (.box, .box), (.button, .button), (.text, .text), (.image, .image), (.textField, .textField), (.table, .table), (.activityIndicator, .activityIndicator), (.collection, .collection): return true case (.view(let lhsView), .view(let rhsView)): return lhsView === rhsView case (.component(let lhsClass), .component(let rhsClass)): return lhsClass == rhsClass default: return false } } class DefaultContext: Context { let templateService: TemplateService = XMLTemplateService() let updateQueue: DispatchQueue = DispatchQueue(label: "UIKitRenderer") } public class UIKitRenderer: Renderer { public typealias ViewType = UIView public static let defaultContext: Context = DefaultContext() }
0
// // RSUmenManager.swift // gokarting // // Created by ZS on 2018/5/16. // Copyright © 2018年 ZS. All rights reserved. // import UIKit import MessageUI private let wechatAppKey = "" private let wechatAppSecret = "" private let wechatRedirectURL = "http://www.benson-car.com" private let qqAppkey = "" private let qqAppSecret = "" private let qqRedirectURL = "http://www.benson-car.com" private let sinaAppKey = "" private let sinaAppSecret = "" private let sinaRedirectURL = "http://www.benson-car.com" enum PlatformType: Int{ case wechatType case qqType case sinaType case WechatTimeLine case email case platformUnKnow } enum ShareType: Int { case shareText case shareImage case shareImageAndText case shareWeb case shareMusic case shareVideo case sharUnKnow } class RSUmenManager: NSObject { @objc class func confitUShareSettings() { UMSocialGlobal.shareInstance().isUsingHttpsWhenShareContent = false UMConfigure.initWithAppkey("", channel: nil) UMConfigure.setLogEnabled(true) configUSharePlatforms() } private class func configUSharePlatforms() { //微信 UMSocialManager.default().setPlaform(.wechatSession, appKey: wechatAppKey, appSecret: wechatAppSecret, redirectURL: wechatRedirectURL) UMSocialManager.default().removePlatformProvider(with: .wechatFavorite) UMSocialManager.default().setPlaform(.QQ, appKey: qqAppkey, appSecret: qqAppSecret, redirectURL: qqRedirectURL) UMSocialManager.default().setPlaform(.sina, appKey: sinaAppKey, appSecret: sinaAppSecret, redirectURL: sinaRedirectURL) } @objc class func configUMGoBack(url: URL) -> Bool { return UMSocialManager.default().handleOpen(url) } class func shareEmail(vc: UIViewController) { guard MFMailComposeViewController.canSendMail() else { return } // let mailVC = MFMailComposeViewController() mailVC.setSubject("本森超跑") mailVC.setMessageBody("r本森超跑-期待你的加入", isHTML: false) if let image = UIImage(named: "common_logio") { mailVC.addAttachmentData(image.pngData()!, mimeType: "image/png", fileName: "logo") } vc.navigationController?.present(mailVC, animated: true, completion: nil) } class func share(platformtype: PlatformType, sharemodel: ShareModel, shareType: ShareType ){ var platform: UMSocialPlatformType? switch platformtype { case .wechatType: platform = .wechatSession break case .qqType: platform = .QQ break case .sinaType: platform = .sina break case .WechatTimeLine: platform = .wechatTimeLine break case .email: platform = .email break default: return } let messageObject = UMSocialMessageObject.init() switch shareType { /// 只分享文字 case .shareText: messageObject.text = sharemodel.text break /// 分享图片 case .shareImage: let shareObject = UMShareImageObject.init() if let _ = sharemodel.thumbImage{ shareObject.thumbImage = UIImage(named: sharemodel.thumbImage!) } if let _ = sharemodel.imageUrl{ shareObject.shareImage = sharemodel.imageUrl } messageObject.shareObject = shareObject break /// 分享图文(支持新浪微博) case .shareImageAndText: messageObject.text = sharemodel.text let shareObject = UMShareImageObject.init() if let _ = sharemodel.thumbImage{ shareObject.thumbImage = UIImage(named: sharemodel.thumbImage!) } if let _ = sharemodel.imageUrl{ shareObject.shareImage = sharemodel.imageUrl } messageObject.shareObject = shareObject break /// 分享网络连接 case .shareWeb: let shareObject = UMShareWebpageObject.shareObject(withTitle: sharemodel.title, descr: sharemodel.desc, thumImage: UIImage(named: sharemodel.thumbImage ?? "common_logio")) shareObject?.webpageUrl = sharemodel.webUrl messageObject.shareObject = shareObject break /// 分享音乐 case .shareMusic: let shareObject = UMShareMusicObject.shareObject(withTitle: sharemodel.title, descr: sharemodel.desc, thumImage: UIImage(named: sharemodel.thumbImage ?? "common_logio")) shareObject?.musicUrl = sharemodel.musicUrl messageObject.shareObject = shareObject break /// 分享视频URL case .shareVideo: let shareObject = UMShareVideoObject.shareObject(withTitle: sharemodel.title, descr: sharemodel.desc, thumImage: UIImage(named: sharemodel.thumbImage ?? "")) shareObject?.videoUrl = sharemodel.videoUrl messageObject.shareObject = shareObject break default: return // break } //一定不为空了 UMSocialManager.default().share(to: platform!, messageObject: messageObject, currentViewController: nil) { (data, error) in } } class func getAuthWithUserInfoFromWechat(type: PlatformType, complete:@escaping (_ finish: Bool) -> ()){ var platform: UMSocialPlatformType? switch type { case .wechatType: platform = .wechatSession break case .qqType: platform = .QQ break default: platform = .sina break } UMSocialManager.default().getUserInfo(with: platform!, currentViewController: nil) { (result, error) in if (error != nil){ // RSProgressHUD.showStatusNarError(titlerStr: "授权失败") complete(false) }else{ let resp = result as! UMSocialUserInfoResponse print(resp.iconurl) // RSAccount.shared.registUid = resp.uid // RSAccount.shared.registHeadUrl = resp.iconurl // RSAccount.shared.registThirdNick = resp.uid complete(true) } } } } class ShareModel{ //文本 @objc var text: String? /// 缩略图名字,本地的 @objc var thumbImage: String? /// 分享图片的url.string @objc var imageUrl: String? /// 分享网页的url.string @objc var webUrl: String? /// 分享的标题 @objc var title: String? /// 分享内容描述 @objc var desc: String? /// 分享音乐url.string @objc var musicUrl: String? /// 分享的视频url.string @objc var videoUrl: String? }
0
// // MagazineCollectionView.swift // SwiftMagazine // // Created by Heberti Almeida on 18/09/14. // Copyright (c) 2014 CocoaHeads Brasil. All rights reserved. // import UIKit class MagazineCollectionView: UICollectionView { var index: Int! init(frame: CGRect, index: Int) { self.index = index // Layout var layout = SpringyFlowLayout() layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) layout.itemSize = CGSize(width: 160, height: 265) layout.minimumLineSpacing = 15 layout.minimumInteritemSpacing = 15 layout.scrollDirection = UICollectionViewScrollDirection.Horizontal; // Init super.init(frame: frame, collectionViewLayout: layout) // Custom collection self.registerClass(MagazineCollectionViewCell.self, forCellWithReuseIdentifier: reuseCollectionItem) self.autoresizingMask = UIViewAutoresizing.FlexibleWidth self.showsHorizontalScrollIndicator = false self.backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
0
// // ArrayBuilderTests.swift // // // Created by Thibault Wittemberg on 2021-02-21. // import Feedbacks import XCTest final class ArrayBuilderTests: XCTestCase { @ArrayBuilder<Int> var mockEntries: [Int] { 1 2 3 4 5 } func testBuildBlock_gathers_entries_into_an_array() { XCTAssertEqual(self.mockEntries, [1, 2, 3, 4, 5]) } }
0
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck import CoreData }(n: T) protocol a { let i: Any, k : (self.B typealias d: d wh
0
// // QSMainTabBarController.swift // QSBaoKan // // Created by mba on 16/6/7. // Copyright © 2016年 mbalib. All rights reserved. // import UIKit class QSMainTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // 增加所有只控制器 addChildViewControllers() } /** 添加所有子控制器 */ private func addChildViewControllers() { // 1.获取json文件的路径 let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) // 2.通过文件路径创建NSData if let jsonPath = path{ let jsonData = NSData(contentsOfFile: jsonPath) do{ // 有可能发生异常的代码放到这里 // 3.序列化json数据 --> Array // try : 发生异常会跳到catch中继续执行 // try! : 发生异常程序直接崩溃 let dictArr = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers) // 4.遍历数组, 动态创建控制器和设置数据 // 在Swift中, 如果需要遍历一个数组, 必须明确数据的类型 for dict in dictArr as! [[String: String]] { // 报错的原因是因为addChildViewController参数必须有值, 但是字典的返回值是可选类型 addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!) } }catch { // 发生异常之后会执行的代码 print(error) // 从本地创建控制器 // addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home") // addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center") // // // 再添加一个占位控制器 // addChildViewController("NullViewController", title: "", imageName: "") // addChildViewController("DiscoverTableViewController", title: "广场", imageName: "tabbar_discover") // addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile") } } } /** 初始化子控制器 :param: childController 需要初始化的子控制器 :param: title 子控制器的标题 :param: imageName 子控制器的图片 */ private func addChildViewController(childControllerName: String, title:String, imageName:String) { // -1.动态获取命名空间 let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String // 0 .将字符串转换为类 // 0.1默认情况下命名空间就是项目的名称, 但是命名空间名称是可以修改的 let cls:AnyClass? = NSClassFromString(ns + "." + childControllerName) // 0.2通过类创建对象 // 0.2.1将AnyClass转换为指定的类型 let vcCls = cls as! UIViewController.Type // 0.2.2通过class创建对象 let vc = vcCls.init() // 1设置首页对应的数据 vc.tabBarItem.image = UIImage(named: "\(imageName)_normal") vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") vc.title = title // 2.给首页包装一个导航控制器 let nav = UINavigationController() nav.addChildViewController(vc) // 3.将导航控制器添加到当前控制器上 addChildViewController(nav) } }
0
import PackageDescription let package = Package( name: "Parsey", dependencies: [ .Package(url: "https://github.com/rxwei/Funky", majorVersion: 2) ] )
0
// // BarLineScatterCandleBubbleRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(BarLineScatterCandleBubbleChartRenderer) open class BarLineScatterCandleBubbleRenderer: DataRenderer { internal var _xBounds = XBounds() // Reusable XBounds object public override init(animator: Animator, viewPortHandler: ViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) } /// Checks if the provided entry object is in bounds for drawing considering the current animation phase. internal func isInBoundsX(entry e: ChartDataEntry, dataSet: IBarLineScatterCandleBubbleChartDataSet) -> Bool { let entryIndex = dataSet.entryIndex(entry: e) return Double(entryIndex) < Double(dataSet.entryCount) * animator.phaseX } /// Calculates and returns the x-bounds for the given DataSet in terms of index in their values array. /// This includes minimum and maximum visible x, as well as range. internal func xBounds(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: IBarLineScatterCandleBubbleChartDataSet, animator: Animator?) -> XBounds { return XBounds(chart: chart, dataSet: dataSet, animator: animator) } /// - Returns: `true` if the DataSet values should be drawn, `false` if not. internal func shouldDrawValues(forDataSet set: IChartDataSet) -> Bool { return set.isVisible && (set.isDrawValuesEnabled || set.isDrawIconsEnabled) } /// Class representing the bounds of the current viewport in terms of indices in the values array of a DataSet. open class XBounds { /// minimum visible entry index open var min: Int = 0 /// maximum visible entry index open var max: Int = 0 /// range of visible entry indices open var range: Int = 0 public init() { } public init(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: IBarLineScatterCandleBubbleChartDataSet, animator: Animator?) { self.set(chart: chart, dataSet: dataSet, animator: animator) } /// Calculates the minimum and maximum x values as well as the range between them. open func set(chart: BarLineScatterCandleBubbleChartDataProvider, dataSet: IBarLineScatterCandleBubbleChartDataSet, animator: Animator?) { let phaseX = Swift.max(0.0, Swift.min(1.0, animator?.phaseX ?? 1.0)) let low = chart.lowestVisibleX let high = chart.highestVisibleX let entryFrom = dataSet.entryForXValue(low, closestToY: .nan, rounding: .down) let entryTo = dataSet.entryForXValue(high, closestToY: .nan, rounding: .up) self.min = entryFrom == nil ? 0 : dataSet.entryIndex(entry: entryFrom!) self.max = entryTo == nil ? 0 : dataSet.entryIndex(entry: entryTo!) range = Int(Double(self.max - self.min) * phaseX) } } } extension BarLineScatterCandleBubbleRenderer.XBounds: RangeExpression { public func relative<C>(to collection: C) -> Swift.Range<Int> where C : Collection, Bound == C.Index { return Swift.Range<Int>(min...min + range) } public func contains(_ element: Int) -> Bool { return (min...min + range).contains(element) } } extension BarLineScatterCandleBubbleRenderer.XBounds: Sequence { public struct Iterator: IteratorProtocol { private let bounds: BarLineScatterCandleBubbleRenderer.XBounds private var value: Int fileprivate init(bounds: BarLineScatterCandleBubbleRenderer.XBounds) { self.bounds = bounds self.value = bounds.min } public mutating func next() -> Int? { guard value < bounds.max else { return nil } value += 1 return value } } public func makeIterator() -> Iterator { return Iterator(bounds: self) } }
0
import SwiftUI @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public struct Inspector { } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) internal extension Inspector { static func attribute(label: String, value: Any) throws -> Any { if label == "super", let superclass = Mirror(reflecting: value).superclassMirror { return superclass } return try attribute(label: label, value: value, type: Any.self) } static func attribute<T>(label: String, value: Any, type: T.Type) throws -> T { let mirror = (value as? Mirror) ?? Mirror(reflecting: value) guard let child = mirror.descendant(label) else { throw InspectionError.attributeNotFound( label: label, type: typeName(value: value)) } return try cast(value: child, type: T.self) } static func attribute(path: String, value: Any) throws -> Any { return try attribute(path: path, value: value, type: Any.self) } static func attribute<T>(path: String, value: Any, type: T.Type) throws -> T { let labels = path.components(separatedBy: "|") let child = try labels.reduce(value, { (value, label) -> Any in try attribute(label: label, value: value) }) return try cast(value: child, type: T.self) } static func cast<T>(value: Any, type: T.Type) throws -> T { guard let casted = value as? T else { throw InspectionError.typeMismatch(value, T.self) } return casted } enum GenericParameters { case keep case remove case customViewPlaceholder } static func typeName(value: Any, namespaced: Bool = false, generics: GenericParameters = .keep) -> String { return typeName(type: type(of: value), namespaced: namespaced, generics: generics) } static func typeName(type: Any.Type, namespaced: Bool = false, generics: GenericParameters = .keep) -> String { let typeName = namespaced ? String(reflecting: type).sanitizingNamespace() : String(describing: type) switch generics { case .keep: return typeName case .remove: return typeName.replacingGenericParameters("") case .customViewPlaceholder: let parameters = ViewType.customViewGenericsPlaceholder return typeName.replacingGenericParameters(parameters) } } } private extension String { func sanitizingNamespace() -> String { var str = self if let range = str.range(of: ".(unknown context at ") { let end = str.index(range.upperBound, offsetBy: .init(11)) str.replaceSubrange(range.lowerBound..<end, with: "") } return str } func replacingGenericParameters(_ replacement: String) -> String { guard let start = self.firstIndex(of: "<") else { return self } var balance = 1 var current = self.index(after: start) while balance > 0 && current < endIndex { let char = self[current] if char == "<" { balance += 1 } if char == ">" { balance -= 1 } current = self.index(after: current) } if balance == 0 { return String(self[..<start]) + replacement + String(self[current...]).replacingGenericParameters(replacement) } return self } } // MARK: - Attributes lookup @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension Inspector { /** Use this function to lookup the struct content: ``` (lldb) po Inspector.print(view) as AnyObject ``` */ static func print(_ value: Any) -> String { let tree = attributesTree(value: value, medium: .empty, visited: []) return typeName(value: value) + print(tree, level: 1) } fileprivate static func print(_ value: Any, level: Int) -> String { let prefix = Inspector.newline(value: value) if let array = value as? [Any] { return prefix + array.description(level: level) } else if let dict = value as? [String: Any] { return prefix + dict.description(level: level) } return prefix + String(describing: value) + "\n" } fileprivate static func indent(level: Int) -> String { return Array(repeating: " ", count: level).joined() } private static func newline(value: Any) -> String { let needsNewLine: Bool = { if let array = value as? [Any] { return array.count > 0 } return value is [String: Any] }() return needsNewLine ? "\n" : "" } private static func attributesTree(value: Any, medium: Content.Medium, visited: [AnyObject]) -> Any { var visited = visited if type(of: value) is AnyClass { let ref = value as AnyObject guard !visited.contains(where: { $0 === ref }) else { return " = { cyclic reference }" } visited.append(ref) } if let array = value as? [Any] { return array.map { attributesTree(value: $0, medium: medium, visited: visited) } } let medium = (try? unwrap(content: Content(value, medium: medium)).medium) ?? medium var mirror = Mirror(reflecting: value) var children = Array(mirror.children) while let superclass = mirror.superclassMirror { mirror = superclass children.append(contentsOf: superclass.children) } var dict: [String: Any] = [:] children.enumerated().forEach { child in let childName = child.element.label ?? "[\(child.offset)]" let childType = typeName(value: child.element.value) dict[childName + ": " + childType] = attributesTree( value: child.element.value, medium: medium, visited: visited) } if let inspectable = value as? Inspectable, let content = try? inspectable.extractContent(environmentObjects: medium.environmentObjects) { let childType = typeName(value: content) dict["body: " + childType] = attributesTree(value: content, medium: medium, visited: visited) } if dict.count == 0 { return " = " + String(describing: value) } return dict } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) fileprivate extension Dictionary where Key == String { func description(level: Int) -> String { let indent = Inspector.indent(level: level) return sorted(by: { $0.key < $1.key }).reduce("") { (str, pair) -> String in return str + indent + pair.key + Inspector.print(pair.value, level: level + 1) } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) fileprivate extension Array { func description(level: Int) -> String { guard count > 0 else { return " = []\n" } let indent = Inspector.indent(level: level) return enumerated().reduce("") { (str, pair) -> String in return str + indent + "[\(pair.offset)]" + Inspector.print(pair.element, level: level + 1) } } } // MARK: - View Inspection @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) internal extension Inspector { static func viewsInContainer(view: Any, medium: Content.Medium) throws -> LazyGroup<Content> { let unwrappedContainer = try Inspector.unwrap(content: Content(view, medium: medium.resettingViewModifiers())) guard Inspector.isTupleView(unwrappedContainer.view) else { return LazyGroup(count: 1) { _ in unwrappedContainer } } return try ViewType.TupleView.children(unwrappedContainer) } static func isTupleView(_ view: Any) -> Bool { return Inspector.typeName(value: view, generics: .remove) == ViewType.TupleView.typePrefix } static func unwrap(view: Any, medium: Content.Medium) throws -> Content { return try unwrap(content: Content(view, medium: medium)) } // swiftlint:disable cyclomatic_complexity static func unwrap(content: Content) throws -> Content { switch Inspector.typeName(value: content.view, generics: .remove) { case "Tree": return try ViewType.TreeView.child(content) case "IDView": return try ViewType.IDView.child(content) case "Optional": return try ViewType.OptionalContent.child(content) case "EquatableView": return try ViewType.EquatableView.child(content) case "ModifiedContent": return try ViewType.ViewModifier<ViewType.Stub>.child(content) case "SubscriptionView": return try ViewType.SubscriptionView.child(content) case "_UnaryViewAdaptor": return try ViewType.UnaryViewAdaptor.child(content) case "_ConditionalContent": return try ViewType.ConditionalContent.child(content) case "EnvironmentReaderView": return try ViewType.EnvironmentReaderView.child(content) case "_DelayedPreferenceView": return try ViewType.DelayedPreferenceView.child(content) case "_PreferenceReadingView": return try ViewType.PreferenceReadingView.child(content) default: return content } } // swiftlint:enable cyclomatic_complexity static func guardType(value: Any, namespacedPrefixes: [String], inspectionCall: String) throws { var typePrefix = typeName(type: type(of: value), namespaced: true, generics: .remove) if typePrefix == ViewType.popupContainerTypePrefix { typePrefix = typeName(type: type(of: value), namespaced: true) } if typePrefix == "SwiftUI.EnvironmentReaderView" { let typeWithParams = typeName(type: type(of: value)) if typeWithParams.contains("NavigationBarItemsKey") { throw InspectionError.notSupported( """ Please insert '.navigationBarItems()' before \(inspectionCall) \ for unwrapping the underlying view hierarchy. """) } } if namespacedPrefixes.contains(typePrefix) { return } if let prefix = namespacedPrefixes.first { let typePrefix = typeName(type: type(of: value), namespaced: true) throw InspectionError.typeMismatch(factual: typePrefix, expected: prefix) } } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension InspectionError { static func typeMismatch<V, T>(_ value: V, _ expectedType: T.Type) -> InspectionError { var factual = Inspector.typeName(value: value) var expected = Inspector.typeName(type: expectedType) if factual == expected { factual = Inspector.typeName(value: value, namespaced: true) expected = Inspector.typeName(type: expectedType, namespaced: true) } return .typeMismatch(factual: factual, expected: expected) } }
0
// // DCPagerProgressView.swift // CDDPagerControllerDemo-Swift // // Created by 陈甸甸 on 2018/3/5. //Copyright © 2018年 陈甸甸. All rights reserved. // import UIKit class DCPagerProgressView: UIView { /** 进度条 */ var progress: NSInteger? /** 尺寸 */ var itemFrames : NSMutableArray? /** 颜色 */ var color : UIColor? /** 是否拉伸 */ var isStretch : Bool? override init(frame: CGRect) { //重写方法 super.init(frame: frame) setUpUI() } func setUpUI() { let height = CGFloat(self.frame.size.height) let lineWidth = 2.0 let cornerRadius = (height >= 4) ? 3.0 : lineWidth self.layer.cornerRadius = CGFloat(cornerRadius) self.layer.masksToBounds = true } override func draw(_ rect: CGRect) { } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
0
import Foundation import Strix public enum TokenType: Int { case end case number case string case `operator` case name case comment } public struct Token: Hashable { public var type: TokenType public var value: String public init(type: TokenType, value: String = "") { self.type = type self.value = value } } public protocol TokenHandling {} public struct NullDenotation<T>: TokenHandling { public typealias Expression = (_ token: Token, _ parser: PrattParser<T>) throws -> T public let expression: Expression public init(expression: @escaping Expression) { self.expression = expression } } public struct LeftDenotation<T>: TokenHandling { public typealias Expression = (_ leftValue: T, _ token: Token, _ parser: PrattParser<T>) throws -> T public let bindingPower: Int public let expression: Expression public init(bindingPower: Int, expression: @escaping Expression) { self.bindingPower = bindingPower self.expression = expression } } private class DenotationGroup<Denotation: TokenHandling> { var denotations: [String: Denotation] = [:] var commonDenotation: Denotation? subscript(token: Token) -> Denotation? { return denotations[token.value] ?? commonDenotation } } extension PrattParser { public enum Error: Swift.Error { case tokenizerFailure(Swift.Error) case denotationNotFound(String) } } public final class PrattParser<T> { private var nullDenotationGroups: [TokenType: DenotationGroup<NullDenotation<T>>] = [:] private var leftDenotationGroups: [TokenType: DenotationGroup<LeftDenotation<T>>] = [:] public private(set) var nextToken: Token = Token(type: .end) public private(set) var advance: () throws -> Void = {} public init() {} public func parse<S: Sequence>(_ tokens: S) throws -> T where S.Element == Token { let tokens = AnyIterator(tokens.makeIterator()) advance = { [self] in if let token = tokens.next() { nextToken = token } else if nextToken.type != .end { nextToken = Token(type: .end) } } return try parse() } public func parse(_ string: String, with tokenizer: Parser<Token>) throws -> T { var state = ParserState(stream: string[...]) advance = { [self] in switch tokenizer.parse(&state) { case let .success(token, _): nextToken = token case let .failure(errors): throw Error.tokenizerFailure( RunError(input: string, position: state.position, underlyingErrors: errors)) } } return try parse() } private func parse() throws -> T { defer { nextToken = Token(type: .end) advance = {} } try advance() return try expression(withRightBindingPower: 0) } public func expression(withRightBindingPower rightBindingPower: Int) throws -> T { let token = nextToken let nud = try nullDenotation(for: token) try advance() var leftValue = try nud.expression(token, self) while true { let token = nextToken let led = try leftDenotation(for: token) guard rightBindingPower < led.bindingPower else { break } try advance() leftValue = try led.expression(leftValue, token, self) } return leftValue } } extension PrattParser { public func add(denotation: NullDenotation<T>, for token: Token) { let group = denotationGroup(for: token.type, in: &nullDenotationGroups) group.denotations[token.value] = denotation } public func add(denotation: NullDenotation<T>, for tokenType: TokenType) { let group = denotationGroup(for: tokenType, in: &nullDenotationGroups) group.commonDenotation = denotation } public func addDenotation( for token: Token, expression: @escaping NullDenotation<T>.Expression ) { add(denotation: NullDenotation<T>(expression: expression), for: token) } public func addDenotation( for tokenType: TokenType, expression: @escaping NullDenotation<T>.Expression ) { add(denotation: NullDenotation<T>(expression: expression), for: tokenType) } public func add(denotation: LeftDenotation<T>, for token: Token) { let group = denotationGroup(for: token.type, in: &leftDenotationGroups) group.denotations[token.value] = denotation } public func add(denotation: LeftDenotation<T>, for tokenType: TokenType) { let group = denotationGroup(for: tokenType, in: &leftDenotationGroups) group.commonDenotation = denotation } public func addDenotation( for token: Token, bindingPower: Int, expression: @escaping LeftDenotation<T>.Expression ) { let denotation = LeftDenotation<T>(bindingPower: bindingPower, expression: expression) add(denotation: denotation, for: token) } public func addDenotation( for tokenType: TokenType, bindingPower: Int, expression: @escaping LeftDenotation<T>.Expression ) { let denotation = LeftDenotation<T>(bindingPower: bindingPower, expression: expression) add(denotation: denotation, for: tokenType) } } extension PrattParser { private func nullDenotation(for token: Token) throws -> NullDenotation<T> { guard let result: NullDenotation = denotation(for: token, in: nullDenotationGroups) else { throw Error.denotationNotFound("could not find the null denotation for \(token)") } return result } private func leftDenotation(for token: Token) throws -> LeftDenotation<T> { guard let result: LeftDenotation = denotation(for: token, in: leftDenotationGroups) else { throw Error.denotationNotFound("could not find the left denotation for \(token)") } return result } private func denotation<Denotation>( for token: Token, in groups: [TokenType: DenotationGroup<Denotation>] ) -> Denotation? { return groups[token.type]?[token] } private func denotationGroup<Denotation>( for type: TokenType, in groups: inout [TokenType: DenotationGroup<Denotation>] ) -> DenotationGroup<Denotation> { let result: DenotationGroup<Denotation> if let group = groups[type] { result = group } else { result = DenotationGroup<Denotation>() groups[type] = result } return result } }
0
// // OES_standard_derivatives.swift // CanvasNative // // Created by Osei Fortune on 4/27/20. // import Foundation import OpenGLES @objcMembers @objc(TNS_OES_standard_derivatives) public class TNS_OES_standard_derivatives: NSObject { public override init() {} }
0
// // ChromaPickerServiceView.swift // Shlist // // Created by Pavel Lyskov on 30.04.2020. // Copyright © 2020 Pavel Lyskov. All rights reserved. // import Reusable import UIKit final class ChromaPickerServiceView: UIView { @IBOutlet var navBar: UINavigationBar! @IBOutlet var doneButton: UIBarButtonItem! @IBOutlet var colorPicker: ChromaColorPicker! @IBOutlet var cancelButton: UIBarButtonItem! @IBOutlet var hexTextField: UITextField! @IBOutlet var brightnessSlider: ChromaBrightnessSlider! var color: UIColor? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } init(color: UIColor) { super.init(frame: .zero) self.color = color self.setup() } func setup() { fromNib() self.brightnessSlider.trackColor = self.color ?? .white self.brightnessSlider.connect(to: self.colorPicker) self.colorPicker.addHandle(at: self.color) self.colorPicker.currentHandle = self.colorPicker.handles[0] self.brightnessSlider.borderWidth = 1 } }
0
public struct DetailsViewModel { public var identifier: String public var icon: String public var price: Double public var lastHour: Double public var lastMonth: Double public var lastYear: Double public init(identifier: String, icon: String, price: Double, lastHour: Double, lastMonth: Double, lastYear: Double) { self.identifier = identifier self.icon = icon self.price = price self.lastHour = lastHour self.lastMonth = lastMonth self.lastYear = lastYear } }
0
@dynamicMemberLookup public final class NestedProperty<Model, Property> where Model: Fields, Property: PropertyProtocol { public let prefix: [FieldKey] public let property: Property init(prefix: [FieldKey], property: Property) { self.prefix = prefix self.property = property } public subscript<Property>( dynamicMember keyPath: KeyPath<Value, Property> ) -> NestedProperty<Model, Property> { .init(prefix: self.path, property: self.value![keyPath: keyPath]) } } extension NestedProperty: AnyField where Property: AnyField { } extension NestedProperty: FieldProtocol where Property: FieldProtocol { } extension NestedProperty: PropertyProtocol { public var path: [FieldKey] { self.prefix + self.property.path } public typealias Model = Property.Model public typealias Value = Property.Value public var value: Value? { get { self.property.value } set { self.property.value = newValue } } } extension NestedProperty: AnyProperty { public var nested: [AnyProperty] { fatalError() } public func input(to input: inout DatabaseInput) { fatalError() } public func output(from output: DatabaseOutput) throws { fatalError() } public func encode(to encoder: Encoder) throws { fatalError() } public func decode(from decoder: Decoder) throws { fatalError() } }
0
// // LNSSimpleTemplateChooser.swift // LNSTemplateChooser // // Created by Mark Alldritt on 2020-07-12. // Copyright © 2020 Mark Alldritt. All rights reserved. // import UIKit public class LNSSimpleTemplateChooser: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, LNSTemplateCellChooser { public var templates: [LNSTemplate] = [] { didSet { if isViewLoaded { collectionView.reloadData() } } } public var completion: ((_ template: LNSTemplate) -> Void)? public var thumbnailSize = CGFloat(220) { didSet { if isViewLoaded { collectionView.reloadData() } } } private (set) var collectionView: UICollectionView! override public func loadView() { let flowLayout = UICollectionViewFlowLayout() flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) collectionView.backgroundColor = .systemBackground collectionView.dataSource = self collectionView.delegate = self collectionView.allowsSelection = true collectionView.allowsMultipleSelection = false collectionView.register(UINib(nibName: "LNSTemplateCell", bundle: .module), forCellWithReuseIdentifier: "LNSTemplateCell") collectionView.tintColor = navigationController?.navigationBar.tintColor ?? UIColor.blue view = collectionView navigationItem.title = "Choose a Template" } public func clearOpeningIndication() { if let selectedIndexPath = collectionView.indexPathsForSelectedItems?.first { collectionView.deselectItem(at: selectedIndexPath, animated: true) } } // MARK: - UICollectionViewDataSource public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return templates.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let template = templates[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LNSTemplateCell", for: indexPath) as! LNSTemplateCell cell.templateChooser = self cell.configure(for: template) return cell } // MARK: - UICollectionViewDelete public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let template = templates[indexPath.row] completion?(template) } // MARK: - UICollectionViewDelegateFlowLayout public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10 } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 12 } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize.zero } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return CGSize.zero } }
0
import Foundation // TODO: Get a logger into here this is real tricky // because of the decoding from JSON nature of DangerDSL public enum SpawnError: Error { case commandFailed(exitCode: Int32, stdout: String, stderr: String, task: Process) } internal class ShellExecutor { func execute(_ command: String, arguments: [String] = [], environmentVariables: [String] = []) -> String { let script = [environmentVariables.joined(separator: " "), command, arguments.joined(separator: " ")].filter { !$0.isEmpty }.joined(separator: " ") print("Executing \(script)") var env = ProcessInfo.processInfo.environment let task = Process() task.launchPath = env["SHELL"] task.arguments = ["-l", "-c", script] task.currentDirectoryPath = FileManager.default.currentDirectoryPath let pipe = Pipe() task.standardOutput = pipe task.launch() task.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() return String(data: data, encoding: String.Encoding.utf8)! } // Similar to above, but can throw, and throws with most of // what you'd probably need in a scripting environment func spawn(_ command: String, arguments: [String] = [], environmentVariables: [String] = []) throws -> String { let script = [environmentVariables.joined(separator: " "), command, arguments.joined(separator: " ")].filter { !$0.isEmpty }.joined(separator: " ") var env = ProcessInfo.processInfo.environment let task = Process() task.launchPath = env["SHELL"] task.arguments = ["-l", "-c", script] task.currentDirectoryPath = FileManager.default.currentDirectoryPath let stdout = Pipe() task.standardOutput = stdout let stderr = Pipe() task.standardError = stderr task.launch() task.waitUntilExit() // Pull out the STDOUT as a string because we'll need that regardless let stdoutData = stdout.fileHandleForReading.readDataToEndOfFile() let stdoutString = String(data: stdoutData, encoding: String.Encoding.utf8)! // 0 is no problems in unix land if task.terminationStatus == 0 { return stdoutString } // OK, so it failed, raise a new error with all the useful metadata let stderrData = stdout.fileHandleForReading.readDataToEndOfFile() let stderrString = String(data: stderrData, encoding: String.Encoding.utf8)! throw SpawnError.commandFailed(exitCode: task.terminationStatus, stdout: stdoutString, stderr: stderrString, task: task) } }
0
// // AppDelegate.swift // ReceptionKit // // Created by Andy Cho on 2015-04-23. // Copyright (c) 2015 Andy Cho. All rights reserved. // import UIKit var camera: Camera! @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let conversationDelegate = ConversationDelegate() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Smooch Settings let smoochSettings = SKTSettings(appToken: Config.Smooch.AppToken) Smooch.initWithSettings(smoochSettings) // Setup Smooch Smooch.conversation().delegate = conversationDelegate Smooch.setUserFirstName(Config.Slack.Name, lastName: "") SKTUser.currentUser().email = Config.Slack.Email // App-wide styles UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Slide) UINavigationBar.appearance().barTintColor = UIColor(hex: Config.Colour.NavigationBar) // Create an instance of the Camera // Cannot create this as a declaration above since the camera will not start // recording in that case camera = Camera() return true } }
0
// // ViewController.swift // tippy // // Created by MHC User on 9/10/18. // Copyright © 2018 Anisha Pai. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tipSlider: UISlider! @IBOutlet weak var preTotalLabel: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var percentage: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onTap(_ sender: Any) { view.endEditing(true) } // When user enters numbers @IBAction func UserTypes(_ sender: Any) { let sliderVal = tipSlider.value percentage.text = String(format: "%.0f%%", sliderVal) let preTotal = Double(preTotalLabel.text!) ?? 0 let tip = preTotal * Double(sliderVal / 100) let total = preTotal + tip tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f", total) } }
0
// // WebViewController.swift // Multiplatform macOS // // Created by Maurice Parker on 7/8/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import AppKit import Combine import RSCore import Articles protocol WebViewControllerDelegate: AnyObject { func webViewController(_: WebViewController, articleExtractorButtonStateDidUpdate: ArticleExtractorButtonState) } class WebViewController: NSViewController { private struct MessageName { static let imageWasClicked = "imageWasClicked" static let imageWasShown = "imageWasShown" static let mouseDidEnter = "mouseDidEnter" static let mouseDidExit = "mouseDidExit" static let showFeedInspector = "showFeedInspector" } var statusBarView: WebStatusBarView! private var webView: PreloadedWebView? private var articleExtractor: ArticleExtractor? = nil var extractedArticle: ExtractedArticle? var isShowingExtractedArticle = false var articleExtractorButtonState: ArticleExtractorButtonState = .off { didSet { delegate?.webViewController(self, articleExtractorButtonStateDidUpdate: articleExtractorButtonState) } } var sceneModel: SceneModel? weak var delegate: WebViewControllerDelegate? var articles: [Article]? { didSet { if oldValue != articles { loadWebView() } } } private var cancellables = Set<AnyCancellable>() override func loadView() { view = NSView() } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(webFeedIconDidBecomeAvailable(_:)), name: .WebFeedIconDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(avatarDidBecomeAvailable(_:)), name: .AvatarDidBecomeAvailable, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(faviconDidBecomeAvailable(_:)), name: .FaviconDidBecomeAvailable, object: nil) statusBarView = WebStatusBarView() statusBarView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(statusBarView) NSLayoutConstraint.activate([ self.view.leadingAnchor.constraint(equalTo: statusBarView.leadingAnchor, constant: -6), self.view.trailingAnchor.constraint(greaterThanOrEqualTo: statusBarView.trailingAnchor, constant: 6), self.view.bottomAnchor.constraint(equalTo: statusBarView.bottomAnchor, constant: 2), statusBarView.heightAnchor.constraint(equalToConstant: 20) ]) sceneModel?.timelineModel.selectedArticlesPublisher?.sink { [weak self] articles in self?.articles = articles } .store(in: &cancellables) } // MARK: Notifications @objc func webFeedIconDidBecomeAvailable(_ note: Notification) { reloadArticleImage() } @objc func avatarDidBecomeAvailable(_ note: Notification) { reloadArticleImage() } @objc func faviconDidBecomeAvailable(_ note: Notification) { reloadArticleImage() } // MARK: API func focus() { webView?.becomeFirstResponder() } func canScrollDown(_ completion: @escaping (Bool) -> Void) { fetchScrollInfo { (scrollInfo) in completion(scrollInfo?.canScrollDown ?? false) } } override func scrollPageDown(_ sender: Any?) { webView?.scrollPageDown(sender) } func toggleArticleExtractor() { guard let article = articles?.first else { return } guard articleExtractor?.state != .processing else { stopArticleExtractor() loadWebView() return } guard !isShowingExtractedArticle else { isShowingExtractedArticle = false loadWebView() articleExtractorButtonState = .off return } if let articleExtractor = articleExtractor { if article.preferredLink == articleExtractor.articleLink { isShowingExtractedArticle = true loadWebView() articleExtractorButtonState = .on } } else { startArticleExtractor() } } func stopArticleExtractorIfProcessing() { if articleExtractor?.state == .processing { stopArticleExtractor() } } func stopWebViewActivity() { if let webView = webView { stopMediaPlayback(webView) } } } // MARK: ArticleExtractorDelegate extension WebViewController: ArticleExtractorDelegate { func articleExtractionDidFail(with: Error) { stopArticleExtractor() articleExtractorButtonState = .error loadWebView() } func articleExtractionDidComplete(extractedArticle: ExtractedArticle) { if articleExtractor?.state != .cancelled { self.extractedArticle = extractedArticle isShowingExtractedArticle = true loadWebView() articleExtractorButtonState = .on } } } // MARK: WKScriptMessageHandler extension WebViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { switch message.name { case MessageName.imageWasShown: return case MessageName.imageWasClicked: return case MessageName.mouseDidEnter: if let link = message.body as? String { statusBarView.mouseoverLink = link } case MessageName.mouseDidExit: statusBarView.mouseoverLink = nil case MessageName.showFeedInspector: return default: return } } } extension WebViewController: WKNavigationDelegate { public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if navigationAction.navigationType == .linkActivated { if let url = navigationAction.request.url { let flags = navigationAction.modifierFlags let invert = flags.contains(.shift) || flags.contains(.command) Browser.open(url.absoluteString, invertPreference: invert) } decisionHandler(.cancel) return } decisionHandler(.allow) } } // MARK: Private private extension WebViewController { func loadWebView() { if let webView = webView { self.renderPage(webView) return } sceneModel?.webViewProvider?.dequeueWebView() { webView in webView.ready { // Add the webview self.webView = webView webView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(webView, positioned: .below, relativeTo: self.statusBarView) NSLayoutConstraint.activate([ self.view.leadingAnchor.constraint(equalTo: webView.leadingAnchor), self.view.trailingAnchor.constraint(equalTo: webView.trailingAnchor), self.view.topAnchor.constraint(equalTo: webView.topAnchor), self.view.bottomAnchor.constraint(equalTo: webView.bottomAnchor) ]) webView.navigationDelegate = self webView.configuration.userContentController.add(WrapperScriptMessageHandler(self), name: MessageName.imageWasClicked) webView.configuration.userContentController.add(WrapperScriptMessageHandler(self), name: MessageName.imageWasShown) webView.configuration.userContentController.add(WrapperScriptMessageHandler(self), name: MessageName.mouseDidEnter) webView.configuration.userContentController.add(WrapperScriptMessageHandler(self), name: MessageName.mouseDidExit) webView.configuration.userContentController.add(WrapperScriptMessageHandler(self), name: MessageName.showFeedInspector) self.renderPage(webView) } } } func renderPage(_ webView: PreloadedWebView) { let style = ArticleStylesManager.shared.currentStyle let rendering: ArticleRenderer.Rendering if articles?.count ?? 0 > 1 { rendering = ArticleRenderer.multipleSelectionHTML(style: style) } else if let articleExtractor = articleExtractor, articleExtractor.state == .processing { rendering = ArticleRenderer.loadingHTML(style: style) } else if let articleExtractor = articleExtractor, articleExtractor.state == .failedToParse, let article = articles?.first { rendering = ArticleRenderer.articleHTML(article: article, style: style) } else if let article = articles?.first, let extractedArticle = extractedArticle { if isShowingExtractedArticle { rendering = ArticleRenderer.articleHTML(article: article, extractedArticle: extractedArticle, style: style) } else { rendering = ArticleRenderer.articleHTML(article: article, style: style) } } else if let article = articles?.first { rendering = ArticleRenderer.articleHTML(article: article, style: style) } else { rendering = ArticleRenderer.noSelectionHTML(style: style) } let substitutions = [ "title": rendering.title, "baseURL": rendering.baseURL, "style": rendering.style, "body": rendering.html ] let html = try! MacroProcessor.renderedText(withTemplate: ArticleRenderer.page.html, substitutions: substitutions) webView.loadHTMLString(html, baseURL: ArticleRenderer.page.baseURL) } func fetchScrollInfo(_ completion: @escaping (ScrollInfo?) -> Void) { guard let webView = webView else { completion(nil) return } let javascriptString = "var x = {contentHeight: document.body.scrollHeight, offsetY: window.pageYOffset}; x" webView.evaluateJavaScript(javascriptString) { (info, error) in guard let info = info as? [String: Any] else { completion(nil) return } guard let contentHeight = info["contentHeight"] as? CGFloat, let offsetY = info["offsetY"] as? CGFloat else { completion(nil) return } let scrollInfo = ScrollInfo(contentHeight: contentHeight, viewHeight: webView.frame.height, offsetY: offsetY) completion(scrollInfo) } } func startArticleExtractor() { if let link = articles?.first?.preferredLink, let extractor = ArticleExtractor(link) { extractor.delegate = self extractor.process() articleExtractor = extractor articleExtractorButtonState = .animated } } func stopArticleExtractor() { articleExtractor?.cancel() articleExtractor = nil isShowingExtractedArticle = false articleExtractorButtonState = .off } func reloadArticleImage() { guard let article = articles?.first else { return } var components = URLComponents() components.scheme = ArticleRenderer.imageIconScheme components.path = article.articleID if let imageSrc = components.string { webView?.evaluateJavaScript("reloadArticleImage(\"\(imageSrc)\")") } } func stopMediaPlayback(_ webView: WKWebView) { webView.evaluateJavaScript("stopMediaPlayback();") } } // MARK: - ScrollInfo private struct ScrollInfo { let contentHeight: CGFloat let viewHeight: CGFloat let offsetY: CGFloat let canScrollDown: Bool let canScrollUp: Bool init(contentHeight: CGFloat, viewHeight: CGFloat, offsetY: CGFloat) { self.contentHeight = contentHeight self.viewHeight = viewHeight self.offsetY = offsetY self.canScrollDown = viewHeight + offsetY < contentHeight self.canScrollUp = offsetY > 0.1 } }
0
// Copyright © 2018 Stormbird PTE. LTD. import Foundation import Alamofire import PromiseKit import Result import SwiftyJSON class OpenSea { typealias PromiseResult = Promise<[AlphaWallet.Address: [OpenSeaNonFungible]]> //Assuming 1 token (token ID, rather than a token) is 4kb, 1500 HyperDragons is 6MB. So we rate limit requests private static let numberOfTokenIdsBeforeRateLimitingRequests = 25 private static let minimumSecondsBetweenRequests = TimeInterval(60) static let sharedInstance = OpenSea() private var recentWalletsWithManyTokens = [AlphaWallet.Address: (Date, PromiseResult)]() private var fetch = OpenSea.makeEmptyFulfilledPromise() private static func makeEmptyFulfilledPromise() -> PromiseResult { return Promise { $0.fulfill([:]) } } static func isServerSupported(_ server: RPCServer) -> Bool { switch server { case .main, .rinkeby: return true case .kovan, .ropsten, .poa, .sokol, .classic, .callisto, .custom, .goerli, .xDai: return false } } ///Call this after switching wallets, otherwise when the current promise is fulfilled, the switched to wallet will think the API results are for them func reset() { fetch = OpenSea.makeEmptyFulfilledPromise() } ///Uses a promise to make sure we don't fetch from OpenSea multiple times concurrently func makeFetchPromise(server: RPCServer, owner: AlphaWallet.Address) -> PromiseResult { guard OpenSea.isServerSupported(server) else { fetch = .value([:]) return fetch } trimCachedPromises() if let cachedPromise = cachedPromise(forOwner: owner) { return cachedPromise } if fetch.isResolved { fetch = Promise { seal in let offset = 0 fetchPage(forServer: server, owner: owner, offset: offset) { result in switch result { case .success(let result): seal.fulfill(result) case .failure(let error): seal.reject(error) } } } } return fetch } private func getBaseURLForOpensea(server: RPCServer) -> String { switch server { case .main: return Constants.openseaAPI case .rinkeby: return Constants.openseaRinkebyAPI default: return Constants.openseaAPI } } private func fetchPage(forServer server: RPCServer, owner: AlphaWallet.Address, offset: Int, sum: [AlphaWallet.Address: [OpenSeaNonFungible]] = [:], completion: @escaping (ResultResult<[AlphaWallet.Address: [OpenSeaNonFungible]], AnyError>.t) -> Void) { let baseURL = getBaseURLForOpensea(server: server) guard let url = URL(string: "\(baseURL)api/v1/assets/?owner=\(owner.eip55String)&order_by=current_price&order_direction=asc&limit=200&offset=\(offset)") else { completion(.failure(AnyError(OpenSeaError(localizedDescription: "Error calling \(baseURL) API \(Thread.isMainThread)")))) return } Alamofire.request( url, method: .get, headers: ["X-API-KEY": Constants.openseaAPIKEY] ).responseJSON { response in guard let data = response.data, let json = try? JSON(data: data) else { completion(.failure(AnyError(OpenSeaError(localizedDescription: "Error calling \(baseURL) API: \(String(describing: response.error))")))) return } DispatchQueue.global(qos: .userInitiated).async { var results = sum var currentPageCount = 0 for (_, each): (String, JSON) in json["assets"] { let tokenId = each["token_id"].stringValue let contractName = each["asset_contract"]["name"].stringValue let symbol = each["asset_contract"]["symbol"].stringValue let name = each["name"].stringValue let description = each["description"].stringValue let thumbnailUrl = each["image_thumbnail_url"].stringValue //We'll get what seems to be the PNG version first, falling back to the sometimes PNG, but sometimes SVG version var imageUrl = each["image_preview_url"].stringValue if imageUrl.isEmpty { imageUrl = each["image_url"].stringValue } let contractImageUrl = each["asset_contract"]["featured_image_url"].stringValue let externalLink = each["external_link"].stringValue let backgroundColor = each["background_color"].stringValue var traits = [OpenSeaNonFungibleTrait]() for each in each["traits"].arrayValue { let traitCount = each["trait_count"].intValue let traitType = each["trait_type"].stringValue let traitValue = each["value"].stringValue let trait = OpenSeaNonFungibleTrait(count: traitCount, type: traitType, value: traitValue) traits.append(trait) } if let contract = AlphaWallet.Address(string: each["asset_contract"]["address"].stringValue) { let cat = OpenSeaNonFungible(tokenId: tokenId, contractName: contractName, symbol: symbol, name: name, description: description, thumbnailUrl: thumbnailUrl, imageUrl: imageUrl, contractImageUrl: contractImageUrl, externalLink: externalLink, backgroundColor: backgroundColor, traits: traits) currentPageCount += 1 if var list = results[contract] { list.append(cat) results[contract] = list } else { let list = [cat] results[contract] = list } } } DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } if currentPageCount > 0 { strongSelf.fetchPage(forServer: server, owner: owner, offset: offset + currentPageCount, sum: results) { results in completion(results) } } else { var tokenIdCount = 0 for (_, tokenIds) in sum { tokenIdCount += tokenIds.count } strongSelf.cachePromise(withTokenIdCount: tokenIdCount, forOwner: owner) completion(.success(sum)) } } } } } private func cachePromise(withTokenIdCount tokenIdCount: Int, forOwner wallet: AlphaWallet.Address) { guard tokenIdCount >= OpenSea.numberOfTokenIdsBeforeRateLimitingRequests else { return } recentWalletsWithManyTokens[wallet] = (Date(), fetch) } private func cachedPromise(forOwner wallet: AlphaWallet.Address) -> PromiseResult? { guard let (_, promise) = recentWalletsWithManyTokens[wallet] else { return nil } return promise } private func trimCachedPromises() { let cachedWallets = recentWalletsWithManyTokens.keys let now = Date() for each in cachedWallets { guard let (date, _) = recentWalletsWithManyTokens[each] else { continue } if now.timeIntervalSince(date) >= OpenSea.minimumSecondsBetweenRequests { recentWalletsWithManyTokens.removeValue(forKey: each) } } } }
0
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { enum S { { } { } protocol C { class b { { { } } } { } let c : b } } protocol a { protocol e { { } typealias A : A } } let : a
0
// // ByteOperations.swift // reiner_ccid_via_dk_sample // // Created by Prakti_E on 03.06.15. // Copyright (c) 2015 Reiner SCT. All rights reserved. // import Foundation /// The C 'unsigned char' type. public typealias Byte = UInt8 /// The C 'unsigned char' type. public typealias byte = UInt8 //public class Range //{ // var startIndex:Int = 0 // var endIndex: Int = 0 // // init(start: Int, end: Int) // { // startIndex = start // endIndex = end // } //} public extension UInt { func toBool () ->Bool? { switch self { case 0: return true default: return false } } } extension Character { var integerValue:Int { let t = Int(String(self)) return t ?? 0 } var utf8Value: UInt8 { for s in String(self).utf8 { return s } return 0 } var utf16Value: UInt16 { for s in String(self).utf16 { return s } return 0 } var unicodeValue: UInt32 { for s in String(self).unicodeScalars { return s.value } return 0 } } public extension String { subscript (i: Int) -> Character { return self[self.characters.index(self.startIndex, offsetBy: i)] } subscript (i: Int) -> Int { return Int(self[self.characters.index(self.startIndex, offsetBy: i)].hashValue) } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { return substring(with: (characters.index(startIndex, offsetBy: r.lowerBound) ..< characters.index(startIndex, offsetBy: r.upperBound))) } subscript (r: CountableClosedRange<Int>) -> String { return substring(with: (characters.index(startIndex, offsetBy: r.lowerBound) ..< characters.index(startIndex, offsetBy: r.upperBound))) } var length: Int { return self.characters.count } func contains(_ compare :String, casesensitive: Bool) -> Bool { if(casesensitive) { if self.range(of: compare) != nil { return true } } if self.lowercased().range(of: compare.lowercased()) != nil { return true } return false } func contains(_ compare :String) -> Bool { return self.contains(compare, casesensitive: false) } func replace(_ string:String, replacement:String) -> String { return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil) } func removeWhitespace() -> String { return self.replace(" ", replacement: "") } static func fromCString (_ cString:[byte])-> String { let data = Data(cString) if let str = String(data: data , encoding: String.Encoding.utf8) { return str } return "" } } public extension Int { init?(_ string: String, radix: UInt) { let digits = "0123456789abcdef" var result = UInt(0) for digit in string.lowercased().characters { if let range = digits.range(of: String(digit)) { let val = UInt(digits.characters.distance(from: digits.startIndex, to: range.lowerBound)) if val >= radix { return nil } result = result * radix + val } else { return nil } } self = Int(result) } static func uInt32FromByteArray (_ bytes:[byte])-> UInt32 { var x: [UInt8] = [0x01, 0x02, 0x03, 0x04] var y: UInt32 = 0 y += UInt32(x[3]) << 0o30 y += UInt32(x[2]) << 0o20 y += UInt32(x[1]) << 0o10 y += UInt32(x[0]) << 0o00 return y } } public func nsDataToByteArray(_ data : Data ) -> [byte] { var array = [UInt8](repeating: 0x00, count: data.count) for i:Int in 0 ..< data.count { array.append( UInt8(data[i]) ) } return array } public func getStringFromASCIIBytes(_ bytes:[byte], maxLength:Int) -> String { //let r = bytes as [UInt8] //let (int8s: Int8...) = r // int8s == [Int8] let uint8s = bytes.map { UInt8($0) } let ret:String = String(bytes: uint8s, encoding: String.Encoding.ascii)! return ret // var swiftString = String() // var workingCharacter:UnicodeScalar = UnicodeScalar(bytes[0]) // var count:Int = 0 // // for wc in bytes // { // workingCharacter = UnicodeScalar(wc) // swiftString.append(workingCharacter) // } // // while swiftString.length != count - 1 { // workingCharacter = UnicodeScalar(bytes[count]) // swiftString.append(workingCharacter) // count++ // // if count > maxLength // { // return swiftString // } // } // return swiftString } public func SplitArray<T>(_ array: [T], range: Range<Int>) -> [T] { var returnVal: [T] = [] let start:Int = range.lowerBound let end:Int = range.upperBound for index in start ..< end { returnVal.append(array[index]) } return returnVal } func getBitsFromByte(_ data: byte) -> [Bool] { var ret: [Bool] = [false,false,false,false,false,false,false,false] for x in 0 ..< 8 { ret[x] = UInt(data<<1).toBool()! } return ret } func strToChar ( _ str: String) -> byte { return byte(Int(str, radix: 16)!) } func hexStringToByteArray(_ value: String) -> [Byte] { var value = value value = value.removeWhitespace() if (value.length % 2 != 0){ return [byte]() } var bytes = [byte]() for char in value.utf8{ bytes += [char] } //var bytes: [byte] = value.cStringUsingEncoding( NSUTF8StringEncoding) let length: Int = bytes.count var ret:[byte] = [] for x in (0..<length) where x % 2 == 0 { let slice:[byte] = Array(bytes[x...x+1]) let temp = String.fromCString( slice ) ret.append(strToChar(temp)) } return ret } func byteArrayToHexString(_ bytes:[byte]) -> String { let hexString = NSMutableString() for byte in bytes { hexString.appendFormat("%02x", UInt8(byte)) hexString.append(" ") } return hexString as String } func byteArrayToInt(_ x:[byte]) ->UInt { var y: UInt32 = 0 y += UInt32(x[3]) << 0o30 y += UInt32(x[2]) << 0o20 y += UInt32(x[1]) << 0o10 y += UInt32(x[0]) << 0o00 return UInt(y) } func IntToByteArray(_ value: Int) -> [UInt8] { let count = 4 let Ints: [Int] = [value] let data = Data(bytes: Ints , count: count) var result = [UInt8](repeating: 0, count: count) (data as NSData).getBytes(&result, length: count) return result } func reverseByteArray(_ array: [byte])-> [byte] { var array = array var end = array.count-1 for i in 0..<end { let aux = array[i] array[i] = array[end] array[end] = aux end -= 1 } return array; } func IntToHEXString(_ value: Int, padding: Int, littleEndian: Bool) -> String { var ret = NSMutableString() ret .appendFormat( String(value, radix: 16, uppercase: false) as NSString) let littlePadding = NSMutableString() var x = 0 if(value < 16 && padding > 2) { ret = NSMutableString() ret.appendFormat("0") ret.appendFormat( String(value, radix: 16, uppercase: false) as NSString) } while ( padding != ret.length) { if(littleEndian) { ret.append("0") x = (ret as String).characters.count + 1 if(x == padding){ break } } else { littlePadding.append("0") x = (littlePadding as String).characters.count + 1 if(x == padding){ break } } } if(!littleEndian) { let temp = (littlePadding as String) + (ret as String) return temp } return ret as String; }
0
// // Ingredient.swift // FoodCourt // // Created by Максим Бойчук on 03.05.2020. // Copyright © 2020 Maksim Boichuk. All rights reserved. // import Foundation public struct Ingredient { private let name: String private let amount: Int private let measure: String init(name: String, amount: Int, measure: String) { self.name = name self.amount = amount self.measure = measure } func getName() -> String { return name } func getAmount() -> Int { return amount } func getMeasure() -> String { return measure } }
0
// // AppDelegate.swift // NiceDemo // // Created by Serhii Kharauzov on 3/4/18. // Copyright © 2018 Serhii Kharauzov. All rights reserved. // import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: Properties var window: UIWindow? var appDelegateService: AppDelegateService! // MARK: UIApplication Delegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let window = UIWindow(frame: UIScreen.main.bounds) appDelegateService = AppDelegateService(window: window) appDelegateService.setupAppCoordinator() self.window = window return true } }
0
// // GribCoordinate.swift // gribParserTest // // Created by Bo Gustafsson on 2018-12-30. // Copyright © 2018 Bo Gustafsson. All rights reserved. // import Foundation struct GribCoordinate { var lat = 0.0 var lon = 0.0 var latRot = 0.0 var lonRot = 0.0 var i = 0 var j = 0 init(i: Int, j: Int, lon: Double, lat: Double, longitudeOfFirstGridPointInDegrees lon0: Double, latitudeOfFirstGridPointInDegrees lat0: Double, iDirectionIncrementInDegrees deltaLon: Double, jDirectionIncrementInDegrees deltaLat: Double) { self.i = i self.j = j self.lon = lon self.lat = lat self.lonRot = lon0 + deltaLon * Double(i) self.latRot = lat0 + deltaLat * Double(j) } init(lon: Double, lat: Double, geography: GribGeographyData ) { if geography.rotated { let zrad = Double.pi / 180.0 let zradi = 1.0 / zrad let zsycen = sin(zrad * (geography.latitudeOfSouthernPoleInDegrees + 90.0)) let zcycen = cos(zrad * (geography.latitudeOfSouthernPoleInDegrees + 90.0)) let zxmxc = zrad * (lon - geography.longitudeOfSouthernPoleInDegrees) let zsxmxc = sin(zxmxc) let zcxmxc = cos(zxmxc) let zsyreg = sin(zrad * lat) let zcyreg = cos(zrad * lat) var zsyrot = zcycen * zsyreg - zsycen * zcyreg * zcxmxc zsyrot = max(zsyrot, -1.0) zsyrot = min(zsyrot, 1.0) let latRot = asin(zsyrot) * zradi let zcyrot = cos(latRot*zrad) var zcxrot = (zcycen * zcyreg * zcxmxc + zsycen * zsyreg) / zcyrot zcxrot = max(zcxrot, -1.0) zcxrot = min(zcxrot, 1.0) let zsxrot = zcyreg * zsxmxc / zcyrot var lonRot = acos(zcxrot) * zradi if zsxrot < 0.0 {lonRot = -lonRot} self.latRot = latRot self.lonRot = lonRot } else { self.latRot = lat self.lonRot = lon } self.lat = lat self.lon = lon self.i = Int((lonRot - geography.longitudeOfFirstGridPointInDegrees) / geography.iDirectionIncrementInDegrees) self.j = Int((latRot - geography.latitudeOfFirstGridPointInDegrees) / geography.jDirectionIncrementInDegrees) } init(lonRot: Double, latRot: Double, geography: GribGeographyData ) { if geography.rotated { let zrad = Double.pi / 180.0 let zradi = 1.0 / zrad let zsycen = sin(zrad*(geography.latitudeOfSouthernPoleInDegrees+90.0)) let zcycen = cos(zrad*(geography.latitudeOfSouthernPoleInDegrees+90.0)) let zsxrot = sin(zrad*lonRot) let zcxrot = cos(zrad*lonRot) let zsyrot = sin(zrad*latRot) let zcyrot = cos(zrad*latRot) var zsyreg = zcycen*zsyrot + zsycen*zcyrot*zcxrot zsyreg = max(zsyreg,-1.0) zsyreg = min(zsyreg,+1.0) let lat = asin(zsyreg)*zradi let zcyreg = cos(lat*zrad) var zcxmxc = (zcycen*zcyrot*zcxrot - zsycen*zsyrot)/zcyreg zcxmxc = max(zcxmxc,-1.0) zcxmxc = min(zcxmxc,+1.0) let zsxmxc = zcyrot*zsxrot/zcyreg var zxmxc = acos(zcxmxc)*zradi if zsxmxc < 0.0 {zxmxc = -zxmxc} let lon = zxmxc + geography.longitudeOfSouthernPoleInDegrees self.lat = lat self.lon = lon } else { self.lat = latRot self.lon = lonRot } self.latRot = latRot self.lonRot = lonRot self.i = Int((lonRot - geography.longitudeOfFirstGridPointInDegrees) / geography.iDirectionIncrementInDegrees) self.j = Int((latRot - geography.latitudeOfFirstGridPointInDegrees) / geography.jDirectionIncrementInDegrees) } } extension GribCoordinate: Comparable, Equatable { static func < (lhs: GribCoordinate, rhs: GribCoordinate) -> Bool { if lhs.j < rhs.j {return true} if lhs.j == rhs.j && lhs.i < rhs.i {return true} return false } }
0
// // UserRequestTests.swift // SwiftYNABTests // // Created by Andre Bocchini on 5/4/19. // Copyright © 2019 Andre Bocchini. All rights reserved. // import XCTest @testable import SwiftYNAB class UserRequestTests: XCTestCase { func testUserRequest() { let request = UserRequest() XCTAssertEqual(request.path, "/v1/user") XCTAssertEqual(request.method, .get) XCTAssertNil(request.query) XCTAssertNil(request.body) } }
0
// // MatchCard.swift // MatchMatch // // Created by Park, Chanick on 5/23/17. // Copyright © 2017 Chanick Park. All rights reserved. // import Foundation import UIKit import SwiftyJSON /** @desc Card Data Model Class */ class MatchCard : NSObject { var id: String = "" var title: String = "" var placeHolderURL: String = "" var frontImageURL: String = "" // MARK: - Init /** @desc Init Movie data with id and name */ init(_ id: String, _ title: String) { self.id = id self.title = title } /** @desc Init Movie data with SwiftyJON */ init(with json: JSON) { self.id = json["id"].string ?? "" self.title = json["title"].string ?? "" self.frontImageURL = json["url_n"].string ?? "" } }
0
// AppDelegate.swift // FirstDraftPrime // // Created by David Casseres on 2/24/18. // Copyright © 2018 David Casseres. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
0
// // DragDropCollectionViewCell.swift // DragDropCollection // // Created by Hari Kunwar on 2/3/17. // Copyright © 2017 Learning. All rights reserved. // import UIKit protocol DragDropCollectionViewCellDelegate: class { func willBeginDragging(cell: DragDropCollectionViewCell) func didEndDragging(cell: DragDropCollectionViewCell) func didDrag(cell: DragDropCollectionViewCell, to center: CGPoint) func delete(cell: DragDropCollectionViewCell) } class DragDropCollectionViewCell: UICollectionViewCell { fileprivate let vibrateAnimationKey = "vibrate" fileprivate var initialCenter: CGPoint? fileprivate var gestureDistanceFromCenter: CGSize? weak var delegate: DragDropCollectionViewCellDelegate? private var closeButton = UIButton(type: UIButtonType.custom) private let deleteWidth: CGFloat = 20 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func didMoveToWindow() { super.didMoveToWindow() // Setup close button self.addSubview(closeButton) closeButton.addTarget(self, action: #selector(deleteButtonPressed), for: .touchUpInside) closeButton.setImage(UIImage(named: "close"), for: .normal) closeButton.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5) closeButton.imageView?.contentMode = .scaleAspectFit closeButton.clipsToBounds = true let longPress = UILongPressGestureRecognizer(target: self, action: #selector(dragging(gesture:))) addGestureRecognizer(longPress) longPress.delegate = self let panning = UIPanGestureRecognizer(target: self, action: #selector(dragging(gesture:))) addGestureRecognizer(panning) panning.delegate = self } override func layoutSubviews() { super.layoutSubviews() let deleteOffset = deleteWidth/2 contentView.frame = CGRect(x: deleteOffset, y: deleteOffset, width: bounds.width - deleteOffset, height: bounds.height - deleteOffset) } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let point = closeButton.convert(point, from: self) if closeButton.bounds.contains(point) { return closeButton } return super.hitTest(point, with: event) } var isEditing: Bool = false { didSet { vibrate(isEditing) showDelete(isEditing) } } fileprivate func vibrate(_ start: Bool) { if start { let isVibrating = layer.animation(forKey: vibrateAnimationKey) != nil if !isVibrating { // Vibrate let angle = Float.pi/72 // 2.5 degree let vibrate = CABasicAnimation(keyPath: "transform.rotation") vibrate.beginTime = CACurrentMediaTime() vibrate.duration = 0.15 vibrate.fromValue = -angle vibrate.toValue = angle vibrate.autoreverses = true vibrate.repeatCount = .infinity layer.add(vibrate, forKey: vibrateAnimationKey) } } else { layer.removeAnimation(forKey: vibrateAnimationKey) } } fileprivate func showDelete(_ show: Bool) { self.bringSubview(toFront: closeButton) let width = deleteWidth let frame = show ? CGRect(x: 0, y: 0, width: width, height: width) : CGRect.zero closeButton.frame = frame // Add blurEffect let blurEffect = UIBlurEffect(style: .prominent) let blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = frame blurView.clipsToBounds = true closeButton.insertSubview(blurView, at: 0) // Fix close image hidding behide blurView if let imageView = closeButton.imageView { closeButton.bringSubview(toFront: imageView) } blurView.layer.cornerRadius = width/2 closeButton.layer.cornerRadius = width/2 } func deleteButtonPressed() { print("Delete pressed.") delegate?.delete(cell: self) } } extension DragDropCollectionViewCell: UIGestureRecognizerDelegate { override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { var shouldBegin = true if let _ = gestureRecognizer as? UIPanGestureRecognizer { shouldBegin = isEditing } return shouldBegin } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } func dragging(gesture: UIGestureRecognizer) { if gesture.state == .began { guard let view = gesture.view else { return } // Show delete button showDelete(true) delegate?.willBeginDragging(cell: self) // Stop vibrating vibrate(false) let gesturePosition = gesture.location(in: view.superview) let distanceFromCenterX = view.center.x - gesturePosition.x let distanceFromCenterY = view.center.y - gesturePosition.y // gestureDistanceFromCenter = CGSize(width: distanceFromCenterX, height: distanceFromCenterY) } else if gesture.state == .changed { guard let distanceFromCenter = gestureDistanceFromCenter else { return } guard let view = gesture.view else { return } let point = gesture.location(in: view.superview) // Calculate new center position let centerX = point.x + distanceFromCenter.width; let centerY = point.y + distanceFromCenter.height; let newCenter = CGPoint(x: centerX, y: centerY) // Notify delegate delegate?.didDrag(cell: self, to: newCenter) } else if gesture.state == .ended { delegate?.didEndDragging(cell: self) // Start vibrating vibrate(true) } } }
1
// RUN: not %target-swift-frontend %s -typecheck } var d{let a= { class A{ struct a {a{ c{ " var d ={ classA{ } {" protocol A{ let a= {" }struct Q { class d{ protocol A{ struct A{class Ba{let i{ (ed =a
0
// // FIT3178_Assignment4_V2Tests.swift // FIT3178_Assignment4_V2Tests // // Created by Yushu Guo on 4/6/20. // Copyright © 2020 Monash University. All rights reserved. // import XCTest @testable import FIT3178_Assignment4_V2 class FIT3178_Assignment4_V2Tests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
0
// // ViewController.swift // accelerometron // // Created by Yasinkbas on 12/17/18. // Copyright © 2018 Yasin. All rights reserved. // import UIKit class ListTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return images.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "parallaxCell", for: indexPath) as? ParallaxCell else{ return UITableViewCell() } cell.configureCell(withImage: images[indexPath.row] ?? UIImage(named: "1"), andDescription: names[indexPath.row]) return cell } }
0
// // MyPagePostTableViewHeader.swift // VegeXI // // Created by Doyoung Song on 8/14/20. // Copyright © 2020 TeamSloth. All rights reserved. // import UIKit class MyPagePostTableViewHeader: UIView { // MARK: - Properties let leftLabel = UILabel().then { $0.text = "글 3" $0.font = UIFont.spoqaHanSansRegular(ofSize: 14) $0.textColor = .vegeTextBlackColor } private lazy var rightStackView = UIStackView(arrangedSubviews: [rightLabel, rightImageView]).then { $0.alignment = .center $0.axis = .horizontal $0.distribution = .fillProportionally $0.spacing = 0 } let rightLabel = UILabel().then { $0.text = "전체" $0.font = UIFont.spoqaHanSansRegular(ofSize: 13) $0.textColor = .vegeTextBlackColor } private let rightImageView = UIImageView().then { $0.clipsToBounds = true let image = UIImage(named: "Arrow_Down") $0.image = image } private var filterActionHandler: () -> Void = { return } // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .white configureUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UI private func configureUI() { setPropertyAttributes() setConstraints() } private func setPropertyAttributes() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:))) rightStackView.addGestureRecognizer(tapGesture) rightStackView.isUserInteractionEnabled = true } private func setConstraints() { [leftLabel, rightStackView].forEach { self.addSubview($0) } leftLabel.snp.makeConstraints { $0.leading.equalToSuperview() $0.centerY.equalToSuperview() } rightStackView.snp.makeConstraints { $0.trailing.equalToSuperview() $0.centerY.equalToSuperview() } rightImageView.snp.makeConstraints { $0.width.equalTo(18) } } // MARK: - Helpers func configureHeader(numberOfPosts: Int, filterActionHandler: @escaping () -> Void) { leftLabel.text = "글 " + String(numberOfPosts) self.filterActionHandler = filterActionHandler } // MARK: - Selectors @objc private func handleTapGesture(_ sender: UITapGestureRecognizer) { filterActionHandler() } }
0
// // CoffeeViewController.swift // FourSquare // // Created by Duy Linh on 5/2/17. // Copyright © 2017 Duy Linh. All rights reserved. // import UIKit class CoffeeViewController: MenuItemViewController { override var section: SectionQuery { return .Coffee } override func viewDidLoad() { super.viewDidLoad() loadVenue() } override func setupUI() { super.setupUI() } }
0
// // SimpleExample.swift // SwiftCombineExamples // // Created by Eidinger, Marco on 3/8/21. // import Foundation import SwiftUI class SimpleExampleModel: ObservableObject { static var randomName: String { "Mike \(["Palmers", "Chamers", "Balmers"].randomElement()!)" } @Published var date: String var name: String = "Hello" init() { self.date = Date().description } func startTimers() { // update name every 2 seconds _ = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(self.updateName), userInfo: nil, repeats: true) // call objectWillChange.send() every 5 seconds _ = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.updateObject), userInfo: nil, repeats: true) // update @Published date every 10 seconds _ = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.updateDate), userInfo: nil, repeats: true) } @objc func updateDate() { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .long dateFormatter.locale = Locale.current self.date = dateFormatter.string(from: Date()) print("date updated") } @objc func updateName() { name = SimpleExampleModel.randomName print("name updated") } @objc func updateObject() { self.objectWillChange.send() print("object updated") } } struct SimpleExampleContentView: View { @ObservedObject var model = SimpleExampleModel() var body: some View { VStack { ExpHeaderView("ObservableObject", subtitle: "State Handling", desc: "View gets re-calcuated when objectWillChange.send was called explicitly OR when @Published properties were updated.", back: .green, textColor: .white) Text("Name: \(model.name)") .padding() Text("Date: \(model.date)") .padding() }.onAppear(perform: { model.startTimers() }) } } struct SimpleExampleContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
0
// Created by Sinisa Drpa on 11/16/17. import Foundation import Kitura import KituraCache import KituraCORS import KituraNet import KituraWebSocket import SwiftyJSON struct Config { static let storeAddress = "17206648368948385036L" } public final class Server { private let socketService = SocketService() private let metronome = Metronome() private let lisk = Lisk() // Store [senderId: Order] private let store = KituraCache(defaultTTL: 0, checkFrequency: 600) public init() { // Set self as SocketServiceDelegate to be able to receive new order events self.socketService.delegate = self // Since there is no way to receive transaction completed event from a node, // we use Lisk API to get transactions for store wallet self.metronome.tick = { [unowned self] in do { // On metronome tick, loop through the pending orders and check whether transaction // for a pending order has been completed (whether a user has paid the order). // If the transaction for a pending order has been completed, update the store // (mark the order as completed). guard let keys = self.store.keys() as? [String] else { return } for senderId in keys { guard let order = self.store.object(forKey: senderId) as? Order, // Process only pending orders order.status == .pending else { continue } // Prevent reusing previous transaction let prevTransactionIds = self.allOrders.map { $0.transactionId } //print(prevTransactionIds) if prevTransactionIds.contains(where: { order.transactionId != nil && $0 == order.transactionId }) { continue } print("Verify transaction for order, sender: \(order.senderId), item: \(order.item)") // Use Lisk API to get the store wallet transactions where // the senderId is equal to the pending order senderId let txs = try self.lisk.transactions(senderId: order.senderId, recipientId: Config.storeAddress) // We use the most recent transaction guard let tx = txs.last else { continue } // Save the order to store, but this time set the status as completed // We should check if the amount paid is equal to the item price, // Skipped here to avoid complexity, basically we should get // the item price from a database and compare to tx amount let anOrder = Order(transactionId: tx.id, senderId: senderId, item: order.item, status: .completed) self.store.setObject(anOrder, forKey: anOrder.senderId) print("Order completed, sender: \(order.senderId), item: \(order.item)") // Broadcast the message let message = OrderResult(senderid: anOrder.senderId, status: OrderStatus.completed.rawValue) self.socketService.broadcast(data: try JSONEncoder().encode(message)) } } catch let e { print(e.localizedDescription) } } } public func run() { var cors: CORS { let options = Options(allowedOrigin: .all, maxAge: 5) return CORS(options: options) } let router = Router() router.all("/", middleware: cors) WebSocket.register(service: socketService, onPath: "/payment") let server = HTTP.createServer() server.delegate = router let port = Int(8182) do { try server.listen(on: port) ListenerGroup.waitForListeners() } catch { print("Could not listen on port \(port): \(error)") } } } extension Server: SocketServiceDelegate { func socketServiceDidReceive(order: Order) { // The received order is saved to store store.setObject(order, forKey: order.senderId) } } extension Server { var allOrders: [Order] { guard let keys = store.keys() as? [String] else { return [] } var orders: [Order] = [] for senderId in keys { guard let order = store.object(forKey: senderId) as? Order else { continue } orders.append(order) } return orders } }
0
// // BooksViewController.swift // SlideMenu // // Created by Saketh Manemala on 28/06/17. // Copyright © 2017 Saketh. All rights reserved. // import UIKit class BooksViewController: UIViewController { @IBOutlet weak var navBar: UINavigationItem! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.isHidden = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backButtonClicked(_ sender: UIBarButtonItem) { _ = self.navigationController?.popViewController(animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
0
// // CircleIconView.swift // CircleMenuDemo // // Created by Shoaib Ahmed on 11/26/16. // Copyright © 2016 Kindows Tech Solutions. All rights reserved. // import UIKit class CircleIconView: UIView { public var image: UIImage? public var highlightedIconColor = UIColor.green public var isSelected: Bool { didSet { if oldValue != isSelected { self.setNeedsDisplay() } } } override init(frame: CGRect) { isSelected = false super.init(frame: frame) isOpaque = false backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) guard image != nil else { return } if isSelected { let context = UIGraphicsGetCurrentContext() context!.translateBy(x: 0, y: image!.size.height) context!.scaleBy(x: 1.0, y: -1.0) context!.setBlendMode(CGBlendMode.color) context!.clip(to: self.bounds, mask: image!.cgImage!) // this restricts drawing to within alpha channel context!.setFillColor(self.highlightedIconColor.cgColor) // this is your color, a light reddish tint context!.fill(rect) } else { image?.draw(in: rect) } } }
0
import Dispatch import Result import Nimble import Quick @testable import ReactiveSwift class UnidirectionalBindingSpec: QuickSpec { override func spec() { describe("BindingTarget") { var token: Lifetime.Token! var lifetime: Lifetime! var target: BindingTarget<Int>! var optionalTarget: BindingTarget<Int?>! var value: Int? beforeEach { token = Lifetime.Token() lifetime = Lifetime(token) target = BindingTarget(lifetime: lifetime, setter: { value = $0 }) optionalTarget = BindingTarget(lifetime: lifetime, setter: { value = $0 }) value = nil } describe("non-optional target") { it("should pass through the lifetime") { expect(target.lifetime).to(beIdenticalTo(lifetime)) } it("should stay bound after deallocation") { weak var weakTarget = target let property = MutableProperty(1) target <~ property expect(value) == 1 target = nil property.value = 2 expect(value) == 2 expect(weakTarget).to(beNil()) } it("should trigger the supplied setter") { expect(value).to(beNil()) target.consume(1) expect(value) == 1 } it("should accept bindings from properties") { expect(value).to(beNil()) let property = MutableProperty(1) target <~ property expect(value) == 1 property.value = 2 expect(value) == 2 } } describe("optional target") { it("should pass through the lifetime") { expect(optionalTarget.lifetime).to(beIdenticalTo(lifetime)) } it("should stay bound after deallocation") { weak var weakTarget = optionalTarget let property = MutableProperty(1) optionalTarget <~ property expect(value) == 1 optionalTarget = nil property.value = 2 expect(value) == 2 expect(weakTarget).to(beNil()) } it("should trigger the supplied setter") { expect(value).to(beNil()) optionalTarget.consume(1) expect(value) == 1 } it("should accept bindings from properties") { expect(value).to(beNil()) let property = MutableProperty(1) optionalTarget <~ property expect(value) == 1 property.value = 2 expect(value) == 2 } } it("should not deadlock on the same queue") { target = BindingTarget(on: UIScheduler(), lifetime: lifetime, setter: { value = $0 }) let property = MutableProperty(1) target <~ property expect(value) == 1 } it("should not deadlock on the main thread even if the context was switched to a different queue") { let queue = DispatchQueue(label: #file) target = BindingTarget(on: UIScheduler(), lifetime: lifetime, setter: { value = $0 }) let property = MutableProperty(1) queue.sync { _ = target <~ property } expect(value).toEventually(equal(1)) } it("should not deadlock even if the value is originated from the same queue indirectly") { let key = DispatchSpecificKey<Void>() DispatchQueue.main.setSpecific(key: key, value: ()) let mainQueueCounter = Atomic(0) let setter: (Int) -> Void = { value = $0 mainQueueCounter.modify { $0 += DispatchQueue.getSpecific(key: key) != nil ? 1 : 0 } } target = BindingTarget(on: UIScheduler(), lifetime: lifetime, setter: setter) let scheduler: QueueScheduler if #available(OSX 10.10, *) { scheduler = QueueScheduler() } else { scheduler = QueueScheduler(queue: DispatchQueue(label: "com.reactivecocoa.ReactiveSwift.UnidirectionalBindingSpec")) } let property = MutableProperty(1) target <~ property.producer .start(on: scheduler) .observe(on: scheduler) expect(value).toEventually(equal(1)) expect(mainQueueCounter.value).toEventually(equal(1)) property.value = 2 expect(value).toEventually(equal(2)) expect(mainQueueCounter.value).toEventually(equal(2)) } } } }
0
/* Copyright (c) <2020> 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 SwiftUI struct ConditionalOverlay<A: Any, V: View> : ViewModifier { @Binding var item : A? var view : V var alignment : Alignment @ViewBuilder func body(content: Content) -> some View { if item != nil { content.overlay(view, alignment: alignment) } else { content } } } extension View { public func overlay<A: Any,V: View>(_ item: Binding<A?>, _ view: V, alignment: Alignment = .center) -> some View { return self.modifier(ConditionalOverlay<A, V>(item: item, view: view, alignment: alignment)) } } #if DEBUG struct BindalbeOverlay_Previews: PreviewProvider { @State static var hidden : Bool? = true static var previews: some View { Group{ Rectangle().foregroundColor(.gray) .overlay($hidden, Text("Hej Hej").overlayStyle("Goddåg")) } } } #endif
0
// // MoviesCell.swift // KLM_t // // Created by Pavle Mijatovic on 27.5.21.. // import UIKit class MoviesCell: UICollectionViewCell { // MARK: - API static let id = "MoviesCell" var vm: MovieVM? { willSet { updateUI(vm: newValue) } } // MARK: - Properties @IBOutlet weak var ratingImageView: UIImageView! @IBOutlet weak var moviePosterImgView: MovieImageView! @IBOutlet weak var ratingLbl: UILabel! @IBOutlet weak var containerView: UIView! @IBOutlet weak var movieNameLbl: UILabel! @IBOutlet weak var movieNameWidth: NSLayoutConstraint! @IBOutlet weak var moviePosterWidth: NSLayoutConstraint! @IBOutlet weak var moviePosterHeight: NSLayoutConstraint! // MARK: - Overrides override func prepareForReuse() { super.prepareForReuse() moviePosterImgView.cancelImageDownload() } // MARK: - Helper private func updateUI(vm: MovieVM?) { guard let vm = vm else { return } // text and images movieNameLbl.text = vm.title ratingLbl.text = vm.rating moviePosterImgView.image = vm.placeHolderImage ratingImageView.image = vm.ratingImage moviePosterImgView.vm = MovieImageVM(imageUrlString: vm.posterUrl) // colors movieNameLbl.textColor = vm.movieTxtColor ratingLbl.textColor = vm.ratingTxtColor contentView.backgroundColor = vm.backgroundColor containerView.backgroundColor = vm.containerBackgroundColor // fonts movieNameLbl.font = vm.movieTitleLblFont ratingLbl.font = vm.ratingLblFont // UX movieNameLbl.numberOfLines = vm.maxNumberOfLines movieNameWidth.constant = frame.width - vm.movieTitlePaddingBothSides moviePosterHeight.constant = frame.height - vm.posterPaddingDown moviePosterWidth.constant = frame.width - vm.posterPaddingBothSides containerView.layer.cornerRadius = vm.cornerRadius } }
0
import Foundation final class MCreateSaveRender { let zoom:Double var slices:[MCreateSaveRenderSlice] init( zoom:Double, slices:[MCreateSaveRenderSlice]) { self.zoom = zoom self.slices = slices } }
0
// // AlbumDetailViewController.swift // AlbumTracker // // Created by Zachary Long on 6/7/20. // Copyright © 2020 Zachary Long. All rights reserved. // import UIKit import os.log class AlbumDetailViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { //MARK: Properties @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var artistTextField: UITextField! @IBOutlet weak var yearTextField: UITextField! @IBOutlet weak var recordLabelTextField: UITextField! @IBOutlet weak var trackListTextField: UITextView! /* This value is either passed by `MealTableViewController` in `prepare(for:sender:)` or constructed as part of adding a new meal(album). */ var album: Album? override func viewDidLoad() { super.viewDidLoad() //Handle the text field's user input through delegate callbacks nameTextField.delegate = self //Set up views if editing an existing album if let album = album { navigationItem.title = album.name + ", " + album.artist nameTextField.text = album.name photoImageView.image = album.photo //rest of the data here artistTextField.text = album.artist yearTextField.text = album.year recordLabelTextField.text = album.recordLabel trackListTextField.text = album.trackList } //Placeholder text for the UITextView if trackListTextField.text.isEmpty { trackListTextField.text = "Enter Track Listing" trackListTextField.textColor = UIColor.lightGray } //Enable the save button only if the text field has a valid name updateSaveButtonState() } //MARK: UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { //Hide the keyboard textField.resignFirstResponder() return true } func textFieldDidEndEditing(_ textField: UITextField) { updateSaveButtonState() navigationItem.title = textField.text } func textFieldDidBeginEditing(_ textField: UITextField) { //Disable the save button while editing saveButton.isEnabled = false } //MARK: UIImagePickerControllerDelegate func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { //Dismiss the picker if the user cancelled dismiss(animated: true, completion: nil) } //imagePicker from the apple tutorial //Original method with the red fix button //private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { //Change from String to UIImagePickerController.InfoKEy seems to fix it func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { //the info may include multiple references /* guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage else { fatalError("Expected a dictionary containing an image, but was provided the following: \(info)") } */ //Original tutorial version //let selectedImage = info[UIImagePickerController.InfoKey.originalImage.rawValue] as? UIImage //Fix with changing String to InfoKey so don't need raw value any more let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage //set photoImageView to display the selected image photoImageView.image = selectedImage //Dismiss the picker dismiss(animated: true, completion: nil) } //MARK: Navigation @IBAction func cancel(_ sender: UIBarButtonItem) { //Depending on the style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways let isPresentingInAddAlbumMode = presentingViewController is UINavigationController if isPresentingInAddAlbumMode { dismiss(animated: true, completion: nil) } else if let owningNavigationController = navigationController { owningNavigationController.popViewController(animated: true) } else { fatalError("The AlbumViewController is not inside a navigation controller.") } //dismiss(animated: true, completion: nil) } //This method configures the view controller before it's presented override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) // Configure the destination view controller only when the save button is pressed. guard let button = sender as? UIBarButtonItem, button === saveButton else { os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug) return } let name = nameTextField.text ?? "" let photo = photoImageView.image let artist = artistTextField.text ?? "" let year = yearTextField.text ?? "" let recordLabel = recordLabelTextField.text ?? "" let trackList = trackListTextField.text ?? "" //Set the album object to be passed to AlbumTableViewController after the unwind segue album = Album(name: name, artist: artist, year: year, recordLabel: recordLabel, photo: photo, trackList: trackList) } //MARK: Actions @IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) { // Hide the keyboard. nameTextField.resignFirstResponder() // UIImagePickerController is a view controller that lets a user pick media from their photo library. let imagePickerController = UIImagePickerController() // Only allow photos to be picked, not taken. imagePickerController.sourceType = .photoLibrary // Make sure ViewController is notified when the user picks an image. imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } //MARK: Private Methods private func updateSaveButtonState() { //Disable the save button if the text field is empty let text = nameTextField.text ?? "" saveButton.isEnabled = !text.isEmpty } //Helper function to make a placeholder for the UITextView //https://stackoverflow.com/questions/27652227/how-can-i-add-placeholder-text-inside-of-a-uitextview-in-swift func textViewDidBeginEditing(_ textView: UITextView) { if trackListTextField.textColor == UIColor.lightGray { trackListTextField.text = nil trackListTextField.textColor = UIColor.black } } func textViewDidEndEditing(_ textView: UITextView) { if trackListTextField.text.isEmpty { trackListTextField.text = "Enter Track Listing" trackListTextField.textColor = UIColor.lightGray } } }
0
// // ImageReply.swift // Aimybox // // Created by Vladyslav Popovych on 07.12.2019. // import Foundation /** Represents a reply with image content, which should be displayed in the UI. */ public protocol ImageReply: Reply { /** URL to the image or GIF. */ var url: URL { get } }
0
// // Gate+SimulatorGate.swift // SwiftQuantumComputing // // Created by Enrique de la Torre on 15/11/2020. // Copyright © 2020 Enrique de la Torre. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation // MARK: - SimulatorGate methods extension Gate: SimulatorGate {} // MARK: - SimulatorRawGate methods extension Gate: SimulatorRawGate { var rawGate: Gate { return self } } // MARK: - SimulatorComponents methods extension Gate: SimulatorComponents { func extractRawInputs() -> [Int] { return gate.extractRawInputs() } func extractMatrix() -> Result<SimulatorGateMatrix, GateError> { return gate.extractMatrix() } }
0
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Get", platforms: [.iOS(.v13), .macCatalyst(.v13), .macOS(.v10_15), .watchOS(.v6), .tvOS(.v13)], products: [ .library(name: "Get", targets: ["Get"]) ], targets: [ .target(name: "Get"), .testTarget(name: "GetTests", dependencies: ["Get"], resources: [.process("Resources")]) ] )
0
// // SyncEngine.swift // Shopping // // Created by Aaron Bratcher on 3/22/15. // Copyright (c) 2015 Aaron Bratcher. All rights reserved. // import Foundation import ALBNoSQLDB import ALBPeerConnection let kSyncComplete = "SyncComplete" let kDevicesTable = "Devices" let kMonthlySummaryEntriesTable = "SummaryEntries" typealias DeviceResponse = (_ allow: Bool) -> () protocol SyncEngineLinkDelegate { func linkRequested(_ device: SyncDevice, deviceResponse: @escaping DeviceResponse) func linkDenied(_ device: SyncDevice) } protocol SyncEngineDelegate { func statusChanged(_ device: SyncDevice) func syncDeviceFound(_ device: SyncDevice) func syncDeviceLost(_ device: SyncDevice) } enum SyncDeviceStatus { case idle, linking, unlinking, syncing } enum DataType: Int { case syncLogRequest = 1 case syncError = 2 case unlink = 3 } final class SyncDevice: DBObject { static var table: DBTable = DBTable(name: kDevicesTable) var key = UUID().uuidString var name = "" var linked = false var lastSync: Date? var lastSequence = 0 var status = SyncDeviceStatus.idle var errorState = false var netNode: ALBPeer? private enum DeviceJsonKey: String, CodingKey { case name, linked, lastSync, lastSequence } required init() { } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DeviceJsonKey.self) name = try container.decode(String.self, forKey: .name) linked = try container.decode(Bool.self, forKey: .linked) lastSequence = try container.decode(Int.self, forKey: .lastSequence) lastSync = try container.decodeIfPresent(Date.self, forKey: .lastSync) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DeviceJsonKey.self) try container.encode(name, forKey: .name) try container.encode(linked, forKey: .linked) try container.encode(lastSequence, forKey: .lastSequence) try container.encodeIfPresent(lastSync, forKey: .lastSync) } } class SyncEngine: ALBPeerServerDelegate, ALBPeerClientDelegate, ALBPeerConnectionDelegate { var delegate: SyncEngineDelegate? { didSet { for device in nearbyDevices { delegate?.syncDeviceFound(device) } } } var linkDelegate: SyncEngineLinkDelegate? var nearbyDevices = [SyncDevice]() var offlineDevices = [SyncDevice]() private var _netServer: ALBPeerServer private var _netClient: ALBPeerClient private var _netConnections = [ALBPeerConnection]() private let syncQueue = DispatchQueue(label: "com.AaronLBratcher.SyncQueue") private var _timer: DispatchSourceTimer private var _identityKey = "" init?(name: String) { if let deviceKeys = ALBNoSQLDB.shared.keysInTable(SyncDevice.table, sortOrder: "name") { for deviceKey in deviceKeys { if let offlineDevice = SyncDevice(db: ALBNoSQLDB.shared, key: deviceKey) { offlineDevices.append(offlineDevice) } } } _timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: syncQueue) /*Migrator FIXME: Use DispatchSourceTimer to avoid the cast*/ as! DispatchSource let _ = ALBNoSQLDB.shared.enableSyncing() if let dbKey = ALBNoSQLDB.shared.instanceKey { _identityKey = dbKey } let netNode = ALBPeer(name: name, peerID: _identityKey) _netServer = ALBPeerServer(serviceType: "_mymoneysync._tcp.", serverNode: netNode, serverDelegate: nil) _netClient = ALBPeerClient(serviceType: "_mymoneysync._tcp.", clientNode: netNode, clientDelegate: nil) _netServer.delegate = self // this is here instead of above because all stored properties of a class must be populated first if _identityKey == "" { return nil } if !_netServer.startPublishing() { return nil } _netClient.delegate = self _netClient.startBrowsing() // auto-sync with linked nearby devices every minute _timer.scheduleRepeating(deadline: .now(), interval: .milliseconds(60000), leeway: .milliseconds(1000)) _timer.setEventHandler { self.syncAllDevices() } _timer.resume() return } func stopBonjour() { _netServer.stopPublishing() _netClient.stopBrowsing() } func startBonjour() { let _ = _netServer.startPublishing() _netClient.startBrowsing() } func linkDevice(_ device: SyncDevice) { device.status = .linking _netClient.connectToServer(device.netNode!) notifyStatusChanged(device) } func forgetDevice(_ device: SyncDevice) { if nearbyDevices.filter({ $0.key == device.key }).count > 0 { device.status = .unlinking _netClient.connectToServer(device.netNode!) notifyStatusChanged(device) } completeDeviceUnlink(device) } func completeDeviceUnlink(_ device: SyncDevice) { ALBNoSQLDB.shared.deleteFromTable(SyncDevice.table, for: device.key) device.linked = false if offlineDevices.filter({ $0.key == device.key }).count > 0 { offlineDevices = offlineDevices.filter({ $0.key != device.key }) } notifyStatusChanged(device) } private func deviceForNode(_ node: ALBPeer) -> SyncDevice { let devices = nearbyDevices.filter({ $0.key == node.peerID }) if devices.count > 0 { return devices[0] } let syncDevice: SyncDevice if let device = SyncDevice(db: ALBNoSQLDB.shared, key: node.peerID) { syncDevice = device } else { let device = SyncDevice() device.key = node.peerID device.name = node.name syncDevice = device } syncDevice.netNode = node return syncDevice } func syncAllDevices() { for device in nearbyDevices { syncWithDevice(device) } } func syncWithDevice(_ device: SyncDevice) { if !device.linked || device.status != .idle { return } device.status = .syncing notifyStatusChanged(device) _netClient.connectToServer(device.netNode!) } private func notifyStatusChanged(_ device: SyncDevice) { DispatchQueue.main.async(execute: { () -> Void in self.delegate?.statusChanged(device) }) } // MARK: - Server delegate calls func serverPublishingError(_ errorDict: [NSObject: AnyObject]) { print("publishing error: \(errorDict)") } /** Called when a connection is requested. - parameter remoteNode: An ALBPeer object initialized with a name and a unique identifier. - parameter requestResponse: A closure that is to be called with a Bool indicating whether to allow the connection or not. This can be done asynchronously so a dialog can be invoked, etc. */ func allowConnectionRequest(_ remoteNode: ALBPeer, requestResponse: @escaping (_ allow: Bool) -> ()) { let device = deviceForNode(remoteNode) if device.linked { requestResponse(true) } else { if let linkDelegate = linkDelegate { linkDelegate.linkRequested(device, deviceResponse: { (allow) -> () in requestResponse(allow) }) } else { requestResponse(false) } } } func clientDidConnect(_ connection: ALBPeerConnection) { // connection delegate must be made to get read and write calls connection.delegate = self // strong reference must be kept of the connection _netConnections.append(connection) // client connected to link or sync. if connection was allowed, we're now linked. let device = deviceForNode(connection.remotNode) if !device.linked { device.linked = true device.save(to: ALBNoSQLDB.shared) } device.status = .idle } // MARK: - Client delegate calls func clientBrowsingError(_ errorDict: [NSObject: AnyObject]) { print("browsing error: \(errorDict)") } func serverFound(_ server: ALBPeer) { syncQueue.sync(execute: { () -> Void in let device = self.deviceForNode(server) if self.nearbyDevices.filter({ $0.key == device.key }).count > 0 || device.key == self._identityKey { return } self.nearbyDevices.append(device) self.offlineDevices = self.offlineDevices.filter({ $0.key != device.key }) self.syncWithDevice(device) DispatchQueue.main.async(execute: { () -> Void in self.delegate?.syncDeviceFound(device) }) }) } func serverLost(_ server: ALBPeer) { syncQueue.sync(execute: { () -> Void in let device = self.deviceForNode(server) if device.status != .idle { return } self.nearbyDevices = self.nearbyDevices.filter({ $0.key != device.key }) if let offlineDevice = SyncDevice(db: ALBNoSQLDB.shared, key: device.key) { self.offlineDevices.append(offlineDevice) } DispatchQueue.main.async(execute: { () -> Void in self.delegate?.syncDeviceLost(device) }) }) } func unableToConnect(_ server: ALBPeer) { let device = deviceForNode(server) switch device.status { case .linking: device.errorState = true case .syncing: device.errorState = true default: break } device.status = .idle notifyStatusChanged(device) } func connectionDenied(_ server: ALBPeer) { let device = deviceForNode(server) device.errorState = false device.status = .idle notifyStatusChanged(device) linkDelegate?.linkDenied(device) } func connected(_ connection: ALBPeerConnection) { // connection delegate must be made to get read and write calls connection.delegate = self // strong reference must be kept of the connection _netConnections.append(connection) let device = deviceForNode(connection.remotNode) // connection was initiatied to link, unlink or sync. An allowed connection says we should now be linked. if !device.linked { device.linked = true device.save(to: ALBNoSQLDB.shared) device.errorState = false } if device.status == .unlinking { let dict = ["dataType": DataType.unlink.rawValue] let data = NSKeyedArchiver.archivedData(withRootObject: dict) connection.sendData(data) connection.disconnect() ALBNoSQLDB.shared.deleteFromTable(SyncDevice.table, for: device.key) device.linked = false device.status = .idle notifyStatusChanged(device) } else { let dict = ["dataType": DataType.syncLogRequest.rawValue, "lastSequence": device.lastSequence] let data = NSKeyedArchiver.archivedData(withRootObject: dict) connection.sendData(data) } } // MARK: - Connection delegate calls func disconnected(_ connection: ALBPeerConnection, byRequest: Bool) { let device = deviceForNode(connection.remotNode) if !byRequest { switch device.status { case .linking: device.errorState = true case .syncing: device.errorState = true default: break } device.status = .idle notifyStatusChanged(device) } _netConnections = _netConnections.filter({ $0 != connection }) } func textReceived(_ connection: ALBPeerConnection, text: String) { // not used } func dataReceived(_ connection: ALBPeerConnection, data: Data) { let device = deviceForNode(connection.remotNode) // data packet is only sent to ask for sync file giving lastSequence or failure status of sync request if let dataDict = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: Int], let dataType = DataType(rawValue: dataDict["dataType"]!) { switch dataType { case .syncLogRequest: // server gets this let lastSequence = dataDict["lastSequence"]! syncQueue.async(execute: { () -> Void in let searchPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentFolderPath = searchPaths[0] let fileName = UUID().uuidString let logFilePath = "\(documentFolderPath)/\(fileName).txt" let url = URL(fileURLWithPath: logFilePath) let (success, _): (Bool, Int) = ALBNoSQLDB.shared.createSyncFileAtURL(url, lastSequence: lastSequence, targetDBInstanceKey: connection.remotNode.peerID) if success, let zipURL = URL(string: "") { let progress = connection.sendResourceAtURL(zipURL, name: "\(fileName).zip", resourceID: fileName, onCompletion: { (sent) -> () in connection.disconnect() do { try FileManager.default.removeItem(at: zipURL) } catch _ { } device.errorState = !sent device.status = .idle self.notifyStatusChanged(device) }) } else { // send sync error message let dict = ["dataType": DataType.syncError.rawValue] let data = NSKeyedArchiver.archivedData(withRootObject: dict) connection.sendData(data) connection.disconnect() } }) case .unlink: completeDeviceUnlink(device) default: // client side gets this device.errorState = true device.status = .idle notifyStatusChanged(device) } } else { // could not parse data packet so don't know message... close connection connection.disconnect() } } func startedReceivingResource(_ connection: ALBPeerConnection, atURL: URL, name: String, resourceID: String, progress: Progress) { print("started to receive \(atURL)") } func resourceReceived(_ connection: ALBPeerConnection, atURL: URL, name: String, resourceID: String) { let device = deviceForNode(connection.remotNode) connection.disconnect() syncQueue.async(execute: { () -> Void in if let summaryKeys = ALBNoSQLDB.shared.keysInTable(kMonthlySummaryEntriesTable, sortOrder: nil) { for key in summaryKeys { ALBNoSQLDB.shared.deleteFromTable(DBTable(name: kMonthlySummaryEntriesTable), for: key) } } let logURL = URL(fileReferenceLiteralResourceName: "") let (successful, _, lastSequence): (Bool, String, Int) = ALBNoSQLDB.shared.processSyncFileAtURL(logURL, syncProgress: nil) if successful { device.lastSequence = lastSequence device.lastSync = Date() device.save(to: ALBNoSQLDB.shared) device.errorState = false } else { device.errorState = true } do { try FileManager.default.removeItem(at: logURL) } catch _ { } device.status = .idle self.notifyStatusChanged(device) NotificationCenter.default.post(name: Notification.Name(rawValue: kSyncComplete), object: nil) }) } }
0
// // AccountViewController.swift // SimpleDocbase // // Created by jeonsangjun on 2017/11/17. // Copyright © 2017年 archive-asia. All rights reserved. // import UIKit import SwiftyFORM import SVProgressHUD import Firebase class AccountViewController: FormViewController { // MARK: Properties let userDefaults = UserDefaults.standard let fbManager = FBManager.sharedManager let alertManager = AlertManager() var user = Auth.auth().currentUser var ref: DatabaseReference! // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() tokenKeySubmitButton() } override func viewDidAppear(_ animated: Bool) { ref = Database.database().reference() } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.popViewController(animated: true) } override func populate(_ builder: FormBuilder) { builder.navigationTitle = "アカウント情報" builder.toolbarMode = .simple builder += SectionHeaderTitleFormItem().title("情報") builder += email builder += SectionHeaderTitleFormItem().title("APIトークン修正") builder += tokenKey builder += SectionHeaderTitleFormItem() builder += signInButton } lazy var email: StaticTextFormItem = { let instance = StaticTextFormItem() instance.title = "メール" if fbManager.statsOfSignIn == true { if let uid = user?.email { instance.value = uid } } else { instance.value = "サインインしてください。" } return instance }() lazy var tokenKey: TextFieldFormItem = { let instance = TextFieldFormItem() instance.placeholder("APIトークンを入力してください。") if let apiToken = fbManager.apiToken { instance.value = apiToken } return instance }() lazy var signInButton: ButtonFormItem = { let instance = ButtonFormItem() if fbManager.statsOfSignIn == true { if let user = user { instance.title = "サインアウト" instance.action = { self.fbManager.signOut { _ = self.navigationController?.popViewController(animated: true) } } } } else { instance.title = "サインイン" instance.action = { self.tabBarController?.selectedIndex = 1 } } return instance }() // MARK: Internal Methods // MARK: Private Methods private func tokenKeySubmitButton() { self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "修正", style: .plain, target: self, action: #selector(tokenKeySubmitAction)) } @objc private func tokenKeySubmitAction() { self.view.endEditing(true) if fbManager.statsOfSignIn == true { if let user = user { if tokenKey.value.isEmpty { // TODO: Check TokenKey Delete Alert PopUp alertManager.defaultAlert(self, title: "APIトークン削除", message: "APIトークンを削除しますか。", btnName: "削除") { self.userDefaults.removeObject(forKey: "selectedTeam") self.userDefaults.removeObject(forKey: "selectedGroup") self.navigationController?.popViewController(animated: true) } } else { // TODO: normally Regist TokenKey saveAPIToken(user, withUsername: tokenKey.value) userDefaults.removeObject(forKey: "selectedGroup") ACATeamRequest().getTeamList(completion: { teams in self.userDefaults.set(teams?.first, forKey: "selectedTeam") }) alertManager.confirmAlert(self, title: "APIトークン登録", message: "APIトークンを登録しました。") { self.navigationController?.popViewController(animated: true) } } } } else { alertManager.confirmAlert(self, title: "サインインしてください。", message: nil) { self.tabBarController?.selectedIndex = 1 } } } private func saveAPIToken(_ user: Firebase.User, withUsername apiToken: String) { // Create a change request let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest() // Commit profile changes to server changeRequest?.commitChanges() { (error) in if let error = error { print(error) return } self.ref.child("users").child(user.uid).setValue(["apiToken": apiToken]) self.fbManager.apiToken = apiToken } } }
0
// Conforming to this protocol allows the entity // to be paginated using `query.paginate()` public protocol Paginatable: Entity { static var pageSize: Int { get } static var pageSorts: [Sort] { get } } // MARK: Optional public var defaultPageSize: Int = 10 extension Paginatable { public static var pageSize: Int { return defaultPageSize } public static var pageSorts: [Sort] { return [ Sort(self, "createdAt", .descending) ] } }
0
// // ListViewController.swift // ListableUI // // Created by Kyle Van Essen on 6/21/20. // import Foundation import UIKit /// /// A class which provides an easy way to set up and display a `ListView`, /// The `ListViewController` itself manages setup and presentation of the `ListView`. /// /// As a consumer of the API, all you need to do is override one method: /// ``` /// func configure(list : inout ListProperties) { /// ... /// } /// ``` /// In which you set up and configure the list as needed. /// /// In order to reload the list when content changes or other display changes are required, call /// ``` /// func reload(animated : Bool = false) /// ``` /// Which will update the list with the new contents returned from your `configure` method. /// If the `ListViewController`'s view is not loaded, this method has no effect. /// open class ListViewController : UIViewController { // // MARK: Configuration // /// The default value for `clearsSelectionOnViewWillAppear` is true. /// This parameter allows mirroring the `clearsSelectionOnViewWillAppear` /// as available from `UITableViewController` or `UICollectionViewController`. public var clearsSelectionOnViewWillAppear : Bool = true // // MARK: Methods To Override // /// Override this method to configure your list how you'd like to. /// The properties on `ListProperties` closely mirror those on `ListView` /// itself, allowing you to fully configure and work with a list without needing to maintain /// and manage the view instance yourself. /// /// Example /// ------- /// ``` /// override func configure(list : inout ListProperties) /// { /// list.appearance = .myAppearance /// /// list.layout = .table { appearance in /// // Configure the appearance. /// } /// /// list.stateObserver.onContentChanged { info in /// MyLogger.log(...) /// } /// /// list("first-section") { section in /// section += self.myPodcasts.map { podcast in /// PodcastItem(podcast) /// } /// } /// } /// ``` /// You should not call super in your overridden implementation. /// open func configure(list : inout ListProperties) { fatalError("Subclasses of `ListViewController` must override `configure(list:)` to customize the content of their list view.") } // // MARK: Updating Content // public func reload(animated : Bool = false) { guard let listView = self.listView else { return } listView.configure { list in list.animatesChanges = animated self.configure(list: &list) } } // // MARK: - Internal & Private Methods - // // MARK: Initialization public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required public init?(coder: NSCoder) { fatalError() } // MARK: UIViewController private var listView : ListView? public override func loadView() { let listView = ListView() self.listView = listView self.view = listView } private var hasViewAppeared : Bool = false open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.hasViewAppeared == false { self.hasViewAppeared = true self.reload(animated: false) } else { if self.clearsSelectionOnViewWillAppear { self.listView?.clearSelectionDuringViewWillAppear(alongside: self.transitionCoordinator, animated: animated) } } } } public extension ListView { /// A method which provides `Behavior.SelectionMode.single`'s `clearsSelectionOnViewWillAppear` behaviour. /// By default, this method is called by `ListViewController`. However if you are not using `ListViewController` you /// will need to call this method yourself one of two ways: /// /// 1) If subclassing `UIViewController`: within your view controller's `viewWillAppear` method. /// /// 2) By invoking this same method on your `ListActions` that you have wired up to your list view. Use this /// in the case that you do not have access to your list view at all, such as when using `BlueprintUILists`. /// /// // Behaviour from UIKit Eng: https://twitter.com/smileyborg/status/1279473615553982464 /// func clearSelectionDuringViewWillAppear(alongside coordinator: UIViewControllerTransitionCoordinator?, animated : Bool) { guard case Behavior.SelectionMode.single = behavior.selectionMode else { return } guard let indexPath = storage.presentationState.selectedIndexPaths.first else { return } let item = storage.presentationState.item(at: indexPath) guard let coordinator = coordinator else { // No transition coordinator is available – we should just deselect return in this case. item.set(isSelected: false, performCallbacks: true) collectionView.deselectItem(at: indexPath, animated: animated) item.applyToVisibleCell(with: self.environment) return } coordinator.animate(alongsideTransition: { _ in item.set(isSelected: false, performCallbacks: true) self.collectionView.deselectItem(at: indexPath, animated: true) item.applyToVisibleCell(with: self.environment) }, completion: { context in if context.isCancelled { item.set(isSelected: true, performCallbacks: false) self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: []) item.applyToVisibleCell(with: self.environment) } }) } }
0
//// // 🦠 Corona-Warn-App // import XCTest @testable import ENA class HealthCertificateConsentViewModelTests: CWATestCase { func testGIVEN_ConsentViewModel_WHEN_getDynamicTableViewModel_THEN_CellsAndSectionsCountAreCorrect() { // GIVEN let viewModel = HealthCertificateInfoViewModel(didTapDataPrivacy: {}) // WHEN let dynamicTableViewModel = viewModel.dynamicTableViewModel // THEN XCTAssertEqual(dynamicTableViewModel.numberOfSection, 3) XCTAssertEqual(dynamicTableViewModel.numberOfRows(section: 0), 5) XCTAssertEqual(dynamicTableViewModel.numberOfRows(section: 1), 1) XCTAssertEqual(dynamicTableViewModel.numberOfRows(section: 2), 1) } }
0
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if NS_FOUNDATION_ALLOWS_TESTABLE_IMPORT #if canImport(SwiftFoundation) && !DEPLOYMENT_RUNTIME_OBJC @testable import SwiftFoundation #else @testable import Foundation #endif #endif @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) extension AttributedStringProtocol { fileprivate mutating func genericSetAttribute() { self.testInt = 3 } } /// Tests for `AttributedString` to confirm expected CoW behavior @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) final class TestAttributedStringCOW: XCTestCase { // MARK: - Utility Functions func createAttributedString() -> AttributedString { var str = AttributedString("Hello", attributes: container) str += AttributedString(" ") str += AttributedString("World", attributes: containerB) return str } func assertCOWCopy(file: StaticString = #file, line: UInt = #line, _ operation: (inout AttributedString) -> Void) { let str = createAttributedString() var copy = str operation(&copy) XCTAssertNotEqual(str, copy, "Mutation operation did not copy when multiple references exist", file: file, line: line) } func assertCOWNoCopy(file: StaticString = #file, line: UInt = #line, _ operation: (inout AttributedString) -> Void) { var str = createAttributedString() let gutsPtr = Unmanaged.passUnretained(str._guts) operation(&str) let newGutsPtr = Unmanaged.passUnretained(str._guts) XCTAssertEqual(gutsPtr.toOpaque(), newGutsPtr.toOpaque(), "Mutation operation copied when only one reference exists", file: file, line: line) } func assertCOWBehavior(file: StaticString = #file, line: UInt = #line, _ operation: (inout AttributedString) -> Void) { assertCOWCopy(file: file, line: line, operation) assertCOWNoCopy(file: file, line: line, operation) } func makeSubrange(_ str: AttributedString) -> Range<AttributedString.Index> { return str.characters.index(str.startIndex, offsetBy: 2)..<str.characters.index(str.endIndex, offsetBy: -2) } lazy var container: AttributeContainer = { var container = AttributeContainer() container.testInt = 2 return container }() lazy var containerB: AttributeContainer = { var container = AttributeContainer() container.testBool = true return container }() // MARK: - Tests func testTopLevelType() { assertCOWBehavior { (str) in str.setAttributes(container) } assertCOWBehavior { (str) in str.mergeAttributes(container) } assertCOWBehavior { (str) in str.replaceAttributes(container, with: containerB) } assertCOWBehavior { (str) in str.append(AttributedString("b", attributes: containerB)) } assertCOWBehavior { (str) in str.insert(AttributedString("b", attributes: containerB), at: str.startIndex) } assertCOWBehavior { (str) in str.removeSubrange(..<str.characters.index(str.startIndex, offsetBy: 3)) } assertCOWBehavior { (str) in str.replaceSubrange(..<str.characters.index(str.startIndex, offsetBy: 3), with: AttributedString("b", attributes: containerB)) } assertCOWBehavior { (str) in str[AttributeScopes.TestAttributes.TestIntAttribute.self] = 3 } assertCOWBehavior { (str) in str.testInt = 3 } assertCOWBehavior { (str) in str.test.testInt = 3 } } func testSubstring() { assertCOWBehavior { (str) in str[makeSubrange(str)].setAttributes(container) } assertCOWBehavior { (str) in str[makeSubrange(str)].mergeAttributes(container) } assertCOWBehavior { (str) in str[makeSubrange(str)].replaceAttributes(container, with: containerB) } assertCOWBehavior { (str) in str[makeSubrange(str)][AttributeScopes.TestAttributes.TestIntAttribute.self] = 3 } assertCOWBehavior { (str) in str[makeSubrange(str)].testInt = 3 } assertCOWBehavior { (str) in str[makeSubrange(str)].test.testInt = 3 } } func testCharacters() { let char: Character = "a" assertCOWBehavior { (str) in str.characters.replaceSubrange(makeSubrange(str), with: "abc") } assertCOWBehavior { (str) in str.characters.append(char) } assertCOWBehavior { (str) in str.characters.append(contentsOf: "abc") } assertCOWBehavior { (str) in str.characters.append(contentsOf: [char, char, char]) } assertCOWBehavior { (str) in str.characters[str.startIndex] = "A" } assertCOWBehavior { (str) in str.characters[makeSubrange(str)].append("a") } } func testUnicodeScalars() { let scalar: UnicodeScalar = "a" assertCOWBehavior { (str) in str.unicodeScalars.replaceSubrange(makeSubrange(str), with: [scalar, scalar]) } } func testGenericProtocol() { assertCOWBehavior { $0.genericSetAttribute() } assertCOWBehavior { $0[makeSubrange($0)].genericSetAttribute() } } static var allTests: [(String, (TestAttributedStringCOW) -> () throws -> Void)] { return [ ("testTopLevelType", testTopLevelType), ("testSubstring", testSubstring), ("testCharacters", testCharacters), ("testUnicodeScalars", testUnicodeScalars), ("testGenericProtocol", testGenericProtocol) ] } }
0
// // AppDelegate.swift // macOSDemo // // Created by Sota Yokoe on 2016/11/03. // // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
0
// // GoogleAuthLoader.swift // Taskgoo // // Created by Tomáš Martykán on 01/04/1976. // Copyright © 2019 Tomáš Martykan. All rights reserved. // import Foundation import p2_OAuth2 class GoogleAPI: OAuth2DataLoader { public init() { let oauth = OAuth2CodeGrant(settings: [ "keychain": true, "client_id": "921625277666-gqdl56ck6h6loesm40sa510862q5agl6.apps.googleusercontent.com", "client_secret": "5jq-QA7-ZCpInV87_Ju276vU", "authorize_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://www.googleapis.com/oauth2/v3/token", "scope": "profile https://www.googleapis.com/auth/tasks", "redirect_uris": ["urn:ietf:wg:oauth:2.0:oob"], ]) oauth.authConfig.authorizeEmbedded = true oauth.logger = OAuth2DebugLogger(.debug) super.init(oauth2: oauth, host: "https://www.googleapis.com") alsoIntercept403 = true } func request(req: URLRequest, callback: @escaping ((OAuth2JSON?, Error?) -> Void)) { perform(request: req) { response in if response.response.statusCode == 204 { DispatchQueue.main.async { callback(nil, nil) } return } do { let dict = try response.responseJSON() DispatchQueue.main.async { callback(dict, nil) } } catch let error { DispatchQueue.main.async { callback(nil, error) } } } } } protocol SyncOperation { func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) } class TasklistList : SyncOperation { func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { let url = URL(string: "https://www.googleapis.com/tasks/v1/users/@me/lists")! let req = googleApi.oauth2.request(forURL: url) googleApi.request(req: req, callback: callback) } } class TasklistAdd : SyncOperation { let tasklist: Tasklist init(tasklist: Tasklist) { self.tasklist = tasklist } func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { let url = URL(string: "https://www.googleapis.com/tasks/v1/users/@me/lists")! var req = googleApi.oauth2.request(forURL: url) req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.httpMethod = "POST" let body: Dictionary<String, Any> = [ "title": tasklist.title ] req.httpBody = try! JSONSerialization.data(withJSONObject: body) googleApi.request(req: req, callback: callback) } } class TasklistUpdate : SyncOperation { let tasklist: Tasklist init(tasklist: Tasklist) { self.tasklist = tasklist } func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { let url = URL(string: "https://www.googleapis.com/tasks/v1/users/@me/lists/" + tasklist.id)! var req = googleApi.oauth2.request(forURL: url) req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.httpMethod = "PATCH" let body: Dictionary<String, Any> = [ "title": tasklist.title ] req.httpBody = try! JSONSerialization.data(withJSONObject: body) googleApi.request(req: req, callback: callback) } } class TasklistDelete : SyncOperation { let tasklist: Tasklist init(tasklist: Tasklist) { self.tasklist = tasklist } func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { let url = URL(string: "https://www.googleapis.com/tasks/v1/users/@me/lists/" + tasklist.id)! var req = googleApi.oauth2.request(forURL: url) req.httpMethod = "DELETE" googleApi.request(req: req, callback: callback) } } class TasksList : SyncOperation { let tasklistId: String init(tasklistId: String) { self.tasklistId = tasklistId } func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { let url = URL(string: "https://www.googleapis.com/tasks/v1/lists/" + tasklistId + "/tasks?showCompleted=true")! let req = googleApi.oauth2.request(forURL: url) googleApi.request(req: req, callback: callback) } } class TasksAdd : SyncOperation { let task: Task init(task: Task) { self.task = task } func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { let url = URL(string: "https://www.googleapis.com/tasks/v1/lists/" + task.tasklist + "/tasks")! var req = googleApi.oauth2.request(forURL: url) req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.httpMethod = "POST" let body: Dictionary<String, Any> = [ "title": task.title ] req.httpBody = try! JSONSerialization.data(withJSONObject: body) googleApi.request(req: req, callback: callback) } } class TasksUpdate : SyncOperation { let task: Task let body: Data init(task: Task, body: Data) { self.task = task self.body = body } func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { if let id = tmpIdMap[self.task.id] { self.task.id = id } return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { let url = URL(string: "https://www.googleapis.com/tasks/v1/lists/" + task.tasklist + "/tasks/" + task.id)! var req = googleApi.oauth2.request(forURL: url) req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.httpMethod = "PATCH" req.httpBody = body googleApi.request(req: req, callback: callback) } } class TasksMove : SyncOperation { let task: Task let previousId: String? init(task: Task, previousId: String?) { self.task = task self.previousId = previousId } func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { if let id = tmpIdMap[self.task.id] { self.task.id = id } return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { var url = URL(string: "https://www.googleapis.com/tasks/v1/lists/" + task.tasklist + "/tasks/" + task.id + "/move")! if previousId != nil { url = URL(string: url.absoluteString + "?previous=" + previousId!)! } var req = googleApi.oauth2.request(forURL: url) req.httpMethod = "POST" googleApi.request(req: req, callback: callback) } } class TasksDelete : SyncOperation { let task: Task init(task: Task) { self.task = task } func tmpIdMap(_ tmpIdMap: [String : String]) -> SyncOperation { if let id = tmpIdMap[self.task.id] { self.task.id = id } return self } func request(googleApi: GoogleAPI, callback: @escaping ((_ dict: OAuth2JSON?, _ error: Error?) -> Void)) { let url = URL(string: "https://www.googleapis.com/tasks/v1/lists/" + task.tasklist + "/tasks/" + task.id)! var req = googleApi.oauth2.request(forURL: url) req.httpMethod = "DELETE" googleApi.request(req: req, callback: callback) } }
0
/* Question - Merge Two Sorted Lists Link - > https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/579/week-1-january-1st-january-7th/3592/ */ class Solution { func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { guard let l1 = l1 else { return l2 } guard let l2 = l2 else { return l1 } var outputNode: ListNode? = nil if l1.val <= l2.val{ outputNode = l1 outputNode!.next = mergeTwoLists(l1.next, l2) }else{ outputNode = l2 outputNode!.next = mergeTwoLists(l1, l2.next) } return outputNode } }
0
// // LineChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class LineChartRenderer: LineRadarRenderer { // TODO: Currently, this nesting isn't necessary for LineCharts. However, it will make it much easier to add a custom rotor // that navigates between datasets. // NOTE: Unlike the other renderers, LineChartRenderer populates accessibleChartElements in drawCircles due to the nature of its drawing options. /// A nested array of elements ordered logically (i.e not in visual/drawing order) for use with VoiceOver. private lazy var accessibilityOrderedElements: [[NSUIAccessibilityElement]] = accessibilityCreateEmptyOrderedElements() @objc open weak var dataProvider: LineChartDataProvider? @objc public init(dataProvider: LineChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } open override func drawData(context: CGContext) { guard let lineData = dataProvider?.lineData else { return } let sets = lineData.dataSets as? [LineChartDataSet] assert(sets != nil, "Datasets for LineChartRenderer must conform to ILineChartDataSet") let drawDataSet = { self.drawDataSet(context: context, dataSet: $0) } sets!.lazy .filter(\.isVisible) .forEach(drawDataSet) } @objc open func drawDataSet(context: CGContext, dataSet: LineChartDataSetProtocol) { if dataSet.entryCount < 1 { return } context.saveGState() context.setLineWidth(dataSet.lineWidth) if dataSet.lineDashLengths != nil { context.setLineDash(phase: dataSet.lineDashPhase, lengths: dataSet.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.setLineCap(dataSet.lineCapType) // if drawing cubic lines is enabled switch dataSet.mode { case .linear: fallthrough case .stepped: drawLinear(context: context, dataSet: dataSet) case .cubicBezier: drawCubicBezier(context: context, dataSet: dataSet) case .horizontalBezier: drawHorizontalBezier(context: context, dataSet: dataSet) } context.restoreGState() } private func drawLine( context: CGContext, spline: CGMutablePath, drawingColor: NSUIColor) { context.beginPath() context.addPath(spline) context.setStrokeColor(drawingColor.cgColor) context.strokePath() } @objc open func drawCubicBezier(context: CGContext, dataSet: LineChartDataSetProtocol) { guard let dataProvider = dataProvider else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! let intensity = dataSet.cubicIntensity // the path for the cubic-spline let cubicPath = CGMutablePath() let valueToPixelMatrix = trans.valueToPixelMatrix if _xBounds.range >= 1 { var prevDx: CGFloat = 0.0 var prevDy: CGFloat = 0.0 var curDx: CGFloat = 0.0 var curDy: CGFloat = 0.0 // Take an extra point from the left, and an extra from the right. // That's because we need 4 points for a cubic bezier (cubic=4), otherwise we get lines moving and doing weird stuff on the edges of the chart. // So in the starting `prev` and `cur`, go -2, -1 let firstIndex = _xBounds.min + 1 var prevPrev: ChartDataEntry! = nil var prev: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 2, 0)) var cur: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 1, 0)) var next: ChartDataEntry! = cur var nextIndex: Int = -1 if cur == nil { return } // let the spline start cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) for j in _xBounds.dropFirst() // same as firstIndex { prevPrev = prev prev = cur cur = nextIndex == j ? next : dataSet.entryForIndex(j) nextIndex = j + 1 < dataSet.entryCount ? j + 1 : j next = dataSet.entryForIndex(nextIndex) if next == nil { break } prevDx = CGFloat(cur.x - prevPrev.x) * intensity prevDy = CGFloat(cur.y - prevPrev.y) * intensity curDx = CGFloat(next.x - prev.x) * intensity curDy = CGFloat(next.y - prev.y) * intensity cubicPath.addCurve( to: CGPoint( x: CGFloat(cur.x), y: CGFloat(cur.y) * CGFloat(phaseY)), control1: CGPoint( x: CGFloat(prev.x) + prevDx, y: (CGFloat(prev.y) + prevDy) * CGFloat(phaseY)), control2: CGPoint( x: CGFloat(cur.x) - curDx, y: (CGFloat(cur.y) - curDy) * CGFloat(phaseY)), transform: valueToPixelMatrix) } } context.saveGState() defer { context.restoreGState() } if dataSet.isDrawFilledEnabled { // Copy this path because we make changes to it let fillPath = cubicPath.mutableCopy() drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds) } if dataSet.isDrawLineWithGradientEnabled { drawGradientLine(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix) } else { drawLine(context: context, spline: cubicPath, drawingColor: drawingColor) } } @objc open func drawHorizontalBezier(context: CGContext, dataSet: LineChartDataSetProtocol) { guard let dataProvider = dataProvider else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // get the color that is specified for this position from the DataSet let drawingColor = dataSet.colors.first! // the path for the cubic-spline let cubicPath = CGMutablePath() let valueToPixelMatrix = trans.valueToPixelMatrix if _xBounds.range >= 1 { var prev: ChartDataEntry! = dataSet.entryForIndex(_xBounds.min) var cur: ChartDataEntry! = prev if cur == nil { return } // let the spline start cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) for j in _xBounds.dropFirst() { prev = cur cur = dataSet.entryForIndex(j) let cpx = CGFloat(prev.x + (cur.x - prev.x) / 2.0) cubicPath.addCurve( to: CGPoint( x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), control1: CGPoint( x: cpx, y: CGFloat(prev.y * phaseY)), control2: CGPoint( x: cpx, y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix) } } context.saveGState() defer { context.restoreGState() } if dataSet.isDrawFilledEnabled { // Copy this path because we make changes to it let fillPath = cubicPath.mutableCopy() drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds) } if dataSet.isDrawLineWithGradientEnabled { drawGradientLine(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix) } else { drawLine(context: context, spline: cubicPath, drawingColor: drawingColor) } } open func drawCubicFill( context: CGContext, dataSet: LineChartDataSetProtocol, spline: CGMutablePath, matrix: CGAffineTransform, bounds: XBounds) { guard let dataProvider = dataProvider else { return } if bounds.range <= 0 { return } let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0 var pt1 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min + bounds.range)?.x ?? 0.0), y: fillMin) var pt2 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min)?.x ?? 0.0), y: fillMin) pt1 = pt1.applying(matrix) pt2 = pt2.applying(matrix) spline.addLine(to: pt1) spline.addLine(to: pt2) spline.closeSubpath() if dataSet.fill != nil { drawFilledPath(context: context, path: spline, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: spline, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } private var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2) @objc open func drawLinear(context: CGContext, dataSet: LineChartDataSetProtocol) { guard let dataProvider = dataProvider else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let isDrawSteppedEnabled = dataSet.mode == .stepped let pointsPerEntryPair = isDrawSteppedEnabled ? 4 : 2 let phaseY = animator.phaseY _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) // if drawing filled is enabled if dataSet.isDrawFilledEnabled && entryCount > 0 { drawLinearFill(context: context, dataSet: dataSet, trans: trans, bounds: _xBounds) } context.saveGState() defer { context.restoreGState() } // more than 1 color if dataSet.colors.count > 1, !dataSet.isDrawLineWithGradientEnabled { if _lineSegments.count != pointsPerEntryPair { // Allocate once in correct size _lineSegments = [CGPoint](repeating: CGPoint(), count: pointsPerEntryPair) } for j in _xBounds.dropLast() { var e: ChartDataEntry! = dataSet.entryForIndex(j) if e == nil { continue } _lineSegments[0].x = CGFloat(e.x) _lineSegments[0].y = CGFloat(e.y * phaseY) if j < _xBounds.max { // TODO: remove the check. // With the new XBounds iterator, j is always smaller than _xBounds.max // Keeping this check for a while, if xBounds have no further breaking changes, it should be safe to remove the check e = dataSet.entryForIndex(j + 1) if e == nil { break } if isDrawSteppedEnabled { _lineSegments[1] = CGPoint(x: CGFloat(e.x), y: _lineSegments[0].y) _lineSegments[2] = _lineSegments[1] _lineSegments[3] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)) } else { _lineSegments[1] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)) } } else { _lineSegments[1] = _lineSegments[0] } _lineSegments = _lineSegments.map { $0.applying(valueToPixelMatrix) } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break } // Determine the start and end coordinates of the line, and make sure they differ. guard let firstCoordinate = _lineSegments.first, let lastCoordinate = _lineSegments.last, firstCoordinate != lastCoordinate else { continue } // make sure the lines don't do shitty things outside bounds if !viewPortHandler.isInBoundsLeft(lastCoordinate.x) || !viewPortHandler.isInBoundsTop(max(firstCoordinate.y, lastCoordinate.y)) || !viewPortHandler.isInBoundsBottom(min(firstCoordinate.y, lastCoordinate.y)) { continue } // get the color that is set for this line-segment context.setStrokeColor(dataSet.color(atIndex: j).cgColor) context.strokeLineSegments(between: _lineSegments) } } else { // only one color per dataset guard dataSet.entryForIndex(_xBounds.min) != nil else { return } var firstPoint = true let path = CGMutablePath() for x in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1) { guard let e1 = dataSet.entryForIndex(x == 0 ? 0 : (x - 1)) else { continue } guard let e2 = dataSet.entryForIndex(x) else { continue } let startPoint = CGPoint( x: CGFloat(e1.x), y: CGFloat(e1.y * phaseY)) .applying(valueToPixelMatrix) if firstPoint { path.move(to: startPoint) firstPoint = false } else { path.addLine(to: startPoint) } if isDrawSteppedEnabled { let steppedPoint = CGPoint( x: CGFloat(e2.x), y: CGFloat(e1.y * phaseY)) .applying(valueToPixelMatrix) path.addLine(to: steppedPoint) } let endPoint = CGPoint( x: CGFloat(e2.x), y: CGFloat(e2.y * phaseY)) .applying(valueToPixelMatrix) path.addLine(to: endPoint) } if !firstPoint { if dataSet.isDrawLineWithGradientEnabled { drawGradientLine(context: context, dataSet: dataSet, spline: path, matrix: valueToPixelMatrix) } else { context.beginPath() context.addPath(path) context.setStrokeColor(dataSet.color(atIndex: 0).cgColor) context.strokePath() } } } } open func drawLinearFill(context: CGContext, dataSet: LineChartDataSetProtocol, trans: Transformer, bounds: XBounds) { guard let dataProvider = dataProvider else { return } let filled = generateFilledPath( dataSet: dataSet, fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0, bounds: bounds, matrix: trans.valueToPixelMatrix) if dataSet.fill != nil { drawFilledPath(context: context, path: filled, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: filled, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } /// Generates the path that is used for filled drawing. private func generateFilledPath(dataSet: LineChartDataSetProtocol, fillMin: CGFloat, bounds: XBounds, matrix: CGAffineTransform) -> CGPath { let phaseY = animator.phaseY let isDrawSteppedEnabled = dataSet.mode == .stepped let matrix = matrix var e: ChartDataEntry! let filled = CGMutablePath() e = dataSet.entryForIndex(bounds.min) if e != nil { filled.move(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix) filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix) } // create a new path for x in stride(from: (bounds.min + 1), through: bounds.range + bounds.min, by: 1) { guard let e = dataSet.entryForIndex(x) else { continue } if isDrawSteppedEnabled { guard let ePrev = dataSet.entryForIndex(x-1) else { continue } filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(ePrev.y * phaseY)), transform: matrix) } filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix) } // close up e = dataSet.entryForIndex(bounds.range + bounds.min) if e != nil { filled.addLine(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix) } filled.closeSubpath() return filled } open override func drawValues(context: CGContext) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData else { return } if isDrawingValuesAllowed(dataProvider: dataProvider) { let phaseY = animator.phaseY var pt = CGPoint() for i in lineData.indices { guard let dataSet = lineData[i] as? LineChartDataSetProtocol, shouldDrawValues(forDataSet: dataSet) else { continue } let valueFont = dataSet.valueFont let formatter = dataSet.valueFormatter let angleRadians = dataSet.valueLabelAngle.DEG2RAD let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let iconsOffset = dataSet.iconsOffset // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75) if !dataSet.isDrawCirclesEnabled { valOffset = valOffset / 2 } _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) for j in _xBounds { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } if dataSet.isDrawValuesEnabled { context.drawText(formatter.stringForValue(e.y, entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler), at: CGPoint(x: pt.x, y: pt.y - CGFloat(valOffset) - valueFont.lineHeight), align: .center, angleRadians: angleRadians, attributes: [.font: valueFont, .foregroundColor: dataSet.valueTextColorAt(j)]) } if let icon = e.icon, dataSet.isDrawIconsEnabled { context.drawImage(icon, atCenter: CGPoint(x: pt.x + iconsOffset.x, y: pt.y + iconsOffset.y), size: icon.size) } } } } } open override func drawExtras(context: CGContext) { drawCircles(context: context) } private func drawCircles(context: CGContext) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData else { return } let phaseY = animator.phaseY var pt = CGPoint() var rect = CGRect() // If we redraw the data, remove and repopulate accessible elements to update label values and frames accessibleChartElements.removeAll() accessibilityOrderedElements = accessibilityCreateEmptyOrderedElements() // Make the chart header the first element in the accessible elements array if let chart = dataProvider as? LineChartView { let element = createAccessibleHeader(usingChart: chart, andData: lineData, withDefaultDescription: "Line Chart") accessibleChartElements.append(element) } context.saveGState() for i in lineData.indices { guard let dataSet = lineData[i] as? LineChartDataSetProtocol else { continue } // Skip Circles and Accessibility if not enabled, // reduces CPU significantly if not needed if !dataSet.isVisible || !dataSet.isDrawCirclesEnabled || dataSet.entryCount == 0 { continue } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix _xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator) let circleRadius = dataSet.circleRadius let circleDiameter = circleRadius * 2.0 let circleHoleRadius = dataSet.circleHoleRadius let circleHoleDiameter = circleHoleRadius * 2.0 let drawCircleHole = dataSet.isDrawCircleHoleEnabled && circleHoleRadius < circleRadius && circleHoleRadius > 0.0 let drawTransparentCircleHole = drawCircleHole && (dataSet.circleHoleColor == nil || dataSet.circleHoleColor == NSUIColor.clear) for j in _xBounds { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.x) pt.y = CGFloat(e.y * phaseY) pt = pt.applying(valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } // Accessibility element geometry let scaleFactor: CGFloat = 3 let accessibilityRect = CGRect(x: pt.x - (scaleFactor * circleRadius), y: pt.y - (scaleFactor * circleRadius), width: scaleFactor * circleDiameter, height: scaleFactor * circleDiameter) // Create and append the corresponding accessibility element to accessibilityOrderedElements if let chart = dataProvider as? LineChartView { let element = createAccessibleElement(withIndex: j, container: chart, dataSet: dataSet, dataSetIndex: i) { (element) in element.accessibilityFrame = accessibilityRect } accessibilityOrderedElements[i].append(element) } context.setFillColor(dataSet.getCircleColor(atIndex: j)!.cgColor) rect.origin.x = pt.x - circleRadius rect.origin.y = pt.y - circleRadius rect.size.width = circleDiameter rect.size.height = circleDiameter if drawTransparentCircleHole { // Begin path for circle with hole context.beginPath() context.addEllipse(in: rect) // Cut hole in path rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter context.addEllipse(in: rect) // Fill in-between context.fillPath(using: .evenOdd) } else { context.fillEllipse(in: rect) if drawCircleHole { context.setFillColor(dataSet.circleHoleColor!.cgColor) // The hole rect rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter context.fillEllipse(in: rect) } } } } context.restoreGState() // Merge nested ordered arrays into the single accessibleChartElements. accessibleChartElements.append(contentsOf: accessibilityOrderedElements.flatMap { $0 } ) accessibilityPostLayoutChangedNotification() } open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let lineData = dataProvider.lineData else { return } let chartXMax = dataProvider.chartXMax context.saveGState() for high in indices { guard let set = lineData[high.dataSetIndex] as? LineChartDataSetProtocol, set.isHighlightEnabled else { continue } guard let e = set.entryForXValue(high.x, closestToY: high.y) else { continue } if !isInBoundsX(entry: e, dataSet: set) { continue } context.setStrokeColor(set.highlightColor.cgColor) context.setLineWidth(set.highlightLineWidth) if set.highlightLineDashLengths != nil { context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } let x = e.x // get the x-position let y = e.y * Double(animator.phaseY) if x > chartXMax * animator.phaseX { continue } let trans = dataProvider.getTransformer(forAxis: set.axisDependency) let pt = trans.pixelForValues(x: x, y: y) high.setDraw(pt: pt) // draw the lines drawHighlightLines(context: context, point: pt, set: set) } context.restoreGState() } func drawGradientLine(context: CGContext, dataSet: LineChartDataSetProtocol, spline: CGPath, matrix: CGAffineTransform) { guard let gradientPositions = dataSet.gradientPositions else { assertionFailure("Must set `gradientPositions if `dataSet.isDrawLineWithGradientEnabled` is true") return } // `insetBy` is applied since bounding box // doesn't take into account line width // so that peaks are trimmed since // gradient start and gradient end calculated wrong let boundingBox = spline.boundingBox .insetBy(dx: -dataSet.lineWidth / 2, dy: -dataSet.lineWidth / 2) guard !boundingBox.isNull, !boundingBox.isInfinite, !boundingBox.isEmpty else { return } let gradientStart = CGPoint(x: 0, y: boundingBox.minY) let gradientEnd = CGPoint(x: 0, y: boundingBox.maxY) let gradientColorComponents: [CGFloat] = dataSet.colors .reversed() .reduce(into: []) { (components, color) in guard let (r, g, b, a) = color.nsuirgba else { return } components += [r, g, b, a] } let gradientLocations: [CGFloat] = gradientPositions.reversed() .map { (position) in let location = CGPoint(x: boundingBox.minX, y: position) .applying(matrix) let normalizedLocation = (location.y - boundingBox.minY) / (boundingBox.maxY - boundingBox.minY) return normalizedLocation.clamped(to: 0...1) } let baseColorSpace = CGColorSpaceCreateDeviceRGB() guard let gradient = CGGradient( colorSpace: baseColorSpace, colorComponents: gradientColorComponents, locations: gradientLocations, count: gradientLocations.count) else { return } context.saveGState() defer { context.restoreGState() } context.beginPath() context.addPath(spline) context.replacePathWithStrokedPath() context.clip() context.drawLinearGradient(gradient, start: gradientStart, end: gradientEnd, options: []) } /// Creates a nested array of empty subarrays each of which will be populated with NSUIAccessibilityElements. /// This is marked internal to support HorizontalBarChartRenderer as well. private func accessibilityCreateEmptyOrderedElements() -> [[NSUIAccessibilityElement]] { guard let chart = dataProvider as? LineChartView else { return [] } let dataSetCount = chart.lineData?.dataSetCount ?? 0 return Array(repeating: [NSUIAccessibilityElement](), count: dataSetCount) } /// Creates an NSUIAccessibleElement representing the smallest meaningful bar of the chart /// i.e. in case of a stacked chart, this returns each stack, not the combined bar. /// Note that it is marked internal to support subclass modification in the HorizontalBarChart. private func createAccessibleElement(withIndex idx: Int, container: LineChartView, dataSet: LineChartDataSetProtocol, dataSetIndex: Int, modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement { let element = NSUIAccessibilityElement(accessibilityContainer: container) let xAxis = container.xAxis guard let e = dataSet.entryForIndex(idx) else { return element } guard let dataProvider = dataProvider else { return element } // NOTE: The formatter can cause issues when the x-axis labels are consecutive ints. // i.e. due to the Double conversion, if there are more than one data set that are grouped, // there is the possibility of some labels being rounded up. A floor() might fix this, but seems to be a brute force solution. let label = xAxis.valueFormatter?.stringForValue(e.x, axis: xAxis) ?? "\(e.x)" let elementValueText = dataSet.valueFormatter.stringForValue(e.y, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler) let dataSetCount = dataProvider.lineData?.dataSetCount ?? -1 let doesContainMultipleDataSets = dataSetCount > 1 element.accessibilityLabel = "\(doesContainMultipleDataSets ? (dataSet.label ?? "") + ", " : "") \(label): \(elementValueText)" modifier(element) return element } }
0
/* * Copyright (c) 2015 Razeware LLC * * 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 UIKit class BookCell : UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! { didSet { imageView.layer.shadowRadius = 4.0 imageView.layer.shadowOpacity = 0.5 imageView.layer.shadowOffset = CGSize.zero } } }