hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
29d22b5af20d14c13f6d2ce9ddbed7a46c7c7823 | 11,296 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import SystemConfiguration
import Foundation
public enum AwesomeReachabilityError: Error {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
}
@available(*, unavailable, renamed: "Notification.Name.AwesomeReachabilityChanged")
public let AwesomeReachabilityChangedNotification = NSNotification.Name("AwesomeReachabilityChangedNotification")
extension Notification.Name {
public static let AwesomeReachabilityChanged = Notification.Name("AwesomeReachabilityChanged")
}
func callback(AwesomeReachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let AwesomeReachability = Unmanaged<AwesomeReachability>.fromOpaque(info).takeUnretainedValue()
AwesomeReachability.AwesomeReachabilityChanged()
}
public class AwesomeReachability {
public typealias NetworkReachable = (AwesomeReachability) -> ()
public typealias NetworkUnreachable = (AwesomeReachability) -> ()
@available(*, unavailable, renamed: "Conection")
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public enum Connection: CustomStringConvertible {
case none, wifi, cellular
public var description: String {
switch self {
case .cellular: return "Cellular"
case .wifi: return "WiFi"
case .none: return "No Connection"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
@available(*, deprecated: 4.0, renamed: "allowsCellularConnection")
public let reachableOnWWAN: Bool = true
/// Set to `false` to force AwesomeReachability.connection to .none when on cellular connection (default value `true`)
public var allowsCellularConnection: Bool
// The notification center on which "AwesomeReachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
@available(*, deprecated: 4.0, renamed: "connection.description")
public var currentAwesomeReachabilityString: String {
return "\(connection)"
}
@available(*, unavailable, renamed: "connection")
public var currentAwesomeReachabilityStatus: Connection {
return connection
}
public var connection: Connection {
guard isReachableFlagSet else { return .none }
// If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return .wifi }
var connection = Connection.none
if !isConnectionRequiredFlagSet {
connection = .wifi
}
if isConnectionOnTrafficOrDemandFlagSet {
if !isInterventionRequiredFlagSet {
connection = .wifi
}
}
if isOnWWANFlagSet {
if !allowsCellularConnection {
connection = .none
} else {
connection = .cellular
}
}
return connection
}
fileprivate var previousFlags: SCNetworkReachabilityFlags?
fileprivate var isRunningOnDevice: Bool = {
#if targetEnvironment(simulator)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate let AwesomeReachabilityRef: SCNetworkReachability
fileprivate let AwesomeReachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.AwesomeReachability")
required public init(AwesomeReachabilityRef: SCNetworkReachability) {
allowsCellularConnection = true
self.AwesomeReachabilityRef = AwesomeReachabilityRef
}
public convenience init?(hostname: String) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(AwesomeReachabilityRef: ref)
}
public convenience init?() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil }
self.init(AwesomeReachabilityRef: ref)
}
deinit {
stopNotifier()
}
}
public extension AwesomeReachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<AwesomeReachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(AwesomeReachabilityRef, callback, &context) {
stopNotifier()
throw AwesomeReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(AwesomeReachabilityRef, AwesomeReachabilitySerialQueue) {
stopNotifier()
throw AwesomeReachabilityError.UnableToSetDispatchQueue
}
// Perform an initial check
AwesomeReachabilitySerialQueue.async {
self.AwesomeReachabilityChanged()
}
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
SCNetworkReachabilitySetCallback(AwesomeReachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(AwesomeReachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
@available(*, deprecated: 4.0, message: "Please use `connection != .none`")
var isReachable: Bool {
guard isReachableFlagSet else { return false }
if isConnectionRequiredAndTransientFlagSet {
return false
}
if isRunningOnDevice {
if isOnWWANFlagSet && !reachableOnWWAN {
// We don't want to connect when on cellular connection
return false
}
}
return true
}
@available(*, deprecated: 4.0, message: "Please use `connection == .cellular`")
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
}
@available(*, deprecated: 4.0, message: "Please use `connection == .wifi`")
var isReachableViaWiFi: Bool {
// Check we're reachable
guard isReachableFlagSet else { return false }
// If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return true }
// Check we're NOT on WWAN
return !isOnWWANFlagSet
}
var description: String {
let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension AwesomeReachability {
func AwesomeReachabilityChanged() {
guard previousFlags != flags else { return }
let block = connection != .none ? whenReachable : whenUnreachable
DispatchQueue.main.async {
block?(self)
self.notificationCenter.post(name: .AwesomeReachabilityChanged, object:self)
}
previousFlags = flags
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return flags.contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return flags.contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return flags.contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return flags.contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return flags.contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return flags.contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return flags.contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return flags.contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return flags.contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return flags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var flags: SCNetworkReachabilityFlags {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(AwesomeReachabilityRef, &flags) {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
}
| 34.544343 | 125 | 0.663863 |
e07e553140003f3810704cd4391751db89e50f8e | 159 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(AsyncHTTPTests.allTests),
]
}
#endif
| 15.9 | 45 | 0.672956 |
efa18bbd7f81b287da85a355766c2d4aefd585af | 67,916 | //
// CoreTest.swift
//
// Created by Giles Payne on 2020/01/27.
//
import XCTest
import OpenCV
class CoreTest: OpenCVTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testAbsdiff() throws {
Core.absdiff(src1: gray128, src2: gray255, dst: dst)
try assertMatEqual(gray127, dst)
}
func testAddMatMatMat() throws {
Core.add(src1: gray128, src2: gray128, dst: dst)
try assertMatEqual(gray255, dst)
}
func testAddMatMatMatMatInt() throws {
Core.add(src1: gray0, src2: gray1, dst: dst, mask: gray1, dtype: CvType.CV_32F)
XCTAssertEqual(CvType.CV_32F, dst.depth())
try assertMatEqual(gray1_32f, dst, OpenCVTestCase.EPS)
}
func testAddWeightedMatDoubleMatDoubleDoubleMat() throws {
Core.addWeighted(src1: gray1, alpha: 120.0, src2: gray127, beta: 1.0, gamma: 10.0, dst: dst)
try assertMatEqual(gray255, dst)
}
func testAddWeightedMatDoubleMatDoubleDoubleMatInt() throws {
Core.addWeighted(src1: gray1, alpha: 126.0, src2: gray127, beta: 1.0, gamma: 2.0, dst: dst, dtype: CvType.CV_32F)
XCTAssertEqual(CvType.CV_32F, dst.depth())
try assertMatEqual(gray255_32f, dst, OpenCVTestCase.EPS)
}
func testBitwise_andMatMatMat() throws {
Core.bitwise_and(src1: gray127, src2: gray3, dst: dst)
try assertMatEqual(gray3, dst)
}
func testBitwise_andMatMatMatMat() throws {
Core.bitwise_and(src1: gray3, src2: gray1, dst: dst, mask: gray255)
try assertMatEqual(gray1, dst)
}
func testBitwise_notMatMat() throws {
Core.bitwise_not(src: gray255, dst: dst)
try assertMatEqual(gray0, dst)
}
func testBitwise_notMatMatMat() throws {
Core.bitwise_not(src: gray0, dst: dst, mask: gray1)
try assertMatEqual(gray255, dst)
}
func testBitwise_orMatMatMat() throws {
Core.bitwise_or(src1: gray1, src2: gray2, dst: dst)
try assertMatEqual(gray3, dst)
}
func testBitwise_orMatMatMatMat() throws {
Core.bitwise_or(src1: gray127, src2: gray3, dst: dst, mask: gray255)
try assertMatEqual(gray127, dst)
}
func testBitwise_xorMatMatMat() throws {
Core.bitwise_xor(src1: gray3, src2: gray2, dst: dst)
try assertMatEqual(gray1, dst)
}
func testBitwise_xorMatMatMatMat() throws {
Core.bitwise_or(src1: gray127, src2: gray128, dst: dst, mask: gray255)
try assertMatEqual(gray255, dst)
}
func testCalcCovarMatrixMatMatMatInt() throws {
let covar = Mat(rows: OpenCVTestCase.matSize, cols: OpenCVTestCase.matSize, type: CvType.CV_64FC1)
let mean = Mat(rows: 1, cols: OpenCVTestCase.matSize, type: CvType.CV_64FC1)
Core.calcCovarMatrix(samples: gray0_32f, covar: covar, mean: mean, flags: CovarFlags.COVAR_ROWS.rawValue | CovarFlags.COVAR_NORMAL.rawValue)
try assertMatEqual(gray0_64f, covar, OpenCVTestCase.EPS)
try assertMatEqual(gray0_64f_1d, mean, OpenCVTestCase.EPS)
}
func testCalcCovarMatrixMatMatMatIntInt() throws {
let covar = Mat(rows: OpenCVTestCase.matSize, cols: OpenCVTestCase.matSize, type: CvType.CV_32F)
let mean = Mat(rows: 1, cols: OpenCVTestCase.matSize, type: CvType.CV_32F)
Core.calcCovarMatrix(samples: gray0_32f, covar: covar, mean: mean, flags: CovarFlags.COVAR_ROWS.rawValue | CovarFlags.COVAR_NORMAL.rawValue, ctype: CvType.CV_32F)
try assertMatEqual(gray0_32f, covar, OpenCVTestCase.EPS)
try assertMatEqual(gray0_32f_1d, mean, OpenCVTestCase.EPS)
}
func testCartToPolarMatMatMatMat() throws {
let x = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try x.put(row: 0, col: 0, data: [3.0, 6.0, 5, 0] as [Float])
let y = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try y.put(row: 0, col: 0, data: [4.0, 8.0, 12.0] as [Float])
let dst_angle = Mat()
Core.cartToPolar(x: x, y: y, magnitude: dst, angle: dst_angle)
let expected_magnitude = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try expected_magnitude.put(row: 0, col: 0, data: [5.0, 10.0, 13.0] as [Float])
let expected_angle = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try expected_angle.put(row: 0, col: 0, data: [atan2rad(4,3), atan2rad(8,6), atan2rad(12,5)])
try assertMatEqual(expected_magnitude, dst, OpenCVTestCase.EPS)
try assertMatEqual(expected_angle, dst_angle, OpenCVTestCase.EPS)
}
func testCartToPolarMatMatMatMatBoolean() throws {
let x = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try x.put(row: 0, col: 0, data: [3.0, 6.0, 5, 0] as [Float])
let y = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try y.put(row: 0, col: 0, data: [4.0, 8.0, 12.0] as [Float])
let dst_angle = Mat()
Core.cartToPolar(x: x, y: y, magnitude: dst, angle: dst_angle, angleInDegrees: true)
let expected_magnitude = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try expected_magnitude.put(row: 0, col: 0, data: [5.0, 10.0, 13.0] as [Float])
let expected_angle = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try expected_angle.put(row: 0, col: 0, data:[atan2deg(4,3), atan2deg(8,6), atan2deg(12,5)])
try assertMatEqual(expected_magnitude, dst, OpenCVTestCase.EPS)
try assertMatEqual(expected_angle, dst_angle, OpenCVTestCase.EPS * 180/Double.pi)
}
func testCheckRangeMat() throws {
let outOfRange = Mat(rows: 2, cols: 2, type: CvType.CV_64F)
try outOfRange.put(row: 0, col: 0, data: [Double.nan, -Double.infinity, Double.infinity, 0])
XCTAssert(Core.checkRange(a: grayRnd_32f))
XCTAssert(Core.checkRange(a: Mat()))
XCTAssertFalse(Core.checkRange(a: outOfRange))
}
func testCheckRangeMatBooleanPointDoubleDouble() throws {
let inRange = Mat(rows: 2, cols: 3, type: CvType.CV_64F)
try inRange.put(row: 0, col: 0, data: [14, 48, 76, 33, 5, 99] as [Double])
XCTAssert(Core.checkRange(a: inRange, quiet: true, minVal: 5, maxVal: 100))
let outOfRange = Mat(rows: 2, cols: 3, type: CvType.CV_64F)
try inRange.put(row: 0, col: 0, data: [-4, 0, 6, 33, 4, 109] as [Double])
XCTAssertFalse(Core.checkRange(a: outOfRange, quiet: true, minVal: 5, maxVal: 100))
}
func testCompare() throws {
Core.compare(src1: gray0, src2: gray0, dst: dst, cmpop: .CMP_EQ)
try assertMatEqual(dst, gray255)
Core.compare(src1: gray0, src2: gray1, dst: dst, cmpop: .CMP_EQ)
try assertMatEqual(dst, gray0)
try grayRnd.put(row: 0, col: 0, data: [0, 0] as [Int8])
Core.compare(src1: gray0, src2: grayRnd, dst: dst, cmpop: .CMP_GE)
let expected = Int32(grayRnd.total()) - Core.countNonZero(src: grayRnd)
XCTAssertEqual(expected, Core.countNonZero(src: dst))
}
func testCompleteSymmMat() throws {
Core.completeSymm(m: grayRnd_32f)
try assertMatEqual(grayRnd_32f, grayRnd_32f.t(), OpenCVTestCase.EPS)
}
func testCompleteSymmMatBoolean() throws {
let grayRnd_32f2 = grayRnd_32f.clone()
Core.completeSymm(m: grayRnd_32f, lowerToUpper: true)
try assertMatEqual(grayRnd_32f, grayRnd_32f.t(), OpenCVTestCase.EPS)
Core.completeSymm(m: grayRnd_32f2, lowerToUpper: false)
try assertMatNotEqual(grayRnd_32f2, grayRnd_32f, OpenCVTestCase.EPS)
}
func testConvertScaleAbsMatMat() throws {
Core.convertScaleAbs(src: gray0, dst: dst)
try assertMatEqual(gray0, dst, OpenCVTestCase.EPS)
Core.convertScaleAbs(src: gray_16u_256, dst: dst)
try assertMatEqual(gray255, dst, OpenCVTestCase.EPS)
}
func testConvertScaleAbsMatMatDoubleDouble() throws {
Core.convertScaleAbs(src: gray_16u_256, dst: dst, alpha: 2, beta: -513)
try assertMatEqual(gray1, dst)
}
func testCountNonZero() throws {
XCTAssertEqual(0, Core.countNonZero(src: gray0))
let gray0copy = gray0.clone()
try gray0copy.put(row: 0, col: 0, data: [-1] as [Int8])
try gray0copy.put(row: gray0copy.rows() - 1, col: gray0copy.cols() - 1, data: [-1] as [Int8])
XCTAssertEqual(2, Core.countNonZero(src: gray0copy))
}
func testCubeRoot() {
let res:Float = Core.cubeRoot(val: -27.0)
XCTAssertEqual(-3.0, res)
}
func testDctMatMat() throws {
let m = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try m.put(row: 0, col: 0, data: [135.22211, 50.811096, 102.27016, 207.6682] as [Float])
let dst1 = Mat()
let dst2 = Mat()
Core.dct(src: gray0_32f_1d, dst: dst1)
Core.dct(src: m, dst: dst2)
truth = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try truth!.put(row: 0, col: 0, data: [247.98576, -61.252407, 94.904533, 14.013477] as [Float])
try assertMatEqual(gray0_32f_1d, dst1, OpenCVTestCase.EPS)
try assertMatEqual(truth!, dst2, OpenCVTestCase.EPS)
}
func testDctMatMatInt() throws {
let m = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try m.put(row: 0, col: 0, data: [247.98576, -61.252407, 94.904533, 14.013477] as [Float])
let dst1 = Mat()
let dst2 = Mat()
Core.dct(src: gray0_32f_1d, dst: dst1, flags:DftFlags.DCT_INVERSE.rawValue)
Core.dct(src: m, dst: dst2, flags:DftFlags.DCT_INVERSE.rawValue)
truth = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try truth!.put(row: 0, col: 0, data: [135.22211, 50.811096, 102.27016, 207.6682] as [Float])
try assertMatEqual(gray0_32f_1d, dst1, OpenCVTestCase.EPS)
try assertMatEqual(truth!, dst2, OpenCVTestCase.EPS)
}
func testDeterminant() throws {
let mat = Mat(rows: 2, cols: 2, type: CvType.CV_32F)
try mat.put(row: 0, col: 0, data: [4.0] as [Float])
try mat.put(row: 0, col: 1, data: [2.0] as [Float])
try mat.put(row: 1, col: 0, data: [4.0] as [Float])
try mat.put(row: 1, col: 1, data: [4.0] as [Float])
let det = Core.determinant(mtx: mat)
XCTAssertEqual(8.0, det)
}
func testDftMatMat() throws {
Core.dft(src: gray0_32f_1d, dst: dst)
try assertMatEqual(gray0_32f_1d, dst, OpenCVTestCase.EPS)
}
func testDftMatMatIntInt() throws {
let src1 = Mat(rows: 2, cols: 4, type: CvType.CV_32F)
try src1.put(row: 0, col: 0, data: [1, 2, 3, 4] as [Float])
try src1.put(row: 1, col: 0, data: [1, 1, 1, 1] as [Float])
let src2 = Mat(rows: 2, cols: 4, type: CvType.CV_32F)
try src2.put(row: 0, col: 0, data: [1, 2, 3, 4] as [Float])
try src2.put(row: 1, col: 0, data: [0, 0, 0, 0] as [Float])
let dst1 = Mat()
let dst2 = Mat()
Core.dft(src: src1, dst: dst1, flags: DftFlags.DFT_REAL_OUTPUT.rawValue, nonzeroRows: 1)
Core.dft(src: src2, dst: dst2, flags: DftFlags.DFT_REAL_OUTPUT.rawValue, nonzeroRows: 0)
try assertMatEqual(dst2, dst1, OpenCVTestCase.EPS)
}
func testDivideDoubleMatMat() throws {
Core.divide(scale: 4.0, src: gray2, dst: dst)
try assertMatEqual(gray2, dst)
Core.divide(scale: 4.0, src: gray0, dst: dst)
try assertMatEqual(gray0, dst)
}
func testDivideDoubleMatMatInt() throws {
Core.divide(scale: 9.0, src: gray3, dst: dst, dtype: CvType.CV_32F)
try assertMatEqual(gray3_32f, dst, OpenCVTestCase.EPS)
}
func testDivideMatMatMat() throws {
Core.divide(src1: gray9, src2: gray3, dst: dst)
try assertMatEqual(gray3, dst)
}
func testDivideMatMatMatDouble() throws {
Core.divide(src1: gray1, src2: gray2, dst: dst, scale: 6.0)
try assertMatEqual(gray3, dst)
}
func testDivideMatMatMatDoubleInt() throws {
Core.divide(src1: gray1, src2: gray2, dst: dst, scale: 6.0, dtype: CvType.CV_32F)
try assertMatEqual(gray3_32f, dst, OpenCVTestCase.EPS)
}
func testEigen() throws {
let src = Mat(rows: 3, cols: 3, type: CvType.CV_32FC1)
try src.put(row: 0, col: 0, data: [2, 0, 0] as [Float])
try src.put(row: 1, col: 0, data: [0, 6, 0] as [Float])
try src.put(row: 2, col: 0, data: [0, 0, 4] as [Float])
let eigenVals = Mat()
let eigenVecs = Mat()
Core.eigen(src: src, eigenvalues: eigenVals, eigenvectors: eigenVecs)
let expectedEigenVals = Mat(rows: 3, cols: 1, type: CvType.CV_32FC1)
try expectedEigenVals.put(row: 0, col: 0, data: [6, 4, 2] as [Float])
try assertMatEqual(eigenVals, expectedEigenVals, OpenCVTestCase.EPS)
// check by definition
let EPS = 1e-3
for i:Int32 in 0..<3 {
let vec = eigenVecs.row(i).t()
let lhs = Mat(rows: 3, cols: 1, type: CvType.CV_32FC1)
Core.gemm(src1: src, src2: vec, alpha: 1.0, src3: Mat(), beta: 1.0, dst: lhs)
let rhs = Mat(rows: 3, cols: 1, type: CvType.CV_32FC1)
Core.gemm(src1: vec, src2: eigenVals.row(i), alpha: 1.0, src3: Mat(), beta: 1.0, dst: rhs)
try assertMatEqual(lhs, rhs, EPS)
}
}
func testExp() throws {
Core.exp(src: gray0_32f, dst: dst)
try assertMatEqual(gray1_32f, dst, OpenCVTestCase.EPS)
}
func testExtractChannel() throws {
Core.extractChannel(src: rgba128, dst: dst, coi: 0)
try assertMatEqual(gray128, dst)
}
func testFastAtan2() {
let EPS: Float = 0.3
let res = Core.fastAtan2(y: 50, x: 50)
XCTAssertEqual(Float(45.0), res, accuracy:EPS)
let res2 = Core.fastAtan2(y: 80, x: 20)
XCTAssertEqual(atan2(80, 20) * 180 / Float.pi, res2, accuracy:EPS)
}
func testFillConvexPolyMatListOfPointScalar() {
let polyline = [Point(x: 1, y: 1), Point(x: 5, y: 0), Point(x: 6, y: 8), Point(x: 0, y: 9)]
dst = gray0.clone()
Imgproc.fillConvexPoly(img: dst, points: polyline, color: Scalar(150))
XCTAssert(0 < Core.countNonZero(src: dst))
XCTAssert(dst.total() > Core.countNonZero(src: dst))
}
func testFillConvexPolyMatListOfPointScalarIntInt() {
let polyline1 = [Point(x: 2, y: 1), Point(x: 5, y: 1), Point(x: 5, y: 7), Point(x: 2, y: 7)]
let polyline2 = [Point(x: 4, y: 2), Point(x: 10, y: 2), Point(x: 10, y: 14), Point(x: 4, y: 14)]
// current implementation of fixed-point version of fillConvexPoly
// requires image to be at least 2-pixel wider in each direction than
// contour
Imgproc.fillConvexPoly(img: gray0, points: polyline1, color: colorWhite, lineType: .LINE_8, shift: 0)
XCTAssert(0 < Core.countNonZero(src: gray0))
XCTAssert(gray0.total() > Core.countNonZero(src: gray0))
Imgproc.fillConvexPoly(img: gray0, points: polyline2, color: colorBlack, lineType: .LINE_8, shift: 1)
XCTAssertEqual(0, Core.countNonZero(src: gray0))
}
func testFillPolyMatListOfListOfPointScalar() throws {
let matSize = 10;
let gray0 = Mat.zeros(Int32(matSize), cols: Int32(matSize), type: CvType.CV_8U)
let polyline = [Point(x: 1, y: 4), Point(x: 1, y: 8), Point(x: 4, y: 1), Point(x: 7, y: 8), Point(x: 7, y: 4)]
let polylines = [polyline]
Imgproc.fillPoly(img: gray0, pts: polylines, color: Scalar(1))
let truth:[Int8] =
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 0, 0,
0, 1, 1, 0, 0, 0, 1, 1, 0, 0,
0, 1, 1, 0, 0, 0, 1, 1, 0, 0,
0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let truthMat = Mat(size: gray0.size(), type: CvType.CV_8U)
try truthMat.put(row:0, col:0, data:truth)
try assertMatEqual(truthMat, gray0)
}
func testFillPolyMatListOfListOfPointScalarIntIntPoint() {
let polyline1 = [Point(x: 1, y: 4), Point(x: 1, y: 8), Point(x: 4, y: 1), Point(x: 7, y: 8), Point(x: 7, y: 4)]
let polyline2 = [Point(x: 0, y: 3), Point(x: 0, y: 7), Point(x: 3, y: 0), Point(x: 6, y: 7), Point(x: 6, y: 3)]
let polylines1 = [polyline1]
let polylines2 = [polyline2]
Imgproc.fillPoly(img: gray0, pts: polylines1, color: Scalar(1), lineType: .LINE_8, shift: 0, offset: Point(x: 0, y: 0))
XCTAssert(0 < Core.countNonZero(src: gray0))
Imgproc.fillPoly(img: gray0, pts: polylines2, color: Scalar(0), lineType: .LINE_8, shift: 0, offset: Point(x: 1, y: 1))
XCTAssertEqual(0, Core.countNonZero(src: gray0))
}
func testFlip() throws {
let src = Mat(rows: 2, cols: 2, type: CvType.CV_32F)
try src.put(row: 0, col: 0, data: [1.0] as [Float])
try src.put(row: 0, col: 1, data: [2.0] as [Float])
try src.put(row: 1, col: 0, data: [3.0] as [Float])
try src.put(row: 1, col: 1, data: [4.0] as [Float])
let dst1 = Mat()
let dst2 = Mat()
Core.flip(src: src, dst: dst1, flipCode: 0)
Core.flip(src: src, dst: dst2, flipCode: 1)
let dst_f1 = Mat(rows: 2, cols: 2, type: CvType.CV_32F)
try dst_f1.put(row: 0, col: 0, data: [3.0] as [Float])
try dst_f1.put(row: 0, col: 1, data: [4.0] as [Float])
try dst_f1.put(row: 1, col: 0, data: [1.0] as [Float])
try dst_f1.put(row: 1, col: 1, data: [2.0] as [Float])
let dst_f2 = Mat(rows: 2, cols: 2, type: CvType.CV_32F)
try dst_f2.put(row: 0, col: 0, data: [2.0] as [Float])
try dst_f2.put(row: 0, col: 1, data: [1.0] as [Float])
try dst_f2.put(row: 1, col: 0, data: [4.0] as [Float])
try dst_f2.put(row: 1, col: 1, data: [3.0] as [Float])
try assertMatEqual(dst_f1, dst1, OpenCVTestCase.EPS)
try assertMatEqual(dst_f2, dst2, OpenCVTestCase.EPS)
}
func testGemmMatMatDoubleMatDoubleMat() throws {
let m1 = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1)
try m1.put(row: 0, col: 0, data: [1.0, 0.0] as [Float])
try m1.put(row: 1, col: 0, data: [1.0, 0.0] as [Float])
let m2 = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1)
try m2.put(row: 0, col: 0, data: [1.0, 0.0] as [Float])
try m2.put(row: 1, col: 0, data: [1.0, 0.0] as [Float])
let dmatrix = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1);
try dmatrix.put(row: 0, col: 0, data: [0.001, 0.001] as [Float])
try dmatrix.put(row: 1, col: 0, data: [0.001, 0.001] as [Float])
Core.gemm(src1: m1, src2: m2, alpha: 1.0, src3: dmatrix, beta: 1.0, dst: dst)
let expected = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1)
try expected.put(row: 0, col: 0, data: [1.001, 0.001] as [Float])
try expected.put(row: 1, col: 0, data: [1.001, 0.001] as [Float])
try assertMatEqual(expected, dst, OpenCVTestCase.EPS)
}
func testGemmMatMatDoubleMatDoubleMatInt() throws {
let m1 = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1)
try m1.put(row: 0, col: 0, data: [1.0, 0.0])
try m1.put(row: 1, col: 0, data: [1.0, 0.0])
let m2 = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1)
try m2.put(row: 0, col: 0, data: [1.0, 0.0])
try m2.put(row: 1, col: 0, data: [1.0, 0.0])
let dmatrix = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1)
try dmatrix.put(row: 0, col: 0, data: [0.001, 0.001])
try dmatrix.put(row: 1, col: 0, data: [0.001, 0.001])
Core.gemm(src1: m1, src2: m2, alpha: 1.0, src3: dmatrix, beta: 1.0, dst: dst, flags: GemmFlags.GEMM_1_T.rawValue)
let expected = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1)
try expected.put(row: 0, col: 0, data: [2.001, 0.001])
try expected.put(row: 1, col: 0, data: [0.001, 0.001])
try assertMatEqual(expected, dst, OpenCVTestCase.EPS)
}
func testGetCPUTickCount() {
let cpuCountStart = Core.getCPUTickCount()
Core.sum(src: gray255)
let actualTickCount = Core.getCPUTickCount()
let expectedTickCount = actualTickCount - cpuCountStart;
XCTAssert(expectedTickCount > 0)
}
func testGetNumberOfCPUs() {
let cpus = Core.getNumberOfCPUs()
XCTAssert(ProcessInfo().processorCount <= cpus)
}
func testGetOptimalDFTSize() {
XCTAssertEqual(1, Core.getOptimalDFTSize(vecsize: 0))
XCTAssertEqual(135, Core.getOptimalDFTSize(vecsize: 133))
XCTAssertEqual(15, Core.getOptimalDFTSize(vecsize: 13))
}
func testGetTickCount() {
let startCount = Core.getTickCount()
Core.divide(src1: gray2, src2: gray1, dst: dst)
let endCount = Core.getTickCount()
let count = endCount - startCount;
XCTAssert(count > 0)
}
func testGetTickFrequency() {
let freq1 = Core.getTickFrequency()
Core.divide(src1: gray2, src2: gray1, dst: dst)
let freq2 = Core.getTickFrequency()
XCTAssert(0 < freq1)
XCTAssertEqual(freq1, freq2)
}
func testHconcat() throws {
let mats = [Mat.eye(rows: 3, cols: 3, type: CvType.CV_8U), Mat.zeros(3, cols: 2, type: CvType.CV_8U)]
Core.hconcat(src: mats, dst: dst)
try assertMatEqual(Mat.eye(rows: 3, cols: 5, type: CvType.CV_8U), dst)
}
func testIdctMatMat() throws {
let mat = Mat(rows: 1, cols: 8, type: CvType.CV_32F)
try mat.put(row: 0, col: 0, data: [1.0, 2.0, 1.0, 0.0, 1.0, 2.0, 3.0, 1.0])
Core.idct(src: mat, dst: dst)
truth = Mat(rows: 1, cols: 8, type: CvType.CV_32F)
try truth!.put(row: 0, col: 0, data: [3.3769724, -1.6215782, 2.3608727, 0.20730907, -0.86502546, 0.028082132, -0.7673766, 0.10917115])
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testIdctMatMatInt() throws {
let mat = Mat(rows: 2, cols: 8, type: CvType.CV_32F)
try mat.put(row: 0, col: 0, data: [1.0, 2.0, 1.0, 0.0, 1.0, 2.0, 3.0, 1.0])
try mat.put(row: 1, col: 0, data: [1.0, 2.0, 1.0, 0.0, 1.0, 2.0, 3.0, 1.0])
Core.idct(src: mat, dst: dst, flags: DftFlags.DCT_ROWS.rawValue)
truth = Mat(rows: 2, cols: 8, type: CvType.CV_32F)
try truth!.put(row: 0, col: 0, data: [3.3769724, -1.6215782, 2.3608727, 0.20730907, -0.86502546, 0.028082132, -0.7673766, 0.10917115])
try truth!.put(row: 1, col: 0, data: [3.3769724, -1.6215782, 2.3608727, 0.20730907, -0.86502546, 0.028082132, -0.7673766, 0.10917115])
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testIdftMatMat() throws {
let mat = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try mat.put(row: 0, col: 0, data: [1.0, 2.0, 3.0, 4.0])
Core.idft(src: mat, dst: dst)
truth = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try truth!.put(row: 0, col: 0, data: [9, -9, 1, 3] as [Float])
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testIdftMatMatIntInt() throws {
let mat = Mat(rows: 2, cols: 4, type: CvType.CV_32F)
try mat.put(row: 0, col: 0, data: [1.0, 2.0, 3.0, 4.0] as [Float])
try mat.put(row: 1, col: 0, data: [1.0, 2.0, 3.0, 4.0] as [Float])
let dst = Mat()
Core.idft(src: mat, dst: dst, flags: DftFlags.DFT_REAL_OUTPUT.rawValue, nonzeroRows: 1)
truth = Mat(rows: 2, cols: 4, type: CvType.CV_32F)
try truth!.put(row: 0, col: 0, data: [18, -18, 2, 6] as [Float])
try truth!.put(row: 1, col: 0, data: [0, 0, 0, 0] as [Float])
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testInRange() throws {
let gray0copy = gray0.clone()
try gray0copy.put(row: 1, col: 1, data: [100, -105, -55] as [Int8])
Core.inRange(src: gray0copy, lowerb: Scalar(120), upperb: Scalar(160), dst: dst)
var vals = [Int8](repeating: 0, count: 3)
try dst.get(row: 1, col: 1, data: &vals)
XCTAssertEqual(0, vals[0])
XCTAssertEqual(-1, vals[1])
XCTAssertEqual(0, vals[2])
XCTAssertEqual(1, Core.countNonZero(src: dst))
}
func testInsertChannel() throws {
dst = rgba128.clone()
Core.insertChannel(src: gray0, dst: dst, coi: 0)
Core.insertChannel(src: gray0, dst: dst, coi: 1)
Core.insertChannel(src: gray0, dst: dst, coi: 2)
Core.insertChannel(src: gray0, dst: dst, coi: 3)
try assertMatEqual(rgba0, dst)
}
func testInvertMatMat() throws {
let src = Mat(rows: 2, cols: 2, type: CvType.CV_32F)
try src.put(row: 0, col: 0, data: [1.0] as [Float])
try src.put(row: 0, col: 1, data: [2.0] as [Float])
try src.put(row: 1, col: 0, data: [1.5] as [Float])
try src.put(row: 1, col: 1, data: [4.0] as [Float])
Core.invert(src: src, dst: dst)
truth = Mat(rows: 2, cols: 2, type: CvType.CV_32F)
try truth!.put(row: 0, col: 0, data: [4.0] as [Float])
try truth!.put(row: 0, col: 1, data: [-2.0] as [Float])
try truth!.put(row: 1, col: 0, data: [-1.5] as [Float])
try truth!.put(row: 1, col: 1, data: [1.0] as [Float])
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testInvertMatMatInt() throws {
let src = Mat.eye(rows: 3, cols: 3, type: CvType.CV_32FC1)
try src.put(row: 0, col: 2, data: [1] as [Float])
let cond = Core.invert(src: src, dst: dst, flags: DecompTypes.DECOMP_SVD.rawValue)
truth = Mat.eye(rows: 3, cols: 3, type: CvType.CV_32FC1)
try truth!.put(row: 0, col: 2, data: [-1] as [Float])
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
XCTAssertEqual(0.3819660544395447, cond, accuracy:OpenCVTestCase.EPS)
}
func testKmeansMatIntMatTermCriteriaIntInt() throws {
let data = Mat(rows: 4, cols: 5, type: CvType.CV_32FC1)
try data.put(row: 0, col: 0, data: [1, 2, 3, 4, 5] as [Float])
try data.put(row: 1, col: 0, data: [2, 3, 4, 5, 6] as [Float])
try data.put(row: 2, col: 0, data: [5, 4, 3, 2, 1] as [Float])
try data.put(row: 3, col: 0, data: [6, 5, 4, 3, 2] as [Float])
let criteria = TermCriteria(type: TermCriteria.eps, maxCount: 0, epsilon: OpenCVTestCase.EPS)
let labels = Mat()
Core.kmeans(data: data, K: 2, bestLabels: labels, criteria: criteria, attempts: 1, flags: KmeansFlags.KMEANS_PP_CENTERS.rawValue)
var first_center = [Int32](repeating: 0, count: 1)
try labels.get(row: 0, col: 0, data: &first_center)
let c1 = first_center[0]
let expected_labels = Mat(rows: 4, cols: 1, type: CvType.CV_32S)
try expected_labels.put(row: 0, col: 0, data: [c1, c1, 1 - c1, 1 - c1])
try assertMatEqual(expected_labels, labels)
}
func testKmeansMatIntMatTermCriteriaIntIntMat() throws {
let data = Mat(rows: 4, cols: 5, type: CvType.CV_32FC1)
try data.put(row: 0, col: 0, data: [1, 2, 3, 4, 5] as [Float])
try data.put(row: 1, col: 0, data: [2, 3, 4, 5, 6] as [Float])
try data.put(row: 2, col: 0, data: [5, 4, 3, 2, 1] as [Float])
try data.put(row: 3, col: 0, data: [6, 5, 4, 3, 2] as [Float])
let criteria = TermCriteria(type:TermCriteria.eps, maxCount: 0, epsilon: OpenCVTestCase.EPS)
let labels = Mat()
let centers = Mat()
Core.kmeans(data: data, K: 2, bestLabels: labels, criteria: criteria, attempts: 6, flags: KmeansFlags.KMEANS_RANDOM_CENTERS.rawValue, centers: centers)
var first_center = [Int32](repeating: 0, count: 1)
try labels.get(row: 0, col: 0, data: &first_center)
let c1 = first_center[0]
let expected_labels = Mat(rows: 4, cols: 1, type: CvType.CV_32S)
try expected_labels.put(row: 0, col: 0, data: [c1, c1, 1 - c1, 1 - c1])
let expected_centers = Mat(rows: 2, cols: 5, type: CvType.CV_32FC1)
try expected_centers.put(row: c1, col: 0, data: [1.5, 2.5, 3.5, 4.5, 5.5] as [Float])
try expected_centers.put(row: 1 - c1, col: 0, data: [5.5, 4.5, 3.5, 2.5, 1.5] as [Float])
try assertMatEqual(expected_labels, labels)
try assertMatEqual(expected_centers, centers, OpenCVTestCase.EPS)
}
func testLineMatPointPointScalar() {
let nPoints = min(gray0.cols(), gray0.rows())
let point1 = Point(x: 0, y: 0)
let point2 = Point(x: nPoints, y: nPoints)
let color = Scalar(255)
Imgproc.line(img: gray0, pt1: point1, pt2: point2, color: color)
XCTAssert(nPoints == Core.countNonZero(src: gray0))
}
func testLineMatPointPointScalarInt() {
let nPoints = min(gray0.cols(), gray0.rows())
let point1 = Point(x: 0, y: 0)
let point2 = Point(x: nPoints, y: nPoints)
Imgproc.line(img: gray0, pt1: point1, pt2: point2, color: colorWhite, thickness: 1)
XCTAssert(nPoints == Core.countNonZero(src: gray0))
}
func testLineMatPointPointScalarIntIntInt() {
let nPoints = min(gray0.cols(), gray0.rows())
let point1 = Point(x: 3, y: 4)
let point2 = Point(x: nPoints, y: nPoints)
let point1_4 = Point(x: 3 * 4, y: 4 * 4)
let point2_4 = Point(x: nPoints * 4, y: nPoints * 4)
Imgproc.line(img: gray0, pt1: point2, pt2: point1, color: colorWhite, thickness: 2, lineType: .LINE_8, shift: 0)
XCTAssertFalse(0 == Core.countNonZero(src: gray0))
Imgproc.line(img: gray0, pt1: point2_4, pt2: point1_4, color: colorBlack, thickness: 2, lineType: .LINE_8, shift: 2)
XCTAssertEqual(0, Core.countNonZero(src: gray0))
}
func testLog() throws {
let mat = Mat(rows: 1, cols: 4, type: CvType.CV_32FC1)
try mat.put(row: 0, col: 0, data: [1.0, 10.0, 100.0, 1000.0])
Core.log(src: mat, dst: dst)
let expected = Mat(rows: 1, cols: 4, type: CvType.CV_32FC1)
try expected.put(row: 0, col: 0, data: [0, 2.3025851, 4.6051702, 6.9077554])
try assertMatEqual(expected, dst, OpenCVTestCase.EPS)
}
func testLUTMatMatMat() throws {
let lut = Mat(rows: 1, cols: 256, type: CvType.CV_8UC1)
lut.setTo(scalar: Scalar(0))
Core.LUT(src: grayRnd, lut: lut, dst: dst)
try assertMatEqual(gray0, dst)
lut.setTo(scalar: Scalar(255))
Core.LUT(src: grayRnd, lut: lut, dst: dst)
try assertMatEqual(gray255, dst)
}
func testMagnitude() throws {
let x = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
let y = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try x.put(row: 0, col: 0, data: [3.0, 5.0, 9.0, 6.0])
try y.put(row: 0, col: 0, data: [4.0, 12.0, 40.0, 8.0])
Core.magnitude(x: x, y: y, magnitude: dst)
let out = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try out.put(row: 0, col: 0, data: [5.0, 13.0, 41.0, 10.0])
try assertMatEqual(out, dst, OpenCVTestCase.EPS)
Core.magnitude(x: gray0_32f, y: gray255_32f, magnitude: dst)
try assertMatEqual(gray255_32f, dst, OpenCVTestCase.EPS)
}
func testMahalanobis() {
Core.setRNGSeed(seed: 45)
let src = Mat(rows: OpenCVTestCase.matSize, cols: OpenCVTestCase.matSize, type: CvType.CV_32F)
Core.randu(dst: src, low: -128, high: 128)
var covar = Mat(rows: OpenCVTestCase.matSize, cols: OpenCVTestCase.matSize, type: CvType.CV_32F)
let mean = Mat(rows: 1, cols: OpenCVTestCase.matSize, type: CvType.CV_32F)
Core.calcCovarMatrix(samples: src, covar: covar, mean: mean, flags: CovarFlags.COVAR_ROWS.rawValue | CovarFlags.COVAR_NORMAL.rawValue, ctype: CvType.CV_32F)
covar = covar.inv()
let line1 = src.row(0)
let line2 = src.row(1)
var d = Core.Mahalanobis(v1: line1, v2: line1, icovar: covar)
XCTAssertEqual(0.0, d)
d = Core.Mahalanobis(v1: line1, v2: line2, icovar: covar)
XCTAssert(d > 0.0)
}
func testMax() throws {
Core.max(src1: gray0, src2: gray255, dst: dst)
try assertMatEqual(gray255, dst)
let x = Mat(rows: 1, cols: 1, type: CvType.CV_32F)
let y = Mat(rows: 1, cols: 1, type: CvType.CV_32F)
try x.put(row: 0, col: 0, data: [23.0])
try y.put(row: 0, col: 0, data: [4.0])
Core.max(src1: x, src2: y, dst: dst)
let truth = Mat(rows: 1, cols: 1, type: CvType.CV_32F)
try truth.put(row: 0, col: 0, data: [23.0])
try assertMatEqual(truth, dst, OpenCVTestCase.EPS)
}
func testMeanMat() {
let mean = Core.mean(src: makeMask(gray128))
assertScalarEqual(Scalar(64), mean, OpenCVTestCase.EPS)
}
func testMeanMatMat() {
let mask1 = makeMask(gray1.clone())
let mask2 = makeMask(gray0, vals: [1])
let mean1 = Core.mean(src: grayRnd, mask: mask1)
let mean2 = Core.mean(src: grayRnd, mask: mask2)
let mean = Core.mean(src: grayRnd, mask: gray1)
assertScalarEqual(mean, Scalar(0.5 * (mean1.val[0].doubleValue + mean2.val[0].doubleValue)), OpenCVTestCase.EPS)
}
func testMeanStdDevMatMatMat() {
let mean = DoubleVector()
let stddev = DoubleVector()
Core.meanStdDev(src: rgbLena, mean: mean, stddev: stddev)
let expectedMean = [105.3989906311035, 99.56269836425781, 179.7303047180176]
let expectedDev = [33.74205485167219, 52.8734582803278, 49.01569488056406]
assertArrayEquals(expectedMean as [NSNumber], mean.array as [NSNumber], OpenCVTestCase.EPS)
assertArrayEquals(expectedDev as [NSNumber], stddev.array as [NSNumber], OpenCVTestCase.EPS)
}
func testMeanStdDevMatMatMatMat() {
var submat = grayRnd.submat(rowStart: 0, rowEnd: grayRnd.rows() / 2, colStart: 0, colEnd: grayRnd.cols() / 2)
submat.setTo(scalar: Scalar(33))
let mask = gray0.clone()
submat = mask.submat(rowStart: 0, rowEnd: mask.rows() / 2, colStart: 0, colEnd: mask.cols() / 2)
submat.setTo(scalar: Scalar(1))
let mean = DoubleVector()
let stddev = DoubleVector()
Core.meanStdDev(src: grayRnd, mean: mean, stddev: stddev, mask: mask)
let expectedMean = [33]
let expectedDev = [0]
assertArrayEquals(expectedMean as [NSNumber], mean.array as [NSNumber], OpenCVTestCase.EPS)
assertArrayEquals(expectedDev as [NSNumber], stddev.array as [NSNumber], OpenCVTestCase.EPS)
}
func testMerge() throws {
let src1 = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1, scalar: Scalar(1))
let src2 = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1, scalar: Scalar(2))
let src3 = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1, scalar: Scalar(3))
let srcArray = [src1, src2, src3]
Core.merge(mv: srcArray, dst: dst)
truth = Mat(rows: 2, cols: 2, type: CvType.CV_32FC3, scalar: Scalar(1, 2, 3))
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testMin() throws {
Core.min(src1: gray0, src2: gray255, dst: dst)
try assertMatEqual(gray0, dst)
}
func testMinMaxLocMat() throws {
let minVal:Double = 1
let maxVal:Double = 10
let minLoc = Point(x: gray3.cols() / 4, y: gray3.rows() / 2)
let maxLoc = Point(x: gray3.cols() / 2, y: gray3.rows() / 4)
let gray3copy = gray3.clone()
try gray3copy.put(row: minLoc.y, col: minLoc.x, data: [minVal])
try gray3copy.put(row: maxLoc.y, col: maxLoc.x, data: [maxVal])
let mmres = Core.minMaxLoc(gray3copy)
XCTAssertEqual(minVal, mmres.minVal)
XCTAssertEqual(maxVal, mmres.maxVal)
assertPointEquals(minLoc, mmres.minLoc)
assertPointEquals(maxLoc, mmres.maxLoc)
}
func testMinMaxLocMatMat() throws {
let src = Mat(rows: 4, cols: 4, type: CvType.CV_8U)
try src.put(row: 0, col: 0, data: [2, 4, 27, 3] as [Int8])
try src.put(row: 1, col: 0, data: [0, 8, 7, -126] as [Int8])
try src.put(row: 2, col: 0, data: [13, 4, 13, 4] as [Int8])
try src.put(row: 3, col: 0, data: [6, 4, 2, 13] as [Int8])
let mask = Mat(rows: 4, cols: 4, type: CvType.CV_8U, scalar: Scalar(0))
mask.submat(rowStart: 1, rowEnd: 3, colStart: 1, colEnd: 4).setTo(scalar: Scalar(1))
let res = Core.minMaxLoc(src, mask: mask)
XCTAssertEqual(4.0, res.minVal)
XCTAssertEqual(130.0, res.maxVal)
assertPointEquals(Point(x: 1, y: 2), res.minLoc)
assertPointEquals(Point(x: 3, y: 1), res.maxLoc)
}
func testMixChannels() throws {
let rgba0Copy = rgba0.clone()
rgba0Copy.setTo(scalar: Scalar(10, 20, 30, 40))
let src = [rgba0Copy]
let dst = [gray3, gray2, gray1, gray0, getMat(CvType.CV_8UC3, vals: [0, 0, 0])]
let fromTo = IntVector([
3, 0,
3, 1,
2, 2,
0, 3,
2, 4,
1, 5,
0, 6])
Core.mixChannels(src: src, dst: dst, fromTo: fromTo)
try assertMatEqual(getMat(CvType.CV_8U, vals: [40]), dst[0])
try assertMatEqual(getMat(CvType.CV_8U, vals: [40]), dst[1])
try assertMatEqual(getMat(CvType.CV_8U, vals: [30]), dst[2])
try assertMatEqual(getMat(CvType.CV_8U, vals: [10]), dst[3])
try assertMatEqual(getMat(CvType.CV_8UC3, vals: [30, 20, 10]), dst[4])
}
func testMulSpectrumsMatMatMatInt() throws {
let src1 = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try src1.put(row: 0, col: 0, data: [1.0, 2.0, 3.0, 4.0])
let src2 = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try src2.put(row: 0, col: 0, data: [1.0, 2.0, 3.0, 4.0])
Core.mulSpectrums(a: src1, b: src2, c: dst, flags: DftFlags.DFT_ROWS.rawValue)
let expected = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try expected.put(row: 0, col: 0, data: [1, -5, 12, 16] as [Float])
try assertMatEqual(expected, dst, OpenCVTestCase.EPS)
}
func testMulSpectrumsMatMatMatIntBoolean() throws {
let src1 = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try src1.put(row: 0, col: 0, data: [1.0, 2.0, 3.0, 4.0])
let src2 = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try src2.put(row: 0, col: 0, data: [1.0, 2.0, 3.0, 4.0])
Core.mulSpectrums(a: src1, b: src2, c: dst, flags: DftFlags.DFT_ROWS.rawValue, conjB: true)
let expected = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try expected.put(row: 0, col: 0, data: [1, 13, 0, 16] as [Float])
try assertMatEqual(expected, dst, OpenCVTestCase.EPS)
}
func testMultiplyMatMatMat() throws {
Core.multiply(src1: gray0, src2: gray255, dst: dst)
try assertMatEqual(gray0, dst)
}
func testMultiplyMatMatMatDouble() throws {
Core.multiply(src1: gray1, src2: gray1, dst: dst, scale: 2.0)
try assertMatEqual(gray2, dst)
}
func testMultiplyMatMatMatDoubleInt() throws {
Core.multiply(src1: gray1, src2: gray2, dst: dst, scale: 1.5, dtype: CvType.CV_32F)
try assertMatEqual(gray3_32f, dst, OpenCVTestCase.EPS)
}
func testMulTransposedMatMatBoolean() throws {
Core.mulTransposed(src: grayE_32f, dst: dst, aTa: true)
try assertMatEqual(grayE_32f, dst, OpenCVTestCase.EPS)
}
func testMulTransposedMatMatBooleanMatDouble() throws {
Core.mulTransposed(src: grayE_32f, dst: dst, aTa: true, delta: gray0_32f, scale: 2)
truth = gray0_32f;
truth!.diag().setTo(scalar: Scalar(2))
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testMulTransposedMatMatBooleanMatDoubleInt() throws {
let a = getMat(CvType.CV_32F, vals: [1])
Core.mulTransposed(src: a, dst: dst, aTa: true, delta: gray0_32f, scale: 3, dtype: CvType.CV_64F)
try assertMatEqual(getMat(CvType.CV_64F, vals: [3 * a.rows()] as [NSNumber]), dst, OpenCVTestCase.EPS)
}
func testNormalizeMatMat() throws {
let m = gray0.clone()
m.diag().setTo(scalar: Scalar(2))
Core.normalize(src: m, dst: dst)
try assertMatEqual(gray0, dst)
}
func testNormalizeMatMatDoubleDoubleInt() throws {
let src = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try src.put(row: 0, col: 0, data: [1.0, 2.0, 3.0, 4.0])
Core.normalize(src: src, dst: dst, alpha: 1.0, beta: 2.0, norm_type: .NORM_INF)
let expected = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try expected.put(row: 0, col: 0, data: [0.25, 0.5, 0.75, 1])
try assertMatEqual(expected, dst, OpenCVTestCase.EPS)
}
func testNormalizeMatMatDoubleDoubleIntInt() throws {
let src = Mat(rows: 1, cols: 5, type: CvType.CV_32F)
try src.put(row: 0, col: 0, data: [0, 1, 2, 3, 4] as [Float])
Core.normalize(src: src, dst: dst, alpha: 1, beta: 2, norm_type: .NORM_MINMAX, dtype: CvType.CV_64F)
let expected = Mat(rows: 1, cols: 5, type: CvType.CV_64F)
try expected.put(row: 0, col: 0, data: [1, 1.25, 1.5, 1.75, 2])
try assertMatEqual(expected, dst, OpenCVTestCase.EPS)
}
func testNormalizeMatMatDoubleDoubleIntIntMat() throws {
let src = Mat(rows: 1, cols: 5, type: CvType.CV_32F)
try src.put(row: 0, col: 0, data: [0, 1, 2, 3, 4] as [Float])
let mask = Mat(rows: 1, cols: 5, type: CvType.CV_8U)
try mask.put(row: 0, col: 0, data: [1, 0, 0, 0, 1] as [Int8])
dst = src.clone()
Core.normalize(src: src, dst: dst, alpha: 1, beta: 2, norm_type: .NORM_MINMAX, dtype: CvType.CV_32F, mask: mask)
let expected = Mat(rows: 1, cols: 5, type: CvType.CV_32F)
try expected.put(row: 0, col: 0, data: [1, 1, 2, 3, 2] as [Float])
try assertMatEqual(expected, dst, OpenCVTestCase.EPS)
}
func testNormMat() throws {
let n = Core.norm(src1: gray1)
XCTAssertEqual(10, n)
}
func testNormMatInt() throws {
let n = Core.norm(src1: gray127, normType: .NORM_INF)
XCTAssertEqual(127, n)
}
func testNormMatIntMat() throws {
let n = Core.norm(src1: gray3, normType: .NORM_L1, mask: gray0)
XCTAssertEqual(0.0, n)
}
func testNormMatMat() throws {
let n = Core.norm(src1: gray0, src2: gray1)
XCTAssertEqual(10.0, n)
}
func testNormMatMatInt() throws {
let n = Core.norm(src1: gray127, src2: gray1, normType: .NORM_INF)
XCTAssertEqual(126.0, n)
}
func testNormMatMatIntMat() throws {
let n = Core.norm(src1: gray3, src2: gray0, normType: .NORM_L1, mask: makeMask(gray0.clone(), vals: [1]))
XCTAssertEqual(150.0, n)
}
func testPCABackProject() throws {
let mean = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try mean.put(row: 0, col: 0, data: [2, 4, 4, 8] as [Float])
let vectors = Mat(rows: 1, cols: 4, type: CvType.CV_32F, scalar: Scalar(0))
try vectors.put(row: 0, col: 0, data: [0.2, 0.4, 0.4, 0.8])
let data = Mat(rows: 3, cols: 1, type: CvType.CV_32F)
try data.put(row: 0, col: 0, data: [-5, 0, -10] as [Float])
let result = Mat()
Core.PCABackProject(data: data, mean: mean, eigenvectors: vectors, result: result)
let truth = Mat(rows: 3, cols: 4, type: CvType.CV_32F)
try truth.put(row: 0, col: 0, data: [1, 2, 2, 4] as [Float])
try truth.put(row: 1, col: 0, data: [2, 4, 4, 8] as [Float])
try truth.put(row: 2, col: 0, data: [0, 0, 0, 0] as [Float])
try assertMatEqual(truth, result, OpenCVTestCase.EPS)
}
func testPCAComputeMatMatMat() throws {
let data = Mat(rows: 3, cols: 4, type: CvType.CV_32F)
try data.put(row: 0, col: 0, data: [1, 2, 2, 4] as [Float])
try data.put(row: 1, col: 0, data: [2, 4, 4, 8] as [Float])
try data.put(row: 2, col: 0, data: [3, 6, 6, 12] as [Float])
let mean = Mat()
let vectors = Mat()
Core.PCACompute(data: data, mean: mean, eigenvectors: vectors)
let mean_truth = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try mean_truth.put(row: 0, col: 0, data: [2, 4, 4, 8] as [Float])
let vectors_truth = Mat(rows: 3, cols: 4, type: CvType.CV_32F, scalar: Scalar(0))
try vectors_truth.put(row: 0, col: 0, data: [0.2, 0.4, 0.4, 0.8] as [Float])
try assertMatEqual(mean_truth, mean, OpenCVTestCase.EPS)
// eigenvectors are normalized (length = 1),
// but direction is unknown (v and -v are both eigen vectors)
// so this direct check doesn't work:
// try assertMatEqual(vectors_truth, vectors, OpenCVTestCase.EPS)
for i in 0..<1 {
let vec0 = vectors_truth.row(Int32(i))
let vec1 = vectors.row(Int32(i))
let vec1_ = Mat()
Core.subtract(src1: Mat(rows: 1, cols: 4, type: CvType.CV_32F, scalar: Scalar(0)), src2: vec1, dst: vec1_)
let scale1 = Core.norm(src1: vec0, src2: vec1)
let scale2 = Core.norm(src1: vec0, src2: vec1_)
XCTAssert(min(scale1, scale2) < OpenCVTestCase.EPS)
}
}
func testPCAComputeMatMatMatInt() throws {
let data = Mat(rows: 3, cols: 4, type: CvType.CV_32F)
try data.put(row: 0, col: 0, data: [1, 2, 2, 4] as [Float])
try data.put(row: 1, col: 0, data: [2, 4, 4, 8] as [Float])
try data.put(row: 2, col: 0, data: [3, 6, 6, 12] as [Float])
let mean = Mat()
let vectors = Mat()
Core.PCACompute(data:data, mean:mean, eigenvectors:vectors, maxComponents:1)
let mean_truth = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try mean_truth.put(row: 0, col: 0, data: [2, 4, 4, 8] as [Float])
let vectors_truth = Mat(rows: 1, cols: 4, type: CvType.CV_32F, scalar: Scalar(0))
try vectors_truth.put(row: 0, col: 0, data: [0.2, 0.4, 0.4, 0.8] as [Float])
try assertMatEqual(mean_truth, mean, OpenCVTestCase.EPS)
// eigenvectors are normalized (length = 1),
// but direction is unknown (v and -v are both eigen vectors)
// so this direct check doesn't work:
// try assertMatEqual(vectors_truth, vectors, OpenCVTestCase.EPS)
for i in 0..<1 {
let vec0 = vectors_truth.row(Int32(i))
let vec1 = vectors.row(Int32(i))
let vec1_ = Mat()
Core.subtract(src1: Mat(rows: 1, cols: 4, type: CvType.CV_32F, scalar: Scalar(0)), src2: vec1, dst: vec1_)
let scale1 = Core.norm(src1: vec0, src2: vec1)
let scale2 = Core.norm(src1: vec0, src2: vec1_)
XCTAssert(min(scale1, scale2) < OpenCVTestCase.EPS)
}
}
func testPCAProject() throws {
let mean = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try mean.put(row: 0, col: 0, data: [2, 4, 4, 8] as [Float])
let vectors = Mat(rows: 1, cols: 4, type: CvType.CV_32F, scalar: Scalar(0))
try vectors.put(row: 0, col: 0, data: [0.2, 0.4, 0.4, 0.8] as [Float])
let data = Mat(rows: 3, cols: 4, type: CvType.CV_32F)
try data.put(row: 0, col: 0, data: [1, 2, 2, 4] as [Float])
try data.put(row: 1, col: 0, data: [2, 4, 4, 8] as [Float])
try data.put(row: 2, col: 0, data: [0, 0, 0, 0] as [Float])
let result = Mat()
Core.PCAProject(data: data, mean: mean, eigenvectors: vectors, result: result)
let truth = Mat(rows: 3, cols: 1, type: CvType.CV_32F)
try truth.put(row: 0, col: 0, data: [-5, 0, -10] as [Float])
try assertMatEqual(truth, result, OpenCVTestCase.EPS)
}
func testPerspectiveTransform() throws {
let src = Mat(rows: OpenCVTestCase.matSize, cols: OpenCVTestCase.matSize, type: CvType.CV_32FC2)
Core.randu(dst: src, low: 0, high: 256)
let transformMatrix = Mat.eye(rows: 3, cols: 3, type: CvType.CV_32F)
Core.perspectiveTransform(src: src, dst: dst, m: transformMatrix)
try assertMatEqual(src, dst, OpenCVTestCase.EPS)
}
func testPerspectiveTransform3D() throws {
let src = Mat(rows: OpenCVTestCase.matSize, cols: OpenCVTestCase.matSize, type: CvType.CV_32FC3)
Core.randu(dst: src, low: 0, high: 256)
let transformMatrix = Mat.eye(rows: 4, cols: 4, type: CvType.CV_32F)
Core.perspectiveTransform(src: src, dst: dst, m: transformMatrix)
try assertMatEqual(src, dst, OpenCVTestCase.EPS)
}
func testPhaseMatMatMat() throws {
let x = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try x.put(row: 0, col: 0, data: [10.0, 10.0, 20.0, 5.0] as [Float])
let y = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try y.put(row: 0, col: 0, data: [20.0, 15.0, 20.0, 20.0] as [Float])
let gold = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try gold.put(row: 0, col: 0, data: [atan2rad(20, 10), atan2rad(15, 10), atan2rad(20, 20), atan2rad(20, 5)])
Core.phase(x: x, y: y, angle: dst)
try assertMatEqual(gold, dst, OpenCVTestCase.EPS)
}
func testPhaseMatMatMatBoolean() throws {
let x = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try x.put(row: 0, col: 0, data: [10.0, 10.0, 20.0, 5.0] as [Float])
let y = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try y.put(row: 0, col: 0, data: [20.0, 15.0, 20.0, 20.0] as [Float])
let gold = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try gold.put(row: 0, col: 0, data: [atan2deg(20, 10), atan2deg(15, 10), atan2deg(20, 20), atan2deg(20, 5)])
Core.phase(x: x, y: y, angle: dst, angleInDegrees: true)
try assertMatEqual(gold, dst, OpenCVTestCase.EPS * 180 / Double.pi)
}
func testPolarToCartMatMatMatMat() throws {
let magnitude = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try magnitude.put(row: 0, col: 0, data: [5.0, 10.0, 13.0])
let angle = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try angle.put(row: 0, col: 0, data: [0.92729962, 0.92729962, 1.1759995])
let xCoordinate = Mat()
let yCoordinate = Mat()
Core.polarToCart(magnitude: magnitude, angle: angle, x: xCoordinate, y: yCoordinate)
let x = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try x.put(row: 0, col: 0, data: [3.0, 6.0, 5, 0])
let y = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try y.put(row: 0, col: 0, data: [4.0, 8.0, 12.0])
try assertMatEqual(x, xCoordinate, OpenCVTestCase.EPS)
try assertMatEqual(y, yCoordinate, OpenCVTestCase.EPS)
}
func testPolarToCartMatMatMatMatBoolean() throws {
let magnitude = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try magnitude.put(row: 0, col: 0, data: [5.0, 10.0, 13.0])
let angle = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try angle.put(row: 0, col: 0, data: [0.92729962, 0.92729962, 1.1759995])
let xCoordinate = Mat()
let yCoordinate = Mat()
Core.polarToCart(magnitude: magnitude, angle: angle, x: xCoordinate, y: yCoordinate, angleInDegrees: true)
let x = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try x.put(row: 0, col: 0, data: [4.9993458, 9.9986916, 12.997262])
let y = Mat(rows: 1, cols: 3, type: CvType.CV_32F)
try y.put(row: 0, col: 0, data: [0.080918625, 0.16183725, 0.26680708])
try assertMatEqual(x, xCoordinate, OpenCVTestCase.EPS)
try assertMatEqual(y, yCoordinate, OpenCVTestCase.EPS)
}
func testPow() throws {
Core.pow(src: gray2, power: 7, dst: dst)
try assertMatEqual(gray128, dst)
}
func testRandn() {
Core.randn(dst: gray0, mean: 100, stddev: 23)
XCTAssertEqual(100, Core.mean(src: gray0).val[0] as! Double, accuracy:23 / 2)
}
func testRandShuffleMat() throws {
let original = Mat(rows: 1, cols: 10, type: CvType.CV_32F)
try original.put(row: 0, col: 0, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] as [Float])
let shuffled = original.clone()
Core.randShuffle(dst: shuffled)
try assertMatNotEqual(original, shuffled, OpenCVTestCase.EPS)
let dst1 = Mat()
let dst2 = Mat()
Core.sort(src: original, dst: dst1, flags: SortFlags.SORT_ASCENDING.rawValue)
Core.sort(src: shuffled, dst: dst2, flags: SortFlags.SORT_ASCENDING.rawValue)
try assertMatEqual(dst1, dst2, OpenCVTestCase.EPS)
}
func testRandShuffleMatDouble() throws {
let original = Mat(rows: 1, cols: 10, type: CvType.CV_32F)
try original.put(row: 0, col: 0, data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] as [Float])
let shuffled = original.clone()
Core.randShuffle(dst: shuffled, iterFactor: 10)
try assertMatNotEqual(original, shuffled, OpenCVTestCase.EPS)
let dst1 = Mat()
let dst2 = Mat()
Core.sort(src: original, dst: dst1, flags: SortFlags.SORT_ASCENDING.rawValue)
Core.sort(src: shuffled, dst: dst2, flags: SortFlags.SORT_ASCENDING.rawValue)
try assertMatEqual(dst1, dst2, OpenCVTestCase.EPS)
}
func testRandu() {
Core.randu(dst: gray0, low: 3, high: 23)
XCTAssert(Core.checkRange(a: gray0, quiet: true, minVal: 3, maxVal: 23))
}
func testRectangleMatPointPointScalar() {
let bottomRight = Point(x: gray0.cols() / 2, y: gray0.rows() / 2)
let topLeft = Point(x: 0, y: 0)
let color = Scalar(128)
Imgproc.rectangle(img: gray0, pt1: bottomRight, pt2: topLeft, color: color)
XCTAssert(0 != Core.countNonZero(src: gray0))
}
func testRectangleMatPointPointScalarInt() {
let bottomRight = Point(x: gray0.cols(), y: gray0.rows())
let topLeft = Point(x: 0, y: 0)
let color = Scalar(128)
Imgproc.rectangle(img: gray0, pt1: bottomRight, pt2: topLeft, color: color, thickness: 2)
Imgproc.rectangle(img: gray0, pt1: bottomRight, pt2: topLeft, color: colorBlack)
XCTAssert(0 != Core.countNonZero(src: gray0))
}
func testRectangleMatPointPointScalarIntInt() {
let bottomRight = Point(x: gray0.cols() / 2, y: gray0.rows() / 2)
let topLeft = Point(x: 0, y: 0)
let color = Scalar(128)
Imgproc.rectangle(img: gray0, pt1: bottomRight, pt2: topLeft, color: color, thickness: 2, lineType: .LINE_AA, shift: 0)
Imgproc.rectangle(img: gray0, pt1: bottomRight, pt2: topLeft, color: colorBlack, thickness: 2, lineType: .LINE_4, shift: 0)
XCTAssert(0 != Core.countNonZero(src: gray0))
}
func testRectangleMatPointPointScalarIntIntInt() {
let bottomRight1 = Point(x: gray0.cols(), y: gray0.rows())
let bottomRight2 = Point(x: gray0.cols() / 2, y: gray0.rows() / 2)
let topLeft = Point(x: 0, y: 0)
let color = Scalar(128)
Imgproc.rectangle(img: gray0, pt1: bottomRight1, pt2: topLeft, color: color, thickness: 2, lineType: .LINE_8, shift: 1)
XCTAssert(0 != Core.countNonZero(src: gray0))
Imgproc.rectangle(img: gray0, pt1: bottomRight2, pt2: topLeft, color: colorBlack, thickness: 2, lineType: .LINE_8, shift: 0)
XCTAssertEqual(0, Core.countNonZero(src: gray0))
}
func testReduceMatMatIntInt() throws {
let src = Mat(rows: 2, cols: 2, type: CvType.CV_32F)
try src.put(row: 0, col: 0, data: [1, 0] as [Float])
try src.put(row: 1, col: 0, data: [3, 0] as [Float])
Core.reduce(src: src, dst: dst, dim: 0, rtype: Int32(Core.REDUCE_AVG))
let out = Mat(rows: 1, cols: 2, type: CvType.CV_32F)
try out.put(row: 0, col: 0, data: [2, 0] as [Float])
try assertMatEqual(out, dst, OpenCVTestCase.EPS)
}
func testReduceMatMatIntIntInt() throws {
let src = Mat(rows: 2, cols: 2, type: CvType.CV_32F)
try src.put(row: 0, col: 0, data: [1, 0] as [Float])
try src.put(row: 1, col: 0, data: [2, 3] as [Float])
Core.reduce(src: src, dst: dst, dim: 1, rtype: Int32(Core.REDUCE_SUM), dtype: CvType.CV_64F)
let out = Mat(rows: 2, cols: 1, type: CvType.CV_64F)
try out.put(row: 0, col: 0, data: [1, 5] as [Double])
try assertMatEqual(out, dst, OpenCVTestCase.EPS)
}
func testRepeat() throws {
let src = Mat(rows: 1, cols: 2, type: CvType.CV_32F, scalar: Scalar(0))
Core.repeat(src: src, ny: OpenCVTestCase.matSize, nx: OpenCVTestCase.matSize / 2, dst: dst)
try assertMatEqual(gray0_32f, dst, OpenCVTestCase.EPS)
}
func testScaleAdd() throws {
Core.scaleAdd(src1: gray3, alpha: 2.0, src2: gray3, dst: dst)
try assertMatEqual(gray9, dst)
}
func testSetIdentityMat() throws {
Core.setIdentity(mtx: gray0_32f)
try assertMatEqual(grayE_32f, gray0_32f, OpenCVTestCase.EPS)
}
func testSetIdentityMatScalar() throws {
let m = gray0_32f;
Core.setIdentity(mtx: m, s: Scalar(5))
truth = Mat(size: m.size(), type: m.type(), scalar: Scalar(0))
truth!.diag().setTo(scalar: Scalar(5))
try assertMatEqual(truth!, m, OpenCVTestCase.EPS)
}
func testSolveCubic() throws {
let coeffs = Mat(rows: 1, cols: 4, type: CvType.CV_32F)
try coeffs.put(row: 0, col: 0, data: [1, 6, 11, 6] as [Float])
XCTAssertEqual(3, Core.solveCubic(coeffs: coeffs, roots: dst))
let roots = Mat(rows: 3, cols: 1, type: CvType.CV_32F)
try roots.put(row: 0, col: 0, data: [-3, -1, -2] as [Float])
try assertMatEqual(roots, dst, OpenCVTestCase.EPS)
}
func testSolveMatMatMat() throws {
let a = Mat(rows: 3, cols: 3, type: CvType.CV_32F)
try a.put(row: 0, col: 0, data: [1, 1, 1] as [Float])
try a.put(row: 1, col: 0, data: [1, -2, 2] as [Float])
try a.put(row: 2, col: 0, data: [1, 2, 1] as [Float])
let b = Mat(rows: 3, cols: 1, type: CvType.CV_32F)
try b.put(row: 0, col: 0, data: [0, 4, 2] as [Float])
XCTAssert(Core.solve(src1: a, src2: b, dst: dst))
let res = Mat(rows: 3, cols: 1, type: CvType.CV_32F)
try res.put(row: 0, col: 0, data: [-12, 2, 10] as [Float])
try assertMatEqual(res, dst, OpenCVTestCase.EPS)
}
func testSolveMatMatMatInt() throws {
let a = Mat(rows: 3, cols: 3, type: CvType.CV_32F)
try a.put(row: 0, col: 0, data: [1, 1, 1] as [Float])
try a.put(row: 1, col: 0, data: [1, -2, 2] as [Float])
try a.put(row: 2, col: 0, data: [1, 2, 1] as [Float])
let b = Mat(rows: 3, cols: 1, type: CvType.CV_32F)
try b.put(row: 0, col: 0, data: [0, 4, 2] as [Float])
XCTAssert(Core.solve(src1: a, src2: b, dst: dst, flags: DecompTypes.DECOMP_QR.rawValue | DecompTypes.DECOMP_NORMAL.rawValue))
let res = Mat(rows: 3, cols: 1, type: CvType.CV_32F)
try res.put(row: 0, col: 0, data: [-12, 2, 10] as [Float])
try assertMatEqual(res, dst, OpenCVTestCase.EPS)
}
func testSolvePolyMatMat() throws {
let coeffs = Mat(rows: 4, cols: 1, type: CvType.CV_32F)
try coeffs.put(row: 0, col: 0, data: [-6, 11, -6, 1] as [Float])
let roots = Mat()
XCTAssertGreaterThanOrEqual(1e-6, abs(Core.solvePoly(coeffs: coeffs, roots: roots)))
truth = Mat(rows: 3, cols: 1, type: CvType.CV_32FC2)
try truth!.put(row: 0, col: 0, data: [1, 0, 2, 0, 3, 0] as [Float])
try assertMatEqual(truth!, roots, OpenCVTestCase.EPS)
}
func testSolvePolyMatMatInt() throws {
let coeffs = Mat(rows: 4, cols: 1, type: CvType.CV_32F)
try coeffs.put(row: 0, col: 0, data: [-6, 11, -6, 1] as [Float])
let roots = Mat()
XCTAssertEqual(10.198039027185569, Core.solvePoly(coeffs: coeffs, roots: roots, maxIters: 1))
truth = Mat(rows: 3, cols: 1, type: CvType.CV_32FC2)
try truth!.put(row: 0, col: 0, data: [1, 0, -1, 2, -2, 12] as [Float])
try assertMatEqual(truth!, roots, OpenCVTestCase.EPS)
}
func testSort() {
var submat = gray0.submat(rowStart: 0, rowEnd: gray0.rows() / 2, colStart: 0, colEnd: gray0.cols() / 2)
submat.setTo(scalar: Scalar(1.0))
Core.sort(src: gray0, dst: dst, flags: SortFlags.SORT_EVERY_ROW.rawValue)
submat = dst.submat(rowStart: 0, rowEnd: dst.rows() / 2, colStart: dst.cols() / 2, colEnd: dst.cols())
XCTAssert(submat.total() == Core.countNonZero(src: submat))
Core.sort(src: gray0, dst: dst, flags: SortFlags.SORT_EVERY_COLUMN.rawValue)
submat = dst.submat(rowStart: dst.rows() / 2, rowEnd: dst.rows(), colStart: 0, colEnd: dst.cols() / 2)
XCTAssert(submat.total() == Core.countNonZero(src: submat))
}
func testSortIdx() throws {
let a = Mat.eye(rows: 3, cols: 3, type: CvType.CV_8UC1)
let b = Mat()
Core.sortIdx(src: a, dst: b, flags: SortFlags.SORT_EVERY_ROW.rawValue | SortFlags.SORT_ASCENDING.rawValue)
truth = Mat(rows: 3, cols: 3, type: CvType.CV_32SC1)
try truth!.put(row: 0, col: 0, data: [1, 2, 0] as [Int32])
try truth!.put(row: 1, col: 0, data: [0, 2, 1] as [Int32])
try truth!.put(row: 2, col: 0, data: [0, 1, 2] as [Int32])
try assertMatEqual(truth!, b)
}
func testSplit() throws {
let m = getMat(CvType.CV_8UC3, vals: [1, 2, 3])
let cois = NSMutableArray()
Core.split(m: m, mv: cois)
try assertMatEqual(gray1, cois[0] as! Mat)
try assertMatEqual(gray2, cois[1] as! Mat)
try assertMatEqual(gray3, cois[2] as! Mat)
}
func testSqrt() throws {
Core.sqrt(src: gray9_32f, dst: dst)
try assertMatEqual(gray3_32f, dst, OpenCVTestCase.EPS)
let rgba144 = Mat(rows: OpenCVTestCase.matSize, cols: OpenCVTestCase.matSize, type: CvType.CV_32FC4, scalar: Scalar.all(144))
let rgba12 = Mat(rows: OpenCVTestCase.matSize, cols: OpenCVTestCase.matSize, type: CvType.CV_32FC4, scalar: Scalar.all(12))
Core.sqrt(src: rgba144, dst: dst)
try assertMatEqual(rgba12, dst, OpenCVTestCase.EPS)
}
func testSubtractMatMatMat() throws {
Core.subtract(src1: gray128, src2: gray1, dst: dst)
try assertMatEqual(gray127, dst)
}
func testSubtractMatMatMatMat() throws {
let mask = makeMask(gray1.clone())
dst = gray128.clone()
Core.subtract(src1: gray128, src2: gray1, dst: dst, mask: mask)
try assertMatEqual(makeMask(gray127, vals: [128]), dst)
}
func testSubtractMatMatMatMatInt() throws {
Core.subtract(src1: gray3, src2: gray2, dst: dst, mask: gray1, dtype: CvType.CV_32F)
try assertMatEqual(gray1_32f, dst, OpenCVTestCase.EPS)
}
func testSumElems() throws {
let src = Mat(rows: 4, cols: 4, type: CvType.CV_8U, scalar: Scalar(10))
let res1 = Core.sum(src: src)
assertScalarEqual(Scalar(160), res1, OpenCVTestCase.EPS)
}
func testSVBackSubst() throws {
let w = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1, scalar: Scalar(2))
let u = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1, scalar: Scalar(4))
let vt = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1, scalar: Scalar(2))
let rhs = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1, scalar: Scalar(1))
Core.SVBackSubst(w: w, u: u, vt: vt, rhs: rhs, dst: dst)
let truth = Mat(rows: 2, cols: 2, type: CvType.CV_32FC1, scalar: Scalar(16))
try assertMatEqual(truth, dst, OpenCVTestCase.EPS)
}
func testSVDecompMatMatMatMat() throws {
let src = Mat(rows: 1, cols: 4, type: CvType.CV_32FC1)
try src.put(row: 0, col: 0, data: [1, 4, 8, 6] as [Float])
let w = Mat()
let u = Mat()
let vt = Mat()
Core.SVDecomp(src: src, w: w, u: u, vt: vt)
let truthW = Mat(rows: 1, cols: 1, type: CvType.CV_32FC1, scalar: Scalar(10.816654))
let truthU = Mat(rows: 1, cols: 1, type: CvType.CV_32FC1, scalar: Scalar(1))
let truthVT = Mat(rows: 1, cols: 4, type: CvType.CV_32FC1)
try truthVT.put(row: 0, col: 0, data: [0.09245003, 0.36980012, 0.73960024, 0.5547002])
try assertMatEqual(truthW, w, OpenCVTestCase.EPS)
try assertMatEqual(truthU, u, OpenCVTestCase.EPS)
try assertMatEqual(truthVT, vt, OpenCVTestCase.EPS)
}
func testSVDecompMatMatMatMatInt() throws {
let src = Mat(rows: 1, cols: 4, type: CvType.CV_32FC1)
try src.put(row: 0, col: 0, data: [1, 4, 8, 6] as [Float])
let w = Mat()
let u = Mat()
let vt = Mat()
Core.SVDecomp(src: src, w: w, u: u, vt: vt, flags: Int32(Core.SVD_NO_UV))
let truthW = Mat(rows: 1, cols: 1, type: CvType.CV_32FC1, scalar: Scalar(10.816654))
try assertMatEqual(truthW, w, OpenCVTestCase.EPS)
XCTAssert(u.empty())
XCTAssert(vt.empty())
}
func testTrace() {
let s = Core.trace(mtx: gray1)
XCTAssertEqual(Scalar(Double(OpenCVTestCase.matSize)), s)
}
func testTransform() throws {
let src = Mat(rows: 2, cols: 2, type: CvType.CV_32F, scalar: Scalar(55))
let m = Mat.eye(rows: 2, cols: 2, type: CvType.CV_32FC1)
Core.transform(src: src, dst: dst, m: m)
truth = Mat(rows: 2, cols: 2, type: CvType.CV_32FC2, scalar: Scalar(55, 1))
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testTranspose() {
gray0.submat(rowStart: 0, rowEnd: gray0.rows() / 2, colStart: 0, colEnd: gray0.cols()).setTo(scalar: Scalar(1))
let destination = getMat(CvType.CV_8U, vals: [0])
Core.transpose(src: gray0, dst: destination)
let subdst = destination.submat(rowStart: 0, rowEnd: destination.rows(), colStart: 0, colEnd: destination.cols() / 2)
XCTAssert(subdst.total() == Core.countNonZero(src: subdst))
}
func testVconcat() throws {
let mats = [Mat.eye(rows: 3, cols: 3, type: CvType.CV_8U), Mat.zeros(2, cols: 3, type: CvType.CV_8U)]
Core.vconcat(src: mats, dst: dst)
try assertMatEqual(Mat.eye(rows: 5, cols: 3, type: CvType.CV_8U), dst)
}
func testCopyMakeBorderMatMatIntIntIntIntInt() throws {
let src = Mat(rows: 2, cols: 2, type: CvType.CV_32F, scalar: Scalar(1))
let border: Int32 = 2
Core.copyMakeBorder(src: src, dst: dst, top: border, bottom: border, left: border, right: border, borderType: .BORDER_REPLICATE)
truth = Mat(rows: 6, cols: 6, type: CvType.CV_32F, scalar: Scalar(1))
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testCopyMakeBorderMatMatIntIntIntIntIntScalar() throws {
let src = Mat(rows: 2, cols: 2, type: CvType.CV_32F, scalar: Scalar(1))
let value = Scalar(0)
let border: Int32 = 2
Core.copyMakeBorder(src: src, dst: dst, top: border, bottom: border, left: border, right: border, borderType: .BORDER_REPLICATE, value: value)
// TODO_: write better test (use Core.BORDER_CONSTANT)
truth = Mat(rows: 6, cols: 6, type: CvType.CV_32F, scalar: Scalar(1))
try assertMatEqual(truth!, dst, OpenCVTestCase.EPS)
}
func testBorderInterpolate() {
let val1 = Core.borderInterpolate(p: 100, len: 150, borderType: .BORDER_REFLECT_101)
XCTAssertEqual(100, val1)
let val2 = Core.borderInterpolate(p: -5, len: 10, borderType: .BORDER_WRAP)
XCTAssertEqual(5, val2)
}
func atan2deg(_ y:Double, _ x:Double) -> Double {
var res = atan2(y, x)
if (res < 0) {
res = Double.pi * 2 + res
}
return res * 180 / Double.pi
}
func atan2rad(_ y:Double, _ x:Double) -> Double {
var res = atan2(y, x)
if (res < 0) {
res = Double.pi * 2 + res
}
return res
}
}
| 39.693746 | 170 | 0.602553 |
9c906b6378241c7df57232a9ed43bcee24e869e3 | 1,051 | //
// AppDelegate.swift
// hindsight
//
// Created by manish on 10/13/18.
// Copyright © 2018 hindsight-inc. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let flow = BaseFlowCoordinator(presenter: DefaultPresenter())
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return flow.presentRootInterface(application: application,
withOptions: launchOptions)
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
| 26.948718 | 115 | 0.706946 |
762d9ae54237f0d18992cba95e851203d0265f23 | 981 | import Foundation
public final class FileLogAssembler {
private let configuration: FileLogConfiguration
public init(_ configuration: FileLogConfiguration) {
self.configuration = configuration
}
}
extension FileLogAssembler: LogAssembler {
public func assemble(at url: URL) throws {
let logFiles = try LogFile.sortedLogFilesByDate(for: configuration)
if logFiles.isEmpty {
throw TextError("Log not found for \(configuration)")
}
try LogFile.removeFileIfExist(at: url)
try LogFile.createEmptyFileIfNotExist(at: url)
let handle = try FileHandle(forWritingTo: url)
defer {
handle.closeFile()
}
handle.seekToEndOfFile()
for logFile in logFiles {
try autoreleasepool {
let data = try logFile.readData()
handle.write(data)
}
}
}
}
| 25.815789 | 75 | 0.588175 |
1ea557634a333c993334c3c3422f2c98d696e0d3 | 7,070 | //
// SignerInfo.swift
// cryptography-in-use
//
// Created by Mojtaba Mirzadeh on 5/5/1400 AP.
//
import Foundation
class SignerInfo : AsnSequnce {
private var _version : CmsVersion!
private var _sid : IssuerAndSerialNumber!
private var _digestAlgorithm : DigestAlgorithmIdentifier!
private var _signedAttributes : SignedAttributes!
private var _signatureAlgorithm : SignatureAlgorithmIdentifier!
private var _signature : OctetString!
init(version: CmsVersion, x509Certificate: X509Certificate) {
super.init()
self._version = version
self.initSid(x509Certificate: x509Certificate)
}
var digestAlgorithm : DigestAlgorithmId? {
willSet {
self._digestAlgorithm = DigestAlgorithmIdentifier(algorithm: newValue!)
}
}
var signatureAlgorithm : SignatureAlgorithmId? {
willSet {
self._signatureAlgorithm = SignatureAlgorithmIdentifier(algorithm: (newValue?.rawValue)!)
}
}
var signedAttributes : SignedAttributes {
get {
return self._signedAttributes
}
}
var signature : Data {
get {
return try! self._signature.asn1encode(tag: nil).serialize()
}
set {
self._signature = OctetString(data: newValue, tag: nil)
}
}
func initSid(x509Certificate: X509Certificate) {
let issuer = x509Certificate.issuerDistinguishedName!
let issuerDistinguishedNames = issuer.components(separatedBy: ", ")
let subject = x509Certificate.subjectDistinguishedName!
let subjectDistinguishedNames = subject.components(separatedBy: ", ")
let countryNameAttribute = AttributeTypeAndValue(type: try! ObjectIdentifier.from(string: Oid.CountryName.rawValue),
value: PrintableString(data: issuerDistinguishedNames.count > 0 ? issuerDistinguishedNames[0].components(separatedBy: "=").last! : ""))
let stateOrProvinceNameAttribute = AttributeTypeAndValue(type: try! ObjectIdentifier.from(string: Oid.StateOrProvinceName.rawValue),
value: Utf8String(data: issuerDistinguishedNames.count > 1 ? issuerDistinguishedNames[1].components(separatedBy: "=").last! : ""))
let localityNameAttribute = AttributeTypeAndValue(type: try! ObjectIdentifier.from(string: Oid.LocalityName.rawValue),
value: Utf8String(data: issuerDistinguishedNames.count > 1 ? issuerDistinguishedNames[1].components(separatedBy: "=").last! : ""))
let organizationNameAttribute = AttributeTypeAndValue(type: try! ObjectIdentifier.from(string: Oid.OrganizationName.rawValue),
value: Utf8String(data: issuerDistinguishedNames.count > 3 ? issuerDistinguishedNames[3].components(separatedBy: "=").last! : ""))
let organizationalUnitNameAttribute = AttributeTypeAndValue(type: try! ObjectIdentifier.from(string: Oid.OrganizationalUnitName.rawValue),
value: Utf8String(data: issuerDistinguishedNames.count > 4 ? issuerDistinguishedNames[4].components(separatedBy: "=").last! : ""))
let commonNameAttribute = AttributeTypeAndValue(type: try! ObjectIdentifier.from(string: Oid.CommonName.rawValue),
value: Utf8String(data: issuerDistinguishedNames.count > 5 ? issuerDistinguishedNames[5].components(separatedBy: "=").last! : ""))
let emailAddressAttribute = AttributeTypeAndValue(type: try! ObjectIdentifier.from(string: Oid.EmailAddress.rawValue),
value: Ia5String(data: subjectDistinguishedNames.count > 6 ? subjectDistinguishedNames[6].components(separatedBy: "=").last! : ""))
let countryName = RelativeDistinguishedName()
countryName.add(value: countryNameAttribute)
let stateOrProvinceName = RelativeDistinguishedName()
stateOrProvinceName.add(value: stateOrProvinceNameAttribute)
let localityName = RelativeDistinguishedName()
localityName.add(value: localityNameAttribute)
let organizationName = RelativeDistinguishedName()
organizationName.add(value: organizationNameAttribute)
let organizationalUnitName = RelativeDistinguishedName()
organizationalUnitName.add(value: organizationalUnitNameAttribute)
let commonName = RelativeDistinguishedName()
commonName.add(value: commonNameAttribute)
let emailAddress = RelativeDistinguishedName()
emailAddress.add(value: emailAddressAttribute)
let certificateIssuer = RDNSequence()
certificateIssuer.add(value: countryName)
certificateIssuer.add(value: stateOrProvinceName)
certificateIssuer.add(value: localityName)
certificateIssuer.add(value: organizationName)
certificateIssuer.add(value: organizationalUnitName)
certificateIssuer.add(value: commonName)
certificateIssuer.add(value: emailAddress)
let certificateSerialData : Data = x509Certificate.serialNumber!
let certificateSerialNumber = Int(bigEndian: certificateSerialData.withUnsafeBytes {$0.load(as: Int.self)})
self._sid = IssuerAndSerialNumber(issuer: certificateIssuer, serial: certificateSerialNumber)
}
func initSignedAttributes(signingTime: Date,
digestAlgorithmId: DigestAlgorithmId,
signatureAlgorithmId: SignatureAlgorithmId,
digestedData: String) {
// Content Type
let contentTypeAttribute = ContentTypeAttribute(value: OID.pkcs7data.rawValue)
// Signing Time
let signingTimeAttribute = SigningTimeAttribute(value: signingTime)
// CMS Algorithm Protection
let cmsAlgorithmProtectionAttribute = CMSAlgorithmProtectionAttribute(digestAlgorithmId: digestAlgorithmId,
signatureAlgorithmId: signatureAlgorithmId)
//MessageDigest
let messageDigestAttribute = MessageDigestAttribute(value: digestedData)
self._signedAttributes = SignedAttributes(tag: 0x00)
self._signedAttributes.add(value: contentTypeAttribute)
self._signedAttributes.add(value: signingTimeAttribute)
self._signedAttributes.add(value: cmsAlgorithmProtectionAttribute)
self._signedAttributes.add(value: messageDigestAttribute)
}
override func getData() -> [ASN1EncodableType] {
return [self._version.rawValue, self._sid!, self._digestAlgorithm!, self._signedAttributes, self._signatureAlgorithm!, self._signature]
}
}
| 50.5 | 198 | 0.656153 |
72a845edfb955808e0fddda380855d2757f217ec | 1,351 | import Foundation
public struct SecureIdUtilityBillValue: Equatable {
public var verificationDocuments: [SecureIdVerificationDocumentReference]
public var translations: [SecureIdVerificationDocumentReference]
public init(verificationDocuments: [SecureIdVerificationDocumentReference], translations: [SecureIdVerificationDocumentReference]) {
self.verificationDocuments = verificationDocuments
self.translations = translations
}
public static func ==(lhs: SecureIdUtilityBillValue, rhs: SecureIdUtilityBillValue) -> Bool {
if lhs.verificationDocuments != rhs.verificationDocuments {
return false
}
if lhs.translations != rhs.translations {
return false
}
return true
}
}
extension SecureIdUtilityBillValue {
init?(fileReferences: [SecureIdVerificationDocumentReference], translations: [SecureIdVerificationDocumentReference]) {
let verificationDocuments: [SecureIdVerificationDocumentReference] = fileReferences
self.init(verificationDocuments: verificationDocuments, translations: translations)
}
func serialize() -> ([String: Any], [SecureIdVerificationDocumentReference], [SecureIdVerificationDocumentReference]) {
return ([:], self.verificationDocuments, self.translations)
}
}
| 39.735294 | 136 | 0.735751 |
db9945d924cb88bba9aec3d3d9517582a5be7ad1 | 484 | //
// EasyPillMedicationImporter+CoreDataProperties.swift
// Introspective
//
// Created by Bryan Nova on 10/29/18.
// Copyright © 2018 Bryan Nova. All rights reserved.
//
//
import CoreData
import Foundation
public extension EasyPillMedicationImporterImpl {
@nonobjc class func fetchRequest() -> NSFetchRequest<EasyPillMedicationImporterImpl> {
NSFetchRequest<EasyPillMedicationImporterImpl>(entityName: "EasyPillMedicationImporter")
}
@NSManaged var lastImport: Date?
}
| 24.2 | 90 | 0.785124 |
01eb0d8942e514fadecd72a374c402b9599080d9 | 846 | //
// ConsentTask.swift
// sampleApp
//
// Created by admin on 6/11/21.
//
import Foundation
import ResearchKit
public var ConsentTask: ORKOrderedTask {
var steps = [ORKStep]()
//VisualConsentStep
let consentDocument = ConsentDocument
let visualConsentStep = ORKVisualConsentStep(identifier: "VisualConsentStep", document: consentDocument)
steps += [visualConsentStep]
//ConsentReviewStep
let signature = consentDocument.signatures!.first
let reviewConsentStep = ORKConsentReviewStep(identifier: "ConsentReviewStep", signature: signature, in: consentDocument)
reviewConsentStep.text = "Review Consent!"
reviewConsentStep.reasonForConsent = "Consent to join study"
steps += [reviewConsentStep]
return ORKOrderedTask(identifier: "ConsentTask", steps: steps)
}
| 26.4375 | 124 | 0.719858 |
ac01a0baa3b0c34a7ce1b3c6674b5fa8a646f772 | 5,936 | //
// SignInView.swift
// Shroud
//
// Created by Lynk on 9/4/20.
// Copyright © 2020 Lynk. All rights reserved.
//
import UIKit
protocol SignInDelegate: AnyObject {
func signUpPressed()
func logInPressed(email: String? , password: String?)
}
class SignInView: UIView {
weak var delegate: SignInDelegate?
lazy var signUpButton: UIButton = {
var button = UIButton(type: .system)
button.setTitle("Sign Up", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(SignUpPressed), for: .touchUpInside)
return button
}()
lazy var logInButton: UIButton = {
var button = UIButton(type: .system)
button.setTitleColor(.white, for: .normal)
button.setTitle("Log In", for: .normal)
button.backgroundColor = .systemBlue
button.addTarget(self, action: #selector(logInPressed), for: .touchUpInside)
return button
}()
lazy var shroudLogo: UIImageView = {
var iv = UIImageView()
iv.contentMode = .scaleAspectFill
iv.image = UIImage(named: "logo.png")?.withRenderingMode(.alwaysTemplate)
iv.tintColor = .white
return iv
}()
lazy var emailTextField: UITextField = {
var tf = CustomTextField()
tf.placeholder = "Email"
tf.autocapitalizationType = .none
tf.autocorrectionType = .no
tf.keyboardType = .emailAddress
return tf
}()
lazy var passwordTextField: UITextField = {
var tf = CustomTextField()
tf.placeholder = "Password"
tf.isSecureTextEntry = true
return tf
}()
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
private func commonInit () {
backgroundColor = .black
addLogo()
addEmailTextField()
addPasswordTextField()
addStackButtons()
}
private func addLogo() {
shroudLogo.translatesAutoresizingMaskIntoConstraints = false
addSubview(shroudLogo)
shroudLogo.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.75).isActive = true
shroudLogo.heightAnchor.constraint(equalTo: shroudLogo.widthAnchor, multiplier: 0.5).isActive = true
shroudLogo.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
NSLayoutConstraint.activate([NSLayoutConstraint(item: shroudLogo, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 0.55, constant: 0)])
}
private func addEmailTextField() {
emailTextField.translatesAutoresizingMaskIntoConstraints = false
addSubview(emailTextField)
emailTextField.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0).isActive = true
emailTextField.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.75).isActive = true
emailTextField.topAnchor.constraint(equalTo: shroudLogo.bottomAnchor, constant: 22).isActive = true
emailTextField.heightAnchor.constraint(equalToConstant: 35).isActive = true
}
private func addPasswordTextField() {
passwordTextField.translatesAutoresizingMaskIntoConstraints = false
addSubview(passwordTextField)
passwordTextField.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0).isActive = true
passwordTextField.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.75).isActive = true
passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor, constant: 11).isActive = true
passwordTextField.heightAnchor.constraint(equalToConstant: 35).isActive = true
}
private func addStackButtons() {
let stack = UIStackView(arrangedSubviews: [signUpButton,logInButton])
stack.translatesAutoresizingMaskIntoConstraints = false
addSubview(stack)
stack.distribution = .fillEqually
stack.axis = .horizontal
stack.centerXAnchor.constraint(equalTo: passwordTextField.centerXAnchor).isActive = true
stack.topAnchor.constraint(equalTo: passwordTextField.bottomAnchor, constant: 22).isActive = true
stack.spacing = 22
logInButton.translatesAutoresizingMaskIntoConstraints = false
logInButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
}
@objc private func logInPressed() {
delegate?.logInPressed(email: emailTextField.text, password: passwordTextField.text)
}
@objc private func SignUpPressed() {
delegate?.signUpPressed()
}
}
class CustomTextField: UITextField {
struct Constants {
static let sidePadding: CGFloat = 10
static let topPadding: CGFloat = 8
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
attributedPlaceholder = NSAttributedString(string: "a",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white.withAlphaComponent(0.3)])
keyboardAppearance = .dark
textColor = .white
backgroundColor = ShroudColors.darkGray
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(
x: bounds.origin.x + Constants.sidePadding,
y: bounds.origin.y + Constants.topPadding,
width: bounds.size.width - Constants.sidePadding * 2,
height: bounds.size.height - Constants.topPadding * 2
)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return self.textRect(forBounds: bounds)
}
}
| 34.71345 | 181 | 0.66004 |
4bc8e19d5af360d420a2e71466e3133482732353 | 5,905 | //
// GameMain.swift
// 0004_PlayerTest
//
// Created by Kikutada on 2020/08/17.
// Copyright © 2020 Kikutada All rights reserved.
//
import SpriteKit
/// Main sequence of game scene.
class CgGameMain : CgSceneFrame {
enum EnMainMode: Int {
case AttractMode = 0, CreditMode, WaitForStartButton, StartMode, PlayMode
}
enum EnSubMode: Int {
case Character = 0, StartDemo, PlayDemo
}
private var scene_attractMode: CgSceneAttractMode!
private var scene_creditMode: CgSceneCreditMode!
private var scene_maze: CgSceneMaze!
private var subMode: EnSubMode = .Character
init(skscene: SKScene) {
super.init()
// Create SpriteKit managers.
self.sprite = CgSpriteManager(view: skscene, imageNamed: "pacman16_16.png", width: 16, height: 16, maxNumber: 64)
self.background = CgCustomBackgroundManager(view: skscene, imageNamed: "pacman8_8.png", width: 8, height: 8, maxNumber: 2)
self.sound = CgSoundManager(binding: self, view: skscene)
self.context = CgContext()
scene_attractMode = CgSceneAttractMode(object: self)
scene_creditMode = CgSceneCreditMode(object: self)
scene_maze = CgSceneMaze(object: self)
}
/// Event handler
/// - Parameters:
/// - sender: Message sender
/// - id: Message ID
/// - values: Parameters of message
override func handleEvent(sender: CbObject, message: EnMessage, parameter values: [Int]) {
if message == .Touch {
if let mode: EnMainMode = EnMainMode(rawValue: getSequence()) {
if mode == .AttractMode || mode == .WaitForStartButton {
goToNextSequence()
}
}
}
}
/// Handle sequence
/// To override in a derived class.
/// - Parameter sequence: Sequence number
/// - Returns: If true, continue the sequence, if not, end the sequence.
override func handleSequence(sequence: Int) -> Bool {
guard let mode: EnMainMode = EnMainMode(rawValue: sequence) else { return false }
switch mode {
case .AttractMode: attarctMode()
case .CreditMode: creditMode()
case .WaitForStartButton: break // Forever loop
case .StartMode: startMode()
case .PlayMode: playMode()
}
// Continue running sequence.
return true
}
// ============================================================
// Execute each mode.
// ============================================================
func attarctMode() {
switch subMode {
case .Character:
scene_attractMode.resetSequence()
scene_attractMode.startSequence()
subMode = .StartDemo
case .StartDemo:
if !scene_attractMode.enabled {
context.demo = true
sound.enableOutput(false)
scene_maze.resetSequence()
scene_maze.startSequence()
subMode = .PlayDemo
}
case .PlayDemo:
if !scene_maze.enabled {
subMode = .Character
}
}
}
func creditMode() {
context.demo = false
if scene_attractMode.enabled {
scene_attractMode.stopSequence()
scene_attractMode.clear()
}
if scene_maze.enabled {
scene_maze.stopSequence()
scene_maze.clear()
}
context.credit += 1
scene_creditMode.resetSequence()
scene_creditMode.startSequence()
sound.enableOutput(true)
sound.playSE(.Credit)
goToNextSequence()
}
func startMode() {
context.credit -= 1
scene_creditMode.stopSequence()
scene_maze.resetSequence()
scene_maze.startSequence()
goToNextSequence()
}
func playMode() {
if !scene_maze.enabled {
subMode = .Character
goToNextSequence(EnMainMode.AttractMode.rawValue)
}
}
}
/// CgCustomBackground creates animation textures by overriden extendTextures function.
class CgCustomBackgroundManager : CgBackgroundManager {
/// String color for background
/// Raw value is offset of colored alphabet.
enum EnBgColor: Int {
case White = 0
case Red = 64
case Purple = 128
case Cyan = 192
case Orange = 256
case Yellow = 320
case Pink = 384
case Character = 512
case Maze = 576
case Blink = 640
}
override func extendTextures() -> Int {
// Blinking power dot
// Add its texture as #16*48.
extendAnimationTexture(sequence: [595, 592], timePerFrame: 0.16)
// Blinking "1" character
extendAnimationTexture(sequence: [17, 0], timePerFrame: 0.26)
// Blinking "U" character
extendAnimationTexture(sequence: [53, 0], timePerFrame: 0.26)
// Blinking "P" character
extendAnimationTexture(sequence: [48, 0], timePerFrame: 0.26)
return 4 // Number of added textures
}
/// Print string with color on a background at the specified position.
/// - Parameters:
/// - number: Background control number between 0 to (maxNumber-1)
/// - color: Specified color
/// - column: Column coordinate for position
/// - row: Row coordinate for position
/// - string: String corresponded to texture numbers
/// - offset: Offset to add to texture number
func print(_ number: Int, color: EnBgColor, column: Int, row: Int, string: String ) {
let asciiOffset: Int = 16*2 // for offset of ASCII
putString(number, column: column, row: row, string: string, offset: color.rawValue-asciiOffset)
}
}
| 31.747312 | 130 | 0.579509 |
0a1e626068aa6cdcfa8a92420315de1cec4a0760 | 16,561 | //
// Copyright (c) 2016-2017 Anton Mironov
//
// 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 Dispatch
public extension EventSource {
/// Adds indexes to update values of the channel
///
/// - Parameters:
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: channel with tuple (index, update) as update value
func enumerated(cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<(Int, Update), Success> {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
var index: OSAtomic_int64_aligned64_t = -1
return self.map(executor: .immediate,
cancellationToken: cancellationToken,
bufferSize: bufferSize) {
let localIndex = Int(OSAtomicIncrement64(&index))
return (localIndex, $0)
}
#else
var locking = makeLocking()
var index = 0
return self.map(executor: .immediate,
cancellationToken: cancellationToken,
bufferSize: bufferSize) {
locking.lock()
defer { locking.unlock() }
let localIndex = index
index += 1
return (localIndex, $0)
}
#endif
}
/// Makes channel of pairs of update values
///
/// - Parameters:
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: channel with tuple (update, update) as update value
func bufferedPairs(cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<(Update, Update), Success>
{
let locking = makeLocking()
var previousUpdate: Update?
return makeProducer(
executor: .immediate,
pure: true,
cancellationToken: cancellationToken,
bufferSize: bufferSize
) { (value, producer, originalExecutor) in
switch value {
case let .update(update):
locking.lock()
let _previousUpdate = previousUpdate
previousUpdate = update
locking.unlock()
if let previousUpdate = _previousUpdate {
let change = (previousUpdate, update)
producer.value?.update(change, from: originalExecutor)
}
case let .completion(completion):
producer.value?.complete(completion, from: originalExecutor)
}
}
}
/// Makes channel of arrays of update values
///
/// - Parameters:
/// - capacity: number of update values of original channel used
/// as update value of derived channel
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: channel with [update] as update value
func buffered(capacity: Int,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<[Update], Success> {
var buffer = [Update]()
buffer.reserveCapacity(capacity)
let locking = makeLocking()
return makeProducer(
executor: .immediate,
pure: true,
cancellationToken: cancellationToken,
bufferSize: bufferSize
) { (value, producer, originalExecutor) in
locking.lock()
switch value {
case let .update(update):
buffer.append(update)
if capacity == buffer.count {
let localBuffer = buffer
buffer.removeAll(keepingCapacity: true)
locking.unlock()
producer.value?.update(localBuffer, from: originalExecutor)
} else {
locking.unlock()
}
case let .completion(completion):
let localBuffer = buffer
buffer.removeAll(keepingCapacity: false)
locking.unlock()
if !localBuffer.isEmpty {
producer.value?.update(localBuffer, from: originalExecutor)
}
producer.value?.complete(completion, from: originalExecutor)
}
}
}
/// Makes channel that delays each value produced by originial channel
///
/// - Parameters:
/// - timeout: in seconds to delay original channel by
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: delayed channel
func delayedUpdate(timeout: Double,
delayingExecutor: Executor = .primary,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<Update, Success> {
return makeProducer(
executor: .immediate,
pure: true,
cancellationToken: cancellationToken,
bufferSize: bufferSize
) { (event: Event, producer, originalExecutor: Executor) -> Void in
delayingExecutor.execute(after: timeout) { (originalExecutor) in
producer.value?.post(event, from: originalExecutor)
}
}
}
}
// MARK: - Distinct
extension EventSource {
/// Returns channel of distinct update values of original channel.
/// Requires dedicated equality checking closure
///
/// - Parameters:
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - isEqual: closure that tells if specified values are equal
/// - Returns: channel with distinct update values
public func distinct(
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default,
isEqual: @escaping (Update, Update) -> Bool
) -> Channel<Update, Success> {
let locking = makeLocking()
var previousUpdate: Update?
return makeProducer(
executor: .immediate,
pure: true,
cancellationToken: cancellationToken,
bufferSize: bufferSize
) { (value, producer, originalExecutor) in
switch value {
case let .update(update):
locking.lock()
let _previousUpdate = previousUpdate
previousUpdate = update
locking.unlock()
if let previousUpdate = _previousUpdate {
if !isEqual(previousUpdate, update) {
producer.value?.update(update, from: originalExecutor)
}
} else {
producer.value?.update(update, from: originalExecutor)
}
case let .completion(completion):
producer.value?.complete(completion, from: originalExecutor)
}
}
}
}
extension EventSource where Update: Equatable {
/// Returns channel of distinct update values of original channel.
/// Works only for equatable update values
/// [0, 0, 1, 2, 3, 3, 4, 3] => [0, 1, 2, 3, 4, 3]
///
/// - Parameters:
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: channel with distinct update values
public func distinct(
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<Update, Success> {
// Test: EventSource_TransformTests.testDistinctInts
return distinct(cancellationToken: cancellationToken, bufferSize: bufferSize, isEqual: ==)
}
}
#if swift(>=4.1)
#else
extension EventSource where Update: AsyncNinjaOptionalAdaptor, Update.AsyncNinjaWrapped: Equatable {
/// Returns channel of distinct update values of original channel.
/// Works only for equatable wrapped in optionals
/// [nil, 1, nil, nil, 2, 2, 3, nil, 3, 3, 4, 5, 6, 6, 7] => [nil, 1, nil, 2, 3, nil, 3, 4, 5, 6, 7]
///
/// - Parameters:
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: channel with distinct update values
public func distinct(
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<Update, Success> {
// Test: EventSource_TransformTests.testDistinctInts
return distinct(cancellationToken: cancellationToken, bufferSize: bufferSize) {
$0.asyncNinjaOptionalValue == $1.asyncNinjaOptionalValue
}
}
}
extension EventSource where Update: Collection, Update.Iterator.Element: Equatable {
/// Returns channel of distinct update values of original channel.
/// Works only for collections of equatable values
/// [[1], [1], [1, 2], [1, 2, 3], [1, 2, 3], [1]] => [[1], [1, 2], [1, 2, 3], [1]]
///
/// - Parameters:
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: channel with distinct update values
public func distinct(
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<Update, Success> {
// Test: EventSource_TransformTests.testDistinctArray
func isEqual(lhs: Update, rhs: Update) -> Bool {
return lhs.count == rhs.count
&& !zip(lhs, rhs).contains { $0.0 != $0.1 }
}
return distinct(cancellationToken: cancellationToken, bufferSize: bufferSize, isEqual: isEqual)
}
}
#endif
// MARK: - skip
public extension EventSource {
/// Makes a channel that skips updates
///
/// - Parameters:
/// - first: number of first updates to skip
/// - last: number of last updates to skip
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: channel that skips updates
func skip(
first: Int,
last: Int,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<Update, Success> {
// Test: EventSource_TransformTests.testSkip
var locking = makeLocking(isFair: true)
var updatesQueue = Queue<Update>()
var numberOfFirstToSkip = first
let numberOfLastToSkip = last
func onEvent(
event: ChannelEvent<Update, Success>,
producerBox: WeakBox<BaseProducer<Update, Success>>,
originalExecutor: Executor) {
switch event {
case let .update(update):
let updateToPost: Update? = locking.locker {
if numberOfFirstToSkip > 0 {
numberOfFirstToSkip -= 1
return nil
} else if numberOfLastToSkip > 0 {
updatesQueue.push(update)
while updatesQueue.count > numberOfLastToSkip {
return updatesQueue.pop()
}
return nil
} else {
return update
}
}
if let updateToPost = updateToPost {
producerBox.value?.update(updateToPost, from: originalExecutor)
}
case let .completion(completion):
producerBox.value?.complete(completion, from: originalExecutor)
}
}
return makeProducer(executor: .immediate, pure: true,
cancellationToken: cancellationToken,
bufferSize: bufferSize, onEvent)
}
}
// MARK: take
public extension EventSource {
/// Makes a channel that takes updates specific number of update
///
/// - Parameters:
/// - first: number of first updates to take
/// - last: number of last updates to take
/// - cancellationToken: `CancellationToken` to use.
/// Keep default value of the argument unless you need
/// an extended cancellation options of returned primitive
/// - bufferSize: `DerivedChannelBufferSize` of derived channel.
/// Keep default value of the argument unless you need
/// an extended buffering options of returned channel
/// - Returns: channel that takes updates
func take(
first: Int,
last: Int,
cancellationToken: CancellationToken? = nil,
bufferSize: DerivedChannelBufferSize = .default
) -> Channel<Update, Success> {
// Test: EventSource_TransformTests.testTake
var locking = makeLocking(isFair: true)
var updatesQueue = Queue<Update>()
var numberOfFirstToTake = first
let numberOfLastToTake = last
func onEvent(
event: ChannelEvent<Update, Success>,
producerBox: WeakBox<BaseProducer<Update, Success>>,
originalExecutor: Executor) {
switch event {
case let .update(update):
let updateToPost: Update? = locking.locker {
if numberOfFirstToTake > 0 {
numberOfFirstToTake -= 1
return update
} else if numberOfLastToTake > 0 {
updatesQueue.push(update)
while updatesQueue.count > numberOfLastToTake {
_ = updatesQueue.pop()
}
return nil
} else {
return nil
}
}
if let updateToPost = updateToPost {
producerBox.value?.update(updateToPost, from: originalExecutor)
}
case let .completion(completion):
if let producer = producerBox.value {
let queue = locking.locker { updatesQueue }
producer.update(queue)
producer.complete(completion, from: originalExecutor)
}
}
}
return makeProducer(executor: .immediate, pure: true,
cancellationToken: cancellationToken,
bufferSize: bufferSize, onEvent)
}
}
| 37.132287 | 102 | 0.656361 |
ff7d7fac0b6ca444cede86315a0e155925ae0dd2 | 3,782 | //
// MyWebStorageManager.swift
// connectivity
//
// Created by Lorenzo Pichilli on 16/12/2019.
//
import Foundation
import WebKit
@available(iOS 9.0, *)
class MyWebStorageManager: NSObject, FlutterPlugin {
static var registrar: FlutterPluginRegistrar?
static var channel: FlutterMethodChannel?
static var websiteDataStore: WKWebsiteDataStore?
static func register(with registrar: FlutterPluginRegistrar) {
}
init(registrar: FlutterPluginRegistrar) {
super.init()
MyWebStorageManager.registrar = registrar
MyWebStorageManager.websiteDataStore = WKWebsiteDataStore.default()
MyWebStorageManager.channel = FlutterMethodChannel(name: "com.pichillilorenzo/flutter_inappwebview_fork_webstoragemanager", binaryMessenger: registrar.messenger())
registrar.addMethodCallDelegate(self, channel: MyWebStorageManager.channel!)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let arguments = call.arguments as? NSDictionary
switch call.method {
case "fetchDataRecords":
let dataTypes = Set(arguments!["dataTypes"] as! [String])
MyWebStorageManager.fetchDataRecords(dataTypes: dataTypes, result: result)
break
case "removeDataFor":
let dataTypes = Set(arguments!["dataTypes"] as! [String])
let recordList = arguments!["recordList"] as! [[String: Any?]]
MyWebStorageManager.removeDataFor(dataTypes: dataTypes, recordList: recordList, result: result)
break
case "removeDataModifiedSince":
let dataTypes = Set(arguments!["dataTypes"] as! [String])
let timestamp = arguments!["timestamp"] as! Int64
MyWebStorageManager.removeDataModifiedSince(dataTypes: dataTypes, timestamp: timestamp, result: result)
break
default:
result(FlutterMethodNotImplemented)
break
}
}
public static func fetchDataRecords(dataTypes: Set<String>, result: @escaping FlutterResult) {
var recordList: [[String: Any?]] = []
MyWebStorageManager.websiteDataStore!.fetchDataRecords(ofTypes: dataTypes) { (data) in
for record in data {
recordList.append([
"displayName": record.displayName,
"dataTypes": record.dataTypes.map({ (dataType) -> String in
return dataType
})
])
}
result(recordList)
}
}
public static func removeDataFor(dataTypes: Set<String>, recordList: [[String: Any?]], result: @escaping FlutterResult) {
var records: [WKWebsiteDataRecord] = []
MyWebStorageManager.websiteDataStore!.fetchDataRecords(ofTypes: dataTypes) { (data) in
for record in data {
for r in recordList {
let displayName = r["displayName"] as! String
if (record.displayName == displayName) {
records.append(record)
break
}
}
}
MyWebStorageManager.websiteDataStore!.removeData(ofTypes: dataTypes, for: records) {
result(true)
}
}
}
public static func removeDataModifiedSince(dataTypes: Set<String>, timestamp: Int64, result: @escaping FlutterResult) {
let date = NSDate(timeIntervalSince1970: TimeInterval(timestamp))
MyWebStorageManager.websiteDataStore!.removeData(ofTypes: dataTypes, modifiedSince: date as Date) {
result(true)
}
}
}
| 40.234043 | 171 | 0.611052 |
67d722ffde859aa2d67180de3b388b58c2cbb88c | 2,043 | //
// PermissionsConfiguration.swift
//
//
// Copyright © 2017-2021 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
/// A model object that defines a configuration for permissions to be requested either as a part of
/// a step or an async action.
public protocol PermissionsConfiguration {
/// List of the permissions required for this action.
var permissionTypes: [PermissionType] { get }
}
| 47.511628 | 99 | 0.768967 |
f5d10cde6852cdce450de96e1323f4264ad07311 | 1,651 | //
// MemCache.swift
// UnitTests
//
// Created by Ondřej Hanák on 06. 05. 2020.
// Copyright © 2020 Userbrain. All rights reserved.
//
import Foundation
final public class MemCache<Key: Hashable, Value> {
// based on https://www.swiftbysundell.com/articles/caching-in-swift/
private let cache = NSCache<WrappedKey, WrappedValue>()
// MARK: - Public
public init() {}
public func setValue(_ value: Value, forKey key: Key) {
self.cache.setObject(WrappedValue(value: value), forKey: WrappedKey(key))
}
public func value(forKey key: Key) -> Value? {
return self.cache.object(forKey: WrappedKey(key))?.value
}
public func removeValue(forKey key: Key) {
self.cache.removeObject(forKey: WrappedKey(key))
}
public func removeAllValues() {
self.cache.removeAllObjects()
}
}
extension MemCache {
public subscript(key: Key) -> Value? {
get {
self.value(forKey: key)
}
set {
if let value = newValue {
self.setValue(value, forKey: key)
} else {
self.removeValue(forKey: key)
}
}
}
}
private extension MemCache {
// Although Apple doc does not say that, keys needs to hashable of course. But just Hashable conformance does not work, needs to be subclass of NSObject.
final class WrappedKey: NSObject {
let key: Key
init(_ key: Key) {
self.key = key
}
override var hash: Int {
key.hashValue
}
override func isEqual(_ object: Any?) -> Bool {
guard let value = object as? WrappedKey else { return false }
return value.key == self.key
}
}
}
private extension MemCache {
final class WrappedValue {
let value: Value
init(value: Value) {
self.value = value
}
}
}
| 20.6375 | 154 | 0.6808 |
ac6c9c95740d4d14eff51cfb91f1ae68e924c10a | 609 | //
// VersaPlayerExtension.swift
// VersaPlayer Demo
//
// Created by Jose Quintero on 10/12/18.
// Copyright © 2018 Quasar. All rights reserved.
//
import Foundation
open class VersaPlayerExtension: NSObject {
/// VersaPlayer instance being used
open var player: VersaPlayerView
public init(with player: VersaPlayerView) {
self.player = player
}
/// Notifies when player added the extension
open func didAddExtension() {
}
/// Make preparations for the extension such as modifying the view
open func prepare() {
}
}
| 20.3 | 70 | 0.642036 |
5df31b8e4005cc43f37e6445f368494ee5e8034e | 3,512 | //
// SegmentControlView.swift
// SegmentControl
//
// Created by Petar Ivanov on 12/3/17.
// Copyright © 2017 Petar Ivanov. All rights reserved.
//
import UIKit
class SegmentControlView: UIView {
private var scale: CGFloat = 0.6
private var circleRadius: CGFloat {
return min(bounds.size.width, bounds.size.height) / 2 * scale
}
private var circleCenter: CGPoint {
return CGPoint(x: bounds.midX, y: bounds.midY)
}
private func pathForSingleSegment(startAngle: CGFloat, endAngle: CGFloat, color: UIColor) -> UIBezierPath {
let path = UIBezierPath(arcCenter: circleCenter, radius: circleRadius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
color.set()
path.lineWidth = 60.0
path.lineCapStyle = .round
return path
}
private func calculateEndAngle(segmentSize: Int) -> Double {
return Double((360 * segmentSize)) / 100.0
}
private func angleToRadians(angle: CGFloat) -> CGFloat {
return angle * CGFloat.pi / 180
}
func getPointOnCircle(radius: CGFloat, center: CGPoint, angle: CGFloat) -> CGPoint {
let theta = angle * CGFloat.pi / 180
let x = radius * CGFloat(cos(theta)) + center.x
let y = radius * CGFloat(sin(theta)) + center.y
return CGPoint(x: x, y: y)
}
private func drawSegments() {
// set initial settings for the drawing of the path
let colors: [UIColor] = [.purple, .red, .orange, .blue, .green] // colors of the segments
let numberOfSegments = 5
let segments: [Int] = [22, 24, 14, 24, 16] // size of the segments, the sum should be 100
var startAngle: CGFloat
var endAngle: CGFloat
var color: UIColor
startAngle = 0
for i in 0..<numberOfSegments {
// calculate the new end angle of the path
endAngle = startAngle + CGFloat(calculateEndAngle(segmentSize: segments[i]))
color = colors[i]
let path = pathForSingleSegment(startAngle: angleToRadians(angle: startAngle), endAngle: angleToRadians(angle: endAngle), color: color)
// let currentPoint = path.currentPoint
// configure string with attributes
let numberString = String(segments[i])
let numberStringAttributes = [
NSAttributedStringKey.foregroundColor: UIColor.white,
NSAttributedStringKey.font: UIFont(name: "Arial", size: 20.0)!
]
let numberAttributeString = NSAttributedString(string: numberString, attributes: numberStringAttributes)
// calculate the point where the string will be drawed
let currentPoint = getPointOnCircle(radius: circleRadius, center: circleCenter, angle: endAngle-30)
path.move(to: currentPoint)
path.stroke()
numberAttributeString.draw(at: currentPoint)
// calculate the new start angle of the path
startAngle = endAngle
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.black
}
override func draw(_ rect: CGRect) {
drawSegments()
}
}
| 32.82243 | 147 | 0.582859 |
ff41c5c484162d9956a54071c1715fe67f8e82e9 | 7,926 | //
// EEZoomableImageView.swift
// EEZoomableImageView
//
// Created by Emre on 27.05.2018.
// Copyright © 2018 Emre. All rights reserved.
//
import UIKit
open class EEZoomableImageView: UIImageView {
private var pinchZoomHandler: PinchZoomHandler!
// Public Configurables
var zoomDelegate: ZoomingDelegate? {
get {
return pinchZoomHandler.delegate
} set {
pinchZoomHandler.delegate = newValue
}
}
// Minimum Scale of ImageView
var minZoomScale: CGFloat {
get {
return pinchZoomHandler.minZoomScale
} set {
pinchZoomHandler.minZoomScale = abs(min(1.0, newValue))
}
}
// Maximum Scale of ImageView
var maxZoomScale: CGFloat {
get {
return pinchZoomHandler.maxZoomScale
} set {
pinchZoomHandler.maxZoomScale = abs(max(1.0, newValue))
}
}
// Duration of finish animation
var resetAnimationDuration: Double {
get {
return pinchZoomHandler.resetAnimationDuration
} set {
pinchZoomHandler.resetAnimationDuration = abs(newValue)
}
}
// True when pinching active
var isZoomingActive: Bool {
get {
return pinchZoomHandler.isZoomingActive
} set { }
}
// MARK: Private Initializations
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
override init(image: UIImage?, highlightedImage: UIImage?) {
super.init(image: image, highlightedImage: highlightedImage)
commonInit()
}
override init(image: UIImage?) {
super.init(image: image)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
pinchZoomHandler = PinchZoomHandler(usingSourceImageView: self)
}
}
public protocol ZoomingDelegate: class {
func pinchZoomHandlerStartPinching()
func pinchZoomHandlerEndPinching()
}
private struct PinchZoomHandlerConstants {
fileprivate static let kMinZoomScaleDefaultValue: CGFloat = 1.0
fileprivate static let kMaxZoomScaleDefaultValue: CGFloat = 3.0
fileprivate static let kResetAnimationDurationDefaultValue = 0.3
fileprivate static let kIsZoomingActiveDefaultValue: Bool = false
}
fileprivate class PinchZoomHandler {
// Configurable
var minZoomScale: CGFloat = PinchZoomHandlerConstants.kMinZoomScaleDefaultValue
var maxZoomScale: CGFloat = PinchZoomHandlerConstants.kMaxZoomScaleDefaultValue
var resetAnimationDuration = PinchZoomHandlerConstants.kResetAnimationDurationDefaultValue
var isZoomingActive: Bool = PinchZoomHandlerConstants.kIsZoomingActiveDefaultValue
weak var delegate: ZoomingDelegate?
weak var sourceImageView: UIImageView?
private var zoomImageView: UIImageView = UIImageView()
private var initialRect: CGRect = CGRect.zero
private var zoomImageLastPosition: CGPoint = CGPoint.zero
private var lastTouchPoint: CGPoint = CGPoint.zero
private var lastNumberOfTouch: Int?
// MARK: Initialization
init(usingSourceImageView sourceImageView: UIImageView) {
self.sourceImageView = sourceImageView
setupPinchGesture(on: sourceImageView)
}
// MARK: Private Methods
private func setupPinchGesture(on pinchContainer: UIView) {
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinchGesture(pinch:)))
pinchGesture.cancelsTouchesInView = false
pinchContainer.isUserInteractionEnabled = true
pinchContainer.addGestureRecognizer(pinchGesture)
}
@objc private func handlePinchGesture(pinch: UIPinchGestureRecognizer) {
guard let pinchableImageView = sourceImageView else { return }
handlePinchMovement(pinchGesture: pinch, sourceImageView: pinchableImageView)
}
private func handlePinchMovement(pinchGesture: UIPinchGestureRecognizer, sourceImageView: UIImageView) {
switch pinchGesture.state {
case .began:
guard !isZoomingActive, pinchGesture.scale >= minZoomScale else { return }
guard let point = sourceImageView.superview?.convert(sourceImageView.frame.origin, to: nil) else { return }
initialRect = CGRect(x: point.x, y: point.y, width: sourceImageView.frame.size.width, height: sourceImageView.frame.size.height)
lastTouchPoint = pinchGesture.location(in: sourceImageView)
zoomImageView = UIImageView(image: sourceImageView.image)
zoomImageView.contentMode = sourceImageView.contentMode
zoomImageView.frame = initialRect
let anchorPoint = CGPoint(x: lastTouchPoint.x/initialRect.size.width, y: lastTouchPoint.y/initialRect.size.height)
zoomImageView.layer.anchorPoint = anchorPoint
zoomImageView.center = lastTouchPoint
zoomImageView.frame = initialRect
sourceImageView.alpha = 0.0
UIApplication.shared.keyWindow?.addSubview(zoomImageView)
zoomImageLastPosition = zoomImageView.center
self.delegate?.pinchZoomHandlerStartPinching()
isZoomingActive = true
lastNumberOfTouch = pinchGesture.numberOfTouches
case .changed:
let isNumberOfTouchChanged = pinchGesture.numberOfTouches != lastNumberOfTouch
if isNumberOfTouchChanged {
let newTouchPoint = pinchGesture.location(in: sourceImageView)
lastTouchPoint = newTouchPoint
}
let scale = zoomImageView.frame.size.width / initialRect.size.width
let newScale = scale * pinchGesture.scale
if scale.isNaN || scale == CGFloat.infinity || CGFloat.nan == initialRect.size.width {
return
}
zoomImageView.frame = CGRect(x: zoomImageView.frame.origin.x,
y: zoomImageView.frame.origin.y,
width: min(max(initialRect.size.width * newScale, initialRect.size.width * minZoomScale), initialRect.size.width * maxZoomScale),
height: min(max(initialRect.size.height * newScale, initialRect.size.height * minZoomScale), initialRect.size.height * maxZoomScale))
let centerXDif = lastTouchPoint.x - pinchGesture.location(in: sourceImageView).x
let centerYDif = lastTouchPoint.y - pinchGesture.location(in: sourceImageView).y
zoomImageView.center = CGPoint(x: zoomImageLastPosition.x - centerXDif, y: zoomImageLastPosition.y - centerYDif)
pinchGesture.scale = 1.0
// Store last values
lastNumberOfTouch = pinchGesture.numberOfTouches
zoomImageLastPosition = zoomImageView.center
lastTouchPoint = pinchGesture.location(in: sourceImageView)
case .ended, .cancelled, .failed:
resetZoom()
default:
break
}
}
private func resetZoom() {
UIView.animate(withDuration: resetAnimationDuration, animations: {
self.zoomImageView.frame = self.initialRect
}) { _ in
self.zoomImageView.removeFromSuperview()
self.sourceImageView?.alpha = 1.0
self.initialRect = .zero
self.lastTouchPoint = .zero
self.isZoomingActive = false
self.delegate?.pinchZoomHandlerEndPinching()
}
}
}
| 35.542601 | 174 | 0.639919 |
083497c2cc7fdb532657d95b1c390519316cdea3 | 907 | import Foundation
// MARK: Derivative
postfix operator ′
public postfix func ′(function: @escaping (Double) -> (Double)) -> (Double) -> (Double) {
return { x in
let h: Double = x.isZero ? 1e-3 : √(ε * x)
return round((function(x + h) - function(x - h)) / (2 * h) / h) * h
}
}
// MARK: Integral
infix operator ∫ : MultiplicationPrecedence
public func ∫(lhs: (lowerBound: Double, upperBound: Double), rhs: (Double) -> (Double)) -> Double {
let n = Int(1e2 + 1)
let h = (lhs.upperBound - lhs.lowerBound) / Double(n)
return (h / 3.0) * (1..<n).reduce(rhs(lhs.lowerBound)) {
let coefficient = $1.isMultiple(of: 2) ? 4.0 : 2.0
return $0 + coefficient * rhs(lhs.lowerBound + Double($1) * h)
} + rhs(lhs.upperBound)
}
public func ∫(lhs: ClosedRange<Double>, rhs: (Double) -> (Double)) -> Double {
return (lhs.lowerBound, lhs.upperBound) ∫ rhs
}
| 31.275862 | 99 | 0.595369 |
f4014272a65593926c7adcdd2fd78b3554ead83b | 3,034 | //
// ProviderSection.swift
// DataProvider
//
// Created by Guilherme Silva Lisboa on 2015-12-22.
// Copyright © 2015 Samsao. All rights reserved.
//
import Foundation
public struct ProviderSectionViewConfiguration {
public internal(set) var view : UIView
public internal(set) var height : CGFloat
/**
Initialize View configuration with a view and a height value for use as header or footer.
- parameter view: view.
- parameter viewHeight: height for this view. If not specified uses view's frame height
- returns: configuration with initialized values.
*/
public init(view : UIView, viewHeight : CGFloat? = nil) {
self.view = view
self.height = viewHeight ?? view.frame.height
}
}
public struct ProviderSection {
// MARK: Properties
public private(set) var headerViewConfiguration : ProviderSectionViewConfiguration?
public private(set) var footerViewConfiguration : ProviderSectionViewConfiguration?
public var items : [ProviderItem]
// MARK: Intializers
/**
create new instance of a provider section with an array of items and possible configuration for header and footer views to be used in this section.
- parameter items: items for the section.
- parameter headerViewConfig: Header view configuration
- parameter footerViewConfig: Footer view configuration
- returns: new instance of a provider section.
*/
public init(items : [ProviderItem], headerViewConfig : ProviderSectionViewConfiguration? = nil, footerViewConfig : ProviderSectionViewConfiguration? = nil) {
self.items = items
self.headerViewConfiguration = headerViewConfig
self.footerViewConfiguration = footerViewConfig
}
// MARK: - Public API
// MARK: Utility Methods
/**
Create collection of provider sections with an collection of dictionaries of reuse identifiers and data.
- parameter sectionsData: collection of dictionaries where which dictionary represent the section data with it's reuse identifier and data.
- returns: collection of provider sections filled with data.
*/
//TODO: There's probably a better way to do this. The API is not really clean IMO - GC
public static func sectionsCollectionWithData<T>(sectionsData : [[String : [T]]]) -> [ProviderSection]{
var sections = [ProviderSection]()
var section : ProviderSection!
var item : ProviderItem!
var items : [ProviderItem]!
//FIXME: This should be optimized
for data in sectionsData {
items = [ProviderItem]()
for cellReuseID in data.keys {
for data in data[cellReuseID]! {
item = ProviderItem(data: data, cellReuseIdentifier: cellReuseID)
items.append(item)
}
}
section = ProviderSection(items: items)
sections.append(section)
}
return sections
}
}
| 35.27907 | 161 | 0.667765 |
186c1c9322cc238378e81509c70118a23d58d462 | 3,208 | //
// Business.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
class Business: NSObject {
let name: String?
let address: String?
let imageURL: URL?
let categories: String?
let distance: String?
let ratingImageURL: URL?
let reviewCount: NSNumber?
init(dictionary: NSDictionary) {
name = dictionary["name"] as? String
let imageURLString = dictionary["image_url"] as? String
if imageURLString != nil {
imageURL = URL(string: imageURLString!)!
} else {
imageURL = nil
}
let location = dictionary["location"] as? NSDictionary
var address = ""
if location != nil {
let addressArray = location!["address"] as? NSArray
if addressArray != nil && addressArray!.count > 0 {
address = addressArray![0] as! String
}
let neighborhoods = location!["neighborhoods"] as? NSArray
if neighborhoods != nil && neighborhoods!.count > 0 {
if !address.isEmpty {
address += ", "
}
address += neighborhoods![0] as! String
}
}
self.address = address
let categoriesArray = dictionary["categories"] as? [[String]]
if categoriesArray != nil {
var categoryNames = [String]()
for category in categoriesArray! {
let categoryName = category[0]
categoryNames.append(categoryName)
}
categories = categoryNames.joined(separator: ", ")
} else {
categories = nil
}
let distanceMeters = dictionary["distance"] as? NSNumber
if distanceMeters != nil {
let milesPerMeter = 0.000621371
distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue)
} else {
distance = nil
}
let ratingImageURLString = dictionary["rating_img_url_large"] as? String
if ratingImageURLString != nil {
ratingImageURL = URL(string: ratingImageURLString!)
} else {
ratingImageURL = nil
}
reviewCount = dictionary["review_count"] as? NSNumber
}
class func businesses(array: [NSDictionary]) -> [Business] {
var businesses = [Business]()
for dictionary in array {
let business = Business(dictionary: dictionary)
businesses.append(business)
}
return businesses
}
class func searchWithTerm(term: String, completion: @escaping ([Business]?, Error?) -> Void) {
_ = YelpClient.sharedInstance.searchWithTerm(term, completion: completion)
}
class func searchWithTerm(term: String, sort: Int?, radius: Int?, categories: [String]?, deals: Bool?, completion: @escaping ([Business]?, Error?) -> Void) -> Void {
_ = YelpClient.sharedInstance.searchWithTerm(term, sort: sort, radius: radius, categories: categories, deals: deals, completion: completion)
}
}
| 33.768421 | 167 | 0.569202 |
6489744cde2bdc0de277fb3548aaf8ce1a079272 | 522 | // DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//131. Palindrome Partitioning
//Given a string s, partition s such that every substring of the partition is a palindrome.
//Return all possible palindrome partitioning of s.
//Example:
//Input: "aab"
//Output:
//[
// ["aa","b"],
// ["a","a","b"]
//]
//class Solution {
// func partition(_ s: String) -> [[String]] {
// }
//}
// Time Is Money | 24.857143 | 91 | 0.680077 |
161653364a098ce9822c25462f5d838ca4ca1622 | 8,355 | //
// EULAUI.swift
// NoMADLoginOkta
//
// Created by Joel Rennich on 3/31/18.
// Copyright © 2018 Orchard & Grove. All rights reserved.
//
import Foundation
import Cocoa
class EULAUI : NSWindowController {
//MARK: Mech things
var mech: MechanismRecord?
//MARK: IB Outlets
@IBOutlet weak var titleText: NSTextField!
@IBOutlet weak var subTitleText: NSTextField!
@IBOutlet weak var doneButton: NSButton!
@IBOutlet weak var agreeButton: NSButton!
@IBOutlet var textView: NSTextView!
@IBOutlet weak var scrollView: NSScrollView!
@IBOutlet weak var scroller: NSScroller!
@IBOutlet weak var cancelButton: NSButton!
var backgroundWindow: NSWindow!
var effectWindow: NSWindow!
override func windowDidLoad() {
os_log("Calling super.windowDidLoad", log: uiLog, type: .default)
super.windowDidLoad()
let scrollNotification = NSNotification.Name.init(rawValue: "NSScrollViewDidLiveScroll")
NotificationCenter.default.addObserver(self, selector: #selector(checkScrollPosition), name: scrollNotification, object: nil)
os_log("EULA window showing.", log: eulaLog, type: .default )
// set everything to off
agreeButton.state = .off
doneButton.isEnabled = false
agreeButton.becomeFirstResponder()
// set the text
if let titleTextPref = getManagedPreference(key: .EULATitle) as? String {
os_log("Setting title text", log: eulaLog, type: .default )
titleText.stringValue = titleTextPref
}
if let subTitleTextPref = getManagedPreference(key: .EULASubTitle) as? String {
os_log("Setting subtitle text", log: eulaLog, type: .default )
subTitleText.stringValue = subTitleTextPref
}
if let text = getManagedPreference(key: .EULAText) as? String {
os_log("Setting eula text", log: eulaLog, type: .default )
// We may need to do some line break things here
textView.string = text.replacingOccurrences(of: "***", with: "\n")
} else {
// no text, let's move on to the next mechanism
os_log("No EULA text, not showing EULA.", log: eulaLog, type: .default )
completeLogin(authResult: .allow)
}
os_log("Configure EULA window", log: eulaLog, type: .default)
loginApperance()
os_log("create background windows", log: eulaLog, type: .default)
createBackgroundWindow()
}
@objc func checkScrollPosition() {
}
@IBAction func agreeAction(_ sender: Any) {
if agreeButton.state == .on {
doneButton.isEnabled = true
} else {
doneButton.isEnabled = false
}
}
@IBAction func cancelClick(_ sender: Any) {
// User doesn't want to agree, stop auth
os_log("User canceled EULA acceptance. Stopping login.", log: eulaLog, type: .default )
writeResponse(accept: false)
completeLogin(authResult: .userCanceled)
}
@IBAction func doneClick(_ sender: Any) {
os_log("User accepted EULA.", log: eulaLog, type: .default )
writeResponse(accept: true)
// complete the auth
completeLogin(authResult: .allow)
}
fileprivate func writeResponse(accept: Bool) {
var kNoMADPath = "/var/db/NoMADLogin"
if let newPath = getManagedPreference(key: .EULAPath) as? String {
kNoMADPath = newPath
}
let fm = FileManager.default
var objcB : ObjCBool? = true
// make a folder if one doesn't exist
if !fm.fileExists(atPath: kNoMADPath, isDirectory: &objcB!) {
do {
try fm.createDirectory(at: URL.init(fileURLWithPath: kNoMADPath), withIntermediateDirectories: true, attributes: nil)
} catch {
os_log("Unable to create folder.", log: eulaLog, type: .default )
}
}
let now = Date()
// Set timestamp
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
let dateInFormat = dateFormatter.string(from: now)
let df2 = DateFormatter.init()
df2.dateFormat = "yyyy-MM-dd-HHmmss"
var action = "Declined"
if accept {
action = "Accepted"
}
let fileName = kNoMADPath + "/" + "\(action)-" + df2.string(from: now)
// Write plist file
var dict : [String: Any] = [
"EULA Acceptance": accept,
"Date": dateInFormat,
// any other key values
]
if let username = getContextString(type: kAuthorizationEnvironmentUsername) {
dict["User"] = username
}
if let username = getHint(type: .noMADUser) {
dict["User"] = username
}
let someData = NSDictionary(dictionary: dict)
os_log("Writing user acceptance.", log: eulaLog, type: .default )
let isWritten = someData.write(toFile: fileName, atomically: true)
os_log("Writing user acceptance complete: @{public}", log: eulaLog, type: .default, String(describing: isWritten) )
}
//MARK: mech functions
/// Complete the NoLo process and either continue to the next Authorization Plugin or reset the NoLo window.
///
/// - Parameter authResult:`Authorizationresult` enum value that indicates if login should proceed.
fileprivate func completeLogin(authResult: AuthorizationResult) {
os_log("Complete login process", log: uiLog, type: .default)
let error = mech?.fPlugin.pointee.fCallbacks.pointee.SetResult((mech?.fEngine)!, authResult)
if error != noErr {
os_log("Got error setting authentication result", log: uiLog, type: .error)
}
NSApp.abortModal()
self.window?.close()
}
fileprivate func loginApperance() {
os_log("Setting window level", log: uiLog, type: .default)
self.window?.level = .screenSaver
self.window?.orderFrontRegardless()
self.window?.titlebarAppearsTransparent = true
self.window?.isMovable = false
self.window?.canBecomeVisibleWithoutLogin = true
}
fileprivate func createBackgroundWindow() {
var image: NSImage?
// Is a background image path set? If not just use gray.
if let backgroundImage = getManagedPreference(key: .BackgroundImage) as? String {
os_log("BackgroundImage preferences found.", log: uiLog, type: .default)
image = NSImage(contentsOf: URL(fileURLWithPath: backgroundImage))
}
for screen in NSScreen.screens {
let view = NSView()
view.wantsLayer = true
view.layer!.contents = image
backgroundWindow = NSWindow(contentRect: screen.frame,
styleMask: .fullSizeContentView,
backing: .buffered,
defer: true)
backgroundWindow.backgroundColor = .gray
backgroundWindow.contentView = view
backgroundWindow.makeKeyAndOrderFront(self)
backgroundWindow.canBecomeVisibleWithoutLogin = true
let effectView = NSVisualEffectView()
effectView.wantsLayer = true
effectView.blendingMode = .behindWindow
effectView.frame = screen.frame
effectWindow = NSWindow(contentRect: screen.frame,
styleMask: .fullSizeContentView,
backing: .buffered,
defer: true)
effectWindow.contentView = effectView
effectWindow.alphaValue = 0.8
effectWindow.orderFrontRegardless()
effectWindow.canBecomeVisibleWithoutLogin = true
}
}
}
//MARK: - ContextAndHintHandling Protocol
extension EULAUI: ContextAndHintHandling {}
| 35.253165 | 133 | 0.587911 |
38964690a559a668017f91b3c387cc6aad52b798 | 18,111 | //
// Map.swift
// MEGameTracker
//
// Created by Emily Ivie on 9/22/15.
// Copyright © 2015 urdnot. All rights reserved.
//
import UIKit
// swiftlint:disable file_length
public struct Map: Codable, MapLocationable, Eventsable {
enum CodingKeys: String, CodingKey {
case id
case isExplored
}
// MARK: Constants
// MARK: Properties
public var rawData: Data? // transient
public var generalData: DataMap
public internal(set) var id: String
public internal(set) var gameVersion: GameVersion
private var _annotationNote: String?
/// (GameModifying, GameRowStorable Protocol)
/// This value's game identifier.
public var gameSequenceUuid: UUID?
/// (DateModifiable Protocol)
/// Date when value was created.
public var createdDate = Date()
/// (DateModifiable Protocol)
/// Date when value was last changed.
public var modifiedDate = Date()
/// (CloudDataStorable Protocol)
/// Flag for whether the local object has changes not saved to the cloud.
public var isSavedToCloud = false
/// (CloudDataStorable Protocol)
/// A set of any changes to the local object since the last cloud sync.
public var pendingCloudChanges = CodableDictionary()
/// (CloudDataStorable Protocol)
/// A copy of the last cloud kit record.
public var lastRecordData: Data?
// Eventsable
private var _events: [Event]?
public var events: [Event] {
get { return _events ?? getEvents() } // cache?
set { _events = newValue }
}
public var rawEventDictionary: [CodableDictionary] { return generalData.rawEventDictionary }
public internal(set) var isExplored: Bool {
get {
return isExploredPerGameVersion[gameVersion] ?? false
}
set {
isExploredPerGameVersion[gameVersion] = newValue
}
}
public internal(set) var isExploredPerGameVersion: [GameVersion: Bool] = [:]
// MARK: Computed Properties
public var name: String { return generalData.name }
public var description: String? { return generalData.description }
public var image: String? { return generalData.image }
public var referenceSize: CGSize? { return generalData.referenceSize }
public var mapType: MapType { return generalData.mapType }
public var isMain: Bool { return generalData.isMain }
public var isSplitMenu: Bool { return generalData.isSplitMenu }
public var relatedLinks: [String] { return generalData.relatedLinks }
public var sideEffects: [String] { return generalData.sideEffects }
public var relatedMissionIds: [String] { return generalData.relatedMissionIds }
public var isExplorable: Bool { return generalData.isExplorable }
public var parentMap: Map? {
if let id = inMapId {
return Map.get(id: id) // isNotify: false
}
return nil
}
/// **Warning:** no changes are saved.
public var relatedDecisionIds: [String] {
// Changing the value of decisionIds does not get saved.
// This is only for refreshing local data without a core data call.
get { return generalData.relatedDecisionIds }
set { generalData.relatedDecisionIds = newValue }
}
public func isAvailableInGame(_ gameVersion: GameVersion) -> Bool {
return generalData.isAvailable && events.filter({ (e: Event) in
return e.type == .unavailableInGame ? e.isBlockingInGame(gameVersion) : false
}).isEmpty
}
// MARK: MapLocationable
public var annotationNote: String? {
get { return _annotationNote ?? generalData.annotationNote }
set { _annotationNote = newValue }
}
public var mapLocationType: MapLocationType {
return generalData.mapLocationType
}
public var mapLocationPoint: MapLocationPoint? {
get { return generalData.mapLocationPoint }
set { generalData.mapLocationPoint = newValue }
}
public var inMapId: String? {
get { return generalData.inMapId }
set { generalData.inMapId = newValue }
}
public var inMissionId: String? {
get { return generalData.inMissionId }
set { generalData.inMissionId = newValue }
}
public var sortIndex: Int {
get { return generalData.sortIndex }
set {}
}
public var isHidden: Bool {
get { return generalData.isHidden }
set {}
}
public var isAvailable: Bool {
get { return isAvailableInGame(gameVersion) }
set {}
}
public var unavailabilityMessages: [String] {
get {
let blockingEvents = events.filter({ (e: Event) in return e.isBlockingInGame(App.current.gameVersion) })
if !blockingEvents.isEmpty {
if let unavailabilityInGameMessage = blockingEvents.filter({ (e: Event) -> Bool in
return e.type == .unavailableInGame
}).first?.description,
!unavailabilityInGameMessage.isEmpty {
return generalData.unavailabilityMessages + [unavailabilityInGameMessage]
} else {
return generalData.unavailabilityMessages
+ blockingEvents.map({ $0.description }).filter({ $0 != nil }).map({ $0! })
}
}
return generalData.unavailabilityMessages
}
set {}
}
public var linkToMapId: String? { return generalData.linkToMapId }
public var shownInMapId: String?
public var isShowInParentMap: Bool = false
public var isShowInList: Bool { return generalData.isShowInList }
public var isShowPin: Bool { return generalData.isShowPin }
public var isOpensDetail: Bool { return generalData.isOpensDetail }
// MARK: Change Listeners And Change Status Flags
/// (DateModifiable, GameRowStorable) Flag to indicate that there are changes pending a core data sync.
public var hasUnsavedChanges = false
public static var onChange = Signal<(id: String, object: Map?)>()
// MARK: Initialization
public init(
id: String,
gameSequenceUuid: UUID? = App.current.game?.uuid,
gameVersion: GameVersion? = nil,
generalData: DataMap,
events: [Event] = []
) {
self.id = id
self.gameSequenceUuid = gameSequenceUuid
self.gameVersion = gameVersion ?? generalData.gameVersion
self.generalData = generalData
self.events = events
setGeneralData()
}
public mutating func setGeneralData() {
self.gameVersion = generalData.gameVersion
}
public mutating func setGeneralData(_ generalData: DataMap) {
self.generalData = generalData
setGeneralData()
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
gameVersion = .game1
generalData = DataMap(id: id) // faulted for now
let isExploredString = try container.decodeIfPresent(String.self, forKey: .isExplored) ?? ""
isExploredPerGameVersion = Map.gameValuesFromIsExplored(gameValues: isExploredString)
try unserializeDateModifiableData(decoder: decoder)
try unserializeGameModifyingData(decoder: decoder)
try unserializeLocalCloudData(decoder: decoder)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(Map.gameValuesForIsExplored(isExploredPerGameVersion: isExploredPerGameVersion), forKey: .isExplored)
try serializeDateModifiableData(encoder: encoder)
try serializeGameModifyingData(encoder: encoder)
try serializeLocalCloudData(encoder: encoder)
}
}
// MARK: Retrieval Functions of Related Data
extension Map {
public func getBreadcrumbs() -> [AbbreviatedMapData] {
return generalData.getBreadcrumbs()
}
public func getCompleteBreadcrumbs() -> [AbbreviatedMapData] {
return generalData.getCompleteBreadcrumbs()
}
public func getMapLocations() -> [MapLocationable] {
return MapLocation.getAll(inMapId: id, gameVersion: gameVersion).sorted(by: MapLocation.sort)
}
// public func getMissions(isCompleted: Bool? = nil) -> [Mission] {
// let missions = MapLocation.getAllMissions(inMapId: id, gameVersion: gameVersion).flatMap { $0 as? Mission }
// if let isCompleted = isCompleted {
// return missions.filter { $0.isCompleted == isCompleted }.sorted(by: Mission.sort)
// }
// return missions
// }
//
// public func getMissionsRatio(missions: [Mission]) -> String {
// let acquired = missions.filter { $0.isCompleted }.count
// let pending = missions.count - acquired
// return "\(acquired)/\(pending)"
// }
//
// public func getItems(isAcquired: Bool? = nil) -> [Item] {
// let items = MapLocation.getAllItems(inMapId: id, gameVersion: gameVersion).flatMap { $0 as? Item }
// if let isAcquired = isAcquired {
// return items.filter { $0.isAcquired == isAcquired }.sorted(by: Item.sort)
// }
// return items
// }
//
// public func getItemsRatio(items: [Item]) -> String {
// let acquired = items.filter { $0.isAcquired }.count
// let pending = items.count - acquired
// return "\(acquired)/\(pending)"
// }
//
public func getChildMaps(isExplored: Bool? = nil) -> [Map] {
let maps = MapLocation.getAllMaps(inMapId: id, gameVersion: gameVersion)
.map({ $0 as? Map }).filter({ $0 != nil }).map({ $0! })
if let isExplored = isExplored {
return maps.filter { $0.isExplored == isExplored }.sorted(by: Map.sort)
}
return maps
}
/// Notesable source data
public func getNotes(completion: @escaping (([Note]) -> Void) = { _ in }) {
let id = self.id
DispatchQueue.global(qos: .background).async {
completion(Note.getAll(identifyingObject: .map(id: id)))
}
}
static func gameValuesForIsExplored(isExploredPerGameVersion: [GameVersion: Bool]) -> String {
var gameValues: [String] = []
for game in GameVersion.allCases {
gameValues.append(isExploredPerGameVersion[game] == true ? "1" : "0")
}
return "|\(gameValues.joined(separator: "|"))|"
}
static func gameValuesFromIsExplored(gameValues: String) -> [GameVersion: Bool] {
let pieces = gameValues.components(separatedBy: "|")
if pieces.count == 5 {
var values: [GameVersion: Bool] = [:]
values[.game1] = pieces[1] == "1"
values[.game2] = pieces[2] == "1"
values[.game3] = pieces[3] == "1"
return values
}
return [.game1: false, .game2: false, .game3: false]
}
}
// MARK: Basic Actions
extension Map {
/// - Returns: A new note object tied to this object
public func newNote() -> Note {
return Note(identifyingObject: .map(id: id))
}
}
// MARK: Data Change Actions
extension Map {
/// Returns a copy of this Map with a set of changes applies
public func changed(fromActionData data: [String: Any?]) -> Map {
if let isExplored = data["isExplored"] as? Bool {
return changed(isExplored: isExplored)
}
return self
}
/// Return a copy of this Map with gameVersion changed
public func changed(
gameVersion: GameVersion
) -> Map {
guard isDifferentGameVersion(gameVersion) else { return self }
var map = self
map.gameVersion = gameVersion
map.generalData = generalData.changed(gameVersion: gameVersion)
map.changeEffects(
isSave: false,
isNotify: false
)
return map
}
/// Return a copy of this Map with isExplored changed
public func changed(
isExplored: Bool,
isSave: Bool = true,
isNotify: Bool = true,
isCascadeChanges: EventDirection = .all
) -> Map {
guard self.isExplored != isExplored else { return self }
var map = self
map.isExplored = isExplored
map.changeEffects(
isSave: isSave,
isNotify: isNotify,
cloudChanges: ["isExplored": isExplored]
)
if isCascadeChanges != .none && !GamesDataBackup.current.isSyncing {
map.applyToHierarchy(
isExplored: isExplored,
isSave: isSave,
isCascadeChanges: isCascadeChanges
)
}
return map
}
private func isDifferentGameVersion(_ gameVersion: GameVersion) -> Bool {
return generalData.isDifferentGameVersion(gameVersion)
}
/// Performs common behaviors after an object change
private mutating func changeEffects(
isSave: Bool = true,
isNotify: Bool = true,
cloudChanges: [String: Any?] = [:]
) {
markChanged()
notifySaveToCloud(fields: cloudChanges)
if isSave {
_ = saveAnyChanges()
}
if isNotify {
Map.onChange.fire((id: self.id, object: self))
}
}
private mutating func applyToHierarchy(
isExplored: Bool,
isSave: Bool,
isCascadeChanges: EventDirection = .all
) {
// let maps = getChildMaps()
// if isCascadeChanges != .up {
// for childMap in maps where childMap.isExplorable && childMap.isExplored != isExplored {
// // complete/uncomplete all submaps if parent was just completed/uncompleted
// _ = childMap.changed(isExplored: isExplored, isSave: isSave, isCascadeChanges: .down)
// }
// }
if isCascadeChanges != .down, let parentMap = self.parentMap, parentMap.isExplorable {
let siblingMaps = parentMap.getChildMaps()
if !isExplored && parentMap.isExplored {
// uncomplete parent
// don't uncomplete other children
_ = parentMap.changed(isExplored: false, isSave: isSave, isCascadeChanges: .up)
} else if isExplored && !parentMap.isExplored {
let exploredCount = siblingMaps.filter({ $0 != self })
.filter({ $0.isExplorable && $0.isExplored }).count + 1
if exploredCount == siblingMaps.count {
// complete parent
_ = parentMap.changed(isExplored: true, isSave: isSave, isCascadeChanges: .up)
}
}
}
}
}
// MARK: Dummy data for Interface Builder
extension Map {
public static func getDummy(json: String? = nil) -> Map? {
// swiftlint:disable line_length
let json = json ?? "{\"id\":\"1\",\"gameVersion\":\"1\",\"name\":\"Sahrabarik\"}"
if var baseMap = try? defaultManager.decoder.decode(DataMap.self, from: json.data(using: .utf8)!) {
baseMap.isDummyData = true
let map = Map(id: "1", generalData: baseMap)
return map
}
// swiftlint:enable line_length
return nil
}
}
//// MARK: SerializedDataStorable
//extension Map: SerializedDataStorable {
//
// public func getData() -> SerializableData {
// var list: [String: SerializedDataStorable?] = [:]
// list["id"] = id
// list["isExplored"] = gameValuesForIsExplored()
//// list = serializeDateModifiableData(list: list)
//// list = serializeGameModifyingData(list: list)
//// list = serializeLocalCloudData(list: list)
// return SerializableData.safeInit(list)
// }
//
// public func gameValuesForIsExplored() -> String {
// var data: [String] = []
// for game in GameVersion.allCases {
// data.append(isExploredPerGameVersion[game] == true ? "1" : "0")
// }
// return "|\(data.joined(separator: "|"))|"
// }
//
//}
// MARK: SerializedDataRetrievable
//extension Map: SerializedDataRetrievable {
// public init?(data: SerializableData?) {
// let gameVersion = GameVersion(rawValue: data?["gameVersion"]?.string ?? "0") ?? .game1
// guard let data = data, let id = data["id"]?.string,
// let dataMap = DataMap.get(id: id),
// let uuidString = data["gameSequenceUuid"]?.string,
// let gameSequenceUuid = UUID(uuidString: uuidString)
// else {
// return nil
// }
//
// self.init(
// id: id,
// gameSequenceUuid: gameSequenceUuid,
// gameVersion: gameVersion,
// generalData: dataMap,
// data: data
// )
// }
//
// public mutating func setData(_ data: SerializableData) {
// id = data["id"]?.string ?? id
// if let gameVersion = GameVersion(rawValue: data["gameVersion"]?.string ?? "0") {
// self.gameVersion = gameVersion
// generalData.change(gameVersion: gameVersion)
//// _events = nil
// }
// if generalData.id != id {
// generalData = DataMap.get(id: id) ?? generalData
// _events = nil
// }
//
//// unserializeDateModifiableData(data: data)
//// unserializeGameModifyingData(data: data)
//// unserializeLocalCloudData(data: data)
//
// isExploredPerGameVersion = gameValuesFromIsExplored(data: data["isExplored"]?.string ?? "")
// }
//
// public func gameValuesFromIsExplored(data: String) -> [GameVersion: Bool] {
// let pieces = data.components(separatedBy: "|")
// if pieces.count == 5 {
// var values: [GameVersion: Bool] = [:]
// values[.game1] = pieces[1] == "1"
// values[.game2] = pieces[2] == "1"
// values[.game3] = pieces[3] == "1"
// return values
// }
// return [.game1: false, .game2: false, .game3: false]
// }
//
//}
// MARK: DateModifiable
extension Map: DateModifiable {}
// MARK: GameModifying
extension Map: GameModifying {}
// MARK: Sorting
extension Map {
static func sort(_ first: Map, _ second: Map) -> Bool {
if first.inMapId == nil && second.inMapId != nil {
return true
} else if first.isExplored != second.isExplored {
return second.isExplored // push to end
} else if first.isAvailable != second.isAvailable {
return first.isAvailable // push to start
} else {
return first.name < second.name // still unsure - all the others sort by id.
}
}
}
// MARK: Equatable
extension Map: Equatable {
public static func == (_ lhs: Map, _ rhs: Map) -> Bool { // not true equality, just same db row
return lhs.id == rhs.id
}
}
//// MARK: Hashable
//extension Map: Hashable {
// public var hashValue: Int { return id.hashValue }
//}
// swiftlint:enable file_length
| 33.292279 | 130 | 0.645298 |
210ccb369a4b4a630e06b86251fa0da512a342d0 | 306 | //
// Extras.swift
// Pitch_Perfect
//
// Created by admin on 10/3/18.
// Copyright © 2018 admin. All rights reserved.
//
import Foundation
enum imageNames: String {
case microphone
case stop
case chipmunk
case darthvader
case echo
case fast
case reverb
case slow
}
| 13.304348 | 48 | 0.647059 |
eb062de50aedfd68505fc08430f1c60986b75733 | 1,766 | //
// ViewController.swift
// IndicatorButton
//
// Created by gwangyonglee on 02/29/2020.
// Copyright (c) 2020 gwangyonglee. All rights reserved.
//
import UIKit
import IndicatorButton
class ViewController: UIViewController {
// MARK: - IBOutlet
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var normalButton: IndicatorButton!
@IBOutlet weak var shakeButton: IndicatorButton!
@IBOutlet weak var flashButton: IndicatorButton!
@IBOutlet weak var pulseButton: IndicatorButton!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
initShakeButton()
initFlashButton()
initPulseButton()
initProgrammaticallyButton()
}
private func initShakeButton() {
shakeButton.type = .shake
}
private func initFlashButton() {
flashButton.type = .flash
}
private func initPulseButton() {
pulseButton.type = .pulse
}
private func initProgrammaticallyButton() {
let indicatorButton = IndicatorButton(frame: CGRect(x: 0, y: 0, width: 125, height: 36), text: "button")
indicatorButton.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
stackView.addArrangedSubview(indicatorButton)
}
@IBAction func touchUpInsideButton(_ sender: IndicatorButton) {
sender.startAnimating {
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
sender.stopAnimating {
sender.isSelected = !sender.isSelected
}
}
}
}
@objc func buttonClicked(_ sender: IndicatorButton) {
sender.startAnimating {
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
sender.stopAnimating {
sender.isSelected = !sender.isSelected
}
}
}
}
}
| 25.594203 | 112 | 0.672707 |
8785edbffe76527a524fa32fc9c33145495db98e | 299 | //
// UIScrollView+Extension.swift
// EasyMyCleaner
//
// Created by Nguyen Trung on 30/12/2021.
//
import UIKit
extension UIScrollView {
var currentPage: Int {
let width = self.frame.width
let page = Int(round(self.contentOffset.x/width))
return page
}
}
| 15.736842 | 57 | 0.628763 |
79bca995fdcc05df81c05946edee5553d04c4a4e | 1,235 | //
// ExampleSwiftUIView.swift
// ClaymorphicKit
//
// Copyright © 2022 Chris Davis, https://www.nthState.com
//
// See https://github.com/nthState/ClaymorphicKit/blob/main/LICENSE for license information.
//
import SwiftUI
struct ExampleSwiftUIView {
@State var animate: Bool = false
}
extension ExampleSwiftUIView: View {
var body: some View {
VStack(spacing: 24) {
button1
button2
}
}
var button1: some View {
Button {
} label: {
Text("Hello, Earth!")
}
.frame(width: 140, height: 56)
.buttonStyle(ClaymorphicButtonStyle(color: .blue,
radius: 20,
inflation: 0.5))
}
var button2: some View {
Button {
} label: {
Text("Hello, Mars!")
}
.frame(width: 140, height: 56)
.buttonStyle(ClaymorphicButtonStyle(color: .red,
radius: 20,
inflation: 0.5,
animation: Animation.wiggleJiggle))
}
}
struct ExampleSwiftUIView_Previews: PreviewProvider {
static var previews: some View {
ExampleSwiftUIView()
}
}
| 20.932203 | 93 | 0.533603 |
037506ab3c6d5f055bc30655ac002ada2d3c5979 | 411 | // 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
{{}{{{{{return[T}c
| 41.1 | 78 | 0.737226 |
2f9025f8005b739368aea821f427714ba804e3ac | 535 | //
// Account.swift
// Walayem
//
// Created by MACBOOK PRO on 5/20/18.
// Copyright © 2018 Inception Innovation. All rights reserved.
//
import Foundation
class Account{
var month: String?
var amount_total: Double?
var state: Int
var orders_count: Int
init(record: [String: Any]){
self.month = record["month"] as? String
self.state = record["state"] as! Int
self.orders_count = record["orders_count"] as! Int
self.amount_total = record["amount_total"] as? Double
}
}
| 22.291667 | 63 | 0.633645 |
6a0c84cf011fc15541c7b493f8c09cc7725868b1 | 6,231 | //
// SQLite.swift
// MoreSQL
//
// Created by zhi zhou on 2017/1/17.
// Copyright © 2017年 zhi zhou. All rights reserved.
//
import UIKit
import FMDB
/**
* 将传入的不包含"自定义类型"的数组或字典, JSON化, 并存储于 "SQL数据库" 中, 方便存取.
*/
class SQLite: NSObject {
// MARK:- 属性
static let shared = SQLite()
/// 是否开启打印
var isPrint = true
/// 表名称
fileprivate var tableName: String?
/// 路径
fileprivate var dbPath: String?
/// 数据库
fileprivate var db: FMDatabase?
// MARK:- 方法
// MARK: >>> 开启数据库
/// 开启数据库
/// - parameter pathName: 数据库存放路径
/// - parameter tableName: 表名
func openDB(pathName: String? = nil, tableName: String) -> Bool {
if let pathName = pathName {
return open(pathName, tableName)
} else {
return open("data", tableName)
}
}
// 封装开启方法
fileprivate func open(_ pathName: String, _ tableName: String) -> Bool {
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
path = path + "/" + pathName + ".sqlite"
dbPath = path
db = FMDatabase(path: path)
if (db?.open())! {
self.tableName = tableName
_ = createTable()
remind("数据库开启成功")
return true
} else {
remind("数据库开启失败")
return false
}
}
// MARK: >>> 创建表
/// 创建表
func createTable() -> Bool {
let sql = "CREATE TABLE IF NOT EXISTS \(tableName!) (id INTEGER PRIMARY KEY AUTOINCREMENT,js BLOB);"
if (db?.executeUpdate(sql, withArgumentsIn: nil))! {
remind("创建表成功")
return true
} else {
remind("创建表失败")
return false
}
}
// MARK: >>> 插入数据
/// 插入数据
/// - parameter objc: 传入非自定义类型
/// - parameter inTable: 需要操作的表名
func insert(objc: Any, inTable: String? = nil) -> Bool {
var sql: String?
if inTable == nil {
sql = "INSERT INTO \(tableName!) (js) VALUES (?);"
} else {
sql = "INSERT INTO \(inTable!) (js) VALUES (?);"
}
let js = toJson(objc: objc)
if (db?.executeUpdate(sql, withArgumentsIn: [js!]))! {
remind("插入数据成功")
return true
} else {
remind("插入数据失败")
return false
}
}
// MARK: >>> 查询数据
/// 查询数据
/// - parameter inTable: 需要操作的表名
func query(inTable: String? = nil) -> [Any]? {
var sql: String?
if inTable == nil {
sql = "SELECT * FROM \(tableName!);"
} else {
sql = "SELECT * FROM \(inTable!);"
}
let set = db?.executeQuery(sql, withArgumentsIn: nil)
guard set != nil else {
return nil
}
var tempArray = [Any]()
while set!.next() {
let result = set?.object(forColumnName: "js")
if let result = result {
let objc = jsonToAny(json: result as! String)
if let objc = objc {
tempArray.append(objc)
}
}
}
return tempArray
}
// MARK: >>> 删除数据 (全部)
/// 删除 (全部) 数据
/// - parameter inTable: 需要操作的表名
func delete(inTable: String? = nil) -> Bool {
// 删除所有 或 where ..... 来进行判断筛选删除
var sql: String?
if inTable == nil {
sql = "DELETE FROM \(tableName!);"
} else {
sql = "DELETE FROM \(inTable!);"
}
if (db?.executeUpdate(sql, withArgumentsIn: nil))! {
remind("删除成功")
return true
} else {
remind("删除失败")
return false
}
}
// MARK: >>> 更新数据
/// 更新数据
/// - parameter newValue: 传入非自定义类型
/// - parameter inTable: 需要操作的表名
func update(newValue: Any, inTable: String? = nil) -> Bool {
let js = toJson(objc: newValue)
var sql: String?
if inTable == nil {
sql = "UPDATE \(tableName!) SET js = '\(js!)';"
} else {
sql = "UPDATE \(inTable!) SET js = '\(js!)';"
}
if (db?.executeUpdate(sql, withArgumentsIn: nil))! {
remind("修改成功")
return true
} else {
remind("修改失败")
return false
}
}
}
// MARK:- JSON、ANY 转换
extension SQLite {
/// **Any** 转换为 **JSON** 类型
/// - parameter objc: 传入非自定义类型
func toJson(objc: Any) -> String? {
let data = try? JSONSerialization.data(withJSONObject: objc, options: .prettyPrinted)
if let data = data {
return String(data: data, encoding: .utf8)
} else {
return nil
}
}
/// **JSON** 转换为 **Any** 类型
/// - parameter json: String 类型数据
func jsonToAny(json: String) -> Any? {
let data = json.data(using: .utf8)
if let data = data {
let anyObjc = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let anyObjc = anyObjc {
return anyObjc
} else {
return nil
}
} else {
return nil
}
}
}
// MARK:- 自定义 print 打印
extension SQLite {
/// 根据 **isPrint** 的值来决定是否打印
/// - parameter message: 打印信息
fileprivate func remind(_ message: String) {
if isPrint {
printDBug(message, isDetail: false)
}
}
/// 仅在 Debug 模式下打印
/// - parameter info: 打印信息
/// - parameter fileName: 打印所在的swift文件
/// - parameter methodName: 打印所在文件的类名
/// - parameter lineNumber: 打印事件发生在哪一行
/// - parameter isDetail: 是否打印详细信息 (默认: true)
func printDBug<T>(_ info: T, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line, isDetail: Bool = true) {
let file = (fileName as NSString).pathComponents.last!
#if DEBUG
if isDetail {
print("\(file) -> \(methodName) [line \(lineNumber)]: \(info)")
} else {
print(info)
}
#endif
}
}
| 26.402542 | 140 | 0.489809 |
1a2459e7ddc1a8cb4674dfeaedb7cc15ae58c4fa | 1,229 | //
// DetailViewController.swift
// Project7-GCD
//
// Created by Carlos David on 22/08/2019.
// Copyright © 2019 cdalvaro. All rights reserved.
//
import UIKit
import WebKit
class DetailViewController: UIViewController {
var webView: WKWebView!
var detailItem: Petition?
override func loadView() {
webView = WKWebView()
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
guard let detailItem = detailItem else { return }
let html = """
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style> body { font-size: 150%; } </style>
</head>
<body>
\(detailItem.body)
</body>
</html>
"""
webView.loadHTMLString(html, baseURL: nil)
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 22.759259 | 106 | 0.590724 |
165087d7a74e82d34dca9350b8b1e3f5264edcfc | 2,403 | //
// SceneDelegate.swift
// GraphTutorial
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt in the project root for license information.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 44.5 | 147 | 0.71702 |
9cd1b3c63a4382927c8151695ce95ad6ec96a1a5 | 502 | //
// AlphaChangeable.swift
// FeedableTest
//
// Created by ParkSangHa on 2017. 3. 20..
// Copyright © 2017년 sanghapark1021. All rights reserved.
//
import Foundation
import UIKit
import Vigorous
protocol AlphaChangeable {}
extension AlphaChangeable where Self: UIView {
func alpha(to: CGFloat) -> Animatable {
return Animatable { animation, completion in
animation {
UIView.animate(withDuration: 0.4, animations: { self.alpha = to }) { completion($0) }
}
}
}
}
| 20.916667 | 93 | 0.679283 |
fb0d2ca5a1f2e2641bf20bf2d5d1943910c1d7dc | 903 | //
// NSViewContainerView.swift
// WebView
//
// Created by Ben Chatelain on 5/5/20.
//
#if os(macOS)
import AppKit
public class NSViewContainerView<ContentView: NSView>: NSView {
var contentView: ContentView? {
willSet {
contentView?.removeFromSuperview()
}
didSet {
if let contentView = contentView {
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentView.leadingAnchor.constraint(equalTo: leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: trailingAnchor),
contentView.topAnchor.constraint(equalTo: topAnchor),
contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
}
}
#endif
| 27.363636 | 83 | 0.602436 |
5bd3975f70f50af74dc1c8f3e8aab2801929ed7b | 3,817 | //
// BGSwiftyRSAError.swift
// begateway
//
// Created by FEDAR TRUKHAN on 9/2/19.
//
import Foundation
enum BGRSAError: Error {
case pemDoesNotContainKey
case keyRepresentationFailed(error: CFError?)
case keyGenerationFailed(error: CFError?)
case keyCreateFailed(error: CFError?)
case keyAddFailed(status: OSStatus)
case keyCopyFailed(status: OSStatus)
case tagEncodingFailed
case asn1ParsingFailed
case invalidAsn1RootNode
case invalidAsn1Structure
case invalidBase64String
case chunkDecryptFailed(index: Int)
case chunkEncryptFailed(index: Int)
case stringToDataConversionFailed
case dataToStringConversionFailed
case invalidDigestSize(digestSize: Int, maxChunkSize: Int)
case signatureCreateFailed(status: OSStatus)
case signatureVerifyFailed(status: OSStatus)
case pemFileNotFound(name: String)
case derFileNotFound(name: String)
case notAPublicKey
case notAPrivateKey
var localizedDescription: String {
switch self {
case .pemDoesNotContainKey:
return "Couldn't get data from PEM key: no data available after stripping headers"
case .keyRepresentationFailed(let error):
return "Couldn't retrieve key data from the keychain: CFError \(String(describing: error))"
case .keyGenerationFailed(let error):
return "Couldn't generate key pair: CFError: \(String(describing: error))"
case .keyCreateFailed(let error):
return "Couldn't create key reference from key data: CFError \(String(describing: error))"
case .keyAddFailed(let status):
return "Couldn't retrieve key data from the keychain: OSStatus \(status)"
case .keyCopyFailed(let status):
return "Couldn't copy and retrieve key reference from the keychain: OSStatus \(status)"
case .tagEncodingFailed:
return "Couldn't create tag data for key"
case .asn1ParsingFailed:
return "Couldn't parse the ASN1 key data. Please file a bug at https://goo.gl/y67MW6"
case .invalidAsn1RootNode:
return "Couldn't parse the provided key because its root ASN1 node is not a sequence. The key is probably corrupt"
case .invalidAsn1Structure:
return "Couldn't parse the provided key because it has an unexpected ASN1 structure"
case .invalidBase64String:
return "The provided string is not a valid Base 64 string"
case .chunkDecryptFailed(let index):
return "Couldn't decrypt chunk at index \(index)"
case .chunkEncryptFailed(let index):
return "Couldn't encrypt chunk at index \(index)"
case .stringToDataConversionFailed:
return "Couldn't convert string to data using specified encoding"
case .dataToStringConversionFailed:
return "Couldn't convert data to string representation"
case .invalidDigestSize(let digestSize, let maxChunkSize):
return "Provided digest type produces a size (\(digestSize)) that is bigger than the maximum chunk size \(maxChunkSize) of the RSA key"
case .signatureCreateFailed(let status):
return "Couldn't sign provided data: OSStatus \(status)"
case .signatureVerifyFailed(let status):
return "Couldn't verify signature of the provided data: OSStatus \(status)"
case .pemFileNotFound(let name):
return "Couldn't find a PEM file named '\(name)'"
case .derFileNotFound(let name):
return "Couldn't find a DER file named '\(name)'"
case .notAPublicKey:
return "Provided key is not a valid RSA public key"
case .notAPrivateKey:
return "Provided key is not a valid RSA pivate key"
}
}
}
| 45.440476 | 147 | 0.682473 |
e4637b945fa55224325f70bb555537e283cbec14 | 1,995 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// SitePropertiesProtocol is site resource specific properties
public protocol SitePropertiesProtocol : Codable {
var state: String? { get set }
var hostNames: [String]? { get set }
var repositorySiteName: String? { get set }
var usageState: UsageStateEnum? { get set }
var enabled: Bool? { get set }
var enabledHostNames: [String]? { get set }
var availabilityState: SiteAvailabilityStateEnum? { get set }
var hostNameSslStates: [HostNameSslStateProtocol?]? { get set }
var serverFarmId: String? { get set }
var reserved: Bool? { get set }
var lastModifiedTimeUtc: Date? { get set }
var siteConfig: SiteConfigProtocol? { get set }
var trafficManagerHostNames: [String]? { get set }
var scmSiteAlsoStopped: Bool? { get set }
var targetSwapSlot: String? { get set }
var hostingEnvironmentProfile: HostingEnvironmentProfileProtocol? { get set }
var clientAffinityEnabled: Bool? { get set }
var clientCertEnabled: Bool? { get set }
var hostNamesDisabled: Bool? { get set }
var outboundIpAddresses: String? { get set }
var possibleOutboundIpAddresses: String? { get set }
var containerSize: Int32? { get set }
var dailyMemoryTimeQuota: Int32? { get set }
var suspendedTill: Date? { get set }
var maxNumberOfWorkers: Int32? { get set }
var cloningInfo: CloningInfoProtocol? { get set }
var snapshotInfo: SnapshotRecoveryRequestProtocol? { get set }
var resourceGroup: String? { get set }
var isDefaultContainer: Bool? { get set }
var defaultHostName: String? { get set }
var slotSwapStatus: SlotSwapStatusProtocol? { get set }
var httpsOnly: Bool? { get set }
}
| 48.658537 | 96 | 0.682707 |
f7f5745fc2e62aa74c8692ca4a9cfd3df2934ee4 | 567 | import Routing
import Core
/// Objects conforming to this protocol can be used
/// to add collections of rotues to a route builder.
public protocol RouteCollection {
func build(_ builder: RouteBuilder) throws
}
extension RouteBuilder {
/// Adds the collection of routes
public func collection<C: RouteCollection>(_ c: C) throws {
try c.build(self)
}
/// Adds the collection of routes
public func collection<C: RouteCollection & EmptyInitializable>(_ c: C.Type) throws {
let c = try C()
try c.build(self)
}
}
| 25.772727 | 89 | 0.675485 |
897047dc42b34f118dbe3a2442ca639565cb0953 | 2,536 | // Copyright 2019 RBKmoney
//
// 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 UIKit
final class PaymentRouterDefaultRootViewController: PaymentRouterRootViewController {
// MARK: - Types
typealias TransitionConfigurator = PaymentRouterRootViewControllerTransitionConfigurator & UINavigationControllerDelegate
// MARK: - Initialization
init(navigationController: UINavigationController, transitionConfigurator: TransitionConfigurator) {
self.navigationController = navigationController
self.transitionConfigurator = transitionConfigurator
navigationController.delegate = transitionConfigurator
}
// MARK: - PaymentRouterRootViewController
func setViewControllers(_ viewControllers: [UIViewController], animated: Bool, transitionStyle: TransitionStyle) {
transitionConfigurator.transitionStyle = transitionStyle
navigationController?.setViewControllers(viewControllers, animated: animated)
}
var viewControllers: [UIViewController] {
return navigationController?.viewControllers ?? []
}
// MARK: - Private
private var transitionConfigurator: PaymentRouterRootViewControllerTransitionConfigurator
private weak var navigationController: UINavigationController?
}
final class PaymentRouterDefaultPaymentDelegate: PaymentDelegate {
// MARK: - Initialization
init(paymentDelegate: PaymentDelegate) {
self.paymentDelegate = paymentDelegate
}
// MARK: - PaymentDelegate
func paymentCancelled(invoiceIdentifier: String) {
paymentDelegate?.paymentCancelled(invoiceIdentifier: invoiceIdentifier)
}
func paymentFinished(invoiceIdentifier: String, paymentMethod: PaymentMethod) {
paymentDelegate?.paymentFinished(invoiceIdentifier: invoiceIdentifier, paymentMethod: paymentMethod)
}
// MARK: - Private
private weak var paymentDelegate: PaymentDelegate?
}
extension NavigationTransitionConfigurator: PaymentRouterRootViewControllerTransitionConfigurator {
}
| 37.294118 | 125 | 0.772476 |
266c4f9584ea599a2895c77c77c5945f39fbc685 | 1,099 | import Time
import Async
import struct Dispatch.DispatchQoS
import class Dispatch.DispatchQueue
@inline(__always)
public func fiber(_ task: @escaping AsyncTask) {
FiberLoop.current.scheduler.async(task)
}
@inline(__always)
@discardableResult
public func yield() -> Fiber.State {
return FiberLoop.current.scheduler.yield()
}
@inline(__always)
@discardableResult
public func suspend() -> Fiber.State {
return FiberLoop.current.scheduler.suspend()
}
@inline(__always)
@discardableResult
public func sleep(until deadline: Time) -> Fiber.State {
return FiberLoop.current.wait(for: deadline)
}
@inline(__always)
public func now() -> Time {
return FiberLoop.current.now
}
/// Spawn DispatchQueue.global().async task and yield until it's done
@inline(__always)
public func syncTask<T>(
onQueue queue: DispatchQueue = DispatchQueue.global(),
qos: DispatchQoS = .background,
deadline: Time = .distantFuture,
task: @escaping () throws -> T
) throws -> T {
return try FiberLoop.current.syncTask(
qos: qos,
deadline: deadline,
task: task)
}
| 22.895833 | 69 | 0.719745 |
ebc680c34d36448b44da8199afe4f2274d3c9426 | 22,760 | //
// ShadowboxLinkViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 8/4/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import Anchorage
import AVFoundation
import AVKit
import MaterialComponents.MaterialProgressView
import RealmSwift
import SDWebImage
import YYText
class ShadowboxLinkViewController: MediaViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate, TextDisplayStackViewDelegate {
func linkTapped(url: URL, text: String) {
if !text.isEmpty {
self.showSpoiler(text)
} else {
self.doShow(url: url, heroView: nil, finalSize: nil, heroVC: nil)
}
}
func linkLongTapped(url: URL) {
}
var type: ContentType.CType = ContentType.CType.UNKNOWN
var textView: TextDisplayStackView!
var bodyScrollView = UIScrollView()
var embeddedVC: EmbeddableMediaViewController!
var content: Object?
var baseURL: URL?
var submission: RSubmission! {
return content as? RSubmission
}
var titleLabel: YYLabel!
var comment = UIImageView()
var upvote = UIImageView()
var downvote = UIImageView()
var more = UIImageView()
var baseBody = UIView()
var thumbImageContainer = UIView()
var thumbImage = UIImageView()
var commenticon = UIImageView()
var submissionicon = UIImageView()
var score = UILabel()
var box = UIStackView()
var buttons = UIStackView()
var comments = UILabel()
var infoContainer = UIView()
var info = UILabel()
var topBody = UIView()
var parentVC: ShadowboxViewController
var backgroundColor: UIColor {
didSet {
if parent is SwipeDownModalVC && parentVC.currentVc == self {
DispatchQueue.main.async {
UIView.animate(withDuration: 0.25) {
(self.parent as! SwipeDownModalVC).background!.backgroundColor = self.backgroundColor
}
}
}
}
}
init(url: URL?, content: Object?, parent: ShadowboxViewController) {
self.parentVC = parent
self.baseURL = url
self.content = content
self.backgroundColor = .black
super.init(nibName: nil, bundle: nil)
if content is RSubmission {
type = ContentType.getContentType(submission: content as? RSubmission)
} else {
type = ContentType.getContentType(baseUrl: baseURL)
}
if titleLabel == nil {
configureView()
configureLayout()
populateData()
doBackground()
titleLabel.preferredMaxLayoutWidth = self.view.frame.size.width - 48
}
doBackground()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureView() {
self.titleLabel = YYLabel(frame: CGRect(x: 75, y: 8, width: 0, height: 0)).then {
$0.accessibilityIdentifier = "Title"
$0.font = FontGenerator.fontOfSize(size: 18, submission: true)
$0.isOpaque = false
$0.numberOfLines = 0
}
self.upvote = UIImageView(frame: CGRect(x: 0, y: 0, width: 24, height: 24)).then {
$0.accessibilityIdentifier = "Upvote Button"
$0.contentMode = .center
$0.isOpaque = false
}
self.bodyScrollView = UIScrollView().then {
$0.accessibilityIdentifier = "Body scroll view"
}
self.downvote = UIImageView(frame: CGRect(x: 0, y: 0, width: 24, height: 20)).then {
$0.accessibilityIdentifier = "Downvote Button"
$0.contentMode = .center
$0.isOpaque = false
}
self.commenticon = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)).then {
$0.accessibilityIdentifier = "Comment Count Icon"
$0.image = LinkCellImageCache.commentsIcon.getCopy(withColor: .white)
$0.contentMode = .scaleAspectFit
$0.isOpaque = false
}
self.submissionicon = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10)).then {
$0.accessibilityIdentifier = "Score Icon"
$0.image = LinkCellImageCache.votesIcon.getCopy(withColor: .white)
$0.contentMode = .scaleAspectFit
$0.isOpaque = false
}
self.score = UILabel().then {
$0.accessibilityIdentifier = "Score Label"
$0.numberOfLines = 1
$0.font = FontGenerator.fontOfSize(size: 12, submission: true)
$0.textColor = .white
$0.isOpaque = false
}
self.comments = UILabel().then {
$0.accessibilityIdentifier = "Comment Count Label"
$0.numberOfLines = 1
$0.font = FontGenerator.fontOfSize(size: 12, submission: true)
$0.textColor = .white
$0.isOpaque = false
}
self.thumbImageContainer = UIView().then {
$0.accessibilityIdentifier = "Thumbnail Image Container"
$0.frame = CGRect(x: 0, y: 0, width: 85, height: 85)
$0.elevate(elevation: 2.0)
}
self.textView = TextDisplayStackView.init(fontSize: 16, submission: true, color: ColorUtil.baseAccent, width: 100, delegate: self).then {
$0.accessibilityIdentifier = "Self Text View"
}
self.textView.baseFontColor = .white
self.thumbImage = UIImageView().then {
$0.accessibilityIdentifier = "Thumbnail Image"
$0.backgroundColor = UIColor.white
$0.layer.cornerRadius = 10
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
self.info = UILabel().then {
$0.accessibilityIdentifier = "Banner Info"
$0.numberOfLines = 2
$0.font = FontGenerator.fontOfSize(size: 12, submission: true)
$0.textColor = .white
}
self.infoContainer = info.withPadding(padding: UIEdgeInsets.init(top: 4, left: 10, bottom: 4, right: 10)).then {
$0.accessibilityIdentifier = "Banner Info Container"
$0.clipsToBounds = true
}
self.box = UIStackView().then {
$0.accessibilityIdentifier = "Count Info Stack Horizontal"
$0.axis = .horizontal
$0.alignment = .center
}
self.thumbImageContainer.addSubview(self.thumbImage)
self.thumbImage.edgeAnchors == self.thumbImageContainer.edgeAnchors
baseBody.addSubviews(titleLabel)
box.addArrangedSubviews(submissionicon, horizontalSpace(2), score, horizontalSpace(8), commenticon, horizontalSpace(2), comments)
self.baseBody.addSubview(box)
self.buttons = UIStackView().then {
$0.accessibilityIdentifier = "Button Stack Horizontal"
$0.axis = .horizontal
$0.alignment = .center
$0.distribution = .fill
$0.spacing = 16
}
buttons.addArrangedSubviews( upvote, downvote)
self.baseBody.addSubview(buttons)
// TODO: - add gestures here
self.view.addSubview(baseBody)
self.view.addSubview(topBody)
baseBody.horizontalAnchors == self.view.horizontalAnchors + 12
baseBody.bottomAnchor == self.view.bottomAnchor - 12
topBody.horizontalAnchors == self.view.horizontalAnchors
topBody.bottomAnchor == baseBody.topAnchor
topBody.topAnchor == self.view.topAnchor
}
func configureLayout() {
baseBody.layoutMargins = UIEdgeInsets(top: 8, left: 16, bottom: 16, right: 16)
box.leftAnchor == baseBody.leftAnchor + 12
box.bottomAnchor == baseBody.bottomAnchor - 8
box.centerYAnchor == buttons.centerYAnchor // Align vertically with buttons
box.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical)
box.heightAnchor == CGFloat(24)
buttons.heightAnchor == CGFloat(24)
buttons.rightAnchor == baseBody.rightAnchor - 12
buttons.bottomAnchor == baseBody.bottomAnchor - 8
buttons.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical)
titleLabel.setContentCompressionResistancePriority(UILayoutPriority.required, for: .vertical)
titleLabel.topAnchor == baseBody.topAnchor
titleLabel.horizontalAnchors == baseBody.horizontalAnchors + 12
titleLabel.bottomAnchor == box.topAnchor - 8
}
func populateData() {
var archived = false
if let link = content as! RSubmission? {
archived = link.archived
upvote.image = LinkCellImageCache.upvote.getCopy(withColor: .white)
downvote.image = LinkCellImageCache.downvote.getCopy(withColor: .white)
var attrs: [String: Any] = [:]
switch ActionStates.getVoteDirection(s: link) {
case .down:
downvote.image = LinkCellImageCache.downvoteTinted
attrs = ([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.downvoteColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.boldFontOfSize(size: 12, submission: true)])
case .up:
upvote.image = LinkCellImageCache.upvoteTinted
attrs = ([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.upvoteColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.boldFontOfSize(size: 12, submission: true)])
default:
attrs = ([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): UIColor.white, convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.fontOfSize(size: 12, submission: true)])
}
score.attributedText = NSAttributedString(string: (link.score >= 10000 && SettingValues.abbreviateScores) ? String(format: " %0.1fk", (Double(link.score) / Double(1000))) : " \(link.score)", attributes: convertToOptionalNSAttributedStringKeyDictionary(attrs))
comments.text = "\(link.commentCount)"
titleLabel.attributedText = CachedTitle.getTitle(submission: link, full: true, false, true, gallery: false)
let size = CGSize(width: self.view.frame.size.width - 48, height: CGFloat.greatestFiniteMagnitude)
let layout = YYTextLayout(containerSize: size, text: titleLabel.attributedText!)!
titleLabel.textLayout = layout
titleLabel.heightAnchor == layout.textBoundingSize.height
} else if let link = content as! RComment? {
archived = link.archived
upvote.image = LinkCellImageCache.upvote
downvote.image = LinkCellImageCache.downvote
var attrs: [String: Any] = [:]
switch ActionStates.getVoteDirection(s: link) {
case .down:
downvote.image = LinkCellImageCache.downvoteTinted
attrs = ([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.downvoteColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.boldFontOfSize(size: 12, submission: true)])
case .up:
upvote.image = LinkCellImageCache.upvoteTinted
attrs = ([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.upvoteColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.boldFontOfSize(size: 12, submission: true)])
default:
attrs = ([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): UIColor.white, convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.fontOfSize(size: 12, submission: true)])
}
score.attributedText = NSAttributedString.init(string: (link.score >= 10000 && SettingValues.abbreviateScores) ? String(format: " %0.1fk", (Double(link.score) / Double(1000))) : " \(link.score)", attributes: convertToOptionalNSAttributedStringKeyDictionary(attrs))
// TODO: - what to do here titleLabel.setText(CachedTitle.getTitle(submission: link, full: false, false, true))
}
if archived || !AccountController.isLoggedIn {
upvote.isHidden = true
downvote.isHidden = true
}
}
func doBackground() {
if SettingValues.blackShadowbox {
self.backgroundColor = .black
} else {
if content is RSubmission {
let thumbnail = (content as! RSubmission).thumbnailUrl
if let url = URL(string: thumbnail) {
SDWebImageDownloader.shared.downloadImage(with: url, options: [.allowInvalidSSLCertificates, .scaleDownLargeImages], progress: { (_, _, _) in
}, completed: { (image, _, _, _) in
if image != nil {
DispatchQueue.global(qos: .background).async {
let average = image!.areaAverage()
DispatchQueue.main.async {
self.backgroundColor = average
}
}
}
})
}
}
}
}
func populateContent() {
self.baseBody.addTapGestureRecognizer {
self.comments(self.view)
}
self.topBody.addTapGestureRecognizer {
self.content(self.view)
}
self.upvote.addTapGestureRecognizer {
self.upvote(self.upvote)
}
self.downvote.addTapGestureRecognizer {
self.downvote(self.downvote)
}
if type == .SELF {
topBody.addSubview(bodyScrollView)
bodyScrollView.horizontalAnchors == topBody.horizontalAnchors + 12
bodyScrollView.verticalAnchors == topBody.verticalAnchors + 12
textView.estimatedWidth = UIScreen.main.bounds.width - 24
textView.setTextWithTitleHTML(NSMutableAttributedString(), htmlString: (content as! RSubmission).htmlBody)
bodyScrollView.addSubview(textView)
textView.leftAnchor == bodyScrollView.leftAnchor
textView.widthAnchor == textView.estimatedWidth
textView.topAnchor == bodyScrollView.topAnchor + 50
textView.heightAnchor == textView.estimatedHeight + 50
bodyScrollView.contentSize = CGSize(width: bodyScrollView.bounds.width, height: textView.estimatedHeight + 100)
parentVC.panGestureRecognizer?.require(toFail: bodyScrollView.panGestureRecognizer)
parentVC.panGestureRecognizer2?.require(toFail: bodyScrollView.panGestureRecognizer)
} else if type != .ALBUM && (ContentType.displayImage(t: type) || ContentType.displayVideo(t: type)) && ((content is RSubmission && !(content as! RSubmission).nsfw) || SettingValues.nsfwPreviews) {
if !ContentType.displayVideo(t: type) || !populated {
let embed = ModalMediaViewController.getVCForContent(ofType: type, withModel: EmbeddableMediaDataModel(baseURL: baseURL, lqURL: nil, text: nil, inAlbum: false, buttons: false))
if embed != nil {
self.embeddedVC = embed
self.addChild(embed!)
embed!.didMove(toParent: self)
self.topBody.addSubview(embed!.view)
embed!.view.horizontalAnchors == topBody.horizontalAnchors
embed!.view.topAnchor == topBody.safeTopAnchor
embed!.view.bottomAnchor == topBody.bottomAnchor
} else {
//Shouldn't be here
}
} else {
populated = false
}
} else if type == .LINK || type == .NONE || type == .ALBUM || ((content is RSubmission && (content as! RSubmission).nsfw) && !SettingValues.nsfwPreviews) {
topBody.addSubviews(thumbImageContainer, infoContainer)
thumbImageContainer.centerAnchors == topBody.centerAnchors
infoContainer.horizontalAnchors == topBody.horizontalAnchors
infoContainer.topAnchor == thumbImageContainer.bottomAnchor + 8
let thumbSize: CGFloat = 85
thumbImageContainer.widthAnchor == thumbSize
thumbImageContainer.heightAnchor == thumbSize
var text = ""
switch type {
case .ALBUM:
text = ("Album")
case .EXTERNAL:
text = "External Link"
case .LINK, .EMBEDDED, .NONE:
text = "Link"
case .DEVIANTART:
text = "Deviantart"
case .TUMBLR:
text = "Tumblr"
case .XKCD:
text = ("XKCD")
case .GIF:
text = ("GIF")
case .IMGUR:
text = ("Imgur")
case .VIDEO:
text = "YouTube"
case .STREAMABLE:
text = "Streamable"
case .VID_ME:
text = ("Vid.me")
case .REDDIT:
text = ("Reddit content")
default:
text = "Link"
}
let finalText = NSMutableAttributedString.init(string: text, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): UIColor.white, convertFromNSAttributedStringKey(NSAttributedString.Key.font): FontGenerator.boldFontOfSize(size: 16, submission: true)]))
finalText.append(NSAttributedString.init(string: "\n\(baseURL!.host ?? baseURL!.absoluteString)"))
info.textAlignment = .center
info.attributedText = finalText
if content is RSubmission {
let submission = content as! RSubmission
if submission.nsfw {
thumbImage.image = LinkCellImageCache.nsfw
} else if submission.thumbnailUrl == "web" || submission.thumbnailUrl.isEmpty {
if type == .REDDIT {
thumbImage.image = LinkCellImageCache.reddit
} else {
thumbImage.image = LinkCellImageCache.web
}
} else {
let thumbURL = submission.thumbnailUrl
DispatchQueue.global(qos: .userInteractive).async {
self.thumbImage.sd_setImage(with: URL.init(string: thumbURL), placeholderImage: LinkCellImageCache.web)
}
}
} else {
if type == .REDDIT {
thumbImage.image = LinkCellImageCache.reddit
} else {
thumbImage.image = LinkCellImageCache.web
}
}
} else if type == .ALBUM {
//We captured it above. Possible implementation in the future?
} else {
//Nothing
}
}
@objc func upvote(_ sender: AnyObject) {
if content is RSubmission {
let submission = content as! RSubmission
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.setVote(ActionStates.getVoteDirection(s: submission) == .up ? .none : .up, name: submission.getId(), completion: { (_) in
})
ActionStates.setVoteDirection(s: submission, direction: ActionStates.getVoteDirection(s: submission) == .up ? .none : .up)
History.addSeen(s: submission)
populateData()
} catch {
}
}
}
@objc func downvote(_ sender: AnyObject) {
if content is RSubmission {
let submission = content as! RSubmission
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.setVote(ActionStates.getVoteDirection(s: submission) == .down ? .none : .down, name: submission.getId(), completion: { (_) in
})
ActionStates.setVoteDirection(s: submission, direction: ActionStates.getVoteDirection(s: submission) == .down ? .none : .down)
History.addSeen(s: submission)
populateData()
} catch {
}
}
}
@objc func comments(_ sender: AnyObject) {
if content is RSubmission {
VCPresenter.openRedditLink((content as! RSubmission).permalink, nil, self)
} else if content is RComment {
VCPresenter.openRedditLink((content as! RComment).permalink, nil, self)
}
}
@objc func content(_ sender: AnyObject) {
doShow(url: baseURL!, heroView: thumbImageContainer.isHidden ? embeddedVC.view : thumbImage, finalSize: nil, heroVC: parentVC)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if populated && embeddedVC is VideoMediaViewController {
let video = embeddedVC as! VideoMediaViewController
video.videoView.player?.play()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !populated {
populateContent()
populated = true
}
}
var first = true
var populated = false
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if embeddedVC is VideoMediaViewController {
let video = embeddedVC as! VideoMediaViewController
video.videoView.player?.pause()
}
}
func horizontalSpace(_ space: CGFloat) -> UIView {
return UIView().then {
$0.widthAnchor == space
}
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) })
}
| 44.023211 | 346 | 0.602109 |
d59c206670db100731bc02398e85296d65ff579e | 1,511 | //
// FEUsuario.swift
// Digipro
//
// Created by Jonathan Viloria M on 20/07/18.
// Copyright © 2018 Digipro Movil. All rights reserved.
//
import Foundation
public class FEUsuario: EVObject{
public var User = "default"
public var Password = ""
public var IP = ""
public var ProyectoID = 0
public var AplicacionID = 0
public var NombreCompleto = ""
public var GrupoAdminID = 0
public var Foto = ""
public var PermisoScreenshot = true
public var PermisoEditarFormato = true
public var PermisoDescargarAnexos = true
public var PendientesEstadoMapa = 0
public var PermisoValidarFormato = true
public var PermisoVerMapa = true
public var PermisoBorrarFormato = true
public var PermisoPendientesPorEnviar = true
public var PermisoNuevoFormato = true
public var PermisoSalirConCambios = true
public var PermisoVisualizarFormato = true
public var PasswordEncoded = ""
public var CurrentPasswordEncoded = ""
public var PasswordNuevo = ""
public var NewPasswordEncoded = ""
public var Consultas: Array<FETipoReporte> = [FETipoReporte]()
override public func skipPropertyValue(_ value: Any, key: String) -> Bool {
if let value = value as? String, value.count == 0 || value == "null" {
return true
} else if let value = value as? NSArray, value.count == 0 {
return true
} else if value is NSNull {
return true
}
return false
}
}
| 30.836735 | 79 | 0.665122 |
8fafd6d44b29a5fcf4ed303ebc7bed14bfaa4eb4 | 854 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "YPImagePicker",
defaultLocalization: "en",
platforms: [
.iOS(.v12)
],
products: [
.library(name: "YPImagePicker", targets: ["YPImagePicker"])
],
dependencies: [
.package(
url: "https://github.com/freshOS/Stevia",
.exact("4.8.0")
),
.package(
url: "https://github.com/HHK1/PryntTrimmerView",
.exact("4.0.2")
)
],
targets: [
.target(
name: "YPImagePicker",
dependencies: ["Stevia", "PryntTrimmerView"],
path: "Source",
exclude: ["Info.plist", "YPImagePickerHeader.h"]
)
]
)
| 25.117647 | 96 | 0.540984 |
1cd83c9805218284b45bfccd66fe7344b44368cf | 911 | //
// InfiniteScrollSettings.swift
// InfiniteScroll
//
// Created by Ion Postolachi on 12/23/19.
// Copyright © 2019 Ion Postolachi. All rights reserved.
//
import UIKit
public protocol SpinnerViewProtocol: UIView {
func startAnimating()
func stopAnimating()
}
extension UIActivityIndicatorView: SpinnerViewProtocol {}
final class InfiniteScrollSettings {
var enabled: Bool = false
var requestInProgress: Bool = false
var completion: ((UIScrollView) -> Void)?
var triggerOffset: CGFloat = 0
var spinnerView: SpinnerViewProtocol?
lazy var loaderView: UIView = createLoaderView()
var shouldRemoveInfiniteScrollHandler: () -> Bool = { return false }
private func createLoaderView() -> UIView {
let view = UIView()
view.backgroundColor = .clear
view.translatesAutoresizingMaskIntoConstraints = false
return view
}
}
| 26.028571 | 72 | 0.698134 |
14d4c4d796188ac36d9a424061f77d75dfea5810 | 818 | //
// RegularSizeRegularTypeLabel.swift
// Theme
//
// Created by Ankur Kesharwani on 23/02/17.
// Copyright © 2017 Ankur Kesharwani. All rights reserved.
//
import UIKit
public class RegularSizeRegularTypeLabel: UILabel {
@IBInspectable public var themeTextColor: String? {
didSet {
self.textColor = Theme.Color.keyToColorMap[themeTextColor!] ?? self.textColor
}
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
private func setup() {
if themeTextColor == nil {
self.textColor = Theme.Color.Text.black
}
self.font = Theme.Font.regular(size: .regular)
}
}
| 22.108108 | 89 | 0.622249 |
67c54463d8a8ec706ad7895eddd64783eade125d | 2,775 | //
// SceneDelegate.swift
// CreditCardAnimationSwiftUI
//
// Created by Burak Tunc on 9.07.2020.
// Copyright © 2020 Burak Tunç. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.692308 | 147 | 0.707387 |
de51ab31f6cbf36d227cc67447560eea0c03a4ad | 1,560 | //
// YahooFinanceDecoder.swift
// StockBar
//
// Created by Hongliang Fan on 2020-06-20.
import Foundation
struct Overview: Codable {
let chart: ChartClass
}
struct ChartClass: Codable {
let result: [Result]?
let error: Error?
}
struct Result: Codable {
let meta: Meta
}
struct Meta: Codable {
let currency : String?
let symbol: String
let regularMarketTime: Int
let exchangeTimezoneName: String
let regularMarketPrice: Double
let chartPreviousClose: Double
func getPrice()->String {
return (currency ?? "Price") + " " + String(format: "%.2f", regularMarketPrice)
}
func getChange()->String {
return String(format: "%+.2f",regularMarketPrice - chartPreviousClose)
}
func getLongChange()->String {
return String(format: "%+.4f",regularMarketPrice - chartPreviousClose)
}
func getChangePct()->String {
return String(format: "%+.4f", 100*(regularMarketPrice - chartPreviousClose)/chartPreviousClose)+"%"
}
func getTimeInfo()->String {
let date = Date(timeIntervalSince1970: TimeInterval(regularMarketTime))
let tradeTimeZone = TimeZone(identifier: exchangeTimezoneName)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm zzz"
dateFormatter.timeZone = tradeTimeZone
return dateFormatter.string(from: date)
}
}
struct Error: Codable {
let errorDescription: String
enum CodingKeys: String, CodingKey {
case errorDescription = "description"
}
}
| 26.440678 | 108 | 0.672436 |
bb6e48c15af32103e0b0ed632c827d77dad9015e | 889 | //
// CoreDataStack.swift
// HomeCook
//
// Created by nate.taylor_macbook on 05/12/2019.
// Copyright © 2019 natetaylor. All rights reserved.
//
import Foundation
import CoreData
/// Class for core data stack (with persistent container)
internal final class CoreDataStack {
static let shared: CoreDataStack = {
let coreDataStack = CoreDataStack()
return coreDataStack
}()
let persistentContainer: NSPersistentContainer
private init() {
let group = DispatchGroup()
persistentContainer = NSPersistentContainer(name: "HomeCookModel")
group.enter()
persistentContainer.loadPersistentStores { storeDescription, error in
if let error = error {
assertionFailure(error.localizedDescription)
}
group.leave()
}
group.wait()
}
}
| 24.694444 | 77 | 0.633296 |
013efbf19a6d4515938f9c56763b1f3b4467eb4b | 1,573 | //
// ProgrammingCardView.swift
// ios
//
// Created by Tom Burke on 12/16/21.
// Copyright © 2021 Bruin Fitness. All rights reserved.
//
import SwiftUI
struct ProgrammingCardView: View {
var cardHeader: String
var cardDescription: String
var cardWidth: CGFloat = 260
var body: some View {
VStack(spacing: 0) {
Text(cardHeader)
.font(.headline)
.foregroundColor(Color("bruinGreenColor"))
.frame(width: cardWidth)
.padding()
.background(Color("workoutCardColor"))
.cornerRadius(20, corners: [.topLeft, .topRight])
Divider()
.frame(width: cardWidth)
Text(cardDescription)
.multilineTextAlignment(.leading)
.font(.subheadline)
.foregroundColor(.white)
.frame(width: cardWidth)
.fixedSize()
.padding()
.background(Color("workoutCardColor"))
.cornerRadius(20, corners: [.bottomLeft, .bottomRight])
}
}
}
struct ProgrammingCardView_Previews: PreviewProvider {
static var previews: some View {
ProgrammingCardView(cardHeader: "WARM UP", cardDescription: "2:00 Bike\n\n2 ROUNDS\n10 Toe touch jumping jacks\n10 Banded Pull Aparts\n20 Shoulder Taps\n\nInto...\n\n2 ROUNDS *\n10 scap Pull-Ups\n5 tempo ring rows\n10 scap push ups\n5 tempo knee push-ups\n\n* Perform slow :03 descent on each rep for the tempo ring row and tempo push-ups")
}
}
| 34.195652 | 348 | 0.596313 |
f5126679e41c7aa41a1345f3455fa50e97ab7822 | 244 | //
// PosterCell.swift
// Flix
//
// Created by Rohan Gupta on 1/17/18.
// Copyright © 2018 Rohan Gupta. All rights reserved.
//
import UIKit
class PosterCell: UICollectionViewCell {
@IBOutlet var posterImageView: UIImageView!
}
| 16.266667 | 54 | 0.688525 |
09393a926b5ddeff7a287e0a6eb69afa5c4995b9 | 6,344 | //
// Created by Jake Lin on 11/19/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
/**
Predefined Animation Type
*/
public indirect enum AnimationType {
case slide(way: Way, direction: Direction)
case squeeze(way: Way, direction: Direction)
case slideFade(way: Way, direction: Direction)
case squeezeFade(way: Way, direction: Direction)
case fade(way: FadeWay)
case zoom(way: Way)
case zoomInvert(way: Way)
case shake(repeatCount: Int)
case pop(repeatCount: Int)
case squash(repeatCount: Int)
case flip(along: Axis)
case morph(repeatCount: Int)
case flash(repeatCount: Int)
case wobble(repeatCount: Int)
case swing(repeatCount: Int)
case rotate(direction: RotationDirection, repeatCount: Int)
case moveTo(x: Double, y: Double)
case moveBy(x: Double, y: Double)
case scale(fromX: Double, fromY: Double, toX: Double, toY: Double)
case compound(animations: [AnimationType], run: Run)
case none
public enum FadeWay: String {
case `in`, out, inOut = "inout", outIn = "outin"
}
public enum Way: String {
case out, `in`
}
public enum Axis: String {
case x, y
}
public enum Direction: String {
case left, right, up, down
func isVertical() -> Bool {
return self == .down || self == .up
}
}
public enum RotationDirection: String {
case cw, ccw
}
public enum Run: String {
case sequential, parallel
}
}
extension AnimationType {
public static func scaleTo(x: Double, y: Double) -> AnimationType {
return .scale(fromX: 1, fromY: 1, toX: x, toY: y)
}
public static func scaleFrom(x: Double, y: Double) -> AnimationType {
return .scale(fromX: x, fromY: y, toX: 1, toY: 1)
}
}
extension AnimationType: IBEnum {
public init(string: String?) {
guard let string = string else {
self = .none
return
}
let (name, params) = AnimationType.extractNameAndParams(from: string.parseNameAndParams)
switch name {
case "slide":
self = .slide(way: Way(raw: params[safe: 0], defaultValue: .in), direction: Direction(raw: params[safe: 1], defaultValue: .left))
case "squeeze":
self = .squeeze(way: Way(raw: params[safe: 0], defaultValue: .in), direction: Direction(raw: params[safe: 1], defaultValue: .left))
case "fade":
self = .fade(way: FadeWay(raw: params[safe: 0], defaultValue: .in))
case "slidefade":
self = .slideFade(way: Way(raw: params[safe: 0], defaultValue: .in), direction: Direction(raw: params[safe: 1], defaultValue: .left))
case "squeezefade":
self = .squeezeFade(way: Way(raw: params[safe: 0], defaultValue: .in), direction: Direction(raw: params[safe: 1], defaultValue: .left))
case "zoom":
self = .zoom(way: Way(raw: params[safe: 0], defaultValue: .in))
case "zoominvert":
self = .zoomInvert(way: Way(raw: params[safe: 0], defaultValue: .in))
case "shake":
let repeatCount = retrieveRepeatCount(string: params[safe: 0])
self = .shake(repeatCount: repeatCount)
case "pop":
let repeatCount = retrieveRepeatCount(string: params[safe: 0])
self = .pop(repeatCount: repeatCount)
case "squash":
let repeatCount = retrieveRepeatCount(string: params[safe: 0])
self = .squash(repeatCount: repeatCount)
case "flip":
let axis = Axis(raw: params[safe: 0], defaultValue: .x)
self = .flip(along: axis)
case "morph":
let repeatCount = retrieveRepeatCount(string: params[safe: 0])
self = .morph(repeatCount: repeatCount)
case "flash":
let repeatCount = retrieveRepeatCount(string: params[safe: 0])
self = .flash(repeatCount: repeatCount)
case "wobble":
let repeatCount = retrieveRepeatCount(string: params[safe: 0])
self = .wobble(repeatCount: repeatCount)
case "swing":
let repeatCount = retrieveRepeatCount(string: params[safe: 0])
self = .swing(repeatCount: repeatCount)
case "rotate":
let repeatCount = retrieveRepeatCount(string: params[safe: 1])
self = .rotate(direction: RotationDirection(raw: params[safe: 0], defaultValue: .cw), repeatCount: repeatCount)
case "moveto":
self = .moveTo(x: params[safe: 0]?.toDouble() ?? 0, y: params[safe: 1]?.toDouble() ?? 0)
case "moveby":
self = .moveBy(x: params[safe: 0]?.toDouble() ?? 0, y: params[safe: 1]?.toDouble() ?? 0)
case "scale":
let fromX = params[safe: 0]?.toDouble() ?? 0
let fromY = params[safe: 1]?.toDouble() ?? 0
let toX = params[safe: 2]?.toDouble() ?? 1
let toY = params[safe: 3]?.toDouble() ?? 1
self = .scale(fromX: fromX, fromY: fromY, toX: toX, toY: toY)
case "scalefrom":
self = .scaleFrom(x: params[safe: 0]?.toDouble() ?? 0, y: params[safe: 1]?.toDouble() ?? 0)
case "scaleto":
self = .scaleTo(x: params[safe: 0]?.toDouble() ?? 0, y: params[safe: 1]?.toDouble() ?? 0)
case "compound":
var params = params
if let last = params.popLast() {
var runP: Run
if let run = Run(raw: last) {
runP = run
} else {
params.append(last)
runP = .parallel
}
self = .compound(animations: params.map { $0.animationType ?? .none }, run: runP)
} else {
self = .none
}
default:
self = .none
}
}
}
private extension String {
var parseNameAndParams: String {
var string = self
if string.starts(with: "[") { // [ animation1, animation2, ...]
string = string.dropFirst().dropLast()
.replacingOccurrences(of: "(", with: "[")
.replacingOccurrences(of: ")", with: "]")
string = "compound("+string+", \(AnimationType.Run.sequential.rawValue))"
} else if string.contains("+") { // animation1 + animation2 + ...
string = string.replacingOccurrences(of: "+", with: ",")
string = "compound("+string+", \(AnimationType.Run.parallel.rawValue))"
}
return string
}
var animationType: AnimationType? {
let type = self.replacingOccurrences(of: "[", with: "(")
.replacingOccurrences(of: "]", with: ")")
return AnimationType(string: type)
}
}
private func retrieveRepeatCount(string: String?) -> Int {
// Default value for repeat count is `1`
guard let string = string, let repeatCount = Int(string) else {
return 1
}
return repeatCount
}
| 33.744681 | 141 | 0.632881 |
50299aba401c030e3bb3037c812aaf874d286341 | 1,931 | //
// ProfileSummary.swift
// Landmarks
//
// Created by JianjiaCoder on 2021/10/13.
//
import SwiftUI
struct ProfileSummary: View {
@EnvironmentObject var modelData: ModelData
var profile: Profile
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 10) {
Text(profile.username)
.bold()
.font(.title)
Text("Notifications: \(profile.prefersNotifications ? "On": "Off" )")
Text("Seasonal Photos: \(profile.seasonalPhoto.rawValue)")
Text("Goal Date: ") + Text(profile.goalDate, style: .date)
Divider()
VStack(alignment: .leading) {
Text("Completed Badges")
.font(.headline)
ScrollView(.horizontal) {
HStack {
HikeBadge(name: "First Hike")
HikeBadge(name: "Earth Day")
.hueRotation(Angle(degrees: 90))
HikeBadge(name: "Tenth Hike")
.grayscale(0.5)
.hueRotation(Angle(degrees: 45))
}
.padding(.bottom)
}
}
Divider()
VStack(alignment: .leading) {
Text("Recent Hikes")
.font(.headline)
HikeView(hike: modelData.hikes[0])
}
}
}
}
}
struct ProfileSummary_Previews: PreviewProvider {
static var previews: some View {
ProfileSummary(profile: Profile.default)
.environmentObject(ModelData())
}
}
| 30.171875 | 85 | 0.420508 |
6472c2eb48c0f189775e6e628e8cd88a63f92b85 | 199 | //
// CGFloat.swift
// CommandLineKit
//
// Created by Bas van Kuijck on 07/02/2019.
//
import Foundation
extension CGFloat {
var isInteger: Bool {
return rint(self) == self
}
}
| 13.266667 | 44 | 0.61809 |
69d4f5bbeb5b9c24d3930b64e2525981367c08e5 | 2,121 | //
// AppDelegate.swift
// CustomViewAlertControllerSample
//
// Created by Kai Hornung on 31.12.16.
// Copyright © 2016 kh. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 48.204545 | 281 | 0.780292 |
f84ffe6eca76ad0451c96403cf0e5ca897e61dc9 | 19,177 | //
// Created by 金秋成 on 2017/8/10.
//
import UIKit
import CloudKit
open class RoyAppDelegate : NSObject, UIApplicationDelegate {
static public let sharedInstance = RoyAppDelegate()
fileprivate var moduleMap : [String : RoyModuleProtocol] = [:]
public func addModule(_ module : RoyModuleProtocol) {
self.moduleMap[module.moduleHost] = module
}
public func addModuleClass(_ moduleClass : RoyModuleProtocol.Type , host : String) {
let module = moduleClass.init(host: host)
self.moduleMap[module.moduleHost] = module
}
public func module(host : String) -> RoyModuleProtocol?{
return self.moduleMap[host]
}
func enumerateMapBool(handle:(RoyModuleProtocol)->Bool) -> Bool {
var returnValue = true
for (_,module) in moduleMap {
returnValue = returnValue && handle(module)
}
return returnValue
}
func enumerateMapVoid(handle:(RoyModuleProtocol)->Void) -> Void {
for (_,module) in moduleMap {
handle(module)
}
}
func enumerateMapViewController(handle:(RoyModuleProtocol)->UIViewController?) -> UIViewController? {
for (_,module) in moduleMap {
if let vc = handle(module){
return vc
}
}
return nil
}
public func applicationDidFinishLaunching(_ application: UIApplication){
enumerateMapVoid { (module) in
module.applicationDidFinishLaunching?(application)
}
}
public func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool{
return enumerateMapBool { (module) -> Bool in
guard let result = module.application?(application, willFinishLaunchingWithOptions: launchOptions) else{
return true
}
return result;
}
}
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool{
return enumerateMapBool { (module) -> Bool in
guard let result = module.application?(application, didFinishLaunchingWithOptions: launchOptions) else{
return true
}
return result;
}
}
public func applicationDidBecomeActive(_ application: UIApplication){
enumerateMapVoid { (module) in
module.applicationDidBecomeActive?(application)
}
}
public func applicationWillResignActive(_ application: UIApplication){
enumerateMapVoid { (module) in
module.applicationWillResignActive?(application)
}
}
// @available(iOS, introduced: 2.0, deprecated: 9.0, message: "Please use application:openURL:options:")
public func application(_ application: UIApplication, handleOpen url: URL) -> Bool{
return enumerateMapBool { (module) -> Bool in
guard let result = module.application?(application, handleOpen: url) else{
return true
}
return result;
}
}
//
// @available(iOS, introduced: 4.2, deprecated: 9.0, message: "Please use application:openURL:options:")
public func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool{
return enumerateMapBool { (module) -> Bool in
guard let result = module.application?(application, open: url, sourceApplication: sourceApplication, annotation: annotation) else{
return true
}
return result;
}
}
public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return enumerateMapBool { (module) -> Bool in
if #available(iOS 9.0, *) {
guard let result = module.application?(app, open: url, options: options) else{
return true
}
return result;
} else {
return true
}
}
}
public func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
enumerateMapVoid { (module) in
module.applicationDidReceiveMemoryWarning?(application)
}
}
public func applicationWillTerminate(_ application: UIApplication){
enumerateMapVoid { (module) in
module.applicationWillTerminate?(application)
}
}
public func applicationSignificantTimeChange(_ application: UIApplication) {
enumerateMapVoid { (module) in
module.applicationSignificantTimeChange?(application)
}
}
public func application(_ application: UIApplication, willChangeStatusBarOrientation newStatusBarOrientation: UIInterfaceOrientation, duration: TimeInterval){
enumerateMapVoid { (module) in
module.application?(application, willChangeStatusBarOrientation: newStatusBarOrientation, duration: duration)
}
}
public func application(_ application: UIApplication, didChangeStatusBarOrientation oldStatusBarOrientation: UIInterfaceOrientation){
enumerateMapVoid { (module) in
module.application?(application, didChangeStatusBarOrientation: oldStatusBarOrientation)
}
}
public func application(_ application: UIApplication, willChangeStatusBarFrame newStatusBarFrame: CGRect) {
enumerateMapVoid { (module) in
module.application?(application, willChangeStatusBarFrame: newStatusBarFrame)
}
}
public func application(_ application: UIApplication, didChangeStatusBarFrame oldStatusBarFrame: CGRect){
enumerateMapVoid { (module) in
module.application?(application, didChangeStatusBarFrame: oldStatusBarFrame)
}
}
public func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings){
enumerateMapVoid { (module) in
module.application?(application, didRegister: notificationSettings)
}
}
public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){
enumerateMapVoid { (module) in
module.application?(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}
}
public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error){
enumerateMapVoid { (module) in
module.application?(application, didFailToRegisterForRemoteNotificationsWithError: error)
}
}
// @available(iOS, introduced: 3.0, deprecated: 10.0, message: "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] for user visible notifications and -[UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] for silent remote notifications")
public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]){
enumerateMapVoid { (module) in
module.application?(application, didReceiveRemoteNotification: userInfo)
}
}
//
//
// @available(iOS, introduced: 4.0, deprecated: 10.0, message: "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]")
public func application(_ application: UIApplication, didReceive notification: UILocalNotification){
enumerateMapVoid { (module) in
module.application?(application, didReceive: notification)
}
}
// Called when your app has been activated by the user selecting an action from a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling the action.
// @available(iOS, introduced: 8.0, deprecated: 10.0, message: "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]")
public func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Swift.Void){
enumerateMapVoid { (module) in
module.application?(application, handleActionWithIdentifier: identifier, for: notification, completionHandler: completionHandler)
}
}
// @available(iOS, introduced: 9.0, deprecated: 10.0, message: "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]")
public func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], withResponseInfo responseInfo: [AnyHashable : Any], completionHandler: @escaping () -> Swift.Void){
enumerateMapVoid { (module) in
if #available(iOS 9.0, *) {
module.application?(application, handleActionWithIdentifier: identifier, forRemoteNotification: userInfo, withResponseInfo: responseInfo, completionHandler: completionHandler)
} else {
// Fallback on earlier versions
}
}
}
// Called when your app has been activated by the user selecting an action from a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling the action.
// @available(iOS, introduced: 8.0, deprecated: 10.0, message: "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]")
public func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], completionHandler: @escaping () -> Swift.Void){
enumerateMapVoid { (module) in
module.application?(application, handleActionWithIdentifier: identifier, forRemoteNotification: userInfo, completionHandler: completionHandler)
}
}
// @available(iOS, introduced: 9.0, deprecated: 10.0, message: "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]")
public func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, withResponseInfo responseInfo: [AnyHashable : Any], completionHandler: @escaping () -> Swift.Void){
enumerateMapVoid { (module) in
if #available(iOS 9.0, *) {
module.application?(application, handleActionWithIdentifier: identifier, for: notification, withResponseInfo: responseInfo, completionHandler: completionHandler)
} else {
// Fallback on earlier versions
}
}
}
/*! This delegate method offers an opportunity for applications with the "remote-notification" background mode to fetch appropriate new data in response to an incoming remote notification. You should call the fetchCompletionHandler as soon as you're finished performing that operation, so the system can accurately estimate its power and data cost.
This method will be invoked even if the application was launched or resumed because of the remote notification. The respective delegate methods will be invoked first. Note that this behavior is in contrast to application:didReceiveRemoteNotification:, which is not called in those cases, and which will not be invoked if this method is implemented. !*/
public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Swift.Void){
enumerateMapVoid { (module) in
module.application?(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler)
}
}
public func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Swift.Void){
enumerateMapVoid { (module) in
module.application?(application, performFetchWithCompletionHandler: completionHandler)
}
}
@available(iOS 9.0, *)
public func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Swift.Void){
enumerateMapVoid { (module) in
module.application?(application, performActionFor: shortcutItem, completionHandler: completionHandler)
}
}
public func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Swift.Void){
enumerateMapVoid { (module) in
module.application?(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler)
}
}
public func application(_ application: UIApplication, handleWatchKitExtensionRequest userInfo: [AnyHashable : Any]?, reply: @escaping ([AnyHashable : Any]?) -> Swift.Void){
enumerateMapVoid { (module) in
if #available(iOS 8.2, *) {
module.application?(application, handleWatchKitExtensionRequest: userInfo, reply: reply)
} else {
// Fallback on earlier versions
}
}
}
public func applicationShouldRequestHealthAuthorization(_ application: UIApplication){
enumerateMapVoid { (module) in
if #available(iOS 9.0, *) {
module.applicationShouldRequestHealthAuthorization?(application)
} else {
// Fallback on earlier versions
}
}
}
public func applicationDidEnterBackground(_ application: UIApplication){
enumerateMapVoid { (module) in
module.applicationDidEnterBackground?(application)
}
}
public func applicationWillEnterForeground(_ application: UIApplication){
enumerateMapVoid { (module) in
module.applicationWillEnterForeground?(application)
}
}
public func applicationProtectedDataWillBecomeUnavailable(_ application: UIApplication){
enumerateMapVoid { (module) in
module.applicationProtectedDataWillBecomeUnavailable?(application)
}
}
public func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication){
enumerateMapVoid { (module) in
module.applicationProtectedDataDidBecomeAvailable?(application)
}
}
public var window: UIWindow?
public func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask{
return UIInterfaceOrientationMask.portrait
}
public func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplicationExtensionPointIdentifier) -> Bool{
return enumerateMapBool(handle: { (module) -> Bool in
guard let result = module.application?(application, shouldAllowExtensionPointIdentifier: extensionPointIdentifier) else{
return true
}
return result
})
}
public func application(_ application: UIApplication, viewControllerWithRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController?{
return enumerateMapViewController(handle: { (module) -> UIViewController? in
return module.application?(application, viewControllerWithRestorationIdentifierPath: identifierComponents, coder: coder)
})
}
public func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool{
return enumerateMapBool(handle: { (module) -> Bool in
guard let result = module.application?(application, shouldSaveApplicationState: coder) else{
return true
}
return result
})
}
public func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool{
return enumerateMapBool(handle: { (module) -> Bool in
guard let result = module.application?(application, shouldRestoreApplicationState: coder) else{
return true
}
return result
})
}
public func application(_ application: UIApplication, willEncodeRestorableStateWith coder: NSCoder){
enumerateMapVoid { (module) in
module.application?(application, willEncodeRestorableStateWith: coder)
}
}
public func application(_ application: UIApplication, didDecodeRestorableStateWith coder: NSCoder){
enumerateMapVoid { (module) in
module.application?(application, didDecodeRestorableStateWith: coder)
}
}
public func application(_ application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool{
return enumerateMapBool(handle: { (module) -> Bool in
guard let result = module.application?(application, willContinueUserActivityWithType: userActivityType) else{
return true
}
return result
})
}
public func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Swift.Void) -> Bool{
return enumerateMapBool(handle: { (module) -> Bool in
guard let result = module.application?(application, continue: userActivity, restorationHandler: restorationHandler) else{
return true
}
return result
})
}
public func application(_ application: UIApplication, didFailToContinueUserActivityWithType userActivityType: String, error: Error){
enumerateMapVoid { (module) in
module.application?(application, didFailToContinueUserActivityWithType: userActivityType, error: error)
}
}
public func application(_ application: UIApplication, didUpdate userActivity: NSUserActivity){
enumerateMapVoid { (module) in
module.application?(application, didUpdate: userActivity)
}
}
@available(iOS 10.0, *)
public func application(_ application: UIApplication, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShareMetadata){
enumerateMapVoid { (module) in
module.application?(application, userDidAcceptCloudKitShareWith: cloudKitShareMetadata)
}
}
}
| 43.191441 | 435 | 0.698702 |
8fc9b31f43c7a9cca2ed935bc646ad6d1104ceb6 | 1,134 | //
// 478 Generate Random Point in a Circle.swift
// LeetCode-Solutions
//
// Created by Aleksandar Dinic on 17/03/2021.
// Copyright © 2021 Aleksandar Dinic. All rights reserved.
//
import Foundation
/// Source: https://leetcode.com/problems/generate-random-point-in-a-circle/
class Solution {
private let radius: Double
private let xCenter: Double
private let yCenter: Double
init(_ radius: Double, _ x_center: Double, _ y_center: Double) {
self.radius = radius
xCenter = x_center
yCenter = y_center
}
/// Generates random point in a circle.
///
/// - Returns: The random point in a circle.
///
/// - Complexity:
/// - time: O(1), only constant time is used.
/// - space: O(1), only constant space is used.
func randPoint() -> [Double] {
let randomR = Double.random(in: 0.0...1.0).squareRoot() * radius
let randomTheta = Double.random(in: 0.0...1.0) * 2 * Double.pi
let newX = xCenter + randomR * cos(randomTheta)
let newY = yCenter + randomR * sin(randomTheta)
return [newX, newY]
}
}
| 28.35 | 76 | 0.612875 |
72fe9205392b8497796cad6c5203463bba7ca12e | 3,733 | //
// AppDelegate.swift
// carbon-analyzer-ios
//
// Created by Paul Chaffanet on 2019-10-16.
// Copyright © 2019 Paul Chaffanet. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "carbon_analyzer_ios")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 44.975904 | 199 | 0.671042 |
9bddd85056230615c07235c558642607119e97ad | 5,730 | //
// MyButton.swift
// Animation
//
// Created by hi on 15/10/13.
// Copyright (c) 2015年 GML. All rights reserved.
//
import UIKit
enum MyButtonAnimationType {
case AnimationTypeScale
case AnimationTypeRotate
}
class MyButton: UIButton {
//---------------变量 、常量 -------------------//
// 正常颜色
private var normal_bgColor = UIColor(red: CGFloat(237 / 255.0), green: CGFloat(85 / 255.0), blue: CGFloat(101 / 255.0), alpha: 1)
// 倒计时中的颜色
var enable_bgColor = UIColor.lightGrayColor()
private var timer:NSTimer!
private var startCount = 0
private var originNum = 0
// 倒计时label
private var timeLabel = UILabel()
var animationType = MyButtonAnimationType.AnimationTypeScale
//***********方法************//
convenience init(count: Int,frame:CGRect, var color:UIColor?) {
self.init(frame:frame)
self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
self.titleLabel?.font = UIFont.systemFontOfSize(17)
// 如果设定的有color 就显示设置的color 没有显示默认颜色
if color == nil {
color = normal_bgColor
} else {
normal_bgColor = color!
}
self.backgroundColor = normal_bgColor
self.startCount = count
self.originNum = count
addLabel()
super.addTarget(self, action: "startCountDown", forControlEvents: UIControlEvents.TouchUpInside)
}
// 倒计时的label
func addLabel() {
timeLabel.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))
timeLabel.backgroundColor = UIColor.clearColor()
timeLabel.font = UIFont.systemFontOfSize(17.0)
timeLabel.textAlignment = NSTextAlignment.Center
timeLabel.text = "\(self.originNum)"
self.addSubview(timeLabel)
}
// 开启定时器
func startCountDown(){
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countDown", userInfo: nil, repeats: true)
self.backgroundColor = enable_bgColor
self.enabled = false
switch self.animationType {
case .AnimationTypeScale :
self.scaleAnimation()
case .AnimationTypeRotate :
self.rorateAnimation()
}
}
// 开始倒计时
func countDown() {
self.startCount--
timeLabel.text = "\(self.startCount)"
// 倒计时完成后停止定时器,移除动画
if self.startCount < 0 {
if self.timer == nil {
return
}
timeLabel.layer.removeAllAnimations()
timeLabel.text = "\(self.originNum)"
self.timer.invalidate()
self.timer = nil
self.enabled = true
self.startCount = self.originNum
self.backgroundColor = normal_bgColor
println(self.startCount)
}
}
// 放大动画
func scaleAnimation() {
let duration: CFTimeInterval = 1
let beginTime = CACurrentMediaTime()
// scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0,0.5,1.0]
scaleAnimation.values = [1,1.5,2]
scaleAnimation.duration = duration
// opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0,0.5,1]
opacityAnimation.values = [1,0.5,0]
opacityAnimation.duration = duration
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation,opacityAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
animation.beginTime = beginTime
timeLabel.layer.addAnimation(animation, forKey: "animation")
self.layer.addSublayer(timeLabel.layer)
}
// 旋转变小东南规划
func rorateAnimation() {
let duration:CFTimeInterval = 1
let beginTime = CACurrentMediaTime()
// rotate animation
let rotateAnimation = CABasicAnimation(keyPath: "transfrom.rotation.z")
rotateAnimation.fromValue = NSNumber(int: 0)
rotateAnimation.toValue = NSNumber(double: M_PI * 2)
rotateAnimation.duration = duration
// scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0]
scaleAnimation.values = [1,2]
scaleAnimation.duration = 0
// opacity animation
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.keyTimes = [0,0.5]
opacityAnimation.values = [1,0]
opacityAnimation.duration = duration
// scale animation
let scaleAnimation2 = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation2.keyTimes = [0,0.5]
scaleAnimation2.values = [2,0]
scaleAnimation2.duration = duration
let animationGroup = CAAnimationGroup()
animationGroup.animations = [rotateAnimation,scaleAnimation,opacityAnimation,scaleAnimation2]
animationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animationGroup.duration = duration
animationGroup.repeatCount = HUGE
animationGroup.removedOnCompletion = false
animationGroup.beginTime = beginTime
self.timeLabel.layer.addAnimation(animationGroup, forKey: "animation")
self.layer.addSublayer(self.timeLabel.layer)
}
}
| 34.518072 | 133 | 0.62548 |
8aab78a9171570804e83609c658b4898aa1c62c2 | 1,457 | // swift-tools-version:5.0
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "swift-nio-ssl",
products: [
.library(name: "NIOSSL", targets: ["NIOSSL"]),
.executable(name: "NIOTLSServer", targets: ["NIOTLSServer"]),
.library(name: "CNIOBoringSSL", type: .static, targets: ["CNIOBoringSSL"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-nio.git", .branch("master")),
],
targets: [
.target(name: "CNIOBoringSSL"),
.target(name: "CNIOBoringSSLShims", dependencies: ["CNIOBoringSSL"]),
.target(name: "NIOSSL",
dependencies: ["NIO", "NIOConcurrencyHelpers", "CNIOBoringSSL", "CNIOBoringSSLShims", "NIOTLS", "_NIO1APIShims"]),
.target(name: "NIOTLSServer", dependencies: ["NIO", "NIOSSL", "NIOConcurrencyHelpers"]),
.testTarget(name: "NIOSSLTests", dependencies: ["NIOTLS", "NIOSSL"]),
],
cxxLanguageStandard: .cxx11
)
| 38.342105 | 130 | 0.580645 |
7a7e1bcbc833d552f9df780673243540fd011cc1 | 3,977 | //
// GameScene.swift
// ControlSystem-ActionButton
//
// Created by Doyoung Song on 1/21/22.
//
import SpriteKit
class GameScene: SKScene {
// MARK: - Properties
private let joystickNode = JoystickNode(isOn: false)
private let jumpButtonNode = SKSpriteNode(imageNamed: "Button")
private let attackButtonNode = SKSpriteNode(imageNamed: "Button")
private let playerNode = PlayerNode(imageNamed: "Idle0")
// MARK: - Lifecycle
override func didMove(to view: SKView) {
setBasics()
addNodes()
}
override func update(_ currentTime: TimeInterval) {
playerNode.move()
}
// MARK: - Touch Events
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
if attackButtonNode.contains(location) {
playerNode.attack()
} else if jumpButtonNode.contains(location) {
playerNode.jump()
} else if location.x < 0 {
joystickNode.activate(at: location)
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
guard joystickNode.isActive else { return }
let location = touch.location(in: self)
if joystickNode.contains(location) {
let movement = joystickNode.move(location: location)
playerNode.setSpeed(x: movement.x, y: movement.y)
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard joystickNode.isActive else { return }
for touch in touches {
let location = touch.location(in: self)
if joystickNode.contains(location) {
joystickNode.deactivate()
playerNode.setSpeed(x: 0, y: 0)
}
}
}
}
// MARK: - SKPhysicsContactDelegate
extension GameScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
let nodeA = contact.bodyA.node
let nodeB = contact.bodyB.node
if let node = nodeA as? PlayerNode {
node.resetJumpCount()
}
if let node = nodeB as? PlayerNode {
node.resetJumpCount()
}
}
}
// MARK: - UI
extension GameScene {
private func setBasics() {
backgroundColor = .black
anchorPoint = CGPoint(x: 0.5, y: 0.5)
physicsWorld.contactDelegate = self
view?.isMultipleTouchEnabled = true
}
private func addNodes() {
// Background
let backgroundNode = SKSpriteNode(imageNamed: "Background")
backgroundNode.zPosition = -100
backgroundNode.size = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
addChild(backgroundNode)
let groundNode = GroundNode(imageName: "Platform", location: CGPoint(x: -500, y: -80), quantity: 8)
groundNode.zPosition = -1
addChild(groundNode)
let obstacleNode = GroundNode(imageName: "Platform", location: CGPoint(x: 0, y: 100), quantity: 1)
groundNode.zPosition = -1
addChild(obstacleNode)
// Buttons
addChild(joystickNode)
attackButtonNode.position = CGPoint(x: frame.width / 2 - 80, y: -80)
attackButtonNode.alpha = 0.4
attackButtonNode.xScale = 0.7
attackButtonNode.yScale = 0.7
addChild(attackButtonNode)
jumpButtonNode.position = CGPoint(x: frame.width / 2 - 200, y: -100)
jumpButtonNode.alpha = 0.4
jumpButtonNode.xScale = 0.7
jumpButtonNode.yScale = 0.7
addChild(jumpButtonNode)
// Player
playerNode.position = CGPoint(x: 0, y: 0)
playerNode.name = "player"
playerNode.setMaxJumpCount(2)
addChild(playerNode)
}
}
| 32.072581 | 108 | 0.598944 |
01496118dbf61157dd6acc1e39e1c31c594783f6 | 3,858 | //
// AppsSearchCell.swift
// AppStoreJsonApi
//
// Created by 建達 陳 on 2019/7/2.
// Copyright © 2019 RokurouC. All rights reserved.
//
import UIKit
class AppsSearchCell: UICollectionViewCell {
var appResult: Result! {
didSet {
nameLabel.text = appResult.trackName
catLabel.text = appResult.primaryGenreName
ratingLabel.text = "Ratiing: \(appResult.averageUserRating ?? 0)"
if let url = URL(string: appResult.artworkUrl100) {
iconImgView.sd_setImage(with: url)
}
if let url = URL(string: appResult.screenshotUrls[0]) {
screenShot1ImageView.sd_setImage(with: url)
}
if appResult.screenshotUrls.count > 1 {
if let url = URL(string: appResult.screenshotUrls[1]) {
screenShot2ImageView.sd_setImage(with: url)
}
}
if appResult.screenshotUrls.count > 2 {
if let url = URL(string: appResult.screenshotUrls[2]) {
screenShot3ImageView.sd_setImage(with: url)
}
}
}
}
let iconImgView: UIImageView = {
let img = UIImageView()
img.translatesAutoresizingMaskIntoConstraints = false
img.widthAnchor.constraint(equalToConstant: 64).isActive = true
img.heightAnchor.constraint(equalToConstant: 64).isActive = true
img.layer.cornerRadius = 12
img.clipsToBounds = true
return img
}()
let nameLabel: UILabel = {
let label = UILabel()
label.text = "APP NAMe"
return label
}()
let catLabel: UILabel = {
let label = UILabel()
label.text = "Photos & Video"
return label
}()
let ratingLabel: UILabel = {
let label = UILabel()
label.text = "97.5M"
return label
}()
let getBtn: UIButton = {
let btn = UIButton()
btn.setTitle("GET", for: .normal)
btn.setTitleColor(.blue, for: .normal)
btn.titleLabel?.font = .boldSystemFont(ofSize: 14)
btn.backgroundColor = UIColor(white: 0.95, alpha: 1)
btn.widthAnchor.constraint(equalToConstant: 80).isActive = true
btn.heightAnchor.constraint(equalToConstant: 32).isActive = true
btn.layer.cornerRadius = 16
return btn
}()
lazy var screenShot1ImageView: UIImageView = self.createImageView()
lazy var screenShot2ImageView: UIImageView = self.createImageView()
lazy var screenShot3ImageView: UIImageView = self.createImageView()
func createImageView() -> UIImageView{
let imageView = UIImageView()
imageView.layer.cornerRadius = 8
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
return imageView
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
let screenShotStackView = UIStackView(arrangedSubviews: [screenShot1ImageView, screenShot2ImageView, screenShot3ImageView])
screenShotStackView.spacing = 12
screenShotStackView.distribution = .fillEqually
let topInostackView = UIStackView(arrangedSubviews: [iconImgView, VerticalStackView(arrangedSubViews: [nameLabel, catLabel, ratingLabel]), getBtn])
topInostackView.spacing = 12
topInostackView.alignment = .center
let overallStackView = VerticalStackView(arrangedSubViews: [topInostackView, screenShotStackView], spacing: 16)
addSubview(overallStackView)
overallStackView.fillSuperview(padding: .init(top: 16, left: 16, bottom: 16, right: 16))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(code:) has not been implemented.")
}
}
| 35.072727 | 155 | 0.621306 |
4aaeb7555be155eaa7792ff624e4c900859005a6 | 2,099 | //
// SettingsViewController.swift
// RandomEats
//
// Created by Maliha Fairooz on 4/25/16.
// Copyright © 2016 RandomEats. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var Single: UIButton!
@IBOutlet weak var double: UIButton!
@IBOutlet weak var Ballin: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
/*Business.searchWithTerm("Restaurant", latitude: 37.721839, longitude: -122.476927, sort: .Distance, categories: [], deals: false, offset: nil, limit: 20, completion: { (businesses: [Business]!, error: NSError!) -> Void in
self.businesses = businesses
//self.filteredBusinesses = self.businesses
self.tableView.reloadData()
})
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
filteredData = searchText.isEmpty ? data : data.filter({(dataString: String) -> Bool in
return dataString.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil
})
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
filteredData = data
} else {
filteredData = data.filter({(dataItem: String) -> Bool in
if dataItem.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil {
return true
} else {
return false
}
})
}
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 26.910256 | 227 | 0.611243 |
e50e1d33c54a4da9d8b77c41f4ac4c73598a5439 | 2,264 | // Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
/// An attributed or unattributed string.
public enum Text {
case unattributed(String)
case attributed(NSAttributedString)
/// Calculate the text size within `maxSize` by given `UIFont`
func textSize(within maxSize: CGSize,
font: UIFont) -> CGSize {
let options: NSStringDrawingOptions = [
.usesLineFragmentOrigin
]
let size: CGSize
switch self {
case .attributed(let attributedText):
if attributedText.length == 0 {
return .zero
}
// UILabel/UITextView uses a default font if one is not specified in the attributed string.
// boundingRect(with:options:attributes:) does not appear to have the same logic,
// so we need to ensure that our attributed string has a default font.
// We do this by creating a new attributed string with the default font and then
// applying all of the attributes from the provided attributed string.
let fontAppliedAttributeString = attributedText.with(font: font)
size = fontAppliedAttributeString.boundingRect(with: maxSize, options: options, context: nil).size
case .unattributed(let text):
if text.isEmpty {
return .zero
}
size = text.boundingRect(with: maxSize, options: options, attributes: [NSAttributedString.Key.font: font], context: nil).size
}
// boundingRect(with:options:attributes:) returns size to a precision of hundredths of a point,
// but UILabel only returns sizes with a point precision of 1/screenDensity.
return CGSize(width: size.width.roundedUpToFractionalPoint, height: size.height.roundedUpToFractionalPoint)
}
}
| 46.204082 | 137 | 0.673145 |
89ef5e7aa7b8cf60a22f4f6914b098fa619c0495 | 792 | import XCTest
@testable import StructuredDataGraphExtensions
import JSON
class StructuredDataWrapperTest: XCTestCase {
enum Greeting : String, StructuredDataEnum {
case prefunctory
case warm
case enthusiastic
}
static var allTests : [(String, (StructuredDataWrapperTest) -> () throws -> Void)] {
return [
("testDefaultGet", testDefaultGet),
]
}
func testDefaultGet() throws {
let sd = JSON(["greeting": "warm"])
var greeting : Greeting?
try greeting = sd.get("greeting", default: .prefunctory)
XCTAssertEqual(greeting, .warm)
try greeting = sd.get("nope", default: .prefunctory)
XCTAssertEqual(greeting, .prefunctory) // Default
}
}
| 25.548387 | 88 | 0.608586 |
62df1d85341021bf391bc295362606daddfac79a | 2,411 | //
// ViewController.swift
// PowerScoutDebugging
//
// Created by Srinivas Dhanwada on 2/13/18.
// Copyright © 2018 FRC Team 525. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var matchStore:MatchStore!
var serviceStore:ServiceStore!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let delegate = UIApplication.shared.delegate as? AppDelegate {
matchStore = delegate.matchStore
serviceStore = delegate.serviceStore
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func unwindToMatchView(_ sender:UIStoryboardSegue) {
AppUtility.revertOrientation()
}
@IBAction func unwindToCompletedMatchView(_ sender:UIStoryboardSegue) {
AppUtility.revertOrientation()
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let id = segue.identifier {
if id.elementsEqual("SegueToDataEntry") {
self.matchStore.createMatch(PowerMatch.self, onComplete:nil)
if let nc = segue.destination as? UINavigationController,
let vc = nc.topViewController as? DataEntryViewController {
vc.matchStore = matchStore
}
} else if id.elementsEqual("SegueToDebugTransfer") {
if let vc = segue.destination as? DebugDataTransferViewController {
vc.matchStore = matchStore
vc.serviceStore = serviceStore
serviceStore.resetStateMachine()
serviceStore.delegate = vc
vc.transferMode = .doNothing
}
} else if id.elementsEqual("SegueToTransfer") {
if let vc = segue.destination as? DataTransferViewController {
vc.matchStore = matchStore
vc.serviceStore = serviceStore
serviceStore.resetStateMachine()
serviceStore.delegate = vc
vc.transferMode = .doNothing
}
}
}
}
}
| 33.027397 | 83 | 0.582746 |
f7279c66f80b015c3aa61d686f4ec773513729e4 | 1,228 | //
// FullGifUITests.swift
// FullGifUITests
//
// Created by on 3/7/16.
// Copyright © 2016 Tuan_Quang. All rights reserved.
//
import XCTest
class FullGifUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 33.189189 | 182 | 0.659609 |
7655f50c8bfacd4f38527b7bc9428d75adc26706 | 503 | //
// Constants.swift
// GoGoTram
//
// Created by Daniel Sykes-Turner on 8/9/19.
// Copyright © 2019 Daniel Sykes-Turner. All rights reserved.
//
import UIKit
struct pc {
static let none: UInt32 = 0x1 << 0
static let tram: UInt32 = 0x1 << 1
static let signalFault: UInt32 = 0x1 << 2
static let passengers: UInt32 = 0x1 << 3
}
struct layers {
static let background:CGFloat = 0
static let actor:CGFloat = 1
static let fire:CGFloat = 2
static let text:CGFloat = 3
}
| 20.958333 | 62 | 0.652087 |
238b59549d9043c589b9cca85e7e00af86e320b0 | 930 | //
// RssItemViewController.swift
// AppleRssViewer
//
// Created by Ivan Yurchenko on 5/9/17.
// Copyright © 2017 Ivan Yurchenko. All rights reserved.
//
import UIKit
class RssItemViewController: UIViewController, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var textLabel: UILabel!
// The item that will be passed by RssTableViewController to show its details
var item: RssItem?
// MARK: Initializer
override func viewDidLoad() {
super.viewDidLoad()
// Show details of the retrieved item
if let item = item {
titleLabel.text = item.title
photoImageView.image = item.image
textLabel.text = item.text
dateLabel.text = item.date
}
}
}
| 26.571429 | 81 | 0.653763 |
91aecf14f0ff4fadcad2918b738183c0971bc180 | 1,202 | //
// Cardify.swift
// Memorize
//
// Created by Andrea Stevanato on 08/06/2020.
// Copyright © 2020 Andrea Stevanato. All rights reserved.
//
import SwiftUI
struct Cardify: AnimatableModifier {
var rotation: Double
init(isFaceUp: Bool) {
rotation = isFaceUp ? 0 : 180
}
var isFaceUp: Bool {
rotation < 90
}
var animatableData: Double {
get { return rotation }
set { rotation = newValue }
}
func body(content: Content) -> some View {
ZStack {
Group {
RoundedRectangle(cornerRadius: cornerRadius).fill(Color.white)
RoundedRectangle(cornerRadius: cornerRadius).stroke(lineWidth: edgeLineWidth)
content
}.opacity(isFaceUp ? 1 : 0)
RoundedRectangle(cornerRadius: cornerRadius)
.fill()
.opacity(isFaceUp ? 0 : 1)
}
.rotation3DEffect(Angle.degrees(rotation), axis: (0,1,0))
}
private let cornerRadius: CGFloat = 10
private let edgeLineWidth: CGFloat = 3
}
extension View {
func cardify(isFaceUp: Bool) -> some View {
self.modifier(Cardify(isFaceUp: isFaceUp))
}
}
| 24.04 | 93 | 0.592346 |
e4ce0651c43f567f062161058f23e8600b8bd9cb | 5,642 | // URLExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(Foundation)
import Foundation
#if canImport(UIKit) && canImport(AVFoundation)
import AVFoundation
import UIKit
#endif
// MARK: - Properties
public extension URL {
/// SwifterSwift: Dictionary of the URL's query parameters
var queryParameters: [String: String]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false),
let queryItems = components.queryItems else { return nil }
var items: [String: String] = [:]
for queryItem in queryItems {
items[queryItem.name] = queryItem.value
}
return items
}
}
// MARK: - Initializers
public extension URL {
/// SwifterSwift: Initializes an `URL` object with a base URL and a relative string. If `string` was malformed, returns `nil`.
/// - Parameters:
/// - string: The URL string with which to initialize the `URL` object. Must conform to RFC 2396. `string` is interpreted relative to `url`.
/// - url: The base URL for the `URL` object.
init?(string: String?, relativeTo url: URL? = nil) {
guard let string = string else { return nil }
self.init(string: string, relativeTo: url)
}
}
// MARK: - Methods
public extension URL {
/// SwifterSwift: URL with appending query parameters.
///
/// let url = URL(string: "https://google.com")!
/// let param = ["q": "Swifter Swift"]
/// url.appendingQueryParameters(params) -> "https://google.com?q=Swifter%20Swift"
///
/// - Parameter parameters: parameters dictionary.
/// - Returns: URL with appending given query parameters.
func appendingQueryParameters(_ parameters: [String: String]) -> URL {
var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)!
urlComponents.queryItems = (urlComponents.queryItems ?? []) + parameters
.map { URLQueryItem(name: $0, value: $1) }
return urlComponents.url!
}
/// SwifterSwift: Append query parameters to URL.
///
/// var url = URL(string: "https://google.com")!
/// let param = ["q": "Swifter Swift"]
/// url.appendQueryParameters(params)
/// print(url) // prints "https://google.com?q=Swifter%20Swift"
///
/// - Parameter parameters: parameters dictionary.
mutating func appendQueryParameters(_ parameters: [String: String]) {
self = appendingQueryParameters(parameters)
}
/// SwifterSwift: Get value of a query key.
///
/// var url = URL(string: "https://google.com?code=12345")!
/// queryValue(for: "code") -> "12345"
///
/// - Parameter key: The key of a query value.
func queryValue(for key: String) -> String? {
return URLComponents(string: absoluteString)?
.queryItems?
.first(where: { $0.name == key })?
.value
}
/// SwifterSwift: Returns a new URL by removing all the path components.
///
/// let url = URL(string: "https://domain.com/path/other")!
/// print(url.deletingAllPathComponents()) // prints "https://domain.com/"
///
/// - Returns: URL with all path components removed.
func deletingAllPathComponents() -> URL {
var url: URL = self
for _ in 0..<pathComponents.count - 1 {
url.deleteLastPathComponent()
}
return url
}
/// SwifterSwift: Remove all the path components from the URL.
///
/// var url = URL(string: "https://domain.com/path/other")!
/// url.deleteAllPathComponents()
/// print(url) // prints "https://domain.com/"
mutating func deleteAllPathComponents() {
for _ in 0..<pathComponents.count - 1 {
deleteLastPathComponent()
}
}
/// SwifterSwift: Generates new URL that does not have scheme.
///
/// let url = URL(string: "https://domain.com")!
/// print(url.droppedScheme()) // prints "domain.com"
func droppedScheme() -> URL? {
if let scheme = scheme {
let droppedScheme = String(absoluteString.dropFirst(scheme.count + 3))
return URL(string: droppedScheme)
}
guard host != nil else { return self }
let droppedScheme = String(absoluteString.dropFirst(2))
return URL(string: droppedScheme)
}
}
// MARK: - Methods
public extension URL {
#if os(iOS) || os(tvOS)
/// SwifterSwift: Generate a thumbnail image from given url. Returns nil if no thumbnail could be created. This function may take some time to complete. It's recommended to dispatch the call if the thumbnail is not generated from a local resource.
///
/// var url = URL(string: "https://video.golem.de/files/1/1/20637/wrkw0718-sd.mp4")!
/// var thumbnail = url.thumbnail()
/// thumbnail = url.thumbnail(fromTime: 5)
///
/// DisptachQueue.main.async {
/// someImageView.image = url.thumbnail()
/// }
///
/// - Parameter time: Seconds into the video where the image should be generated.
/// - Returns: The UIImage result of the AVAssetImageGenerator
func thumbnail(fromTime time: Float64 = 0) -> UIImage? {
let imageGenerator = AVAssetImageGenerator(asset: AVAsset(url: self))
let time = CMTimeMakeWithSeconds(time, preferredTimescale: 1)
var actualTime = CMTimeMake(value: 0, timescale: 0)
guard let cgImage = try? imageGenerator.copyCGImage(at: time, actualTime: &actualTime) else {
return nil
}
return UIImage(cgImage: cgImage)
}
#endif
}
#endif
| 35.936306 | 251 | 0.621588 |
eb1cb415faae59e15b51934f7732d5a9978d1111 | 1,967 | import UIKit
import MetalKit
class ViewController: UIViewController, MTKViewDelegate {
var mtkView: MTKView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let appDelegate = UIApplication.shared.delegate as? AppDelegate
if appDelegate != nil {
mtkView = MTKView()
mtkView.delegate = self
mtkView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(mtkView)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[mtkView]|", options: [], metrics: nil, views: ["mtkView" : mtkView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[mtkView]|", options: [], metrics: nil, views: ["mtkView" : mtkView]))
let device = MTLCreateSystemDefaultDevice()!
mtkView.device = device
mtkView.colorPixelFormat = .bgra8Unorm_srgb
mtkView.depthStencilPixelFormat = .depth32Float
let width = 600
let height = 400
appDelegate!._bridge!.init(mtkView, width:Int32(width), height:Int32(height))
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let appDelegate = UIApplication.shared.delegate as? AppDelegate
if mtkView == nil {
return
}
if appDelegate != nil {
appDelegate!._bridge!.resize(Int32(600), height: Int32(400))
}
}
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
// no resize here. keep the 600x400 size for validation tests.
}
func draw(in view: MTKView) {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
if appDelegate != nil {
appDelegate!._bridge!.render()
}
}
}
| 33.338983 | 155 | 0.619217 |
e02330cb5132dd68e34ee3e0766b651dd640c3cc | 9,751 | //
// RDFParser.swift
// Kineo
//
// Created by Gregory Todd Williams on 1/21/17.
// Copyright © 2017 Gregory Todd Williams. All rights reserved.
//
import serd
import Foundation
import SPARQLSyntax
#if canImport(FoundationXML)
import FoundationXML
#endif
public class RDFParserCombined : RDFPushParser {
public var mediaTypes: Set<String> = [
]
public enum RDFParserError : Error {
case parseError(String)
case unsupportedSyntax(String)
case internalError(String)
}
public enum RDFSyntax {
case nquads
case ntriples
case turtle
case rdfxml
var serdSyntax : SerdSyntax? {
switch self {
case .nquads:
return SERD_NQUADS
case .ntriples:
return SERD_NTRIPLES
case .turtle:
return SERD_TURTLE
default:
return nil
}
}
}
public static func guessSyntax(filename: String) -> RDFSyntax {
if filename.hasSuffix("ttl") {
return .turtle
} else if filename.hasSuffix("nq") {
return .nquads
} else if filename.hasSuffix("nt") {
return .ntriples
} else if filename.hasSuffix("rdf") {
return .rdfxml
} else {
return .turtle
}
}
public static func guessSyntax(mediaType: String) -> RDFSyntax {
if mediaType.hasPrefix("text/turtle") {
return .turtle
} else if mediaType.hasPrefix("text/plain") {
return .turtle
} else if mediaType.hasPrefix("application/rdf+xml") {
return .rdfxml
} else if mediaType.hasPrefix("application/xml") {
return .rdfxml
} else if mediaType.hasSuffix("application/n-triples") {
return .ntriples
} else if mediaType.hasSuffix("application/n-quads") {
return .nquads
} else {
return .turtle
}
}
var defaultBase: String
var produceUniqueBlankIdentifiers: Bool
required public init() {
self.defaultBase = "http://base.example.org/"
self.produceUniqueBlankIdentifiers = true
}
public init(base defaultBase: String = "http://base.example.org/", produceUniqueBlankIdentifiers: Bool = true) {
self.defaultBase = defaultBase
self.produceUniqueBlankIdentifiers = produceUniqueBlankIdentifiers
}
@discardableResult
public func parse(string: String, mediaType type: String, base: String? = nil, handleTriple: @escaping TripleHandler) throws -> Int {
let inputSyntax = RDFParserCombined.guessSyntax(mediaType: type)
guard inputSyntax != .nquads else {
throw RDFParserError.unsupportedSyntax("Cannot parse N-Quads data with a triple-based parsing API")
}
return try parse(string: string, syntax: inputSyntax, base: base, handleTriple: handleTriple)
}
@discardableResult
public func parse(string: String, mediaType type: String, defaultGraph: Term, base: String? = nil, handleQuad: @escaping QuadHandler) throws -> Int {
let inputSyntax = RDFParserCombined.guessSyntax(mediaType: type)
if case .nquads = inputSyntax {
return try parse(string: string, syntax: inputSyntax, defaultGraph: defaultGraph, base: base, handleQuad: handleQuad)
} else {
return try parse(string: string, syntax: inputSyntax, base: base) { (s, p, o) in
handleQuad(s, p, o, defaultGraph)
}
}
}
@discardableResult
public func parse<L: LineReadable>(data: L, mediaType type: String, defaultGraph: Term, base: String? = nil, handleQuad: @escaping QuadHandler) throws -> Int {
let inputSyntax = RDFParserCombined.guessSyntax(mediaType: type)
let string = try data.lines().joined(separator: "\n")
if case .nquads = inputSyntax {
return try parse(string: string, syntax: inputSyntax, defaultGraph: defaultGraph, base: base, handleQuad: handleQuad)
} else {
return try parse(string: string, syntax: inputSyntax, base: base) { (s, p, o) in
handleQuad(s, p, o, defaultGraph)
}
}
}
@discardableResult
public func parse(string: String, syntax inputSyntax: RDFSyntax, defaultGraph: Term, base: String? = nil, handleQuad: @escaping QuadHandler) throws -> Int {
let base = base ?? defaultBase
switch inputSyntax {
case .nquads:
let p = NQuadsParser(reader: string, defaultGraph: defaultGraph)
var count = 0
for q in p {
count += 1
handleQuad(q.subject, q.predicate, q.object, q.graph)
}
return count
case .ntriples, .turtle:
let p = SerdParser(syntax: inputSyntax, base: base, produceUniqueBlankIdentifiers: produceUniqueBlankIdentifiers)
return try p.serd_parse(string: string) { (s,p,o) in
handleQuad(s,p,o,defaultGraph)
}
default:
let p = RDFXMLParser()
var count = 0
try p.parse(string: string) { (s,p,o) in
count += 1
handleQuad(s,p,o,defaultGraph)
}
return count
}
}
@discardableResult
public func parse(string: String, syntax inputSyntax: RDFSyntax, base: String? = nil, handleTriple: @escaping TripleHandler) throws -> Int {
let base = base ?? defaultBase
switch inputSyntax {
case .ntriples, .turtle:
let p = SerdParser(syntax: inputSyntax, base: base, produceUniqueBlankIdentifiers: produceUniqueBlankIdentifiers)
return try p.serd_parse(string: string, handleTriple: handleTriple)
default:
let p = RDFXMLParser()
try p.parse(string: string, tripleHandler: handleTriple)
return 0
}
}
@discardableResult
public func parse(file filename: String, base: String? = nil, handleTriple: @escaping TripleHandler) throws -> Int {
let inputSyntax = RDFParserCombined.guessSyntax(filename: filename)
return try parse(file: filename, syntax: inputSyntax, base: base, handleTriple: handleTriple)
}
@discardableResult
public func parse(file filename: String, defaultGraph: Term, base: String? = nil, handleQuad: @escaping QuadHandler) throws -> Int {
let inputSyntax = RDFParserCombined.guessSyntax(filename: filename)
return try parse(file: filename, syntax: inputSyntax, defaultGraph: defaultGraph, base: base, handleQuad: handleQuad)
}
@discardableResult
public func parseFile(_ filename: String, mediaType type: String, base: String? = nil, handleTriple: @escaping TripleHandler) throws -> Int {
let inputSyntax = RDFParserCombined.guessSyntax(mediaType: type)
return try parse(file: filename, syntax: inputSyntax, base: base, handleTriple: handleTriple)
}
@discardableResult
public func parseFile(_ filename: String, mediaType type: String, defaultGraph: Term, base: String?, handleQuad: @escaping QuadHandler) throws -> Int {
let inputSyntax = RDFParserCombined.guessSyntax(mediaType: type)
return try parse(file: filename, syntax: inputSyntax, defaultGraph: defaultGraph, base: base, handleQuad: handleQuad)
}
@discardableResult
public func parse(file filename: String, syntax inputSyntax: RDFSyntax, base: String? = nil, handleTriple: @escaping TripleHandler) throws -> Int {
let base = base ?? defaultBase
switch inputSyntax {
case .ntriples, .turtle:
let p = SerdParser(syntax: inputSyntax, base: base, produceUniqueBlankIdentifiers: produceUniqueBlankIdentifiers)
return try p.serd_parse(file: filename, base: base, handleTriple: handleTriple)
default:
let fileURI = URL(fileURLWithPath: filename)
let p = RDFXMLParser(base: fileURI.absoluteString)
let data = try Data(contentsOf: fileURI)
try p.parse(data: data, tripleHandler: handleTriple)
return 0
}
}
@discardableResult
public func parse(file filename: String, syntax inputSyntax: RDFSyntax, defaultGraph: Term, base: String? = nil, handleQuad: @escaping QuadHandler) throws -> Int {
let base = base ?? defaultBase
switch inputSyntax {
case .nquads:
let reader = FileReader(filename: filename)
let p = NQuadsParser(reader: reader, defaultGraph: defaultGraph)
var count = 0
for q in p {
count += 1
handleQuad(q.subject, q.predicate, q.object, q.graph)
}
return count
case .ntriples, .turtle:
let p = SerdParser(syntax: inputSyntax, base: base, produceUniqueBlankIdentifiers: produceUniqueBlankIdentifiers)
var count = 0
_ = try p.serd_parse(file: filename, defaultGraph: defaultGraph, base: base) { (s,p,o,g) in
let graph = (g == sentinel_graph) ? defaultGraph : g
handleQuad(s,p,o,graph)
count += 1
}
return count
default:
let fileURI = URL(fileURLWithPath: filename)
let p = RDFXMLParser(base: fileURI.absoluteString)
let data = try Data(contentsOf: fileURI)
var count = 0
try p.parse(data: data) { (s,p,o) in
handleQuad(s,p,o,defaultGraph)
count += 1
}
return count
}
}
}
| 39.638211 | 167 | 0.614706 |
ddd20a239adf16e40af646cc9d16ee435c8869f1 | 90 | //
// Test.swift
// Test
//
// Created by Yana Honchar on 11/9/20.
//
class Test {
}
| 8.181818 | 39 | 0.544444 |
ab328cd0d8f42e4949add007a29ff47cbef8365e | 1,131 | //
// MmappedFile.swift
//
//
// Created by Sera Brocious on 12/14/20.
//
import Foundation
import LibSpan
public enum FileError: Error {
case FileNotFound
case StatFailed
case MmapFailed
case Unknown
}
public class MmappedFile {
let fd: Int32
let addr: UnsafeMutableRawPointer
let memSize: Int
public let data: Span<UInt8>
public let size: Int
public init(_ filename: String) throws {
fd = open(filename, O_RDONLY)
if fd < 0 { throw FileError.FileNotFound }
var statBuf = stat()
if fstat(fd, &statBuf) < 0 { throw FileError.StatFailed }
size = Int(statBuf.st_size)
memSize = size & 0x3FFF != 0
? (size & ~0x3FFF) + 0x4000
: size
guard let addr = mmap(nil, size, PROT_READ, MAP_SHARED, fd, 0) else {
close(fd)
throw FileError.MmapFailed
}
self.addr = addr
data = Span<UInt8>.from(pointer: addr.bindMemory(to: UInt8.self, capacity: size), length: size)
}
deinit {
munmap(addr, memSize)
close(fd)
}
}
| 22.62 | 103 | 0.580902 |
336c86e5bf80a17141b847cc74482aec571293cc | 3,105 | //
// DraftMessageManager.swift
// Rocket.Chat
//
// Created by Filipe Alvarenga on 06/11/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
struct DraftMessageManager {
static let userDefaults = UserDefaults.standard
/**
This property gets the selected server's URL for us to use it as a identification
to store and retrieve its subscriptions's draft messages.
*/
static var selectedServerKey: String {
let selectedIndex = DatabaseManager.selectedIndex
guard
let servers = DatabaseManager.servers,
servers.count > selectedIndex
else {
return ""
}
return servers[selectedIndex][ServerPersistKeys.serverURL] ?? ""
}
/**
This method takes a subscription id and returns a more meaningful key
than the id only for us to persist.
- parameter identifier: The subscription id to update or retrieve a draft message.
*/
static internal func draftMessageKey(for identifier: String) -> String {
return String(format: "\(identifier)-cacheddraftmessage")
}
/**
This method clears all the cached draft messages for the selected server if any.
*/
static func clearServerDraftMessages() {
guard !selectedServerKey.isEmpty else { return }
userDefaults.set(nil, forKey: selectedServerKey)
}
/**
This method takes a draft message and a subscription so it can update
the subscription current draft message then when the user come back to
this subscription in the app the draft message will be available for him.
- parameter draftMessage: The new draft message to update.
- parameter subscription: The subscription that is related to the draftMessage.
*/
static func update(draftMessage: String, for subscription: Subscription) {
guard !selectedServerKey.isEmpty else { return }
let subscriptionKey = draftMessageKey(for: subscription.rid)
if var currentServerDraftMessages = userDefaults.dictionary(forKey: selectedServerKey) {
currentServerDraftMessages[subscriptionKey] = draftMessage
userDefaults.set(currentServerDraftMessages, forKey: selectedServerKey)
} else {
userDefaults.set([subscriptionKey: draftMessage], forKey: selectedServerKey)
}
}
/**
This method takes a subscription and returns the current cached draft message
that is related to it, if any.
- parameter subscription: The subscription we that we need to retrieve a draft message.
*/
static func draftMessage(for subscription: Subscription) -> String {
guard !selectedServerKey.isEmpty else { return "" }
let subscriptionKey = draftMessageKey(for: subscription.rid)
if let serverDraftMessages = userDefaults.dictionary(forKey: selectedServerKey),
let draftMessage = serverDraftMessages[subscriptionKey] as? String {
return draftMessage
}
return ""
}
}
| 34.88764 | 96 | 0.674396 |
1455f0a65c4c0ca45e3e5399701f1271511bceed | 1,198 | import Foundation
protocol IChartView: class {
func showSpinner()
func hideSpinner()
func setChartType(tag: Int)
func setChartTypeEnabled(tag: Int)
func show(viewItem: ChartViewItem)
func showSelectedPoint(chartType: ChartType, timestamp: TimeInterval, value: CurrencyValue)
func showError()
func reloadAllModels()
func addTypeButtons(types: [ChartType])
}
protocol IChartViewDelegate {
var coin: Coin { get }
func viewDidLoad()
func onSelect(type: ChartType)
func chartTouchSelect(point: ChartPoint)
}
protocol IChartInteractor {
var defaultChartType: ChartType { get set }
func subscribeToChartStats()
func subscribeToLatestRate(coinCode: CoinCode, currencyCode: String)
func syncStats(coinCode: CoinCode, currencyCode: String)
}
protocol IChartInteractorDelegate: class {
func didReceive(chartData: ChartData)
func didReceive(rate: Rate)
func onError()
}
protocol IChartRateConverter {
func convert(chartRateData: ChartRateData) -> [ChartPoint]
}
protocol IChartRateFactory {
func chartViewItem(type: ChartType, chartData: ChartData, rate: Rate?, currency: Currency) throws -> ChartViewItem
}
| 23.96 | 118 | 0.740401 |
18bf408817948a4741b3b371a5c90b193f9cfdda | 5,711 | //
// GridViewParticleView.swift
// PulsewafeTest
//
// Created by Andreas Neusüß on 19.08.16.
// Copyright © 2016 Anerma. All rights reserved.
//
import UIKit
class GridViewParticleView: UIView {
init () {
super.init(frame: .zero)
backgroundColor = UIColor.black.withAlphaComponent(0.0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let color = UIColor.black.withAlphaComponent(0.5)
color.setStroke()
let gap : CGFloat = 0.0
let lineWidth : CGFloat = 1.0
let topCenter = CGPoint(x: bounds.midX, y: bounds.origin.y + gap)
let rightCenter = CGPoint(x: bounds.width - gap, y: bounds.midY)
let bottomCenter = CGPoint(x: bounds.midX, y: bounds.height - gap)
let leftCenter = CGPoint(x: bounds.origin.x + gap, y: bounds.midY)
let topThirdLeft = CGPoint(x: bounds.width * 0.2, y: bounds.origin.y + gap)
let bottomThirdLeft = CGPoint(x: topThirdLeft.x, y: bounds.height - gap)
let topThirdRight = CGPoint(x: bounds.width - topThirdLeft.x, y: bounds.origin.y + gap)
let bottomThirdRight = CGPoint(x: topThirdRight.x, y: bounds.height - gap)
// let center = convert(self.center, to: self)
let center = CGPoint(x: bounds.midX, y: bounds.midY)
// let context = UIGraphicsGetCurrentContext()
// let rect = CGRect(x: bounds.origin.x + lineWidth, y: bounds.origin.y + lineWidth, width: bounds.width - (2 * lineWidth), height: bounds.height - (2 * lineWidth))
let rotatedRectPath = UIBezierPath()
rotatedRectPath.move(to: topCenter)
rotatedRectPath.addLine(to: rightCenter)
rotatedRectPath.addLine(to: bottomCenter)
rotatedRectPath.addLine(to: leftCenter)
rotatedRectPath.addLine(to: topCenter)
rotatedRectPath.lineWidth = lineWidth
rotatedRectPath.stroke()
let verticalLineLeft = UIBezierPath()
verticalLineLeft.move(to: topThirdLeft)
verticalLineLeft.addLine(to: center)
verticalLineLeft.addLine(to: bottomThirdLeft)
verticalLineLeft.lineWidth = lineWidth
verticalLineLeft.stroke()
let verticalLineRight = UIBezierPath()
verticalLineRight.move(to: topThirdRight)
verticalLineRight.addLine(to: center)
verticalLineRight.addLine(to: bottomThirdRight)
verticalLineRight.lineWidth = lineWidth
verticalLineRight.stroke()
// context?.setStrokeColor(UIColor.red.cgColor)
//context?.stroke(rect)
}
static let rippleAnimationKeyTimes : [NSNumber] = [0, 0.1, 0.61, 0.7, 1]//[0, 0.61, 0.7, 0.887, 1]
func animateView(withDuration duration: TimeInterval, particleDelay: TimeInterval, particleDirection: CGPoint, onlyOnce : Bool = false) {
let timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0, 0.2, 1)
let linearFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let easeOutFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
let easeInOutTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let zeroPointValue = NSValue(cgPoint: CGPoint.zero)
var animations = [CAAnimation]()
// Transform.scale
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.values = [1, 1.05, 1, 1, 1]//[1, 1, 1.05, 1, 1] //more for more depth
scaleAnimation.keyTimes = GridViewParticleView.rippleAnimationKeyTimes
scaleAnimation.timingFunctions = [linearFunction, timingFunction, timingFunction, linearFunction]
scaleAnimation.beginTime = 0.0
scaleAnimation.duration = duration
animations.append(scaleAnimation)
// Position
let positionAnimation = CAKeyframeAnimation(keyPath: "position")
positionAnimation.duration = duration/3.0
positionAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction]
positionAnimation.keyTimes = GridViewParticleView.rippleAnimationKeyTimes
positionAnimation.values = [zeroPointValue, NSValue(cgPoint:particleDirection), zeroPointValue, zeroPointValue]
positionAnimation.isAdditive = true
animations.append(positionAnimation)
// Opacity
let opacityStart = layer.presentation()?.opacity ?? 0
let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
opacityAnimation.duration = duration
opacityAnimation.timingFunctions = [linearFunction, easeOutFunction]
opacityAnimation.keyTimes = [0.0, 0.1, 1.0]
opacityAnimation.values = [opacityStart, 1, 0.0]//[0.0, 1.0, 0.45, 0.6, 0.0, 0.0]
animations.append(opacityAnimation)
// Group
let groupAnimation = CAAnimationGroup()
groupAnimation.repeatCount = onlyOnce ? 1 : Float.infinity
groupAnimation.fillMode = kCAFillModeBoth
groupAnimation.duration = duration
groupAnimation.beginTime = CACurrentMediaTime() + particleDelay
groupAnimation.isRemovedOnCompletion = false
groupAnimation.animations = animations
/// The offset between the AnimatedULogoView and the background Grid
// groupAnimation.timeOffset = kAnimationTimeOffset
layer.add(groupAnimation, forKey: "pulse")
}
}
| 43.59542 | 171 | 0.657153 |
e0516871d5d232ffc942abeddfe13331462657d9 | 633 | //
// Rx+Response+Tests.swift
// Example
//
// Created by Luciano Polit on 12/3/17.
// Copyright © 2017 Luciano Polit. All rights reserved.
//
import Foundation
import RxSwift
import XCTest
@testable import Leash
#if !COCOAPODS
@testable import RxLeash
#endif
// MARK: - Utils
extension ResponseTests {
func testRxObservableJustValue() {
let response = ReactiveResponse(123, nil)
let observable = Observable.just(response)
observable.justValue()
.subscribe(onNext: { value in
XCTAssertEqual(response.value, value)
})
.dispose()
}
}
| 19.78125 | 56 | 0.635071 |
23d55a7946a5b98f6ae399764a18247d120d0c08 | 1,389 | //
// meshView.swift
// artbum
//
// Created by shreyas gupta on 16/07/20.
// Copyright © 2020 shreyas gupta. All rights reserved.
//
import SwiftUI
struct Wave: Shape{
var amplitude: Double
var frequency: Double
var phase: Double
func path(in rect: CGRect) -> Path {
let path = UIBezierPath()
let width = Double(rect.width)
let height = Double(rect.height)
let midWeight = width/2
let midHeight = height/2
let wavelenth = width/frequency
path.move(to: CGPoint(x: 0, y: midHeight))
for x in stride(from: 0, to: width, by: 10){
let y = amplitude * sin(x/wavelenth + phase) + midHeight
path.addLine(to: CGPoint(x: x, y: y))
}
return Path(path.cgPath)
}
}
struct meshView: View {
@State var phase: Double = 0.0
var body: some View {
ZStack{
Wave(amplitude: 50, frequency: 10, phase: phase)
.stroke(Color.white, lineWidth: 4)
}
.background(Color.blue)
.edgesIgnoringSafeArea(.all)
.onAppear{
withAnimation(Animation.linear(duration: 1).repeatForever(autoreverses: false)){
self.phase = .pi * 2
}
}
}
}
struct meshView_Previews: PreviewProvider {
static var previews: some View {
meshView()
}
}
| 24.803571 | 92 | 0.565875 |
0884254094fef989140547ab431840be4372c752 | 469 | //
// CDLink+CoreDataProperties.swift
//
//
// Created by Ankur Kesharwani on 05/06/17.
//
//
import Foundation
import CoreData
extension CDLink {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CDLink> {
return NSFetchRequest<CDLink>(entityName: "Links")
}
@NSManaged public var urlString: String?
@NSManaged public var startIndex: Int64
@NSManaged public var length: Int64
@NSManaged public var tweet: CDTweet?
}
| 18.76 | 73 | 0.695096 |
56e4495be5045d5997b44029702c0fe06c39b12a | 4,230 | //
// ScheduleControlNavigationBar.swift
// Taskem
//
// Created by Wilson on 10/6/18.
// Copyright © 2018 Wilson. All rights reserved.
//
import Foundation
import TaskemFoundation
protocol ScheduleControlNavigationBarDataSource {
func views(_ navbar: ScheduleControlNavigationBar) -> [ScheduleNavigationBarCell]
func subtitle(_ navbar: ScheduleControlNavigationBar) -> String
}
class ScheduleControlNavigationBar: UINavigationBar, ThemeObservable {
public var dataSource: ScheduleControlNavigationBarDataSource?
public var isCustomViewsVisible = true {
didSet {
contentView.isHidden = !isCustomViewsVisible
subtitle.isHidden = !isCustomViewsVisible
}
}
public var contentView: ScheduleControlNavigationBarContentView = {
return .init(maxWidth: 0)
}()
public var subtitle: UILabel = {
let label = UILabel()
label.font = .avenirNext(ofSize: 14, weight: .demiBold)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupUI()
}
override func layoutSubviews() {
super.layoutSubviews()
layoutUIIfNeed()
}
public func applyTheme(_ theme: AppTheme) {
subtitle.textColor = theme.navBarTitle
}
public func setEditing(_ editing: Bool) {
contentView.alpha = editing ? 0 : 1
contentView.alpha = editing ? 0 : 1
subtitle.alpha = editing ? 0 : 1
}
private func setupUI() {
observeAppTheme()
}
public func reloadData() {
guard let dataSource = dataSource else { return }
subtitle.text = dataSource.subtitle(self)
contentView.reload(dataSource.views(self))
}
private func layoutUIIfNeed() {
guard shouldLayout,
let titleView = largeTitle else { return }
titleView.clipsToBounds = false
setupSubtitle(in: titleView)
setupContentView(in: titleView)
}
private var shouldLayout: Bool {
for view in subviews where isLargeTitle(view) {
if view.clipsToBounds == true ||
subtitle.superview == nil ||
contentView.superview == nil {
return true
}
}
return false
}
private func setupContentView(in view: UIView) {
let isHidden = contentView.isHidden
contentView.isHidden = true
contentView.stackView.maxWidth = frame.width / 3
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.removeFromSuperview()
view.addSubview(contentView)
contentView.leftAnchor.constraint(equalTo: subtitle.safeAreaLayoutGuide.rightAnchor).isActive = true
contentView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -10).isActive = true
contentView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true
contentView.heightAnchor.constraint(equalToConstant: view.frame.height)
contentView.isHidden = isHidden
}
private func setupSubtitle(in view: UIView) {
guard let largeTitleLabel = view.subviews.first as? UILabel else { return }
subtitle.translatesAutoresizingMaskIntoConstraints = false
subtitle.removeFromSuperview()
view.addSubview(subtitle)
subtitle.leftAnchor.constraint(equalTo: largeTitleLabel.safeAreaLayoutGuide.leftAnchor).isActive = true
subtitle.bottomAnchor.constraint(equalTo: largeTitleLabel.safeAreaLayoutGuide.topAnchor).isActive = true
}
private var largeTitle: UIView? {
return subviews.first(where: { isLargeTitle($0) })
}
private func isLargeTitle(_ view: UIView) -> Bool {
return String(describing: type(of: view)).contains("BarLargeTitleView")
}
}
| 30.431655 | 122 | 0.644917 |
23b9c6517b9529f6580a9aa56ddf9dee2d817633 | 1,440 | //
// AccountSummaryViewController+Networking.swift
// Bankey
//
// Created by niab on Jan/02/22.
//
import Foundation
import UIKit
struct Account: Codable {
let id: String
let type: AccountType
let name: String
let amount: Decimal
let createdDateTime: Date
static func makeSkeleton() -> Account {
return Account(id: "1", type: .Banking, name: "Account name", amount: 0.0, createdDateTime: Date())
}
}
extension AccountSummaryViewController {
func fetchAccounts(forUserId userId: String, completion: @escaping (Result<[Account],NetworkError>) -> Void) {
let url = URL(string: "https://fierce-retreat-36855.herokuapp.com/bankey/profile/\(userId)/accounts")!
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
guard let data = data, error == nil else {
completion(.failure(.serverError))
return
}
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let accounts = try decoder.decode([Account].self, from: data)
completion(.success(accounts))
} catch {
completion(.failure(.decodingError))
}
}
}.resume()
}
}
| 29.387755 | 114 | 0.554167 |
208c915d998cb4b5c569c46cdad252e3163a97c1 | 2,401 | //
// GDGeoDataListView.swift
// GDGeoDataDemo
//
// Created by Knut Inge Grosland on 2019-10-11.
// Copyright © 2019 Cocmoc. All rights reserved.
//
import SwiftUI
struct GDGeoDataView: View {
@State private var items = GDRegion.regions
var body: some View {
NavigationView {
RegionListView(regions: $items)
.navigationBarTitle(Text("GDGeoData"))
}.navigationViewStyle(DoubleColumnNavigationViewStyle())
}
}
struct RegionListView: View {
@Binding var regions: [GDRegion]
var worldView: some View {
List {
ForEach(GDCountry.countries, id: \.self) { country in
NavigationLink(
destination: CountryView(country: country)
) {
Text(country.name)
}
}
}
}
func destination(region: GDRegion) -> AnyView {
switch region.name {
case "World":
return AnyView(worldView.navigationBarTitle(Text(region.name)))
default:
return AnyView(SubRegionListView(region: region))
}
}
var body: some View {
List {
ForEach(regions, id: \.self) { region in
NavigationLink(
destination: self.destination(region: region)
) {
Text(region.name)
}
}
}
}
}
struct SubRegionListView: View {
var region: GDRegion
var body: some View {
List {
ForEach(region.subRegions, id: \.self) { subRegion in
NavigationLink(
destination: CountryListView(subRegion: subRegion)
) {
Text(subRegion.name)
}
}
}.navigationBarTitle(Text(region.name))
}
}
struct CountryListView: View {
var subRegion: GDSubRegion
var body: some View {
List {
ForEach(subRegion.countries, id: \.self) { country in
NavigationLink(
destination: CountryView(country: country)
) {
Text(country.name)
}
}
}.navigationBarTitle(Text(subRegion.name))
}
}
struct GDGeoDataListView_Previews: PreviewProvider {
static var previews: some View {
GDGeoDataView()
}
}
| 25.010417 | 75 | 0.528946 |
333766af9d97bbddfce625db189902a80482f958 | 1,232 | //
// RepoInteractor.swift
// StackBuilderDemo
//
// Created by Mustafa Ezzat on 2/11/19.
// Copyright © 2019 kitchen. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
protocol RepoInteractorProtocol {
func fetchRepo()
}
class RepoInteractor {
var repoPresenter: RepoPresenterProtocol?
}
extension RepoInteractor: RepoInteractorProtocol{
func fetchRepo() {
let utilityQueue = DispatchQueue.global(qos: .utility)
let url = "https://api.github.com/users/CristhianMotoche/repos"
Alamofire.request(url, method: .get).responseArray(queue: utilityQueue) {
(response: DataResponse<[RepoModel]>) in
if let repoResponse = response.result.value {
DispatchQueue.main.async {
self.repoPresenter?.presentingRepoSuccess(with: repoResponse)
}
} else{
DispatchQueue.main.async {
if let localizedDescription = response.error?.localizedDescription{
self.repoPresenter?.presentingRepoFailure(with: localizedDescription)
}
}
}
}
}
}
| 29.333333 | 93 | 0.627435 |
ddf806c3df689ce2c8108cb2e42ad52aa2aa25c7 | 29,775 | //
// NokeDevice.swift
// NokeMobileLibrary
//
// Created by Spencer Apsley on 1/12/18.
// Copyright © 2018 Noke. All rights reserved.
//
import Foundation
import CoreBluetooth
/// Protocol for interacting with the Noke device (in virtually all cases this is the NokeDeviceManager)
protocol NokeDeviceDelegate
{
/// Called after Noke device reads the session and stores it
func didSetSession(_ mac:String)
}
/**
Lock states of Noke Devices
- Unlocked: Noke device unlocked OR Device has been locked but phone never received updated status
- Locked: Noke device locked
*/
public enum NokeDeviceLockState : Int{
case nokeDeviceLockStateUnknown = -1
case nokeDeviceLockStateUnlocked = 0
case nokeDeviceLockStateUnshackled = 1
case nokeDeviceLockStateLocked = 2
}
/// Class stores information about the Noke device and contains methods for interacting with the Noke device
public class NokeDevice: NSObject, NSCoding, CBPeripheralDelegate{
/// Time Interval representing the most recent time the device was discovered
public var lastSeen: Double = 0.0
/// typealias used for handling bytes from the lock
public typealias byteArray = UnsafeMutablePointer<UInt8>
/// Name of the Noke device (strictly cosmetic)
public var name: String = ""
/// MAC address of Noke device. This can be found in the peripheral name
public var mac: String = ""
/// Serial number of Noke device. Laser engraved onto the device during manufacturing
public var serial: String = ""
/// UUID of the lock. Unique identifier assigned by iOS upon connection
public var uuid: String = ""
/// Firmware and hardware version of the lock. Follows format: '3P-2.10' where '3P' is the hardware version and '2.10' is the firmware version
public var version: String = ""
/// Tracking key used to track Noke device usage and activity
public var trackingKey: String = ""
/// CBPeripheral of the Noke device used by CoreBluetooth
var peripheral: CBPeripheral?
/// Delegate of the Noke device. In virtually all cases this is the NokeDeviceManager
var delegate: NokeDeviceDelegate?
/// Byte array read from the session characteristic upon connecting to the Noke device
public var session: String?
/// Battery level of the Noke device in millivolts
public var battery: UInt64 = 0
/// Connection state of the Noke device
public var connectionState: NokeDeviceConnectionState?
/// Lock state of the Noke device
public var lockState: NokeDeviceLockState = NokeDeviceLockState.nokeDeviceLockStateLocked
/// Bluetooth Gatt Service of Noke device
var nokeService: CBService?
/// Read characteristic of Noke device
var rxCharacteristic: CBCharacteristic?
/// Write characteristic of Noke device
var txCharacteristic: CBCharacteristic?
/// Session characteristic of Noke device. This is read upon connecting and used for encryption
var sessionCharacteristic: CBCharacteristic?
/// Array of commands to be sent to the Noke device
var commandArray: Array<Data>!
/// Array of responses from the Noke device that need to be uploaded
var responseArray: Array<String>!
/// Unlock command used for offline unlocking
var unlockCmd: String = ""
/// Unique key used for encrypting the unlock command for offline unlocking
var offlineKey: String = ""
/// Indicates if the lock keys need to be restored
var isRestoring: Bool = false
/// UUID of the Noke service
internal static func nokeServiceUUID() -> (CBUUID){
return CBUUID.init(string: "1bc50001-0200-d29e-e511-446c609db825")
}
/// UUID of the Noke write characteristic
internal static func txCharacteristicUUID() -> (CBUUID){
return CBUUID.init(string: "1bc50002-0200-d29e-e511-446c609db825")
}
/// UUID of the Noke read characteristic
internal static func rxCharacteristicUUID() -> (CBUUID){
return CBUUID.init(string: "1bc50003-0200-d29e-e511-446c609db825")
}
/// UUID of the Noke session characteristic
internal static func sessionCharacteristicUUID() -> (CBUUID){
return CBUUID.init(string: "1bc50004-0200-d29e-e511-446c609db825")
}
/**
Initializes a new Noke device with provided properties
- Parameters:
- name: Name of the noke device (strictly for UI purposes)
- mac: MAC address of noke device. NokeDeviceManager will scan for this mac address
-Returns: A beautiful, ready-to-use, Noke device just for you
*/
public init?(name: String, mac: String){
self.name = name
self.mac = mac
self.unlockCmd = ""
self.offlineKey = ""
self.lockState = NokeDeviceLockState.nokeDeviceLockStateLocked
super.init()
}
/**
Initializes a new Noke device with provided properties. This is mostly used when loading cached locks from user defaults, but can also be used to initialize a Noke device when more properties are known
- Parameters:
- name: Name of the noke device (strictly for UI purposes)
- mac: MAC address of noke device. NokeDeviceManager will scan for this mac address
- serial: Serial address of the Noke device, laser-engraved on the device during manufacturing
- uuid: Unique identifier of the Noke device, assigned by iOS
- version: Hardware and firmware version of the Noke device
- trackingKey: Tracking key of the Noke device used to track activity
- battery: Battery level of the lock in millivolts
- unlockCmd: Unlock command used for offline unlocking
- offlineKey: Key used to encrypt the offline unlock command
-Returns: A beautiful, ready-to-use, Noke device just for you
*/
public init(name: String, mac: String, serial: String, uuid: String, version: String, trackingKey: String, battery: UInt64, unlockCmd: String, offlineKey: String){
self.name = name
self.mac = mac
self.serial = serial
self.uuid = uuid
self.version = version
self.trackingKey = trackingKey
self.battery = battery
self.unlockCmd = unlockCmd
self.offlineKey = offlineKey
}
/// Method used to encode class to be stored in User Defaults
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.mac, forKey: "mac")
aCoder.encode(self.serial, forKey:"serial")
aCoder.encode(self.uuid, forKey:"uuid")
aCoder.encode(self.version, forKey:"version")
aCoder.encode(self.trackingKey, forKey:"trackingkey")
aCoder.encode(self.battery, forKey:"battery")
aCoder.encode(self.unlockCmd, forKey:"unlockcmd")
aCoder.encode(self.offlineKey, forKey:"offlinekey")
}
/// Method used to decode class to reload from User Defaults
public required convenience init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObject(forKey: "name") as? String,
let mac = aDecoder.decodeObject(forKey: "mac") as? String,
let serial = aDecoder.decodeObject(forKey: "serial") as? String,
let uuid = aDecoder.decodeObject(forKey: "uuid") as? String,
let version = aDecoder.decodeObject(forKey: "version") as? String,
let trackingKey = aDecoder.decodeObject(forKey: "trackingkey") as? String,
let battery = aDecoder.decodeObject(forKey: "battery") as? UInt64,
let unlockCmd = aDecoder.decodeObject(forKey: "unlockcmd") as? String,
let offlineKey = aDecoder.decodeObject(forKey: "offlinekey") as? String
else{return nil}
self.init(
name: name,
mac: mac,
serial: serial,
uuid: uuid,
version: version,
trackingKey: trackingKey,
battery: battery,
unlockCmd: unlockCmd,
offlineKey: offlineKey)
}
/// Called when initial bluetooth connection has been established
fileprivate func didConnect(){
self.peripheral?.delegate = self
self.peripheral!.discoverServices([NokeDevice.nokeServiceUUID()])
}
/// Stores the session after reading the session characteristic upon connecting
fileprivate func setSession(_ data: Data){
self.session = self.bytesToString(data: data, start: 0, length: 20)
getBatteryFromSession(data: data)
self.delegate?.didSetSession(self.mac)
}
/// Extracts the battery level from the session and stores it in the battery variable
fileprivate func getBatteryFromSession(data: Data){
var session = data
session.withUnsafeMutableBytes{(bytes: UnsafeMutablePointer<UInt8>)->Void in
let batteryArray = byteArray.allocate(capacity: 2)
batteryArray[0] = bytes[3]
batteryArray[1] = bytes[2]
let batteryString = String.init(format: "%02x%02x", batteryArray[0],batteryArray[1])
let batteryResult = UInt64(batteryString, radix:16)
battery = batteryResult!
}
}
/**
Adds encrypted command to array to be sent to Noke device
- Parameter data: 20 byte command to be sent to the lock
*/
internal func addCommandToCommandArray(_ data: Data){
if(commandArray == nil){
commandArray = Array<Data>()
}
commandArray.append(data)
}
/// Sends command from the first position of the command array to the Noke device via bluetooth
internal func writeCommandArray(){
if(self.txCharacteristic?.properties != nil){
let cmdData = commandArray.first
self.peripheral?.writeValue(cmdData!, for:self.txCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
}else{
debugPrint("No write property on TX characteristic")
}
}
/// Reads the session characteristic
fileprivate func readSessionCharacteristic(){
self.peripheral?.readValue(for: self.sessionCharacteristic!)
}
/**
Parses through the broadcast data and pulls out the version
Parameters
data: broadcast data from the lock
*/
public func setVersion(data: Data, deviceName: String){
var byteData = data
if(deviceName.contains(Constants.NOKE_DEVICE_IDENTIFIER_STRING)){
byteData.withUnsafeMutableBytes{(bytes: UnsafeMutablePointer<UInt8>)->Void in
let majorVersion = bytes[3]
let minorVersion = bytes[4]
let startIndex = deviceName.index(deviceName.startIndex, offsetBy: 4)
let endIndex = deviceName.index(startIndex, offsetBy:2)
let hardwareVersion = String(deviceName[startIndex..<endIndex])
self.version = String(format: "%@-%d.%d", hardwareVersion ?? "",majorVersion,minorVersion)
}
}
}
public func getHardwareVersion()->String{
let endIndex = version.index(version.startIndex, offsetBy:2)
return String(version[version.startIndex..<endIndex])
}
public func getSoftwareVersion()->String{
let startIndex = version.index(version.startIndex, offsetBy: 3)
return String(version[startIndex..<version.endIndex])
}
/// MARK: CBPeripheral Delegate Methods
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if(error != nil){
return
}
for s: CBService in (peripheral.services!){
if(s.uuid.isEqual(NokeDevice.nokeServiceUUID())){
self.nokeService = s
self.peripheral?.discoverCharacteristics([NokeDevice.txCharacteristicUUID(), NokeDevice.rxCharacteristicUUID(), NokeDevice.sessionCharacteristicUUID()], for: s)
}
}
}
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if((error) != nil){
return
}
for c : CBCharacteristic in service.characteristics!
{
if(c.uuid.isEqual(NokeDevice.rxCharacteristicUUID())){
self.rxCharacteristic = c
self.peripheral!.setNotifyValue(true, for:self.rxCharacteristic!)
}
else if(c.uuid.isEqual(NokeDevice.txCharacteristicUUID())){
self.txCharacteristic = c
}
else if(c.uuid.isEqual(NokeDevice.sessionCharacteristicUUID())){
self.sessionCharacteristic = c
self.readSessionCharacteristic()
}
}
}
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if(error != nil){
return
}
if(characteristic == self.rxCharacteristic){
let response = characteristic.value
_ = self.receivedDataFromLock(response!)
}
else if(characteristic == self.sessionCharacteristic){
let data = characteristic.value
self.setSession(data!)
}
}
/**
Called when the phone receives data from the Noke device. There are two main types of data packets:
- Server packets: Encrypted responses from the locks that are parsed by the server. Can include logs, keys, and quick-click confirmations
- App packets: Unencrypted responses that indicate whether command succeeded or failed.
- Parameter data: 20 byte response from the lock
*/
fileprivate func receivedDataFromLock(_ data: Data){
var newData = data
newData.withUnsafeMutableBytes{(bytes: UnsafeMutablePointer<UInt8>)->Void in
let dataBytes = bytes
let destByte = Int(dataBytes[0])
switch destByte{
case Constants.SERVER_Dest:
if(self.session != nil){
NokeDeviceManager.shared().addUploadPacketToQueue(
response: self.bytesToString(data: data, start: 0, length: 20),
session: self.session!,
mac: self.mac)
}
break
case Constants.APP_Dest:
let resultByte = Int(data[1])
switch resultByte{
case Constants.SUCCESS_ResultType:
if(isRestoring){
let commandid = Int(data[2])
commandArray.removeAll()
NokeDeviceManager.shared().clearUploadQueue()
self.isRestoring = false
NokeDeviceManager.shared().confirmRestore(noke: self, commandid: commandid)
NokeDeviceManager.shared().disconnectNokeDevice(self)
}else{
self.moveToNext()
if(self.commandArray.count == 0){
self.lockState = NokeDeviceLockState.nokeDeviceLockStateUnlocked
self.connectionState = NokeDeviceConnectionState.nokeDeviceConnectionStateUnlocked
NokeDeviceManager.shared().delegate?.nokeDeviceDidUpdateState(to: self.connectionState!, noke: self)
}
}
break
case Constants.INVALIDKEY_ResultType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidKey, message: "Invalid Key Result", noke: self)
self.moveToNext()
// if(self.commandArray.count == 0){
// if(!isRestoring){
// NokeDeviceManager.shared().restoreDevice(noke: self)
// }
// }
break
case Constants.INVALIDCMD_ResultType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidCmd, message: "Invalid Command Result", noke: self)
self.moveToNext()
break
case Constants.INVALIDPERMISSION_ResultType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidPermission, message: "Invalid Permission (wrong key) Result", noke: self)
self.moveToNext()
break
case Constants.SHUTDOWN_ResultType:
let lockStateByte = Int32(data[2])
var isLocked = true
if(lockStateByte == 0){
self.lockState = NokeDeviceLockState.nokeDeviceLockStateUnlocked
isLocked = false
}
else if(lockStateByte == 1){
self.lockState = NokeDeviceLockState.nokeDeviceLockStateLocked
}
let timeoutStateByte = Int32(data[3])
var didTimeout = true
if(timeoutStateByte == 1){
didTimeout = false
}
NokeDeviceManager.shared().delegate?.nokeDeviceDidShutdown(noke: self, isLocked: isLocked, didTimeout: didTimeout)
break
case Constants.INVALIDDATA_ResultType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidData, message: "Invalid Data Result", noke: self)
self.moveToNext()
break
case Constants.FAILEDTOLOCK_ResultType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidData, message: "Failed To Lock", noke: self)
break
case Constants.FAILEDTOUNLOCK_ResultType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidData, message: "Failed To Unlock", noke: self)
break
case Constants.FAILEDTOUNSHACKLE_ResultType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidData, message: "Failed To Unshackle", noke: self)
break
case Constants.INVALID_ResultType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidResult, message: "Invalid Result", noke: self)
self.moveToNext()
break
default:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorUnknown, message: "Unable to recognize result", noke: self)
self.moveToNext()
break
}
break
case Constants.INVALID_ResponseType:
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeDeviceErrorInvalidResult, message: "Invalid packet received", noke: self)
break
default:
break
}
}
}
/// Moves to next command in the command array in preperation to sending
func moveToNext(){
if(commandArray != nil){
if(commandArray.count >= 1){
commandArray.remove(at: 0)
if(commandArray.count >= 1){
writeCommandArray()
}
}
}
}
/**
Makes the necessary checks and then requests the unlock commands from the server (or generates the unlock command if offline)
This method is also responsible for sending the command to the lock after it's received
Before unlocking, please check:
- unlock URL is set on the NokeDeviceManager
- unlock endpoint has been properly implemented on server
- Noke Device is provided with valid offline key and command (if unlocking offline)
- A internet connection is present (if unlocking online)
*/
public func unlock(){
if(Reachability.isConnectedToNetwork()){
}else{
// TODO: Handle offline unlock
}
}
/**
Sends a command string from the Noke Core API to the Noke device
- Parameter commands: A command string from the Core API. Commands are delimited by '+'
*/
public func sendCommands(_ commands: String){
let commandsArr = commands.components(separatedBy: "+")
for command: String in commandsArr{
self.addCommandToCommandArray(self.stringToBytes(hexstring: command)!)
}
self.writeCommandArray()
}
/**
Sets offline key and command used for unlocking offline
- Parameters:
-key: String used to encrypt the command to the lock. Received from the Core API
-command: String sent to the lock to unlock offline. Received from the Core API
*/
public func setOfflineValues(key: String, command: String){
self.offlineKey = key
self.unlockCmd = command
}
/**
Sets offline values before offline unlocking
- Parameters:
-key: String used to encrypt the command to the lock. Received from the Core API
-command: String sent to the lock to unlock offline. Received from the Core API
*/
public func offlineUnlock(key: String, command: String){
self.offlineKey = key
self.unlockCmd = command
self.offlineUnlock()
}
/**
Unlocks the lock using the offline key and the unlock command. If the keys and commands have been set, no internet connection is required.
*/
public func offlineUnlock(){
if(offlineKey.count == Constants.OFFLINE_KEY_LENGTH && unlockCmd.count == Constants.OFFLINE_COMMAND_LENGTH){
var keydata = Data(capacity: offlineKey.count/2)
let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
regex.enumerateMatches(in: offlineKey, options: [], range: NSMakeRange(0, offlineKey.count)) { match, flags, stop in
let byteString = (offlineKey as NSString).substring(with: match!.range)
var num = UInt8(byteString, radix: 16)!
keydata.append(&num, count: 1)
}
guard keydata.count > 0 else {
return
}
var cmddata = Data(capacity:unlockCmd.count/2)
regex.enumerateMatches(in: unlockCmd, options: [], range: NSMakeRange(0, unlockCmd.count)) { match, flags, stop in
let byteCmdString = (unlockCmd as NSString).substring(with: match!.range)
var cmdnum = UInt8(byteCmdString, radix: 16)!
cmddata.append(&cmdnum, count: 1)
}
guard cmddata.count > 0 else {
return
}
let currentDateTime = Date()
let timeStamp = UInt64(currentDateTime.timeIntervalSince1970)
let timedata = Data.init(bytes: [UInt8((timeStamp >> 24) & 0xFF), UInt8((timeStamp >> 16) & 0xFF), UInt8((timeStamp >> 8) & 0xFF), UInt8((timeStamp & 0xFF))])
let finalCmdData = createOfflineUnlock(preSessionKey: keydata, unlockCmd: cmddata, timestamp: timedata)
self.addCommandToCommandArray(finalCmdData)
self.writeCommandArray()
}else{
NokeDeviceManager.shared().delegate?.nokeErrorDidOccur(error: NokeDeviceManagerError.nokeLibraryErrorInvalidOfflineKey, message: "Offline Key/Command is not a valid length", noke: self)
}
}
/**
Creates the offline unlock command, adds the current timestamp, and encrypts using the keys.
- Parameters:
- preSessionKey: key used to encrypt commands
- unlockCmd: command to be encrypted
- timestamp: Current time to be embedded into the command
*/
fileprivate func createOfflineUnlock(preSessionKey: Data, unlockCmd: Data, timestamp: Data) -> Data
{
let newCommandPacket = byteArray.allocate(capacity: 20)
var key = self.createOfflineCombinedKey(baseKey:preSessionKey)
var unlockCmdBytes = [UInt8](unlockCmd)
var x = 0
while x<4 {
newCommandPacket[x] = unlockCmdBytes[x]
x += 1
}
let cmddata = byteArray.allocate(capacity: 16)
var i = 0
while i<16 {
cmddata[i] = unlockCmd[i+4]
i += 1
}
var timeStampBytes = [UInt8](timestamp)
cmddata[2] = timeStampBytes[3]
cmddata[3] = timeStampBytes[2]
cmddata[4] = timeStampBytes[1]
cmddata[5] = timeStampBytes[0]
var checksum:Int = 0
var n = 0
while n<15 {
checksum += Int(cmddata[n])
n += 1
}
cmddata[15] = UInt8.init(truncatingIfNeeded: checksum)
key.withUnsafeMutableBytes {(bytes: UnsafeMutablePointer<UInt8>)->Void in
let keyBytes = bytes
self.copyArray(newCommandPacket, outStart: 4, dataIn: self.encryptPacket(keyBytes, data: cmddata), inStart: 0, size: 16)
}
return Data.init(bytes: [newCommandPacket[0], newCommandPacket[1], newCommandPacket[2], newCommandPacket[3], newCommandPacket[4], newCommandPacket[5], newCommandPacket[6], newCommandPacket[7], newCommandPacket[8], newCommandPacket[9], newCommandPacket[10], newCommandPacket[11], newCommandPacket[12], newCommandPacket[13], newCommandPacket[14], newCommandPacket[15], newCommandPacket[16], newCommandPacket[17], newCommandPacket[18], newCommandPacket[19]])
}
//Creates offline key by combining the offline key with the session
fileprivate func createOfflineCombinedKey(baseKey: Data) -> Data{
let session = stringToBytes(hexstring: self.session!)!
var sessionBytes = [UInt8](session)
var baseKeyBytes = [UInt8](baseKey)
var total:Int
var x = 0
while x<16 {
total = Int(baseKeyBytes[x]) + Int(sessionBytes[x])
baseKeyBytes[x] = UInt8.init(truncatingIfNeeded: total)
x += 1
}
return Data.init(bytes: baseKeyBytes)
}
/// Converts hex string to byte array (data)
internal func stringToBytes(hexstring: String) -> Data? {
var data = Data(capacity: hexstring.count / 2)
let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
regex.enumerateMatches(in: hexstring, range: NSMakeRange(0, hexstring.utf16.count)) { match, flags, stop in
let byteString = (hexstring as NSString).substring(with: match!.range)
var num = UInt8(byteString, radix: 16)!
data.append(&num, count: 1)
}
guard data.count > 0 else { return nil }
return data
}
/// Converts byte array (data) to hex string
internal func bytesToString(data:Data, start:Int, length:Int) -> String
{
var bytes = [UInt8](data)
let hex = NSMutableString(string: "")
var x = 0
while x < length {
hex.appendFormat("%02x", bytes[x + start])
x += 1
}
let immutableHex = String.init(hex)
return immutableHex
}
fileprivate func copyArray(_ dataOut: byteArray, outStart: Int, dataIn: byteArray, inStart: Int, size: Int){
var x = 0
while x < size {
dataOut[x+outStart] = dataIn[x+inStart]
x += 1
}
}
fileprivate func copyArray(_ dataOut: byteArray, dataIn: byteArray, size: Int)
{
var x = 0
while x < size {
dataOut[x] = dataIn[x]
x += 1
}
}
fileprivate func copyArray(_ dataOut: Data, dataIn: Data, size: Int) -> Data
{
var bytesDataOut = [UInt8](dataOut)
var bytesDataIn = [UInt8](dataIn)
var x = 0
while x < size {
bytesDataOut[x] = bytesDataIn[x]
x += 1
}
return Data.init(bytes: bytesDataOut)
}
fileprivate func encryptPacket(_ combinedKey: byteArray, data: byteArray) -> byteArray
{
let tempKey = byteArray.allocate(capacity: 16)
let buffer = byteArray.allocate(capacity: 16)
self.copyArray(tempKey, dataIn: combinedKey, size: 16)
aes_enc_dec(data, tempKey, 1)
self.copyArray(buffer, dataIn: data, size: 16)
return buffer
}
}
| 42.055085 | 463 | 0.606516 |
8f67d3052f2503c9d0c803c8188357bb530610c5 | 943 | //
// UserInfoList.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import AnyCodable
import Foundation
import Vapor
/** */
public final class UserInfoList: Content, Hashable {
/** An array of `userInfo` objects containing information about the users in the group. */
public var users: [UserInfo]?
public init(users: [UserInfo]? = nil) {
self.users = users
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case users
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(users, forKey: .users)
}
public static func == (lhs: UserInfoList, rhs: UserInfoList) -> Bool {
lhs.users == rhs.users
}
public func hash(into hasher: inout Hasher) {
hasher.combine(users?.hashValue)
}
}
| 23.575 | 94 | 0.660657 |
7a983b202d6896134915cd9665112c48f793876a | 3,603 | //
// NSTableView.swift
// Bond
//
// Created by Srdan Rasic on 18/08/16.
// Copyright © 2016 Swift Bond. All rights reserved.
//
import AppKit
import ReactiveKit
public extension NSTableView {
public var rDelegate: ProtocolProxy {
return protocolProxy(for: NSTableViewDelegate.self, setter: NSSelectorFromString("setDelegate:"))
}
public var rDataSource: ProtocolProxy {
return protocolProxy(for: NSTableViewDataSource.self, setter: NSSelectorFromString("setDataSource:"))
}
}
public extension SignalProtocol where Element: DataSourceEventProtocol, Error == NoError {
public typealias DataSource = Element.DataSource
@discardableResult
public func bind(to tableView: NSTableView, animated: Bool = true, createCell: @escaping (DataSource, Int, NSTableView) -> NSView) -> Disposable {
let dataSource = Property<DataSource?>(nil)
tableView.rDelegate.feed(
property: dataSource,
to: #selector(NSTableViewDelegate.tableView(_:viewFor:row:)),
map: { (dataSource: DataSource?, tableView: NSTableView, column: NSTableColumn, row: Int) -> NSView in
return createCell(dataSource!, row, tableView)
})
tableView.rDataSource.feed(
property: dataSource,
to: #selector(NSTableViewDataSource.numberOfRows(in:)),
map: { (dataSource: DataSource?, _: NSTableView) -> Int in dataSource?.numberOfItems(inSection: 0) ?? 0 }
)
let serialDisposable = SerialDisposable(otherDisposable: nil)
var updating = false
serialDisposable.otherDisposable = observeIn(ImmediateOnMainExecutionContext).observeNext { [weak tableView] event in
guard let tableView = tableView else {
serialDisposable.dispose()
return
}
dataSource.value = event.dataSource
guard animated else {
tableView.reloadData()
return
}
switch event.kind {
case .reload:
tableView.reloadData()
case .insertItems(let indexPaths):
if !updating && indexPaths.count > 1 {
tableView.beginUpdates()
defer { tableView.endUpdates() }
}
indexPaths.forEach { indexPath in
tableView.insertRows(at: IndexSet(integer: indexPath.item), withAnimation: [])
}
case .deleteItems(let indexPaths):
if !updating && indexPaths.count > 1 {
tableView.beginUpdates()
defer { tableView.endUpdates() }
}
indexPaths.forEach { indexPath in
tableView.insertRows(at: IndexSet(integer: indexPath.item), withAnimation: [])
}
case .reloadItems(let indexPaths):
if !updating && indexPaths.count > 1 {
tableView.beginUpdates()
defer { tableView.endUpdates() }
}
indexPaths.forEach { indexPath in
tableView.insertRows(at: IndexSet(integer: indexPath.item), withAnimation: [])
}
case .moveItem(let indexPath, let newIndexPath):
tableView.moveRow(at: indexPath.item, to: newIndexPath.item)
case .insertSections:
fatalError("NSTableView binding does not support sections.")
case .deleteSections:
fatalError("NSTableView binding does not support sections.")
case .reloadSections:
fatalError("NSTableView binding does not support sections.")
case .moveSection:
fatalError("NSTableView binding does not support sections.")
case .beginUpdates:
tableView.beginUpdates()
updating = true
case .endUpdates:
updating = false
tableView.endUpdates()
}
}
return serialDisposable
}
}
| 32.754545 | 148 | 0.666944 |
ebad7b683d3d6b2fd0d0fdc2c71521e00a5bb608 | 1,569 | import Alamofire
public enum GenericResult<T> {
case success(T)
case failure(Error)
}
public enum ExposureResult {
case success(Int)
case failure(Error)
}
public enum GenericError: Error {
case unknown
case badRequest
case cancelled
case notFound
case notImplemented
case unauthorized
}
public enum ExposureError: LocalizedError {
case `default`(String?)
case dailyFileProcessingLimitExceeded
case cancelled
/// TODO localize this
public var errorDescription: String? {
switch self {
case .default(message: let message):
return message ?? String.emptyMessageError
case .dailyFileProcessingLimitExceeded:
return String.dailyFileProcessingLimitExceeded.localized
case .cancelled:
return String.exposureDetectionCanceled.localized
}
}
}
public enum APIError: LocalizedError {
case `default`(message: String?)
public var errorDescription: String? {
switch self {
case .default(message: let message):
return message ?? String.emptyMessageError
}
}
}
public enum SubmissionError: CustomNSError {
case `default`(message: String?)
case noKeysOnDevice
public var errorDescription: String? {
switch self {
case .noKeysOnDevice:
return String.noKeysOnDevice
case .default(message: let message):
return message ?? String.emptyMessageError
}
}
public var errorCode: Int {
switch self {
case .noKeysOnDevice:
return 999
default:
return 0
}
}
}
public let GenericSuccess = GenericResult.success(())
| 18.458824 | 62 | 0.70682 |
ab5a6d8cc1ead7631a6c82dda4f933fd35b6bef2 | 3,996 | // WebAuthError.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
List of possible web-based authentication errors
- NoBundleIdentifierFound: Cannot get the App's Bundle Identifier to use for redirect_uri.
- CannotDismissWebAuthController: When trying to dismiss WebAuth controller, no presenter controller could be found.
- UserCancelled: User cancelled the web-based authentication, e.g. tapped the "Done" button in SFSafariViewController
- PKCENotAllowed: PKCE for the supplied Auth0 ClientId was not allowed. You need to set the `Token Endpoint Authentication Method` to `None` in your Auth0 Dashboard
- noNonceProvided: A nonce value must be provided to use the response option of id_token
- invalidIdTokenNonce: Failed to match token nonce with request nonce
- missingAccessToken: access_token missing in response
*/
public enum WebAuthError: CustomNSError {
case noBundleIdentifierFound
case cannotDismissWebAuthController
case userCancelled
case pkceNotAllowed(String)
case noNonceProvided
case missingResponseParam(String)
case invalidIdTokenNonce
case missingAccessToken
static let genericFoundationCode = 1
static let cancelledFoundationCode = 0
public static let infoKey = "com.auth0.webauth.error.info"
public static let errorDomain: String = "com.auth0.webauth"
public var errorCode: Int {
switch self {
case .userCancelled:
return WebAuthError.cancelledFoundationCode
default:
return WebAuthError.genericFoundationCode
}
}
public var errorUserInfo: [String: Any] {
switch self {
case .userCancelled:
return [
NSLocalizedDescriptionKey: "User Cancelled Web Authentication",
WebAuthError.infoKey: self
]
case .pkceNotAllowed(let message):
return [
NSLocalizedDescriptionKey: message,
WebAuthError.infoKey: self
]
case .noNonceProvided:
return [
NSLocalizedDescriptionKey: "A nonce value must be supplied when response_type includes id_token in order to prevent replay attacks",
WebAuthError.infoKey: self
]
case .invalidIdTokenNonce:
return [
NSLocalizedDescriptionKey: "Could not validate the id_token",
WebAuthError.infoKey: self
]
case .missingAccessToken:
return [
NSLocalizedDescriptionKey: "Could not validate the token",
WebAuthError.infoKey: self
]
default:
return [
NSLocalizedDescriptionKey: "Failed to perform webAuth",
WebAuthError.infoKey: self
]
}
}
}
| 41.625 | 181 | 0.678679 |
6a6f381978cab8a0f3038c1e1efee33ff75a3c52 | 833 | import Foundation
public protocol DateProtocol {
var date: Date { get }
func addingTimeInterval(_: TimeInterval) -> Self
init()
init(timeIntervalSince1970: TimeInterval)
var timeIntervalSince1970: TimeInterval { get }
}
extension Date: DateProtocol {
public var date: Date {
return self
}
}
internal struct MockDate: DateProtocol {
private let time: TimeInterval
internal init() {
self.time = 1475361315
}
internal init(timeIntervalSince1970 time: TimeInterval) {
self.time = time
}
internal var timeIntervalSince1970: TimeInterval {
return self.time
}
internal var date: Date {
return Date(timeIntervalSince1970: self.time)
}
internal func addingTimeInterval(_ interval: TimeInterval) -> MockDate {
return MockDate(timeIntervalSince1970: self.time + interval)
}
}
| 20.825 | 74 | 0.72509 |
90c333fa430b22ea594e8df4d5c9a3b5e01f42a8 | 1,504 | //
// AuthzPresenter.swift
// Cidaas
//
// Created by Ganesh on 17/05/20.
//
import Foundation
public class AuthzPresenter {
public static var shared: AuthzPresenter = AuthzPresenter()
public init() {}
// Get Request Id
public func getRequestId(response: String?, errorResponse: WebAuthError?, callback: @escaping (Result<RequestIdResponseEntity>) -> Void) {
if errorResponse != nil {
logw(errorResponse!.errorMessage, cname: "cidaas-sdk-verification-error-log")
callback(Result.failure(error: errorResponse!))
}
else {
let decoder = JSONDecoder()
do {
let data = response!.data(using: .utf8)!
// decode the json data to object
let resp = try decoder.decode(RequestIdResponseEntity.self, from: data)
logw(response ?? "Empty response string", cname: "cidaas-sdk-verification-success-log")
// return success
callback(Result.success(result: resp))
}
catch(let error) {
// return failure
logw("\(String(describing: error)) JSON parsing issue, Response: \(String(describing: response))", cname: "cidaas-sdk-verification-error-log")
callback(Result.failure(error: WebAuthError.shared.serviceFailureException(errorCode: 400, errorMessage: error.localizedDescription, statusCode: 400)))
}
}
}
}
| 36.682927 | 167 | 0.599069 |
50cb659a404fde41902b9548e182896de9bd1940 | 1,841 | //
// ProductDetailViewController.swift
// Project03
//
// Created by Lam Nguyen on 5/24/21.
//
import UIKit
class ProductDetailViewController: UIViewController {
@IBOutlet weak var productName: UILabel!
@IBOutlet weak var rating: UILabel!
@IBOutlet weak var desc: UILabel!
@IBOutlet weak var img: UIImageView!
@IBOutlet weak var numOfItems: UILabel!
@IBOutlet weak var priceLabel: UITextField!
var prodViewModel : ProductViewModel?
var cartViewModel : ShoppingCartViewModel?
override func viewDidLoad() {
super.viewDidLoad()
if prodViewModel != nil{
desc.text = prodViewModel!.description
productName.text = prodViewModel!.name
img.image = UIImage(named: prodViewModel!.image)
priceLabel.text = prodViewModel!.price
}
}
@IBAction func subItem(_ sender: Any) {
numOfItems.text = cartViewModel?.preSubItem()
}
@IBAction func addItem(_ sender: Any) {
numOfItems.text = cartViewModel?.preAddItem()
}
@IBAction func addToCart(_ sender: Any) {
cartViewModel?.addItemsToCart(product: prodViewModel!.getObj())
NotificationCenter.default.post(name: .shoppingCartDidUpdate, object: nil)
}
@IBAction func getUserDashboard(_ sender: UIButton) {
let sb = UIStoryboard(name:"UserDashboard", bundle:nil)
let show = sb.instantiateViewController(withIdentifier: "userDash") as! UserDashboardViewController
self.present(show,animated: true, completion: nil)
}
@IBAction func showStoreMenu(_ sender: UIButton) {
let sb = UIStoryboard(name: "StoreMenu", bundle:nil)
let show = sb.instantiateViewController(withIdentifier: "storeMenu")
self.present(show, animated: true, completion: nil)
}
}
| 30.683333 | 107 | 0.670831 |
113a2cbcd46aa1489f81663f96bc940b14bd66e6 | 4,690 | import UIKit
import Photos
class GridView: UIView {
// MARK: - Initialization
lazy var topView: UIView = self.makeTopView()
lazy var bottomView: UIView = self.makeBottomView()
lazy var bottomBlurView: UIVisualEffectView = self.makeBottomBlurView()
lazy var arrowButton: ArrowButton = self.makeArrowButton()
lazy var collectionView: UICollectionView = self.makeCollectionView()
lazy var closeButton: UIButton = self.makeCloseButton()
lazy var doneButton: UIButton = self.makeDoneButton()
lazy var emptyView: UIView = self.makeEmptyView()
lazy var loadingIndicator: UIActivityIndicatorView = self.makeLoadingIndicator()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setup()
loadingIndicator.startAnimating()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
Config.Grid.Dimension.columnCount = max(4, round( self.frame.size.width / 100.0))
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.layoutIfNeeded()
}
// MARK: - Setup
private func setup() {
[collectionView, bottomView, topView, emptyView, loadingIndicator].forEach {
addSubview($0)
}
[closeButton, arrowButton].forEach {
topView.addSubview($0)
}
[bottomBlurView, doneButton].forEach {
bottomView.addSubview($0)
}
Constraint.on(
topView.leftAnchor.constraint(equalTo: topView.superview!.leftAnchor),
topView.rightAnchor.constraint(equalTo: topView.superview!.rightAnchor),
topView.heightAnchor.constraint(equalToConstant: 40),
loadingIndicator.centerXAnchor.constraint(equalTo: loadingIndicator.superview!.centerXAnchor),
loadingIndicator.centerYAnchor.constraint(equalTo: loadingIndicator.superview!.centerYAnchor)
)
if #available(iOS 11, *) {
Constraint.on(
topView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor)
)
} else {
Constraint.on(
topView.topAnchor.constraint(equalTo: topView.superview!.topAnchor)
)
}
bottomView.g_pinDownward()
bottomView.g_pin(height: 80)
emptyView.g_pinEdges(view: collectionView)
collectionView.g_pinDownward()
collectionView.g_pin(on: .top, view: topView, on: .bottom, constant: 1)
bottomBlurView.g_pinEdges()
closeButton.g_pin(on: .top)
closeButton.g_pin(on: .left)
closeButton.g_pin(size: CGSize(width: 40, height: 40))
arrowButton.g_pinCenter()
arrowButton.g_pin(height: 40)
doneButton.g_pin(on: .centerY)
doneButton.g_pin(on: .right, constant: -38)
}
// MARK: - Controls
private func makeTopView() -> UIView {
let view = UIView()
view.backgroundColor = UIColor.white
return view
}
private func makeBottomView() -> UIView {
let view = UIView()
return view
}
private func makeBottomBlurView() -> UIVisualEffectView {
let view = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
return view
}
private func makeArrowButton() -> ArrowButton {
let button = ArrowButton()
button.layoutSubviews()
return button
}
private func makeGridView() -> GridView {
let view = GridView()
return view
}
private func makeCloseButton() -> UIButton {
let button = UIButton(type: .custom)
button.setImage(GalleryBundle.image("gallery_close")?.withRenderingMode(.alwaysTemplate), for: UIControl.State())
button.tintColor = Config.Grid.CloseButton.tintColor
return button
}
private func makeDoneButton() -> UIButton {
let button = UIButton(type: .system)
button.setTitleColor(UIColor.white, for: UIControl.State())
button.setTitleColor(UIColor.lightGray, for: .disabled)
button.titleLabel?.font = Config.Font.Text.regular.withSize(16)
button.setTitle("Gallery.Done".g_localize(fallback: "Done"), for: UIControl.State())
return button
}
private func makeCollectionView() -> UICollectionView {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 2
layout.minimumLineSpacing = 2
let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.backgroundColor = UIColor.white
return view
}
private func makeEmptyView() -> EmptyView {
let view = EmptyView()
view.isHidden = true
return view
}
private func makeLoadingIndicator() -> UIActivityIndicatorView {
let view = UIActivityIndicatorView(style: .whiteLarge)
view.color = .gray
view.hidesWhenStopped = true
return view
}
}
| 26.954023 | 117 | 0.703625 |
d9c638e5e4ea53e87661878829d1e8ceaa1a9cd5 | 3,035 | //
// HealthKitManager.swift
// DemoHealthKit
//
// Created by Tam Nguyen M. on 4/1/19.
// Copyright © 2019 Tam Nguyen M. All rights reserved.
//
import Foundation
import HealthKit
import SwiftDate
typealias HKCompletion = (_ success: Bool, _ error: Error?) -> Void
typealias HKStepsCompletion = (_ atDate: DateInRegion, _ steps: Int, _ error: Error?) -> Void
typealias HKStepResult = [String: Int]
typealias HKStepsArrayCompletion = (_ steps: HKStepResult, _ error: Error?) -> Void
class HealthKitManager {
static let manager = HealthKitManager()
fileprivate let store = HKHealthStore()
func authen(_ completion: @escaping HKCompletion) {
guard HKHealthStore.isHealthDataAvailable() else { return }
guard let type = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) else { return }
store.requestAuthorization(toShare: nil, read: [type], completion: completion)
}
var authenStatus: HKAuthorizationStatus {
guard let type = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) else { return HKAuthorizationStatus.sharingDenied }
return store.authorizationStatus(for: type)
}
func steps(inDate date: DateInRegion, completion: @escaping HKStepsCompletion) {
let fromDate = date.startOf(component: .day)
let toDate = fromDate.endOf(component: .day)
steps(fromDate, toDate: toDate, atDate: date, completion: completion)
}
func steps(_ fromDate: DateInRegion, toDate: DateInRegion, atDate: DateInRegion, completion: @escaping HKStepsCompletion) {
guard HKHealthStore.isHealthDataAvailable() else {
completion(atDate, 0, nil)
return
}
guard let type = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) else { return }
let anchorDate = fromDate.startOf(component: .day).absoluteDate
let interval = DateComponents(year: 0, month: 0, day: 1)
let endDate = toDate.endOf(component: .day).absoluteDate
let startDate = fromDate.startOf(component: .day).absoluteDate
let pre = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
let query = HKStatisticsCollectionQuery(quantityType: type, quantitySamplePredicate: pre, options: .cumulativeSum, anchorDate: anchorDate, intervalComponents: interval)
query.initialResultsHandler = { query, result, error in
guard error == nil else {
completion(atDate, 0, error)
return
}
result?.enumerateStatistics(from: startDate, to: endDate, with: { (statistics, stop) in
guard let quantity = statistics.sumQuantity() else {
completion(atDate, 0, nil)
return
}
let value = quantity.doubleValue(for: HKUnit.count())
completion(atDate, Int(round(value)), nil)
})
}
store.execute(query)
}
}
| 42.152778 | 176 | 0.675124 |
1108428ac1d08e299f2a9678def525d7eb1237c6 | 2,312 | //
// AppDelegate.swift
// Favoritos
//
// Created by [email protected] on 01/21/2021.
// Copyright (c) 2021 [email protected]. All rights reserved.
//
import UIKit
import Favoritos
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
let mainViewController = FavoritosViewController()
let navigationController = UINavigationController(rootViewController: mainViewController)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 42.036364 | 285 | 0.743945 |
11b7338a9e7f114842d2a6a02e81d7ecee2cac23 | 291 | // RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum a<s func g{var f=a
struct c<T
where g:C{class a{func b{
var f=b
| 29.1 | 87 | 0.735395 |
14ead1eb9f9edee55f769300873096a886340814 | 1,995 | /**
* Publish
* Copyright (c) John Sundell 2019
* MIT license, see LICENSE file for details
*/
import XCTest
import Publish
import Plot
import Ink
final class PluginTests: PublishTestCase {
func testAddingContentUsingPlugin() throws {
let site = try publishWebsite(using: [
.installPlugin(Plugin(name: "Plugin") { context in
context.addItem(.stub())
})
])
XCTAssertEqual(site.sections[.one].items.count, 1)
}
func testAddingInkModifierUsingPlugin() throws {
let site = try publishWebsite(using: [
.installPlugin(Plugin(name: "Plugin") { context in
context.markdownParser.addModifier(Modifier(
target: .paragraphs,
closure: { html, _ in
"<div>\(html)</div>"
}
))
}),
.addMarkdownFiles()
], content: [
"one/a.md": "Hello"
])
let items = site.sections[.one].items
XCTAssertEqual(items.count, 1)
XCTAssertEqual(items.first?.path, "one/a")
XCTAssertEqual(items.first?.body.html, "<div><p>Hello</p></div>")
}
func testAddingPluginToDefaultPipeline() throws {
let htmlFactory = HTMLFactoryMock<WebsiteStub.WithoutItemMetadata>()
htmlFactory.makeIndexHTML = { content, _ in
HTML(.body(content.body.node))
}
try publishWebsite(
using: Theme(htmlFactory: htmlFactory),
content: ["index.md": "Hello, World!"],
plugins: [Plugin(name: "Plugin") { context in
context.markdownParser.addModifier(Modifier(
target: .paragraphs,
closure: { html, _ in
"<section>\(html)</section>"
}
))
}],
expectedHTML: ["index.html": "<section><p>Hello, World!</p></section>"]
)
}
}
| 30.692308 | 83 | 0.53183 |
d6083806649f6ba822403ab02ef38eed49acdcf3 | 2,317 | // Copyright 2018-2021 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// StandardSmokeServerStaticContextInitializer.swift
// SmokeOperationsHTTP1Server
//
import Foundation
import SmokeOperationsHTTP1
import SmokeHTTP1
import SmokeOperations
/**
A protocol that is derived from `SmokeServerStaticContextInitializerV2` that uses the `StandardSmokeHTTP1HandlerSelector`
type as the `SelectorType` and `JSONPayloadHTTP1OperationDelegate` as the `DefaultOperationDelegateType`.
This reduces the configuration required for applications that use these standard components.
*/
public protocol StandardJSONSmokeServerStaticContextInitializer: SmokeServerStaticContextInitializerV2
where SelectorType ==
StandardSmokeHTTP1HandlerSelector<ContextType, JSONPayloadHTTP1OperationDelegate<SmokeInvocationTraceContext>,
OperationIdentifer> {
associatedtype ContextType
associatedtype OperationIdentifer: OperationIdentity
typealias OperationsInitializerType = ((inout StandardSmokeHTTP1HandlerSelector<ContextType, JSONPayloadHTTP1OperationDelegate<SmokeInvocationTraceContext>, OperationIdentifer>) -> Void)
}
public extension StandardJSONSmokeServerStaticContextInitializer {
var handlerSelectorProvider: (() -> SelectorType) {
func provider() -> SelectorType {
return SelectorType(defaultOperationDelegate: self.defaultOperationDelegate,
serverName: self.serverName,
reportingConfiguration: self.reportingConfiguration)
}
return provider
}
var defaultOperationDelegate: SelectorType.DefaultOperationDelegateType {
return JSONPayloadHTTP1OperationDelegate()
}
}
| 42.907407 | 190 | 0.746655 |
50e399b5e50b291e29604d655658ebad3ec27d9c | 6,992 | // Made With Flow.
//
// DO NOT MODIFY, your changes will be lost when this file is regenerated.
//
import UIKit
@IBDesignable
public class ArtboardView: UIView {
public struct Defaults {
public static let size = CGSize(width: 320, height: 68)
public static let backgroundColor = UIColor(red: 0, green: 0, blue: 1, alpha: 1)
}
public var wGroup: UIView!
public var o: ShapeView!
public var flGroup: UIView!
public var l: ShapeView!
public var f: ShapeView!
public var w: ShapeView!
public override var intrinsicContentSize: CGSize {
return Defaults.size
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
private func setup() {
backgroundColor = Defaults.backgroundColor
createViews()
addSubviews()
//scale(to: frame.size)
}
/// Scales `self` and its subviews to `size`.
///
/// - Parameter size: The size `self` is scaled to.
///
/// UIKit specifies: "In iOS 8.0 and later, the transform property does not affect Auto Layout. Auto layout
/// calculates a view's alignment rectangle based on its untransformed frame."
///
/// see: https://developer.apple.com/documentation/uikit/uiview/1622459-transform
///
/// If there are any constraints in IB affecting the frame of `self`, this method will have consequences on
/// layout / rendering. To properly scale an animation, you will have to position the view manually.
public func scale(to size: CGSize) {
let x = size.width / Defaults.size.width
let y = size.height / Defaults.size.height
transform = CGAffineTransform(scaleX: x, y: y)
}
private func createViews() {
CATransaction.suppressAnimations {
createWGroup()
createO()
createFlGroup()
createL()
createF()
createW()
}
}
private func createWGroup() {
wGroup = UIView(frame: CGRect(x: 269, y: 34, width: 94, height: 60))
wGroup.backgroundColor = UIColor.clear
wGroup.layer.shadowOffset = CGSize(width: 0, height: 0)
wGroup.layer.shadowColor = UIColor.clear.cgColor
wGroup.layer.shadowOpacity = 1
wGroup.layer.position = CGPoint(x: 269, y: 34)
wGroup.layer.bounds = CGRect(x: 0, y: 0, width: 94, height: 60)
wGroup.layer.masksToBounds = true
}
private func createO() {
o = ShapeView(frame: CGRect(x: 175, y: 34, width: 64, height: 64))
o.backgroundColor = UIColor.clear
o.layer.shadowOffset = CGSize(width: 0, height: 0)
o.layer.shadowColor = UIColor.clear.cgColor
o.layer.shadowOpacity = 1
o.layer.position = CGPoint(x: 175, y: 34)
o.layer.bounds = CGRect(x: 0, y: 0, width: 64, height: 64)
o.layer.masksToBounds = false
o.shapeLayer.fillRule = CAShapeLayerFillRule.evenOdd
o.shapeLayer.fillColor = UIColor.white.cgColor
o.shapeLayer.lineDashPattern = []
o.shapeLayer.lineDashPhase = 0
o.shapeLayer.lineWidth = 0
o.shapeLayer.path = CGPathCreateWithSVGString("M32,64c-17.707,0,-32,-14.293,-32,-32 0,-17.707,14.293,-32,32,-32 17.707,0,32,14.293,32,32 0,17.707,-14.293,32,-32,32")!
}
private func createFlGroup() {
flGroup = UIView(frame: CGRect(x: 70, y: 34, width: 132, height: 60))
flGroup.backgroundColor = UIColor.clear
flGroup.layer.shadowOffset = CGSize(width: 0, height: 0)
flGroup.layer.shadowColor = UIColor.clear.cgColor
flGroup.layer.shadowOpacity = 1
flGroup.layer.position = CGPoint(x: 70, y: 34)
flGroup.layer.bounds = CGRect(x: 0, y: 0, width: 132, height: 60)
flGroup.layer.masksToBounds = true
}
private func createL() {
l = ShapeView(frame: CGRect(x: 102, y: 30, width: 60, height: 60))
l.backgroundColor = UIColor.clear
l.layer.shadowOffset = CGSize(width: 0, height: 0)
l.layer.shadowColor = UIColor.clear.cgColor
l.layer.shadowOpacity = 1
l.layer.position = CGPoint(x: 102, y: 30)
l.layer.bounds = CGRect(x: 0, y: 0, width: 60, height: 60)
l.layer.masksToBounds = false
l.shapeLayer.fillRule = CAShapeLayerFillRule.evenOdd
l.shapeLayer.fillColor = UIColor.white.cgColor
l.shapeLayer.lineDashPattern = []
l.shapeLayer.lineDashPhase = 0
l.shapeLayer.lineWidth = 0
l.shapeLayer.path = CGPathCreateWithSVGString("M56.682,60s0,0,0,0c0,0,-53.36,0,-53.36,0 -1.822,0,-3.322,-1.5,-3.322,-3.322l0,-53.36c0,-3,3.536,-4.393,5.679,-2.357l53.36,53.36c2.036,2.143,0.643,5.679,-2.357,5.679")!
}
private func createF() {
f = ShapeView(frame: CGRect(x: 30, y: 30, width: 60, height: 60))
f.backgroundColor = UIColor.clear
f.layer.shadowOffset = CGSize(width: 0, height: 0)
f.layer.shadowColor = UIColor.clear.cgColor
f.layer.shadowOpacity = 1
f.layer.position = CGPoint(x: 30, y: 30)
f.layer.bounds = CGRect(x: 0, y: 0, width: 60, height: 60)
f.layer.masksToBounds = false
f.shapeLayer.fillRule = CAShapeLayerFillRule.evenOdd
f.shapeLayer.fillColor = UIColor.white.cgColor
f.shapeLayer.lineDashPattern = []
f.shapeLayer.lineDashPhase = 0
f.shapeLayer.lineWidth = 0
f.shapeLayer.path = CGPathCreateWithSVGString("M0,56.682s0,0,0,0c0,0,0,-53.36,0,-53.36 0,-1.822,1.5,-3.322,3.322,-3.322l53.36,0c3,0,4.393,3.536,2.357,5.679l-53.36,53.36c-2.143,2.036,-5.679,0.643,-5.679,-2.357")!
}
private func createW() {
w = ShapeView(frame: CGRect(x: 47, y: 30, width: 94, height: 60))
w.backgroundColor = UIColor.clear
w.layer.shadowOffset = CGSize(width: 0, height: 0)
w.layer.shadowColor = UIColor.clear.cgColor
w.layer.shadowOpacity = 1
w.layer.position = CGPoint(x: 47, y: 30)
w.layer.bounds = CGRect(x: 0, y: 0, width: 94, height: 60)
w.layer.masksToBounds = false
w.shapeLayer.fillRule = CAShapeLayerFillRule.evenOdd
w.shapeLayer.fillColor = UIColor.white.cgColor
w.shapeLayer.lineDashPattern = []
w.shapeLayer.lineDashPhase = 0
w.shapeLayer.lineWidth = 0
w.shapeLayer.path = CGPathCreateWithSVGString("M56.12,0s0,0,0,0c0,0,-18.95,0,-18.95,0s0,0,0,0c0,0,-33.89,0,-33.89,0 -1.8,0,-3.285,1.5,-3.29,3.32l0,53.36c0.005,3.002,3.506,4.395,5.63,2.36 0,0,28.22,-28.503,28.22,-28.503s0,0,0,0c0,0,0,26.143,0,26.143 0,3.002,3.545,4.395,5.69,2.36l53.51,-53.36c2.038,-2.144,0.641,-5.68,-2.37,-5.68 0,0,-34.55,0,-34.55,0zM56.12,0")!
}
private func addSubviews() {
wGroup.addSubview(w)
flGroup.addSubview(l)
flGroup.addSubview(f)
addSubview(wGroup)
addSubview(o)
addSubview(flGroup)
}
}
| 40.183908 | 370 | 0.626144 |
3a51dbf8d5f1dfa0846bb3d4dfa0f06789a95d5f | 157 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(DraculaTests.allTests),
]
}
#endif
| 15.7 | 45 | 0.66879 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.