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
e45fb1bcc93ed6f92391efddc21b18c76c955d2d
1,728
// // PetitionsNetworkRequestor.swift // SayTheirNames // // Copyright (c) 2020 Say Their Names Team (https://github.com/Say-Their-Name) // // 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 import Alamofire // MARK: - PetitionEnvironment enum PetitionEnvironment { static let urlString: String = { return "\(Environment.serverURLString)/api/petitions" }() } // MARK: - NetworkRequestor (Petition) extension NetworkRequestor { // MARK: - Public methods public func fetchPetitions(completion: @escaping (Result<PetitionsResponsePage, AFError>) -> Swift.Void) { self.fetchDecodable(PetitionEnvironment.urlString, completion: completion) } }
42.146341
110
0.747685
bb6878f92af6f67be83d9a706124f6e19c61c5c9
13,368
// Copyright (c) 2021 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import XCTest import BitByteData class LsbBitWriterTests: XCTestCase { func testWriteBit() { let writer = LsbBitWriter() writer.write(bit: 0) writer.write(bit: 1) writer.write(bit: 0) writer.write(bit: 1) writer.write(bit: 1) writer.align() XCTAssertEqual(writer.data, Data([26])) } func testWriteBitsArray() { let writer = LsbBitWriter() writer.write(bits: [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1]) writer.align() XCTAssertEqual(writer.data, Data([83, 6])) } func testWriteNumber() { let writer = LsbBitWriter() writer.write(number: 127, bitsCount: 8) XCTAssertEqual(writer.data, Data([127])) writer.write(number: 6, bitsCount: 4) XCTAssertEqual(writer.data, Data([127])) writer.write(number: 56, bitsCount: 7) XCTAssertEqual(writer.data, Data([127, 134])) writer.align() XCTAssertEqual(writer.data, Data([127, 134, 3])) writer.write(number: -123, bitsCount: 8) XCTAssertEqual(writer.data, Data([127, 134, 3, 133])) writer.write(number: -56, bitsCount: 12) XCTAssertEqual(writer.data, Data([127, 134, 3, 133, 200])) writer.align() XCTAssertEqual(writer.data, Data([127, 134, 3, 133, 200, 15])) writer.write(number: Int.max, bitsCount: Int.bitWidth) writer.write(number: Int.min, bitsCount: Int.bitWidth) if Int.bitWidth == 64 { XCTAssertEqual(writer.data, Data([127, 134, 3, 133, 200, 15, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0, 0, 0, 0, 0, 0, 0, 0x80])) } else if Int.bitWidth == 32 { XCTAssertEqual(writer.data, Data([127, 134, 3, 133, 200, 15, 0xFF, 0xFF, 0xFF, 0x7F, 0, 0, 0, 0x80])) } } func testWriteSignedNumber_SM() { let repr = SignedNumberRepresentation.signMagnitude let writer = LsbBitWriter() writer.write(signedNumber: 127, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([127])) writer.write(signedNumber: 6, bitsCount: 4, representation: repr) XCTAssertEqual(writer.data, Data([127])) writer.write(signedNumber: 56, bitsCount: 7, representation: repr) XCTAssertEqual(writer.data, Data([127, 134])) writer.align() XCTAssertEqual(writer.data, Data([127, 134, 3])) writer.write(signedNumber: -123, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([127, 134, 3, 251])) writer.write(signedNumber: -56, bitsCount: 12, representation: repr) XCTAssertEqual(writer.data, Data([127, 134, 3, 251, 56])) writer.align() XCTAssertEqual(writer.data, Data([127, 134, 3, 251, 56, 8])) writer.write(signedNumber: Int.max, bitsCount: Int.bitWidth, representation: repr) writer.write(signedNumber: Int.min + 1, bitsCount: Int.bitWidth, representation: repr) if Int.bitWidth == 64 { XCTAssertEqual(writer.data, Data([127, 134, 3, 251, 56, 8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])) } else if Int.bitWidth == 32 { XCTAssertEqual(writer.data, Data([127, 134, 3, 251, 56, 8, 0xFF, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF])) } } func testWriteSignedNumber_1C() { let repr = SignedNumberRepresentation.oneComplementNegatives let writer = LsbBitWriter() writer.write(signedNumber: 127, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([127])) writer.write(signedNumber: 6, bitsCount: 4, representation: repr) XCTAssertEqual(writer.data, Data([127])) writer.write(signedNumber: 56, bitsCount: 7, representation: repr) XCTAssertEqual(writer.data, Data([127, 134])) writer.align() XCTAssertEqual(writer.data, Data([127, 134, 3])) writer.write(signedNumber: -123, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([127, 134, 3, 132])) writer.write(signedNumber: -56, bitsCount: 12, representation: repr) XCTAssertEqual(writer.data, Data([127, 134, 3, 132, 199])) writer.align() XCTAssertEqual(writer.data, Data([127, 134, 3, 132, 199, 15])) writer.write(signedNumber: Int.max, bitsCount: Int.bitWidth, representation: repr) writer.write(signedNumber: Int.min + 1, bitsCount: Int.bitWidth, representation: repr) if Int.bitWidth == 64 { XCTAssertEqual(writer.data, Data([127, 134, 3, 132, 199, 15, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0, 0, 0, 0, 0, 0, 0, 0x80])) } else if Int.bitWidth == 32 { XCTAssertEqual(writer.data, Data([127, 134, 3, 132, 199, 15, 0xFF, 0xFF, 0xFF, 0x7F, 0, 0, 0, 0x80])) } } func testWriteSignedNumber_2C() { let repr = SignedNumberRepresentation.twoComplementNegatives let writer = LsbBitWriter() writer.write(signedNumber: 127, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([127])) writer.write(signedNumber: 6, bitsCount: 4, representation: repr) XCTAssertEqual(writer.data, Data([127])) writer.write(signedNumber: 56, bitsCount: 7, representation: repr) XCTAssertEqual(writer.data, Data([127, 134])) writer.align() XCTAssertEqual(writer.data, Data([127, 134, 3])) writer.write(signedNumber: -123, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([127, 134, 3, 133])) writer.write(signedNumber: -56, bitsCount: 12, representation: repr) XCTAssertEqual(writer.data, Data([127, 134, 3, 133, 200])) writer.align() XCTAssertEqual(writer.data, Data([127, 134, 3, 133, 200, 15])) writer.write(signedNumber: Int.max, bitsCount: Int.bitWidth, representation: repr) writer.write(signedNumber: Int.min, bitsCount: Int.bitWidth, representation: repr) if Int.bitWidth == 64 { XCTAssertEqual(writer.data, Data([127, 134, 3, 133, 200, 15, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0, 0, 0, 0, 0, 0, 0, 0x80])) } else if Int.bitWidth == 32 { XCTAssertEqual(writer.data, Data([127, 134, 3, 133, 200, 15, 0xFF, 0xFF, 0xFF, 0x7F, 0, 0, 0, 0x80])) } } func testWriteSignedNumber_Biased_E127() { let repr = SignedNumberRepresentation.biased(bias: 127) let writer = LsbBitWriter() writer.write(signedNumber: 126, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([253])) writer.write(signedNumber: 6, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([253, 133])) writer.write(signedNumber: 56, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([253, 133, 183])) writer.write(signedNumber: 0, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([253, 133, 183, 127])) writer.align() XCTAssertEqual(writer.data, Data([253, 133, 183, 127])) writer.write(signedNumber: -123, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([253, 133, 183, 127, 4])) writer.write(signedNumber: -56, bitsCount: 12, representation: repr) XCTAssertEqual(writer.data, Data([253, 133, 183, 127, 4, 71])) writer.align() XCTAssertEqual(writer.data, Data([253, 133, 183, 127, 4, 71, 0])) writer.write(signedNumber: Int.max - 127, bitsCount: Int.bitWidth, representation: repr) if Int.bitWidth == 64 { XCTAssertEqual(writer.data, Data([253, 133, 183, 127, 4, 71, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F])) } else if Int.bitWidth == 32 { XCTAssertEqual(writer.data, Data([253, 133, 183, 127, 4, 71, 0, 0xFF, 0xFF, 0xFF, 0x7F])) } } func testWriteSignedNumber_Biased_E3() { let repr = SignedNumberRepresentation.biased(bias: 3) let writer = LsbBitWriter() writer.write(signedNumber: -3, bitsCount: 4, representation: repr) XCTAssertFalse(writer.isAligned) writer.write(signedNumber: 12, bitsCount: 4, representation: repr) XCTAssertTrue(writer.isAligned) XCTAssertEqual(writer.data, Data([240])) writer.write(signedNumber: 126, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([240, 129])) writer.write(signedNumber: 6, bitsCount: 12, representation: repr) XCTAssertFalse(writer.isAligned) XCTAssertEqual(writer.data, Data([240, 129, 9])) writer.write(signedNumber: 56, bitsCount: 6, representation: repr) XCTAssertFalse(writer.isAligned) XCTAssertEqual(writer.data, Data([240, 129, 9, 176])) writer.align() XCTAssertTrue(writer.isAligned) XCTAssertEqual(writer.data, Data([240, 129, 9, 176, 3])) writer.write(signedNumber: 0, bitsCount: 8, representation: repr) XCTAssertEqual(writer.data, Data([240, 129, 9, 176, 3, 3])) writer.write(signedNumber: Int.max - 3, bitsCount: Int.bitWidth, representation: repr) if Int.bitWidth == 64 { XCTAssertEqual(writer.data, Data([240, 129, 9, 176, 3, 3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F])) } else if Int.bitWidth == 32 { XCTAssertEqual(writer.data, Data([240, 129, 9, 176, 3, 3, 0xFF, 0xFF, 0xFF, 0x7F])) } } func testWriteSignedNumber_Biased_E1023() { let repr = SignedNumberRepresentation.biased(bias: 1023) let writer = LsbBitWriter() writer.write(signedNumber: -1023, bitsCount: 11, representation: repr) XCTAssertFalse(writer.isAligned) XCTAssertEqual(writer.data, Data([0])) writer.align() XCTAssertTrue(writer.isAligned) XCTAssertEqual(writer.data, Data([0, 0])) writer.write(signedNumber: 0, bitsCount: 11, representation: repr) XCTAssertFalse(writer.isAligned) XCTAssertEqual(writer.data, Data([0, 0, 255])) writer.align() XCTAssertTrue(writer.isAligned) XCTAssertEqual(writer.data, Data([0, 0, 255, 3])) writer.write(signedNumber: Int.max - 1023, bitsCount: Int.bitWidth, representation: repr) if Int.bitWidth == 64 { XCTAssertEqual(writer.data, Data([0, 0, 255, 3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F])) } else if Int.bitWidth == 32 { XCTAssertEqual(writer.data, Data([0, 0, 255, 3, 0xFF, 0xFF, 0xFF, 0x7F])) } } func testWriteSignedNumber_RN2() { let repr = SignedNumberRepresentation.radixNegativeTwo let writer = LsbBitWriter() writer.write(signedNumber: 6, bitsCount: 5, representation: repr) writer.write(signedNumber: -2, bitsCount: 3, representation: repr) XCTAssertEqual(writer.data, Data([90])) writer.write(signedNumber: -1023, bitsCount: 12, representation: repr) XCTAssertFalse(writer.isAligned) XCTAssertEqual(writer.data, Data([90, 1])) writer.write(signedNumber: 0, bitsCount: 4, representation: repr) XCTAssertTrue(writer.isAligned) XCTAssertEqual(writer.data, Data([90, 1, 12])) } func testWriteUnsignedNumber() { let writer = LsbBitWriter() writer.write(unsignedNumber: UInt.max, bitsCount: UInt.bitWidth) if UInt.bitWidth == 64 { XCTAssertEqual(writer.data, Data([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])) } else if UInt.bitWidth == 32 { XCTAssertEqual(writer.data, Data([0xFF, 0xFF, 0xFF, 0xFF])) } } func testAppendByte() { let writer = LsbBitWriter() writer.append(byte: 0xCA) XCTAssertEqual(writer.data, Data([0xCA])) writer.append(byte: 0xFF) XCTAssertEqual(writer.data, Data([0xCA, 0xFF])) writer.append(byte: 0) XCTAssertEqual(writer.data, Data([0xCA, 0xFF, 0])) } func testAlign() { let writer = LsbBitWriter() writer.align() XCTAssertEqual(writer.data, Data()) XCTAssertTrue(writer.isAligned) } func testIsAligned() { let writer = LsbBitWriter() writer.write(bits: [0, 1, 0]) XCTAssertFalse(writer.isAligned) writer.write(bits: [0, 1, 0, 1, 0]) XCTAssertTrue(writer.isAligned) writer.write(bit: 0) XCTAssertFalse(writer.isAligned) writer.align() XCTAssertTrue(writer.isAligned) } func testNamingConsistency() { let writer = LsbBitWriter() writer.write(signedNumber: 14582, bitsCount: 15) writer.align() XCTAssertEqual(writer.data, Data([0xF6, 0x38])) let reader = LsbBitReader(data: writer.data) XCTAssertEqual(reader.signedInt(fromBits: 15), 14582) } }
47.404255
125
0.613256
7af73cfc89522a7855c01066e4573029ed0ec6c5
11,596
import Foundation import SourceKittenFramework public struct UnusedDeclarationRule: AutomaticTestableRule, ConfigurationProviderRule, AnalyzerRule, CollectingRule { public struct FileUSRs { var referenced: Set<String> var declared: [(usr: String, nameOffset: Int)] var testCaseUSRs: Set<String> } public typealias FileInfo = FileUSRs public var configuration = UnusedDeclarationConfiguration(severity: .error, includePublicAndOpen: false) public init() {} public static let description = RuleDescription( identifier: "unused_declaration", name: "Unused Declaration", description: "Declarations should be referenced at least once within all files linted.", kind: .lint, nonTriggeringExamples: [ """ let kConstant = 0 _ = kConstant """, """ enum Change<T> { case insert(T) case delete(T) } extension Sequence { func deletes<T>() -> [T] where Element == Change<T> { return compactMap { operation in if case .delete(let value) = operation { return value } else { return nil } } } } let changes = [Change.insert(0), .delete(0)] changes.deletes() """, """ struct Item {} struct ResponseModel: Codable { let items: [Item] enum CodingKeys: String, CodingKey { case items = "ResponseItems" } } _ = ResponseModel(items: [Item()]).items """, """ class ResponseModel { @objc func foo() { } } _ = ResponseModel() """ ], triggeringExamples: [ """ let ↓kConstant = 0 """, """ struct Item {} struct ↓ResponseModel: Codable { let ↓items: [Item] enum ↓CodingKeys: String { case items = "ResponseItems" } } """, """ class ↓ResponseModel { func ↓foo() { } } """ ], requiresFileOnDisk: true ) public func collectInfo(for file: SwiftLintFile, compilerArguments: [String]) -> UnusedDeclarationRule.FileUSRs { guard !compilerArguments.isEmpty else { queuedPrintError(""" Attempted to lint file at path '\(file.path ?? "...")' with the \ \(type(of: self).description.identifier) rule without any compiler arguments. """) return FileUSRs(referenced: [], declared: [], testCaseUSRs: []) } let allCursorInfo = file.allCursorInfo(compilerArguments: compilerArguments) return FileUSRs(referenced: Set(SwiftLintFile.referencedUSRs(allCursorInfo: allCursorInfo)), declared: SwiftLintFile.declaredUSRs(allCursorInfo: allCursorInfo, includePublicAndOpen: configuration.includePublicAndOpen), testCaseUSRs: SwiftLintFile.testCaseUSRs(allCursorInfo: allCursorInfo)) } public func validate(file: SwiftLintFile, collectedInfo: [SwiftLintFile: UnusedDeclarationRule.FileUSRs], compilerArguments: [String]) -> [StyleViolation] { let allReferencedUSRs = collectedInfo.values.reduce(into: Set()) { $0.formUnion($1.referenced) } let allTestCaseUSRs = collectedInfo.values.reduce(into: Set()) { $0.formUnion($1.testCaseUSRs) } return violationOffsets(in: file, compilerArguments: compilerArguments, declaredUSRs: collectedInfo[file]?.declared ?? [], allReferencedUSRs: allReferencedUSRs, allTestCaseUSRs: allTestCaseUSRs) .map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: $0)) } } private func violationOffsets(in file: SwiftLintFile, compilerArguments: [String], declaredUSRs: [(usr: String, nameOffset: Int)], allReferencedUSRs: Set<String>, allTestCaseUSRs: Set<String>) -> [Int] { // Unused declarations are: // 1. all declarations // 2. minus all references // 3. minus all XCTestCase subclasses // 4. minus all XCTest test functions let unusedDeclarations = declaredUSRs .filter { !allReferencedUSRs.contains($0.usr) } .filter { !allTestCaseUSRs.contains($0.usr) } .filter { declaredUSR in return !allTestCaseUSRs.contains(where: { testCaseUSR in return declaredUSR.usr.hasPrefix(testCaseUSR + "(im)test") || declaredUSR.usr.hasPrefix( testCaseUSR.replacingOccurrences(of: "@M@", with: "@CM@") + "(im)test" ) }) } return unusedDeclarations.map { $0.nameOffset } } } // MARK: - File Extensions private extension SwiftLintFile { func allCursorInfo(compilerArguments: [String]) -> [SourceKittenDictionary] { guard let path = path, let editorOpen = (try? Request.editorOpen(file: self.file).sendIfNotDisabled()) .map(SourceKittenDictionary.init) else { return [] } return syntaxMap.tokens .compactMap { token in guard let kind = token.kind, !syntaxKindsToSkip.contains(kind) else { return nil } let offset = Int64(token.offset) let request = Request.cursorInfo(file: path, offset: offset, arguments: compilerArguments) guard var cursorInfo = try? request.sendIfNotDisabled() else { return nil } if let acl = editorOpen.aclAtOffset(offset) { cursorInfo["key.accessibility"] = acl.rawValue } cursorInfo["swiftlint.offset"] = offset return cursorInfo } .map(SourceKittenDictionary.init) } static func declaredUSRs(allCursorInfo: [SourceKittenDictionary], includePublicAndOpen: Bool) -> [(usr: String, nameOffset: Int)] { return allCursorInfo.compactMap { cursorInfo in return declaredUSRAndOffset(cursorInfo: cursorInfo, includePublicAndOpen: includePublicAndOpen) } } static func referencedUSRs(allCursorInfo: [SourceKittenDictionary]) -> [String] { return allCursorInfo.compactMap(referencedUSR) } static func testCaseUSRs(allCursorInfo: [SourceKittenDictionary]) -> Set<String> { return Set(allCursorInfo.compactMap(testCaseUSR)) } private static func declaredUSRAndOffset(cursorInfo: SourceKittenDictionary, includePublicAndOpen: Bool) -> (usr: String, nameOffset: Int)? { if let offset = cursorInfo.swiftlintOffset, let usr = cursorInfo.usr, let kind = cursorInfo.declarationKind, !declarationKindsToSkip.contains(kind), let acl = cursorInfo.accessibility, includePublicAndOpen || [.internal, .private, .fileprivate].contains(acl) { // Skip declarations marked as @IBOutlet, @IBAction or @objc // since those might not be referenced in code, but only dynamically (e.g. Interface Builder) if let annotatedDecl = cursorInfo.annotatedDeclaration, ["@IBOutlet", "@IBAction", "@objc", "@IBInspectable"].contains(where: annotatedDecl.contains) { return nil } // Classes marked as @UIApplicationMain are used by the operating system as the entry point into the app. if let annotatedDecl = cursorInfo.annotatedDeclaration, annotatedDecl.contains("@UIApplicationMain") { return nil } // Skip declarations that override another. This works for both subclass overrides & // protocol extension overrides. if cursorInfo.value["key.overrides"] != nil { return nil } // Sometimes default protocol implementations don't have `key.overrides` set but they do have // `key.related_decls`. if cursorInfo.value["key.related_decls"] != nil { return nil } // Skip CodingKeys as they are used if kind == .enum, cursorInfo.name == "CodingKeys", let annotatedDecl = cursorInfo.annotatedDeclaration, annotatedDecl.contains("usr=\"s:s9CodingKeyP\">CodingKey<") { return nil } return (usr, Int(offset)) } return nil } private static func referencedUSR(cursorInfo: SourceKittenDictionary) -> String? { if let usr = cursorInfo.usr, let kind = cursorInfo.kind, kind.starts(with: "source.lang.swift.ref") { if let synthesizedLocation = usr.range(of: "::SYNTHESIZED::")?.lowerBound { return String(usr.prefix(upTo: synthesizedLocation)) } return usr } return nil } private static func testCaseUSR(cursorInfo: SourceKittenDictionary) -> String? { if let kind = cursorInfo.declarationKind, kind == .class, let annotatedDecl = cursorInfo.annotatedDeclaration, annotatedDecl.contains("<Type usr=\"c:objc(cs)XCTestCase\">XCTestCase</Type>"), let usr = cursorInfo.usr { return usr } return nil } } private extension SourceKittenDictionary { var swiftlintOffset: Int64? { return value["swiftlint.offset"] as? Int64 } var usr: String? { return value["key.usr"] as? String } var annotatedDeclaration: String? { return value["key.annotated_decl"] as? String } func aclAtOffset(_ offset: Int64) -> AccessControlLevel? { if let nameOffset = nameOffset, nameOffset == offset, let acl = accessibility { return acl } for child in substructure { if let acl = child.aclAtOffset(offset) { return acl } } return nil } } // Skip initializers, deinit, enum cases and subscripts since we can't reliably detect if they're used. private let declarationKindsToSkip: Set<SwiftDeclarationKind> = [ .functionConstructor, .functionDestructor, .enumelement, .functionSubscript ] /// Skip syntax kinds that won't respond to cursor info requests. private let syntaxKindsToSkip: Set<SyntaxKind> = [ .attributeBuiltin, .attributeID, .comment, .commentMark, .commentURL, .buildconfigID, .buildconfigKeyword, .docComment, .docCommentField, .keyword, .number, .string, .stringInterpolationAnchor ]
36.465409
119
0.560883
e9d47d418e6efcdc4fde250525de41c64af26471
578
// // RoleField.swift // Rocket.Chat // // Created by Vadym Brusko on 10/4/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation import SwiftyJSON import RealmSwift class TextField: CustomField { override class var type: String { return "text" } @objc dynamic var minLength: Int = 0 @objc dynamic var maxLength: Int = 10 override func map(_ values: JSON, realm: Realm?) { minLength = values["minLength"].intValue maxLength = values["maxLength"].intValue super.map(values, realm: realm) } }
22.230769
54
0.655709
bfcdddbfc220d8561474fd1c49cd6f168a6f9ced
5,152
// // EventDetailViewController.swift // Pretto // // Created by Josiah Gaskin on 6/14/15. // Copyright (c) 2015 Pretto. All rights reserved. // import Foundation class EventDetailViewController : ZoomableCollectionViewController, UICollectionViewDataSource, UICollectionViewDelegate { var invitation : Invitation? @IBOutlet weak var requestButton: UIButton! @IBOutlet weak var headerImage: PFImageView! var photos : [Photo] = [] var refreshControl : UIRefreshControl! var selectedIndex: Int? override func viewDidLoad() { super.viewDidLoad() self.requestButton.backgroundColor = UIColor.prettoBlue() self.title = invitation?.event.title self.headerImage.file = invitation?.event.coverPhoto self.headerImage.loadInBackground() refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refreshData", forControlEvents: UIControlEvents.ValueChanged) collectionView.addSubview(refreshControl) collectionView.alwaysBounceVertical = true self.onSelectionChange() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) cameraView.hidden = true // Scale up to maximum flowLayout.itemSize = aspectScaleWithConstraints(flowLayout.itemSize, scale: 10, max: maxSize, min: minSize) self.refreshControl.beginRefreshing() self.clearSelections() self.refreshData() } func refreshData() { let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud.activityIndicatorColor = UIColor.whiteColor() hud.color = UIColor.prettoBlue().colorWithAlphaComponent(0.75) dispatch_async(GlobalMainQueue) { self.invitation?.event.getAllPhotosInEvent(kOrderedByNewestFirst) {photos in self.photos = photos dispatch_async(dispatch_get_main_queue()) { self.collectionView.reloadData() self.clearSelections() self.refreshControl.endRefreshing() MBProgressHUD.hideHUDForView(self.view, animated: true) } } } } // Clear all selections func clearSelections() { for path in selectedPaths { if let path = path as? NSIndexPath { deselectItemAtIndexPathIfNecessary(path) } } } @IBAction func didTapRequestPhotos(sender: UIButton) { requestButton.setTitle("Requesting photos...", forState: UIControlState.Normal) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { for path in self.selectedPaths { Request.makeRequestForPhoto(self.photos[path.row]).save() } dispatch_async(dispatch_get_main_queue()) { self.requestButton.setTitle("Request Sent!", forState: UIControlState.Normal) self.clearSelections() } } } override func onSelectionChange() { let selectionCount = selectedPaths.count if selectionCount == 0 { requestButton.setTitle("Select Photos", forState: UIControlState.Normal) requestButton.enabled = false } else { requestButton.setTitle("Create Album with \(selectionCount) Photos", forState: UIControlState.Normal) requestButton.enabled = true } } } // MARK: AUX Methods extension EventDetailViewController { func doubleTapReconized(sender: UITapGestureRecognizer) { selectedIndex = collectionView.indexPathForCell(sender.view as! SelectableImageCell)?.row self.performSegueWithIdentifier("SingleImageViewSegue", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { println("Preparing for Segue with image index \(selectedIndex)") let singlePhotoVC = segue.destinationViewController as! SinglePhotoViewController singlePhotoVC.photos = self.photos singlePhotoVC.initialIndex = self.selectedIndex ?? 0 } } // UICollectionViewDataSource Extension extension EventDetailViewController : UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as! SelectableImageCell let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: "doubleTapReconized:") doubleTapRecognizer.numberOfTapsRequired = 2 cell.addGestureRecognizer(doubleTapRecognizer) cell.image.file = self.photos[indexPath.row].thumbnailFile cell.image.loadInBackground() cell.backgroundColor = UIColor.clearColor() cell.updateCheckState() return cell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.photos.count } }
39.030303
134
0.674884
035d6f56600b95369496cb16a8ade06001071a04
2,719
// // DatePickerView.swift // Moviez // // Created by Evidence Osikhena on 26/01/2021. // import SwiftUI struct DatePickerView: View { private var formatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "eee D" return formatter } var body: some View { VStack(alignment: .leading) { Text("Select Day") .fontWeight(.semibold) .textCase(.uppercase) .font(.system(size: 20)) .padding(.leading) ScrollView(.horizontal) { HStack { ForEach(daysOfCurrentWeek(), id: \.self) { data in let str = formatter.string(from: data) VStack(spacing: 10) { Text(str.prefix(4)) .font(.system(size: 16)) // RoundedRectangle(cornerRadius: CGFloat(5.0) / 2.0) // .frame(width: 40, height: CGFloat(2.0)) // .foregroundColor(Color.white) // .padding(5) Text(str.suffix(3)) .font(.system(size: 14)) .padding(12) .background(Color.white) .cornerRadius(48) .shadow(radius: 3) } .padding(.vertical, 8) .padding(.horizontal, 3) } } } .padding(.leading) } .foregroundColor(.black) .frame(width: UIScreen.main.bounds.size.width) .padding(.leading, 18) } func daysOfCurrentWeek() -> [Date] { let calendar = Calendar.current let today = calendar.startOfDay(for: Date()) let dayOfWeek = calendar.component(.weekday, from: today) let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)! let days = (weekdays.lowerBound ..< weekdays.upperBound) .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) } // use `flatMap` in Xcode versions before 9.3 // .filter { !calendar.isDateInWeekend($0) } return days } } struct DatePickerView_Previews: PreviewProvider { static var previews: some View { DatePickerView() .previewLayout(.sizeThatFits) } }
34.858974
138
0.445017
03afdac1a45028f51e65b5d69e7f655038423ef7
1,888
// // LiveDecode.swift // TLSphinx // // Created by Bruno Berisso on 5/29/15. // Copyright (c) 2015 Bruno Berisso. All rights reserved. // import UIKit import XCTest import AVFoundation import TLSphinx class LiveDecode: XCTestCase { func getModelPath() -> String? { return Bundle(for: LiveDecode.self).path(forResource: "en-us", ofType: nil) } func testAVAudioRecorder() { if let modelPath = getModelPath() { let hmm = (modelPath as NSString).appendingPathComponent("en-us") let lm = (modelPath as NSString).appendingPathComponent("en-us.lm.dmp") let dict = (modelPath as NSString).appendingPathComponent("cmudict-en-us.dict") if let config = Config(args: ("-hmm", hmm), ("-lm", lm), ("-dict", dict)) { config.showDebugInfo = false if let decoder = Decoder(config:config) { decoder.startDecodingSpeech { (hyp) -> () in print("Utterance: \(hyp)") } let expectation = self.expectation(description: "") DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(15.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) , execute: { () -> Void in decoder.stopDecodingSpeech() expectation.fulfill() }) waitForExpectations(timeout: NSTimeIntervalSince1970, handler: nil) } } else { XCTFail("Can't run test without a valid config") } } else { XCTFail("Can't access pocketsphinx model. Bundle root: \(Bundle.main)") } } }
33.122807
173
0.512182
edb28a3fb96142c347fb3149565ba0be972a1db3
9,902
// // TransitionButton.swift // TransitionButton // // Created by Alaeddine M. on 11/1/15. // Copyright (c) 2015 Alaeddine M. All rights reserved. // import Foundation import UIKit /** Stop animation style of the `TransitionButton`. - normal: just revert the button to the original state. - expand: expand the button and cover all the screen, useful to do transit animation. - shake: revert the button to original state and make a shaoe animation, useful to reflect that something went wrong */ public enum StopAnimationStyle { case normal case expand case shake } /// UIButton sublass for loading and transition animation. Useful for network based application or where you need to animate an action button while doing background tasks. @IBDesignable open class TransitionButton : UIButton, UIViewControllerTransitioningDelegate, CAAnimationDelegate { /// the color of the spinner while animating the button @IBInspectable open var spinnerColor: UIColor = UIColor.white { didSet { spiner.spinnerColor = spinnerColor } } /// the background of the button in disabled state @IBInspectable open var disabledBackgroundColor: UIColor = UIColor.lightGray { didSet { self.setBackgroundImage(UIImage(color: disabledBackgroundColor), for: .disabled) } } /// the corner radius value to have a button with rounded corners. @IBInspectable open var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } private lazy var spiner: SpinerLayer = { let spiner = SpinerLayer(frame: self.frame) self.layer.addSublayer(spiner) return spiner }() private var cachedTitle: String? private var cachedImage: UIImage? private let springGoEase:CAMediaTimingFunction = CAMediaTimingFunction(controlPoints: 0.45, -0.36, 0.44, 0.92) private let shrinkCurve:CAMediaTimingFunction = CAMediaTimingFunction(name: .linear) private let expandCurve:CAMediaTimingFunction = CAMediaTimingFunction(controlPoints: 0.95, 0.02, 1, 0.05) private let shrinkDuration: CFTimeInterval = 0.1 public override init(frame: CGRect) { super.init(frame: frame) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() self.setup() } open override func layoutSubviews() { super.layoutSubviews() self.spiner.setToFrame(self.frame) } private func setup() { self.clipsToBounds = true spiner.spinnerColor = spinnerColor } /** start animating the button, before starting a task, exemple: before a network call. */ open func startAnimation() { self.isUserInteractionEnabled = false // Disable the user interaction during the animation self.cachedTitle = title(for: .normal) // cache title before animation of spiner self.cachedImage = image(for: .normal) // cache image before animation of spiner self.setTitle("", for: .normal) // place an empty string as title to display a spiner self.setImage(nil, for: .normal) // remove the image, if any, before displaying the spinner UIView.animate(withDuration: 0.1, animations: { () -> Void in self.layer.cornerRadius = self.frame.height / 2 // corner radius should be half the height to have a circle corners }, completion: { completed -> Void in self.shrink() // reduce the width to be equal to the height in order to have a circle self.spiner.animation() // animate spinner }) } /** stop animating the button. - Parameter animationStyle: the style of the stop animation. - Parameter revertAfterDelay: revert the button to the original state after a delay to give opportunity to custom transition. - Parameter completion: a callback closure to be called once the animation finished, it may be useful to transit to another view controller, example transit to the home screen from the login screen. */ open func stopAnimation(animationStyle:StopAnimationStyle = .normal, revertAfterDelay delay: TimeInterval = 1.0, completion:(()->Void)? = nil) { let delayToRevert = max(delay, 0.2) switch animationStyle { case .normal: // We return to original state after a delay to give opportunity to custom transition DispatchQueue.main.asyncAfter(deadline: .now() + delayToRevert) { self.setOriginalState(completion: completion) } case .shake: // We return to original state after a delay to give opportunity to custom transition DispatchQueue.main.asyncAfter(deadline: .now() + delayToRevert) { self.setOriginalState(completion: nil) self.shakeAnimation(completion: completion) } case .expand: self.spiner.stopAnimation() // before animate the expand animation we need to hide the spiner first self.expand(completion: completion, revertDelay: delayToRevert) // scale the round button to fill the screen } } private func shakeAnimation(completion:(()->Void)?) { let keyFrame = CAKeyframeAnimation(keyPath: "position") let point = self.layer.position keyFrame.values = [NSValue(cgPoint: CGPoint(x: CGFloat(point.x), y: CGFloat(point.y))), NSValue(cgPoint: CGPoint(x: CGFloat(point.x - 10), y: CGFloat(point.y))), NSValue(cgPoint: CGPoint(x: CGFloat(point.x + 10), y: CGFloat(point.y))), NSValue(cgPoint: CGPoint(x: CGFloat(point.x - 10), y: CGFloat(point.y))), NSValue(cgPoint: CGPoint(x: CGFloat(point.x + 10), y: CGFloat(point.y))), NSValue(cgPoint: CGPoint(x: CGFloat(point.x - 10), y: CGFloat(point.y))), NSValue(cgPoint: CGPoint(x: CGFloat(point.x + 10), y: CGFloat(point.y))), NSValue(cgPoint: point)] keyFrame.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) keyFrame.duration = 0.7 self.layer.position = point CATransaction.setCompletionBlock { completion?() } self.layer.add(keyFrame, forKey: keyFrame.keyPath) CATransaction.commit() } private func setOriginalState(completion:(()->Void)?) { self.animateToOriginalWidth(completion: completion) self.spiner.stopAnimation() self.setTitle(self.cachedTitle, for: .normal) self.setImage(self.cachedImage, for: .normal) self.isUserInteractionEnabled = true // enable again the user interaction self.layer.cornerRadius = self.cornerRadius } private func animateToOriginalWidth(completion:(()->Void)?) { let shrinkAnim = CABasicAnimation(keyPath: "bounds.size.width") shrinkAnim.fromValue = (self.bounds.height) shrinkAnim.toValue = (self.bounds.width) shrinkAnim.duration = shrinkDuration shrinkAnim.timingFunction = shrinkCurve shrinkAnim.fillMode = .forwards shrinkAnim.isRemovedOnCompletion = false CATransaction.setCompletionBlock { completion?() } self.layer.add(shrinkAnim, forKey: shrinkAnim.keyPath) CATransaction.commit() } private func shrink() { let shrinkAnim = CABasicAnimation(keyPath: "bounds.size.width") shrinkAnim.fromValue = frame.width shrinkAnim.toValue = frame.height shrinkAnim.duration = shrinkDuration shrinkAnim.timingFunction = shrinkCurve shrinkAnim.fillMode = .forwards shrinkAnim.isRemovedOnCompletion = false layer.add(shrinkAnim, forKey: shrinkAnim.keyPath) } private func expand(completion:(()->Void)?, revertDelay: TimeInterval) { let expandAnim = CABasicAnimation(keyPath: "transform.scale") let expandScale = (UIScreen.main.bounds.size.height/self.frame.size.height)*2 expandAnim.fromValue = 1.0 expandAnim.toValue = max(expandScale,26.0) expandAnim.timingFunction = expandCurve expandAnim.duration = 0.4 expandAnim.fillMode = .forwards expandAnim.isRemovedOnCompletion = false CATransaction.setCompletionBlock { completion?() // We return to original state after a delay to give opportunity to custom transition DispatchQueue.main.asyncAfter(deadline: .now() + revertDelay) { self.setOriginalState(completion: nil) self.layer.removeAllAnimations() // make sure we remove all animation } } layer.add(expandAnim, forKey: expandAnim.keyPath) CATransaction.commit() } } public extension UIImage { convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image!.cgImage else { return nil } self.init(cgImage: cgImage) } }
39.927419
203
0.635831
1c3a279ff780aa12f329db71b6b788a0355ec2c3
1,840
// // ItunesEntity.swift // ItunesSimpleSearch // // Created by Bastián Véliz Vega on 21-05-20. // Copyright © 2020 Bastián Véliz Vega. All rights reserved. // import Foundation struct ItunesEntity: Codable { let wrapperType: String? let kind: String? let artistId: Int64? let collectionId: Int64? let trackId: Int64? let artistName: String? let collectionName: String? let trackName: String? let collectionCensoredName: String? let trackCensoredName: String? let artistViewUrl: String? let collectionViewUrl: String? let trackViewUrl: String? let previewUrl: String? let artworkUrl60: String? let artworkUrl100: String? let collectionPrice: Float? let trackPrice: Float? let collectionExplicitness: String? let trackExplicitness: String? let discCount: Int? let discNumber: Int? let trackCount: Int? let trackNumber: Int? let trackTimeMillis: Int64? let country: String? let currency: String? let primaryGenreName: String? private enum ItunesElementKeys: String, CodingKey { case wrapperType case kind case artistId case collectionId case trackId case artistName case collectionName case trackName case collectionCensoredName case trackCensoredName case artistViewUrl case collectionViewUrl case trackViewUrl case previewUrl case artworkUrl60 case artworkUrl100 case collectionPrice case trackPrice case collectionExplicitness case trackExplicitness case discCount case discNumber case trackCount case trackNumber case trackTimeMillis case country case currency case primaryGenreName } }
25.555556
61
0.666304
ef2e9850724e3b24fff955de4d45ce41a4c2e973
1,621
import Foundation import LambdaRuntime import Dispatch import NIO import NIOHTTP1 #if os(Linux) import FoundationNetworking #endif let session = URLSession(configuration: .default) func sendEcho(session: URLSession, completion: @escaping (Result<HTTPResponseStatus, Error>) -> ()) { let urlRequest = URLRequest(url: URL(string: "https://postman-echo.com/get?foo1=bar1&foo2=bar2")!) let task = session.dataTask(with: urlRequest) { (data, response, error) in if let error = error { completion(.failure(error)) } guard let response = response as? HTTPURLResponse else { fatalError("unexpected response type") } let status = HTTPResponseStatus(statusCode: response.statusCode) completion(.success(status)) } task.resume() } func echoCall(input: ByteBuffer?, context: Context) -> EventLoopFuture<ByteBuffer?> { let promise = context.eventLoop.makePromise(of: ByteBuffer?.self) sendEcho(session: session) { (result) in switch result { case .success(let status): context.logger.info("HTTP call with NSURLSession success: \(status)") promise.succeed(nil) case .failure(let error): context.logger.error("HTTP call with NSURLSession failed: \(error)") promise.fail(error) } } return promise.futureResult } let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) defer { try! group.syncShutdownGracefully() } do { let runtime = try Runtime.createRuntime(eventLoopGroup: group, handler: echoCall) defer { try! runtime.syncShutdown() } try runtime.start().wait() } catch { print("\(error)") }
26.57377
101
0.702653
09024bfd834678417ed03f28988e7c90fb418eed
2,580
// // APIUrls.swift // Storizy-iOS // // Created by 임수정 on 2021/11/11. // import Foundation struct APIUrls { static let baseURL = "http://3.38.20.217:3000/api/" // auth static let postSigninURL = baseURL + "auth/login" static let postSignupURL = baseURL + "auth/signup" static let getCheckEmailURL = baseURL + "auth/check-email/" static let getSendAuthEmailURL = baseURL + "auth/mail/" static let getAuthEmailURL = baseURL + "auth/mail" // profile static let getMyProfileURL = baseURL + "profile" // 내 프로필 조회 static let getProfileURL = baseURL + "profile/" // 다른 사람 프로필 조회 static let postUpdateProfileURL = baseURL + "profile" // 내 프로필 수정 // home static let getMyStoryURL = baseURL + "user/story" // 내 스토리 조회 static let getMyStoryTagsURL = baseURL + "user/tags" // 내 태그 목록 조회 static let getMySearchedStoryURL = baseURL + "user/page" // 내 태그별 스토리 조회 static let getStoryURL = baseURL + "user/" // 남 스토리 조회 {userId}/story static let getStoryTagsURL = baseURL + "user/" // 남 태그 목록 조회 /api/user/{userId}/tags // upload static let uploadProfileImageURL = baseURL + "upload/profile" // 프로필 이미지 업로드 static let uploadPageImagesURL = baseURL + "upload/page" // 페이지 이미지 업로드 // tag static let getRecomTagURL = baseURL + "profile/tags/recommend" // 추천 태그 조회 static let postSetProfileTagsURL = baseURL + "profile/tags" // 프로필 태그 설정 static let postAddTagURL = baseURL + "tags" // 태그 추가 static let postAddColorTagURL = baseURL + "tags/color" // 컬러 태그 추가 // project static let getColorsURL = baseURL + "project/colors" // 색 목록 조회 static let postCreateProjectURL = baseURL + "project" // 프로젝트 생성 static let postUpdateProjectURL = baseURL + "project/" // 프로젝트 수정 static let delProjectURL = baseURL + "project/" // 프로젝트 삭제 static let getProjectDetailURL = baseURL + "project/" // 프로젝트 상세 조회 // page static let postCreatePageURL = baseURL + "page" // 페이지 생성 static let postUpdatePageURL = baseURL + "page/" // 페이지 수정 static let delPageURL = baseURL + "page/" // 페이지 삭제 static let getPageURL = baseURL + "page/" // 페이지 상세 조회 // exp static let getRecomPageURL = baseURL + "explore/page/recommend" // 추천페이지목록조회 static let searchPageURL = baseURL + "explore/page" // 페이지 검색 static let searchProfileURL = baseURL + "explore/user" // 프로필 검색 // like static let getLikePageURL = baseURL + "like/page" // 좋아요한 페이지 목록 static let getLikeProfileURL = baseURL + "like/user" // 좋아요한 프로필 목록 }
37.391304
88
0.65814
6789353bc7b8283eadacaf3ff6fa0addb5cc2f24
476
import Foundation struct Task: Identifiable, Codable, Sendable { let id: UUID let date: Date var body: String var completed = Bool.random() } extension Task { static let sample1 = Task(id: .init(), date: .init(), body: "Lorem ipsum dolor sit amet.") static let sample2 = Task(id: .init(), date: .distantFuture, body: "Consectetur adipiscing elit sed.") static let sample3 = Task(id: .init(), date: .distantPast, body: "Do eismod tempor elit.") }
31.733333
106
0.670168
1af6e3af6bfb355de29da6a5547b99cc087b2c22
11,550
// // 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 typealias Fallible<S> = Result<S, Swift.Error> // MARK: - Casting public extension Fallible { /// Transforms the fallible to a fallible of unrelated type /// Correctness of such transformation is left on our behalf func staticCast<T>() -> Fallible<T> { switch self { case let .success(success): return .success(success as! T) case let .failure(failure): return .failure(failure) } } /// Transforms the fallible to a fallible of unrelated type /// Incorrect transformation will result into dynamicCastFailed failure func dynamicCast<T>() -> Fallible<T> { switch self { case let .success(success): if let castedSuccess = success as? T { return .success(castedSuccess) } else { return .failure(AsyncNinjaError.dynamicCastFailed) } case let .failure(failure): return .failure(failure) } } } // MARK: - Description extension Fallible: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of this instance. public var description: String { return description(withBody: "") } /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { return description(withBody: "<\(Success.self)>") } /// **internal use only** private func description(withBody body: String) -> String { switch self { case .success(let value): return "success\(body)(\(value))" case .failure(let value): return "failure\(body)(\(value))" } } } // MARK: - state managers public extension Fallible { /// Returns success if Fallible has a success value inside. /// Returns nil otherwise var maybeSuccess: Success? { switch self { case let .success(succes): return succes case .failure: return nil } } /// Returns failure if Fallible has a failure value inside. /// Returns nil otherwise var maybeFailure: Failure? { switch self { case .success: return nil case let .failure(failure): return failure } } /// Executes block if Fallible has success value inside /// /// - Parameters: /// - handler: handler to execute /// - success: success value of Fallible /// - Throws: rethrows an error thrown by the block func onSuccess(_ block: (_ success: Success) throws -> Void) rethrows { if case let .success(success) = self { try block(success) } } /// Executes block if Fallible has failure value inside /// /// - Parameters: /// - handler: handler to execute /// - failure: failure value of Fallible /// - Throws: rethrows an error thrown by the block func onFailure(_ block: (_ failure: Failure) throws -> Void) rethrows { if case let .failure(failure) = self { try block(failure) } } } // MARK: - transformers public extension Fallible { /// Applies transformation to Fallible /// /// - Parameters: /// - transform: block to apply. /// A success value returned from block will be a success value of the transformed Fallible. /// An error thrown from block will be a failure value of a transformed Fallible /// **This block will not be executed if an original Fallible contains a failure.** /// **That failure will become a failure value of a transfomed Fallible** /// - success: success value of original Fallible /// - Returns: transformed Fallible func map<T>(_ transform: (_ success: Success) throws -> T) -> Fallible<T> { return self.flatMap { .success(try transform($0)) } } /// Applies transformation to Fallible and flattens nested Fallibles. /// /// - Parameters: /// - transform: block to apply. /// A fallible value returned from block will be a value (after flattening) of the transformed Fallible. /// An error thrown from block will be a failure value of the transformed Fallible. /// **This block will not be executed if an original Fallible contains a failure.** /// **That failure will become a failure value of a transfomed Fallible** /// - success: success value of original Fallible /// - Returns: transformed Fallible func flatMap<T>(_ transform: (_ success: Success) throws -> Fallible<T>) -> Fallible<T> { switch self { case let .success(success): return flatFallible { try transform(success) } case let .failure(failure): return .failure(failure) } } /// Applies transformation to Fallible /// /// - Parameters: /// - transform: block to apply. /// A success value returned from block will be a success value of the transformed Fallible. /// An error thrown from block will be a failure value of a transformed Fallible. /// **This block will not be executed if an original Fallible contains a success value.** /// **That success value will become a success value of a transfomed Fallible** /// - failure: failure value of original Fallible /// - Returns: transformed Fallible func tryRecover(_ transform: (_ failure: Failure) throws -> Success) -> Fallible<Success> { switch self { case let .success(success): return .success(success) case let .failure(failure): do { return .success(try transform(failure)) } catch { return .failure(error) } } } /// Applies non-throwable transformation to Fallible /// /// - Parameters: /// - transform: block to apply. /// A success value returned from block will be returned from method. /// **This block will not be executed if an original Fallible contains a success value.** /// **That success value will become a success value of a transfomed Fallible** /// - failure: failure value of original Fallible /// - Returns: success value func recover(_ transform: (_ failure: Failure) -> Success) -> Success { switch self { case let .success(success): return success case let .failure(failure): return transform(failure) } } /// Applies non-throwable transformation to Fallible /// /// - Parameters: /// - success: recover failure with /// - Returns: success value func recover(with success: Success) -> Success { switch self { case let .success(success): return success case .failure: return success } } } // MARK: - consturctors /// Executes specified block and wraps a returned value or a thrown error with Fallible /// /// - Parameter block: to execute. /// A returned value will become success value of retured Fallible. /// A thrown error will become failure value of returned Fallible. /// - Returns: fallible constructed of a returned value or a thrown error with Fallible public func fallible<T>(block: () throws -> T) -> Fallible<T> { do { return .success(try block()) } catch { return .failure(error) } } /// Executes specified block and returns returned Fallible or wraps a thrown error with Fallible /// /// - Parameter block: to execute. /// A returned value will returned from method. /// A thrown error will become failure value of returned Fallible. /// - Returns: returned Fallible or a thrown error wrapped with Fallible public func flatFallible<T>(block: () throws -> Fallible<T>) -> Fallible<T> { do { return try block() } catch { return .failure(error) } } // MARK: - flattening extension Fallible where Success: _Fallible { /// Flattens two nested Fallibles: /// ``` /// < <Success> > => <Success> /// < <Failure> > => <Failure> /// <Failure> => <Failure> /// ``` /// /// - Returns: flattened Fallible public func flatten() -> Fallible<Success.Success> { switch self { case let .success(success): return success as! Fallible<Success.Success> case let .failure(failure): return .failure(failure) } } } /// **Internal use only** /// The combination of protocol _Fallible and enum Fallible is a dirty hack of type system. /// But there are no higher kinded types or generic protocols to implement it properly. /// Major propose is an ability to implement flatten() method. public protocol _Fallible: CustomStringConvertible { /// a type of a successful case value associatedtype Success associatedtype Failure /// returns success value if _Fallible contains one var maybeSuccess: Success? { get } /// returns failure value if _Fallible contains one var maybeFailure: Failure? { get } /// executes handler if the fallible containse success value func onSuccess(_ handler: (Success) throws -> Void) rethrows /// executes handler if the fallible containse failure value func onFailure(_ handler: (Failure) throws -> Void) rethrows /// (success or failure) * (try transform success to success) -> (success or failure) func map<T>(_ transform: (Success) throws -> T) -> Fallible<T> /// (success or failure) * (try transform success to (success or failure)) -> (success or failure) func flatMap<T>(_ transform: (Success) throws -> Fallible<T>) -> Fallible<T> /// (success or failure) * (try transform failure to success) -> (success or failure) func tryRecover(_ transform: (Failure) throws -> Success) -> Fallible<Success> /// (success or failure) * (transform failure to success) -> success func recover(_ transform: (Failure) -> Success) -> Success /// returns success or throws failure func get() throws -> Success } /// Combines successes of two failables or returns fallible with first error public func zip<A, B>( _ a: Fallible<A>, _ b: Fallible<B> ) -> Fallible<(A, B)> { switch (a, b) { case let (.success(successA), .success(successB)): return .success((successA, successB)) case let (.failure(failure), _), let (_, .failure(failure)): return .failure(failure) default: fatalError() } } /// Combines successes of tree failables or returns fallible with first error public func zip<A, B, C>( _ a: Fallible<A>, _ b: Fallible<B>, _ c: Fallible<C> ) -> Fallible<(A, B, C)> { switch (a, b, c) { case let (.success(successA), .success(successB), .success(successC)): return .success((successA, successB, successC)) case let (.failure(failure), _, _), let (_, .failure(failure), _), let (_, _, .failure(failure)): return .failure(failure) default: fatalError() } } extension Fallible: _Fallible { }
33.575581
110
0.672814
3aac90282721184a49d274dca829eaf9bca4f592
4,513
// // FFmpegPlaybackContext.swift // Aural // // Copyright © 2021 Kartik Venugopal. All rights reserved. // // This software is licensed under the MIT software license. // See the file "LICENSE" in the project root directory for license terms. // import AVFoundation /// /// Provides information necessary for scheduling and playback of a non-native track using **FFmpeg**. /// class FFmpegPlaybackContext: PlaybackContextProtocol { let file: URL var fileContext: FFmpegFileContext? var decoder: FFmpegDecoder? var audioCodec: FFmpegAudioCodec? { decoder?.codec } let audioFormat: AVAudioFormat /// /// The maximum number of samples that will be read, decoded, and scheduled for **immediate** playback, /// i.e. when **play(file)** is called, triggered by the user. /// /// # Notes # /// /// 1. This value should be small enough so that, when starting playback /// of a file, there is little to no perceived lag. Typically, this should represent about 2-5 seconds of audio (depending on sample rate). /// /// 2. This value should generally be smaller than *sampleCountForDeferredPlayback*. /// var sampleCountForImmediatePlayback: Int32 = 0 /// /// The maximum number of samples that will be read, decoded, and scheduled for **deferred** playback, i.e. playback that will occur /// at a later time, as the result, of a recursive scheduling task automatically triggered when a previously scheduled audio buffer has finished playing. /// /// # Notes # /// /// 1. The greater this value, the longer each recursive scheduling task will take to complete, and the larger the memory footprint of each audio buffer. /// The smaller this value, the more often disk reads will occur. Choose a value that is a good balance between memory usage, decoding / resampling time, and frequency of disk reads. /// Example: 10-20 seconds of audio (depending on sample rate). /// /// 2. This value should generally be larger than *sampleCountForImmediatePlayback*. /// var sampleCountForDeferredPlayback: Int32 = 0 var sampleRate: Double = 0 var frameCount: Int64 = 0 var duration: Double {fileContext?.duration ?? 0} init(for file: URL) throws { self.file = file self.fileContext = try FFmpegFileContext(for: file) self.decoder = try FFmpegDecoder(for: fileContext!) let codec = decoder!.codec let sampleRate: Int32 = codec.sampleRate let sampleRateDouble: Double = Double(sampleRate) self.sampleRate = sampleRateDouble self.frameCount = Int64(sampleRateDouble * fileContext!.duration) let channelLayout: AVAudioChannelLayout = FFmpegChannelLayoutsMapper.mapLayout(ffmpegLayout: Int(codec.channelLayout)) ?? .stereo self.audioFormat = AVAudioFormat(standardFormatWithSampleRate: sampleRateDouble, channelLayout: channelLayout) // The effective sample rate, which also takes into account the channel count, gives us a better idea // of the computational cost of decoding and resampling the given file, as opposed to just the // sample rate. let channelCount: Int32 = codec.channelCount let effectiveSampleRate: Int32 = sampleRate * channelCount switch effectiveSampleRate { case 0..<100000: // 44.1 / 48 KHz stereo sampleCountForImmediatePlayback = 5 * sampleRate // 5 seconds of audio sampleCountForDeferredPlayback = 10 * sampleRate // 10 seconds of audio case 100000..<500000: // 96 / 192 KHz stereo sampleCountForImmediatePlayback = 3 * sampleRate // 3 seconds of audio sampleCountForDeferredPlayback = 10 * sampleRate // 10 seconds of audio default: // 96 KHz surround and higher sample rates sampleCountForImmediatePlayback = 2 * sampleRate // 2 seconds of audio sampleCountForDeferredPlayback = 7 * sampleRate // 7 seconds of audio } } func open() throws { if fileContext == nil { fileContext = try FFmpegFileContext(for: file) decoder = try FFmpegDecoder(for: fileContext!) } } func close() { decoder = nil fileContext = nil } deinit { close() } }
34.984496
186
0.650787
26270412cd01a07fd8e808a5066b044b80b41fda
1,433
// // ImageStore.swift // PhotoBin // // Created by Vipin Aggarwal on 27/06/21. // Copyright © 2021 Vipin Aggarwal. All rights reserved. // import Foundation import UIKit struct ImageStore { static let SAVED_PHOTOS = "SavedPhotos" static func saveImage(image: UIImage) throws -> Photo{ do { let photo = try Photo(image: image) try Self.savePhoto(photo: photo) return photo } catch let error { throw error } } // static func getImages() -> [UIImage?] { // let fileNames = Self.getSavedFileNames() // let images: [UIImage?] = fileNames.map { // if let fileURL = getPathFor(fileName: $0) { // return UIImage(contentsOfFile: fileURL.path) // } // return nil // } // return images // } private static func savePhoto(photo: Photo) throws { var photos = getSavedPhotos() photos.append(photo) let userDefaults = UserDefaults.standard do { try userDefaults.setObject(photos, forKey: SAVED_PHOTOS) } catch let error { throw error } } static func getSavedPhotos() -> [Photo] { let userDefaults = UserDefaults.standard let photos = try? userDefaults.getObject(forKey: SAVED_PHOTOS, castTo: [Photo].self) return photos ?? [] } }
26.054545
92
0.565248
3310de6a860036dec48362aa9ded94dbab5d0522
1,226
// // GlobalFuction.swift // FloatingWindow // // Created by 盘国权 on 2018/6/10. // Copyright © 2018年 pgq. All rights reserved. // import UIKit /* view.backgroundColor = .blue let dd = HideFloatingWindowView(frame: CGRect(x: 0, y: 0, width: 160, height: 160)) view.addSubview(dd) dd.center = view.center let btn = view.addSubview(btn) */ var margin: CGFloat = 20 let floatingWindowBtn = FloatingWindowView(frame: CGRect(x: UIScreen.main.bounds.width - 50 - margin , y: (UIScreen.main.bounds.height - 50) * 0.5, width: 50, height: 50), image: UIImage(named: "head")) let hideFrame = CGRect(x: UIScreen.main.bounds.width, y: UIScreen.main.bounds.height, width: 160, height: 160) let hideWindowView = HideFloatingWindowView(frame: hideFrame) var fwController: FloatingWindowController = FloatingWindowController() /// show btn public func showFloatingWindowBtn(){ floatingWindowBtn.isHidden = false if hideWindowView.superview == nil { UIApplication.shared.keyWindow?.addSubview(hideWindowView) } if floatingWindowBtn.superview == nil { UIApplication.shared.keyWindow?.addSubview(floatingWindowBtn) } }
27.863636
202
0.681077
dd6d13d9368046d7bf65b57774f73e8fa661ed25
17,211
// // SettingViewController.swift // STRCourier // // Created by Nitin Singh on 17/10/17. // Copyright © 2017 OSSCube. All rights reserved. // import UIKit import SwiftyJSON class SettingModel : NSObject, NSCoding { var day: String? var from : String? var to : String? init(day: String?,from : String?,to: String?){ self.day = day self.from = from self.to = to } func encode(with aCoder: NSCoder) { aCoder.encode(self.day, forKey: "day") aCoder.encode(self.from, forKey: "from") aCoder.encode(self.to, forKey: "to") } required init(coder decoder: NSCoder) { if let day = decoder.decodeObject(forKey: "day") as? String{ self.day = day } if let from = decoder.decodeObject(forKey: "from") as? String{ self.from = from } if let to = decoder.decodeObject(forKey: "to") as? String{ self.to = to } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encode(self.day, forKey: "day"); aCoder.encode(self.from, forKey: "from"); aCoder.encode(self.to, forKey: "to"); } } class SettingViewController: UIViewController { @IBOutlet weak var endTimeText: UITextField! @IBOutlet var vwSegment: STRHomeSegment! var inputViewObj = UIView() @IBOutlet weak var startTimeText: UITextField! var textFieldSelected : UITextField! var startWeekString : String! = "00:00" var endWeekString : String! = "23:59" var startSunday : String! = "00:00" var endSunday : String! = "23:59" var startSaturday : String! = "00:00" var endSaturday : String! = "23:59" var segmentCount : Int = 0 var arrayData: [SettingModel]! = [] var datePickerObject = UIDatePicker() override func viewDidLoad() { super.viewDidLoad() self.title = TitleName.trackingSetting.rawValue customizeNavigationforAll(self) inputViewObj = UIView() dataFeeding() self.vwSegment.blockSegmentButtonClicked = {(segment) in self.segmentCount = segment let setting = self.arrayData![segment] if segment == 0 { print("0") self.startTimeText.text = setting.from self.endTimeText.text = setting.to }else if segment == 1{ print("1") self.startTimeText.text = setting.from self.endTimeText.text = setting.to }else{ print("2") self.startTimeText.text = setting.from self.endTimeText.text = setting.to } // self.textFieldSelected.isUserInteractionEnabled = true // self.textFieldSelected.resignFirstResponder() // self.inputViewObj.removeFromSuperview() } NotificationCenter.default.addObserver(self, selector: #selector(SettingViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SettingViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) let tap = UITapGestureRecognizer(target: self, action: #selector(hidePicker)) tap.numberOfTapsRequired = 1 self.view.addGestureRecognizer(tap) setUpPicker() } func setUpPicker(){ self.datePickerObject.datePickerMode = .time self.startTimeText.inputView = self.datePickerObject self.endTimeText.inputView = self.datePickerObject self.datePickerObject.addTarget(self, action: #selector(handleDatePicker(_:)), for: UIControlEvents.valueChanged) } @objc func hidePicker(){ self.textFieldSelected.resignFirstResponder() } func keyboardWillShow(notification: NSNotification) { let keyboardSize = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size if self.view.frame.origin.y == 64{ self.view.frame.origin.y -= keyboardSize.height } } func keyboardWillHide(notification: NSNotification) { let keyboardSize = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size if self.view.frame.origin.y != 64{ self.view.frame.origin.y += keyboardSize.height } } func sortButtonClicked(_ sender : AnyObject){ // let VW = STRSearchViewController(nibName: "STRSearchViewController", bundle: nil) // self.navigationController?.pushViewController(VW, animated: true) } func backToDashbaord(_ sender: AnyObject) { let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.initSideBarMenu() } @IBAction func saveButtonClicked(_ sender: Any) { self.textFieldSelected.resignFirstResponder() let setting = self.arrayData![segmentCount] updateTrackingTime(day: setting.day!, from: setting.from!, to: setting.to!) } func updateTrackingTime(day : String , from : String , to : String){ if day == "weekdays" { let paramDictfrom : [[String :String]] = [["from": self.appendTimeString(timeString: from), "to":self.appendTimeString(timeString: to)]] let paramDictsun : [[String :String]] = [["from": self.appendTimeString(timeString: self.arrayData![2].from!), "to":self.appendTimeString(timeString: self.arrayData![2].to!)]] let paramDictsatr : [[String :String]] = [["from": self.appendTimeString(timeString: self.arrayData![1].from!), "to":self.appendTimeString(timeString: self.arrayData![1].to!)]] let paramDict = [day: paramDictfrom, "sunday": paramDictsun, "saturday": paramDictsatr] as [String : Any] updateTrackingTimeData(paramDict: paramDict as Dictionary<String, AnyObject>) } if day == "saturday" { let paramDictfrom : [[String :String]] = [["from": self.appendTimeString(timeString: self.arrayData![0].from!), "to":self.appendTimeString(timeString: self.arrayData![0].to!)]] let paramDictsun : [[String :String]] = [["from": self.appendTimeString(timeString: self.arrayData![2].from!), "to":self.appendTimeString(timeString: self.arrayData![2].to!)]] let paramDictsatr : [[String :String]] = [["from": self.appendTimeString(timeString: from), "to":self.appendTimeString(timeString: to)]] let paramDict = ["weekdays": paramDictfrom, "sunday": paramDictsun, day: paramDictsatr] as [String : Any] updateTrackingTimeData(paramDict: paramDict as Dictionary<String, AnyObject>) } if day == "sunday" { let paramDictfrom : [[String :String]] = [["from": self.appendTimeString(timeString: self.arrayData![0].from!), "to":self.appendTimeString(timeString: self.arrayData![0].to!)]] let paramDictsun : [[String :String]] = [["from": self.appendTimeString(timeString:from), "to":self.appendTimeString(timeString: to)]] let paramDictsatr : [[String :String]] = [["from": self.appendTimeString(timeString: self.arrayData![1].from!), "to":self.appendTimeString(timeString: self.arrayData![1].from!)]] let paramDict = ["weekdays": paramDictfrom, day: paramDictsun, "saturday": paramDictsatr] as [String : Any] updateTrackingTimeData(paramDict: paramDict as Dictionary<String, AnyObject>) } } func toggleSideMenu(_ sender: AnyObject) { self.revealViewController().revealToggle(animated: true) } func dataFeeding() { let loadingNotification = MBProgressHUD.showAdded(to: self.view, animated: true) loadingNotification?.mode = MBProgressHUDMode.indeterminate loadingNotification?.labelText = "Loading" let generalApiobj = GeneralAPI() let someDict:[String:String] = ["":""] generalApiobj.hitApiwith(someDict as Dictionary<String, AnyObject>, serviceType: .strApiTrackingSetting, success: { (response) in DispatchQueue.main.async { print(response) guard let data = response["data"] as? [String:AnyObject] else{ utility.createAlert(TextMessage.alert.rawValue, alertMessage: TextMessage.tryAgain.rawValue, alertCancelTitle: TextMessage.Ok.rawValue ,view: self) return } print(data) self.setUpData(data: data) MBProgressHUD.hideAllHUDs(for: self.view, animated: true) } }) { (err) in DispatchQueue.main.async { MBProgressHUD.hideAllHUDs(for: self.view, animated: true) utility.createAlert(TextMessage.alert.rawValue, alertMessage: TextMessage.tryAgain.rawValue, alertCancelTitle: TextMessage.Ok.rawValue ,view: self) NSLog(" %@", err) } } } func setUpData(data:[String:AnyObject]){ let weekdaysValues = data["weekdays"] as? [AnyObject] let weekdays = weekdaysValues![0] as! Dictionary<String, AnyObject> let settingWeekdays = SettingModel(day: "weekdays", from : self.substringTime(timeString: (weekdays["from"] as? String)!), to: self.substringTime(timeString: (weekdays["to"] as? String)!)) self.startTimeText.text = self.substringTime(timeString: (weekdays["from"] as? String)!) self.endTimeText.text = self.substringTime(timeString: (weekdays["to"] as? String)!) self.arrayData?.append(settingWeekdays) let saturdayValues = data["saturday"] as? [AnyObject] let saturday = saturdayValues![0] as! Dictionary<String, AnyObject> let settingSaturday = SettingModel(day: "saturday", from : self.substringTime(timeString: (saturday["from"] as? String)!), to: self.substringTime(timeString: (saturday["to"] as? String)!)) self.arrayData?.append(settingSaturday) let sundayValues = data["sunday"] as? [AnyObject] let sunday = sundayValues![0] as! Dictionary<String, AnyObject> let settingObj = SettingModel(day: "sunday", from : self.substringTime(timeString: (sunday["from"] as? String)!), to: self.substringTime(timeString: (sunday["to"] as? String)!)) self.arrayData?.append(settingObj) utility.setselectedTrackingTime(self.arrayData!) } func substringTime (timeString: String) -> String { let start = timeString.startIndex let end = timeString.index(timeString.endIndex, offsetBy: -3) let substring = timeString[start..<end] print(substring) return substring } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } public func textFieldDidBeginEditing(_ textField: UITextField) { // if inputViewObj != nil // { // inputViewObj.removeFromSuperview() // } // textField.resignFirstResponder() if textField == startTimeText { textFieldSelected = startTimeText // datePicker(textfeild: startTimeText) } if textField == endTimeText { textFieldSelected = endTimeText // datePicker(textfeild: endTimeText) } // textFieldSelected.isUserInteractionEnabled = false } func datePicker (textfeild : UITextField){ let screenSize = UIScreen.main.bounds let screenWidth = screenSize.width let origin = (screenWidth/4) - 100 inputViewObj = UIView(frame: CGRect.init(x: origin, y: self.view.frame.height - 240, width: screenWidth , height: 240)) // inputViewObj.backgroundColor = UIColor.gray let datePickerView : UIDatePicker = UIDatePicker(frame:CGRect.init(x: 50, y: 50, width: 0, height: 0)) datePickerView.datePickerMode = UIDatePickerMode.countDownTimer inputViewObj.addSubview(datePickerView) // add date picker to UIView let doneButton = UIButton(frame: CGRect.init(x: (screenWidth/2) + 70, y: 20, width: 100, height: 50)) doneButton.setTitle("Done", for: UIControlState.normal) doneButton.setTitle("Done", for: UIControlState.highlighted) doneButton.setTitleColor(UIColor.black, for: UIControlState.normal) doneButton.setTitleColor(UIColor.gray, for: UIControlState.highlighted) inputViewObj.addSubview(doneButton) // add Button to UIView doneButton.addTarget(self, action: #selector(doneButton(_:)), for: UIControlEvents.touchUpInside) // set button click event textfeild.inputView = inputView datePickerView.addTarget(self, action: #selector(handleDatePicker(_:)), for: UIControlEvents.valueChanged) self.view.addSubview(inputViewObj) handleDatePicker(datePickerView) } func handleDatePicker(_ sender: UIDatePicker) { let fireDate = sender.date datePickerObject = sender let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" textFieldSelected.text = dateFormatter.string(from: sender.date) doneButton(UIButton()); } func doneButton(_ sender:UIButton) { if !self.validateTime() { return } var setting = self.arrayData![segmentCount] if segmentCount == 0 { if textFieldSelected == startTimeText{ setting.from = textFieldSelected.text }else{setting.to = textFieldSelected.text} } if segmentCount == 1 { if textFieldSelected == startTimeText{ setting.from = textFieldSelected.text }else{setting.to = textFieldSelected.text} } if segmentCount == 2 { if textFieldSelected == startTimeText{ setting.from = textFieldSelected.text }else{setting.to = textFieldSelected.text} } //textFieldSelected.isUserInteractionEnabled = true // textFieldSelected.resignFirstResponder() //inputViewObj.removeFromSuperview()// To resign the inputView on clicking done. } func validateTime() -> Bool{ let formatter = DateFormatter() formatter.dateFormat = "HH:mm" let firedate = datePickerObject.date let date1 = formatter.date(from: startTimeText.text!) let date2 = formatter.date(from: endTimeText.text!) if date2! < date1! { print("selected date is smaller than ") utility.createAlert(TextMessage.alert.rawValue, alertMessage: TextMessage.dateValidation.rawValue, alertCancelTitle: TextMessage.Ok.rawValue ,view: self) return false } return true } func datePickerFromValueChanged(sender:UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH : mm" textFieldSelected.text = dateFormatter.string(from: sender.date) } func appendTimeString (timeString: String) -> String { let appendString = timeString + ":00" print(appendString) return appendString } func updateTrackingTimeData(paramDict : Dictionary<String, AnyObject>) { let loadingNotification = MBProgressHUD.showAdded(to: self.view, animated: true) loadingNotification?.mode = MBProgressHUDMode.indeterminate loadingNotification?.labelText = "Loading" let generalApiobj = GeneralAPI() print(paramDict) generalApiobj.hitApiwith(paramDict as! Dictionary<String, AnyObject>, serviceType: .strApiUpdateTrackingSetting, success: { (response) in DispatchQueue.main.async { print(response) let dataDictionary = response["data"] as? [String : AnyObject] // self.dataFeeding() let description = response["description"] as? String utility.createAlert("", alertMessage: description!, alertCancelTitle: "OK", view: self.view); self.setUpData(data: dataDictionary!) MBProgressHUD.hideAllHUDs(for: self.view, animated: true) } }) { (err) in DispatchQueue.main.async { MBProgressHUD.hideAllHUDs(for: self.view, animated: true) NSLog(" %@", err) } } } } extension SettingViewController: UIPickerViewDelegate{ }
41.174641
196
0.615014
0ae51ad8606156e560d2510dedc01ff680266ee5
1,612
// // Amazing_meteorApp.swift // Amazing meteor // // Created by venus on 9/20/21. // import SwiftUI @main struct Amazing_meteorApp: App { //@ObservedObject var meteorViewModel = MeteorViewModel() init() { configureTheme() } var body: some Scene { WindowGroup { NavigationView { //MainView(meteors: $meteorViewModel.meteors) MainView() } } } private func configureTheme() { //set the color of the navigationbar UINavigationBar.appearance().tintColor = UIColor.BarBgClr UINavigationBar.appearance().barTintColor = UIColor.BarBgClr //set the navigationbar's title color and font UINavigationBar.appearance().titleTextAttributes = [.font : UIFont.navBarTitleFont!, .foregroundColor : UIColor.white] //set the color of the UITabBar UITabBar.appearance().backgroundColor = UIColor.BarBgClr UITabBar.appearance().barTintColor = UIColor.BarBgClr //set the color of the UISegmentedControl UISegmentedControl.appearance().selectedSegmentTintColor = .SegmentedSelClr UISegmentedControl.appearance().backgroundColor = .SegmentedBgClr UISegmentedControl.appearance().setTitleTextAttributes([.font: UIFont.segmentTextFont!, .foregroundColor: UIColor.TitleClr], for: .selected) UISegmentedControl.appearance().setTitleTextAttributes([.font: UIFont.segmentTextFont!, .foregroundColor: UIColor.TitleClr], for: .normal) UITableView.appearance().backgroundColor = UIColor.ViewBkClr } }
36.636364
148
0.67928
edef778d936d298cb58b90a6bef5178fd5a38330
18,041
// // File.swift // PerfectLib // // Created by Kyle Jessup on 7/7/15. // Copyright (C) 2015 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // #if os(Linux) import LinuxBridge // !FIX! these are obviously sketchy // I hope SwiftGlibc to eventually include these // Otherwise, export them from LinuxBridge import var Glibc.S_IRUSR import var Glibc.S_IWUSR import var Glibc.S_IXUSR import var Glibc.S_IFMT import var Glibc.S_IFREG import var Glibc.S_IFDIR import var Glibc.S_IFLNK let S_IRGRP = (S_IRUSR >> 3) let S_IWGRP = (S_IWUSR >> 3) let S_IXGRP = (S_IXUSR >> 3) let S_IRWXU = (__S_IREAD|__S_IWRITE|__S_IEXEC) let S_IRWXG = (S_IRWXU >> 3) let S_IRWXO = (S_IRWXG >> 3) let S_IROTH = (S_IRGRP >> 3) let S_IWOTH = (S_IWGRP >> 3) let S_IXOTH = (S_IXGRP >> 3) let SEEK_CUR: Int32 = 1 let EXDEV = Int32(18) let EACCES = Int32(13) let EAGAIN = Int32(11) let F_OK: Int32 = 0 #else import Darwin #endif let fileCopyBufferSize = 16384 /// Provides access to a file on the local file system public class File { /// The underlying file system descriptor. public var fd = -1 var internalPath = "" /// Checks that the file exists on the file system /// - returns: True if the file exists or false otherwise public var exists: Bool { return access(internalPath, F_OK) != -1 } /// Returns true if the file has been opened public var isOpen: Bool { return fd != -1 } /// Returns the file's path public var path: String { return internalPath } /// Returns the file path. If the file is a symbolic link, the link will be resolved. public var realPath: String { let maxPath = 2048 guard isLink else { return internalPath } var ary = [UInt8](repeating: 0, count: maxPath) let res: Int = ary.withUnsafeMutableBytes { guard let p = $0.bindMemory(to: Int8.self).baseAddress else { return -1 } return readlink(internalPath, p, maxPath) } guard res != -1 else { return internalPath } let trailPath = String(cString: ary) let lastChar = trailPath[trailPath.startIndex] guard lastChar != "/" && lastChar != "." else { return trailPath } return internalPath.deletingLastFilePathComponent + "/" + trailPath } /// Returns the modification date for the file in the standard UNIX format of seconds since 1970/01/01 00:00:00 GMT /// - returns: The date as Int public var modificationTime: Int { var st = stat() let res = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st) guard res == 0 else { return Int.max } #if os(Linux) return Int(st.st_mtim.tv_sec) #else return Int(st.st_mtimespec.tv_sec) #endif } static func resolveTilde(inPath: String) -> String { #if !os(iOS) && !os(tvOS) if !inPath.isEmpty && inPath[inPath.startIndex] == "~" { var wexp = wordexp_t() guard 0 == wordexp(inPath, &wexp, 0), let we_wordv = wexp.we_wordv else { return inPath } defer { wordfree(&wexp) } if let resolved = we_wordv[0], let pth = String(validatingUTF8: resolved) { return pth } } #endif return inPath } /// Create a file object given a path and open mode /// - parameter path: Path to the file which will be accessed /// - parameter fd: The file descriptor, if any, for an already opened file public init(_ path: String, fd: Int32 = -1) { internalPath = File.resolveTilde(inPath: path) self.fd = Int(fd) } deinit { close() } /// Closes the file if it had been opened public func close() { if fd != -1 { #if os(Linux) _ = SwiftGlibc.close(CInt(fd)) #else _ = Darwin.close(CInt(fd)) #endif fd = -1 } } /// Resets the internal file descriptor, leaving the file opened if it had been. public func abandon() { fd = -1 } } public extension File { /// The open mode for the file. enum OpenMode { /// Opens the file for read-only access. case read /// Opens the file for write-only access, creating the file if it did not exist. case write /// Opens the file for read-write access, creating the file if it did not exist. case readWrite /// Opens the file for read-write access, creating the file if it did not exist and moving the file marker to the end. case append /// Opens the file for read-write access, creating the file if it did not exist and setting the file's size to zero. case truncate var toMode: Int { switch self { case .read: return Int(O_RDONLY) case .write: return Int(O_WRONLY|O_CREAT) case .readWrite: return Int(O_RDWR|O_CREAT) case .append: return Int(O_RDWR|O_APPEND|O_CREAT) case .truncate: return Int(O_RDWR|O_TRUNC|O_CREAT) } } } /// A file or directory access permission value. struct PermissionMode: OptionSet { /// File system mode type. public typealias Mode = mode_t /// The raw mode. public let rawValue: Mode /// Create a permission mode with a raw value. public init(rawValue: Mode) { self.rawValue = rawValue } #if os(Linux) init(rawValue: Int32) { self.init(rawValue: UInt32(rawValue)) } #endif /// Readable by user. public static let readUser = PermissionMode(rawValue: S_IRUSR) /// Writable by user. public static let writeUser = PermissionMode(rawValue: S_IWUSR) /// Executable by user. public static let executeUser = PermissionMode(rawValue: S_IXUSR) /// Readable by group. public static let readGroup = PermissionMode(rawValue: S_IRGRP) /// Writable by group. public static let writeGroup = PermissionMode(rawValue: S_IWGRP) /// Executable by group. public static let executeGroup = PermissionMode(rawValue: S_IXGRP) /// Readable by others. public static let readOther = PermissionMode(rawValue: S_IROTH) /// Writable by others. public static let writeOther = PermissionMode(rawValue: S_IWOTH) /// Executable by others. public static let executeOther = PermissionMode(rawValue: S_IXOTH) /// Read, write, execute by user. public static let rwxUser: PermissionMode = [.readUser, .writeUser, .executeUser] /// Read, write by user and group. public static let rwUserGroup: PermissionMode = [.readUser, .writeUser, .readGroup, .writeGroup] /// Read, execute by group. public static let rxGroup: PermissionMode = [.readGroup, .executeGroup] /// Read, execute by other. public static let rxOther: PermissionMode = [.readOther, .executeOther] } /// Opens the file using the given mode. /// - throws: `PerfectError.FileError` func open(_ mode: OpenMode = .read, permissions: PermissionMode = .rwUserGroup) throws { if fd != -1 { close() } #if os(Linux) let openFd = linux_open(internalPath, CInt(mode.toMode), permissions.rawValue) #else let openFd = Darwin.open(internalPath, CInt(mode.toMode), permissions.rawValue) #endif guard openFd != -1 else { try ThrowFileError() } fd = Int(openFd) } } public extension File { /// The current file read/write position. var marker: Int { /// Returns the value of the file's current position marker get { if isOpen { return Int(lseek(Int32(fd), 0, SEEK_CUR)) } return 0 } /// Sets the file's position marker given the value as measured from the begining of the file. set { lseek(Int32(fd), off_t(newValue), SEEK_SET) } } } public extension File { /// Closes and deletes the file func delete() { close() unlink(path) } /// Moves the file to the new location, optionally overwriting any existing file /// - parameter path: The path to move the file to /// - parameter overWrite: Indicates that any existing file at the destination path should first be deleted /// - returns: Returns a new file object representing the new location /// - throws: `PerfectError.FileError` func moveTo(path: String, overWrite: Bool = false) throws -> File { let destFile = File(path) if destFile.exists { guard overWrite else { throw PerfectError.fileError(-1, "Can not overwrite existing file") } destFile.delete() } close() let res = rename(self.path, path) if res == 0 { return destFile } if errno == EXDEV { _ = try copyTo(path: path, overWrite: overWrite) delete() return destFile } try ThrowFileError() } /// Copies the file to the new location, optionally overwriting any existing file /// - parameter path: The path to copy the file to /// - parameter overWrite: Indicates that any existing file at the destination path should first be deleted /// - returns: Returns a new file object representing the new location /// - throws: `PerfectError.FileError` @discardableResult func copyTo(path pth: String, overWrite: Bool = false) throws -> File { let destFile = File(pth) if destFile.exists { guard overWrite else { throw PerfectError.fileError(-1, "Can not overwrite existing file") } destFile.delete() } let wasOpen = isOpen let oldMarker = marker if !wasOpen { try open() } else { _ = marker = 0 } defer { if !wasOpen { close() } else { _ = marker = oldMarker } } try destFile.open(.truncate) var bytes = try readSomeBytes(count: fileCopyBufferSize) while bytes.count > 0 { try destFile.write(bytes: bytes) bytes = try readSomeBytes(count: fileCopyBufferSize) } destFile.close() return destFile } } public extension File { /// Returns the size of the file in bytes var size: Int { var st = stat() let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st) guard statRes != -1 else { return 0 } return Int(st.st_size) } /// Returns true if the file is actually a directory var isDir: Bool { var st = stat() let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st) guard statRes != -1 else { return false } let mode = st.st_mode return (Int32(mode) & Int32(S_IFMT)) == Int32(S_IFDIR) } /// Returns the UNIX style permissions for the file var perms: PermissionMode { get { var st = stat() let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st) guard statRes != -1 else { return PermissionMode(rawValue: PermissionMode.Mode(0)) } let mode = st.st_mode return PermissionMode(rawValue: mode_t(Int32(mode) ^ Int32(S_IFMT))) } set { _ = chmod(internalPath, newValue.rawValue) } } } public extension File { /// Returns true if the file is a symbolic link var isLink: Bool { var st = stat() let statRes = lstat(internalPath, &st) guard statRes != -1 else { return false } let mode = st.st_mode return (Int32(mode) & Int32(S_IFMT)) == Int32(S_IFLNK) } /// Create a symlink from the target to the destination. @discardableResult func linkTo(path: String, overWrite: Bool = false) throws -> File { let destFile = File(path) if destFile.exists { guard overWrite else { throw PerfectError.fileError(-1, "Can not overwrite existing file") } destFile.delete() } let res = symlink(self.path, path) if res == 0 { return File(path) } try ThrowFileError() } } public extension File { /// Reads up to the indicated number of bytes from the file /// - parameter count: The maximum number of bytes to read /// - returns: The bytes read as an array of UInt8. May have a count of zero. /// - throws: `PerfectError.FileError` func readSomeBytes(count: Int) throws -> [UInt8] { if !isOpen { try open() } func sizeOr(_ value: Int) -> Int { var st = stat() let statRes = isOpen ? fstat(Int32(fd), &st) : stat(internalPath, &st) guard statRes != -1 else { return 0 } if (Int32(st.st_mode) & Int32(S_IFMT)) == Int32(S_IFREG) { return Int(st.st_size) } return value } let bSize = min(count, sizeOr(count)) var ary = [UInt8](repeating: 0, count: bSize) let readCount = ary.withUnsafeMutableBytes { read(CInt(fd), $0.bindMemory(to: Int8.self).baseAddress, bSize) } guard readCount >= 0 else { try ThrowFileError() } if readCount < bSize { ary.removeLast(bSize - readCount) } return ary } /// Reads the entire file as a string func readString() throws -> String { let bytes = try readSomeBytes(count: size) return UTF8Encoding.encode(bytes: bytes) } } public extension File { /// Writes the string to the file using UTF-8 encoding /// - parameter s: The string to write /// - returns: Returns the number of bytes which were written /// - throws: `PerfectError.FileError` @discardableResult func write(string: String) throws -> Int { return try write(bytes: Array(string.utf8)) } /// Write the indicated bytes to the file /// - parameter bytes: The array of UInt8 to write. /// - parameter dataPosition: The offset within `bytes` at which to begin writing. /// - parameter length: The number of bytes to write. /// - throws: `PerfectError.FileError` @discardableResult func write(bytes: [UInt8], dataPosition: Int = 0, length: Int = Int.max) throws -> Int { let len = min(bytes.count - dataPosition, length) #if os(Linux) let wrote = bytes.withUnsafeBytes { SwiftGlibc.write(Int32(fd), $0.bindMemory(to: Int8.self).baseAddress?.advanced(by: dataPosition), len) } #else let wrote = bytes.withUnsafeBytes { Darwin.write(Int32(fd), $0.bindMemory(to: Int8.self).baseAddress?.advanced(by: dataPosition), len) } #endif guard wrote == len else { try ThrowFileError() } return wrote } } public extension File { /// Attempts to place an advisory lock starting from the current position marker up to the indicated byte count. This function will block the current thread until the lock can be performed. /// - parameter byteCount: The number of bytes to lock /// - throws: `PerfectError.FileError` func lock(byteCount: Int) throws { if !isOpen { try open(.write) } let res = lockf(Int32(fd), F_LOCK, off_t(byteCount)) guard res == 0 else { try ThrowFileError() } } /// Unlocks the number of bytes starting from the current position marker up to the indicated byte count. /// - parameter byteCount: The number of bytes to unlock /// - throws: `PerfectError.FileError` func unlock(byteCount: Int) throws { if !isOpen { try open(.write) } let res = lockf(Int32(fd), F_ULOCK, off_t(byteCount)) guard res == 0 else { try ThrowFileError() } } /// Attempts to place an advisory lock starting from the current position marker up to the indicated byte count. This function will throw an exception if the file is already locked, but will not block the current thread. /// - parameter byteCount: The number of bytes to lock /// - throws: `PerfectError.FileError` func tryLock(byteCount: Int) throws { if !isOpen { try open(.write) } let res = lockf(Int32(fd), F_TLOCK, off_t(byteCount)) guard res == 0 else { try ThrowFileError() } } /// Tests if the indicated bytes are locked /// - parameter byteCount: The number of bytes to test /// - returns: True if the file is locked /// - throws: `PerfectError.FileError` func testLock(byteCount: Int) throws -> Bool { if !isOpen { try open(.write) } let res = Int(lockf(Int32(fd), F_TEST, off_t(byteCount))) guard res == 0 || res == Int(EACCES) || res == Int(EAGAIN) else { try ThrowFileError() } return res != 0 } } // Subclass to represent a file which can not be closed private final class UnclosableFile : File { override init(_ path: String, fd: Int32) { super.init(path, fd: fd) } override func close() { // nothing } } /// A temporary, randomly named file. public final class TemporaryFile: File { /// Create a temporary file, usually in the system's /tmp/ directory /// - parameter withPrefix: The prefix for the temporary file's name. Random characters will be appended to the file's eventual name. public convenience init(withPrefix: String) { let template = withPrefix + "XXXXXX" let utf8 = template.utf8 let name = UnsafeMutablePointer<Int8>.allocate(capacity: utf8.count + 1) var i = utf8.startIndex for index in 0..<utf8.count { name[index] = Int8(utf8[i]) i = utf8.index(after: i) } name[utf8.count] = 0 let fd = mkstemp(name) let tmpFileName = String(validatingUTF8: name)! name.deallocate() self.init(tmpFileName, fd: fd) } } /// This file can be used to write to standard in public var fileStdin: File { return UnclosableFile("/dev/stdin", fd: STDIN_FILENO) } /// This file can be used to write to standard out public var fileStdout: File { return UnclosableFile("/dev/stdout", fd: STDOUT_FILENO) } /// This file can be used to write to standard error public var fileStderr: File { return UnclosableFile("/dev/stderr", fd: STDERR_FILENO) }
29.91874
221
0.634776
6af102ed90ed406be9de8a78a4eae8590b20dfc8
1,867
// // ViewController.swift // Test Table View // // Created by Thyago on 1/19/17. // Copyright © 2017 Thyago Stall Araujo. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { private var items = ["Amanda", "Cheryl", "Stephanie", "Johnny", "Edward", "Diana", "Laura", "Amy", "Louis", "Denise", "William", "Antonio", "Walter", "Louise", "Eugene"] @IBOutlet private weak var table: UITableView! override func viewDidLoad() { super.viewDidLoad() table.dataSource = self table.delegate = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell cell.set(text: items[indexPath.item]) return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { items.remove(at: indexPath.item) tableView.deleteRows(at: [indexPath], with: .automatic) } } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let defaultRowAction = UITableViewRowAction(style: .normal, title: "Set Default", handler: {action, indexpath in }); let deleteRowAction = UITableViewRowAction(style: .destructive, title: "Delete", handler:{action, indexpath in self.tableView(tableView, commit: .delete, forRowAt: indexPath) }); return [deleteRowAction, defaultRowAction]; } }
33.945455
173
0.651312
48bfc7f36f8bd0a8869170363b86fc8cb65e03cb
1,302
// // MulticastDelegate.swift // // Created by Michael Wybrow on 23/3/19. // Copyright © 2019 Monash University. All rights reserved. // import Foundation class MulticastDelegate <T> { private var delegates = Set<WeakObjectWrapper>() func addDelegate(_ delegate: T) { let delegateObject = delegate as AnyObject delegates.insert(WeakObjectWrapper(value: delegateObject)) } func removeDelegate(_ delegate: T) { let delegateObject = delegate as AnyObject delegates.remove(WeakObjectWrapper(value: delegateObject)) } func invoke(invocation: (T) -> ()) { delegates.forEach { (delegateWrapper) in if let delegate = delegateWrapper.value { invocation(delegate as! T) } } } } private class WeakObjectWrapper: Equatable, Hashable { weak var value: AnyObject? init(value: AnyObject) { self.value = value } // Hash based on the address (pointer) of the value. var hashValue: Int { return ObjectIdentifier(value!).hashValue } // Equate based on equality of the value pointers of two wrappers. static func == (lhs: WeakObjectWrapper, rhs: WeakObjectWrapper) -> Bool { return lhs.value === rhs.value } }
26.571429
77
0.634409
2658cef766739eed4405919816749858bc7e901c
145
public protocol Pagination: Codable { associatedtype Content: Codable var items: [Content] { get } var hasNext: Bool { get } }
18.125
37
0.648276
16e2807cb6eca91ffdaa2f7158642e97625f0ed5
859
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "random-word", platforms: [ .macOS(.v11), ], products: [ .executable(name: "random-word", targets: ["random-word"]), .library(name: "RandomWord", targets: ["RandomWord"]), ], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0"), ], targets: [ .target( name: "RandomWord", dependencies: [] ), .target( name: "random-word", dependencies: [ "RandomWord", .product(name: "ArgumentParser", package: "swift-argument-parser"), ] ), .testTarget( name: "random-wordTests", dependencies: ["random-word"] ), ] )
24.542857
87
0.498254
bfe59f03e23b332bb72a2f7bfcd321ab08ed56f6
342
// // BaseNavController.swift // RestorableApp // // Created by Eddie on 2019/03/22. // Copyright © 2019 Eddie. All rights reserved. // import UIKit class BaseNavController: UINavigationController { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) restorationIdentifier = className } }
19
49
0.681287
29fe104ddd126428ee1b5625b874fedd31330d41
1,595
// From: https://medium.com/@kewindannerfjordremeczki/swift-4-0-decodable-heterogeneous-collections-ecc0e6b468cf import Foundation /// To support a new class family, create an enum that conforms to this protocol and contains the different types. protocol ClassFamily: Decodable { /// The discriminator key. static var discriminator: Discriminator { get } /// Returns the class type of the object corresponding to the value. func getType() -> AnyObject.Type } /// Discriminator key enum used to retrieve discriminator fields in JSON payloads. enum Discriminator: String, CodingKey { case type = "ty" } extension KeyedDecodingContainer { /// Decode a heterogeneous list of objects for a given family. /// - Parameters: /// - heterogeneousType: The decodable type of the list. /// - family: The ClassFamily enum for the type family. /// - key: The CodingKey to look up the list in the current container. /// - Returns: The resulting list of heterogeneousType elements. func decode<T : Decodable, U : ClassFamily>(_ heterogeneousType: [T].Type, ofFamily family: U.Type, forKey key: K) throws -> [T] { var container = try self.nestedUnkeyedContainer(forKey: key) var list = [T]() var tmpContainer = container while !container.isAtEnd { let typeContainer = try container.nestedContainer(keyedBy: Discriminator.self) let family: U = try typeContainer.decode(U.self, forKey: U.discriminator) if let type = family.getType() as? T.Type { list.append(try tmpContainer.decode(type)) } } return list } }
38.902439
132
0.711599
d511009e42360c2b7b09eaa84bf30a8f9e4eb740
4,829
// // FAQAPI.swift // DroidconBoston // // Created by Justin Poliachik on 4/3/17. // Copyright © 2017 Droidcon Boston. All rights reserved. // import Foundation import Alamofire struct FAQItem { var question: String var answer: String var photoUrl: String? var mapUrl: String? var otherUrl: String? init?(json: [String: Any]) throws { guard let question = FAQItem.getDataFromKey(key: "gsx$question", json: json) else { throw SerializationError.missing("gsx$question") } guard let answer = FAQItem.getDataFromKey(key: "gsx$answers", json: json) else { throw SerializationError.missing("gsx$answers") } let photoUrl = FAQItem.getDataFromKey(key: "gsx$photolink", json: json) let mapUrl = FAQItem.getDataFromKey(key: "gsx$maplink", json: json) let otherUrl = FAQItem.getDataFromKey(key: "gsx$otherlink", json: json) self.question = question self.answer = answer self.photoUrl = photoUrl self.mapUrl = mapUrl self.otherUrl = otherUrl } static func getDataFromKey(key: String, json: [String: Any]) -> String? { if let item = json[key] as? [String: Any] { // spreadsheet api embeds the value inside '$t' key if let value = item["$t"] as? String { if value.characters.count > 0 { return value } } } return nil; } } struct FAQAPI { static func getSavedFileLocation() -> URL { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let fileURL = documentsURL.appendingPathComponent("FAQData.json") return fileURL } static func getFAQ(callback:@escaping (([FAQItem]?) -> Void)) { var fileLocation: URL let fileExists = (try? getSavedFileLocation().checkResourceIsReachable()) ?? false if fileExists { fileLocation = getSavedFileLocation() } else { fileLocation = Bundle.main.url(forResource: "DefaultFAQ", withExtension: "json")! } FAQAPI.getFAQAtPath(path: fileLocation) { (results) in callback(results) } } static func downloadFAQ(callback:@escaping ((Bool) -> Void)) { let url = "https://spreadsheets.google.com/feeds/list/1Cx6aAfj4N9K8UPUPhVq-5vJ9XAQQhWyln3qh_K-dSZg/2/public/values?alt=json" let destination: DownloadRequest.DownloadFileDestination = { _, _ in return (getSavedFileLocation(), [.removePreviousFile, .createIntermediateDirectories]) } Alamofire.download(url, to: destination).response { response in let success = (response.error == nil) callback(success) } } static func getFAQAtPath(path: URL, callback:@escaping (([FAQItem]?) -> Void)) { do { let jsonData = try Data(contentsOf: path) let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any] FAQAPI.parseJson(json: json, callback: { (results) in callback(results) }) return; } catch { print(error.localizedDescription) callback(nil) } } static func createTableData(items: [FAQItem]) -> (sections: [String], rows: [[FAQItem]]) { // group FAQ by common questions var sections: [String] = [] var rows: [[FAQItem]] = [] for item in items { let question = item.question if let index = sections.index(of: question) { // existing question rows[index].append(item) } else { // new question sections.append(question) rows.append([item]) } } return (sections, rows) } static func parseJson(json: [String: Any], callback:@escaping (([FAQItem]?) -> Void)) { guard let feed = json["feed"] as? [String: Any] else { callback(nil) return } guard let entries = feed["entry"] as? [Any] else { callback(nil) return } do { var results: [FAQItem] = [] for case let entryJson as [String: Any] in entries { if let entry = try FAQItem(json: entryJson) { results.append(entry) } } callback(results) } catch { print(error.localizedDescription) callback(nil) } } }
31.357143
132
0.543591
2985b0edea42e5329b47322d79597940c4c738c5
1,633
// // SettingsController.swift // ChromaProjectApp // // Created by Boolky Bear on 26/12/14. // Copyright (c) 2014 ByBDesigns. All rights reserved. // import UIKit typealias SettingsChangeHandler = (SaveSettings) -> Void class SettingsController: UITableViewController { @IBOutlet var localCell: UITableViewCell! @IBOutlet var iCloudCell: UITableViewCell! @IBOutlet var localButton: UIButton! @IBOutlet var iCloudButton: UIButton! var settingsChange: SettingsChangeHandler? = nil var isiCloudEnabled: Bool = false func changeSettings(saveSettings: SaveSettings) { self.refreshCellMarksWithSettings(saveSettings) NSUserDefaults.setSaveSettings(saveSettings) if let change = self.settingsChange { change(saveSettings) } } func enableiCloud(enabled: Bool) { self.isiCloudEnabled = enabled if let button = self.iCloudButton { button.enabled = enabled } } override func viewDidLoad() { super.viewDidLoad() self.iCloudButton.enabled = self.isiCloudEnabled self.refreshCellMarksWithSettings(NSUserDefaults.saveSettings()) } } // MARK: Actions extension SettingsController { @IBAction func localButtonClicked(sender: AnyObject) { self.changeSettings(.SaveLocally) } @IBAction func iCloudButtonClicked(sender: AnyObject) { self.changeSettings(.SaveInCloud) } } // Helpers extension SettingsController { func refreshCellMarksWithSettings(saveSettings: SaveSettings) { self.localCell.accessoryType = saveSettings == SaveSettings.SaveLocally ? .Checkmark : .None self.iCloudCell.accessoryType = saveSettings == SaveSettings.SaveInCloud ? .Checkmark : .None } }
23
95
0.763625
2155854046f0f1105088fb8c82def2f6ae9ec20b
18,041
// // UIButton+Extension.swift // TTAUtils_Swift // // Created by TobyoTenma on 03/03/2017. // Copyright © 2017 TobyoTenma. All rights reserved. // import UIKit import Kingfisher /// Custom Layout UIButton /// /// - `default`: Default Layout /// - imageRightTitleLeft: Image on the right, and title on the left, align centre, margin is paddig /// - imageTopTitleBottom: Image on the top, and title on the bottom, align centre, margin is paddig /// - imageBottomTitleTop: Image on the bottom, and title on the top, align centre, margin is paddig /// - imageCenterTitleTop: Image on the button right center, and title on the top of the image, margin is paddig /// - imageCenterTitleBottom: Image on the button right center, and title on the bottom of the image, margin is paddig /// - imageCenterTitleTopToButton: Image on the button right center, and title on the top of the image, margin to the button top is paddig /// - imageCenterTitleBottomToButton: Image on the button right center, and title on the bottom of the image, margin to the button bottom is paddig public enum UIButtonLayoutType: Int { case `default` = 0 case imageRightTitleLeft case imageTopTitleBottom case imageBottomTitleTop case imageCenterTitleTop case imageCenterTitleBottom case imageCenterTitleTopToButton case imageCenterTitleBottomToButton } private struct AssociateKey { static var layoutType = "UIButtonLayoutType" static var layoutTypePadding = "UIButtonLayoutTypePadding" } extension UIButton { convenience init(title: String? = nil, titleColor: UIColor = UIColor.darkGray, imageName: String? = nil, backgroundImageName: String? = nil, font: UIFont = UIFont.systemFont(ofSize: 13), target: Any? = nil, action: Selector? = nil, event: UIControlEvents = .touchUpInside){ self.init() if let title = title { self.setTitle(title, for: .normal) self.setTitleColor(titleColor, for: .normal) self.titleLabel?.font = font } if let imageName = imageName { self.setImage(UIImage(named: imageName), for: .normal) self.setImage(UIImage(named: "\(imageName)_sel"), for: .highlighted) } if let backgroundImageName = backgroundImageName { self.setBackgroundImage(UIImage(named: backgroundImageName), for: .normal) self.setBackgroundImage(UIImage(named: backgroundImageName), for: .highlighted) } if let target = target, let action = action { let selector = action self.addTarget(target, action: selector, for: event) } self.sizeToFit() } } // MARK: - KingFisher Package extension TTAUtils where Base: UIButton { public func setImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil){ _ = base.setImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } public func cancelImageDownloadTask() { base.cancelImageDownloadTask() } public func setBackgroundImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) { _ = base.setBackgroundImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } public func cancelBackgroundImageDownloadTask() { base.cancelBackgroundImageDownloadTask() } } fileprivate extension UIButton { func setImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } func cancelImageDownloadTask() { kf.cancelImageDownloadTask() } func setBackgroundImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setBackgroundImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } func cancelBackgroundImageDownloadTask() { kf.cancelBackgroundImageDownloadTask() } } // MARK: - CustomLayout fileprivate var kLayoutType: UIButtonLayoutType = .default fileprivate var kLayoutTypePadding : CGFloat = 0 extension TTAUtils where Base: UIButton { /// Custom UIButtonLayoutType open var layoutType: UIButtonLayoutType { get { return kLayoutType } set { setLayoutType(type: newValue, padding: self.layoutTypePadding) } } /// Custom UIButtonLayoutType padding open var layoutTypePadding: CGFloat { get { return kLayoutTypePadding } set { setLayoutType(type: self.layoutType, padding: newValue) } } /// Set custom UIButtonLayoutType and padding /// /// - Parameters: /// - type: layout type /// - padding: padding open func setLayoutType(type: UIButtonLayoutType, padding: CGFloat = 0.0) { kLayoutType = type kLayoutTypePadding = padding base.titleEdgeInsets = UIEdgeInsets.zero base.imageEdgeInsets = UIEdgeInsets.zero let imageRect = (base.imageView?.frame)! let titleRect = (base.titleLabel?.frame)! let totalHeight = imageRect.size.height + padding + titleRect.size.height let selfHeight = base.frame.size.height; let selfWidth = base.frame.size.width; switch type { case .default: if (padding != 0) { base.titleEdgeInsets = UIEdgeInsetsMake(0, padding / 2, 0, -padding / 2); base.imageEdgeInsets = UIEdgeInsetsMake(0, -padding / 2, 0, padding / 2); } case .imageRightTitleLeft: //图片在右,文字在左 base.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageRect.size.width + padding / 2), 0, (imageRect.size.width + padding / 2)); base.imageEdgeInsets = UIEdgeInsetsMake(0, (titleRect.size.width + padding / 2), 0, -(titleRect.size.width + padding / 2)); case .imageTopTitleBottom: //图片在上,文字在下 base.titleEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight) / 2 + imageRect.size.height + padding - titleRect.origin.y), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -((selfHeight - totalHeight) / 2 + imageRect.size.height + padding - titleRect.origin.y), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); base.imageEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight) / 2 - imageRect.origin.y), (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), -((selfHeight - totalHeight) / 2 - imageRect.origin.y), -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageBottomTitleTop: //图片在下,文字在上。 base.titleEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight) / 2 - titleRect.origin.y), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -((selfHeight - totalHeight) / 2 - titleRect.origin.y), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); base.imageEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight) / 2 + titleRect.size.height + padding - imageRect.origin.y), (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), -((selfHeight - totalHeight) / 2 + titleRect.size.height + padding - imageRect.origin.y), -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageCenterTitleTop: base.titleEdgeInsets = UIEdgeInsetsMake(-(titleRect.origin.y - padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, (titleRect.origin.y - padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); base.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageCenterTitleBottom: base.titleEdgeInsets = UIEdgeInsetsMake((selfHeight - padding - titleRect.origin.y - titleRect.size.height), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -(selfHeight - padding - titleRect.origin.y - titleRect.size.height), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); base.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageCenterTitleTopToButton: base.titleEdgeInsets = UIEdgeInsetsMake(-(titleRect.origin.y + titleRect.size.height - imageRect.origin.y + padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, (titleRect.origin.y + titleRect.size.height - imageRect.origin.y + padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); base.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageCenterTitleBottomToButton: base.titleEdgeInsets = UIEdgeInsetsMake((imageRect.origin.y + imageRect.size.height - titleRect.origin.y + padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -(imageRect.origin.y + imageRect.size.height - titleRect.origin.y + padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); base.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); } } } // MARK: - Deprecated // MARK: - extension UIButton { /// Custom UIButtonLayoutType @available(*, deprecated, message: "Extessions directly on UIButton are deprecated. Use `button.tta.layoutType` instead", renamed: "tta.layoutType") open var layoutType: UIButtonLayoutType { get { return kLayoutType } set { tta.setLayoutType(type: newValue, padding: self.layoutTypePadding) } } /// Custom UIButtonLayoutType padding @available(*, deprecated, message: "Extessions directly on UIButton are deprecated. Use `button.tta.layoutTypePadding` instead", renamed: "tta.layoutTypePadding") open var layoutTypePadding: CGFloat { get { return kLayoutTypePadding } set { tta.setLayoutType(type: self.layoutType, padding: newValue) } } /// Set custom UIButtonLayoutType and padding /// /// - Parameters: /// - type: layout type /// - padding: padding @available(*, deprecated, message: "Extessions directly on UIButton are deprecated. Use `button.tta.setLayoutType` instead", renamed: "tta.setLayoutType") open func setLayoutType(type: UIButtonLayoutType, padding: CGFloat = 0.0) { kLayoutType = type kLayoutTypePadding = padding titleEdgeInsets = UIEdgeInsets.zero imageEdgeInsets = UIEdgeInsets.zero let imageRect = (imageView?.frame)! let titleRect = (titleLabel?.frame)! let totalHeight = imageRect.size.height + padding + titleRect.size.height let selfHeight = frame.size.height; let selfWidth = frame.size.width; switch type { case .default: if (padding != 0) { self.titleEdgeInsets = UIEdgeInsetsMake(0, padding / 2, 0, -padding / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, -padding / 2, 0, padding / 2); } case .imageRightTitleLeft: //图片在右,文字在左 self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageRect.size.width + padding / 2), 0, (imageRect.size.width + padding / 2)); self.imageEdgeInsets = UIEdgeInsetsMake(0, (titleRect.size.width + padding / 2), 0, -(titleRect.size.width + padding / 2)); case .imageTopTitleBottom: //图片在上,文字在下 self.titleEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight) / 2 + imageRect.size.height + padding - titleRect.origin.y), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -((selfHeight - totalHeight) / 2 + imageRect.size.height + padding - titleRect.origin.y), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight) / 2 - imageRect.origin.y), (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), -((selfHeight - totalHeight) / 2 - imageRect.origin.y), -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageBottomTitleTop: //图片在下,文字在上。 self.titleEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight) / 2 - titleRect.origin.y), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -((selfHeight - totalHeight) / 2 - titleRect.origin.y), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(((selfHeight - totalHeight) / 2 + titleRect.size.height + padding - imageRect.origin.y), (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), -((selfHeight - totalHeight) / 2 + titleRect.size.height + padding - imageRect.origin.y), -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageCenterTitleTop: self.titleEdgeInsets = UIEdgeInsetsMake(-(titleRect.origin.y - padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, (titleRect.origin.y - padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageCenterTitleBottom: self.titleEdgeInsets = UIEdgeInsetsMake((selfHeight - padding - titleRect.origin.y - titleRect.size.height), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -(selfHeight - padding - titleRect.origin.y - titleRect.size.height), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageCenterTitleTopToButton: self.titleEdgeInsets = UIEdgeInsetsMake(-(titleRect.origin.y + titleRect.size.height - imageRect.origin.y + padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, (titleRect.origin.y + titleRect.size.height - imageRect.origin.y + padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); case .imageCenterTitleBottomToButton: self.titleEdgeInsets = UIEdgeInsetsMake((imageRect.origin.y + imageRect.size.height - titleRect.origin.y + padding), (selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2, -(imageRect.origin.y + imageRect.size.height - titleRect.origin.y + padding), -(selfWidth / 2 - titleRect.origin.x - titleRect.size.width / 2) - (selfWidth - titleRect.size.width) / 2); self.imageEdgeInsets = UIEdgeInsetsMake(0, (selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2), 0, -(selfWidth / 2 - imageRect.origin.x - imageRect.size.width / 2)); } } }
60.949324
444
0.652403
ab2a503bef3eabbc0d88678f8b809d66c93a9dd8
2,001
// Copyright (c) 2018-2021 InSeven Limited // // 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 import FileawayCore class VariableState: ObservableObject, Identifiable, Hashable { var id = UUID() @Published var name: String @Published var type: VariableType public init(_ variable: Variable) { self.name = variable.name self.type = variable.type } public init(_ variableState: VariableState) { id = UUID() name = String(variableState.name) type = variableState.type } public init(name: String, type: VariableType) { self.name = name self.type = type } static func == (lhs: VariableState, rhs: VariableState) -> Bool { return lhs.id == rhs.id } func hash(into hasher: inout Hasher) { hasher.combine(id) } } extension Variable { init(_ state: VariableState) { self.init(name: state.name, type: state.type) } }
31.265625
81
0.701149
d64803fbb421e7613a7d624b6e01f186837a5e51
3,692
// // ViewController.swift // TraningTimer // // Created by Guilherme Ogliari on 25/05/17. // Copyright © 2017 Guilherme Ogliari. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var lblRepeticoes: UILabel! @IBOutlet weak var lblDescanso: UILabel! @IBOutlet weak var lblContTempo: UILabel! @IBOutlet weak var lblContRepeticoes: UILabel! @IBOutlet weak var sldRepeticoes: UISlider! @IBOutlet weak var sldTempo: UISlider! @IBOutlet weak var btnStart: UIButton! var repeticoes: Int = 1 var tempo: Int = 10 var hora: Int = 0 var minuto: Int = 0 var segundos: Int = 0 var tempoDec: Int = 0 var timer = Timer() let generator = UIImpactFeedbackGenerator(style: .heavy) override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func sldChangeRepeat(_ sender: UISlider) { if(Int(sender.value) != 1){ lblRepeticoes.text = String(Int(sender.value))+" Séries" }else{ lblRepeticoes.text = String(Int(sender.value))+" Série" } lblContRepeticoes.text = String(Int(sender.value)) repeticoes = Int(sender.value) } @IBAction func sldChangeTime(_ sender: UISlider) { if(Int(sender.value) < 60){ lblDescanso.text = String(Int(sender.value))+" Segundos de descanso" }else if(Int(sender.value) >= 60 && Int(sender.value) < 120 ){ if(((Int(sender.value) % 3600) % 60) != 0){ lblDescanso.text = String(Int(sender.value)/60)+" Minuto e "+String((Int(sender.value) % 3600) % 60)+" segundos de descanso" }else{ lblDescanso.text = String(Int(sender.value)/60)+" Minuto de descanso" } }else{ if(((Int(sender.value) % 3600) % 60) != 0){ lblDescanso.text = String(Int(sender.value)/60)+" Minutos e "+String((Int(sender.value) % 3600) % 60)+" segundos de descanso" }else{ lblDescanso.text = String(Int(sender.value)/60)+" Minutos de descanso" } } lblContTempo.text = String(describing: secondsToHoursMinutesSeconds(seconds: Int(sender.value))) tempo = Int(sender.value) } @IBAction func btnClickStart(_ sender: UIButton) { timer.invalidate() generator.impactOccurred() tempoDec = tempo if(repeticoes>0){ repeticoes -= 1 } lblContRepeticoes.text = String(repeticoes) timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true) sldTempo.isEnabled = false sldRepeticoes.isEnabled = false btnStart.isEnabled = false btnStart.alpha = 0.1 } func timerAction() { tempoDec -= 1 lblContTempo.text = String(describing: secondsToHoursMinutesSeconds(seconds: Int(tempoDec))) if(tempoDec==0){ timer.invalidate() lblContTempo.text = String(describing: secondsToHoursMinutesSeconds(seconds: Int(tempo))) sldTempo.isEnabled = true sldRepeticoes.isEnabled = true btnStart.isEnabled = true btnStart.alpha = 1.0 generator.impactOccurred() } } func secondsToHoursMinutesSeconds (seconds : Int) -> (String) { hora = (seconds / 3600) minuto = ((seconds % 3600) / 60) segundos = ((seconds % 3600) % 60) return String(format:"%02d:%02d", minuto, segundos) } }
33.87156
141
0.604009
7235fe53783945a6ddf976a9a06fe1e99c1cbc1d
602
// // MemoryStorage.swift // Pilot // // Created by Felix Chacaltana on 16/03/22. // import Foundation /* MemoryStorage Almacenamiento en memoria. */ final class MemoryStorage: Storage { var requests: [Request]! = [Request]() func subscribe(_ request: Request) { self.requests.append(request) } func fetchRequests(_ search: String) -> [Request] { let str = search.trimmingCharacters(in: .whitespacesAndNewlines) if str == "" { return self.requests } return self.requests.filter({ $0.path.contains(str) }) } }
20.066667
72
0.612957
e06b7fb40fb77980ff971e997a9c90a7fc68beed
15,623
// // PieChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit /// View that represents a pie chart. Draws cake like slices. public class PieChartView: PieRadarChartViewBase { /// rect object that represents the bounds of the piechart, needed for drawing the circle private var _circleBox = CGRect() /// array that holds the width of each pie-slice in degrees private var _drawAngles = [CGFloat]() /// array that holds the absolute angle in degrees of each slice private var _absoluteAngles = [CGFloat]() /// maximum angle for this pie private var _maxAngle: CGFloat = 360.0 public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal override func initialize() { super.initialize() renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } public override func drawRect(rect: CGRect) { super.drawRect(rect) if _data === nil { return } let optionalContext = UIGraphicsGetCurrentContext() guard let context = optionalContext else { return } renderer!.drawData(context: context) if (valuesToHighlight()) { renderer!.drawHighlighted(context: context, indices: _indicesToHighlight) } renderer!.drawExtras(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) drawDescription(context: context) drawMarkers(context: context) } internal override func calculateOffsets() { super.calculateOffsets() // prevent nullpointer when no data set if _data === nil { return } let radius = diameter / 2.0 let c = self.centerOffsets let shift = (data as? PieChartData)?.dataSet?.selectionShift ?? 0.0 // create the circle box that will contain the pie-chart (the bounds of the pie-chart) _circleBox.origin.x = (c.x - radius) + shift _circleBox.origin.y = (c.y - radius) + shift _circleBox.size.width = diameter - shift * 2.0 _circleBox.size.height = diameter - shift * 2.0 } internal override func calcMinMax() { super.calcMinMax() calcAngles() } public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { let center = self.centerCircleBox var r = self.radius var off = r / 10.0 * 3.6 if self.isDrawHoleEnabled { off = (r - (r * self.holeRadiusPercent)) / 2.0 } r -= off // offset to keep things inside the chart let rotationAngle = self.rotationAngle let i = e.xIndex // offset needed to center the drawn text in the slice let offset = drawAngles[i] / 2.0 // calculate the text position let x: CGFloat = (r * cos(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.x) let y: CGFloat = (r * sin(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.y) return CGPoint(x: x, y: y) } /// calculates the needed angles for the chart slices private func calcAngles() { _drawAngles = [CGFloat]() _absoluteAngles = [CGFloat]() _drawAngles.reserveCapacity(_data.yValCount) _absoluteAngles.reserveCapacity(_data.yValCount) let yValueSum = (_data as! PieChartData).yValueSum var dataSets = _data.dataSets var cnt = 0 for (var i = 0; i < _data.dataSetCount; i++) { let set = dataSets[i] let entryCount = set.entryCount for (var j = 0; j < entryCount; j++) { guard let e = set.entryForIndex(j) else { continue } _drawAngles.append(calcAngle(abs(e.value), yValueSum: yValueSum)) if (cnt == 0) { _absoluteAngles.append(_drawAngles[cnt]) } else { _absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt]) } cnt++ } } } /// checks if the given index in the given DataSet is set for highlighting or not public func needsHighlight(xIndex xIndex: Int, dataSetIndex: Int) -> Bool { // no highlight if (!valuesToHighlight() || dataSetIndex < 0) { return false } for (var i = 0; i < _indicesToHighlight.count; i++) { // check if the xvalue for the given dataset needs highlight if (_indicesToHighlight[i].xIndex == xIndex && _indicesToHighlight[i].dataSetIndex == dataSetIndex) { return true } } return false } /// calculates the needed angle for a given value private func calcAngle(value: Double) -> CGFloat { return calcAngle(value, yValueSum: (_data as! PieChartData).yValueSum) } /// calculates the needed angle for a given value private func calcAngle(value: Double, yValueSum: Double) -> CGFloat { return CGFloat(value) / CGFloat(yValueSum) * _maxAngle } public override func indexForAngle(angle: CGFloat) -> Int { // take the current angle of the chart into consideration let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle) for (var i = 0; i < _absoluteAngles.count; i++) { if (_absoluteAngles[i] > a) { return i } } return -1; // return -1 if no index found } /// - returns: the index of the DataSet this x-index belongs to. public func dataSetIndexForIndex(xIndex: Int) -> Int { var dataSets = _data.dataSets for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].entryForXIndex(xIndex) !== nil) { return i } } return -1 } /// - returns: an integer array of all the different angles the chart slices /// have the angles in the returned array determine how much space (of 360°) /// each slice takes public var drawAngles: [CGFloat] { return _drawAngles } /// - returns: the absolute angles of the different chart slices (where the /// slices end) public var absoluteAngles: [CGFloat] { return _absoluteAngles } /// Sets the color for the hole that is drawn in the center of the PieChart (if enabled). /// /// *Note: Use holeTransparent with holeColor = nil to make the hole transparent.* public var holeColor: UIColor? { get { return (renderer as! PieChartRenderer).holeColor! } set { (renderer as! PieChartRenderer).holeColor = newValue setNeedsDisplay() } } /// Set the hole in the center of the PieChart transparent public var holeTransparent: Bool { get { return (renderer as! PieChartRenderer).holeTransparent } set { (renderer as! PieChartRenderer).holeTransparent = newValue setNeedsDisplay() } } /// - returns: true if the hole in the center of the PieChart is transparent, false if not. public var isHoleTransparent: Bool { return (renderer as! PieChartRenderer).holeTransparent } /// the alpha of the hole in the center of the piechart, in case holeTransparent == true /// /// **default**: 0.41 public var holeAlpha: CGFloat { get { return (renderer as! PieChartRenderer).holeAlpha } set { (renderer as! PieChartRenderer).holeAlpha = newValue setNeedsDisplay() } } /// true if the hole in the center of the pie-chart is set to be visible, false if not public var drawHoleEnabled: Bool { get { return (renderer as! PieChartRenderer).drawHoleEnabled } set { (renderer as! PieChartRenderer).drawHoleEnabled = newValue setNeedsDisplay() } } /// - returns: true if the hole in the center of the pie-chart is set to be visible, false if not public var isDrawHoleEnabled: Bool { get { return (renderer as! PieChartRenderer).drawHoleEnabled } } /// the text that is displayed in the center of the pie-chart public var centerText: String? { get { return (renderer as! PieChartRenderer).centerAttributedText?.string } set { var attrString: NSMutableAttributedString? if newValue == nil { attrString = nil } else { let paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail paragraphStyle.alignment = .Center attrString = NSMutableAttributedString(string: newValue!) attrString?.setAttributes([ NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(12.0), NSParagraphStyleAttributeName: paragraphStyle ], range: NSMakeRange(0, attrString!.length)) } (renderer as! PieChartRenderer).centerAttributedText = attrString setNeedsDisplay() } } /// the text that is displayed in the center of the pie-chart public var centerAttributedText: NSAttributedString? { get { return (renderer as! PieChartRenderer).centerAttributedText } set { (renderer as! PieChartRenderer).centerAttributedText = newValue setNeedsDisplay() } } /// true if drawing the center text is enabled public var drawCenterTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawCenterTextEnabled } set { (renderer as! PieChartRenderer).drawCenterTextEnabled = newValue setNeedsDisplay() } } /// - returns: true if drawing the center text is enabled public var isDrawCenterTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawCenterTextEnabled } } internal override var requiredLegendOffset: CGFloat { return _legend.font.pointSize * 2.0 } internal override var requiredBaseOffset: CGFloat { return 0.0 } public override var radius: CGFloat { return _circleBox.width / 2.0 } /// - returns: the circlebox, the boundingbox of the pie-chart slices public var circleBox: CGRect { return _circleBox } /// - returns: the center of the circlebox public var centerCircleBox: CGPoint { return CGPoint(x: _circleBox.midX, y: _circleBox.midY) } /// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart) /// /// **default**: 0.5 (50%) (half the pie) public var holeRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).holeRadiusPercent } set { (renderer as! PieChartRenderer).holeRadiusPercent = newValue setNeedsDisplay() } } /// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart) /// /// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default public var transparentCircleRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).transparentCircleRadiusPercent } set { (renderer as! PieChartRenderer).transparentCircleRadiusPercent = newValue setNeedsDisplay() } } /// set this to true to draw the x-value text into the pie slices public var drawSliceTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawXLabelsEnabled } set { (renderer as! PieChartRenderer).drawXLabelsEnabled = newValue setNeedsDisplay() } } /// - returns: true if drawing x-values is enabled, false if not public var isDrawSliceTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawXLabelsEnabled } } /// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent. public var usePercentValuesEnabled: Bool { get { return (renderer as! PieChartRenderer).usePercentValuesEnabled } set { (renderer as! PieChartRenderer).usePercentValuesEnabled = newValue setNeedsDisplay() } } /// - returns: true if drawing x-values is enabled, false if not public var isUsePercentValuesEnabled: Bool { get { return (renderer as! PieChartRenderer).usePercentValuesEnabled } } /// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole public var centerTextRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).centerTextRadiusPercent } set { (renderer as! PieChartRenderer).centerTextRadiusPercent = newValue setNeedsDisplay() } } /// The max angle that is used for calculating the pie-circle. /// 360 means it's a full pie-chart, 180 results in a half-pie-chart. /// - default: 360.0 public var maxAngle: CGFloat { get { return _maxAngle } set { _maxAngle = newValue if _maxAngle > 360.0 { _maxAngle = 360.0 } if _maxAngle < 90.0 { _maxAngle = 90.0 } } } }
28.71875
189
0.564424
38b50eb01511f267ea360457cb75f3bae44d03b3
10,862
// // SymbolTableTests.swift // SwiftPascalInterpreterTests // // Created by Igor Kulman on 10/12/2017. // Copyright © 2017 Igor Kulman. All rights reserved. // import Foundation @testable import PascalInterpreter import XCTest class SemanticAnalyzerTests: XCTestCase { func testSemanticAnalyzer() { let program = """ PROGRAM Part10AST; VAR a, b, number : INTEGER; y : REAL; BEGIN BEGIN number := 2; a := number; a := 10 * a + 10 * number / 4; END; y := 11; END. """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() let state = analyzer.analyze(node: node) XCTAssert(state.keys.count == 1) XCTAssert(state["global"] != nil) XCTAssert(state["global"]!.level == 1) XCTAssert(state["global"]!.lookup("y") != nil) XCTAssert(state["global"]!.lookup("a") != nil) XCTAssert(state["global"]!.lookup("b") != nil) XCTAssert(state["global"]!.lookup("number") != nil) XCTAssert(state["global"]!.lookup("c") == nil) } func testSemanticAnalyzerAssignUndeclaredVariable() { let program = """ PROGRAM Part10AST; VAR a, b, number : INTEGER; y : REAL; BEGIN BEGIN number := 2; a := number; a := 10 * a + 10 * number / 4; END; x := 11; END. """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() expectFatalError(expectedMessage: "Symbol(indetifier) not found 'x'") { _ = analyzer.analyze(node: node) } } func testSemanticAnalyzerUndeclaredVariable() { let program = """ program SymTab5; var x : integer; begin x := y; end. """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() expectFatalError(expectedMessage: "Symbol(indetifier) not found 'y'") { _ = analyzer.analyze(node: node) } } func testSemanticAnalyzerMultipleDeclarations() { let program = """ program SymTab6; var x, y : integer; y : real; begin x := x + y; end. """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() expectFatalError(expectedMessage: "Duplicate identifier 'y' found") { _ = analyzer.analyze(node: node) } } func testSemanticAnalyzerProcedure() { let program = """ program Main; var x, y: real; procedure Alpha(a : integer); var y : integer; begin x := a + x + y; end; begin { Main } end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() let state = analyzer.analyze(node: node) XCTAssert(state.keys.count == 2) XCTAssert(state["global"] != nil) XCTAssert(state["global"]!.level == 1) XCTAssert(state["global"]!.lookup("x") != nil) XCTAssert(state["global"]!.lookup("y") != nil) XCTAssert(state["global"]!.lookup("a") == nil) XCTAssert(state.keys.count == 2) XCTAssert(state["Alpha"] != nil) XCTAssert(state["Alpha"]!.level == 2) XCTAssert(state["Alpha"]!.lookup("x") != nil) XCTAssert(state["Alpha"]!.lookup("y") != nil) XCTAssert(state["Alpha"]!.lookup("a") != nil) } func testSemanticAnalyzerUndeclaredProcedure() { let program = """ program Main; var x, y: real; procedure Alpha(a : integer); var y : integer; begin x := a + x + y; end; begin { Main } Beta(); end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() expectFatalError(expectedMessage: "Symbol(procedure) not found 'Beta'") { _ = analyzer.analyze(node: node) } } func testSemanticAnalyzerProcedureCall() { let program = """ program Main; var x, y: real; procedure Alpha(); var y : integer; begin x := x + y; end; begin { Main } Alpha(); end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() let state = analyzer.analyze(node: node) XCTAssert(state.keys.count == 2) XCTAssert(state["global"] != nil) XCTAssert(state["global"]!.level == 1) XCTAssert(state["global"]!.lookup("x") != nil) XCTAssert(state["global"]!.lookup("y") != nil) XCTAssert(state["global"]!.lookup("a") == nil) XCTAssert(state.keys.count == 2) XCTAssert(state["Alpha"] != nil) XCTAssert(state["Alpha"]!.level == 2) XCTAssert(state["Alpha"]!.lookup("x") != nil) XCTAssert(state["Alpha"]!.lookup("y") != nil) XCTAssert(state["Alpha"]!.lookup("a") == nil) } func testSemanticAnalyzerProcedureUndeclaredVariable() { let program = """ program Main; var x, y: real; procedure Alpha(a : integer); var y : integer; begin x := a + x + b; end; begin { Main } end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() expectFatalError(expectedMessage: "Symbol(indetifier) not found 'b'") { _ = analyzer.analyze(node: node) } } func testSemanticAnalyzerProcedureCallWithoutParameter() { let program = """ program Main; var x, y: real; procedure Alpha(a : integer); var y : integer; begin x := a + x; end; begin { Main } Alpha() end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() expectFatalError(expectedMessage: "Procedure called with wrong number of parameters 'Alpha'") { _ = analyzer.analyze(node: node) } } func testSemanticAnalyzerProcedureCallWithParameter() { let program = """ program Main; var x, y: real; procedure Alpha(a : integer); var y : integer; begin x := a + x; end; begin { Main } Alpha(5) end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() let state = analyzer.analyze(node: node) XCTAssert(state.keys.count == 2) XCTAssert(state["global"] != nil) XCTAssert(state["global"]!.level == 1) XCTAssert(state["global"]!.lookup("x") != nil) XCTAssert(state["global"]!.lookup("y") != nil) XCTAssert(state["global"]!.lookup("a") == nil) XCTAssert(state.keys.count == 2) XCTAssert(state["Alpha"] != nil) XCTAssert(state["Alpha"]!.level == 2) XCTAssert(state["Alpha"]!.lookup("x") != nil) XCTAssert(state["Alpha"]!.lookup("y") != nil) XCTAssert(state["Alpha"]!.lookup("a") != nil) } func testSemanticAnalyzerProcedureCallWithParameterWrongType() { let program = """ program Main; var x, y: real; procedure Alpha(a : integer); var y : integer; begin x := a + x; end; begin { Main } Alpha(5.2) end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() expectFatalError(expectedMessage: "Cannot assing Real to Integer parameter in procedure call 'Alpha'") { _ = analyzer.analyze(node: node) } } func testSemanticAnalyzerFunctionCallWithParameter() { let program = """ program Main; var x, y: real; function Alpha(a : integer): Integer; var y : integer; begin Alpha := a + X; end; begin { Main } x := Alpha(5); end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() let state = analyzer.analyze(node: node) XCTAssert(state.keys.count == 2) XCTAssert(state["global"] != nil) XCTAssert(state["global"]!.level == 1) XCTAssert(state["global"]!.lookup("x") != nil) XCTAssert(state["global"]!.lookup("y") != nil) XCTAssert(state["global"]!.lookup("a") == nil) XCTAssert(state.keys.count == 2) XCTAssert(state["Alpha"] != nil) XCTAssert(state["Alpha"]!.level == 2) XCTAssert(state["Alpha"]!.lookup("x") != nil) XCTAssert(state["Alpha"]!.lookup("y") != nil) XCTAssert(state["Alpha"]!.lookup("a") != nil) } func testSemanticAnalyzerBuildInFunction() { let program = """ program Main; var x: Integer; begin { Main } x := 5; writeln(x); end. { Main } """ let parser = Parser(program) let node = parser.parse() let analyzer = SemanticAnalyzer() let state = analyzer.analyze(node: node) XCTAssert(state.keys.count == 1) XCTAssert(state["global"] != nil) XCTAssert(state["global"]!.level == 1) XCTAssert(state["global"]!.lookup("x") != nil) XCTAssert(state["global"]!.lookup("WRITELN") != nil) XCTAssert(state["global"]!.lookup("a") == nil) } }
28.212987
112
0.482324
1ac2cb501ba53681054f938e123f205c0265acd3
412
import Foundation /// A type used to annotate track object modifications through time. /// Most of the time you'll just use date as stamp using `Date().stamp` method public typealias Stamp = Double extension Date { /// Generate a stamp suitable to use in `IdentityMap`. /// Don't suppose it equals unix timestamp (it is not) public var stamp: Stamp { timeIntervalSinceReferenceDate } }
29.428571
78
0.711165
f5aad9ce3a8c1e77baa6024068a7a5b655ae8b0d
27,996
// // DataViewController+LevelProgress.swift // Charles // // Created by Jacob Foster Davis on 5/29/17. // Copyright © 2017 Zero Mu, LLC. All rights reserved. // import Foundation import UIKit import CoreData /******************************************************/ /*******************///MARK: Extension for all level progress logic and presentation /******************************************************/ extension DataViewController { /******************************************************/ /*******************///MARK: Level Progress /******************************************************/ func refreshLevelProgress(_ justAnimatedPlayerFinishingLevel: Bool = false) { //figure out what level the player is on let userXP = calculateUserXP() let currentLevelAndProgress = Levels.getLevelAndProgress(from: userXP) //if the player isn't working on objectives, hide this progress bar if getCurrentScore() < minimumScoreToUnlockObjective { levelProgressView.isHidden = true thisLevelLabel.alpha = 0.0 nextLevelLabel.alpha = 0 levelDescriptionLabel.alpha = 0 //play sounds if needed compareLevelAndProgressAndPlaySounds(given: currentLevelAndProgress) } else { //show the level progress levelProgressView.isHidden = false //if just got done animating player to a full bar, set the progressbar progress to zero so it can finish animating to current progress if justAnimatedPlayerFinishingLevel { levelProgressView.setProgress(0, animated: false) } if let progress = calculateProgressValue() { var thisLevelColor: UIColor var nextLevelColor: UIColor //there are 11 sections of the progress bar and the width of each label is 1/11 of the progress bar. 1/11 = 0.0909090909 switch progress { case let x where x < 0.091: thisLevelColor = UIColor.darkGray nextLevelColor = UIColor.darkGray case let x where x >= 0.91: thisLevelColor = progressViewLightTextColor.textColor nextLevelColor = progressViewLightTextColor.textColor default: thisLevelColor = progressViewLightTextColor.textColor nextLevelColor = UIColor.darkGray } //if progress is in between the 1/11ths, activate background color switch progress { case let x where x > 0 && x < 0.091: thisLevelColor = progressViewLightTextColor.textColor thisLevelLabel.backgroundColor = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 0.5) //dark gray background color thisLevelLabel.roundCorners(with: 4) case let x where x < 1 && x >= 0.91: nextLevelLabel.backgroundColor = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 0.5) //dark gray background color nextLevelLabel.roundCorners(with: 4) default: thisLevelLabel.backgroundColor = .clear nextLevelLabel.backgroundColor = .clear } /******************************************************/ /*******************///MARK: PERK INCREASED XP /******************************************************/ //if an increased XP perk is active, change the color of the progressview let xpPerks = getAllPerks(ofType: .increasedXP, withStatus: .unlocked) if xpPerks.isEmpty { //no perks are active, set to normal color levelProgressView.progressTintColor = progressViewProgressTintColorDefault } else { //a perk is active so put the special color on //TODO: flash the bar to the perk color then back self.levelProgressView.progressTintColor = self.progressViewProgressTintColorXPPerkActive } //only animate if the user is progressing on the same level or degressing on same level. don't animate if user just lost a level or if the view just loaded. var shouldAnimate = false var playerLeveledUpWithXPPerkActive = false let currentLevel = currentLevelAndProgress.0 shouldAnimate = didPlayer(magnitudeDirection: .noChange, in: .level, byAchieving: currentLevel.level) //determine if the player leveled up while the XP perk was active, or by earning more than 1 xp //this would occur if progress > 0 and the player increased in level let playerIncreasedLevel = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: currentLevel.level) if playerIncreasedLevel && !xpPerks.isEmpty { playerLeveledUpWithXPPerkActive = true } /******************************************************/ /*******************///MARK: END PERK INCREASED XP /******************************************************/ if playerLeveledUpWithXPPerkActive && progress < 1.0 { //TODO: fix this so it works //flash user feedback for increased xp //the player leveled up by earning more than 1 XP, so progress bar should animate to full, then reset to the current level and progress //0. update labels //trick the label to think it will end up light thisLevelColor = progressViewLightTextColor.textColor nextLevelColor = progressViewLightTextColor.textColor let currentLevel = currentLevelAndProgress.0 let previousLevel = (Levels.Game[currentLevel.level - 1])! UIView.animate(withDuration: 0.8, delay: 0.8, animations: { self.thisLevelLabel.alpha = 1 self.thisLevelLabel.text = String(describing: previousLevel.level) self.thisLevelLabel.textColor = thisLevelColor //print(" text of this level label: \(self.thisLevelLabel.text)") //if player is on the highest level, don't show a level label if currentLevel != Levels.HighestLevel { self.nextLevelLabel.alpha = 1 self.nextLevelLabel.text = String(describing: (previousLevel.level + 1)) self.nextLevelLabel.textColor = nextLevelColor } else { //player is on highest level self.nextLevelLabel.alpha = 0 self.nextLevelLabel.text = "" self.nextLevelLabel.textColor = nextLevelColor } //level label self.levelDescriptionLabel.alpha = 1 self.levelDescriptionLabel.text = previousLevel.name }) //1. animate the progress bar to full //to do this need to animate it to 1 self.levelProgressView.setProgress(1, animated: true) //2. wait then call this refresh function again let seconds = 2 let deadline = DispatchTime.now() + DispatchTimeInterval.seconds(seconds) DispatchQueue.main.asyncAfter(deadline: deadline, execute: { self.refreshLevelProgress(true) }) } else { UIView.animate(withDuration: 0.8, delay: 0.8, animations: { let currentLevel = currentLevelAndProgress.0 self.thisLevelLabel.alpha = 1 self.thisLevelLabel.text = String(describing: currentLevel.level) self.thisLevelLabel.textColor = thisLevelColor //print(" text of this level label: \(self.thisLevelLabel.text)") //if player is on the highest level, don't show a level label if currentLevel != Levels.HighestLevel { self.nextLevelLabel.alpha = 1 self.nextLevelLabel.text = String(describing: (currentLevel.level + 1)) self.nextLevelLabel.textColor = nextLevelColor } else { //player is on highest level self.nextLevelLabel.alpha = 0 self.nextLevelLabel.text = "" self.nextLevelLabel.textColor = nextLevelColor } }, completion: { (finished:Bool) in //if progress is going to 1, then animate to 1 then continue self.levelProgressView.setProgress(progress, animated: shouldAnimate) //level label self.levelDescriptionLabel.alpha = 1 self.levelDescriptionLabel.text = currentLevel.name }) } } else { //no progress value returned (some sort of problem) levelProgressView.setProgress(0.0, animated: true) //TODO: log problem } //play sounds if needed compareLevelAndProgressAndPlaySounds(given: currentLevelAndProgress) } checkIfMapShouldBePresentedAndPresent() checkIfClueShouldBePresentedAndPresent() } ///determines if the map should be presented func checkIfMapShouldBePresentedAndPresent() { // let userXP = calculateUserXP() // let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP) let userCurrentLevel = getUserCurrentLevel().level let didPlayerProgressToGetHere = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: userCurrentLevel) if userCurrentLevel >= Levels.ReturnToDarknessLevelFirst.level && userCurrentLevel <= Levels.ReturnToDarknessLevelLast.level { //player is returning to darkness so do not present the map return } else if didPlayerProgressToGetHere && userCurrentLevel >= 11 { let topVC = topMostController() let mapVC = self.storyboard!.instantiateViewController(withIdentifier: "MapCollectionViewController") as! MapCollectionViewController mapVC.initialLevelToScrollTo = userCurrentLevel - 1 //initial level is the one just passed mapVC.playerHasFinishedInitialLevelToScrollTo = true topVC.present(mapVC, animated: true, completion: nil) } } ///checks if the user's new level warrants the presentation of a clue, and presents that clue func checkIfClueShouldBePresentedAndPresent() { let userXP = calculateUserXP() let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP) let userCurrentLevel = userLevelAndProgress.0.level let didPlayerProgressToGetHere = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: userCurrentLevel) //if the user progressed to get to here (as opposed to lost a level) and there is a clue for this new level if let clue = Clues.Lineup[userCurrentLevel], didPlayerProgressToGetHere { //there is a clue, so present this clue let topVC = topMostController() let clueVC = self.storyboard!.instantiateViewController(withIdentifier: "BasicClueViewController") as! BasicClueViewController clueVC.clue = clue topVC.present(clueVC, animated: true, completion: nil) } } ///calculates the progress value for the progress meter based on the user's level and XP. returns Float func calculateProgressValue() -> Float? { //get user's level and progress let userXP = calculateUserXP() let currentLevelAndProgress = Levels.getLevelAndProgress(from: userXP) let usersProgressOnCurrentLevel = currentLevelAndProgress.1 let usersCurrentLevel = currentLevelAndProgress.0 let progress: Float = Float(usersProgressOnCurrentLevel) / (Float(usersCurrentLevel.xPRequired) - 1) return progress } ///sets the playerLevelBaseline and playerProgerssBaseline for comparisonlater. should be called before the player starts an objective func setUserLevelAndProgressBaselines() { let userXP = calculateUserXP() let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP) //record the current level for comparison at score time let userLevel = userLevelAndProgress.0 playerLevelBaseline = userLevel.level let userProgress = userLevelAndProgress.1 playerProgressBaseline = userProgress } //a test to see if the user progressed, degressed, or remained same in a Baseline compared to the given level func didPlayer(magnitudeDirection: MagnitudeComparison, in baseline: Baseline, byAchieving newValue: Int) -> Bool { //figure out what type of comparison to make var comparisonOperator: (Int, Int) -> Bool switch magnitudeDirection { case .increase: comparisonOperator = (>) case .decrease: comparisonOperator = (<) default: comparisonOperator = (==) } if baseline == .level { if comparisonOperator(newValue, playerLevelBaseline) { return true } else { return false } } else { //must be referring to a progress not a level if comparisonOperator(newValue, playerProgressBaseline) { return true } else { return false } } } /******************************************************/ /*******************///MARK: XP and Levels /******************************************************/ /// sets the current score, returns the newly set score func giveXP(value: Int = 1, earnedDatetime: Date = Date(), level: Int, score: Int, successScore: Float, time: Int, toggles: Int, metaInt1: Int? = nil, metaInt2: Int? = nil, metaString1: String? = nil, metaString2: String? = nil, consolidatedRecords: Int? = nil, dontExceedHighestLevel: Bool = true) { guard let fc = frcDict[keyXP] else { return } guard (fc.fetchedObjects as? [XP]) != nil else { return } guard successScore >= 0 && successScore <= 1 else { //TODO: log error return } var xpToAward = value if let excessXP = howMuchWouldPlayerExceedHighestLevel(ifPlayerGained: value), dontExceedHighestLevel { //if the player is at the highest level of the game and this function should not exceed that xpToAward -= excessXP } //create a new score object let newXP = XP(entity: NSEntityDescription.entity(forEntityName: "XP", in: stack.context)!, insertInto: fc.managedObjectContext) newXP.value = Int64(xpToAward) newXP.successScore = successScore newXP.earnedDatetime = earnedDatetime newXP.level = Int64(level) newXP.score = Int64(score) newXP.time = Int64(time) newXP.toggles = Int64(toggles) if let int1 = metaInt1 { newXP.metaInt1 = Int64(int1) } if let int2 = metaInt1 { newXP.metaInt2 = Int64(int2) } newXP.metaString1 = metaString1 newXP.metaString2 = metaString2 if let records = consolidatedRecords { newXP.consolidatedRecords = Int64(records) } //save this right away stack.save() } ///checks to see how many XP records there are. If above the given number, will combine them all into a single record for each level. This to prevent big O problems func checkXPAndConsolidateIfNeccessary(consolidateAt numRecords: Int) { guard let fc = frcDict[keyXP] else { fatalError("Counldn't get frcDict") } guard let xps = fc.fetchedObjects as? [XP] else { fatalError("Counldn't get XP") } if xps.count >= numRecords { //go thru each level for (levelKey, _) in Levels.Game { var resultantValue:Int64 = 0 var resultantScore:Int64 = 0 var resultantRecordsCount: Int64 = 0 var rawSuccessScores: [Float] = [Float]() var found = false var numFound = 0 //and check each xp record's level for xp in xps { if Int(xp.level) == levelKey { //this xp record matches the level resultantValue += xp.value resultantScore += xp.score resultantRecordsCount += xp.consolidatedRecords //consolidatedRecords holds records counts if resultantRecordsCount == 0 { //this is a single record so weigh it as 1 rawSuccessScores.append(xp.successScore) //weight of 1 } else { //this is a consolidated record so weigh it rawSuccessScores.append(xp.successScore * Float(xp.consolidatedRecords)) //weighted scores } found = true numFound += 1 //now delete the record you just found let delegate = UIApplication.shared.delegate as! AppDelegate self.stack = delegate.stack if let context = self.frcDict[keyXP]?.managedObjectContext { context.delete(xp) } } } //if an applicable XP record was found, then consolidate and create a new XP if found { //create a new score object let newXP = XP(entity: NSEntityDescription.entity(forEntityName: "XP", in: stack.context)!, insertInto: fc.managedObjectContext) newXP.value = Int64(resultantValue) newXP.earnedDatetime = Date() newXP.level = Int64(levelKey) newXP.score = Int64(resultantScore) //calculate the average success var sumOfSuccessScores: Float = 0 for successScore in rawSuccessScores { sumOfSuccessScores += successScore } let averageSuccessScore: Float switch (Int(resultantRecordsCount), rawSuccessScores.count) { case (0, 1): //there is only a single record, this one is not consolidated, so it is the average averageSuccessScore = sumOfSuccessScores case (0, let y) where y > 1: //there are multiple records but none of them is a consolidated one averageSuccessScore = sumOfSuccessScores / Float(rawSuccessScores.count) case (let x, _) where x > 0: //there are multiple records but none of them is a consolidated one averageSuccessScore = sumOfSuccessScores / Float(resultantRecordsCount) default: //TODO: Make this a log entry fatalError("Unexpected case for consolidating a successScore. \(Int(resultantRecordsCount), rawSuccessScores.count))") } newXP.successScore = averageSuccessScore newXP.consolidatedRecords = resultantRecordsCount + Int64(numFound) //add the number of records consolidating to the count print("Consolidated \(numFound) XP objects at level \(levelKey). Resulting XP sum for this level is \(resultantValue).") } } } } ///returns the total amount of user XP func calculateUserXP() -> Int { guard let fc = frcDict[keyXP] else { fatalError("Counldn't get frcDict") } guard let xps = fc.fetchedObjects as? [XP] else { fatalError("Counldn't get XP") } var sum = 0 for xp in xps { sum = sum + Int(xp.value) } return sum } ///returns the user's current level determine programmatically. returns nil if user's level is off the charts high func getUserCurrentLevel() -> Level { let userXP = calculateUserXP() let userLevel = Levels.getLevelAndProgress(from: userXP) //userLevel is a tuple (player level, xp towards that level) return userLevel.0 } ///determines if the user just reached the highest progress of the highest level func didPlayerBeatGame() -> Bool { let userCurrentLevel = getUserCurrentLevel().level if isPlayerAtHighestLevelAndProgress() { //looks like the user is at the highest level with the highest progress //check that the player just arrived at this level let didJustReach = didPlayer(magnitudeDirection: .increase, in: .level, byAchieving: userCurrentLevel) //if the player just reached this level, then show the "you won" sequence if didJustReach { return true } } return false } ///determines if the user is at the highest level and progress values allowed func isPlayerAtHighestLevelAndProgress() -> Bool { let highestLevel = (Levels.HighestLevel.level) let highestProgressRequiredOnHighestLevel = Levels.Game[(highestLevel)]?.xPRequired let userXP = calculateUserXP() let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP) let requiredProgressValue = highestProgressRequiredOnHighestLevel! - 1 //The user must get up to 1 fewer than the highest XP of the highest level to win the game if userLevelAndProgress.0.level == highestLevel && userLevelAndProgress.1 == requiredProgressValue { return true } else { return false } } ///determines if the user is at the highest level and progress values allowed func howMuchWouldPlayerExceedHighestLevel(ifPlayerGained XP: Int) -> Int? { let highestLevel = Levels.HighestLevel let userXP = calculateUserXP() let userXPAndHypotheticalXP = userXP + XP let userLevelAndProgress = Levels.getLevelAndProgress(from: userXPAndHypotheticalXP) if (userLevelAndProgress.0.level) > (highestLevel.level) { var maxXP = 0 var level = 1 while level <= (Levels.HighestLevel.level) { maxXP += (Levels.Game[level]?.xPRequired)! level += 1 } //maxXP now holds the total number of XP required to win let xpDeviation = abs(userXPAndHypotheticalXP - maxXP) + 1 //if the user level is higher than the highest level the deviation will be the entire higher levels plus one. return xpDeviation } else { return nil } } ///shows the wining sequence func showWinningSequence() { let topVC = topMostController() let youWonVC = self.storyboard!.instantiateViewController(withIdentifier: "GameWinner") as! GameWinnerViewController let userXP = calculateUserXP() let userLevelAndProgress = Levels.getLevelAndProgress(from: userXP) let userLevel = userLevelAndProgress.0.level youWonVC.parentVC = self youWonVC.userLevel = userLevel topVC.present(youWonVC, animated: true, completion: nil) } //modifies the user's real XP data to send them back to the given level func reducePlayerLevel(to level: Int = 22) { //destroy all XP earned after the player reached given level guard let fc = frcDict[keyXP] else { fatalError("Counldn't get frcDict") } guard let xps = fc.fetchedObjects as? [XP] else { fatalError("Counldn't get XP") } //delete any xp object earnedon the given level or higher let delegate = UIApplication.shared.delegate as! AppDelegate self.stack = delegate.stack for xp in xps { if Int(xp.level) >= level { if let context = self.frcDict[keyXP]?.managedObjectContext { print("Deleting XP for level \(xp.level)") context.delete(xp) } } } stack.save() //now check that player is back to given level let newActualLevel = getUserCurrentLevel().level if newActualLevel > level { fatalError("Something went wrong when trying to put player back to level \(level). Current level being reported as \(String(describing: newActualLevel))") } } }
45.521951
304
0.527397
fb10d86765f47d798c17954552686d020614f72c
10,187
// // M13CheckboxDotController.swift // M13Checkbox // // Created by McQuilkin, Brandon on 4/1/16. // Copyright © 2016 Brandon McQuilkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit internal class M13CheckboxDotController: M13CheckboxController { //---------------------------- // MARK: - Properties //---------------------------- override var tintColor: UIColor { didSet { selectedBoxLayer.strokeColor = tintColor.cgColor if style == .stroke { markLayer.strokeColor = tintColor.cgColor if markType == .radio { markLayer.fillColor = tintColor.cgColor } } else { selectedBoxLayer.fillColor = tintColor.cgColor } } } override var secondaryTintColor: UIColor? { didSet { unselectedBoxLayer.strokeColor = secondaryTintColor?.cgColor } } override var secondaryCheckmarkTintColor: UIColor? { didSet { if style == .fill { markLayer.strokeColor = secondaryCheckmarkTintColor?.cgColor } } } override var hideBox: Bool { didSet { selectedBoxLayer.isHidden = hideBox unselectedBoxLayer.isHidden = hideBox } } fileprivate var style: M13Checkbox.AnimationStyle = .stroke init(style: M13Checkbox.AnimationStyle) { self.style = style super.init() sharedSetup() } override init() { super.init() sharedSetup() } fileprivate func sharedSetup() { // Disable som implicit animations. let newActions = [ "opacity": NSNull(), "strokeEnd": NSNull(), "transform": NSNull(), "fillColor": NSNull(), "path": NSNull(), "lineWidth": NSNull() ] // Setup the unselected box layer unselectedBoxLayer.lineCap = .round unselectedBoxLayer.rasterizationScale = UIScreen.main.scale unselectedBoxLayer.shouldRasterize = true unselectedBoxLayer.actions = newActions unselectedBoxLayer.transform = CATransform3DIdentity unselectedBoxLayer.fillColor = nil // Setup the selected box layer. selectedBoxLayer.lineCap = .round selectedBoxLayer.rasterizationScale = UIScreen.main.scale selectedBoxLayer.shouldRasterize = true selectedBoxLayer.actions = newActions selectedBoxLayer.fillColor = nil selectedBoxLayer.transform = CATransform3DIdentity // Setup the checkmark layer. markLayer.lineCap = .round markLayer.lineJoin = .round markLayer.rasterizationScale = UIScreen.main.scale markLayer.shouldRasterize = true markLayer.actions = newActions markLayer.transform = CATransform3DIdentity markLayer.fillColor = nil } //---------------------------- // MARK: - Layers //---------------------------- let markLayer = CAShapeLayer() let selectedBoxLayer = CAShapeLayer() let unselectedBoxLayer = CAShapeLayer() override var layersToDisplay: [CALayer] { return [unselectedBoxLayer, selectedBoxLayer, markLayer] } //---------------------------- // MARK: - Animations //---------------------------- override func animate(_ fromState: M13Checkbox.CheckState?, toState: M13Checkbox.CheckState?, completion: (() -> Void)?) { super.animate(fromState, toState: toState) if pathGenerator.pathForMark(toState) == nil && pathGenerator.pathForMark(fromState) != nil { let scaleAnimation = animationGenerator.fillAnimation(1, amplitude: 0.18, reverse: true) let opacityAnimation = animationGenerator.opacityAnimation(true) CATransaction.begin() CATransaction.setCompletionBlock({ [weak self] in self?.resetLayersForState(toState) completion?() }) if style == .stroke { unselectedBoxLayer.opacity = 0.0 let quickOpacityAnimation = animationGenerator.quickOpacityAnimation(false) quickOpacityAnimation.beginTime = CACurrentMediaTime() + scaleAnimation.duration - quickOpacityAnimation.duration unselectedBoxLayer.add(quickOpacityAnimation, forKey: "opacity") } selectedBoxLayer.add(scaleAnimation, forKey: "transform") markLayer.add(opacityAnimation, forKey: "opacity") CATransaction.commit() } else if pathGenerator.pathForMark(toState) != nil && pathGenerator.pathForMark(fromState) == nil { markLayer.path = pathGenerator.pathForMark(toState)?.cgPath let scaleAnimation = animationGenerator.fillAnimation(1, amplitude: 0.18, reverse: false) let opacityAnimation = animationGenerator.opacityAnimation(false) CATransaction.begin() CATransaction.setCompletionBlock({ [weak self] in self?.resetLayersForState(toState) completion?() }) if style == .stroke { let quickOpacityAnimation = animationGenerator.quickOpacityAnimation(true) quickOpacityAnimation.beginTime = CACurrentMediaTime() unselectedBoxLayer.add(quickOpacityAnimation, forKey: "opacity") } selectedBoxLayer.add(scaleAnimation, forKey: "transform") markLayer.add(opacityAnimation, forKey: "opacity") CATransaction.commit() } else { let fromPath = pathGenerator.pathForMark(fromState) let toPath = pathGenerator.pathForMark(toState) let morphAnimation = animationGenerator.morphAnimation(fromPath, toPath: toPath) CATransaction.begin() CATransaction.setCompletionBlock({ [weak self] in self?.resetLayersForState(self?.state) completion?() }) markLayer.add(morphAnimation, forKey: "path") CATransaction.commit() } } //---------------------------- // MARK: - Layout //---------------------------- override func layoutLayers() { // Frames unselectedBoxLayer.frame = CGRect(x: 0.0, y: 0.0, width: pathGenerator.size, height: pathGenerator.size) selectedBoxLayer.frame = CGRect(x: 0.0, y: 0.0, width: pathGenerator.size, height: pathGenerator.size) markLayer.frame = CGRect(x: 0.0, y: 0.0, width: pathGenerator.size, height: pathGenerator.size) // Paths unselectedBoxLayer.path = pathGenerator.pathForDot()?.cgPath selectedBoxLayer.path = pathGenerator.pathForBox()?.cgPath markLayer.path = pathGenerator.pathForMark(state)?.cgPath } //---------------------------- // MARK: - Display //---------------------------- override func resetLayersForState(_ state: M13Checkbox.CheckState?) { super.resetLayersForState(state) // Remove all remnant animations. They will interfere with each other if they are not removed before a new round of animations start. unselectedBoxLayer.removeAllAnimations() selectedBoxLayer.removeAllAnimations() markLayer.removeAllAnimations() // Set the properties for the final states of each necessary property of each layer. unselectedBoxLayer.strokeColor = secondaryTintColor?.cgColor unselectedBoxLayer.lineWidth = pathGenerator.boxLineWidth selectedBoxLayer.strokeColor = tintColor.cgColor selectedBoxLayer.lineWidth = pathGenerator.boxLineWidth if style == .stroke { selectedBoxLayer.fillColor = nil markLayer.strokeColor = tintColor.cgColor if markType != .radio { markLayer.fillColor = nil } else { markLayer.fillColor = tintColor.cgColor } } else { selectedBoxLayer.fillColor = tintColor.cgColor markLayer.strokeColor = secondaryCheckmarkTintColor?.cgColor } markLayer.lineWidth = pathGenerator.checkmarkLineWidth if pathGenerator.pathForMark(state) != nil { unselectedBoxLayer.opacity = 0.0 selectedBoxLayer.transform = CATransform3DIdentity markLayer.opacity = 1.0 } else { unselectedBoxLayer.opacity = 1.0 selectedBoxLayer.transform = CATransform3DMakeScale(0.0, 0.0, 0.0) markLayer.opacity = 0.0 } // Paths unselectedBoxLayer.path = pathGenerator.pathForDot()?.cgPath selectedBoxLayer.path = pathGenerator.pathForBox()?.cgPath markLayer.path = pathGenerator.pathForMark(state)?.cgPath } }
40.106299
464
0.608521
2912d60b59f2c2e17c879a67686229cd5c1042d8
2,088
// // log_op_test.swift // SerranoTests // // Created by ZHONGHAO LIU on 6/6/17. // Copyright © 2017 ZHONGHAO LIU. All rights reserved. // import XCTest import XCTest @testable import Serrano class LogOpDelegate: OperatorDelegateConvUnaryOp { required public convenience init(compareBlock: ((Tensor, Tensor) -> Void)?) { let blcok = {(rawTensor: Tensor, resultTensor: Tensor) -> Void in XCTAssertEqual(rawTensor.count, resultTensor.count) let readerReader = rawTensor.floatValueReader let resultReader = resultTensor.floatValueReader for i in 0..<rawTensor.count { let val = log(readerReader[i]) if val.isNaN || val.isInfinite || resultReader[i].isNaN || resultReader[i].isInfinite { continue } XCTAssertEqual(val, resultReader[i], accuracy: max(0.001, abs(val*0.001))) } } self.init(block: blcok) // grad: 1/x self.gradVerifyBlock = {(grads: [String : DataSymbolSupportedDataType], inputs:[Tensor]) -> Void in for (index, input) in inputs.enumerated() { let resultGrad = grads["input_\(index)"]!.tensorValue for i in 0..<input.count { let val:Float = 1 / input.floatValueReader[i] if val.isNaN || val.isInfinite { continue } XCTAssertEqual(val, resultGrad.floatValueReader[i], accuracy: max(0.001, abs(val*0.001))) } } } } } class LogOpTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func test() { let testCase = UnarOpTest<LogOpDelegate, LogOperator>() testCase.testAll() } }
33.142857
114
0.584291
e567ea6625c1a0988dc8a1ec6f63b03a78463311
2,850
// // AppDelegate.swift // CoreDataTest-EmployeeToCompany // // Created by admin on 12/14/18. // Copyright © 2018 admin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { //UIAppearance Proxy UINavigationBar.appearance().isTranslucent = false UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().barTintColor = UIColor.lightRed UINavigationBar.appearance().prefersLargeTitles = true UINavigationBar.appearance().largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white] UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white] window = UIWindow() window?.makeKeyAndVisible() let navVC = CustomNavigationController(rootViewController: CompaniesController()) window?.rootViewController = navVC 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:. } }
47.5
285
0.745263
4b7342dc2e0f18ab8848946f05d31966ed486e97
2,300
// // SceneDelegate.swift // Caoculadora // // Created by Alessandra Pereira on 25/10/20. // 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 necessarily 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. } }
43.396226
147
0.713913
9c7039b9ee5a3b2ebc683000bcbc7def9a233254
2,636
// // LoginView.swift // SinglePass // // Created by Juan Francisco Dorado Torres on 28/10/20. // import SwiftUI struct LoginView: View { @Binding var showCreateAccount: Bool @State private var email = "" @State private var password = "" @State private var formOffset: CGFloat = 0 var body: some View { SubscriptionView( content: createContent(), publisher: NotificationCenter.keyboardPublisher ) { frame in withAnimation { self.formOffset = frame.height > 0 ? -200 : 0 } } } private func createContent() -> some View { VStack { Image("singlePass-dynamic") .resizable() .aspectRatio(contentMode: .fit) .frame(height: 30) .padding(.bottom) VStack(spacing: 30) { Text("Login") .font(.title) .bold() VStack(spacing: 30) { SharedTextField( value: self.$email, header: "Email", placeholder: "Your email", errorMessage: "" ) PasswordField( value: self.$password, header: "Master Password", placeholder: "Make sure the password is strong", errorMessage: "", isSecure: true ) LCButton(text: "Login", backgroundColor: Color.accent) { // To be implemented } Button( action: { // To be implemented }, label: { VStack { Image(systemName: "faceid") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 40, height: 40) .foregroundColor(.accent) Text("Use face ID") .foregroundColor(.accent) } } ) } .modifier(FormModifier()) .offset(y: self.formOffset) createAccountButton() } } } private func createAccountButton() -> some View { Button( action: { withAnimation(.spring()) { self.showCreateAccount.toggle() } }, label: { HStack { Image(systemName: "arrow.left.square.fill") .resizable() .aspectRatio(contentMode: .fit) .frame(height: 20) .foregroundColor(.darkerAccent) Text("Create account") .accentColor(.darkerAccent) } } ) } } struct LoginView_Previews: PreviewProvider { static var previews: some View { LoginView(showCreateAccount: .constant(false)) } }
23.122807
66
0.51214
7a6c8d891159eef388ce2e6c94a18dd577675abf
2,182
// // ZoomViewJob.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif @objc(ZoomChartViewJob) open class ZoomViewJob: ViewPortJob { @objc internal var scaleX: CGFloat = 0.0 @objc internal var scaleY: CGFloat = 0.0 @objc internal var axisDependency: YAxis.AxisDependency = YAxis.AxisDependency.left @objc public init( viewPortHandler: ViewPortHandler, scaleX: CGFloat, scaleY: CGFloat, xValue: Double, yValue: Double, transformer: Transformer, axis: YAxis.AxisDependency, view: ChartViewBase) { super.init( viewPortHandler: viewPortHandler, xValue: xValue, yValue: yValue, transformer: transformer, view: view) self.scaleX = scaleX self.scaleY = scaleY self.axisDependency = axis } open override func doJob() { guard let viewPortHandler = viewPortHandler, let transformer = transformer, let view = view else { return } var matrix = viewPortHandler.setZoom(scaleX: scaleX, scaleY: scaleY) let _ = viewPortHandler.refresh(newMatrix: matrix, chart: view, invalidate: false) let yValsInView = (view as! BarLineChartViewBase).getAxis(axisDependency).axisRange / Double(viewPortHandler.scaleY) let xValsInView = (view as! BarLineChartViewBase).xAxis.axisRange / Double(viewPortHandler.scaleX) var pt = CGPoint( x: CGFloat(xValue - xValsInView / 2.0), y: CGFloat(yValue + yValsInView / 2.0) ) transformer.pointValueToPixel(&pt) matrix = viewPortHandler.translate(pt: pt) let _ = viewPortHandler.refresh(newMatrix: matrix, chart: view, invalidate: false) (view as! BarLineChartViewBase).calculateOffsets() view.setNeedsDisplay() } }
28.710526
124
0.619157
720f9f3679cf20e613a813da501a7918c872b4f1
1,458
// // GAPClassOfDevice.swift // Bluetooth // // Created by Carlos Duclos on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// Specifies the class of the device /// Size: 3 octets @frozen public struct GAPClassOfDevice: GAPData { public typealias Identifier = (UInt8, UInt8, UInt8) public static let dataType: GAPDataType = .classOfDevice public let device: Identifier public init(device: Identifier) { self.device = device } } public extension GAPClassOfDevice { init?(data: Data) { guard data.count == MemoryLayout<Identifier>.size else { return nil } let device = (data[0], data[1], data[2]) self.init(device: device) } func append(to data: inout Data) { data += device.0 data += device.1 data += device.2 } var dataLength: Int { return MemoryLayout<Identifier>.size } } // MARK: - Equatable extension GAPClassOfDevice: Equatable { public static func == (lhs: GAPClassOfDevice, rhs: GAPClassOfDevice) -> Bool { return lhs.device == rhs.device } } // MARK: - Hashable extension GAPClassOfDevice: Hashable { public func hash(into hasher: inout Hasher) { withUnsafeBytes(of: device) { hasher.combine(bytes: $0) } } }
20.25
82
0.578875
ac230c4f6c7db2ec0e8836a7a4c6cea22dc63a81
1,752
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Realm /** :nodoc: **/ public extension ObjectiveCSupport { /// Convert a `SyncCredentials` to a `RLMSyncCredentials`. static func convert(object: SyncCredentials) -> RLMSyncCredentials { return RLMSyncCredentials(object) } /// Convert a `RLMSyncCredentials` to a `SyncCredentials`. static func convert(object: RLMSyncCredentials) -> SyncCredentials { return SyncCredentials(object) } /// Convert a `SyncConfiguration` to a `RLMSyncConfiguration`. static func convert(object: SyncConfiguration) -> RLMSyncConfiguration { return object.asConfig() } /// Convert a `RLMSyncConfiguration` to a `SyncConfiguration`. static func convert(object: RLMSyncConfiguration) -> SyncConfiguration { return SyncConfiguration(config: object) } /// Convert a `RLMSyncSubscription` to a `SyncSubscription`. static func convert(object: RLMSyncSubscription) -> SyncSubscription { return SyncSubscription(object) } }
35.04
76
0.653539
4659a038402c7c39e53153a054f0524f1d2e1fa7
306
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { struct B<d where T : a<d { let start = b typealias f = b<d { return " class A { typealias e = b<d { return "))) } func b<H : b
20.4
87
0.689542
1c704900132651e4716e2dc3a89cd469fe027c73
17,049
import Foundation /** The request body you use to create an advanced App Clip experience. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperiencecreaterequest> */ public struct AppClipAdvancedExperienceCreateRequest: Codable, RequestBody { /// The resource data. public let data: Data /// The included related resources. @NullCodable public var included: [AppClipAdvancedExperienceLocalizationInlineCreate]? public init(data: Data, included: [AppClipAdvancedExperienceLocalizationInlineCreate]? = nil) { self.data = data self.included = included } /** The data element of the request body. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperiencecreaterequest/data> */ public struct Data: Codable { /// The resource type. public var type: String { "appClipAdvancedExperiences" } /// The resource's attributes. public let attributes: Attributes /// The relationships to other resources that you can set with this request. public let relationships: Relationships public init(attributes: Attributes, relationships: Relationships) { self.attributes = attributes self.relationships = relationships } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) attributes = try container.decode(Attributes.self, forKey: .attributes) relationships = try container.decode(Relationships.self, forKey: .relationships) if try container.decode(String.self, forKey: .type) != type { throw DecodingError.dataCorruptedError(forKey: .type, in: container, debugDescription: "Not matching \(type)") } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type, forKey: .type) try container.encode(attributes, forKey: .attributes) try container.encode(relationships, forKey: .relationships) } private enum CodingKeys: String, CodingKey { case type case attributes case relationships } /** Attributes that you set that describe the new resource. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperiencecreaterequest/data/attributes> */ public struct Attributes: Codable { /// The call-to-action verb that appears on the App Clip card. @NullCodable public var action: AppClipAction? /// The business category of an advanced App Clip experience; for example, PARKING @NullCodable public var businessCategory: AppClipAdvancedExperience.Attributes.BusinessCategory? /// The default language for the advanced App Clip experience. public let defaultLanguage: AppClipAdvancedExperienceLanguage /// A Boolean value that indicates whether the advanced App Clip experience was submitted by a platform provider that serves multiple businesses. public let isPoweredBy: Bool /// The invocation URL of the advanced App Clip experience you’re creating. public let link: String /// The physical location you associate with the advanced App Clip experience. If you associate an advanced App Clip experience with a place, users can launch your App Clip from from location-based suggestions from Siri Suggestions and the Maps app. @NullCodable public var place: Place? public init(action: AppClipAction? = nil, businessCategory: AppClipAdvancedExperience.Attributes.BusinessCategory? = nil, defaultLanguage: AppClipAdvancedExperienceLanguage, isPoweredBy: Bool, link: String, place: Place? = nil) { self.action = action self.businessCategory = businessCategory self.defaultLanguage = defaultLanguage self.isPoweredBy = isPoweredBy self.link = link self.place = place } public struct Place: Codable { public var categories: String? @NullCodable public var displayPoint: DisplayPoint? public var homePage: String? @NullCodable public var mainAddress: MainAddress? @NullCodable public var mapAction: MapAction? public var names: String? @NullCodable public var phoneNumber: PhoneNumber? public var placeId: String? @NullCodable public var relationship: Relationship? public init(categories: String? = nil, displayPoint: DisplayPoint? = nil, homePage: String? = nil, mainAddress: MainAddress? = nil, mapAction: MapAction? = nil, names: String? = nil, phoneNumber: PhoneNumber? = nil, placeId: String? = nil, relationship: Relationship? = nil) { self.categories = categories self.displayPoint = displayPoint self.homePage = homePage self.mainAddress = mainAddress self.mapAction = mapAction self.names = names self.phoneNumber = phoneNumber self.placeId = placeId self.relationship = relationship } public struct DisplayPoint: Codable { @NullCodable public var coordinates: Coordinates? @NullCodable public var source: Source? public init(coordinates: Coordinates? = nil, source: Source? = nil) { self.coordinates = coordinates self.source = source } public struct Coordinates: Codable { public var latitude: Double? public var longitude: Double? public init(latitude: Double? = nil, longitude: Double? = nil) { self.latitude = latitude self.longitude = longitude } } public enum Source: String, Codable, CaseIterable { case calculated = "CALCULATED" case manuallyPlaced = "MANUALLY_PLACED" } } public struct MainAddress: Codable { public var fullAddress: String? @NullCodable public var structuredAddress: StructuredAddress? public init(fullAddress: String? = nil, structuredAddress: StructuredAddress? = nil) { self.fullAddress = fullAddress self.structuredAddress = structuredAddress } public struct StructuredAddress: Codable { public var countryCode: String? public var floor: String? public var locality: String? public var neighborhood: String? public var postalCode: String? public var stateProvince: String? public var streetAddress: String? public init(countryCode: String? = nil, floor: String? = nil, locality: String? = nil, neighborhood: String? = nil, postalCode: String? = nil, stateProvince: String? = nil, streetAddress: String? = nil) { self.countryCode = countryCode self.floor = floor self.locality = locality self.neighborhood = neighborhood self.postalCode = postalCode self.stateProvince = stateProvince self.streetAddress = streetAddress } } } public enum MapAction: String, Codable, CaseIterable { case buyTickets = "BUY_TICKETS" case viewAvailability = "VIEW_AVAILABILITY" case viewPricing = "VIEW_PRICING" case hotelBookRoom = "HOTEL_BOOK_ROOM" case parkingReserveParking = "PARKING_RESERVE_PARKING" case restaurantJoinWaitlist = "RESTAURANT_JOIN_WAITLIST" case restaurantOrderDelivery = "RESTAURANT_ORDER_DELIVERY" case restaurantOrderFood = "RESTAURANT_ORDER_FOOD" case restaurantOrderTakeout = "RESTAURANT_ORDER_TAKEOUT" case restaurantReservation = "RESTAURANT_RESERVATION" case scheduleAppointment = "SCHEDULE_APPOINTMENT" case restaurantViewMenu = "RESTAURANT_VIEW_MENU" case theaterNowPlaying = "THEATER_NOW_PLAYING" } public struct PhoneNumber: Codable { public var intent: String? public var number: String? @NullCodable public var type: PhoneNumberType? public init(intent: String? = nil, number: String? = nil, type: PhoneNumberType? = nil) { self.intent = intent self.number = number self.type = type } public enum PhoneNumberType: String, Codable, CaseIterable { case fax = "FAX" case landline = "LANDLINE" case mobile = "MOBILE" case tollfree = "TOLLFREE" } } public enum Relationship: String, Codable, CaseIterable { case owner = "OWNER" case authorized = "AUTHORIZED" case other = "OTHER" } } } /** The relationships to other resources that you can set with this request. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperiencecreaterequest/data/relationships> */ public struct Relationships: Codable { public let appClip: AppClip public let headerImage: HeaderImage public let localizations: Localizations public init(appClip: AppClip, headerImage: HeaderImage, localizations: Localizations) { self.appClip = appClip self.headerImage = headerImage self.localizations = localizations } public struct AppClip: Codable { /// The type and ID of the resource that you're relating with the resource you're creating. public let data: Data public init(data: Data) { self.data = data } /** The type and ID of the resource that you're relating with the resource you're creating. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperiencecreaterequest/data/relationships/appclip/data> */ public struct Data: Codable { /// The opaque resource ID that uniquely identifies the resource. public let id: String /// The resource type. public var type: String { "appClips" } public init(id: String) { self.id = id } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) if try container.decode(String.self, forKey: .type) != type { throw DecodingError.dataCorruptedError(forKey: .type, in: container, debugDescription: "Not matching \(type)") } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(type, forKey: .type) } private enum CodingKeys: String, CodingKey { case id case type } } } public struct HeaderImage: Codable { /// The type and ID of the resource that you're relating with the resource you're creating. public let data: Data public init(data: Data) { self.data = data } /** The type and ID of the resource that you're relating with the resource you're creating. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperiencecreaterequest/data/relationships/headerimage/data> */ public struct Data: Codable { /// The opaque resource ID that uniquely identifies the resource. public let id: String /// The resource type. public var type: String { "appClipAdvancedExperienceImages" } public init(id: String) { self.id = id } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) if try container.decode(String.self, forKey: .type) != type { throw DecodingError.dataCorruptedError(forKey: .type, in: container, debugDescription: "Not matching \(type)") } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(type, forKey: .type) } private enum CodingKeys: String, CodingKey { case id case type } } } public struct Localizations: Codable { /// The type and ID of the resource that you're relating with the resource you're creating. public let data: [Data] public init(data: [Data]) { self.data = data } /** The type and ID of the resource that you're relating with the resource you're creating. Full documentation: <https://developer.apple.com/documentation/appstoreconnectapi/appclipadvancedexperiencecreaterequest/data/relationships/localizations/data> */ public struct Data: Codable { /// The opaque resource ID that uniquely identifies the resource. public let id: String /// The resource type. public var type: String { "appClipAdvancedExperienceLocalizations" } public init(id: String) { self.id = id } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) if try container.decode(String.self, forKey: .type) != type { throw DecodingError.dataCorruptedError(forKey: .type, in: container, debugDescription: "Not matching \(type)") } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(type, forKey: .type) } private enum CodingKeys: String, CodingKey { case id case type } } } } } }
46.709589
292
0.546132
c135bc1e0525f4fe621b3a876c2405c41e77a7c3
1,150
// 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: "GLTFSceneKit", platforms: [ .iOS(.v12), .macOS(.v11) ], products: [ .library(name: "GLTFSceneKit", targets: ["GLTFSceneKit"]), ], targets: [ .target( name: "GLTFSceneKit", path: "Sources", resources: [ .copy("Resources/GLTFShaderModifierFragment_alphaCutoff.shader"), .copy("Resources/GLTFShaderModifierSurface_alphaModeBlend.shader"), .copy("Resources/GLTFShaderModifierSurface_doubleSidedWorkaround.shader"), .copy("Resources/GLTFShaderModifierSurface_pbrSpecularGlossiness_doubleSidedWorkaround.shader"), .copy("Resources/GLTFShaderModifierSurface_pbrSpecularGlossiness_texture_doubleSidedWorkaround.shader"), .copy("Resources/GLTFShaderModifierSurface_pbrSpecularGlossiness.shader"), .copy("Resources/GLTFShaderModifierSurface.shader"), ]) ] )
38.333333
120
0.653913
e9787f261ff836e85c3e3fa3a230e923a3fc3fd7
513
// // ViewController.swift // JJGuisoWebP // // Created by only-icesoul on 11/01/2020. // Copyright (c) 2020 only-icesoul. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
20.52
80
0.672515
4a331c9a39b412774985d9c5aea6fd3ea42917ac
6,852
// // InputPasscodeWithCustomPad.swift // ARRR-Wallet // // Created by Lokesh Sehgal on 20/05/21. // Copyright © 2021 Francisco Gindre. All rights reserved. // import Foundation import SwiftUI struct InputPasscodeWithCustomPad: View { @State var isPassCodeEntered = false @EnvironmentObject var appEnvironment: ZECCWalletEnvironment @Environment(\.presentationMode) var mode:Binding<PresentationMode> @State var copiedValue: PasteboardItemModel? @State var destination: Destination? @State var aUniqueCode : [String] = [] @State var customDigits : [NumPadRow] = [] var anInitialPassCode = "" let aPasscodeTitle = "Enter a Passcode".localized() let aConfirmPasscode = "Confirm Passcode".localized() enum Destination: Int, Identifiable, Hashable { case inputPasscode var id: Int { return self.rawValue } } func getRandomNumbers()->[Int]{ var allNumbers = [0,1,2,3,4,5,6,7,8,9] var uniqueNumbers = [Int]() while allNumbers.count > 0 { let number = Int(arc4random_uniform(UInt32(allNumbers.count))) uniqueNumbers.append(allNumbers[number]) allNumbers.swapAt(number, allNumbers.count-1) allNumbers.removeLast() } return uniqueNumbers } func getRandomizedPadDigits()->[NumPadRow]{ var customPadDigits = [NumPadRow]() let uniqueNumbers = getRandomNumbers() var aColumnIndex = 0 var aRowIndex = 0 var arrayOfNumPadValues = [NumPadValue]() for aNumber in uniqueNumbers { if aColumnIndex > 2 { aColumnIndex = 0 customPadDigits.append(NumPadRow(id: aRowIndex, row: arrayOfNumPadValues)) arrayOfNumPadValues.removeAll() aRowIndex += 1 } if uniqueNumbers.last == aNumber { arrayOfNumPadValues.append(NumPadValue(id: 0, value: "delete.left.fill")) arrayOfNumPadValues.append(NumPadValue(id: 1, value: String(aNumber))) }else{ arrayOfNumPadValues.append(NumPadValue(id: aColumnIndex, value: String(aNumber))) } aColumnIndex += 1 } customPadDigits.append(NumPadRow(id: 3, row: arrayOfNumPadValues)) return customPadDigits } var body: some View { ZStack(alignment: .center) { ZcashBackground.pureBlack NavigationView{ VStack{ VStack{ Spacer() Text(!isPassCodeEntered ? aPasscodeTitle : aConfirmPasscode).font(.title) HStack(spacing: 20){ ForEach(aUniqueCode,id: \.self){i in Text(i).font(.title).fontWeight(.semibold) } }.padding(.vertical) Spacer() CustomNumberPad(uniqueCodes: $aUniqueCode,customDigits: $customDigits) } }.onAppear { if customDigits.isEmpty { customDigits = getRandomizedPadDigits() } NotificationCenter.default.addObserver(forName: NSNotification.Name("EnteredCode"), object: nil, queue: .main) { (_) in self.isPassCodeEntered = true } } }.preferredColorScheme(.dark) .animation(.spring()) }.background(Color.black) } } struct InputPasscodeWithCustomPad_Previews: PreviewProvider { static var previews: some View { InputPasscodeWithCustomPad() } } struct NumPadRow : Identifiable { var id : Int var row : [NumPadValue] } struct NumPadValue : Identifiable { var id : Int var value : String } struct CustomNumberPad : View { @Binding var uniqueCodes : [String] @Binding var customDigits : [NumPadRow] var body : some View{ VStack(alignment: .leading,spacing: 20){ ForEach(customDigits){index in HStack(spacing: self.getScreenSpacing()){ ForEach(index.row){jIndex in Button(action: { if jIndex.value == "delete.left.fill"{ self.uniqueCodes.removeLast() } else{ self.uniqueCodes.append(jIndex.value) if self.uniqueCodes.count == 4{ // Success here code is verified print(self.getPasscode()) NotificationCenter.default.post(name: NSNotification.Name("EnteredCode"), object: nil) self.uniqueCodes.removeAll() } } }) { if jIndex.value == "delete.left.fill"{ Image(systemName: jIndex.value).font(.body).padding(.vertical) } else{ Text(jIndex.value).font(.title).fontWeight(.semibold).padding(.vertical) } } } } } }.foregroundColor(.white) } func getScreenSpacing()->CGFloat{ return UIScreen.main.bounds.width / 3 } func getPasscode()->String{ var code = "" for i in self.uniqueCodes{ code += i } return code.replacingOccurrences(of: " ", with: "") } }
28.669456
139
0.441477
393bc520a1d97e16dcae465ab0b66954790aa73c
1,566
// // MainPresenter.swift // JSONPlaceHolderApp // // Created by Iván Díaz Molina on 15/2/21. // Copyright (c) 2021 IDIAZM. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol MainPresentationLogic { func setupView(response: Main.SetupView.Response) func displayLoading(_ show: Bool) func presentPosts() func presentPostDetails(response: Main.DidSelectedItem.Response) } class MainPresenter: MainPresentationLogic { weak var viewController: MainDisplayLogic? // MARK: Presentation Logic func setupView(response: Main.SetupView.Response) { var viewModel = Main.SetupView.ViewModel() viewModel.title = "posts.title".localized viewController?.setupView(viewModel: viewModel) } /// method shows loading in screen /// - Parameter show: flag to show loading func displayLoading(_ show: Bool) { viewController?.showLoading(show) } /// method shows posts in screen func presentPosts() { viewController?.displayPosts() } /// method navigates to details of selected post /// - Parameter response: response func presentPostDetails(response: Main.DidSelectedItem.Response) { // 1. create viewModel let viewModel = Main.DidSelectedItem.ViewModel() // 2. display data viewController?.displayPostDetails(viewModel: viewModel) } }
28.472727
70
0.683269
1a371d47c0481b5e946dffee7727d3559dc4e022
20,949
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -disable-availability-checking %S/Inputs/specialize_opaque_type_archetypes_2.swift -module-name External -emit-module -emit-module-path %t/External.swiftmodule // RUN: %target-swift-frontend -disable-availability-checking %S/Inputs/specialize_opaque_type_archetypes_3.swift -enable-library-evolution -module-name External2 -emit-module -emit-module-path %t/External2.swiftmodule // RUN: %target-swift-frontend -disable-availability-checking %S/Inputs/specialize_opaque_type_archetypes_4.swift -I %t -enable-library-evolution -module-name External3 -emit-module -emit-module-path %t/External3.swiftmodule // RUN: %target-swift-frontend -disable-availability-checking %S/Inputs/specialize_opaque_type_archetypes_3.swift -I %t -enable-library-evolution -module-name External2 -Osize -emit-module -o - | %target-sil-opt -module-name External2 | %FileCheck --check-prefix=RESILIENT %s // RUN: %target-swift-frontend -disable-availability-checking -I %t -module-name A -enforce-exclusivity=checked -Osize -emit-sil -sil-verify-all %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // RUN: %target-swift-frontend -disable-availability-checking -I %t -module-name A -enforce-exclusivity=checked -enable-library-evolution -Osize -emit-sil -sil-verify-all %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize import External import External2 import External3 public protocol P { func myValue() -> Int64 } extension Int64: P { public func myValue() -> Int64 { return self } } @inline(never) func useP<T: P> (_ t: T) { print(t) } public func bar(_ x: Int64) -> some P { return x } public func foo(_ x: Int64) -> some P { if x > 0 { return bar(x + 1) } return bar(x - 1) } @inline(never) func getInt() -> Int64 { return 2 } @inline(never) func identity<T>(_ t: T) -> T { return t } // CHECK-LABEL: sil @$s1A10testFooBaryyxAA1PRzlF : $@convention(thin) <T where T : P> (@in_guaranteed T) -> () { // CHECK: bb3([[FOOS_INT:%.*]] : $Builtin.Int64): // CHECK: [[FOO_RES:%.*]] = struct $Int64 ([[FOOS_INT]] : $Builtin.Int64) // CHECK: [[ID:%.*]] = function_ref @$s1A8identityyxxlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> Int64 // CHECK: [[ID_RES:%.*]] = apply [[ID]]([[FOO_RES]]) : $@convention(thin) (Int64) -> Int64 // CHECK: [[USEP:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () // CHECK: apply [[USEP]]([[ID_RES]]) : $@convention(thin) (Int64) -> () // CHECK: apply [[USEP]]([[FOO_RES]]) : $@convention(thin) (Int64) -> () public func testFooBar<T:P>(_ t : T) { let x = foo(getInt()) useP(identity(x)) useP(x.myValue()) } struct AddressOnly : P{ var p : P = Int64(1) func myValue() -> Int64 { return p.myValue() } } public func addressOnlyFoo() -> some P { return AddressOnly() } // CHECK-LABEL: sil @$s1A21testAddressOnlyFoobaryyF // CHECK-NOT: return type of // CHECK: return public func testAddressOnlyFoobar() { let x = addressOnlyFoo() let y = x useP(x.myValue()) useP(y.myValue()) } public protocol CP : class { func myValue() -> Int64 } class C : CP { func myValue() -> Int64 { return 0 } } public func returnC() -> some CP { return C() } // CHECK-LABEL: sil @$s1A4useCyyF // CHECK: [[FUN:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 // CHECK: [[INT:%.*]] = struct $Int64 ( // CHECK: = apply [[FUN]]([[INT]]) public func useC() { let c = returnC() useP(c.myValue()) } // CHECK-LABEL: sil @$s1A11useExternalyyF // CHECK: // function_ref Int64.myValue2() // CHECK: [[FUN:%.*]] = function_ref @$ss5Int64V8ExternalE8myValue2AByF // CHECK: apply [[FUN]] public func useExternal() { let e = external() useP(e.myValue2()) } // Call to a resilient function should not be specialized. // CHECK-LABEL: sil @$s1A20useExternalResilientyyF // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External217externalResilientQryF : $@convention(thin) () -> @out @_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: apply [[FUN]]([[RES]]) // CHECK: witness_method // CHECK: return public func useExternalResilient() { let e = externalResilient() useP(e.myValue3()) } struct Container { var x : some P { get { return Int64(1) } } } // CHECK-LABEL: sil @$s1A11usePropertyyyF // CHECK: [[VAL:%.*]] = struct $Int64 // CHECK: // function_ref specialized useP<A>(_:) // CHECK: [[FUN:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 // CHECK: apply [[FUN]]([[VAL]]) public func useProperty() { let p = Container().x useP(p.myValue()) } protocol Q { associatedtype T func f() -> T associatedtype T2 func g() -> T2 } struct S : Q { func f()->some P { return Int64(1) } func g()->some CP { return C() } } struct Container2 { var member : S.T mutating func blah(_ x: S.T) { member = x } } class Container3 { @inline(__always) init(member : S.T) { self.member = member } var member : S.T func blah(_ x: S.T) { member = x } } struct Container4 { var member : S.T2 mutating func blah(_ x: S.T2) { member = x } } struct Container5 { var member : (S.T2, S.T) mutating func blah(_ x: S.T2, _ y: S.T) { member = (x,y) } } struct Pair<T, V> { var first: T var second: V } // CHECK-LABEL: sil @$s1A10storedPropyyF // CHECK-NOT: apply // CHECK: store // CHECK-NOT: apply // CHECK: store // CHECK-NOT: apply // CHECK: store // CHECK-NOT: apply // CHECK: return public func storedProp() { var c = Container2(member: S().f()) c.blah(S().f()) var c2 = Container3(member: S().f()) c2.blah(S().f()) var c3 = Container4(member: S().g()) c3.blah(S().g()) var s = S() var c4 = Container5(member: (s.g(), s.f())) c4.blah(s.g(), s.f()) } public func usePair() { var x = Pair(first: bar(1), second: returnC()) useP(x.first.myValue()) useP(x.second.myValue()) } struct MyInt64 : ExternalP2 { var x = Int64(0) public func myValue3() -> Int64 { return x + 3 } } func nonResilient() -> some ExternalP2 { return MyInt64() } // CHECK-LABEL: sil @$s1A019usePairResilientNonC0yyF : $@convention(thin) () -> () // CHECK: alloc_stack $Pair<MyInt64, @_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: [[USEP:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 // CHECK: [[FIRST_MYVALUE3:%.*]] = struct $Int64 // CHECK: apply [[USEP]]([[FIRST_MYVALUE3]]) // CHECK: [[MYVALUE_WITNESS:%.*]] = witness_method $@_opaqueReturnTypeOf("$s9External217externalResilientQryF" // CHECK: [[SECOND_MYVALUE3:%.*]] = apply [[MYVALUE_WITNESS]] // CHECK: apply [[USEP]]([[SECOND_MYVALUE3]]) // CHECK: return public func usePairResilientNonResilient() { var x = Pair(first: nonResilient(), second: externalResilient()) useP(x.first.myValue3()) useP(x.second.myValue3()) } public protocol P3 { associatedtype AT func foo() -> AT } public struct Adapter<T: P3>: P3 { var inner: T public func foo() -> some P3 { return inner } } // Don't assert. // CHECK-LABEL: sil {{.*}} @$s1A7AdapterVyxGAA2P3A2aEP3foo2ATQzyFTW // CHECK: [[F:%.*]] = function_ref @$s1A7AdapterV3fooQryF // CHECK: apply [[F]]<τ_0_0>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : P3> (@in_guaranteed Adapter<τ_0_0>) -> extension P3 { public func foo() -> some P3 { return Adapter(inner: self) } } // We should specialize the opaque type because the resilient function is // inlineable. // CHECK-LABEL: sil @$s1A21useExternalResilient2yyF : $@convention(thin) () -> () // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External226inlinableExternalResilientQryF : $@convention(thin) () -> @out Int64 // CHECK: apply [[FUN]]([[RES]]) // CHECK: return public func useExternalResilient2() { let e = inlinableExternalResilient() useP(e.myValue3()) } // In this case we should only 'peel' one layer of opaque archetypes. // CHECK-LABEL: sil @$s1A21useExternalResilient3yyF // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External3031inlinableExternalResilientCallsD0QryF : $@convention(thin) () -> @out @_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) // CHECK: apply [[FUN]]([[RES]]) public func useExternalResilient3() { let e = inlinableExternalResilientCallsResilient() useP(e.myValue3()) } // Check that we can look throught two layers of inlinable resilient functions. // CHECK-LABEL: sil @$s1A21useExternalResilient4yyF // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External3040inlinableExternalResilientCallsInlinablecD0QryF : $@convention(thin) () -> @out Int64 // CHECK: apply [[FUN]]([[RES]]) public func useExternalResilient4() { let e = inlinableExternalResilientCallsInlinableExternalResilient() useP(e.myValue3()) } // CHECK-LABEL: sil @$s1A18testStoredPropertyyyF // CHECK: [[CONTAINER_INIT_FUN:%.*]] = function_ref @$s8External0A9ContainerVACycfC // CHECK: [[CONTAINER:%.*]] = apply [[CONTAINER_INIT_FUN]] // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[COMPUTED_PROP:%.*]] = function_ref @$s8External0A9ContainerV16computedPropertyQrvg // CHECK: apply [[COMPUTED_PROP]]([[RES]], [[CONTAINER]]) // CHECK: [[MYVALUE:%.*]] = function_ref @$ss5Int64V8ExternalE8myValue2AByF : $@convention(method) (Int64) -> Int64 // CHECK: apply [[MYVALUE]] public func testStoredProperty() { let c = ExternalContainer() useP(c.computedProperty.myValue2()) } // CHECK-LABEL: sil @$s1A21testResilientPropertyyyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External218ResilientContainerV16computedPropertyQrvp", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External218ResilientContainerV16computedPropertyQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientProperty() { let r = ResilientContainer() useP(r.computedProperty.myValue3()) } // CHECK-LABEL: sil @$s1A30testResilientInlinablePropertyyyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External218ResilientContainerV18inlineablePropertyQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientInlinableProperty() { let r = ResilientContainer() useP(r.inlineableProperty.myValue3()) } // CHECK-LABEL: sil @$s1A31testResilientInlinableProperty3yyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External218ResilientContainerV19inlineableProperty2Qrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientInlinableProperty3() { let r = ResilientContainer() useP(r.inlineableProperty2.myValue3()) } // CHECK-LABEL: sil @$s1A22testResilientProperty2yyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer2 // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External319ResilientContainer2V16computedPropertyQrvp", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External319ResilientContainer2V16computedPropertyQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientProperty2() { let r = ResilientContainer2() useP(r.computedProperty.myValue3()) } // The inlinable property recursively calls an resilient property 'peel' one layer of opaque archetypes. // CHECK-LABEL: sil @$s1A31testResilientInlinableProperty2yyF // CHECK: [[CONTAINER:%.*]] = alloc_stack $ResilientContainer2 // CHECK: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External218ResilientContainerV16computedPropertyQrvp", 0) // CHECK: [[FUN:%.*]] = function_ref @$s9External319ResilientContainer2V18inlineablePropertyQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINER]]) public func testResilientInlinableProperty2() { let r = ResilientContainer2() useP(r.inlineableProperty.myValue3()) } // CHECK-LABEL: sil @$s1A035testResilientInlinablePropertyCallsbC0yyF : $@convention(thin) () -> () { // CHECK: [[CONTAINTER:%.*]] = alloc_stack $ResilientContainer2 // CHECK: [[RES:%.*]] = alloc_stack $Int64 // CHECK: [[FUN:%.*]] = function_ref @$s9External319ResilientContainer2V023inlineablePropertyCallsB10InlineableQrvg // CHECK: apply [[FUN]]([[RES]], [[CONTAINTER]]) public func testResilientInlinablePropertyCallsResilientInlinable() { let r = ResilientContainer2() useP(r.inlineablePropertyCallsResilientInlineable.myValue3()) } // RESILIENT-LABEL: sil [serialized] [canonical] @$s9External218ResilientContainerV17inlineableContextyyF // RESILIENT: [[RES:%.*]] = alloc_stack $@_opaqueReturnTypeOf("$s9External218ResilientContainerV16computedPropertyQrvp", 0) // RESILIENT: [[FUN:%.*]] = function_ref @$s9External218ResilientContainerV16computedPropertyQrvg // RESILIENT: apply [[FUN]]([[RES]], %0) public protocol P4 { associatedtype AT func foo(_ x: Int64) -> AT func test() } struct PA : P4 { func foo(_ x: Int64) -> some P { return Int64(x) } } // CHECK-LABEL: sil private [transparent] [thunk] @$s1A2PAVAA2P4A2aDP4testyyFTW // CHECK: [[V:%.*]] = load %0 : $*PA // CHECK: [[F:%.*]] = function_ref @$s1A2PAV4testyyF // CHECK: apply [[F]]([[V]]) // CHECK-64-LABEL: sil hidden @$s1A2PAV4testyyF : $@convention(method) (PA) -> () // CHECK-64: [[V:%.*]] = integer_literal $Builtin.Int64, 5 // CHECK-64: [[I:%.*]] = struct $Int64 ([[V]] : $Builtin.Int64) // CHECK-64: [[F:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 // CHECK-64: apply [[F]]([[I]]) : $@convention(thin) (Int64) -> () // CHECK-64: apply [[F]]([[I]]) : $@convention(thin) (Int64) -> () @inline(never) func testIt<T>(cl: (Int64) throws -> T) { do { print(try cl(5)) } catch (_) {} } // CHECK-LABEL: sil shared [noinline] @$s1A16testPartialApplyyyxAA2P4RzlFAA2PAV_Tg5 // CHECK: [[PA:%.*]] = alloc_stack $PA // CHECK: store %0 to [[PA]] : $*PA // CHECK: [[F:%.*]] = function_ref @$s1A16testPartialApplyyyxAA2P4RzlF2ATQzs5Int64Vcxcfu_AeGcfu0_AA2PAV_TG5 : $@convention(thin) (Int64, @in_guaranteed PA) -> @out Int64 // CHECK: [[C:%.*]] = partial_apply [callee_guaranteed] [[F]]([[PA]]) : $@convention(thin) (Int64, @in_guaranteed PA) -> @out Int64 // CHECK: convert_function [[C]] : $@callee_guaranteed (Int64) -> @out Int64 to $@callee_guaranteed @substituted <τ_0_0> (Int64) -> (@out τ_0_0, @error Error) for <Int64> @inline(never) func testPartialApply<T: P4>(_ t: T) { let fun = t.foo testIt(cl: fun) print(fun(5)) } public func testPartialApply() { testPartialApply(PA()) } struct Trivial<T> { var x : Int64 } func createTrivial<T>(_ t: T) -> Trivial<T> { return Trivial<T>(x: 1) } // CHECK: sil @$s1A11testTrivialyyF : $@convention(thin) () -> () // CHECK: %0 = integer_literal $Builtin.Int64, 1 // CHECK: %1 = struct $Int64 (%0 : $Builtin.Int64) // CHECK: %2 = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () // CHECK: %3 = apply %2(%1) public func testTrivial() { let s = bar(10) let t = createTrivial(s) useP(t.x) } func createTuple<T>(_ t: T) -> (T,T) { return (t, t) } // CHECK: sil @$s1A9testTupleyyF // CHECK: [[I:%.*]] = integer_literal $Builtin.Int64, 10 // CHECK: [[I2:%.*]] = struct $Int64 ([[I]] : $Builtin.Int64) // CHECK: [[F:%.*]] = function_ref @$s1A4usePyyxAA1PRzlFs5Int64V_Tg5 : $@convention(thin) (Int64) -> () // CHECK: apply [[F]]([[I2]]) : $@convention(thin) (Int64) -> () // CHECK: apply [[F]]([[I2]]) : $@convention(thin) (Int64) -> () public func testTuple() { let s = bar(10) let t = createTuple(s) useP(t.0) useP(t.1) } extension PA { func test() { var p = (foo, foo) useP(p.0(5)) useP(p.1(5)) } } public struct Foo { var id : Int = 0 var p : Int64 = 1 } struct Test : RandomAccessCollection { struct Index : Comparable, Hashable { var identifier: AnyHashable? var offset: Int static func < (lhs: Index, rhs: Index) -> Bool { return lhs.offset < rhs.offset } func hash(into hasher: inout Hasher) { hasher.combine(identifier) hasher.combine(offset) } } let foos: [Foo] let ids: [AnyHashable] init(foos: [Foo]) { self.foos = foos self.ids = foos.map { $0.id } } func _index(atOffset n: Int) -> Index { return Index(identifier: ids.isEmpty ? nil : ids[n], offset: n) } var startIndex: Index { return _index(atOffset: 0) } var endIndex: Index { return Index(identifier: nil, offset: ids.endIndex) } func index(after i: Index) -> Index { return _index(atOffset: i.offset + 1) } func index(before i: Index) -> Index { return _index(atOffset: i.offset - 1) } func distance(from start: Index, to end: Index) -> Int { return end.offset - start.offset } func index(_ i: Index, offsetBy n: Int) -> Index { return _index(atOffset: i.offset + n) } subscript(i: Index) -> some P { return foos[i.offset].p } } @inline(never) func useAbstractFunction<T: P>(_ fn: (Int64) -> T) {} public func testThinToThick() { useAbstractFunction(bar) } // CHECK-LABEL: sil @$s1A19rdar56410009_normalyyF public func rdar56410009_normal() { // CHECK: [[EXTERNAL_RESILIENT_WRAPPER:%.+]] = function_ref @$s9External224externalResilientWrapperyQrxAA10ExternalP2RzlF // CHECK: = apply [[EXTERNAL_RESILIENT_WRAPPER]]<@_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) __>({{%.+}}, {{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : ExternalP2> (@in_guaranteed τ_0_0) -> @out @_opaqueReturnTypeOf("$s9External224externalResilientWrapperyQrxAA10ExternalP2RzlF", 0) __<τ_0_0> _ = externalResilientWrapper(externalResilient()) } // CHECK: end sil function '$s1A19rdar56410009_normalyyF' // CHECK-LABEL: sil @$s1A25rdar56410009_inlinedInneryyF public func rdar56410009_inlinedInner() { // CHECK: [[EXTERNAL_RESILIENT_WRAPPER:%.+]] = function_ref @$s9External224externalResilientWrapperyQrxAA10ExternalP2RzlF // CHECK: = apply [[EXTERNAL_RESILIENT_WRAPPER]]<Int64>({{%.+}}, {{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : ExternalP2> (@in_guaranteed τ_0_0) -> @out @_opaqueReturnTypeOf("$s9External224externalResilientWrapperyQrxAA10ExternalP2RzlF", 0) __<τ_0_0> _ = externalResilientWrapper(inlinableExternalResilient()) } // CHECK: end sil function '$s1A25rdar56410009_inlinedInneryyF' // CHECK-LABEL: sil @$s1A25rdar56410009_inlinedOuteryyF public func rdar56410009_inlinedOuter() { // CHECK: [[INLINABLE_EXTERNAL_RESILIENT_WRAPPER:%.+]] = function_ref @$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFAA08externalD0QryFQOyQo__Tg5 // CHECK: = apply [[INLINABLE_EXTERNAL_RESILIENT_WRAPPER]]({{%.+}}, {{%.+}}) : $@convention(thin) (@in_guaranteed @_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) __) -> @out WrapperP2<@_opaqueReturnTypeOf("$s9External217externalResilientQryF" _ = inlinableExternalResilientWrapper(externalResilient()) } // CHECK: end sil function '$s1A25rdar56410009_inlinedOuteryyF' // Specialized from above // CHECK-LABEL: sil shared [noinline] @$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFAA08externalD0QryFQOyQo__Tg5 // CHECK: [[WRAPPER_INIT:%.+]] = function_ref @$s9External29WrapperP2VyACyxGxcfC // CHECK: = apply [[WRAPPER_INIT]]<@_opaqueReturnTypeOf("$s9External217externalResilientQryF", 0) __>({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : ExternalP2> (@in τ_0_0, @thin WrapperP2<τ_0_0>.Type) -> @out WrapperP2<τ_0_0> // CHECK: end sil function '$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFAA08externalD0QryFQOyQo__Tg5' // Specialized from below // CHECK-LABEL: sil shared [noinline] @$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFs5Int64V_Tg5 // CHECK: [[WRAPPER_INIT:%.+]] = function_ref @$s9External29WrapperP2VyACyxGxcfC // CHECK: = apply [[WRAPPER_INIT]]<Int64>({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : ExternalP2> (@in τ_0_0, @thin WrapperP2<τ_0_0>.Type) -> @out WrapperP2<τ_0_0> // CHECK: end sil function '$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFs5Int64V_Tg5' // CHECK-LABEL: sil @$s1A24rdar56410009_inlinedBothyyF public func rdar56410009_inlinedBoth() { // CHECK: [[INLINABLE_EXTERNAL_RESILIENT_WRAPPER:%.+]] = function_ref @$s9External233inlinableExternalResilientWrapperyQrxAA0C2P2RzlFs5Int64V_Tg5 // CHECK: = apply [[INLINABLE_EXTERNAL_RESILIENT_WRAPPER]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int64) -> @out WrapperP2<Int64> _ = inlinableExternalResilientWrapper(inlinableExternalResilient()) } // CHECK: end sil function '$s1A24rdar56410009_inlinedBothyyF'
36.118966
318
0.683278
9b25b5b6922049bc2b9288b5b967b97b708c9bd6
100
enum Spread: CaseIterable, Equatable { case butter case hazelnutChocolate case hummus }
16.666667
38
0.72
ab8fc57c7d1c7ae45897221ee4aa63910d909cc3
1,588
// // CustomPresentAnimationController.swift // ViewControllerTransition // // Created by Kaushal Elsewhere on 2/09/2016. // Copyright © 2016 Kaushal Elsewhere. All rights reserved. // import UIKit class CustomPresentAnimationController: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 2.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let finalFrameForVC = transitionContext.finalFrameForViewController(toViewController) let containerView = transitionContext.containerView() let bounds = UIScreen.mainScreen().bounds toViewController.view.frame = CGRectOffset(finalFrameForVC, 0, bounds.size.height) containerView!.addSubview(toViewController.view) UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: .CurveLinear, animations: { fromViewController.view.alpha = 0.5 toViewController.view.frame = finalFrameForVC }, completion: { finished in transitionContext.completeTransition(true) fromViewController.view.alpha = 1.0 }) } }
42.918919
179
0.733627
5df55dce3975e88f8b5ace5fc5945eaea8190318
4,295
// // Nnn.swift // YBIMSDK // // Created by apolla on 2020/1/19. // Copyright © 2015 Hilen. All rights reserved. // import Foundation /// PDF image size : 20px * 20px is perfect one public typealias ActionHandler = () -> Void public extension UIViewController { //Back bar with custom action func leftBackAction(_ action: @escaping ActionHandler) { self.leftBackBarButton(TSAsset.Back_icon.image, action: action) } //Back bar with go to previous action func leftBackToPrevious() { self.leftBackBarButton(TSAsset.Back_icon.image, action: nil) } //back action fileprivate func leftBackBarButton(_ backImage: UIImage, action: ActionHandler!) { guard self.navigationController != nil else { assert(false, "Your target ViewController doesn't have a UINavigationController") return } let button: UIButton = UIButton(type: UIButton.ButtonType.custom) button.setImage(backImage, for: UIControl.State()) button.frame = CGRect(x: 0, y: 0, width: 40, height: 30) button.imageView!.contentMode = .scaleAspectFit; button.contentHorizontalAlignment = .left button.ngl_addAction(forControlEvents: .touchUpInside, withCallback: {[weak self] in //If custom action ,call back if action != nil { action() return } if self!.navigationController!.viewControllers.count > 1 { self!.navigationController?.popViewController(animated: true) } else if (self!.presentingViewController != nil) { self!.dismiss(animated: true, completion: nil) } }) let barButton = UIBarButtonItem(customView: button) let gapItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) gapItem.width = -7 //fix the space self.navigationItem.leftBarButtonItems = [gapItem, barButton] } } public extension UINavigationItem { //left bar func leftButtonAction(_ image: UIImage, action:@escaping ActionHandler) { let button: UIButton = UIButton(type: UIButton.ButtonType.custom) button.setImage(image, for: UIControl.State()) button.frame = CGRect(x: 0, y: 0, width: 40, height: 30) button.imageView!.contentMode = .scaleAspectFit; button.contentHorizontalAlignment = .left button.ngl_addAction(forControlEvents: .touchUpInside, withCallback: { action() }) let barButton = UIBarButtonItem(customView: button) let gapItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) gapItem.width = -7 //fix the space self.leftBarButtonItems = [gapItem, barButton] } //right bar func rightButtonAction(_ image: UIImage, action:@escaping ActionHandler) { let button: UIButton = UIButton(type: UIButton.ButtonType.custom) button.setImage(image, for: UIControl.State()) button.frame = CGRect(x: 0, y: 0, width: 40, height: 30) button.imageView!.contentMode = .scaleAspectFit; button.contentHorizontalAlignment = .right button.ngl_addAction(forControlEvents: .touchUpInside, withCallback: { action() }) let barButton = UIBarButtonItem(customView: button) let gapItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) gapItem.width = -7 //fix the space self.rightBarButtonItems = [gapItem, barButton] } } /* Block of UIControl */ open class ClosureWrapper : NSObject { let _callback : () -> Void init(callback : @escaping () -> Void) { _callback = callback } @objc open func invoke() { _callback() } } var AssociatedClosure: UInt8 = 0 extension UIControl { fileprivate func ngl_addAction(forControlEvents events: UIControl.Event, withCallback callback: @escaping () -> Void) { let wrapper = ClosureWrapper(callback: callback) addTarget(wrapper, action:#selector(ClosureWrapper.invoke), for: events) objc_setAssociatedObject(self, &AssociatedClosure, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } }
36.092437
125
0.655646
214c0d305c5d03edd203e7010838b94d541ff582
2,001
// // ImageLoader.swift // iTunesSearchSave2019 // // Created by Staszek on 26/12/2019. // Copyright © 2019 st4n. All rights reserved. // import UIKit class ImageLoader: NSObject { private var loadedImages = NSCache<NSString, UIImage>() private var runningRequests = [UUID: URLSessionTask]() typealias ImageLoaderHandler = (Result<UIImage, APIError>) -> Void func loadImage(_ urlString: String, _ completion: @escaping ImageLoaderHandler) -> UUID? { if let image = loadedImages.object(forKey: NSString(string: urlString)) { completion(.success(image)) return nil } let uuid = UUID() guard let url = URL(string: urlString) else { completion(.failure(.invalidUrl)) return nil } let task = URLSession.shared.dataTask(with: url) { data, response, error in defer { self.runningRequests.removeValue(forKey: uuid)} if let error = error { if (error as NSError).code == NSURLErrorCancelled { return } else { completion(.failure(.otherError(error))) } } guard let HTTPResponse = response as? HTTPURLResponse, 200 ..< 300 ~= HTTPResponse.statusCode else { completion(.failure(.badResponse)) return } if let data = data, let image = UIImage(data: data) { self.loadedImages.setObject(image, forKey: NSString(string: urlString)) completion(.success(image)) } else { completion(.failure(.badData)) } } task.resume() runningRequests[uuid] = task return uuid } func cancelLoad(_ uuid: UUID) { runningRequests[uuid]?.cancel() runningRequests.removeValue(forKey: uuid) } }
31.265625
94
0.544228
29cf92dd7fd7aaf520ff341d77f0206e8ee257b3
2,478
// // CandidateSelector.swift // Tracery // // Created by Benzi on 11/03/17. // Copyright © 2017 Benzi Ahamed. All rights reserved. // import XCTest @testable import Tracery class CandidateSelector : XCTestCase { func testRuleCandidateSelectorIsInvoked() { let t = Tracery {[ "msg" : ["hello", "world"] ]} let selector = AlwaysPickFirst() t.setCandidateSelector(rule: "msg", selector: selector) XCTAssertEqual(t.expand("#msg#"), "hello") } func testRuleCandidateSelectorBogusSelectionsAreIgnored() { let t = Tracery {[ "msg" : ["hello", "world"] ]} let selector = BogusSelector() t.setCandidateSelector(rule: "msg", selector: selector) XCTAssertEqual(t.expand("#msg#"), "#msg#") } func testRuleCandidateSelectorReturnValueIsAlwaysHonoured() { let t = Tracery {[ "msg" : ["hello", "world"] ]} let selector = PickSpecificItem(offset: .fromEnd(0)) t.setCandidateSelector(rule: "msg", selector: selector) var tracker = [ "hello": 0, "world": 0, ] t.add(modifier: "track") { let count = tracker[$0] ?? 0 tracker[$0] = count + 1 return $0 } let target = 10 for _ in 0..<target { XCTAssertEqual(t.expand("#msg.track#"), "world") } XCTAssertEqual(tracker["hello"], 0) XCTAssertEqual(tracker["world"], target) } func testDefaultRuleCandidateSelectorIsUniformlyDistributed() { let animals = ["unicorn","raven","sparrow","scorpion","coyote","eagle","owl","lizard","zebra","duck","kitten"] var tracker = [String: Int]() animals.forEach { tracker[$0] = 0 } let t = Tracery { ["animal" : animals] } t.add(modifier: "track") { let count = tracker[$0] ?? 0 tracker[$0] = count + 1 return $0 } let invokesPerItem = 10 for _ in 0..<(invokesPerItem * animals.count) { XCTAssertItemInArray(item: t.expand("#animal.track#"), array: animals) } for key in tracker.keys { XCTAssertEqual(tracker[key], invokesPerItem) } } }
25.030303
118
0.510089
672d20a9fb81833cd3002d7dfe5a734284143ae9
251
// // ViewController.swift // TeamupCal-Example // // Created by Merrick Sapsford on 14/11/2017. // Copyright © 2017 AMRAP Labs. All rights reserved. // import UIKit import TeamupKit import TeamupCal class ViewController: UIViewController { }
14.764706
53
0.733068
ff028c522d61c222f646edd815fc69fa03b2e4c0
829
// // PBXFileReference.swift // XcodeProjKit // // Created by phimage on 30/07/2017. // Copyright © 2017 phimage (Eric Marchand). All rights reserved. // import Foundation public class PBXFileReference: PBXReference { public enum PBXKeys: PBXKey { case lastKnownFileType case explicitFileType } #if LAZY public lazy var lastKnownFileType: String? = self.string(PBXKeys.lastKnownFileType) public lazy var explicitFileType: String? = self.string(PBXKeys.explicitFileType) #else public var lastKnownFileType: String? { self.string(PBXKeys.lastKnownFileType) } public var explicitFileType: String? { self.string(PBXKeys.explicitFileType) } #endif public func fullPath(_ project: XcodeProj) -> PathType? { return project.objects.fullFilePaths[self.ref] } }
26.741935
87
0.71532
39321bf360dd90fcd7e9a10fdc550c685e7bc2ce
198
// // ViewController.swift // // Created by Jose Saldana. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
10.421053
40
0.626263
d980ebb3d7dba1849f26d5d8fd64365f8e46e45b
549
// // BetaTesterInvitation.swift // AppStoreConnect-Swift-SDK // // Created by Pascal Edmond on 12/11/2018. // import Foundation /// The data structure that represents the resource. public struct BetaTesterInvitation: Decodable { /// (Required) The opaque resource ID that uniquely identifies the resource. public let `id`: String /// (Required) The resource type.Value: betaTesterInvitations public let type: String /// (Required) Navigational links that include the self-link. public let links: ResourceLinks }
24.954545
80
0.721311
26ed275ad5e8d17e4461659dbf260bffa26e9bfe
5,461
// Copyright © 2018 Square1. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import CoreData public protocol FRCTableViewDataSourceDelegate: class { associatedtype Object: NSFetchRequestResult associatedtype Cell: UITableViewCell func configure(_ cell: Cell, for object: Object) func dataSourceDidChangeContent() } public class FRCTableViewDataSource<Delegate: FRCTableViewDataSourceDelegate>: NSObject, UITableViewDataSource, NSFetchedResultsControllerDelegate { public typealias Object = Delegate.Object public typealias Cell = Delegate.Cell fileprivate let tableView: UITableView fileprivate let fetchedResultsController: NSFetchedResultsController<Object> fileprivate weak var delegate: Delegate! fileprivate let cellIdentifier: String public var count: Int { return fetchedResultsController.fetchedObjects?.count ?? 0 } public init(tableView: UITableView, cellIdentifier: String, fetchedResultsController: NSFetchedResultsController<Object>, delegate: Delegate) { self.tableView = tableView self.fetchedResultsController = fetchedResultsController self.cellIdentifier = cellIdentifier self.delegate = delegate super.init() fetchedResultsController.delegate = self try! fetchedResultsController.performFetch() tableView.dataSource = self tableView.reloadData() } public var selectedObject: Object? { guard let indexPath = tableView.indexPathForSelectedRow else { return nil } return objectAtIndexPath(indexPath) } public func objectAtIndexPath(_ indexPath: IndexPath) -> Object { return fetchedResultsController.object(at: indexPath) } public func reconfigureFetchRequest(_ configure: (NSFetchRequest<Object>) -> ()){ NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: fetchedResultsController.cacheName) configure(fetchedResultsController.fetchRequest) do { try fetchedResultsController.performFetch() } catch { fatalError("Error performing fetch request") } tableView.reloadData() } // MARK: - UITableViewDataSource public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let section = fetchedResultsController.sections?[section] else { return 0 } return section.numberOfObjects } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let object = fetchedResultsController.object(at: indexPath) guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? Cell else { fatalError("Unexpected cell type for indentifier \(cellIdentifier) at indexPath \(indexPath)") } delegate.configure(cell, for: object) return cell } // MARK: - NSFetchedResultsControllerDelegate public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.beginUpdates() } public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: guard let indexPath = newIndexPath else { fatalError("IndexPath can't be nil") } tableView.insertRows(at: [indexPath], with: .fade) case .update: guard let indexPath = indexPath else { fatalError("IndexPath can't be nil") } let object = objectAtIndexPath(indexPath) guard let cell = tableView.cellForRow(at: indexPath) as? Cell else { break } delegate.configure(cell, for: object) case .move: guard let indexPath = indexPath else { fatalError("IndexPath can't be nil") } guard let newIndexPath = newIndexPath else { fatalError("IndexPath can't be nil") } tableView.deleteRows(at: [indexPath], with: .fade) tableView.insertRows(at: [newIndexPath], with: .fade) case .delete: guard let indexPath = indexPath else { fatalError("IndexPath can't be nil") } tableView.deleteRows(at: [indexPath], with: .fade) } } public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView.endUpdates() delegate.dataSourceDidChangeContent() } }
41.371212
148
0.73796
dbc728b0f328f08e004f4ddb918deac1e01b5845
15,174
// // AlarmScheduler.swift // Alarm-ios-swift // // Created by longyutao on 16/1/15. // Copyright (c) 2016年 LongGames. All rights reserved. // import Foundation import UIKit import UserNotifications protocol TimerElapsedDelegate: class { func onAlarmTimeElapsed(forAlarm alarm: Alarm) } class AlarmScheduler { weak var alarmModelController: AlarmModelController! var notificationRequestIds = [String]() var backgroundTimers = [Timer]() weak var timerElapsedDelegate: TimerElapsedDelegate? init() { self.requestNotificationAuthorization { granted in if granted { self.setupNotificationCategories() } } } private func setupNotificationCategories() { // Specify the notification actions. let stopAction = UNNotificationAction( identifier: AlarmIdentifier.NotificationAction.stop, title: "OK", options: []) let snoozeAction = UNNotificationAction( identifier: AlarmIdentifier.NotificationAction.snooze, title: "Snooze", options: []) // create categories let snoozeNotificationCategory = UNNotificationCategory( identifier: AlarmIdentifier.NotificationCategory.snooze, actions: [stopAction, snoozeAction], intentIdentifiers: [], options: [.customDismissAction]) let noSnoozeNotificationCategory = UNNotificationCategory( identifier: AlarmIdentifier.NotificationCategory.noSnooze, actions: [stopAction], intentIdentifiers: [], options: [.customDismissAction]) //TODO: clarify alarmCategory.minimalActions = notificationActions UNUserNotificationCenter.current().getNotificationCategories { existingCategories in for existingCategory in existingCategories { print("Existing Notification Category: \(existingCategory)") } // let the notification center know about the not. categories let notificationCategories: Set = [snoozeNotificationCategory, noSnoozeNotificationCategory] UNUserNotificationCenter.current().setNotificationCategories(notificationCategories) } } private func requestNotificationAuthorization(authorisationGranted: @escaping (Bool) -> Void) { let options: UNAuthorizationOptions = [.alert, .sound] UNUserNotificationCenter.current().requestAuthorization(options: options) { (granted, error) in if !granted { print("User denied Local Notification Authorization rights") if let error = error { print("Error: \(error)") } // TODO: show alert view explaining why it sucks to have no permissions, // pressing OK, ask again, pressing cancel accept the result, which is // OK as we will ask again on next creation atempt authorisationGranted(false) } else { print("Notification authorization granted by user") authorisationGranted(true) } } } private func createNotificationDates(forAlarm alarm: Alarm) -> [Date] { var notificationDates = [Date]() let calendar = Calendar(identifier: Calendar.Identifier.gregorian) let now = Date() //no repeat if !alarm.isRepeating() { //scheduling date is earlier than current date if alarm.alertDate < now { //plus one day, otherwise the notification will be fired righton notificationDates.append(alarm.alertDate.toSomeDaysLaterDate(daysToAdd: 1)) } else { //later notificationDates.append(alarm.alertDate) } return notificationDates } //repeat else { let componentsToExtract: Set<Calendar.Component> = [.weekday, .weekdayOrdinal, .day] let dateComponents = calendar.dateComponents(componentsToExtract, from: alarm.alertDate) guard let dayOfAlertDate: Int = dateComponents.weekday, let weekdayOfAlertDate = Weekday(rawValue: dayOfAlertDate) else { return notificationDates } let daysInWeek = Weekday.all().count notificationDates.removeAll(keepingCapacity: true) for repetitionWeekday in alarm.repeatAtWeekdays { var dateOfWeekday: Date //schedule on next week let comparisonResult = repetitionWeekday.compare(with: weekdayOfAlertDate) switch comparisonResult { case .before: dateOfWeekday = alarm.alertDate.toSomeDaysLaterDate(daysToAdd: repetitionWeekday.dayInWeek() + daysInWeek - weekdayOfAlertDate.dayInWeek()) case .same: //scheduling date is earlier than current date, then schedule on next week if alarm.alertDate.compare(now) == ComparisonResult.orderedAscending { dateOfWeekday = alarm.alertDate.toSomeDaysLaterDate(daysToAdd: daysInWeek) } else { //later dateOfWeekday = alarm.alertDate } case .after: dateOfWeekday = alarm.alertDate.toSomeDaysLaterDate(daysToAdd: repetitionWeekday.dayInWeek() - weekdayOfAlertDate.dayInWeek()) } //fix second component to 0 dateOfWeekday = dateOfWeekday.toMinutesRoundedDate() notificationDates.append(dateOfWeekday) } return notificationDates } } private func addNotification(forAlarm alarm: Alarm) { let datesForNotification = self.createNotificationDates(forAlarm: alarm) addBackgroundTimer(alarm: alarm) requestNotificationAuthorization { granted in if !granted { print("ERROR: Cannot create notification without user's permission") return } let content = self.createNotificationContent(forAlarm: alarm) var notificationRequests = [UNNotificationRequest]() for notificationDate in datesForNotification { let alarmNotificationRequest = self.createNotificationRequest( notificationDate: notificationDate, isRepeating: alarm.isRepeating(), content: content) notificationRequests.append(alarmNotificationRequest) } for notificationRequest in notificationRequests { UNUserNotificationCenter.current().add(notificationRequest) { (error) in if let error = error { print("Unable to Add Notification Request: \(error)") } else { print("Created Notification Request: \(notificationRequest)") } } } } } private func addBackgroundTimer(alarm: Alarm) { if !alarm.isRepeating() { let timeUntilFirstAlarm = alarm.alertDate.timeIntervalSinceReferenceDate - Date().timeIntervalSinceReferenceDate let timer = Timer.scheduledTimer(withTimeInterval: timeUntilFirstAlarm, repeats: false) { timer in print("Timer \(timer) elapsed of alarm \(alarm.alarmName)") self.timerElapsedDelegate?.onAlarmTimeElapsed(forAlarm: alarm) } self.backgroundTimers.append(timer) } else { let oneWeekInSeconds = 7 * 24 * 60 * 60.0 let notificationDates = self.createNotificationDates(forAlarm: alarm) for notificationDate in notificationDates { let timer = Timer(fire: notificationDate, interval: oneWeekInSeconds, repeats: true) { timer in print("Timer \(timer) elapsed of alarm \(alarm.alarmName)") self.timerElapsedDelegate?.onAlarmTimeElapsed(forAlarm: alarm) } self.backgroundTimers.append(timer) } } self.backgroundTimers.forEach { timer in print("Created timer: Fires next: \(timer.fireDate) in interval of \(timer.timeInterval/60/60) hours") } } private func createNotificationRequest(notificationDate: Date, isRepeating: Bool, content: UNMutableNotificationContent) -> UNNotificationRequest { let notificationDateTrigger = createNotificationTrigger( notificationDate: notificationDate.toMinutesRoundedDate(), isRepeating: isRepeating) // Make them unique let identifier = "AlarmNotificationRequest_\(UUID().uuidString)" self.notificationRequestIds.append(identifier) let alarmNotificationRequest = UNNotificationRequest( identifier: identifier, content: content, trigger: notificationDateTrigger) return alarmNotificationRequest } private func createNotificationTrigger(notificationDate: Date, isRepeating: Bool) -> UNNotificationTrigger { var notificationDateComponents: DateComponents if !isRepeating { notificationDateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: notificationDate) } else { notificationDateComponents = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: notificationDate) } let notificationDateTrigger = UNCalendarNotificationTrigger( dateMatching: notificationDateComponents, repeats: isRepeating) return notificationDateTrigger } private func createNotificationContent(forAlarm alarm: Alarm) -> UNMutableNotificationContent { let content = UNMutableNotificationContent() content.title = "Alarm: \(alarm.alarmName)" content.body = "Wake Up!" // TODO: think about criticalSound content.sound = UNNotificationSound(named: UNNotificationSoundName(alarm.mediaLabel + ".mp3")) if alarm.snoozeEnabled { content.categoryIdentifier = AlarmIdentifier.NotificationCategory.snooze } else { content.categoryIdentifier = AlarmIdentifier.NotificationCategory.noSnooze } let userInfo = UserInfo() userInfo.index = alarm.indexInTable userInfo.soundName = alarm.mediaLabel userInfo.isSnoozeEnabled = alarm.snoozeEnabled userInfo.repeating = alarm.isRepeating() // add user info to content content.userInfo = userInfo.userInfoDictionary return content } func scheduleSnoozeNotification(snoozeForMinutes: Int, soundName: String) { let now = Date() let snoozeTime = now.toSomeMinutesLaterDate(minutesToAdd: snoozeForMinutes).toMinutesRoundedDate() let snoozeAlarm = Alarm() snoozeAlarm.alertDate = snoozeTime snoozeAlarm.repeatAtWeekdays = [Weekday]() snoozeAlarm.snoozeEnabled = true snoozeAlarm.mediaLabel = soundName addNotification(forAlarm: snoozeAlarm) } func recreateNotificationsFromDataModel() { //printNotificationSettings() removeExistingNotifications() for alarmIndex in 0..<self.alarmModelController.alarmCount { if let alarm = self.alarmModelController.getAlarmAtTableIndex(index: alarmIndex) { if alarm.enabled { self.addNotification(forAlarm: alarm) } } } printPendingNotificationRequests(context: "After adding ") } private func removeExistingNotifications() { printPendingNotificationRequests(context: "Before removal") //cancel all and register all is often more convenient //UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: self.notificationRequestIds) UNUserNotificationCenter.current().removeAllDeliveredNotifications() //UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: self.notificationRequestIds) UNUserNotificationCenter.current().removeAllPendingNotificationRequests() self.notificationRequestIds.removeAll() // remove all timers self.backgroundTimers.forEach { timer in timer.invalidate() } self.backgroundTimers.removeAll() printPendingNotificationRequests(context: "After removal") } private func printPendingNotificationRequests(context: String) { UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in let count = notificationRequests.count print("\(context) Existing Pending Notification Requests: \(count)") notificationRequests.forEach({ (request) in print("\(context) Pending: Notification Request: \(request)") }) } } private func printNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in print("Notification Settings: \(settings)") } } // workaround for some situation that alarm model is not setting properly (when app on background or not launched) func disableAlarmsIfOutdated() { UNUserNotificationCenter.current().getPendingNotificationRequests { (pendingNotifications) in let count = pendingNotifications.count if count == 0 { self.alarmModelController.disableAllAlarms() } else { for alarmIndex in 0..<self.alarmModelController.alarmCount { if let alarm = self.alarmModelController.getAlarmAtTableIndex(index: alarmIndex) { var isOutDated = true for notification in pendingNotifications { if let trigger = notification.trigger as? UNCalendarNotificationTrigger { if let nextFireDate = trigger.nextTriggerDate() { if alarm.alertDate >= nextFireDate { isOutDated = false } } } } if isOutDated { alarm.enabled = false } } } } } } }
37.840399
124
0.605641
38203db3d00eea5a30527bec3d1552a7946d3638
447
// // APIManager_Example.swift // PROJECT // // Created by PROJECT_OWNER on TODAYS_DATE. // Copyright (c) TODAYS_YEAR PROJECT_OWNER. All rights reserved. // import UIKit import URLNavigator import YHLCore import ${POD_NAME} /// 这里是给Example工程的调用示例 extension APIManager { func registAllRouter() { distributeRouter${POD_NAME}Service(YHLNavigator.shared) distributeRouter${POD_NAME}ServiceExample(YHLNavigator.shared) } }
22.35
70
0.744966
2077c2988cba24362dafa755a4cbb560292c3218
2,984
//: [Previous](@previous) import Foundation import Combine var subscriptions = Set<AnyCancellable>() //:## Mapping errors example(of: "map vs tryMap") { enum NameError: Error { case tooShort(String) case unknown } Just("Hello") .setFailureType(to: NameError.self) .tryMap { $0 + " World" } .mapError { $0 as? NameError ?? .unknown} .sink { completion in switch completion { case .finished: print("Done!") case .failure(.tooShort(let name)): print("\(name) is too short!") case .failure(.unknown): print("An unknown error!") } } receiveValue: { print("Got Value: \($0)") } .store(in: &subscriptions) } example(of: "mapError") { enum NameError: Error { case tooShort(String) case unknown } Just("Hello") .setFailureType(to: NameError.self) .tryMap { throw NameError.tooShort($0) } .mapError { $0 as? NameError ?? .unknown} .sink { completion in switch completion { case .finished: print("Done!") case .failure(.tooShort(let name)): print("\(name) is too short!") case .failure(.unknown): print("An unknown error!") } } receiveValue: { print("Got Value: \($0)") } .store(in: &subscriptions) } //: [Next](@next) /// Copyright (c) 2019 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// 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.
34.298851
83
0.677949
dbbde82b2a41b0cd5307643965b4dad39657bd63
629
// // WebViewController.swift // zly-ofo // // Created by 郑乐银 on 2017/5/18. // Copyright © 2017年 郑乐银. All rights reserved. // import UIKit import WebKit class WebViewController: UIViewController { @IBOutlet weak var webView: UIWebView! var wkWebView : WKWebView! override func viewDidLoad() { super.viewDidLoad() self.title = "活动中心" wkWebView = WKWebView(frame: self.view.frame) view.addSubview(wkWebView) let url = URL(string: "http://m.ofo.so/active.html")! let request = URLRequest(url: url); wkWebView.load(request) } }
17.971429
57
0.616852
4bd7badd9026f6735759b9ddd0d86382c312fbad
7,743
import QueueCommunication import QueueModels import XCTest class WorkersToUtilizeCalculatorTests: XCTestCase { private let calculator = DefaultWorkersToUtilizeCalculator(logger: .noOp) func test___disjoint___with_equal_number_of_workers_and_versions() { let initialWorkers = buildWorkers(count: 4) let initialMapping = buildMapping(versionsCount: 4, workers: initialWorkers) let mapping = calculator.disjointWorkers(mapping: initialMapping) let workers = mapping.values.flatMap { $0 } XCTAssertEqual(mapping["V1"]?.count, 1) XCTAssertEqual(mapping["V2"]?.count, 1) XCTAssertEqual(mapping["V3"]?.count, 1) XCTAssertEqual(mapping["V4"]?.count, 1) XCTAssertEqual(Set(workers), Set(initialWorkers)) } func test___disjoint___with_less_versions_then_deployments() { let initialWorkers = buildWorkers(count: 4) let initialMapping = buildMapping(versionsCount: 2, workers: initialWorkers) let mapping = calculator.disjointWorkers(mapping: initialMapping) let workers = mapping.values.flatMap { $0 } XCTAssertEqual(mapping["V1"]?.count, 2) XCTAssertEqual(mapping["V2"]?.count, 2) XCTAssertEqual(Set(workers), Set(initialWorkers)) } func test___disjoint___with_more_versions_then_deployments() { let initialWorkers = buildWorkers(count: 3) let initialMapping = buildMapping(versionsCount: 4, workers: initialWorkers) let mapping = calculator.disjointWorkers(mapping: initialMapping) let workers = mapping.values.flatMap { $0 } XCTAssertEqual(mapping["V1"]?.count, 1) XCTAssertEqual(mapping["V2"]?.count, 1) XCTAssertEqual(mapping["V3"]?.count, 1) XCTAssertEqual(mapping["V4"]?.count, 1) XCTAssertEqual(Set(workers), Set(initialWorkers)) } func test___disjoint___with_only_one_version() { let initialWorkers = buildWorkers(count: 4) let initialMapping = buildMapping(versionsCount: 1, workers: initialWorkers) let mapping = calculator.disjointWorkers(mapping: initialMapping) let workers = mapping.values.flatMap { $0 } XCTAssertEqual(Set(workers), Set(initialWorkers)) } func test___disjoint___with_dedicated_deployments() { let initialWorkers = buildWorkers(count: 4) var initialWorkersForV1 = initialWorkers initialWorkersForV1.append("WorkerId5") let initialMapping: WorkersPerVersion = [ "V1": initialWorkersForV1, "V2": initialWorkers, "V3": initialWorkers, "V4": initialWorkers ] let mapping = calculator.disjointWorkers(mapping: initialMapping) let deployments = mapping["V2"]! + mapping["V3"]! + mapping["V4"]! XCTAssertEqual(mapping["V1"]?.count, 2) XCTAssertEqual(mapping["V2"]?.count, 1) XCTAssertEqual(mapping["V3"]?.count, 1) XCTAssertEqual(mapping["V4"]?.count, 1) XCTAssertEqual(Set(deployments).count, 3) } func test___disjoint___with_no_intersection() { let initialWorkers1: [WorkerId] = [ "WorkerId1", "WorkerId2" ] let initialWorkers2: [WorkerId] = [ "WorkerId3", "WorkerId4" ] let initialMapping: WorkersPerVersion = [ "V1": initialWorkers1, "V2": initialWorkers2, ] let mapping = calculator.disjointWorkers(mapping: initialMapping) XCTAssertEqual(Set(mapping["V1"]!), Set(initialWorkers1)) XCTAssertEqual(Set(mapping["V2"]!), Set(initialWorkers2)) } func test___disjoint___with_mixed_deployments() { let worker1: WorkerId = "workerId1" let worker2: WorkerId = "workerId2" let worker3: WorkerId = "workerId3" let worker4: WorkerId = "workerId4" let workersForV1 = [worker1, worker2] let workersForV2 = [worker2, worker3] let workersForV3 = [worker3, worker4] let workersForV4 = [worker4, worker1] let initialMapping: WorkersPerVersion = [ "V1": workersForV1, "V2": workersForV2, "V3": workersForV3, "V4": workersForV4 ] let mapping = calculator.disjointWorkers(mapping: initialMapping) XCTAssertEqual(Set(mapping["V1"]!), Set(workersForV1)) XCTAssertEqual(Set(mapping["V2"]!), Set(workersForV2)) XCTAssertEqual(Set(mapping["V3"]!), Set(workersForV3)) XCTAssertEqual(Set(mapping["V4"]!), Set(workersForV4)) } func test___disjoint___implementation_imprint() { let initialWorkers = buildWorkers(count: 70) let initialMapping = buildMapping(versionsCount: 3, workers: initialWorkers) let expectedMapping: WorkersPerVersion = [ "V1" : [ "WorkerId01", "WorkerId04", "WorkerId07", "WorkerId10", "WorkerId13", "WorkerId16", "WorkerId19", "WorkerId22", "WorkerId25", "WorkerId28", "WorkerId31", "WorkerId34", "WorkerId37", "WorkerId40", "WorkerId43", "WorkerId46", "WorkerId49", "WorkerId52", "WorkerId55", "WorkerId58", "WorkerId61", "WorkerId64", "WorkerId67", "WorkerId70" ], "V2" : [ "WorkerId02", "WorkerId05", "WorkerId08", "WorkerId11", "WorkerId14", "WorkerId17", "WorkerId20", "WorkerId23", "WorkerId26", "WorkerId29", "WorkerId32", "WorkerId35", "WorkerId38", "WorkerId41", "WorkerId44", "WorkerId47", "WorkerId50", "WorkerId53", "WorkerId56", "WorkerId59", "WorkerId62", "WorkerId65", "WorkerId68" ], "V3" : [ "WorkerId03", "WorkerId06", "WorkerId09", "WorkerId12", "WorkerId15", "WorkerId18", "WorkerId21", "WorkerId24", "WorkerId27", "WorkerId30", "WorkerId33", "WorkerId36", "WorkerId39", "WorkerId42", "WorkerId45", "WorkerId48", "WorkerId51", "WorkerId54", "WorkerId57", "WorkerId60", "WorkerId63", "WorkerId66", "WorkerId69" ] ] let mapping = calculator.disjointWorkers(mapping: initialMapping) XCTAssertEqual(mapping, expectedMapping) } func test___disjoint___returns_same_set_of_workers_on_same_data() { let initialMapping1: WorkersPerVersion = [ "V1": ["WorkerId1", "WorkerId2", "WorkerId3"], "V2": ["WorkerId1", "WorkerId2", "WorkerId3"], "V3": ["WorkerId1", "WorkerId2", "WorkerId3"], ] let initialMapping2: WorkersPerVersion = [ "V3": ["WorkerId3", "WorkerId2", "WorkerId1"], "V1": ["WorkerId1", "WorkerId2", "WorkerId3"], "V2": ["WorkerId2", "WorkerId3", "WorkerId1"], ] let mapping1 = calculator.disjointWorkers(mapping: initialMapping1) let mapping2 = calculator.disjointWorkers(mapping: initialMapping2) XCTAssertEqual(mapping1, mapping2) } private func buildWorkers(count: Int) -> [WorkerId] { var workers = [WorkerId]() for i in 1...count { let prependedZero = i < 10 ? "0" : "" workers.append(WorkerId(value: "WorkerId\(prependedZero)\(i)")) } return workers } private func buildMapping(versionsCount: Int, workers: [WorkerId]) -> WorkersPerVersion { var mapping = WorkersPerVersion() for i in 1...versionsCount { mapping[Version(value: "V\(i)")] = workers } return mapping } }
41.18617
155
0.612295
e83a4e9c4567b0e1ebdc53f7394e3c24f8b1cd93
406
// // CancelPasswordReset.swift // tl2swift // // Generated automatically. Any changes will be lost! // Based on TDLib 1.8.0-fa8feefe // https://github.com/tdlib/td/tree/fa8feefe // import Foundation /// Cancels reset of 2-step verification password. The method can be called if passwordState.pending_reset_date > 0 public struct CancelPasswordReset: Codable, Equatable { public init() {} }
20.3
115
0.729064
87d6c93148bdb693f1d57b633465780e9c360460
699
// // LeftPanGestureRecognizer.swift // ListableUI // // Created by Kyle Bashour on 4/21/20. // import UIKit.UIGestureRecognizerSubclass /// `LeftPanGestureRecognizer` tracks horizontal swipes which begin to the left. final class LeftPanGestureRecognizer: UIPanGestureRecognizer { override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesMoved(touches, with: event) if state == .began { let velocity = self.velocity(in: view) if abs(velocity.y) > abs(velocity.x) { state = .cancelled } if velocity.x > 0 { state = .cancelled } } } }
22.548387
80
0.60515
09d144a0f470bca14970bafdb94ac824428d9144
1,651
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "ApplozicSwift", defaultLocalization: "en", platforms: [.iOS(.v12)], products: [ .library( name: "ApplozicSwift", targets: ["ApplozicSwift"] ), .library( name: "RichMessageKit", targets: ["RichMessageKit"] ), ], dependencies: [ .package(name: "Applozic", url: "https://github.com/AppLozic/Applozic-Chat-iOS-Framework.git", .exact("8.3.0")), .package(name: "Kingfisher", url: "https://github.com/onevcat/Kingfisher.git", .exact("7.0.0")), .package(name: "SwipeCellKit", url: "https://github.com/SwipeCellKit/SwipeCellKit.git", from: "2.7.1"), ], targets: [ .target(name: "ApplozicSwift", dependencies: ["RichMessageKit", .product(name: "ApplozicCore", package: "Applozic"), "Kingfisher", "SwipeCellKit"], path: "Sources", exclude: ["Extras"], linkerSettings: [ .linkedFramework("Foundation"), .linkedFramework("SystemConfiguration"), .linkedFramework("UIKit", .when(platforms: [.iOS])), ]), .target(name: "RichMessageKit", dependencies: [], path: "RichMessageKit", linkerSettings: [ .linkedFramework("Foundation"), .linkedFramework("UIKit", .when(platforms: [.iOS])), ]), ] )
36.688889
120
0.496669
e8eda5bd470097ed313cd0b8a15feccaaae9f6d8
3,184
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019 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 NIO import NIOExtras import NIOHTTP1 class SendSimpleRequestHandler: ChannelInboundHandler { typealias InboundIn = HTTPClientResponsePart typealias OutboundOut = HTTPClientRequestPart private let allDonePromise: EventLoopPromise<ByteBuffer> init(allDonePromise: EventLoopPromise<ByteBuffer>) { self.allDonePromise = allDonePromise } func channelRead(context: ChannelHandlerContext, data: NIOAny) { if case .body(let body) = self.unwrapInboundIn(data) { self.allDonePromise.succeed(body) } } func errorCaught(context: ChannelHandlerContext, error: Error) { self.allDonePromise.fail(error) context.close(promise: nil) } func channelActive(context: ChannelHandlerContext) { let headers = HTTPHeaders([("host", "httpbin.org"), ("accept", "application/json")]) context.write(self.wrapOutboundOut(.head(.init(version: .init(major: 1, minor: 1), method: .GET, uri: "/delay/0.2", headers: headers))), promise: nil) context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) } } guard let outputFile = CommandLine.arguments.dropFirst().first else { print("Usage: \(CommandLine.arguments[0]) OUTPUT.pcap") exit(0) } let fileSink = try NIOWritePCAPHandler.SynchronizedFileSink.fileSinkWritingToFile(path: outputFile) { error in print("ERROR: \(error)") exit(1) } let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) defer { try! group.syncShutdownGracefully() } let allDonePromise = group.next().makePromise(of: ByteBuffer.self) let connection = try ClientBootstrap(group: group.next()) .channelInitializer { channel in return channel.pipeline.addHandler(NIOWritePCAPHandler(mode: .client, fileSink: fileSink.write)).flatMap { channel.pipeline.addHTTPClientHandlers() }.flatMap { channel.pipeline.addHandler(SendSimpleRequestHandler(allDonePromise: allDonePromise)) } } .connect(host: "httpbin.org", port: 80) .wait() let bytesReceived = try allDonePromise.futureResult.wait() print("# Success!", String(decoding: bytesReceived.readableBytesView, as: Unicode.UTF8.self), separator: "\n") try connection.close().wait() try fileSink.syncClose() print("# Your pcap file should have been written to '\(outputFile)'") print("#") print("# You can view \(outputFile) with") print("# - Wireshark") print("# - tcpdump -r '\(outputFile)'")
37.458824
114
0.628141
4858a8c09a88a33c36840a77d914371cfcd17baa
274
// RUN: not %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 deinit{class c<[{ {{{ {{ { {{{ { {{{ { < v= " { class case,
13.7
87
0.671533
ff855cb3f6c7d7476815920435822cf56223ff2a
5,679
// // YPPhotoCaptureDefaults.swift // YPImagePicker // // Created by Sacha DSO on 08/03/2018. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import AVFoundation extension YPPhotoCapture { // MARK: - Setup private func setupCaptureSession() { session.beginConfiguration() session.sessionPreset = .photo let cameraPosition: AVCaptureDevice.Position = YPConfig.usesFrontCamera ? .front : .back let aDevice = deviceForPosition(cameraPosition) if let d = aDevice { deviceInput = try? AVCaptureDeviceInput(device: d) } if let videoInput = deviceInput { if session.canAddInput(videoInput) { session.addInput(videoInput) } if session.canAddOutput(output) { session.addOutput(output) configure() } } session.commitConfiguration() isCaptureSessionSetup = true } // MARK: - Start/Stop Camera func start(with previewView: UIView, completion: @escaping () -> Void) { self.previewView = previewView sessionQueue.async { [weak self] in guard let strongSelf = self else { return } if !strongSelf.isCaptureSessionSetup { strongSelf.setupCaptureSession() } strongSelf.startCamera(completion: { completion() }) } } func startCamera(completion: @escaping (() -> Void)) { if !session.isRunning { sessionQueue.async { [weak self] in // Re-apply session preset self?.session.sessionPreset = .photo let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) switch status { case .notDetermined, .restricted, .denied: self?.session.stopRunning() case .authorized: self?.session.startRunning() completion() self?.tryToSetupPreview() @unknown default: fatalError() } } } } func stopCamera() { if session.isRunning { sessionQueue.async { [weak self] in self?.session.stopRunning() } } } // MARK: - Preview func tryToSetupPreview() { if !isPreviewSetup { setupPreview() isPreviewSetup = true } } func setupPreview() { videoLayer = AVCaptureVideoPreviewLayer(session: session) DispatchQueue.main.async { self.videoLayer.frame = self.previewView.bounds self.videoLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill self.previewView.layer.addSublayer(self.videoLayer) } } func hide(){ self.videoLayer?.isHidden = true } func show(){ self.videoLayer?.isHidden = false } // MARK: - Focus func focus(on point: CGPoint) { setFocusPointOnDevice(device: device!, point: point) } // MARK: - Zoom func zoom(began: Bool, scale: CGFloat) { guard let device = device else { return } if began { initVideoZoomFactor = device.videoZoomFactor return } do { try device.lockForConfiguration() defer { device.unlockForConfiguration() } var minAvailableVideoZoomFactor: CGFloat = 1.0 if #available(iOS 11.0, *) { minAvailableVideoZoomFactor = device.minAvailableVideoZoomFactor } var maxAvailableVideoZoomFactor: CGFloat = device.activeFormat.videoMaxZoomFactor if #available(iOS 11.0, *) { maxAvailableVideoZoomFactor = device.maxAvailableVideoZoomFactor } maxAvailableVideoZoomFactor = min(maxAvailableVideoZoomFactor, YPConfig.maxCameraZoomFactor) let desiredZoomFactor = initVideoZoomFactor * scale device.videoZoomFactor = max(minAvailableVideoZoomFactor, min(desiredZoomFactor, maxAvailableVideoZoomFactor)) } catch let error { print("💩 \(error)") } } // MARK: - Flip func flipCamera(completion: @escaping () -> Void) { sessionQueue.async { [weak self] in self?.flip() DispatchQueue.main.async { completion() } } } private func flip() { session.resetInputs() guard let di = deviceInput else { return } deviceInput = flippedDeviceInputForInput(di) guard let deviceInput = deviceInput else { return } if session.canAddInput(deviceInput) { session.addInput(deviceInput) } } // MARK: - Orientation func setCurrentOrienation() { let connection = output.connection(with: .video) let orientation = YPDeviceOrientationHelper.shared.currentDeviceOrientation switch orientation { case .portrait: connection?.videoOrientation = .portrait case .portraitUpsideDown: connection?.videoOrientation = .portraitUpsideDown case .landscapeRight: connection?.videoOrientation = .landscapeLeft case .landscapeLeft: connection?.videoOrientation = .landscapeRight default: connection?.videoOrientation = .portrait } } }
30.532258
122
0.562071
1e41df4f1c577dde5e22fef07a263ca8f5158b81
589
// // AppDelegateExtension.swift // MemoryChainKit // // Created by Marc Steven on 2020/3/17. // Copyright © 2020 Marc Steven All rights reserved. // import UIKit import AVFoundation public extension UIApplicationDelegate { /// support background mode func supportBackgroundMode() { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, options: .mixWithOthers) try AVAudioSession.sharedInstance().setActive(true) }catch { fatalError("\(error.localizedDescription)") } } }
24.541667
118
0.672326
f4417cdc1b8ef2abbb6f2e494513f3d7ca68716e
4,252
// // NetUDP.swift // PerfectNet // // Created by Kyle Jessup on 2017-01-23. // Copyright (C) 2016 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // // #if os(Linux) import SwiftGlibc #else import Darwin #endif public class NetUDP: Net { /// Creates an instance which will use the given file descriptor /// - parameter fd: The pre-existing file descriptor public convenience init(fd: Int32) { self.init() self.fd.fd = fd self.fd.family = AF_INET self.fd.switchToNonBlocking() } public override init() { super.init() self.initSocket(family: AF_INET) } public override func initSocket(family: Int32) { initSocket(family: family, type: SOCK_DGRAM) } /// Read up to the indicated number of bytes and deliver them and the sender's address on the provided callback. /// - parameter count: The number of bytes to read /// - parameter timeoutSeconds: The number of seconds to wait for the requested number of bytes. A timeout value of negative one indicates that the request should have no timeout. /// - parameter completion: The callback on which the results will be delivered. If the timeout occurs before the requested number of bytes have been read, a nil object will be delivered to the callback. public func readBytes(count: Int, timeoutSeconds: Double, completion: @escaping (() throws -> ([UInt8], NetAddress)?) -> ()) { var a = [UInt8](repeating: 0, count: count) let ptr = UnsafeMutableRawPointer(mutating: a) var addr = sockaddr_storage() let addrPtr = UnsafeMutableRawPointer(&addr) var addrSize = socklen_t(MemoryLayout<sockaddr_storage>.size) let size = recvfrom(fd.fd, ptr, count, 0, addrPtr.assumingMemoryBound(to: sockaddr.self), &addrSize) if size > 0, let addr = NetAddress(addr: addr) { completion({ return (Array(a[0..<size]), addr) }) } else if size == 0 { completion({ return nil }) } else if isEAgain(err: size) && timeoutSeconds > 0 { NetEvent.add(socket: fd.fd, what: .read, timeoutSeconds: timeoutSeconds) { [weak self] fd, w in if case .read = w { self?.readBytes(count: count, timeoutSeconds: 0.0, completion: completion) } else { completion({ return nil }) } } } else { let err = errno completion({ let msg = String(validatingUTF8: strerror(err))! throw PerfectNetError.networkError(err, msg + " \(#file) \(#function) \(#line)") }) } } /// Write the indicated bytes and call the callback with the number of bytes which were written. /// - parameter bytes: The array of UInt8 to write. /// - parameter completion: The callback which will be called once the write has completed. The callback will be passed the number of bytes which were successfuly written, which may be zero. public func write(bytes: [UInt8], to: NetAddress, timeoutSeconds: Double, completion: @escaping (() throws -> (Int, NetAddress)) -> ()) { var addr = to.addr let addrPtr = UnsafeMutableRawPointer(&addr) let addrSize = socklen_t(addr.ss_len) let sent = sendto(fd.fd, UnsafePointer(bytes), bytes.count, 0, addrPtr.assumingMemoryBound(to: sockaddr.self), addrSize) if sent == bytes.count { completion({ return (sent, to) }) } else if isEAgain(err: sent) && timeoutSeconds > 0 { NetEvent.add(socket: fd.fd, what: .write, timeoutSeconds: timeoutSeconds) { [weak self] fd, w in if case .write = w { self?.write(bytes: bytes, to: to, timeoutSeconds: 0.0, completion: completion) } else { completion({ let err = EAGAIN let msg = String(validatingUTF8: strerror(err))! throw PerfectNetError.networkError(err, msg + " \(#file) \(#function) \(#line)") }) } } } else { let err = errno completion({ let msg = String(validatingUTF8: strerror(err))! throw PerfectNetError.networkError(err, msg + " \(#file) \(#function) \(#line)") }) } } }
37.298246
204
0.65969
674989ffc6dd56fa195ad32633244e1c84e086c5
1,827
/* Copyright 2020 New Vector Ltd 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 @objcMembers final class EncryptionTrustLevelBadgeImageHelper: NSObject { static func roomBadgeImage(for trustLevel: RoomEncryptionTrustLevel) -> UIImage { let badgeImage: UIImage switch trustLevel { case .warning: badgeImage = Asset.Images.encryptionWarning.image case .normal: badgeImage = Asset.Images.encryptionNormal.image case .trusted: badgeImage = Asset.Images.encryptionTrusted.image case .unknown: badgeImage = Asset.Images.encryptionNormal.image @unknown default: badgeImage = Asset.Images.encryptionNormal.image } return badgeImage } static func userBadgeImage(for trustLevel: UserEncryptionTrustLevel) -> UIImage? { let badgeImage: UIImage? switch trustLevel { case .warning: badgeImage = Asset.Images.encryptionWarning.image case .normal: badgeImage = Asset.Images.encryptionNormal.image case .trusted: badgeImage = Asset.Images.encryptionTrusted.image default: badgeImage = nil } return badgeImage } }
30.45
86
0.660099
dd4213ce6010aa92dd8deca174495119c156f81a
669
// // GameThumbImageCell.swift // PandaTV // // Created by 钟斌 on 2017/3/31. // Copyright © 2017年 xiaobin. All rights reserved. // import UIKit import Kingfisher class GameThumbImageCell: UICollectionViewCell { @IBOutlet weak var gameImage: UIImageView! @IBOutlet weak var gameName: UILabel! var item : ThundImageItem? { didSet { guard let item = item else {return} guard let img = item.img else {return} let url = URL(string: img) gameImage.kf.setImage(with: ImageResource(downloadURL: url!)) gameName.text = item.title ?? item.cname } } }
23.892857
73
0.600897
20c354d3ed668fea990fc85389597edd1de1d1a7
208
import UIKit import ReactiveCocoa extension UITextField { func returnKeySignal () -> RACSignal { return rac_signalForControlEvents(.EditingDidEndOnExit).takeUntil(rac_willDeallocSignal()) } }
26
98
0.764423
d963be2615f45a9f9e625eee0638c2001bc450ab
755
import XCTest class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } 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() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
24.354839
111
0.57351
ab62087f4a454e2a362feedceefa7eaf5ba44a21
312
// // GetCountryCode.swift // tl2swift // // Created by Code Generator // import Foundation /// Uses the current IP address to find the current country. Returns two-letter ISO 3166-1 alpha-2 country code. Can be called before authorization public struct GetCountryCode: Codable { public init() {} }
17.333333
147
0.721154
d7bbe3c076f7b54857c783a7e709bdfcb1ff0f60
432
// // Account.swift // MovieLister // // Created by Ben Scheirman on 11/10/19. // Copyright © 2019 Fickle Bits. All rights reserved. // import Foundation import SimpleNetworking struct Account : Model { let id: Int let name: String? let username: String? var displayName: String { if let name = name, !name.isEmpty { return name } return username ?? "(uknown)" } }
18
54
0.601852
e0c45af7c57b706a5287de2f1a09318c488e2596
874
// // OrganizeViewController.swift // NotesApp // // Created by Ethan Neff on 4/7/16. // Copyright © 2016 Ethan Neff. All rights reserved. // import UIKit class OrganizeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ }
24.277778
106
0.679634
22f3c5eb0aadbc2aa2009df023c7b59903e28089
551
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -verify %s // REQUIRES: objc_interop import Foundation var x = 1 _ = [x] as [NSNumber] _ = ["x":["y":"z","a":1]] as [String : [String : AnyObject]] _ = ["x":["z",1]] as [String : [AnyObject]] _ = [["y":"z","a":1]] as [[String : AnyObject]] _ = [["z",1]] as [[AnyObject]] var y: Any = 1 _ = ["x":["y":"z","a":y]] as [String : [String : AnyObject]] _ = ["x":["z",y]] as [String : [AnyObject]] _ = [["y":"z","a":y]] as [[String : AnyObject]] _ = [["z",y]] as [[AnyObject]]
26.238095
85
0.53539
ccddeb15185a434e671cad368b99d75fd495a48e
3,331
// // AppDelegate.swift // SKTiled Demo - iOS // // Created by Michael Fessenden. // // Web: https://github.com/mfessenden // Email: [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Thread.sleep(forTimeInterval: 3.0) // 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) { // 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:. } }
49.716418
285
0.753527
9cfe2e5520a8be06272f17ec2aa5e0e4f6abaafe
705
// // VerificationSourceType.swift // Verification // // Created by Aleksander Wojcik on 14/07/2020. // Copyright © 2020 Aleksander Wojcik. All rights reserved. // /// Enum representing different possible ways the verification code might be collected. public enum VerificationSourceType: String, Codable { /// Code was automatically intercepted by the interceptor. case interception = "INTERCEPTION" /// Code was manually typed by the user. case manual = "MANUAL" /// Code was grabbed from the log. For example from the call history for flashcall verification method. case log = "LOG" /// Code was verified seamlessly. case seamless = "SEAMLESS" }
29.375
107
0.700709
3845a8629515f12c3e425813438fd1cfd8287c66
522
// // Observable.swift // PatKit // // Created by Patrick O'Leary on 9/20/17. // Copyright © 2017 Patrick O'Leary. All rights reserved. // import Foundation class Observable<T> { let didChange = Event<(T, T)>() private var value: T init(_ initialValue: T) { value = initialValue } func set(newValue: T) { let oldValue = value value = newValue didChange.raise(data: (oldValue, newValue)) } func get() -> T { return value } }
17.4
58
0.561303
e2ada7b6650d259f4a2d3366cb703325b2705df9
1,842
@testable import App import XCTVapor class ProductTests: AppTestCase { func test_Product_save() throws { let pkg = Package(id: UUID(), url: "1") let ver = try Version(id: UUID(), package: pkg) let prod = try Product(id: UUID(), version: ver, type: .library, name: "p1", targets: ["t1", "t2"]) try pkg.save(on: app.db).wait() try ver.save(on: app.db).wait() try prod.save(on: app.db).wait() do { let p = try XCTUnwrap(Product.find(prod.id, on: app.db).wait()) XCTAssertEqual(p.$version.id, ver.id) XCTAssertEqual(p.type, .library) XCTAssertEqual(p.name, "p1") XCTAssertEqual(p.targets, ["t1", "t2"]) } } func test_delete_cascade() throws { // delete version must delete products let pkg = Package(id: UUID(), url: "1") let ver = try Version(id: UUID(), package: pkg) let prod = try Product(id: UUID(), version: ver, type: .library, name: "p1") try pkg.save(on: app.db).wait() try ver.save(on: app.db).wait() try prod.save(on: app.db).wait() XCTAssertEqual(try Package.query(on: app.db).count().wait(), 1) XCTAssertEqual(try Version.query(on: app.db).count().wait(), 1) XCTAssertEqual(try Product.query(on: app.db).count().wait(), 1) // MUT try ver.delete(on: app.db).wait() // version and product should be deleted XCTAssertEqual(try Package.query(on: app.db).count().wait(), 1) XCTAssertEqual(try Version.query(on: app.db).count().wait(), 0) XCTAssertEqual(try Product.query(on: app.db).count().wait(), 0) } }
36.84
84
0.530402
2167e859ebd909b9c1543945af0f28e6b4288217
510
// // ViewController.swift // VehicleCheckPrototype // // Created by Leon Yuu on 5/2/18. // Copyright © 2018 Leon Yuu. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.615385
80
0.670588
ed26b5a801feef5b65411ea933484de959009a65
8,151
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/main/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore // MARK: Paginators extension WorkMail { /// Creates a paginated call to list the aliases associated with a given entity. public func listAliasesPaginator( _ input: ListAliasesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListAliasesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAliases, tokenKey: \ListAliasesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns an overview of the members of a group. Users and groups can be members of a group. public func listGroupMembersPaginator( _ input: ListGroupMembersRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListGroupMembersResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listGroupMembers, tokenKey: \ListGroupMembersResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns summaries of the organization's groups. public func listGroupsPaginator( _ input: ListGroupsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListGroupsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listGroups, tokenKey: \ListGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the mailbox permissions associated with a user, group, or resource mailbox. public func listMailboxPermissionsPaginator( _ input: ListMailboxPermissionsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListMailboxPermissionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listMailboxPermissions, tokenKey: \ListMailboxPermissionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns summaries of the customer's organizations. public func listOrganizationsPaginator( _ input: ListOrganizationsRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListOrganizationsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listOrganizations, tokenKey: \ListOrganizationsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the delegates associated with a resource. Users and groups can be resource delegates and answer requests on behalf of the resource. public func listResourceDelegatesPaginator( _ input: ListResourceDelegatesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListResourceDelegatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listResourceDelegates, tokenKey: \ListResourceDelegatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns summaries of the organization's resources. public func listResourcesPaginator( _ input: ListResourcesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListResourcesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listResources, tokenKey: \ListResourcesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns summaries of the organization's users. public func listUsersPaginator( _ input: ListUsersRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled, onPage: @escaping (ListUsersResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listUsers, tokenKey: \ListUsersResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension WorkMail.ListAliasesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> WorkMail.ListAliasesRequest { return .init( entityId: self.entityId, maxResults: self.maxResults, nextToken: token, organizationId: self.organizationId ) } } extension WorkMail.ListGroupMembersRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> WorkMail.ListGroupMembersRequest { return .init( groupId: self.groupId, maxResults: self.maxResults, nextToken: token, organizationId: self.organizationId ) } } extension WorkMail.ListGroupsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> WorkMail.ListGroupsRequest { return .init( maxResults: self.maxResults, nextToken: token, organizationId: self.organizationId ) } } extension WorkMail.ListMailboxPermissionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> WorkMail.ListMailboxPermissionsRequest { return .init( entityId: self.entityId, maxResults: self.maxResults, nextToken: token, organizationId: self.organizationId ) } } extension WorkMail.ListOrganizationsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> WorkMail.ListOrganizationsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension WorkMail.ListResourceDelegatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> WorkMail.ListResourceDelegatesRequest { return .init( maxResults: self.maxResults, nextToken: token, organizationId: self.organizationId, resourceId: self.resourceId ) } } extension WorkMail.ListResourcesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> WorkMail.ListResourcesRequest { return .init( maxResults: self.maxResults, nextToken: token, organizationId: self.organizationId ) } } extension WorkMail.ListUsersRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> WorkMail.ListUsersRequest { return .init( maxResults: self.maxResults, nextToken: token, organizationId: self.organizationId ) } }
33.405738
156
0.633419
909fad129d1168ea0aa61f8aa9769b5c788f0354
207
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "MapVsForInVsForEachChallenge", targets: [ .testTarget(name: "MapVsForInVsForEachChallengeTests") ] )
17.25
62
0.705314
e4a437ce87244aaf75f6870f2f1f55fa4848ee53
823
// // HTTPRequest.swift // NobodyHackathons // // Created by Charly Maxter on 19/10/2018. // Copyright © 2018 Charly Maxter. All rights reserved. // import Foundation public typealias ServiceResponse = (Data, NSError?) -> Void public func makeHTTPGetRequestAuth(_ path: String, auth: String, onCompletion: @escaping ServiceResponse) { let request = NSMutableURLRequest(url: URL(string: path)!) if(auth != ""){ request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("jwt \(auth)", forHTTPHeaderField: "Authorization") } let session = URLSession.shared let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in onCompletion(data!, error as NSError?) }) task.resume() }
30.481481
113
0.690158
eb02cd2cbaa414d9c0df8a063e46d8a5a7e6fcc6
2,318
// // SceneDelegate.swift // Fabric versions // // Copyright © 2020 BoogieMonster1O1. All rights reserved. // 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. } }
43.735849
147
0.715272
6460a3dd3fe4b2c5f7de4921ffdc338f0c298363
1,125
// // AccountTests.swift // SwiftFHIR // // Generated from FHIR 1.4.0.8139 on 2016-08-17. // 2016, SMART Health IT. // import XCTest import SwiftFHIR class AccountTests: XCTestCase { func instantiateFrom(filename: String) throws -> SwiftFHIR.Account { return instantiateFrom(json: try readJSONFile(filename)) } func instantiateFrom(json: FHIRJSON) -> SwiftFHIR.Account { let instance = SwiftFHIR.Account(json: json) XCTAssertNotNil(instance, "Must have instantiated a test instance") return instance } func testAccount1() { do { let instance = try runAccount1() try runAccount1(instance.asJSON()) } catch { XCTAssertTrue(false, "Must instantiate and test Account successfully, but threw") } } @discardableResult func runAccount1(_ json: FHIRJSON? = nil) throws -> SwiftFHIR.Account { let inst = (nil != json) ? instantiateFrom(json: json!) : try instantiateFrom(filename: "account-example.json") XCTAssertEqual(inst.id, "example") XCTAssertEqual(inst.text?.div, "<div>[Put rendering here]</div>") XCTAssertEqual(inst.text?.status, "generated") return inst } }
24.456522
113
0.712
e9b0fbc8a1ddbf2217ca0ebd56697247fc0b1a95
950
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -module-name ConstraintsOnOuterContext -emit-module-path %t/ConstraintsOnOuterContext.swiftmodule // RUN: %target-swift-symbolgraph-extract -module-name ConstraintsOnOuterContext -I %t -pretty-print -output-dir %t // RUN: %FileCheck %s --input-file %t/ConstraintsOnOuterContext.symbols.json public struct MyStruct<S: Sequence> { public var x: S public init(x: S) { self.x = x } public func foo() where S.Element == Int {} } // CHECK-LABEL: "precise": "s:25ConstraintsOnOuterContext8MyStructV3fooyySi7ElementRtzrlF" // CHECK: swiftGenerics // CHECK: "constraints": [ // { // CHECK: "kind": "conformance" // CHECK-NEXT: "lhs": "S" // CHECK-NEXT: "rhs": "Sequence" // }, // { // CHECK: "kind": "sameType" // CHECK-NEXT: "lhs": "S.Element" // CHECK-NEXT: "rhs": "Int" // CHECK-NEXT: } // CHECK-NEXT: ]
33.928571
128
0.625263
d5f9c70f983cb326e43d547e27d86a6368133a96
976
// // Contest.swift // JumuNordost // // Created by Martin Richter on 13/02/16. // Copyright © 2016 Martin Richter. All rights reserved. // import Argo import Curry struct Contest { let id: String let name: String let hostCountry: String let timeZone: NSTimeZone let startDate: NSDate let endDate: NSDate let contestCategories: [ContestCategory] let venues: [Venue] } // MARK: - Equatable extension Contest: Equatable {} func ==(lhs: Contest, rhs: Contest) -> Bool { return lhs.id == rhs.id } // MARK: - Decodable extension Contest: Decodable { static func decode(json: JSON) -> Decoded<Contest> { return curry(self.init) <^> json <| "id" <*> json <| "name" <*> json <| "host_country" <*> json <| "time_zone" <*> json <| "start_date" <*> json <| "end_date" <*> json <|| "contest_categories" <*> json <|| "venues" } }
21.217391
57
0.569672
abaf382f7da0e42c72745be395928905843bd4ce
1,126
//===--- UIBezierPath+KeyedArchiveOpaqueRepresentation.swift --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2017-2018 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 // //===----------------------------------------------------------------------===// #if os(iOS) || os(tvOS) import Foundation import UIKit fileprivate let bezierPathTag = "BEZP" extension UIBezierPath: KeyedArchiveOpaqueRepresentation { var tag: String { return bezierPathTag } func encodeOpaqueRepresentation(with encoder: NSCoder, usingFormat format: LogEncoder.Format) throws { do { try self.encodeForLogEntry(using: encoder) } catch { throw LoggingError.encodingFailure(reason: "Failed to encode UIBezierPath using NSKeyedArchiver") } } } #endif
34.121212
113
0.610124
2f8e50166615c06cbd186799e35eea35b7c0755b
1,822
// // BarcodeGenerateViewController.swift // CodeScanner // // Created by 須藤 将史 on 2017/02/15. // Copyright © 2017年 masashi_sutou. All rights reserved. // import UIKit import CodeScanner final class BarcodeGenerateViewController: UIViewController { private var imageView: UIImageView = UIImageView() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Generate a barcode" self.view.backgroundColor = .groupTableViewBackground self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "generate", style: .done, target: self, action: #selector(BarcodeGenerateViewController.generateButtonTapped(_:))) self.imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.width)) self.imageView.center = self.view.center self.imageView.image = UIImage(named: "no_image") self.imageView.contentMode = .scaleAspectFit self.view.addSubview(imageView) } @objc func generateButtonTapped(_ sender: UIBarButtonItem) { let alert = UIAlertController(title: "Generate a Barcode", message: "Enter the text you want to make into the Barcode", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {(_) -> Void in })) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: {(_) -> Void in if let textFields: [UITextField] = alert.textFields as [UITextField]? { self.imageView.image = Code.generate128Barcode(text: (textFields.first?.text)!) } })) alert.addTextField(configurationHandler: {(_) -> Void in }) present(alert, animated: true, completion: nil) } }
40.488889
191
0.667398
08496545eb713dcdca5c0cb3d8a3adb9ffe7d44b
6,597
import FluentKit import NIO /// Lets you mock the row results for each query. /// /// Make sure you `append` a result for each query you will /// make to the database. Running out of results will result /// in a failed `EventLoopFuture` with the /// `TestDatabaseError.ranOutOfResults` error. /// /// **Examples:** /// /// Return an empty result for the next query: /// /// let db = ArrayTestDatabase() /// db.append([]) /// /// Return an empty result for first query, and a single result /// for the second query (perhaps a query to find a record with /// no results followed by a successful query to create the record): /// /// let db = ArrayTestDatabase() /// db.append([]) /// db.append([ /// TestOutput(["id": 1, "name": "Boise"]) /// ]) /// /// Return multiple rows for one query: /// /// let db = ArrayTestDatabase() /// db.append([ /// TestOutput(["id": 1, ...]), /// TestOutput(["id": 2, ...]) /// ]) /// /// Append a `Model`: /// /// let db = ArrayTestDatabase() /// db.append([ /// TestOutput(Planet(name: "Pluto")) /// ]) /// public final class ArrayTestDatabase: TestDatabase { var results: [[DatabaseOutput]] public init() { self.results = [] } public func append(_ result: [DatabaseOutput]) { self.results.append(result) } public func execute(query: DatabaseQuery, onOutput: (DatabaseOutput) -> ()) throws { guard !self.results.isEmpty else { throw TestDatabaseError.ranOutOfResults } for output in self.results.removeFirst() { onOutput(output) } } } public final class CallbackTestDatabase: TestDatabase { var callback: (DatabaseQuery) -> [DatabaseOutput] public init(callback: @escaping (DatabaseQuery) -> [DatabaseOutput]) { self.callback = callback } public func execute(query: DatabaseQuery, onOutput: (DatabaseOutput) -> ()) throws { for output in self.callback(query) { onOutput(output) } } } public protocol TestDatabase { func execute( query: DatabaseQuery, onOutput: (DatabaseOutput) -> () ) throws } extension TestDatabase { public var db: Database { self.database(context: .init( configuration: self.configuration, logger: Logger(label: "codes.vapor.fluent.test"), eventLoop: EmbeddedEventLoop() )) } func database(context: DatabaseContext) -> Database { _TestDatabase(test: self, context: context) } } private struct _TestDatabase: Database { var inTransaction: Bool { false } let test: TestDatabase var context: DatabaseContext func execute( query: DatabaseQuery, onOutput: @escaping (DatabaseOutput) -> () ) -> EventLoopFuture<Void> { guard context.eventLoop.inEventLoop else { return self.eventLoop.flatSubmit { self.execute(query: query, onOutput: onOutput) } } do { try self.test.execute(query: query, onOutput: onOutput) } catch { return self.eventLoop.makeFailedFuture(error) } return self.eventLoop.makeSucceededFuture(()) } func transaction<T>(_ closure: @escaping (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> { closure(self) } func withConnection<T>(_ closure: (Database) -> EventLoopFuture<T>) -> EventLoopFuture<T> { closure(self) } func execute(enum: DatabaseEnum) -> EventLoopFuture<Void> { self.eventLoop.makeSucceededFuture(()) } func execute(schema: DatabaseSchema) -> EventLoopFuture<Void> { self.eventLoop.makeSucceededFuture(()) } } extension TestDatabase { public var configuration: DatabaseConfiguration { _TestConfiguration(test: self) } } private struct _TestConfiguration: DatabaseConfiguration { let test: TestDatabase var middleware: [AnyModelMiddleware] = [] func makeDriver(for databases: Databases) -> DatabaseDriver { _TestDriver(test: self.test) } } private struct _TestDriver: DatabaseDriver { let test: TestDatabase func makeDatabase(with context: DatabaseContext) -> Database { self.test.database(context: context) } func shutdown() { // Do nothing } } public enum TestDatabaseError: Error { case ranOutOfResults } public struct TestOutput: DatabaseOutput { public func schema(_ schema: String) -> DatabaseOutput { self } public func decode<T>(_ key: FieldKey, as type: T.Type) throws -> T where T: Decodable { if let res = dummyDecodedFields[key] as? T { return res } throw TestRowDecodeError.wrongType } public func contains(_ path: FieldKey) -> Bool { true } public func nested(_ key: FieldKey) throws -> DatabaseOutput { self } public func decodeNil(_ key: FieldKey) throws -> Bool { false } public var description: String { return "<dummy>" } var dummyDecodedFields: [FieldKey: Any] public init() { self.dummyDecodedFields = [:] } public init(_ mockFields: [FieldKey: Any]) { self.dummyDecodedFields = mockFields } public init<TestModel>(_ model: TestModel) where TestModel: Model { func unpack(_ dbValue: DatabaseQuery.Value) -> Any? { switch dbValue { case .null: return nil case .enumCase(let value): return value case .custom(let value): return value case .bind(let value): return value case .array(let array): return array.map(unpack) case .dictionary(let dictionary): return dictionary.mapValues(unpack) case .default: return "" } } let collect = CollectInput() model.input(to: collect) self.init( collect.storage.mapValues(unpack) ) } public mutating func append(key: FieldKey, value: Any) { dummyDecodedFields[key] = value } } private final class CollectInput: DatabaseInput { var storage: [FieldKey: DatabaseQuery.Value] init() { self.storage = [:] } func set(_ value: DatabaseQuery.Value, at key: FieldKey) { self.storage[key] = value } } public enum TestRowDecodeError: Error { case wrongType }
25.275862
102
0.598454
03b7b13ddf2188ccd062be638236475ca3f19ea7
1,251
// // InstagramUITests.swift // InstagramUITests // // Created by Sumit Dhungel on 3/10/17. // Copyright © 2017 Sumit Dhungel. All rights reserved. // import XCTest class InstagramUITests: 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.810811
182
0.664269
38dba1472c9451492d4bbfed877a124ad212afc7
18,527
// Copyright 2019 Google LLC // // 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 // // https://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. /// Lifts a FuzzIL program to JavaScript. public class JavaScriptLifter: ComponentBase, Lifter { /// Prefix and suffix to surround the emitted code in private let prefix: String private let suffix: String /// The inlining policy to follow. This influences to look of the emitted code. let policy: InliningPolicy /// The identifier to refer to the global object. /// /// For node.js this is "global", otherwise probably just "this". let globalObjectIdentifier: String /// Supported versions of the ECMA standard. enum ECMAScriptVersion { case es5 case es6 } /// The version of the ECMAScript standard that this lifter generates code for. let version: ECMAScriptVersion public init(prefix: String = "", suffix: String = "", inliningPolicy: InliningPolicy, globalObjectIdentifier: String = "this") { self.prefix = prefix self.suffix = suffix self.policy = inliningPolicy self.globalObjectIdentifier = globalObjectIdentifier self.version = .es6 super.init(name: "JavaScriptLifter") } public func lift(_ program: Program) -> String { var w = ScriptWriter() // Analyze the program to determine the uses of a variable var analyzer = DefUseAnalyzer(for: program) // Associates variables with the expressions that produce them // TODO use VariableMap here? var expressions = [Variable: Expression]() func expr(for v: Variable) -> Expression { return expressions[v] ?? Identifier.new(v.identifier) } w.emitBlock(prefix) let varDecl = version == .es6 ? "let" : "var" let constDecl = version == .es6 ? "const" : "var" for instr in program { // Conveniece access to inputs func input(_ idx: Int) -> Expression { return expr(for: instr.input(idx)) } func value(_ idx: Int) -> Any? { switch analyzer.definition(of: instr.input(idx)).operation { case let op as LoadInteger: return op.value case let op as LoadFloat: return op.value case let op as LoadString: return op.value default: return nil } } var output: Expression? = nil switch instr.operation { case is Nop: break case let op as LoadInteger: output = NumberLiteral.new(String(op.value)) case let op as LoadFloat: if op.value.isNaN { output = Identifier.new("NaN") } else if op.value.isEqual(to: -Double.infinity) { output = UnaryExpression.new("-Infinity") } else if op.value.isEqual(to: Double.infinity) { output = Identifier.new("Infinity") } else { output = NumberLiteral.new(String(op.value)) } case let op as LoadString: output = Literal.new() <> "\"" <> op.value <> "\"" case let op as LoadBoolean: output = Literal.new(op.value ? "true" : "false") case is LoadUndefined: output = Identifier.new("undefined") case is LoadNull: output = Literal.new("null") case let op as CreateObject: var properties = [String]() for (index, propertyName) in op.propertyNames.enumerated() { properties.append(propertyName + ":" + input(index)) } output = ObjectLiteral.new("{" + properties.joined(separator: ",") + "}") case is CreateArray: let elems = instr.inputs.map({ expr(for: $0).text }).joined(separator: ",") output = ArrayLiteral.new("[" + elems + "]") case let op as CreateObjectWithSpread: var properties = [String]() for (index, propertyName) in op.propertyNames.enumerated() { properties.append(propertyName + ":" + input(index)) } // Remaining ones are spread. for v in instr.inputs.dropFirst(properties.count) { properties.append("..." + expr(for: v).text) } output = ObjectLiteral.new("{" + properties.joined(separator: ",") + "}") case let op as CreateArrayWithSpread: var elems = [String]() for (i, v) in instr.inputs.enumerated() { if op.spreads[i] { elems.append("..." + expr(for: v).text) } else { elems.append(expr(for: v).text) } } output = ArrayLiteral.new("[" + elems.joined(separator: ",") + "]") case let op as LoadBuiltin: output = Identifier.new(op.builtinName) case let op as LoadProperty: output = MemberExpression.new() <> input(0) <> "." <> op.propertyName case let op as StoreProperty: let dest = MemberExpression.new() <> input(0) <> "." <> op.propertyName let expr = AssignmentExpression.new() <> dest <> " = " <> input(1) w.emit(expr) case let op as DeleteProperty: let target = MemberExpression.new() <> input(0) <> "." <> op.propertyName let expr = UnaryExpression.new() <> "delete " <> target w.emit(expr) case let op as LoadElement: output = MemberExpression.new() <> input(0) <> "[" <> op.index <> "]" case let op as StoreElement: let dest = MemberExpression.new() <> input(0) <> "[" <> op.index <> "]" let expr = AssignmentExpression.new() <> dest <> " = " <> input(1) w.emit(expr) case let op as DeleteElement: let target = MemberExpression.new() <> input(0) <> "[" <> op.index <> "]" let expr = UnaryExpression.new() <> "delete " <> target w.emit(expr) case is LoadComputedProperty: output = MemberExpression.new() <> input(0) <> "[" <> input(1).text <> "]" case is StoreComputedProperty: let dest = MemberExpression.new() <> input(0) <> "[" <> input(1).text <> "]" let expr = AssignmentExpression.new() <> dest <> " = " <> input(2) w.emit(expr) case is DeleteComputedProperty: let target = MemberExpression.new() <> input(0) <> "[" <> input(1).text <> "]" let expr = UnaryExpression.new() <> "delete " <> target w.emit(expr) case is TypeOf: output = UnaryExpression.new() <> "typeof " <> input(0) case is InstanceOf: output = BinaryExpression.new() <> input(0) <> " instanceof " <> input(1) case is In: output = BinaryExpression.new() <> input(0) <> " in " <> input(1) case let op as BeginFunctionDefinition: var identifiers = instr.innerOutputs.map({ $0.identifier }) if op.hasRestParam, let last = instr.innerOutputs.last { identifiers[identifiers.endIndex - 1] = "..." + last.identifier } let params = identifiers.joined(separator: ",") w.emit("function \(instr.output)(\(params)) {") w.increaseIndentionLevel() if (op.isJSStrictMode) { w.emit("'use strict'") } case is Return: w.emit("return \(input(0));") case is EndFunctionDefinition: w.decreaseIndentionLevel() w.emit("}") case is CallFunction: let arguments = instr.inputs.dropFirst().map({ expr(for: $0).text }) output = CallExpression.new() <> input(0) <> "(" <> arguments.joined(separator: ",") <> ")" case let op as CallMethod: let arguments = instr.inputs.dropFirst().map({ expr(for: $0).text }) let method = MemberExpression.new() <> input(0) <> "." <> op.methodName output = CallExpression.new() <> method <> "(" <> arguments.joined(separator: ",") <> ")" case is Construct: let arguments = instr.inputs.dropFirst().map({ expr(for: $0).text }) output = NewExpression.new() <> "new " <> input(0) <> "(" <> arguments.joined(separator: ",") <> ")" case let op as CallFunctionWithSpread: var arguments = [String]() for (i, v) in instr.inputs.dropFirst().enumerated() { if op.spreads[i] { arguments.append("..." + expr(for: v).text) } else { arguments.append(expr(for: v).text) } } output = CallExpression.new() <> input(0) <> "(" <> arguments.joined(separator: ",") <> ")" case let op as UnaryOperation: if op.op == .Inc { output = BinaryExpression.new() <> input(0) <> " + 1" } else if op.op == .Dec { output = BinaryExpression.new() <> input(0) <> " - 1" } else { output = UnaryExpression.new() <> op.op.token <> input(0) } case let op as BinaryOperation: output = BinaryExpression.new() <> input(0) <> " " <> op.op.token <> " " <> input(1) case is Phi: w.emit("\(varDecl) \(instr.output) = \(input(0));") case is Copy: w.emit("\(instr.input(0)) = \(input(1));") case let op as Compare: output = BinaryExpression.new() <> input(0) <> " " <> op.comparator.token <> " " <> input(1) case let op as Eval: // Woraround until Strings implement the CVarArg protocol in the linux Foundation library... // TODO can make this permanent, but then use different placeholder pattern var string = op.string for v in instr.inputs { let range = string.range(of: "%@")! string.replaceSubrange(range, with: expr(for: v).text) } w.emit(string) case is BeginWith: w.emit("with (\(input(0))) {") w.increaseIndentionLevel() case is EndWith: w.decreaseIndentionLevel() w.emit("}") case let op as LoadFromScope: output = Identifier.new(op.id) case let op as StoreToScope: w.emit("\(op.id) = \(input(0));") case is BeginIf: w.emit("if (\(input(0))) {") w.increaseIndentionLevel() case is BeginElse: w.decreaseIndentionLevel() w.emit("} else {") w.increaseIndentionLevel() case is EndIf: w.decreaseIndentionLevel() w.emit("}") case let op as BeginWhile: let cond = BinaryExpression.new() <> input(0) <> " " <> op.comparator.token <> " " <> input(1) w.emit("while (\(cond)) {") w.increaseIndentionLevel() case is EndWhile: w.decreaseIndentionLevel() w.emit("}") case is BeginDoWhile: w.emit("do {") w.increaseIndentionLevel() case let op as EndDoWhile: w.decreaseIndentionLevel() let cond = BinaryExpression.new() <> input(0) <> " " <> op.comparator.token <> " " <> input(1) w.emit("} while (\(cond));") case let op as BeginFor: let loopVar = Identifier.new(instr.innerOutput.identifier) let cond = BinaryExpression.new() <> loopVar <> " " <> op.comparator.token <> " " <> input(1) var expr: Expression if let i = value(2) as? Int, i == 1 && op.op == .Add { expr = PostfixExpression.new() <> loopVar <> "++" } else if let i = value(2) as? Int, i == 1 && op.op == .Sub { expr = PostfixExpression.new() <> loopVar <> "--" } else { let newValue = BinaryExpression.new() <> loopVar <> " " <> op.op.token <> " " <> input(2) expr = AssignmentExpression.new() <> loopVar <> " = " <> newValue } w.emit("for (\(varDecl) \(loopVar) = \(input(0)); \(cond); \(expr)) {") w.increaseIndentionLevel() case is EndFor: w.decreaseIndentionLevel() w.emit("}") case is BeginForIn: w.emit("for (\(constDecl) \(instr.innerOutput) in \(input(0))) {") w.increaseIndentionLevel() case is EndForIn: w.decreaseIndentionLevel() w.emit("}") case is BeginForOf: w.emit("for (\(constDecl) \(instr.innerOutput) of \(input(0))) {") w.increaseIndentionLevel() case is EndForOf: w.decreaseIndentionLevel() w.emit("}") case is Break: w.emit("break;") case is Continue: w.emit("continue;") case is BeginTry: w.emit("try {") w.increaseIndentionLevel() case is BeginCatch: w.decreaseIndentionLevel() w.emit("} catch(\(instr.innerOutput)) {") w.increaseIndentionLevel() case is EndTryCatch: w.decreaseIndentionLevel() w.emit("}") case is ThrowException: w.emit("throw \(input(0));") case is Print: w.emit("\(fuzzilOutputFuncName)(\(input(0)));") case is InspectType: w.emitBlock( """ { try { var proto = (\(input(0))).__proto__; var typename = proto == null ? "Object" : proto.constructor.name; \(fuzzilOutputFuncName)(typename); } catch (e) { \(fuzzilOutputFuncName)(""); } } """) case is InspectValue: w.emitBlock( """ { var properties = []; var methods = []; var obj = \(input(0)); while (obj != null) { for (p of Object.getOwnPropertyNames(obj)) { var prop; try { prop = obj[p]; } catch (e) { continue; } if (typeof(prop) === 'function') { methods.push(p); } // Every method is also a property! properties.push(p); } obj = obj.__proto__; } \(fuzzilOutputFuncName)(JSON.stringify({properties: properties, methods: methods})); } """) case is EnumerateBuiltins: w.emitBlock(""" { var globals = Object.getOwnPropertyNames(\(globalObjectIdentifier)); \(fuzzilOutputFuncName)(JSON.stringify({globals: globals})); } """) default: logger.fatal("Unhandled Operation: \(type(of: instr.operation))") } if let expression = output { let v = instr.output if policy.shouldInline(expression) && expression.canInline(instr, analyzer.usesIndices(of: v)) { expressions[v] = expression } else { w.emit("\(constDecl) \(v) = \(expression);") } } } w.emitBlock(suffix) return w.code } }
41.727477
132
0.447941
893c647c0f62c168c5a6f5bbde83be1f26d04040
5,143
import UIKit import Kingfisher import WoWonderTimelineSDK class InviteFriendsController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var inviteLabel: UILabel! @IBOutlet var navView: UIView! var usersArray = [[String:Any]]() var pageId = "" var groupId = "" override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.hexStringToUIColor(hex: ControlSettings.appMainColor) self.navView.backgroundColor = UIColor.hexStringToUIColor(hex: ControlSettings.appMainColor) self.tableView.tableFooterView = UIView() self.inviteLabel.text = NSLocalizedString("Invite Friends", comment: "Invite Friends") if self.pageId != "" { self.getNotPageMembers(pageId: Int(self.pageId) ?? 10) } else { self.getNotGroupMembers(groupId: Int(self.groupId) ?? 10) } } @IBAction func Back(_ sender: Any) { self.navigationController?.popViewController(animated: true) } private func getNotPageMembers (pageId : Int) { GetNotPageMemberManager.sharedInstance.getNotPageMember(pageId: pageId) { (success, authError, error) in if success != nil { for i in success!.users{ self.usersArray.append(i) } self.tableView.reloadData() } else if authError != nil { self.showAlert(title: "", message: (authError?.errors.errorText)!) } else if error != nil { print("InternalError") } } } private func getNotGroupMembers (groupId : Int) { MemberNot_inGroupManager.sharedInstance.getNotGroupMember(groupId: groupId, completionBlock: { (success, authError, error) in if success != nil { for i in success!.users{ self.usersArray.append(i) } self.tableView.reloadData() } else if authError != nil { self.showAlert(title: "", message: (authError?.errors.errorText)!) } else if error != nil { print("InternalError") } }) } private func AddMembertoPage(user_id : String){ AddMembertoPageManager.sharedInstance.addMembertoPage(pageId: self.pageId, userId: user_id) { (success, authError, error) in if success != nil { print(success?.message) } else if authError != nil { print(authError?.errors.errorText) } else if error != nil { print(error?.localizedDescription) } } } private func AddMembertoGroup(user_id : String){ AddMembertoGroupManager.sharedInstance.addMembertoGroup(groupId: self.groupId, userId: user_id) { (success, authError, error) in if success != nil { print(success?.message) } else if authError != nil { print(authError?.errors.errorText) } else if error != nil { print(error?.localizedDescription) } } } @IBAction func addMember (sender:UIButton) { let position = (sender as AnyObject).convert(CGPoint.zero, to: self.tableView) let indexPath = self.tableView.indexPathForRow(at: position)! let cell = tableView!.cellForRow(at: IndexPath(row: indexPath.row, section: 0)) as! InviteFriendCell let index = self.usersArray[indexPath.row] var userId = "" if let userid = index["user_id"] as? String{ userId = userid } if self.pageId != "" { self.AddMembertoPage(user_id: userId) } else { self.AddMembertoGroup(user_id: userId) } self.usersArray.remove(at: indexPath.row) self.tableView.reloadData() } } extension InviteFriendsController : UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.usersArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "inviteFriend") as! InviteFriendCell let index = usersArray[indexPath.row] if let name = index["username"] as? String { cell.nameLabel.text = name } if let profileImage = index["avatar"] as? String{ let url = URL(string: profileImage) cell.profileIcon.kf.setImage(with: url) } cell.addBtn.addTarget(self, action: #selector(self.addMember(sender:)), for: .touchUpInside) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80.0 } }
33.396104
136
0.578067
3a630d6730855faaa66fbdce88859d8cce8dcc1b
6,413
// // LocalJob.swift // VeracitySDK // // Created by Andrew on 16/04/2019. // Copyright © 2019 Veracity Protocol s.r.o. All rights reserved. // import Foundation import RealmSwift public enum ExpectedJobResult : String { case verified = "verified" case failed = "failed" } ///Represents local variation of server `Job` represented by `type`. public class LocalJob: Object { //MARK: Shared properties @objc dynamic public var identifier: String = LocalProtectItem.generateLocalID() @objc dynamic var createdAt = Date() @objc private dynamic var jobType : String? ///Refenrece to existing job on server. Used to remove after upload complete @objc dynamic public var jobID : String? //MARK: Image Search unique properties @objc dynamic public var overviewImageFilename: String? @objc dynamic public var thumbnailImageFilename: String? //remote data @objc dynamic public var overviewImageUrl : String? @objc dynamic public var thumbnailImageUrl : String? //MARK: Verification unique properties @objc dynamic public var publicArtwork : PublicProtectItem? @objc dynamic public var verificationArtwork : VerificationProtectItem? @objc dynamic public var artwork : ProtectItem? public var fingerprintImageFilenames = List<String>() @objc dynamic public var fingerprintImageFilenamesCount: Int = 0//Used in filter & when taking fps with MAP. @objc dynamic public var algo : String? @objc dynamic private(set) public var expectedResult : String? //remote data public var fingerprintImageUrls = List<String>() ///fingerprint is loaded before verification flow, or later when uploading. @objc dynamic public var fingerprint : Fingerprint? @objc dynamic public var batchJobID : String? public var filesUploadTracking = List<FileUploadTrack>() public var type : JobType? { get { if let jobType = jobType { return JobType(rawValue: jobType) } return nil } set { jobType = newValue?.rawValue } } public var state : ItemState? { if jobID != nil { return .analyzing }else { if UploadManager.shared.currentUploadIdentifier != identifier { return .pending } return .uploading } } public var canBeUploaded : Bool { if type == .verification, jobID == nil, anyArtwork != nil, Array(fingerprintImageFilenames).count > 0 { return true }else if type == .imageSearch, jobID == nil, overviewImageFilename != nil, thumbnailImageFilename != nil { return true } return false } ///Used to get data from any of stored Artwork (`Artwork`, `VerificationArtwork`, `PublicArtwork`). ///Simplify getting overview, width, height, artist etc. public var anyArtwork : ProtectItem? { return artwork ?? verificationArtwork ?? publicArtwork } override public static func primaryKey() -> String { return "identifier" } override public class func shouldIncludeInDefaultSchema() -> Bool { return false } //MARK: - Lifecycle public convenience init(type : JobType, artwork : ProtectItem?) { self.init() self.type = type if let publicArtwork = artwork as? PublicProtectItem { self.publicArtwork = publicArtwork }else if let verificationArtwork = artwork as? VerificationProtectItem { self.verificationArtwork = verificationArtwork }else if let artwork = artwork { self.artwork = artwork } if VeracitySDK.configuration.verificationShouldMatchProtectingAlgo { updateVerificationAlgoToMatchProtectedAlgo() } } //MARK: - Verification unique methods ///Adds fingerprint filename to array and increase separate count of filenames and persist changes ///Because Realm can't filter by @count public func appendFingerprintFilename(_ filename : String) { RealmHandler.shared.persist { self.fingerprintImageFilenames.append(filename) self.fingerprintImageFilenamesCount += 1 } } ///Removes fingerprint data from disk a resets the counter. public func clearFingerprints() { guard Array(fingerprintImageFilenames).count > 0, fingerprintImageFilenamesCount > 0 else { return } fingerprintImageFilenames.forEach({ ImagePersistence.removeImage(atPath: $0) }) RealmHandler.shared.persist { self.fingerprintImageFilenames.removeAll() self.fingerprintImageFilenamesCount = 0 } } ///Removes taken fingerprints, overview & thumbnail images. ///Called before removing whole object from database. public func removeAllLocalImages() { fingerprintImageFilenames.forEach({ ImagePersistence.removeImage(atPath: $0) }) if let overview = overviewImageFilename { ImagePersistence.removeImage(atPath: overview) } if let thumbnail = thumbnailImageFilename { ImagePersistence.removeImage(atPath: thumbnail) } } public func updateVerificationAlgoToMatchProtectedAlgo() { if let protectingAlgo = anyArtwork?.algorithmUsed { algo = protectingAlgo } } ///Trezor verifier unique func. Sets expected job result before verification begins to handle false positive results on backend. public func setExpectedResult(_ expectation : ExpectedJobResult) { expectedResult = expectation.rawValue } public func getTimeUploadFiles() -> Int64 { return self.filesUploadTracking.map { (track) -> Int64 in return track.timeUpload() }.reduce(0, +) } } // MARK: - VeracityItem extension LocalJob: VeracityItem { public var id: String { return identifier } public var itemName: String? { return anyArtwork?.name } public var date: Date? { return createdAt } public var thumbImageUrl: String? { return anyArtwork?.thumbnail ?? thumbnailImageUrl } public var overlayImageUrl: String? { return Array(anyArtwork?.fingerprintUrls ?? []).first ?? Array(fingerprintImageUrls).first } }
34.853261
132
0.658038