repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
apple/swift-nio
Sources/NIOPerformanceTester/LockBenchmark.swift
1
2636
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 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 NIOCore import NIOPosix import Dispatch import NIOConcurrencyHelpers final class NIOLockBenchmark: Benchmark { private let numberOfThreads: Int private let lockOperationsPerThread: Int private let threadPool: NIOThreadPool private let group: EventLoopGroup private let sem1 = DispatchSemaphore(value: 0) private let sem2 = DispatchSemaphore(value: 0) private let sem3 = DispatchSemaphore(value: 0) private var opsDone = 0 private let lock = NIOLock() init(numberOfThreads: Int, lockOperationsPerThread: Int) { self.numberOfThreads = numberOfThreads self.lockOperationsPerThread = lockOperationsPerThread self.threadPool = NIOThreadPool(numberOfThreads: numberOfThreads) self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1) } func setUp() throws { self.threadPool.start() } func tearDown() { try! self.threadPool.syncShutdownGracefully() try! self.group.syncShutdownGracefully() } func run() throws -> Int { self.lock.withLock { self.opsDone = 0 } for _ in 0..<self.numberOfThreads { _ = self.threadPool.runIfActive(eventLoop: self.group.next()) { self.sem1.signal() self.sem2.wait() for _ in 0 ..< self.lockOperationsPerThread { self.lock.withLock { self.opsDone &+= 1 } } self.sem3.signal() } } // Wait until all threads are ready. for _ in 0..<self.numberOfThreads { self.sem1.wait() } // Kick off the work. for _ in 0..<self.numberOfThreads { self.sem2.signal() } // Wait until all threads are done. for _ in 0..<self.numberOfThreads { self.sem3.wait() } let done = self.lock.withLock { self.opsDone } precondition(done == self.numberOfThreads * self.lockOperationsPerThread) return done } }
apache-2.0
fbe949648a77a0c73b02fcf362e53ab5
30.759036
81
0.563733
4.954887
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/remove-boxes.swift
2
1185
/** * https://leetcode.com/problems/remove-boxes/ * * */ // Date: Fri Aug 27 11:56:14 PDT 2021 class Solution { /// Probably the hardest DP problem I've ever seen. /// Reference Link: https://www.youtube.com/watch?v=wT7aS5fHZhs /// - Complexity: /// - Time: O(n^4) /// - Space: O(n^3) private var dp: [[[Int]]] = [] func removeBoxes(_ boxes: [Int]) -> Int { let n = boxes.count dp = Array(repeating: Array(repeating: Array(repeating: 0, count: n), count: n), count: n) return dfs(boxes, 0, n - 1, 0) } private func dfs(_ boxes: [Int], _ l: Int, _ r: Int, _ k: Int) -> Int { if l > r { return 0 } if dp[l][r][k] > 0 { return dp[l][r][k] } var rr = r var kk = k while l < rr && boxes[rr] == boxes[rr - 1] { rr -= 1 kk += 1 } dp[l][r][k] = dfs(boxes, l, rr - 1, 0) + (kk + 1) * (kk + 1) for index in l ..< rr { if boxes[index] == boxes[rr] { dp[l][r][k] = max(dp[l][r][k], dfs(boxes, l, index, kk + 1) + dfs(boxes, index + 1, rr - 1, 0)) } } return dp[l][r][k] } }
mit
452ae94843de6bc086ae6f0a2baecf4f
31.054054
111
0.458228
2.969925
false
false
false
false
iStig/Uther_Swift
Pods/LTMorphingLabel/LTMorphingLabel/LTEmitterView.swift
17
3288
// // LTEmitterView.swift // LTMorphingLabelDemo // // Created by Lex on 3/15/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import UIKit public struct LTEmitter { let layer: CAEmitterLayer = { let layer = CAEmitterLayer() layer.emitterPosition = CGPointMake(10, 10) layer.emitterSize = CGSizeMake(10, 1) layer.renderMode = kCAEmitterLayerOutline layer.emitterShape = kCAEmitterLayerLine return layer }() let cell: CAEmitterCell = { let image = UIImage(named:"Sparkle")!.CGImage let cell = CAEmitterCell() cell.name = "sparkle" cell.birthRate = 150.0 cell.velocity = 50.0 cell.velocityRange = -80.0 cell.lifetime = 0.16 cell.lifetimeRange = 0.1 cell.emissionLongitude = CGFloat(M_PI_2 * 2.0) cell.emissionRange = CGFloat(M_PI_2 * 2.0) cell.contents = image cell.scale = 0.1 cell.yAcceleration = 100 cell.scaleSpeed = -0.06 cell.scaleRange = 0.1 return cell }() public var duration: Float = 0.6 init(name: String, duration: Float) { self.cell.name = name self.duration = duration } public func play() { if let cells = layer.emitterCells { if cells.count > 0 { return } } layer.emitterCells = [cell] let d: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(duration * Float(NSEC_PER_SEC))) dispatch_after(d, dispatch_get_main_queue()) { self.layer.birthRate = 0.0 } } public func stop() { if (nil != layer.superlayer) { layer.removeFromSuperlayer() } } func update(configureClosure: LTEmitterConfigureClosure? = .None) -> LTEmitter { if let closure = configureClosure { configureClosure!(self.layer, self.cell) } return self } } public typealias LTEmitterConfigureClosure = (CAEmitterLayer, CAEmitterCell) -> Void public class LTEmitterView: UIView { public lazy var emitters: Dictionary<String, LTEmitter> = { var _emitters = Dictionary<String, LTEmitter>() return _emitters }() public func createEmitter(name: String, duration: Float, configureClosure: LTEmitterConfigureClosure? = Optional.None) -> LTEmitter { var emitter: LTEmitter if let e = emitterByName(name) { emitter = e } else { emitter = LTEmitter(name: name, duration: duration) if let closure = configureClosure { configureClosure!(emitter.layer, emitter.cell) } layer.addSublayer(emitter.layer) emitters.updateValue(emitter, forKey: name) } return emitter } public func emitterByName(name: String) -> LTEmitter? { if let e = emitters[name] { return e } return Optional.None } public func removeAllEmit() { for (name, emitter) in emitters { emitter.layer.removeFromSuperlayer() } emitters.removeAll(keepCapacity: false) } }
mit
01136ba9ee1b2083300df8a0501a2fb2
26.408333
137
0.571776
4.573018
false
true
false
false
stephentyrone/swift
test/Serialization/load-target-normalization.swift
6
8715
// RUN: %empty-directory(%t/ForeignModule.swiftmodule) // RUN: touch %t/ForeignModule.swiftmodule/garbage-garbage-garbage.swiftmodule // Test format: We try to import ForeignModule with architectures besides // garbage-garbage-garbage and check the target triple listed in the error // message to make sure it was normalized correctly. This works in lieu of a // mechanism to query the compiler for normalized triples. // // The extra flags in the RUN lines serve the following purposes: // // * "-parse-stdlib" ensures we don't reject any of these for not having an // appropriate standard library built. // * "-Xcc -arch -Xcc i386" makes sure the clang importer doesn't reject triples // clang considers invalid. import ForeignModule // CHECK: error: could not find module 'ForeignModule' // CHECK-SAME: '[[NORM]]' // Run lines for individual test cases follow. // // OSES // // OS version numbers should be stripped. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macosx10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // macos, macosx, and darwin should all normalize to macos. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macos10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macosx10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-darwin46.0 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // ios, tvos, watchos should be accepted. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-tvos40 2>&1 | %FileCheck -DNORM=arm64-apple-tvos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-watchos9.1.1 2>&1 | %FileCheck -DNORM=arm64-apple-watchos %s // Other OSes should be passed through without version stripping. We can't test // a totally garbage case because we'll get diag::error_unsupported_target_os. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-linux40.04 2>&1 | %FileCheck -DNORM=x86_64-apple-linux40.04 %s // // VENDORS // // If the OS looks like an Apple OS, vendor should be normalized to apple. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-unknown-macos10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64--ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-ibm-tvos40 2>&1 | %FileCheck -DNORM=arm64-apple-tvos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-snapple-watchos9.1.1 2>&1 | %FileCheck -DNORM=arm64-apple-watchos %s // // ARCHITECTURES // // arm64 and aarch64 are normalized to arm64. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target aarch64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s // armv7s, armv7k, armv7, arm64e should be accepted. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7s-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7s-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7k-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7k-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7-apple-ios %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64e-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64e-apple-ios %s // x86_64h should be accepted. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64h-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64h-apple-macos %s // x64_64 and amd64 are normalized to x86_64. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target amd64-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s // i[3-9]86 are normalized to i386. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i486-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i586-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i686-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i786-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i886-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i986-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s // Other arches should be passed through. We can't test a totally garbage case // because we'll get diag::error_unsupported_target_arch. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target powerpc64-apple-macos10.11 2>&1 | %FileCheck -DNORM=powerpc64-apple-macos %s // // ENVIRONMENTS // // simulator should be permitted on the non-Mac operating systems. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-ios40.0-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-ios-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-tvos40-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-tvos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-watchos9.1.1-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-watchos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-ios40.0-simulator 2>&1 | %FileCheck -DNORM=i386-apple-ios-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-tvos40-simulator 2>&1 | %FileCheck -DNORM=i386-apple-tvos-simulator %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-watchos9.1.1-simulator 2>&1 | %FileCheck -DNORM=i386-apple-watchos-simulator %s // Other environments should be passed through. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-ios40.0-in_spaaaaaaace 2>&1 | %FileCheck -DNORM=i386-apple-ios-in_spaaaaaaace %s // // DARWIN ONLY // // Non-isDarwinOS() OSes should have no normalization applied. // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-unknown-linux40.04 2>&1 | %FileCheck -DNORM=x86_64-unknown-linux40.04 %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target aarch64--linux-android 2>&1 | %FileCheck -DNORM=aarch64--linux-android %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target amd64-ibm-linux40.04 2>&1 | %FileCheck -DNORM=amd64-ibm-linux40.04 %s // RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i986-snapple-haiku 2>&1 | %FileCheck -DNORM=i986-snapple-haiku %s
apache-2.0
a0d11a588b25442ccfa271318b9e289e
68.72
192
0.715089
2.876238
false
false
false
false
tgyhlsb/RxSwiftExt
Tests/RxCocoa/notTests+RxCocoa.swift
2
791
// // notTests+RxCocoa.swift // RxSwiftExt // // Created by Rafael Ferreira on 3/7/17. // Copyright © 2017 RxSwiftCommunity. All rights reserved. // import XCTest import RxCocoa import RxSwift import RxSwiftExt import RxTest class NotCocoaTests: XCTestCase { func testNot() { let values = [true, false, true] let scheduler = TestScheduler(initialClock: 0) let observer = scheduler.createObserver(Bool.self) _ = Observable.from(values).asDriver(onErrorJustReturn: false) .not() .drive(observer) scheduler.start() let correct = [ next(0, false), next(0, true), next(0, false), completed(0) ] XCTAssertEqual(observer.events, correct) } }
mit
d6340415f22ae9fd5ed53ddc3e14e5ea
20.351351
70
0.602532
4.293478
false
true
false
false
Liqiankun/DLSwift
Swift/Swift3Six.playground/Contents.swift
1
1227
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //函数作为参数 func changeScores(scores :inout [Int],by changeScore:(Int)-> Int){ for(index,score) in scores.enumerated(){ scores[index] = changeScore(score) } } var array = [1,2,3,4] func changeScore(b :Int) ->Int{ return b + 1 } changeScores(scores: &array, by: changeScore) array class StudentList{ var students : [String] init(students:[String]) { self.students = students } func addStudent(name:String,at index:Int) { self.students.insert(name, at: index) } func addStudent(name:String,after student:String) { if let index = self.students.index(of: student){ self.students.insert(name, at: index) } } func addStudent(name:String,before student:String) { if let index = self.students.index(of: student){ self.students.insert(name, at: index + 1) } } } let list = StudentList(students: ["1","2","3"]) list.addStudent(name: "4", at: 3) list.students //Swift2: let f = list.addStudent //Swift3 let f = list.addStudent(name:at:) f("5",4) list.students
mit
e531b0c098cc38134be72b7d57ffed42
16.867647
66
0.615638
3.319672
false
false
false
false
fifty-five/Cargo-iOS-Swift
Cargo/Core/CARConstants.swift
1
1998
// // CARConstants.swift // Cargo // // Created by Julien Gil on 24/08/16. // Copyright © 2016 fifty-five All rights reserved. // import Foundation /* ******************************************* tracker ****************************************** */ let APPLICATION_ID: String = "applicationId"; let ENABLE_DEBUG: String = "enableDebug"; let ENABLE_OPTOUT: String = "enableOptOut"; let DISABLE_TRACKING: String = "disableTracking"; let DISPATCH_INTERVAL: String = "dispatchInterval"; let LEVEL2: String = "level2"; let CUSTOM_DIM1: String = "customDim1"; let CUSTOM_DIM2: String = "customDim2"; /* ******************************************* screen ******************************************* */ let SCREEN_NAME: String = "screenName"; /* ******************************************* event ******************************************** */ let EVENT_NAME: String = "eventName"; let EVENT_ID: String = "eventId"; let EVENT_VALUE: String = "eventValue"; let EVENT_TYPE: String = "eventType"; /* ******************************************** user ******************************************** */ let USER_ID: String = "userId"; let USER_AGE: String = "userAge"; let USER_EMAIL: String = "userEmail"; let USER_NAME: String = "userName"; let USER_GENDER: String = "userGender"; let USER_GOOGLE_ID: String = "userGoogleId"; let USER_TWITTER_ID: String = "userTwitterId"; let USER_FACEBOOK_ID: String = "userFacebookId"; /* ***************************************** transaction **************************************** */ let TRANSACTION_ID: String = "transactionId"; let TRANSACTION_TOTAL: String = "transactionTotal"; let TRANSACTION_CURRENCY_CODE: String = "transactionCurrencyCode"; let TRANSACTION_PRODUCTS: String = "transactionProducts"; let TRANSACTION_PRODUCT_NAME: String = "name"; let TRANSACTION_PRODUCT_SKU: String = "sku"; let TRANSACTION_PRODUCT_PRICE: String = "price"; let TRANSACTION_PRODUCT_CATEGORY: String = "category"; let TRANSACTION_PRODUCT_QUANTITY: String = "quantity";
mit
cf18859e635ef1931ad3264d0a6bc23f
36.679245
100
0.564847
4.195378
false
false
false
false
ubi-naist/SenStick
ios/Pods/iOSDFULibrary/iOSDFULibrary/Classes/Utilities/DFUPackage/Manifest/ManifestFirmwareInfo.swift
5
667
// // ManifestFirmwareInfo.swift // Pods // // Created by Mostafa Berg on 28/07/16. // // class ManifestFirmwareInfo: NSObject { var binFile: String? = nil var datFile: String? = nil var valid: Bool { return binFile != nil // && datFile != nil The init packet was not required before SDK 7.1 } init(withDictionary aDictionary : Dictionary<String, AnyObject>) { if aDictionary.keys.contains("bin_file") { binFile = String(describing: aDictionary["bin_file"]!) } if aDictionary.keys.contains("dat_file") { datFile = String(describing: aDictionary["dat_file"]!) } } }
mit
b004d69aae9e101ad09261d1e5c5a9f5
25.68
98
0.605697
3.923529
false
false
false
false
space-app-challenge-london/iOS-client
SpaceApps001/ProductStagesViewController.swift
1
2027
// // LocationSelectionViewController.swift // SpaceApps001 // // Created by Remi Robert on 29/04/2017. // Copyright © 2017 Bratt Neumayer. All rights reserved. // import UIKit import RxSwift import RxCocoa class ProductStagesViewController: UIViewController { private let bag = DisposeBag() @IBOutlet weak var tableview: UITableView! private var dataSource: DataSource<ProductStagesTableViewCell, ProcessStage>! var titlePage: String? var datasFood = [DataFood]() var dataStages = [DataStages]() private var stages: [ProcessStage]? override func viewDidLoad() { super.viewDidLoad() title = titlePage ?? "Stages" configureTableview() tableview.rx.itemSelected.subscribe(onNext: { [weak self] indexPath in let state = states[indexPath.row] self?.performSegue(withIdentifier: "selectProductSegue", sender: state) }).addDisposableTo(bag) } override func viewWillAppear(_ animated: Bool) { self.createStages() } private func configureTableview() { tableview.registerCell(identifier: ProductStagesTableViewCell.identifier) tableview.tableFooterView = UIView() self.createStages() dataSource = DataSource<ProductStagesTableViewCell, ProcessStage>(tableview: tableview, datas: stages!) } func createStages() { if self.dataStages.isEmpty{ stages = datasFood.map({ return ProcessStage(title: $0.rawValue, weight: 1, waterUsage: $0.waterUsage, carbonFootprint: $0.carbonFootprint, wastage: $0.foodWastage) }) }else{ stages = dataStages.map({ return ProcessStage(title: $0.rawValue, weight: 1, waterUsage: $0.waterUsage, carbonFootprint: $0.carbonFootprint, wastage: $0.foodWastage) }) } } }
mit
634f0fbc6d889e513f70ca7436a13d4b
26.753425
155
0.612043
4.789598
false
false
false
false
boqian2000/swift-algorithm-club
Knuth-Morris-Pratt/KnuthMorrisPratt.swift
2
2006
/* Knuth-Morris-Pratt algorithm for pattern/string matching The code is based on the book: "Algorithms on String, Trees and Sequences: Computer Science and Computational Biology" by Dan Gusfield Cambridge University Press, 1997 */ import Foundation extension String { func indexesOf(ptnr: String) -> [Int]? { let text = Array(self.characters) let pattern = Array(ptnr.characters) let textLength: Int = text.count let patternLength: Int = pattern.count guard patternLength > 0 else { return nil } var suffixPrefix: [Int] = [Int](repeating: 0, count: patternLength) var textIndex: Int = 0 var patternIndex: Int = 0 var indexes: [Int] = [Int]() /* Pre-processing stage: computing the table for the shifts (through Z-Algorithm) */ let zeta = ZetaAlgorithm(ptnr: ptnr) for patternIndex in (1 ..< patternLength).reversed() { textIndex = patternIndex + zeta![patternIndex] - 1 suffixPrefix[textIndex] = zeta![patternIndex] } /* Search stage: scanning the text for pattern matching */ textIndex = 0 patternIndex = 0 while textIndex + (patternLength - patternIndex - 1) < textLength { while patternIndex < patternLength && text[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } if patternIndex == patternLength { indexes.append(textIndex - patternIndex) } if patternIndex == 0 { textIndex = textIndex + 1 } else { patternIndex = suffixPrefix[patternIndex - 1] } } guard !indexes.isEmpty else { return nil } return indexes } }
mit
bdd08f785ab5b824648b42e511a7fe98
29.861538
92
0.546361
4.868932
false
false
false
false
tad-iizuka/swift-sdk
Source/DiscoveryV1/Models/BlekkoResult.swift
2
2449
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** The results the search engine Blekko returns. */ public struct BlekkoResult: JSONDecodable { /// Language of the document. If the language is something other than "en" for /// english, the document will fail to be processed and the Status of the QueryResponse /// will be 'ERROR'. public let language: String? /// Raw title of the document. public let rawTitle: [String]? /// Cleaned title of the document by the service. public let cleanTitle: [String]? /// Extracted URL of the document. public let url: String? /// The publication date in epoch seconds from UTC. public let chrondate: Int? /// Extracted text snippets of the document. public let snippets: [String]? /// Hostname of the document. public let host: String? /// Extracted type of document. public let documentType: String? /// The raw JSON object used to construct this model. public let json: [String: Any] /// Used internally to initialize a `BlekkoResult` model from JSON. public init(json: JSON) throws { language = try? json.getString(at: "lang") rawTitle = try? json.decodedArray(at: "raw_title", type: Swift.String) cleanTitle = try? json.decodedArray(at: "clean_title", type: Swift.String) url = try? json.getString(at: "url") chrondate = try? json.getInt(at: "chrondate") snippets = try? json.decodedArray(at: "snippets", type: Swift.String) host = try? json.getString(at: "host") documentType = try? json.getString(at: "documentType") self.json = try json.getDictionaryObject() } /// Used internally to serialize a 'BlekkoResult' model to JSON. public func toJSONObject() -> Any { return json } }
apache-2.0
ee3e699d4299229ffcdcfc9b0ec40c6f
34.492754
91
0.668028
4.222414
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Card/Detail/Controller/CardDetailViewController.swift
1
14830
// // CardDetailViewController.swift // DereGuide // // Created by zzk on 16/6/16. // Copyright © 2016年 zzk. All rights reserved. // import UIKit import SnapKit import ImageViewer import SDWebImage import AudioToolbox class CardDetailViewController: BaseTableViewController { var card: CGSSCard! { didSet { loadDataAsync() } } private func createGalleryItem(url: URL?) -> GalleryItem { let myFetchImageBlock: FetchImageBlock = { (completion) in guard let url = url else { completion(nil) return } SDWebImageManager.shared().loadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, _, _) in completion(image) }) } let itemViewControllerBlock: ItemViewControllerBlock = { index, itemCount, fetchImageBlock, configuration, isInitialController in return GalleryImageItemBaseController(index: index, itemCount: itemCount, fetchImageBlock: myFetchImageBlock, configuration: configuration, isInitialController: isInitialController) } let galleryItem = GalleryItem.custom(fetchImageBlock: myFetchImageBlock, itemViewControllerBlock: itemViewControllerBlock) return galleryItem } lazy var items: [GalleryItem] = { var result = [GalleryItem]() result.append(self.createGalleryItem(url: URL(string: self.card.cardImageRef))) if self.card.hasSpread { result.append(self.createGalleryItem(url: self.card.spreadImageURL)) } if self.card.hasSign { result.append(self.createGalleryItem(url: self.card.signImageURL)) } return result }() fileprivate func createGalleryViewController(startIndex: Int) -> GalleryViewController { let config = [ GalleryConfigurationItem.closeButtonMode(.builtIn), GalleryConfigurationItem.closeLayout(.pinLeft(32, 20)), GalleryConfigurationItem.hideDecorationViewsOnLaunch(true), GalleryConfigurationItem.deleteButtonMode(.none), GalleryConfigurationItem.thumbnailsButtonMode(.none), GalleryConfigurationItem.swipeToDismissMode(.vertical) ] let vc = GalleryViewController(startIndex: startIndex, itemsDataSource: self, itemsDelegate: nil, displacedViewsDataSource: self, configuration: config) return vc } fileprivate struct Row: CustomStringConvertible { var type: UITableViewCell.Type var description: String { return type.description() } } override var prefersStatusBarHidden: Bool { return isSpreadModeOn } fileprivate var rows: [Row] = [] var spreadImageView: SpreadImageView? { return (self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? CardDetailSpreadImageCell)?.spreadImageView } private func loadDataAsync() { CGSSGameResource.shared.master.getMusicInfo(charaID: card.charaId) { (songs) in DispatchQueue.main.async { self.songs = songs self.prepareRows() self.registerCells() self.tableView?.reloadData() print("load card \(self.card.id!)") } } } private func prepareRows() { rows.removeAll() guard let card = self.card else { return } if card.hasSpread { rows.append(Row(type: CardDetailSpreadImageCell.self)) } rows.append(Row(type: CardDetailBasicCell.self)) rows.append(Row(type: CardDetailAppealCell.self)) rows.append(Row(type: CardDetailRelativeStrengthCell.self)) if card.skill != nil { rows.append(Row(type: CardDetailSkillCell.self)) } if card.leaderSkill != nil { rows.append(Row(type: CardDetailLeaderSkillCell.self)) } rows.append(Row(type: CardDetailEvolutionCell.self)) rows.append(Row(type: CardDetailRelatedCardsCell.self)) if card.rarityType.rawValue >= CGSSRarityTypes.sr.rawValue { rows.append(Row(type: CardDetailSourceCell.self)) } if songs.count > 0 { let row = Row(type: CardDetailMVCell.self) self.rows.append(row) } } override func viewDidLoad() { super.viewDidLoad() // 自定义titleView的文字大小 let titleView = UILabel.init(frame: CGRect(x: 0, y: 0, width: 0, height: 44)) titleView.text = card.name titleView.font = UIFont.systemFont(ofSize: 12) titleView.textAlignment = .center titleView.adjustsFontSizeToFitWidth = true titleView.baselineAdjustment = .alignCenters navigationItem.titleView = titleView // let rightItem = UIBarButtonItem.init(title: CGSSFavoriteManager.defaultManager.contains(card.id!) ? "取消":"收藏", style: .Plain, target: self, action: #selector(addOrRemoveFavorite)) let rightItem = UIBarButtonItem.init(image: FavoriteCardsManager.shared.contains(card.id) ? UIImage.init(named: "748-heart-toolbar-selected") : UIImage.init(named: "748-heart-toolbar"), style: .plain, target: self, action: #selector(addOrRemoveFavorite)) rightItem.tintColor = UIColor.red navigationItem.rightBarButtonItem = rightItem // let leftItem = UIBarButtonItem.init(title: "返回", style: .Plain, target: self, action: #selector(backAction)) let leftItem = UIBarButtonItem.init(image: UIImage.init(named: "765-arrow-left-toolbar"), style: .plain, target: self, action: #selector(backAction)) navigationItem.leftBarButtonItem = leftItem prepareToolbar() tableView.estimatedRowHeight = 68 tableView.tableFooterView = UIView() } private func registerCells() { for row in rows { tableView .register(row.type, forCellReuseIdentifier: row.description) } } // 添加当前卡到收藏 @objc func addOrRemoveFavorite() { let manager = FavoriteCardsManager.shared if !manager.contains(card.id) { manager.add(card) self.navigationItem.rightBarButtonItem?.image = UIImage.init(named: "748-heart-toolbar-selected") } else { manager.remove(card.id) self.navigationItem.rightBarButtonItem?.image = UIImage.init(named: "748-heart-toolbar") } } @available(iOS 9.0, *) override var previewActionItems: [UIPreviewActionItem] { let titleString: String let manager = FavoriteCardsManager.shared if manager.contains(card.id) { titleString = NSLocalizedString("取消收藏", comment: "") } else { titleString = NSLocalizedString("收藏", comment: "") } let item3 = UIPreviewAction.init(title: titleString, style: .default, handler: { (action, vc) in if let card = (vc as? CardDetailViewController)?.card { if manager.contains(card.id) { manager.remove(card.id) } else { manager.add(card) } } }) return [item3] } func prepareToolbar() { // let item1 = UIBarButtonItem.init(title: NSLocalizedString("3D模型", comment: ""), style: .plain, target: self, action: #selector(show3DModelAction)) // let spaceItem1 = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let item2 = UIBarButtonItem.init(title: NSLocalizedString("卡片图", comment: ""), style: .plain, target: self, action: #selector(showCardImageAction)) let spaceItem2 = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let item3 = UIBarButtonItem.init(title: NSLocalizedString("签名图", comment: ""), style: .plain, target: self, action: #selector(showSignImageAction)) if card.signImageURL == nil { item3.isEnabled = false } toolbarItems = [item2, spaceItem2, item3] } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if isShowing { setSpreadImageMode(card.hasSpread && UIDevice.current.orientation.isLandscape, animated: false) } super.viewWillTransition(to: size, with: coordinator) } fileprivate var isSpreadModeOn = false fileprivate func setSpreadImageMode(_ isOn: Bool, animated: Bool) { isSpreadModeOn = isOn setNeedsStatusBarAppearanceUpdate() navigationController?.setToolbarHidden(isOn, animated: animated) navigationController?.setNavigationBarHidden(isOn, animated: animated) navigationController?.interactivePopGestureRecognizer?.isEnabled = !isOn if animated { tableView.beginUpdates() tableView.endUpdates() } let indexPath = IndexPath(row: 0, section: 0) if isOn { tableView.scrollToRow(at: indexPath, at: .middle, animated: animated) } } private var isShowing = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isShowing = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isShowing = false } @objc func backAction() { navigationController?.popViewController(animated: true) } @objc func showCardImageAction() { let vc = createGalleryViewController(startIndex: 0) presentImageGallery(vc) } @objc func showSignImageAction() { let vc = createGalleryViewController(startIndex: 2) presentImageGallery(vc) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if isSpreadModeOn && indexPath.row == 0 { return UIScreen.main.bounds.height } else { return UITableViewAutomaticDimension } } private var songs = [CGSSSong]() override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = rows[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: row.description, for: indexPath) switch cell { case let cell as CardDetailSetable: cell.setup(with: card) default: break } switch cell { case let cell as CardDetailRelatedCardsCell: cell.delegate = self case let cell as CardDetailEvolutionCell: cell.delegate = self case let cell as CardDetailMVCell: cell.delegate = self cell.setup(songs: songs) case let cell as CardDetailSpreadImageCell: cell.delegate = self default: break } return cell } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rows.count } override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if isSpreadModeOn { setSpreadImageMode(false, animated: true) } } } extension CardDetailViewController: CardDetailRelatedCardsCellDelegate { func didClickRightDetail(_ cardDetailRelatedCardsCell: CardDetailRelatedCardsCell) { let vc = CharDetailViewController() vc.chara = card.chara navigationController?.pushViewController(vc, animated: true) } } extension CardDetailViewController: CardDetailSpreadImageCellDelegate { func cardDetailSpreadImageCell(_ cardDetailSpreadImageCell: CardDetailSpreadImageCell, longPressAt point: CGPoint) { guard let image = cardDetailSpreadImageCell.spreadImageView.image else { return } // 作为被分享的内容 不能是可选类型 否则分享项不显示 let urlArray = [image] let activityVC = UIActivityViewController.init(activityItems: urlArray, applicationActivities: nil) let excludeActivitys:[UIActivityType] = [] activityVC.excludedActivityTypes = excludeActivitys activityVC.popoverPresentationController?.sourceView = cardDetailSpreadImageCell.spreadImageView activityVC.popoverPresentationController?.sourceRect = CGRect(x: point.x, y: point.y, width: 0, height: 0) present(activityVC, animated: true, completion: nil) // play sound like pop(3d touch) AudioServicesPlaySystemSound(1520) } func tappedCardDetailSpreadImageCell(_ cardDetailSpreadImageCell: CardDetailSpreadImageCell) { let vc = createGalleryViewController(startIndex: 1) presentImageGallery(vc) } } extension CardDetailViewController: GalleryItemsDataSource { func itemCount() -> Int { var count = 1 if card.hasSpread { count += 1 } if card.signImageURL != nil { count += 1 } return count } func provideGalleryItem(_ index: Int) -> GalleryItem { return items[index] } } extension CardDetailViewController: GalleryDisplacedViewsDataSource { func provideDisplacementItem(atIndex index: Int) -> DisplaceableView? { if index == 1 { return spreadImageView } else { return nil } } } extension CardDetailViewController: CGSSIconViewDelegate { func iconClick(_ iv: CGSSIconView) { if let icon = iv as? CGSSCardIconView { let dao = CGSSDAO.shared // 如果因为数据更新导致未查找到指定的卡片, 则不弹出新页面 if let card = dao.findCardById(icon.cardID!) { let cardDetailVC = CardDetailViewController() cardDetailVC.card = card // cardDetailVC.modalTransitionStyle = .CoverVertical self.navigationController?.pushViewController(cardDetailVC, animated: true) } } } } extension CardDetailViewController: CardDetailMVCellDelegate { func cardDetailMVCell(_ cardDetailMVCell: CardDetailMVCell, didClickAt index: Int) { let vc = SongDetailController() vc.setup(songs: songs, index: index) navigationController?.pushViewController(vc, animated: true) } }
mit
c70fbea150cd7dd21673cbe0bba821a0
35.734336
262
0.636215
5.01094
false
false
false
false
kevinup7/S4HeaderExtensions
Sources/S4HeaderExtensions/ResponseHeaders/Vary.swift
1
2033
import S4 extension Headers { /** The `Vary` header field in a response describes what parts of a request message, aside from the method, Host header field, and request target, might influence the origin server's process for selecting and representing this response. The value consists of either a single asterisk ("*") or a list of header field names (case-insensitive). ## Example Headers `Vary: accept-encoding, accept-language` `Vary: *` ## Examples var response = Response() request.headers.vary = .Any var response = Response() response.headers.vary = .Fields(["accept-encoding", "accept-language"]) - seealso: [RFC7231](https://tools.ietf.org/html/rfc7231#section-7.1.4) */ public var vary: Vary? { get { if let headerValues = headers["Vary"] { return Vary(headerValue: headerValues) } return nil } set { headers["Vary"] = newValue?.headerValue } } } public enum Vary: Equatable { case any case fields([CaseInsensitiveString]) } extension Vary { public init?(headerValue: String) { if headerValue == "*" { self = .any } else { if let strings = CaseInsensitiveString.values(fromHeader: headerValue) { self = .fields(strings) } else { return nil } } } } extension Vary: HeaderValueRepresentable { public var headerValue: String { switch self { case .any: return "*" case .fields(let fields): return fields.headerValue } } } public func ==(lhs: Vary, rhs: Vary) -> Bool { switch (lhs, rhs) { case (.any, .any): return true case (.fields(let lhsFields), .fields(let rhsFields)): return lhsFields == rhsFields default: return false } }
mit
897de5ceef62d817caf65d1ba22cc290
24.4125
84
0.551894
4.52784
false
false
false
false
penatheboss/PWCameraView
PWCameraView.swift
2
10221
/* MIT License Copyright (c) [2016] [Pranav Wadhwa] 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. */ //Notes: //This project is witten in Swift 3 //rotateButton has an image named "rotate" PWCameraView checks if the image exists; otherwise it will replace with a title //The 'reload' method cannot be called in 'viewDidLoad'. Call it in 'viewWillAppear' or 'viewDidAppear' //Add "NSCameraUsageDescription" in your info.plist with a String that states how your app will use the camera import UIKit import AVFoundation class PWCameraView: UIView { enum CameraDirection { case Front case Back } var direction: CameraDirection = .Back func flipCamera(sender: AnyObject) { if direction == .Back { direction = .Front } else { direction = .Back } reload() } var clickButton = UIButton() var rotateButton = UIButton() var beginGestureScale = CGFloat() var captureSession: AVCaptureSession? var stillImageOutput: AVCaptureStillImageOutput? var previewLayer: AVCaptureVideoPreviewLayer? var tempBackground = UIImageView() var clickedImage: UIImage? { didSet { tempBackground.image = clickedImage } } func clickPicture() { if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) { videoConnection.videoOrientation = .portrait stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in if sampleBuffer != nil { let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) let dataProvider = CGDataProvider(data: imageData!) let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent) let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right) self.captureSession?.stopRunning() self.clickedImage = image self.clickButton.frame.size = CGSize(width: 200, height: 80) self.clickButton.setTitle("Retake", for: []) self.clickButton.layer.cornerRadius = 40 self.clickButton.center.x = self.center.x self.clickButton.layer.backgroundColor = self.shadeColor.cgColor self.clickButton.removeTarget(nil, action: nil, for: .allEvents) self.clickButton.addTarget(self, action: #selector(self.retakePicture), for: .touchUpInside) self.clickButton.superview!.bringSubview(toFront: self.clickButton) } }) } } func retakePicture() { tempBackground.frame = self.frame reload() clickButton.setTitle("", for: []) clickButton.frame.size = CGSize(width: 80, height: 80) clickButton.layer.cornerRadius = clickButton.frame.size.width / 2 clickButton.layer.borderColor = UIColor.white().cgColor clickButton.removeTarget(nil, action: nil, for: .allEvents) clickButton.layer.backgroundColor = shadeColor.cgColor clickButton.center.x = self.center.x clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside) clickButton.superview!.bringSubview(toFront: clickButton) } func reload() { captureSession?.stopRunning() previewLayer?.removeFromSuperlayer() captureSession = AVCaptureSession() captureSession!.sessionPreset = AVCaptureSessionPresetiFrame1280x720 var captureDevice:AVCaptureDevice! = nil let videoDevices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) for device in videoDevices! { let device = device as! AVCaptureDevice if device.position == AVCaptureDevicePosition.front { captureDevice = device break } } var input = AVCaptureDeviceInput() do { input = try AVCaptureDeviceInput(device: captureDevice) } catch { print("catch") return } if self.captureSession!.canAddInput(input) == true { self.captureSession!.addInput(input) self.stillImageOutput = AVCaptureStillImageOutput() self.stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] if self.captureSession!.canAddOutput(self.stillImageOutput) { self.captureSession!.addOutput(self.stillImageOutput) self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) self.previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect self.previewLayer!.connection?.videoOrientation = .portrait self.previewLayer?.frame = self.bounds self.layer.addSublayer(self.previewLayer!) self.captureSession!.startRunning() self.clickedImage = nil self.bringSubview(toFront: self.clickButton) self.bringSubview(toFront: self.rotateButton) } else { print("cannot add ouput") } } else { print("cannot add input") } self.bringSubview(toFront: clickButton) self.bringSubview(toFront: rotateButton) } func zoom(recognizer: UIPinchGestureRecognizer) { if recognizer.state == .began { beginGestureScale = recognizer.scale } var allTouchesAreOnThePreviewLayer: Bool = true let numTouches: Int = recognizer.numberOfTouches() for i in 0..<numTouches { let location: CGPoint = recognizer.location(ofTouch: i, in: self) let convertedLocation: CGPoint = previewLayer!.convert(location, from: previewLayer!.superlayer) if !previewLayer!.contains(convertedLocation) { allTouchesAreOnThePreviewLayer = false } } if allTouchesAreOnThePreviewLayer { var effectiveScale = beginGestureScale * recognizer.scale if effectiveScale < 1.0 { effectiveScale = 1.0 } let maxScaleAndCropFactor: CGFloat = stillImageOutput!.connection(withMediaType: AVMediaTypeVideo).videoMaxScaleAndCropFactor if effectiveScale > maxScaleAndCropFactor { effectiveScale = maxScaleAndCropFactor } CATransaction.begin() CATransaction.setAnimationDuration(0.025) previewLayer?.setAffineTransform(CGAffineTransform(scaleX: effectiveScale, y: effectiveScale)) CATransaction.commit() } } override init(frame: CGRect) { super.init(frame: frame) if UIImagePickerController.isSourceTypeAvailable(.camera) == false { UIApplication.shared().openURL(URL(string: UIApplicationOpenSettingsURLString)!) return } let pinch = UIPinchGestureRecognizer(target: self, action: #selector(self.zoom(recognizer:))) self.addGestureRecognizer(pinch) previewLayer?.frame = self.bounds clickButton.frame.size = CGSize(width: 100, height: 100) clickButton.layer.cornerRadius = clickButton.frame.size.width / 2 clickButton.layer.borderColor = UIColor.white().cgColor clickButton.layer.borderWidth = 2.5 clickButton.layer.backgroundColor = shadeColor.cgColor clickButton.center.x = self.center.x clickButton.center.y = self.frame.size.height - clickButton.frame.size.height + 20 clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside) self.addSubview(clickButton) rotateButton.frame.size = CGSize(width: 45, height: 45) rotateButton.center = CGPoint(x: self.frame.size.width - rotateButton.frame.size.width, y: rotateButton.frame.size.height) if let rotateImage = UIImage(named: "rotate") { rotateButton.setImage(rotateImage, for: []) } else { rotateButton.setTitle("Rotate", for: []) rotateButton.titleLabel?.font = UIFont.systemFont(ofSize: 11, weight: UIFontWeightLight) } self.addSubview(rotateButton) self.addSubview(tempBackground) self.bringSubview(toFront: clickButton) self.bringSubview(toFront: rotateButton) } let shadeColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.7) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
c9de7fd18020f0e317fc5fee2d694608
38.925781
145
0.629293
5.396515
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/EthereumKit/Models/Transactions/EthereumTransactionFee.swift
1
2752
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import MoneyKit import PlatformKit public struct EthereumTransactionFee { // MARK: Types public enum FeeLevel { case regular case priority } // MARK: Static Methods static func `default`(network: EVMNetwork) -> EthereumTransactionFee { switch network { case .ethereum: return EthereumTransactionFee( regular: 50, priority: 100, gasLimit: 21000, gasLimitContract: 75000, network: .ethereum ) case .polygon: return EthereumTransactionFee( regular: 30, priority: 40, gasLimit: 21000, gasLimitContract: 75000, network: .polygon ) } } // MARK: Private Properties private let regular: CryptoValue private let priority: CryptoValue private let gasLimit: Int private let gasLimitContract: Int private let network: EVMNetwork // MARK: Init init( regular: Int, priority: Int, gasLimit: Int, gasLimitContract: Int, network: EVMNetwork ) { self.regular = .ether(gwei: BigInt(regular), network: network) self.priority = .ether(gwei: BigInt(priority), network: network) self.gasLimit = gasLimit self.gasLimitContract = gasLimitContract self.network = network } // MARK: Private Methods public func gasPrice(feeLevel: FeeLevel) -> BigUInt { switch feeLevel { case .regular: return BigUInt(regular.amount) case .priority: return BigUInt(priority.amount) } } public func gasLimit( extraGasLimit: BigUInt = 0, isContract: Bool ) -> BigUInt { BigUInt(isContract ? gasLimitContract : gasLimit) + extraGasLimit } public func absoluteFee( with feeLevel: FeeLevel, extraGasLimit: BigUInt = 0, isContract: Bool ) -> CryptoValue { let price = gasPrice(feeLevel: feeLevel) let gasLimit = gasLimit(extraGasLimit: extraGasLimit, isContract: isContract) let amount = price * gasLimit return CryptoValue .create( minor: BigInt(amount), currency: network.cryptoCurrency ) } } extension CryptoValue { static func ether( gwei: BigInt, network: EVMNetwork ) -> CryptoValue { let wei = gwei * BigInt(1e9) return CryptoValue( amount: wei, currency: network.cryptoCurrency ) } }
lgpl-3.0
1866fe12577765c5a820a1fcce65b4fa
24.009091
85
0.569248
4.759516
false
false
false
false
qmathe/Starfish
Test/TestCommon.swift
1
2686
/** Copyright (C) 2017 Quentin Mathe Author: Quentin Mathe <[email protected]> Date: June 2017 License: MIT */ import XCTest @testable import Starfish struct DummyError: Error { } extension XCTestCase { func wait(_ delay: TimeInterval = 0.001) { RunLoop.main.run(until: Date(timeIntervalSinceNow: delay)) } } typealias Event<T> = Flux<T>.Event<T> func XCTAssertEqual<T: Equatable>(_ expression1: @autoclosure () throws -> [Event<T>], _ expression2: @autoclosure () throws -> [Event<T>], _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(expression1, expression2, { $0 == $1 }, message, file: file, line: line) } // Arrays and tuples (tuples nested in arrarys in our test case) doesn't conform to Equatable and cannot be // extended to do so in Swift 3: // // - we implement equalEvents() to compare event arrays // - we pass a closure to decide whether two event values are equal or not rather instead of using == func XCTAssertEqual<T>(_ expression1: @autoclosure () throws -> [Event<T>], _ expression2: @autoclosure () throws -> [Event<T>], _ equal: (T, T) -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) { guard let lhs = try? expression1(), let rhs = try? expression2() else { XCTFail() return } if equalEvents(lhs, rhs, equal) { XCTAssertTrue(true) } else { print("Expected \(lhs), got \(rhs)") XCTFail() } } // TODO: With Swift 4, we could support extension Event: Equatable where T: Equatable { } private func equalEvents <T>(_ lhs: [Event<T>], _ rhs: [Event<T>], _ equal: (T, T) -> Bool) -> Bool { guard lhs.count == rhs.count else { return false } for (index, lhsElement) in lhs.enumerated() { let rhsElement = rhs[index] if !equalEvent(lhsElement, rhsElement, equal) { return false } } return true } func equalEvent<T>(_ lhs: Event<T>, _ rhs: Event<T>, _ equal: (T, T) -> Bool) -> Bool { switch (lhs, rhs) { case (Event<T>.value(let value1), Event<T>.value(let value2)): return equal(value1, value2) case (Event<T>.error(_), Event<T>.error(_)): return true case (Event<T>.completed, Event<T>.completed): return true default: return false } } func == <T: Equatable>(lhs: Event<T>, rhs: Event<T>) -> Bool { switch (lhs, rhs) { case (Event<T>.value(let value1), Event<T>.value(let value2)): return value1 == value2 case (Event<T>.error(_), Event<T>.error(_)): return true case (Event<T>.completed, Event<T>.completed): return true default: return false } } extension Event { var value: T? { guard case .value(let value) = self else { return nil } return value } }
mit
f52ab257117c30c8077b5f1e01325970
26.979167
246
0.657483
3.13785
false
false
false
false
vector-im/riot-ios
Riot/Modules/Secrets/Setup/RecoveryKey/SecretsSetupRecoveryKeyCoordinator.swift
1
2787
// File created from ScreenTemplate // $ createScreen.sh SecretsSetupRecoveryKey SecretsSetupRecoveryKey /* 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 Foundation import UIKit final class SecretsSetupRecoveryKeyCoordinator: SecretsSetupRecoveryKeyCoordinatorType { // MARK: - Properties // MARK: Private private var secretsSetupRecoveryKeyViewModel: SecretsSetupRecoveryKeyViewModelType private let secretsSetupRecoveryKeyViewController: SecretsSetupRecoveryKeyViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: SecretsSetupRecoveryKeyCoordinatorDelegate? // MARK: - Setup init(recoveryService: MXRecoveryService, passphrase: String?) { let secretsSetupRecoveryKeyViewModel = SecretsSetupRecoveryKeyViewModel(recoveryService: recoveryService, passphrase: passphrase) let secretsSetupRecoveryKeyViewController = SecretsSetupRecoveryKeyViewController.instantiate(with: secretsSetupRecoveryKeyViewModel) self.secretsSetupRecoveryKeyViewModel = secretsSetupRecoveryKeyViewModel self.secretsSetupRecoveryKeyViewController = secretsSetupRecoveryKeyViewController } // MARK: - Public methods func start() { self.secretsSetupRecoveryKeyViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.secretsSetupRecoveryKeyViewController } } // MARK: - SecretsSetupRecoveryKeyViewModelCoordinatorDelegate extension SecretsSetupRecoveryKeyCoordinator: SecretsSetupRecoveryKeyViewModelCoordinatorDelegate { func secretsSetupRecoveryKeyViewModelDidComplete(_ viewModel: SecretsSetupRecoveryKeyViewModelType) { self.delegate?.secretsSetupRecoveryKeyCoordinatorDidComplete(self) } func secretsSetupRecoveryKeyViewModelDidFailed(_ viewModel: SecretsSetupRecoveryKeyViewModelType) { self.delegate?.secretsSetupRecoveryKeyCoordinatorDidFailed(self) } func secretsSetupRecoveryKeyViewModelDidCancel(_ viewModel: SecretsSetupRecoveryKeyViewModelType) { self.delegate?.secretsSetupRecoveryKeyCoordinatorDidCancel(self) } }
apache-2.0
66a9fb4eacd06507db4999a980385dfb
37.708333
141
0.775386
6.699519
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/LifetimeTracker/Sources/iOS/UI/LifetimeTrackerListViewController.swift
1
1655
// // LifetimeTrackerListViewController.swift // LifetimeTracker-iOS // // Created by Hans Seiffert on 18.03.18. // Copyright © 2018 LifetimeTracker. All rights reserved. // import UIKit protocol PopoverViewControllerDelegate: class { func dismissPopoverViewController() func changeHideOption(for hideOption: HideOption) } class LifetimeTrackerListViewController: UIViewController { weak var delegate: PopoverViewControllerDelegate? weak var tableViewController: DashboardTableViewController? var dashboardViewModel = BarDashboardViewModel() override func viewDidLoad() { super.viewDidLoad() } @IBAction func closeButtonPressed(_ sender: Any) { delegate?.dismissPopoverViewController() } @IBAction func settingsButtonPressed(_ sender: Any) { SettingsManager.showSettingsActionSheet(on: self, completionHandler: { [weak self] (selectedOption: HideOption) in self?.delegate?.changeHideOption(for: selectedOption) }) } func update(dashboardViewModel: BarDashboardViewModel) { self.dashboardViewModel = dashboardViewModel title = "popover.dasboard.title".lt_localized tableViewController?.update(dashboardViewModel: dashboardViewModel) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Constants.Segue.embedDashboardTableView.identifier { tableViewController = segue.destination as? DashboardTableViewController tableViewController?.update(dashboardViewModel: dashboardViewModel) } } }
mit
001394236bc9d11e08f69d6963a58b5e
30.807692
122
0.711608
5.422951
false
false
false
false
GTMYang/GTMRefresh
GTMRefreshExample/YahooWeather/YahooWeatherRefreshHeader.swift
1
4146
// // YahooWeatherRefreshHeader.swift // PullToRefreshKit // // Created by luoyang on 2016/12/8. // Copyright © 2016年 luoyang. All rights reserved. // import UIKit import GTMRefresh class YahooWeatherRefreshHeader: GTMRefreshHeader, SubGTMRefreshHeaderProtocol { let imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 40, height: 40)) let logoImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 60, height: 14)) let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { // self.backgroundColor = UIColor(white: 0.0, alpha: 0.25) imageView.image = UIImage(named: "sun_000000") logoImage.image = UIImage(named: "yahoo_logo") label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: 12) label.text = "Last update: 5 minutes ago" self.contentView.addSubview(imageView) self.contentView.addSubview(logoImage) self.contentView.addSubview(label) } override func layoutSubviews() { super.layoutSubviews() logoImage.center = CGPoint(x: self.bounds.width/2.0, y: frame.height - 30 - 7.0) imageView.center = CGPoint(x: self.bounds.width/2.0 - 60.0, y: frame.height - 30) label.frame = CGRect(x: logoImage.frame.origin.x, y: logoImage.frame.origin.y + logoImage.frame.height + 2,width: 200, height: 20) } var animating: Bool = false func startTransitionAnimation(){ if animating { return } animating = true imageView.image = UIImage(named: "sun_00073") // let images = (27...72).map({"sun_000\($0)"}).map({UIImage(named:$0)!}) // imageView.animationImages = images // imageView.animationDuration = Double(images.count) * 0.02 // imageView.animationRepeatCount = 1 // imageView.startAnimating() // self.perform(#selector(YahooWeatherRefreshHeader.transitionFinihsed), with: nil, afterDelay: imageView.animationDuration) let images = (73...109).map({return $0 < 100 ? "sun_000\($0)" : "sun_00\($0)"}).map({UIImage(named:$0)!}) imageView.animationImages = images imageView.animationDuration = Double(images.count) * 0.03 imageView.animationRepeatCount = 1000000 imageView.startAnimating() } @objc func transitionFinihsed(){ let images = (73...109).map({return $0 < 100 ? "sun_000\($0)" : "sun_00\($0)"}).map({UIImage(named:$0)!}) imageView.animationImages = images imageView.animationDuration = Double(images.count) * 0.03 imageView.animationRepeatCount = 1000000 imageView.startAnimating() } // MARK: SubGTMRefreshHeaderProtocol func contentHeight() -> CGFloat { return 60.0 } func toNormalState() { print("\(self) toNormalState") //imageView.image = UIImage(named: "sun_000000") } func toRefreshingState() { // imageView.image = nil print("\(self) statr refreshing") startTransitionAnimation() } func toPullingState() { } func changePullingPercent(percent: CGFloat) { let adjustPercent = max(min(1.0, percent),0.0) let index = Int(adjustPercent * 27) let imageName = index < 10 ? "sun_0000\(index)" : "sun_000\(index)" DispatchQueue.main.async { [weak self] in self?.imageView.image = UIImage(named:imageName) } } func toWillRefreshState() { // imageView.image = nil print("\(self) will refreshing") startTransitionAnimation() } func willEndRefreshing(isSuccess: Bool) { print("\(self) willEndRefreshing") } func didEndRefreshing() { print("\(self) didEndRefreshing") imageView.stopAnimating() animating = false } }
mit
5a799db3bfd0aab5bd16af812b2811ca
30.625954
138
0.596428
4.302181
false
false
false
false
ssmali1505/Web-service-call-in-swift
WebServiceCalls/WebServiceCalls/APIUtilityHelper.swift
1
1830
// // APIUtilityHelper.swift // WebServiceCalls // // Created by SANDY on 02/01/15. // Copyright (c) 2015 Evgeny Nazarov. All rights reserved. // import Foundation import SystemConfiguration public class APIUtilityHelper: NSObject { override init() { super.init(); } // MARK: UTILITY /// Reachability Method to check Internet available or not func isInternetAvailable() -> Bool { var objAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) objAddress.sin_len = UInt8(sizeofValue(objAddress)) objAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&objAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return false } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) ? true : false } func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String { var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil if NSJSONSerialization.isValidJSONObject(value) { if let data = NSJSONSerialization.dataWithJSONObject(value, options: options, error: nil) { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return string } } } return "" } }
apache-2.0
8d7ebf0e047a60cb78d164a7c612ff38
31.696429
142
0.620765
4.692308
false
false
false
false
cactis/SwiftEasyKit
Source/Classes/Segment.swift
1
11230
// // Segment.swift // // Created by ctslin on 2/28/16. import UIKit public enum Direction { case horizontal case vertical } open class SegmentWithViews: DefaultView, UIScrollViewDelegate { public var header = UIView() public var segment: Segment! public var scrollView = UIScrollView() public var views = [UIView]() public var segmentHeight: CGFloat = 40 public var segmentXPad: CGFloat = 0 public var segmentYPad: CGFloat = 0 public var scrollViewBottomPadding: CGFloat? public init(titles: [String]!, iconCodes: [String]! = [], color: (active: UIColor, deactive: UIColor), size: CGFloat = K.Size.Text.normal, index: Int = 0, views: [UIView], direction: Direction = .vertical) { if iconCodes.count > 0 { self.segment = IconFontSegment(titles: titles, iconCodes: iconCodes, color: color, size: size, index: index, direction: direction) } else { self.segment = TextSegment(titles: titles, size: size, index: index) } self.views = views super.init(frame: .zero) } override open func layoutUI() { super.layoutUI() layout([header.layout([segment]), scrollView.layout(views)]) } override open func bindUI() { super.bindUI() scrollView.delegate = self scrollView.isPagingEnabled = true segment.segmentTapped = { self.segmentTapped() } } @objc public func tappedAtIndex(_ index: Int) { segment.tappedAtIndex(index) } @objc public func segmentTapped() { // self.delayedJobCancelable(0.2, closure: { let index = self.segment.index.cgFloat self.scrollView.setContentOffset(CGPoint(x: index * self.scrollView.width, y: 0), animated: true) // }) } enum ScrollDirection { case vertical case horizontal } var lastContentOffset: CGPoint! = .zero var direction: ScrollDirection! public func scrollViewDidScroll(_ scrollView: UIScrollView) { direction = lastContentOffset.x == scrollView.contentOffset.x ? .vertical : .horizontal lastContentOffset = scrollView.contentOffset } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if direction == .horizontal { let index = Int(scrollView.contentOffset.x / segment.width) segment.index = index } } override open func layoutSubviews() { super.layoutSubviews() header.anchorAndFillEdge(.top, xPad: 0, yPad: 0, otherSize: segmentHeight) segment.fillSuperview(left: segmentXPad, right: segmentXPad, top: segmentYPad, bottom: segmentYPad) scrollView.alignUnder(header, matchingLeftAndRightFillingHeightWithTopPadding: 10, bottomPadding: scrollViewBottomPadding ?? tabBarHeight()) scrollView.groupHorizontally(views.map({$0 as UIView}), fillingHeightWithLeftPadding: 0, spacing: 0, topAndBottomPadding: 0, width: scrollView.width) scrollView.contentSize = CGSize(width: scrollView.width * views.count.cgFloat, height: scrollView.height) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } open class IconFontSegmentWithUnderline: IconFontSegment { override open func indicatorConstraints() { switch direction { case .horizontal: indicator.opacity(0.2) radiused() indicator.radiused() let h = group.groupMargins[index].height() indicator.align(above: group.groupMargins[index], matchingLeftAndRightWithBottomPadding: -1 * h, height: h) default: indicator.alignUnder(group.groupMargins[index], matchingCenterWithTopPadding: indicatorHeight * 5, width: labels[index].label.textWidth(), height: indicatorHeight) } } override open func layoutSubviews() { super.layoutSubviews() } } open class IconFontSegment: TextSegment { public var icons = [UILabel]() public var direction: Direction = .vertical { didSet { layoutSubviews() } } override open func didChange() { delayedJob(0.3) { (0...self.labels.count - 1).forEach { (i) in self.labels[i].label.colored(self.deactiveColor) self.icons[i].colored(self.deactiveColor) } self.icons[self.index].colored(self.activeColor) self.labels[self.index].label.colored(self.activeColor) } } public init(titles: [String]!, iconCodes: [String]!, color: (active: UIColor, deactive: UIColor), size: CGFloat = K.Size.Text.normal, index: Int = 0, direction: Direction = .vertical) { super.init(titles: titles, size: size, index: index) ({ self.activeColor = color.active })() self.deactiveColor = color.deactive for i in 0...iconCodes.count - 1 { icons.append(UILabel()) icons[i].iconFonted(iconCodes[i], iconColor: color.deactive, size: size) icons[i].adjustsFontSizeToFitWidth = true group.groups[i].layout([icons[i]]) } self.index = index ({ self.direction = direction })() } override open func bindUI() { super.bindUI() group.groups.forEach { (tab) -> () in tab.whenTapped(self, action: #selector(Segment.tabTapped(_:))) } } override open func layoutSubviews() { super.layoutSubviews() for i in 0...icons.count - 1 { switch direction { case .horizontal: let h = size let bp = h! * 0.2 let lp = (width / icons.count.cgFloat - h! - bp - labels[i].label.textWidth()) / 2 icons[i].anchorToEdge(.left, padding: lp, width: h!, height: h!) labels[i].align(toTheRightOf: icons[i], matchingCenterWithLeftPadding: bp, width: labels[i].label.textWidth(), height: labels[i].label.textHeight()) let badge = labels[i].badge badge.badgeSize = h default: let h = height - labels[i].label.textHeight() - 40 icons[i].anchorTopCenter(withTopPadding: 10, width: h, height: h) icons[i].centered().sized(h) labels[i].alignUnder(icons[i], centeredFillingWidthWithLeftAndRightPadding: 0, topPadding: 10, height: labels[i].label.textHeight()) } } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } open class IconSegment: Segment { public var icons = [UIImageView]() public init(titles: [String]!, images: [UIImage]!, size: CGFloat = K.Size.Text.normal, index: Int = 0){ super.init(titles: titles, size: size, index: index) for i in 0...images.count - 1 { icons.append(UIImageView()) icons[i].image = images[i] group.groups[i].layout([icons[i]]) } } override open func layoutSubviews() { super.layoutSubviews() for i in 0...icons.count - 1 { let s = width / group.groups.count.cgFloat * 0.7 icons[i].anchorTopCenter(withTopPadding: 10, width: s, height: s) labels[i].alignUnder(icons[i], centeredFillingWidthWithLeftAndRightPadding: 0, topPadding: 0, height: labels[i].label.textHeight()) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } open class TextSegment: Segment { public var indicatorHeight: CGFloat = K.Size.Segment.underline { didSet { indicatorConstraints() } } override open func indicatorConstraints() { switch style { case .cover: let target = group.groupMargins[index] indicator.backgroundColored(K.Color.navigator.lighter().withAlphaComponent(0.25)) indicator.alignUnder(target, matchingCenterWithTopPadding: -1 * target.height() + 1, width: target.width() - 2, height: target.height() - 2) default: indicator.alignUnder(group.groupMargins[index], matchingLeftAndRightWithTopPadding: -1 * indicatorHeight + 1, height: indicatorHeight) } } override open func layoutSubviews() { super.layoutSubviews() labels.forEach { (tab) -> () in switch style { case .cover: tab.fillSuperview() default: // tab.fillSuperview() tab.anchorInCenter(withWidth: width / titles.count.cgFloat , height: size) } } } } open class Segment: DefaultView { public var labels: [BadgeLabel]! = [] public var indicator = UIView() public var indicatorColor = K.Color.indicator { didSet { indicator.backgroundColored(indicatorColor) } } public var titles: [String]! = [] public var size: CGFloat! { didSet { labels.forEach({$0.label.sized(size)}) }} public var group: GroupsView! public var changed: () -> () = {} public var segmentTapped: () -> () = {} public var style: IndicatorStyle = .underline { didSet { } } public var textColorFollowedByIndicator = false { didSet { indicatorConstraints() } } @objc public func tappedAtIndex(_ index: Int) { self.index = index segmentTapped() changed() } public enum IndicatorStyle { case underline case cover } public var index: Int = 0 { didSet { reConstraints() didChange() } } public var activeColor: UIColor! = K.Color.indicator { didSet { indicator.backgroundColor = activeColor } } public var deactiveColor: UIColor! public func didChange() { } public init(iconCodes: [String]!, titles: [String]!, size: CGFloat = K.Size.Text.normal, index: Int = 0) { self.titles = titles self.size = size self.index = index group = GroupsView(count: titles.count, padding: 1, group: .horizontal, margin: .zero) for i in 0...titles.count - 1 { let label = BadgeLabel(text: titles[i], size: size * 0.8, value: "") label.label.texted(iconCodes[i], text: titles[i], size: size) group.groups[i].layout([label]) labels.append(label) } super.init(frame: .zero) } public init(titles: [String]!, size: CGFloat = K.Size.Text.normal, index: Int = 0){ self.titles = titles self.size = size self.index = index group = GroupsView(count: titles.count, padding: 1, group: .horizontal, margin: .zero) for i in 0...titles.count - 1 { let label = BadgeLabel(text: titles[i], size: size, value: "") group.groups[i].layout([label]) labels.append(label) } super.init(frame: .zero) } override open func layoutUI() { super.layoutUI() layout([group.layout([indicator])]) } override open func styleUI() { super.styleUI() backgroundColor = UIColor.white indicator.backgroundColored(indicatorColor) } override open func bindUI() { super.bindUI() group.groups.forEach { (tab) -> () in tab.whenTapped(self, action: #selector(Segment.tabTapped(_:))) } } @objc public func tabTapped(_ sender: UITapGestureRecognizer) { index = group.groups.index(of: sender.view!)! segmentTapped() changed() reConstraints() } public func reConstraints() { UIView.animate(withDuration: 0.5) { () -> Void in self.indicatorConstraints() } } override open func layoutSubviews() { super.layoutSubviews() group.fillSuperview(left: 0, right: 0, top: 0, bottom: 0) indicatorConstraints() } public func indicatorConstraints() { if textColorFollowedByIndicator { labels.forEach({ (label) in label.label.colored(deactiveColor) }) labels[index].label.colored(indicatorColor) } } override init(frame: CGRect) { super.init(frame: frame)} required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
7fc69ac04c9ccae63b16c82b1b2650e1
31.270115
209
0.672039
3.983682
false
false
false
false
mrlegowatch/RolePlayingCore
RolePlayingCore/RolePlayingCore/Dice/CompoundDice.swift
1
2263
// // CompoundDice.swift // RolePlayingCore // // Created by Brian Arnold on 3/22/17. // Copyright © 2017 Brian Arnold. All rights reserved. // import Foundation /// General-purpose composition of dice rolls. /// /// The two primary use cases for this type are: /// - combining two rolls, e.g., "2d4+d6", /// - using a modifier, e.g., "d12+2". public struct CompoundDice: Dice { public let lhs: Dice public let rhs: Dice public let mathOperator: String /// Creates a dice that conforms to the syntax "<times>d<size><mathOperator><modifier>". /// All parameters except die are optional; times defaults to 1, modifier defaults to 0, /// and math operator defaults to "+". public init(_ die: Die, times: Int = 1, modifier: Int = 0, mathOperator: String = "+") { let dice = SimpleDice(die, times: times) let modifier = DiceModifier(modifier) self.init(lhs: dice, rhs: modifier, mathOperator: mathOperator) } /// Creates a dice from two dice instances with a math operator. public init(lhs: Dice, rhs: Dice, mathOperator: String) { self.lhs = lhs self.rhs = rhs self.mathOperator = mathOperator } /// Function signature for a math operator or function. internal typealias MathOperator = (Int, Int) -> Int /// Mapping of strings to function signatures. internal static let mathOperators: [String: MathOperator] = ["+": (+), "-": (-), "x": (*), "*": (*), "/": (/)] /// Rolls the specified number of times, optionally adding or multiplying a modifier, /// and returning the result. public func roll() -> DiceRoll { let lhsRoll = lhs.roll() let rhsRoll = rhs.roll() let result = CompoundDice.mathOperators[mathOperator]!(lhsRoll.result, rhsRoll.result) let description = "\(lhsRoll.description) \(mathOperator) \(rhsRoll.description)" return DiceRoll(result, description) } /// Returns the number of sides of the left hand dice. public var sides: Int { return lhs.sides } /// Returns a description of the left and right hand sides with the math operator. public var description: String { return "\(lhs)\(mathOperator)\(rhs)" } }
mit
d5643386b35c2b55964b2ba59a48ab97
34.904762
114
0.637489
4.135283
false
false
false
false
edmw/Volumio_ios
Volumio/TabBarViewController.swift
1
1535
// // TabBarViewController.swift // Volumio // // Created by Federico Sintucci on 01/10/16. // Copyright © 2016 Federico Sintucci. All rights reserved. // import UIKit class TabBarViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() localize() self.tabBar.tintColor = UIColor.black } } // MARK: - Localization extension TabBarViewController { fileprivate func localize() { if let items = self.tabBar.items { if let item = items[safe: 0] { item.title = NSLocalizedString("TAB_PLAYBACK", comment: "[trigger](short) show playback view" ) item.accessibilityLabel = "Playback" } if let item = items[safe: 1] { item.title = NSLocalizedString("TAB_QUEUE", comment: "[trigger](short) show queue view" ) item.accessibilityLabel = "Queue" } if let item = items[safe: 2] { item.title = NSLocalizedString("TAB_BROWSE", comment: "[trigger](short) show browse view" ) item.accessibilityLabel = "Browse" } if let item = items[safe: 3] { item.title = NSLocalizedString("TAB_SETTINGS", comment: "[trigger](short) show settings view" ) item.accessibilityLabel = "Settings" } } } }
gpl-3.0
fe388bc0c0b35abaa4921fead382023b
26.890909
66
0.524772
4.823899
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab5MyPage/SLV_916_MyPagePushController.swift
1
8441
// // SLV_916_MyPagePushController.swift // selluv-ios // // Created by 김택수 on 2017. 3. 5.. // Copyright © 2017년 BitBoy Labs. All rights reserved. // import UIKit class SLV_916_MyPagePushController: SLVBaseStatusShowController { var titleList:[String]? var tableList:[[Dictionary<String, AnyObject>]]? var dataList:[SLVRespAlarm]? @IBOutlet weak var tabSeg: UISegmentedControl!; @IBOutlet weak var tableView: UITableView! // var tradeUseCell: SLV916MyPagePushCell! // var newsUseCell: SLV916MyPagePushCell! // var replyUseCell: SLV916MyPagePushCell! //MARK: //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() self.settingUI() self.loadData() } //MARK: //MARK: Private func settingUI() { tabController.hideFab() tabController.animationTabBarHidden(true) self.title = "알림 설정" self.navigationItem.hidesBackButton = true let back = UIButton() back.setImage(UIImage(named:"ic-back-arrow.png"), for: .normal) back.frame = CGRect(x: 17, y: 23, width: 12+32, height: 20) back.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 26) back.addTarget(self, action: #selector(SLV_916_MyPagePushController.touchBackButton(_:)), for: .touchUpInside) let item = UIBarButtonItem(customView: back) self.navigationItem.leftBarButtonItem = item self.tableView.register(UINib(nibName: "SLV916MyPagePushCell", bundle: nil), forCellReuseIdentifier: "myPagePushCell") } func loadData() { self.titleList = self.getTableTitle() self.tableList = self.getTableList() MyInfoDataModel.shared.myAlarms { (success, respAlarm) in self.dataList = respAlarm self.tableView.reloadData() } } func getTableTitle() ->[String] { let title = ["거래 알림 사용", "소식 알림 사용", "댓글 알림 사용"] return title } func getTableList() -> [[Dictionary<String, AnyObject>]] { let list = [ [ ["title":"내 아이템이 판매되었을 때(카카오톡)", "kind":"alarm_1"], ["title":"운송장이 업데이트 되었을 때 (카카오톡)", "kind":"alarm_2"], ["title":"구매자가 구매완료 했을 때", "kind":"alarm_3"], ["title":"판매자가 배송신청 했을 때", "kind":"alarm_4"], ["title":"거래 상대가 구매후기나 판매후기를 남겼을 때", "kind":"alarm_6"], ["title":"판매자가 네고를 승인 하였을때", "kind":"alarm_7"], ["title":"네고 제안이 거절 되었을때", "kind":"alarm_8"], ["title":"정품 서비스 판정 알림", "kind":"alarm_9"], ["title":"물품 판매 후 셀럽 머니가 적립되었을 때", "kind":"alarm_10"] ], [ ["title":"내가 초대한 친구에 의해 리워드를 얻었을 때", "kind":"alarm_11"], ["title":"신고한 항목에 대한 리워드를 얻었을 때", "kind":"alarm_12"], ["title":"내 아이템이 포토샵 되었을 때", "kind":"alarm_13"], ["title":"누군가 나를 팔로우 할 때", "kind":"alarm_14"], ["title":"누군가 나의 아이템을 좋아요 할 때", "kind":"alarm_15"], ["title":"내 아이템이 잇템 되었을 때", "kind":"alarm_16"], ["title":"좋아요 아이템이 가격 인하 되었을 때", "kind":"alarm_17"], ["title":"팔로잉 유저가 새로운 상품을 등록하였을 때", "kind":"alarm_18"], ["title":"팔로잉 유저가 새로운 스타일을 등록하였을 때", "kind":"alarm_19"], ["title":"팔로잉 유저가 잇템 하였을 때", "kind":"alarm_20"], ["title":"팔로잉 브랜드 새로운 상품이 등록되었을 때", "kind":"alarm_21"], ["title":"찾고 있는 제품이 업데이트(등록:?) 되었을 때", "kind":"alarm_22"], ["title":"셀럽 이벤트가 새롭게 등록되었을 때", "kind":"alarm_23"], ["title":"셀럽 공지 및 광고", "kind":"alarm_24"] ], [ ["title":"내 아이템에 댓글이 달렸을 때", "kind":"alarm_25"], ["title":"나의 댓글에 답글이 달렸을 때", "kind":"alarm_26"], ] ]; return list as [[Dictionary<String, AnyObject>]]; } func switchValueChanged(_ key: String, _ button: UISwitch) { } func updateAlarm(kind:String, onOff:Bool) { MyInfoDataModel.shared.updateAlarms(kind: kind, yes: onOff) { (success) in print("?") } } //MARK: //MARK: IBAction func touchBackButton(_ sender:UIButton) { self.navigationController?.popViewController() } @IBAction func touchTabSegmentedController(_ button: UIButton) { self.tableView.reloadData() } //MARK: //MARK: Override } extension SLV_916_MyPagePushController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return 52+15 } else { return 52 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) cell?.setSelected(false, animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let tableList = self.tableList { let tabIndex = self.tabSeg.selectedSegmentIndex; let list = tableList[tabIndex] return list.count } else { return 0 } } func isOnForAllSwitch(isOn: Bool) { if let list = self.tableList { let tabIndex = self.tabSeg.selectedSegmentIndex; let dataArray = list[tabIndex] for dic in dataArray { let kind = dic["kind"] as! String? for data in self.dataList! { if data.kind == kind { data.isAcceptance = isOn break } } } } self.tableView.reloadData() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myPagePushCell", for: indexPath) as! SLV916MyPagePushCell if indexPath.row == 0 { cell.key = "" if let title = self.titleList { let tabIndex = self.tabSeg.selectedSegmentIndex; cell.titleLabel.text = title[tabIndex] cell.setupSwitchBlock(block: { (key, button) in self.isOnForAllSwitch(isOn: button.isOn) }) } } else { if let list = self.tableList { let tabIndex = self.tabSeg.selectedSegmentIndex; let data = list[tabIndex][indexPath.row - 1] let kind = data["kind"] as! String? cell.key = kind cell.titleLabel.text = data["title"] as! String? cell.switchButton.isOn = self.isAcceptance(key: kind!) cell.setupSwitchBlock { (key, button) in self.updateAlarm(kind: key, onOff: button.isOn) } } } return cell } func isAcceptance(key:String) -> Bool { if self.dataList != nil { for data in self.dataList! { if data.kind == key { return data.isAcceptance! } } } return false } }
mit
9b990de6935efb034e52a7f2c510d8b5
32.021459
123
0.511048
3.767875
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/BaseExploreFeedSettingsViewController.swift
1
15176
protocol ExploreFeedSettingsItem { var title: String { get } var subtitle: String? { get } var disclosureType: WMFSettingsMenuItemDisclosureType { get } var disclosureText: String? { get } var iconName: String? { get } var iconColor: UIColor? { get } var iconBackgroundColor: UIColor? { get } var controlTag: Int { get } var isOn: Bool { get } func updateSubtitle(for displayType: ExploreFeedSettingsDisplayType) func updateDisclosureText(for displayType: ExploreFeedSettingsDisplayType) func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) } extension ExploreFeedSettingsItem { var subtitle: String? { return nil } var disclosureType: WMFSettingsMenuItemDisclosureType { return .switch } var disclosureText: String? { return nil } var iconName: String? { return nil } var iconColor: UIColor? { return nil } var iconBackgroundColor: UIColor? { return nil } func updateSubtitle(for displayType: ExploreFeedSettingsDisplayType) { } func updateDisclosureText(for displayType: ExploreFeedSettingsDisplayType) { } func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) { } } enum ExploreFeedSettingsMainType: Equatable { case entireFeed case singleFeedCard(WMFContentGroupKind) } private extension WMFContentGroupKind { var switchTitle: String { switch self { case .news: return WMFLocalizedString("explore-feed-preferences-show-news-title", value: "Show In the news card", comment: "Text for the setting that allows users to toggle the visibility of the In the news card") case .featuredArticle: return WMFLocalizedString("explore-feed-preferences-show-featured-article-title", value: "Show Featured article card", comment: "Text for the setting that allows users to toggle the visibility of the Featured article card") case .topRead: return WMFLocalizedString("explore-feed-preferences-show-top-read-title", value: "Show Top read card", comment: "Text for the setting that allows users to toggle the visibility of the Top read card") case .onThisDay: return WMFLocalizedString("explore-feed-preferences-show-on-this-day-title", value: "Show On this day card", comment: "Text for the setting that allows users to toggle the visibility of the On this day card") case .pictureOfTheDay: return WMFLocalizedString("explore-feed-preferences-show-picture-of-the-day-title", value: "Show Picture of the day card", comment: "Text for the setting that allows users to toggle the visibility of the Picture of the day card") case .locationPlaceholder: fallthrough case .location: return WMFLocalizedString("explore-feed-preferences-show-places-title", value: "Show Places card", comment: "Text for the setting that allows users to toggle the visibility of the Places card") case .random: return WMFLocalizedString("explore-feed-preferences-show-randomizer-title", value: "Show Randomizer card", comment: "Text for the setting that allows users to toggle the visibility of the Randomizer card") case .continueReading: return WMFLocalizedString("explore-feed-preferences-show-continue-reading-title", value: "Show Continue reading card", comment: "Text for the setting that allows users to toggle the visibility of the Continue reading card") case .relatedPages: return WMFLocalizedString("explore-feed-preferences-show-related-pages-title", value: "Show Because you read card", comment: "Text for the setting that allows users to toggle the visibility of the Because you read card") default: assertionFailure("\(self) is not customizable") return "" } } } class ExploreFeedSettingsPrimary: ExploreFeedSettingsItem { let title: String let controlTag: Int = -1 var isOn: Bool = false let type: ExploreFeedSettingsMainType init(for type: ExploreFeedSettingsMainType) { self.type = type if case let .singleFeedCard(contentGroupKind) = type { title = contentGroupKind.switchTitle isOn = contentGroupKind.isInFeed } else { title = WMFLocalizedString("explore-feed-preferences-explore-tab", value: "Explore tab", comment: "Text for the setting that allows users to toggle whether the Explore tab is enabled or not") isOn = UserDefaults.standard.defaultTabType == .explore } } func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) { if case let .singleFeedCard(contentGroupKind) = type { isOn = contentGroupKind.isInFeed } else { isOn = UserDefaults.standard.defaultTabType == .explore } } } struct ExploreFeedSettingsSection { let headerTitle: String? let footerTitle: String let items: [ExploreFeedSettingsItem] } class ExploreFeedSettingsLanguage: ExploreFeedSettingsItem { let title: String let subtitle: String? let controlTag: Int var isOn: Bool = false let siteURL: URL let languageLink: MWKLanguageLink init(_ languageLink: MWKLanguageLink, controlTag: Int, displayType: ExploreFeedSettingsDisplayType) { self.languageLink = languageLink title = languageLink.localizedName subtitle = languageLink.contentLanguageCode.uppercased() self.controlTag = controlTag siteURL = languageLink.siteURL updateIsOn(for: displayType) } func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) { switch displayType { case .singleLanguage: return case .multipleLanguages: isOn = languageLink.isInFeed case .detail(let contentGroupKind): isOn = languageLink.isInFeed(for: contentGroupKind) } } } class ExploreFeedSettingsGlobalCards: ExploreFeedSettingsItem { let disclosureType: WMFSettingsMenuItemDisclosureType = .switch let title: String = WMFLocalizedString("explore-feed-preferences-global-cards-title", value: "Global cards", comment: "Title for the setting that allows users to toggle non-language specific feed cards") let subtitle: String? = WMFLocalizedString("explore-feed-preferences-global-cards-description", value: "Non-language specific cards", comment: "Description of global feed cards") let controlTag: Int = -2 var isOn: Bool = MWKDataStore.shared().feedContentController.areGlobalContentGroupKindsInFeed func updateIsOn(for displayType: ExploreFeedSettingsDisplayType) { guard displayType == .singleLanguage || displayType == .multipleLanguages else { return } isOn = MWKDataStore.shared().feedContentController.areGlobalContentGroupKindsInFeed } } enum ExploreFeedSettingsDisplayType: Equatable { case singleLanguage case multipleLanguages case detail(WMFContentGroupKind) } class BaseExploreFeedSettingsViewController: SubSettingsViewController { @objc var dataStore: MWKDataStore? open var displayType: ExploreFeedSettingsDisplayType = .singleLanguage var activeSwitch: UISwitch? var updateFeedBeforeViewDisappears: Bool = false override func viewDidLoad() { super.viewDidLoad() tableView.register(WMFSettingsTableViewCell.wmf_classNib(), forCellReuseIdentifier: WMFSettingsTableViewCell.identifier) tableView.register(WMFTableHeaderFooterLabelView.wmf_classNib(), forHeaderFooterViewReuseIdentifier: WMFTableHeaderFooterLabelView.identifier) tableView.sectionHeaderHeight = UITableView.automaticDimension tableView.estimatedSectionHeaderHeight = 44 tableView.sectionFooterHeight = UITableView.automaticDimension tableView.estimatedSectionFooterHeight = 44 NotificationCenter.default.addObserver(self, selector: #selector(exploreFeedPreferencesDidSave(_:)), name: NSNotification.Name.WMFExploreFeedPreferencesDidSave, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(newExploreFeedPreferencesWereRejected(_:)), name: NSNotification.Name.WMFNewExploreFeedPreferencesWereRejected, object: nil) } var preferredLanguages: [MWKLanguageLink] { return MWKDataStore.shared().languageLinkController.preferredLanguages } lazy var languages: [ExploreFeedSettingsLanguage] = { let languages = preferredLanguages.enumerated().compactMap { (index, languageLink) in ExploreFeedSettingsLanguage(languageLink, controlTag: index, displayType: self.displayType) } return languages }() var feedContentController: WMFExploreFeedContentController? { return dataStore?.feedContentController } deinit { NotificationCenter.default.removeObserver(self) } open var sections: [ExploreFeedSettingsSection] { assertionFailure("Subclassers should override") return [] } lazy var itemsGroupedByIndexPaths: [IndexPath: ExploreFeedSettingsItem] = { var dictionary = [IndexPath: ExploreFeedSettingsItem]() for (sectionIndex, section) in sections.enumerated() { for (itemIndex, item) in section.items.enumerated() { dictionary[IndexPath(row: itemIndex, section: sectionIndex)] = item } } return dictionary }() func getItem(at indexPath: IndexPath) -> ExploreFeedSettingsItem { let items = getSection(at: indexPath.section).items assert(items.indices.contains(indexPath.row), "Item at indexPath \(indexPath) doesn't exist") return items[indexPath.row] } func getSection(at index: Int) -> ExploreFeedSettingsSection { assert(sections.indices.contains(index), "Section at index \(index) doesn't exist") return sections[index] } // MARK: - Notifications private func reload() { for (indexPath, item) in itemsGroupedByIndexPaths { item.updateIsOn(for: displayType) item.updateDisclosureText(for: displayType) item.updateSubtitle(for: displayType) guard let cell = tableView.cellForRow(at: indexPath) as? WMFSettingsTableViewCell else { continue } cell.disclosureSwitch.setOn(item.isOn, animated: true) cell.disclosureText = item.disclosureText cell.subtitle = item.subtitle } } @objc private func exploreFeedPreferencesDidSave(_ notification: Notification) { updateFeedBeforeViewDisappears = true DispatchQueue.main.async { self.reload() } } @objc private func newExploreFeedPreferencesWereRejected(_ notification: Notification) { guard let activeSwitch = activeSwitch else { return } activeSwitch.setOn(!activeSwitch.isOn, animated: true) } // MARK: - Themeable override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.baseBackground tableView.backgroundColor = theme.colors.baseBackground if viewIfLoaded?.window != nil { tableView.reloadData() } } } // MARK: - UITableViewDataSource extension BaseExploreFeedSettingsViewController { override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let section = getSection(at: section) return section.items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: WMFSettingsTableViewCell.identifier, for: indexPath) as? WMFSettingsTableViewCell else { return UITableViewCell() } let item = getItem(at: indexPath) configureCell(cell, item: item) return cell } private func configureCell(_ cell: WMFSettingsTableViewCell, item: ExploreFeedSettingsItem) { cell.configure(item.disclosureType, disclosureText: item.disclosureText, title: item.title, subtitle: item.subtitle, iconName: item.iconName, isSwitchOn: item.isOn, iconColor: item.iconColor, iconBackgroundColor: item.iconBackgroundColor, controlTag: item.controlTag, theme: theme) cell.delegate = self } } // MARK: - UITableViewDelegate extension BaseExploreFeedSettingsViewController { @objc func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UITableView.automaticDimension } @objc func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let text = getSection(at: section).headerTitle return WMFTableHeaderFooterLabelView.headerFooterViewForTableView(tableView, text: text, theme: theme) } @objc func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { let text = getSection(at: section).footerTitle return WMFTableHeaderFooterLabelView.headerFooterViewForTableView(tableView, text: text, type: .footer, setShortTextAsProse: true, theme: theme) } @objc func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let text = getSection(at: section).footerTitle guard !text.isEmpty else { return 0 } return UITableView.automaticDimension } } // MARK: - WMFSettingsTableViewCellDelegate extension BaseExploreFeedSettingsViewController: WMFSettingsTableViewCellDelegate { open func settingsTableViewCell(_ settingsTableViewCell: WMFSettingsTableViewCell!, didToggleDisclosureSwitch sender: UISwitch!) { assertionFailure("Subclassers should override") } } // MARK: - MWKLanguageLink Convenience Methods fileprivate extension MWKLanguageLink { private var feedContentController: WMFExploreFeedContentController { MWKDataStore.shared().feedContentController } /** Flag indicating whether there are any visible customizable feed content sources in this language. Returns true if there is at least one content source in this language visible in the feed. Returns false if there are no content sources in this language visible in the feed. */ var isInFeed: Bool { feedContentController.anyContentGroupsVisibleInTheFeed(forSiteURL: siteURL) } /** Flag indicating whether the content group of given kind is visible in the feed in this language. Returns YES if the content group of given kind is visible in the feed in this language. Returns NO if the content group of given kind is not visible in the feed in this language. */ func isInFeed(for contentGroupKind: WMFContentGroupKind) -> Bool { feedContentController.contentLanguageCodes(for: contentGroupKind).contains(contentLanguageCode) } }
mit
b02742b76006be8d5c96ceb554c4a801
42.36
289
0.712638
5.108044
false
false
false
false
xiaoxionglaoshi/DNSwiftProject
DNSwiftProject/DNSwiftProject/Classes/Main/DNMine/Controller/DNMineViewController.swift
1
2764
// // DNMineViewController.swift // DNSwiftProject // // Created by mainone on 16/11/25. // Copyright © 2016年 wjn. All rights reserved. // import UIKit private let cellIdentifier = "cellID" class DNMineViewController: DNBaseViewController { override func viewDidLoad() { super.viewDidLoad() self.tableView.register(DNMineCell.self, forCellReuseIdentifier: cellIdentifier) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private lazy var tableView: UITableView = { let tableV = UITableView(frame: self.view.frame, style: .grouped) tableV.sectionHeaderHeight = 10 tableV.sectionFooterHeight = 10 tableV.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 20)) tableV.delegate = self tableV.dataSource = self self.view.addSubview(tableV) return tableV }() lazy var dataArray: Array<Array<Dictionary<String, String>>> = { let dataArr = [ [ ["image" : "tx", "title" : "小熊老师"] ], [ ["image" : "MoreMyAlbum", "title" : "相册"], ["image" : "MoreMyFavorites", "title" : "收藏"], ["image" : "MoreMyBankCard", "title" : "钱包"], ["image" : "MyCardPackageIcon", "title" : "卡包"] ], [ ["image" : "MoreExpressionShops", "title" : "表情"] ], [ ["image" : "MoreSetting", "title" : "设置"] ] ] return dataArr }() } extension DNMineViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } extension DNMineViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return self.dataArray.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArray[section].count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! DNMineCell cell.cellModel = self.dataArray[indexPath.section][indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return indexPath.section == 0 ? 80.0 : 44.0 } }
apache-2.0
6d708b22635dc96a40a6cadc6fc6d2d5
28.663043
111
0.590693
4.609797
false
false
false
false
bananafish911/SmartReceiptsiOS
SmartReceipts/Constants/Constants.swift
1
1208
// // Constants.swift // SmartReceipts // // Created by Jaanus Siim on 16/05/16. // Copyright © 2016 Will Baumann. All rights reserved. // import Foundation import QuartzCore func onMainThread(_ closure: @escaping () -> ()) { DispatchQueue.main.async(execute: closure) } func timeMeasured(_ desc: String = "", closure: () -> ()) { let start = CACurrentMediaTime() closure() Logger.debug(String(format: "%@ - time: %f", desc, CACurrentMediaTime() - start)) } func delayedExecution(_ afterSecons: TimeInterval, closure: @escaping () -> ()) { let delayTime = DispatchTime.now() + Double(Int64(afterSecons * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime, execute: closure) } func LocalizedString(_ key: String, comment: String = "") -> String { return NSLocalizedString(key, comment: comment) } func MainStoryboard() -> UIStoryboard { return UI_USER_INTERFACE_IDIOM() == .pad ? UIStoryboard(name: "MainStoryboard_iPad", bundle: nil) : UIStoryboard(name: "MainStoryboard_iPhone", bundle: nil) } func executeFor(iPhone: ()->(), iPad: ()->()) { UI_USER_INTERFACE_IDIOM() == .pad ? iPad() : iPhone() }
agpl-3.0
77af4b12d5379b85562e757db9a6aedd
29.948718
113
0.665286
3.807571
false
false
false
false
tensorflow/swift-models
Examples/LeNet-MNIST/main.swift
1
1963
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Datasets import TensorFlow import TrainingLoop let epochCount = 12 let batchSize = 128 // Until https://github.com/tensorflow/swift-apis/issues/993 is fixed, default to the eager-mode // device on macOS instead of X10. #if os(macOS) let device = Device.defaultTFEager #else let device = Device.defaultXLA #endif let dataset = MNIST(batchSize: batchSize, on: device) // The LeNet-5 model, equivalent to `LeNet` in `ImageClassificationModels`. var classifier = Sequential { Conv2D<Float>(filterShape: (5, 5, 1, 6), padding: .same, activation: relu) AvgPool2D<Float>(poolSize: (2, 2), strides: (2, 2)) Conv2D<Float>(filterShape: (5, 5, 6, 16), activation: relu) AvgPool2D<Float>(poolSize: (2, 2), strides: (2, 2)) Flatten<Float>() Dense<Float>(inputSize: 400, outputSize: 120, activation: relu) Dense<Float>(inputSize: 120, outputSize: 84, activation: relu) Dense<Float>(inputSize: 84, outputSize: 10) } var optimizer = SGD(for: classifier, learningRate: 0.1) var trainingLoop = TrainingLoop( training: dataset.training, validation: dataset.validation, optimizer: optimizer, lossFunction: softmaxCrossEntropy, metrics: [.accuracy], callbacks: [try! CSVLogger().log]) trainingLoop.statisticsRecorder!.setReportTrigger(.endOfEpoch) try! trainingLoop.fit(&classifier, epochs: epochCount, on: device)
apache-2.0
adb26d96e12a91651b44850d068cc860
34.053571
96
0.740194
3.615101
false
false
false
false
ChristianKienle/highway
Sources/Task/Finding and Executing/PathEnvironmentParser.swift
1
1442
import Foundation import ZFile import POSIX import Url /// Parser that extracts urls from a String-Array of paths. /// Usually used to parse the contents of the PATH-environment /// variable. Any component (PATH=comp1:comp2:...) equal to "." /// is subsituted by $cwd. Furthermore: Any component which only /// contains a "." is used as an input to Absolute.init:. (which /// standardizes the path). public struct PathEnvironmentParser { // MARK: - Convenience public static func local() throws -> PathEnvironmentParser { let env = ProcessInfo.processInfo.environment let path = env["PATH"] ?? "" return try self.init(value: path, currentDirectoryUrl: FileSystem().currentFolder) } // MARK: - Init public init(value: String, currentDirectoryUrl: FolderProtocol) throws { let paths = value.components(separatedBy: ":") self.urls = try paths.compactMap { path in guard path != "" else { return nil } guard path != "." else { return currentDirectoryUrl } let isRelative = path.hasPrefix("/") == false guard isRelative else { return try Folder(path: path) } return try currentDirectoryUrl.subfolder(atPath: path) } self.currentDirectoryUrl = currentDirectoryUrl } // MARK: - Properties public let currentDirectoryUrl: FolderProtocol public var urls: [FolderProtocol] }
mit
38f0202e0b246cee7fbd86f24e2dbd6f
36.947368
90
0.658114
4.806667
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01185-swift-parser-parsetypeidentifier.swift
1
1315
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func b<c { enum b { func b var _ = b func k<q { enum k { } } class x { } struct j<u> : r { func j(j: j.n) { } } enum q<v> { let k: v } protocol y { } struct D : y { func y<v k r { } class y<D> { } } func l<c>(m: (l, c) -> c) -> (l, c) -> c { f { i }, k) class l { class func m { b let k: String = { }() struct q<q : n, p: n where p.q == q.q> { } o q: n = { m, i j l { k m p<i) { } } } }lass func c() } s} class a<f : b, : b where f.d == g> { } struct j<l : o> { } func a<l>() -> [j<l>] { } func f<l>() -> (l, l -> l) -> l { l j l.n = { } { l) { n } } protocol f { } class l: f{ class func n {} func a<i>() { b b { } } class a<f : b, l : b m f.l == l> { } protocol b { } struct j<n : b> : b { } enum e<b> : d { func c<b>() -> b { } } protocol d { } enum A : String { } if c == .b { } struct c<f : h> { var b: [c<f>] { g []e f() { } } protocol c : b { func b class j { func y((Any, j))(v: (Any, AnyObject)) { }
apache-2.0
c5656fe63a2502a38145e4753fdcbf97
12.842105
79
0.530798
2.240204
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/View Collection/Default View/QSearchListDefaultCell.swift
1
1864
// // QSearchListDefaultCell.swift // Example // // Created by Ahmad Athaullah on 9/20/17. // Copyright © 2017 Ahmad Athaullah. All rights reserved. // import UIKit class QSearchListDefaultCell: QSearchListCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descriptionView: UITextView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func setupUI() { self.titleLabel.text = comment!.roomName } override func searchTextChanged() { let boldAttr = [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 14.0)] let normalAttr = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14.0)] let message = self.comment!.text let newLabelText = NSMutableAttributedString(string: message) let allRange = (message as NSString).range(of: message) newLabelText.setAttributes(normalAttr, range: allRange) if let matchRange: Range = message.lowercased().range(of: searchText.lowercased()) { let matchRangeStart: Int = message.distance(from: message.startIndex, to: matchRange.lowerBound) let matchRangeEnd: Int = message.distance(from: message.startIndex, to: matchRange.upperBound) let matchRangeLength: Int = matchRangeEnd - matchRangeStart newLabelText.setAttributes(boldAttr, range: NSMakeRange(matchRangeStart, matchRangeLength)) } self.descriptionView.attributedText = newLabelText } }
mit
c8b5a5085b113b3e7a328b4cb6de4a96
34.150943
108
0.661299
5.035135
false
false
false
false
morestudio/MSAPIService
MSAPIService/MSAConfiguration.swift
1
683
// // MSAPIConfiguration.swift // MSAPIService // // Created by Tum on 11/29/16. // Copyright © 2016 Morestudio. All rights reserved. // import UIKit public struct MSAConfiguration { public static var `default` = MSAConfiguration() public var baseURL: String = "" public var versionEnpoint: String = "/api/v1" public var errorDomain = "error" } extension MSAConfiguration { public var baseAPIString: String { assert(!baseURL.isEmpty) return baseURL + versionEnpoint } public var baseAPIURL: URL? { guard let url = URL(string: baseAPIString) else { assert(false); return nil } return url } }
mit
659ac019db759a628e1599df7daee60c
21
85
0.646628
3.942197
false
true
false
false
swixbase/multithreading
Sources/Multithreading/PSXWorkerThread.swift
1
1613
/// Copyright 2017 Sergei Egorov /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. import Foundation public class PSXWorkerThread: PSXThread { // MARK: Properties, initialization, deinitialization /// Thread pool. internal let pool: PSXThreadPool /// Friendly id public let id: Int // TODO: - NEW internal var lastActivity: Date /// Initialization. /// /// - Parameters: /// - pool: A thread pool. /// - id: A friendly id of created thread. /// internal init(pool: PSXThreadPool, id: Int) { self.id = id self.pool = pool self.lastActivity = Date() super.init() } } internal extension Array where Element: PSXWorkerThread { internal func withMinJobs() -> Element { let min = self.min { $0.privateQueue.jobsCount < $1.privateQueue.jobsCount } return min! } internal func lastActive() -> Element { let max = self.max { $0.lastActivity.timeIntervalSinceNow < $1.lastActivity.timeIntervalSinceNow } return max! } }
apache-2.0
ea50c1301353c127933860787d235da2
28.327273
106
0.647241
4.278515
false
false
false
false
WestlakeAPC/game-off-2016
external/Fiber2D/Fiber2D/PhysicsWorld+Internal.swift
1
3421
// // PhysicsWorld+Internal.swift // Fiber2D // // Created by Andrey Volodin on 18.09.16. // Copyright © 2016 s1ddok. All rights reserved. // internal func collisionBeginCallbackFunc(_ arb: UnsafeMutablePointer<cpArbiter>?, _ space: UnsafeMutablePointer<cpSpace>?, _ world: cpDataPointer?) -> cpBool { var a: UnsafeMutablePointer<cpShape>? = nil var b: UnsafeMutablePointer<cpShape>? = nil cpArbiterGetShapes(arb, &a, &b) let shapeA = Unmanaged<PhysicsShape>.fromOpaque(cpShapeGetUserData(a)).takeUnretainedValue() let shapeB = Unmanaged<PhysicsShape>.fromOpaque(cpShapeGetUserData(b)).takeUnretainedValue() let contactPointer = UnsafeMutablePointer<PhysicsContact>.allocate(capacity: 1) let contact = PhysicsContact(shapeA: shapeA, shapeB: shapeB, arb: arb) contactPointer.initialize(to: contact) cpArbiterSetUserData(arb, contactPointer) let world = Unmanaged<PhysicsWorld>.fromOpaque(world!).takeUnretainedValue() world.contactDelegate?.didBegin(contact: contact) return 1 } internal func collisionPreSolveCallbackFunc(_ arb: UnsafeMutablePointer<cpArbiter>?, _ space: UnsafeMutablePointer<cpSpace>?, _ world: cpDataPointer?) -> cpBool { return 1 } internal func collisionPostSolveCallbackFunc(_ arb: UnsafeMutablePointer<cpArbiter>?, _ space: UnsafeMutablePointer<cpSpace>?, _ world: cpDataPointer?) -> Void { } internal func collisionSeparateCallbackFunc(_ arb: UnsafeMutablePointer<cpArbiter>?, _ space: UnsafeMutablePointer<cpSpace>?, _ world: cpDataPointer?) -> Void { let contactPointer = cpArbiterGetUserData(arb).assumingMemoryBound(to: PhysicsContact.self) let contact = contactPointer.pointee let world = Unmanaged<PhysicsWorld>.fromOpaque(world!).takeUnretainedValue() world.contactDelegate?.didEnd(contact: contact) free(contactPointer) } internal extension PhysicsWorld { internal func updateDelaysIfNeeded() { if !delayAddBodies.isEmpty || !delayRemoveBodies.isEmpty { updateBodies() } if !delayAddJoints.isEmpty || !delayRemoveJoints.isEmpty { updateJoints() } } internal func update(dt: Time, userCall: Bool = false) { guard dt > Float.ulpOfOne else { return } if userCall { cpHastySpaceStep(chipmunkSpace, cpFloat(dt)) } else { updateTime += dt if fixedUpdateRate > 0 { let step = 1.0 / Time(fixedUpdateRate) let dt = step * speed while updateTime > step { updateTime -= step cpHastySpaceStep(chipmunkSpace, cpFloat(dt)) } } else { updateRateCount += 1 if Float(updateRateCount) > updateRate { let dt = updateTime * speed / Time(substeps) for _ in 0..<substeps { cpHastySpaceStep(chipmunkSpace, cpFloat(dt)) for b in bodies { b.fixedUpdate(delta: dt) } } updateRateCount = 0 updateTime = 0 } } } // debugDraw() } }
apache-2.0
473b2149e79036c6ceb0c8438d66d7d2
34.625
162
0.597953
4.678523
false
false
false
false
Dan2552/DropboxSync
DropboxSync/Classes/DropboxSync.swift
1
13310
import Foundation import SwiftyDropbox import SwiftyJSON private enum SyncState { case notStarted case findRemoteFiles case downloadMetadata case readMetadata case queueRemainingUploads case preperation case delete case upload case download case finish } open class DropboxSync { var delegate: DropboxSyncDelegate? var items: [DropboxSyncable] public init<T: DropboxSyncable, S: Sequence>(_ items: S) where S.Iterator.Element == T { self.items = Array(items) self.syncableType = T.self } convenience public init<T: DropboxSyncable, S: Sequence>(_ items: S, delegate: DropboxSyncDelegate) where S.Iterator.Element == T { self.init(items) self.delegate = delegate } open func sync() { DropboxSyncOptions.log("Sync starting") guard DropboxSyncAuthorization.loggedIn(), state == .notStarted else { DropboxSyncOptions.log("Failed to start. Logged in? Already running?") return } progressTotal = nil for item in items { syncables.append(item) } next(.findRemoteFiles) } ////// Private private var syncableType: DropboxSyncable.Type private var syncables = [DropboxSyncable]() private var state: SyncState = .notStarted private var client: DropboxClient! { return DropboxClientsManager.authorizedClient } private var remoteMetaPaths = [String]() private var remoteMetaPathsToDownload = [String]() private var remoteMetaPathsToRead = [String]() private var idsToDeleteLocally = [String]() private var idsToDeleteRemotely = [String]() private var idsToUpload = [String]() private var idsToDownload = [String]() private var idsAlreadySynced = [String]() private var idsAtEnd = [String]() private var progressTotal: Int? private func next(_ state: SyncState) { switch state { case .findRemoteFiles: findRemoteFiles() case .downloadMetadata: downloadMetaFiles() case .readMetadata: readMetaFiles() case .queueRemainingUploads: queueRemainingUploads() case .preperation: preperation() case .delete: deleteLocally() deleteRemotely() case .upload: uploadFiles() case .download: downloadFiles() case .finish: finish() default: break } } private func preperation() { setProgressTotal() // Record the IDs we'll have at the end of the sync, so we can persist them once finished idsAtEnd = idsToUpload + idsToDownload + idsAlreadySynced next(.delete) } private func findRemoteFiles() { DropboxSyncOptions.log("Finding remote files") client.files.listFolder(path: "", recursive: true, includeDeleted: true).response { response, error in if let result = response { for entry in result.entries { if let file = entry as? Files.FileMetadata { guard file.name == "meta.json" else { continue } self.remoteMetaPaths.append(file.pathLower!) self.remoteMetaPathsToRead.append(file.pathLower!) self.remoteMetaPathsToDownload.append(file.pathLower!) } if let deletedFile = entry as? Files.DeletedMetadata { guard deletedFile.name == "meta.json" else { continue } let path = deletedFile.pathDisplay! self.idsToDeleteLocally.append(path.components(separatedBy: "/")[1]) } } if result.hasMore { self.client.files.listFolderContinue(cursor: result.cursor) } else { self.next(.downloadMetadata) } } else { print(error!) } } } private func downloadMetaFiles() { DropboxSyncOptions.log("Downloading meta") guard let nextMetaPath = remoteMetaPathsToDownload.popLast() else { next(.readMetadata) return } let directory = self.directoryFor(nextMetaPath) self.createDirectory(directory) let destinationURL = directory.appendingPathComponent("meta.json") let destination: (URL, HTTPURLResponse) -> URL = { temporaryURL, response in return destinationURL } client.files.download(path: nextMetaPath, overwrite: true, destination: destination) .response { response, error in if let e = error { print(e) } self.downloadMetaFiles() } } private func readMetaFiles() { DropboxSyncOptions.log("Reading meta") guard let nextMetaPath = remoteMetaPathsToRead.popLast() else { next(.queueRemainingUploads) return } let path = directoryFor(nextMetaPath).appendingPathComponent("meta.json") guard let data = dataForFile(path) else { readMetaFiles() return } let json = JSON(data: data) // Check if the "type" in the json matches the type we're syncing. // // For backwards compatibility, if we don't have a metaType, we can ignore it if let metaType = json["type"].string, metaType != "\(syncableType)" { return readMetaFiles() } if let uuid = json["uuid"].string, let updatedAtInterval = json["updated_at"].double { let remoteUpdatedAt = floor(updatedAtInterval) var foundLocalSyncable = false for syncable in syncables { guard syncable.syncableUniqueIdentifier() == uuid else { continue } foundLocalSyncable = true let localUpdatedAt = floor(syncable.syncableUpdatedAt().timeIntervalSince1970) if localUpdatedAt > remoteUpdatedAt { idsToUpload.append(uuid) } else if localUpdatedAt < remoteUpdatedAt { idsToDownload.append(uuid) } else { idsAlreadySynced.append(uuid) } } // If we've not found it locally, it either needs to be downloaded to local, or deleted from remote if !foundLocalSyncable { let previousSync = fetchPreviousSync(type: syncableType) // If a previous sync contains the UUID, it must have been deleted locally if previousSync.contains(uuid) { idsToDeleteRemotely.append(uuid) } else { idsToDownload.append(uuid) } } } else { print("WARNING: metadata parse failed. Ignoring. (\(nextMetaPath))") } readMetaFiles() } private func queueRemainingUploads() { // Any local items that exist that aren't already marked for syncing, must not yet exist on the remote end for syncable in syncables { guard !idsToUpload.contains(syncable.syncableUniqueIdentifier()) else { continue } guard !idsToDownload.contains(syncable.syncableUniqueIdentifier()) else { continue } guard !idsAlreadySynced.contains(syncable.syncableUniqueIdentifier()) else { continue } guard !idsToDeleteLocally.contains(syncable.syncableUniqueIdentifier()) else { continue } idsToUpload.append(syncable.syncableUniqueIdentifier()) } next(.preperation) } private func uploadFiles() { DropboxSyncOptions.log("upload:") DropboxSyncOptions.log("\(idsToUpload)") progressUpdate() guard let nextUpload = idsToUpload.popLast() else { next(.download) return } let syncable = syncables.filter { return $0.syncableUniqueIdentifier() == nextUpload }.first! let uuid = syncable.syncableUniqueIdentifier() let contentPath = "/\(uuid)/content.json" let metaPath = "/\(uuid)/meta.json" let data = syncable.syncableSerialize() let meta = [ "uuid": uuid, "updated_at": Int(syncable.syncableUpdatedAt().timeIntervalSince1970), "type": "\(syncableType)" ] as [String : Any] let metaData = try! SwiftyJSON.JSON(meta).rawData() let uploadGroup = DispatchGroup() let uploadContent = { uploadGroup.enter() self.client.files.upload(path: contentPath, mode: Files.WriteMode.overwrite, input: data).response { response, error in if let metadata = response { DropboxSyncOptions.log("Uploaded file name: \(metadata.name) - \(contentPath)") } else { print(error!) } uploadGroup.leave() } } let uploadMeta = { uploadGroup.enter() self.client.files.upload(path: metaPath, mode: Files.WriteMode.overwrite, input: metaData).response { response, error in if let metadata = response { DropboxSyncOptions.log("Uploaded file name: \(metadata.name) - \(metaPath)") } else { print(error!) } uploadGroup.leave() } } uploadContent() uploadMeta() uploadGroup.notify(queue: DispatchQueue.main) { self.next(.upload) } } private func downloadFiles() { DropboxSyncOptions.log("download:") DropboxSyncOptions.log("\(idsToDownload)") progressUpdate() guard let nextDownload = idsToDownload.popLast() else { next(.finish) return } let uuid = nextDownload let contentPath = "/\(uuid)/content.json" client.files.download(path: contentPath, overwrite: true, destination: { _, response in let directory = self.directoryFor(contentPath) self.createDirectory(directory) return directory.appendingPathComponent("content.json") }).response { response, error in if let e = error { print(e) } else { self.importDownloadedFile(contentPath) } self.downloadFiles() } } private func deleteLocally() { DropboxSyncOptions.log("delete: \(idsToDeleteLocally)") for identifier in idsToDeleteLocally { syncableType.syncableDelete(uniqueIdentifier: identifier) } idsToDeleteLocally = [] } private func deleteRemotely() { guard let nextDeletion = idsToDeleteRemotely.popLast() else { next(.upload) return } let uuid = nextDeletion let path = "/\(uuid)" client.files.delete(path: path).response { response, error in if let e = error { print(e) } } } private func importDownloadedFile(_ pathString: String) { let path = directoryFor(pathString).appendingPathComponent("content.json") guard let data = dataForFile(path) else { return } syncableType.syncableDeserialize(data) } private func finish() { persistPreviousSync(type: syncableType, ids: idsAtEnd) delegate?.dropboxSyncDidFinish(dropboxSync: self) } private func directoryFor(_ path: String) -> URL { let components = path.components(separatedBy: "/") let fileManager = FileManager.default var directoryURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0] directoryURL = directoryURL.appendingPathComponent(components[1].lowercased()) return directoryURL } private func createDirectory(_ url: URL) { try! FileManager.default.createDirectory(atPath: url.path, withIntermediateDirectories: true, attributes: nil) } private func dataForFile(_ url: URL) -> Data? { do { return try Data(contentsOf: url, options: .mappedIfSafe) } catch { return nil } } private func progressUpdate() { guard let total = progressTotal else { return } let currentProgress = total - (idsToUpload.count + idsToDownload.count + idsToDeleteLocally.count) delegate?.dropboxSyncProgressUpdate(dropboxSync: self, progress: currentProgress, total: total) } private func setProgressTotal() { guard progressTotal == nil else { return } progressTotal = idsToUpload.count + idsToDownload.count + idsToDeleteLocally.count } }
mit
7241f36b4ec64720a13aa2c0707e6588
34.118734
135
0.572276
5.20125
false
false
false
false
Azero123/JW-Broadcasting
JW Broadcasting/CollectionViewAlignmentFlowLayout.swift
1
7578
// // CollectionViewAlignmentFlowLayout.swift // JW Broadcasting // // Created by Austin Zelenka on 11/18/15. // Copyright © 2015 xquared. All rights reserved. // import UIKit class CollectionViewAlignmentFlowLayout: UICollectionViewFlowLayout { var spacingPercentile:CGFloat=1 var headerSpace:CGFloat=50 var headerBottomSpace:CGFloat=25 override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { /* Defines the position and size of the indivigual cell. */ let layoutAttribute=super.layoutAttributesForItemAtIndexPath(indexPath)?.copy() as! UICollectionViewLayoutAttributes /* Handles right to left placement of items. Does this by reversing the math (Getting the far right distance and moving the attributes back the normal distance plus their width instead of from the left and adding both.) */ if (textDirection == UIUserInterfaceLayoutDirection.RightToLeft){ layoutAttribute.frame=CGRect(x: (self.collectionView?.frame.size.width)!-(layoutAttribute.frame.origin.x)-(layoutAttribute.frame.size.width), y: (layoutAttribute.frame.origin.y), width: (layoutAttribute.frame.size.width), height: (layoutAttribute.frame.size.height)) } return layoutAttribute } override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { /* Supplementary item code is handled differently for UICollectionViewFlowLayout then it's subclasses? I was unable to do so without creating code to tell it where to add the items. This just creates the attributes without a position. */ let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, withIndexPath: indexPath) attributes.frame = CGRect(x: 0, y: 0, width: (self.collectionView?.frame.size.width)!, height: 50) return attributes } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { /* Because previously layoutAttributesForItemAtIndexPath(...) was not being called for our needs consistently. Now all elements are laid out so that we don't have errors with users panning/scrolling through cells too quickly for the items to cells.*/ var attributes:Array<UICollectionViewLayoutAttributes>=super.layoutAttributesForElementsInRect(rect)! if (self.collectionView?.numberOfSections()>0){ for (var i=0;i<self.collectionView?.numberOfItemsInSection(0);i++){ attributes.append(self.layoutAttributesForItemAtIndexPath(NSIndexPath(forRow: i, inSection: 0))!) } } for attrs in attributes { /* Handles right to left placement of items. Does this by reversing the math (Getting the far right distance and moving the attributes back the normal distance plus their width instead of from the left and adding both.) */ /* if (textDirection == UIUserInterfaceLayoutDirection.RightToLeft){ attrs.frame=CGRect( x: self.collectionView!.frame.size.width-attrs.frame.origin.x, y: attrs.frame.origin.y, width: attrs.frame.size.width, height: attrs.frame.height) }*/ /* Calculates the vertical position of the items using spacgingPercentile and the offset added by section headers. */ attrs.frame=CGRect(x: (attrs.frame.origin.x), y: attrs.frame.origin.y*spacingPercentile+CGFloat(headerSpace*CGFloat(attrs.indexPath.section+1))-25, width: attrs.frame.size.width, height: attrs.frame.height) /* Whenever the first item for the section is being generated it first adds in the section header in it's place (roughly). */ if attrs.indexPath.row == 0 { let indexPath = NSIndexPath(forItem: 0, inSection: attrs.indexPath.section) let layoutAttributes = self.layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: indexPath) layoutAttributes?.frame=CGRect(x: (layoutAttributes?.frame.origin.x)!, y: attrs.frame.origin.y-headerSpace+headerBottomSpace, width: (layoutAttributes?.frame.size.width)!, height: (layoutAttributes?.frame.size.height)!) attributes.append(layoutAttributes!) } } return attributes } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } override func collectionViewContentSize() -> CGSize { /* This calculates the content height for the collection view for our code so it has enough space to scroll. To do this we account for how many cells there are based on the suggested content height then we multiply the actual space the cells take up by that number then we add the height all the headers take up. */ var layout=CGSize(width: 0,height: 0) if ((self.collectionView?.delegate?.isKindOfClass(CategoryController.self)) == true){ layout=(self.collectionView!.delegate as! CategoryController).collectionView(self.collectionView!, layout: self, sizeForItemAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) } else if ((self.collectionView?.delegate?.isKindOfClass(MediaOnDemandController.self)) == true){ print((self.collectionView!.delegate as! MediaOnDemandController).collectionView(self.collectionView!, layout: self, sizeForItemAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))) //self.collectionView. return CGSize(width: (self.collectionView?.frame.size.width)!, height: 1500) //layout=(self.collectionView!.delegate as! MediaOnDemandController).collectionView(self.collectionView!, layout: self, sizeForItemAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) } else if ((self.collectionView?.delegate?.isKindOfClass(AudioController.self)) == true){ print((self.collectionView!.delegate as! AudioController).collectionView(self.collectionView!, layout: self, sizeForItemAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))) //self.collectionView. return CGSize(width: (self.collectionView?.frame.size.width)!, height: 500) //layout=(self.collectionView!.delegate as! MediaOnDemandController).collectionView(self.collectionView!, layout: self, sizeForItemAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) } let verticalRowCount=ceil(super.collectionViewContentSize().height/(layout.height)) let headerHeight=layoutAttributesForSupplementaryViewOfKind( UICollectionElementKindSectionHeader , atIndexPath: NSIndexPath(forRow: 0, inSection: 0))?.frame.size.height let accumulativeHeaderHeight=CGFloat((self.collectionView?.numberOfSections())!)*headerHeight! let completedContentSize=CGSize(width: super.collectionViewContentSize().width, height: (layout.height)*spacingPercentile*verticalRowCount+accumulativeHeaderHeight) return completedContentSize } }
mit
9e05d5800dcce3a84546936d94f9db1d
53.905797
278
0.682724
5.470758
false
false
false
false
brentdax/swift
test/stdlib/KVOKeyPaths.swift
3
2997
// RUN: %target-run-simple-swift-swift3 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation struct Guts { var internalValue = 42 var value: Int { get { return internalValue } } init(value: Int) { internalValue = value } init() { } } class Target : NSObject, NSKeyValueObservingCustomization { // This dynamic property is observed by KVO dynamic var objcValue: String dynamic var objcValue2: String { willSet { willChangeValue(for: \.objcValue2) } didSet { didChangeValue(for: \.objcValue2) } } dynamic var objcValue3: String // This Swift-typed property causes vtable usage on this class. var swiftValue: Guts override init() { self.swiftValue = Guts() self.objcValue = "" self.objcValue2 = "" self.objcValue3 = "" super.init() } static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath> { if (key == \Target.objcValue) { return [\Target.objcValue2, \Target.objcValue3] } else { return [] } } static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool { if key == \Target.objcValue2 || key == \Target.objcValue3 { return false } return true } func print() { Swift.print("swiftValue \(self.swiftValue.value), objcValue \(objcValue)") } } class ObserverKVO : NSObject { var target: Target? var observation: NSKeyValueObservation? = nil override init() { target = nil; super.init() } func observeTarget(_ target: Target) { self.target = target observation = target.observe(\.objcValue) { (object, change) in Swift.print("swiftValue \(object.swiftValue.value), objcValue \(object.objcValue)") } } func removeTarget() { observation!.invalidate() } } var t2 = Target() var o2 = ObserverKVO() print("unobserved 2") t2.objcValue = "one" t2.objcValue = "two" print("registering observer 2") o2.observeTarget(t2) print("Now witness the firepower of this fully armed and operational panopticon!") t2.objcValue = "three" t2.objcValue = "four" t2.swiftValue = Guts(value: 13) t2.objcValue2 = "six" //should fire t2.objcValue3 = "nothing" //should not fire o2.removeTarget() t2.objcValue = "five" //make sure that we don't crash or keep posting changes if you deallocate an observation after invalidating it print("target removed") // CHECK: registering observer 2 // CHECK-NEXT: Now witness the firepower of this fully armed and operational panopticon! // CHECK-NEXT: swiftValue 42, objcValue three // CHECK-NEXT: swiftValue 42, objcValue four // CHECK-NEXT: swiftValue 13, objcValue four // CHECK-NEXT: swiftValue 13, objcValue four // CHECK-NEXT: swiftValue 13, objcValue four // CHECK-NEXT: target removed
apache-2.0
ebde9b0e1d4a7e4824c74531f580bc61
26
132
0.634635
4.21519
false
false
false
false
googlesamples/mlkit
ios/ios-snippets/swift-snippets/ModelManagement.swift
1
3163
// // Copyright (c) 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import MLKitCommon import MLKitImageClassificationAutoML class ModelManagementSnippets { func setupRemoteModel() { // [START setup_remote_model] let downloadConditions = ModelDownloadConditions(allowsCellularAccess: true, allowsBackgroundDownloading: true) // Instantiate a concrete subclass of RemoteModel. let remoteModel = AutoMLRemoteModel(name: "your_remote_model" // The name you assigned in the console. ) // [END setup_remote_model] // [START start_download] let downloadProgress = ModelManager.modelManager().download(remoteModel, conditions: downloadConditions) // ... if downloadProgress.isFinished { // The model is available on the device } // [END start_download] } func setupModelDownloadNotifications() { // [START setup_notifications] NotificationCenter.default.addObserver( forName: .mlkitModelDownloadDidSucceed, object: nil, queue: nil ) { [weak self] notification in guard let strongSelf = self, let userInfo = notification.userInfo, let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue] as? RemoteModel, model.name == "your_remote_model" else { return } // The model was downloaded and is available on the device } NotificationCenter.default.addObserver( forName: .mlkitModelDownloadDidFail, object: nil, queue: nil ) { [weak self] notification in guard let strongSelf = self, let userInfo = notification.userInfo, let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue] as? RemoteModel else { return } let error = userInfo[ModelDownloadUserInfoKey.error.rawValue] // ... } // [END setup_notifications] } func setupLocalModel() { // [START setup_local_model] guard let manifestPath = Bundle.main.path(forResource: "manifest", ofType: "json", inDirectory: "my_model") else { return } // Instantiate a concrete subclass of LocalModel. let localModel = AutoMLLocalModel(manifestPath: manifestPath) // [END setup_local_model] } }
apache-2.0
63456d1ff8bc02c57ec24fddc59bc834
37.573171
112
0.604489
5.012678
false
false
false
false
honghaoz/2048-Solver-AI
2048 AI/AI/TDLearning/Game2048Board.swift
1
3536
// Copyright © 2019 ChouTi. All rights reserved. import Foundation class BoardUtils { struct METRICS { static var MARGIN_WIDTH = 1 static var TOTAL_MARGIN = 2 * MARGIN_WIDTH } /* * Returned position is margin-based */ class func toMarginPos(boardSize: RectSize, pos: BoardPos) -> Int { return (pos.row() + 1) * (boardSize.width + METRICS.TOTAL_MARGIN) + pos.column() + 1 } class func toMarginPos(boardWidth: Int, row: Int, col: Int) -> Int { return toMarginPos(RectSize(size: boardWidth), pos: BoardPos(row: row, col: col)) } class func isValidPosition(pos: Int, boardSize: Int) -> Bool { return isValidPosition(pos, rows: boardSize, cols: boardSize) } class func isValidPosition(pos: Int, rows: Int, cols: Int) -> Bool { let row = rowFromPos(pos, boardWidth: cols) let col = colFromPos(pos, boardWidth: cols) return row >= 0 && row < rows && col >= 0 && col < cols } class func rowFromPos(pos: Int, boardWidth: Int) -> Int { return pos / (boardWidth + METRICS.TOTAL_MARGIN) - 1 } class func colFromPos(pos: Int, boardWidth: Int) -> Int { return pos % (boardWidth + METRICS.TOTAL_MARGIN) - 1 } } func == (lhs: Game2048Board, rhs: Game2048Board) -> Bool { if lhs.buffer.count != rhs.buffer.count { return false } for i in 0..<lhs.buffer.count { if lhs.buffer[i] != rhs.buffer[i] { return false } } return true } class Game2048Board: Equatable { var SIZE: Int = 4 var MARGIN_WIDTH = BoardUtils.METRICS.MARGIN_WIDTH var WIDTH: Int var BUFFER_SIZE: Int var WALL = -2 var buffer: [Int] init() { self.WIDTH = SIZE + 2 * MARGIN_WIDTH self.BUFFER_SIZE = WIDTH * WIDTH self.buffer = Array(count: BUFFER_SIZE, repeatedValue: 0) } convenience init(input: [Double]) { self.init() initMargins() for r in 0..<SIZE { for c in 0..<SIZE { setValue(r, col: c, color: inputToBoardValue(input, r: r, c: c)) } } } convenience init(buffer: [Int]) { self.init() self.buffer = buffer } private func inputToBoardValue(input: [Double], r: Int, c: Int) -> Int { return Int(input[r * SIZE + c] + 0.5) } private func initMargins() { for i in 0..<WIDTH { setValueInternal(0, col: i, color: WALL) setValueInternal(WIDTH - 1, col: i, color: WALL) setValueInternal(i, col: 0, color: WALL) setValueInternal(i, col: WIDTH - 1, color: WALL) } } func toPos(row: Int, col: Int) -> Int { return (row + 1) * WIDTH + col + 1 } private func toPosInternal(row: Int, col: Int) -> Int { return row * WIDTH + col } func setValue(row: Int, col: Int, color: Int) { buffer[toPos(row, col: col)] = color } private func setValueInternal(row: Int, col: Int, color: Int) { buffer[toPosInternal(row, col: col)] = color } func getValue(row: Int, col: Int) -> Int { return buffer[toPos(row, col: col)] } func getValue(pos: Int) -> Int { return buffer[pos] } func getSize() -> Int { return SIZE } func toString() -> String { var stringBoard = "\n" for r in 0..<getSize() { stringBoard += String(r + 1) stringBoard += " " for c in 0..<getSize() { stringBoard += String(getValue(r, col: c)) } stringBoard += "\n" } return stringBoard } func getWidth() -> Int { return getSize() } func getHeight() -> Int { return getSize() } func clone() -> Game2048Board { return Game2048Board(buffer: buffer) } }
gpl-2.0
30a85618e6b30c71208b93384b4ab868
22.410596
88
0.607355
3.291434
false
false
false
false
airbnb/lottie-ios
Sources/Private/MainThread/NodeRenderSystem/Nodes/RenderNodes/FillNode.swift
3
1993
// // FillNode.swift // lottie-swift // // Created by Brandon Withrow on 1/17/19. // import CoreGraphics import Foundation // MARK: - FillNodeProperties final class FillNodeProperties: NodePropertyMap, KeypathSearchable { // MARK: Lifecycle init(fill: Fill) { keypathName = fill.name color = NodeProperty(provider: KeyframeInterpolator(keyframes: fill.color.keyframes)) opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: fill.opacity.keyframes)) type = fill.fillRule keypathProperties = [ "Opacity" : opacity, PropertyName.color.rawValue : color, ] properties = Array(keypathProperties.values) } // MARK: Internal var keypathName: String let opacity: NodeProperty<LottieVector1D> let color: NodeProperty<LottieColor> let type: FillRule let keypathProperties: [String: AnyNodeProperty] let properties: [AnyNodeProperty] } // MARK: - FillNode final class FillNode: AnimatorNode, RenderNode { // MARK: Lifecycle init(parentNode: AnimatorNode?, fill: Fill) { fillRender = FillRenderer(parent: parentNode?.outputNode) fillProperties = FillNodeProperties(fill: fill) self.parentNode = parentNode } // MARK: Internal let fillRender: FillRenderer let fillProperties: FillNodeProperties let parentNode: AnimatorNode? var hasLocalUpdates = false var hasUpstreamUpdates = false var lastUpdateFrame: CGFloat? = nil var renderer: NodeOutput & Renderable { fillRender } // MARK: Animator Node Protocol var propertyMap: NodePropertyMap & KeypathSearchable { fillProperties } var isEnabled = true { didSet { fillRender.isEnabled = isEnabled } } func localUpdatesPermeateDownstream() -> Bool { false } func rebuildOutputs(frame _: CGFloat) { fillRender.color = fillProperties.color.value.cgColorValue fillRender.opacity = fillProperties.opacity.value.cgFloatValue * 0.01 fillRender.fillRule = fillProperties.type } }
apache-2.0
ff33b77921cb28f6cf0081088fd952e0
21.144444
93
0.721525
4.419069
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/maximum-depth-of-n-ary-tree.swift
2
1436
/** * https://leetcode.com/problems//maximum-depth-of-n-ary-tree/ * * */ // Date: Tue May 5 14:29:15 PDT 2020 /** * Definition for a Node. * public class Node { * public var val: Int * public var children: [Node] * public init(_ val: Int) { * self.val = val * self.children = [] * } * } */ class Solution { func maxDepth(_ root: Node?) -> Int { guard let root = root else { return 0 } var queue = [root] var depth = 0 while !queue.isEmpty { depth += 1 var n = queue.count while n > 0 { n -= 1 let node = queue.removeFirst() for child in node.children { queue.append(child) } } } return depth } } /** * https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ * * */ // Date: Tue May 5 14:31:31 PDT 2020 /** * Definition for a Node. * public class Node { * public var val: Int * public var children: [Node] * public init(_ val: Int) { * self.val = val * self.children = [] * } * } */ class Solution { func maxDepth(_ root: Node?) -> Int { guard let root = root else { return 0 } var maxDep = 0 for child in root.children { maxDep = max(maxDep, maxDepth(child)) } return 1 + maxDep } }
mit
3e284038f0e8dfa004cb00324fdb2184
21.092308
62
0.481894
3.598997
false
false
false
false
Traleski/NSCoding-Object-Generator
NSCodingObjectGeneratorOSX/NSCodingObjectGeneratorOSX/Generator.swift
1
4156
// // Generator.swift // NSCodingObjectGeneratorOSX // // Created by Pablo Henemann on 09/12/15. // Copyright (c) 2015 Pablo Henemann. All rights reserved. // import Cocoa @objc(Generator) class Generator: NSViewController { @IBOutlet var classNameTextField: NSTextField! @IBOutlet var codeTextView: NSTextView! var variables: [ObjectVariable] = [] override func viewDidLoad() { super.viewDidLoad() variables.append(ObjectVariable(name: "integer", type: "Int", optional: true)) variables.append(ObjectVariable(name: "string", type: "String", optional: true)) variables.append(ObjectVariable(name: "float", type: "Float", optional: true)) variables.append(ObjectVariable(name: "double", type: "Double", optional: true)) variables.append(ObjectVariable(name: "custom", type: "User", optional: true)) self.generateCode() // Do view setup here. } } extension Generator { func generateCode() { let className = classNameTextField.stringValue var classText = "" classText += "import Foundation\n\n" classText += "class " + className + ": NSObject, NSCoding {\n\n" for objectVar in variables { var varDeclare = " var " + objectVar.name! + ": " + objectVar.type! if objectVar.optional! { varDeclare += "?\n" } else { varDeclare += "!\n" } classText += varDeclare } classText += "\n" + " init(" var index = 0 for objectVar in variables { var varDeclare = objectVar.name! + ": " + objectVar.type! if objectVar.optional! { varDeclare += "?" } if index != variables.count - 1 { varDeclare += ", " } classText += varDeclare index++ } classText += ") {\n\n" for objectVar in variables { var varDeclare = " self." + objectVar.name! + " = " + objectVar.name! + "\n" classText += varDeclare } classText += "\n" + " }\n\n" classText += " convenience required init(coder decoder: NSCoder) {\n\n" for objectVar in variables { var varDeclare = " let " + objectVar.name! + " = decoder.decodeObjectForKey(\"" + objectVar.name! + "\") as" if objectVar.optional! { varDeclare += "? " } else { varDeclare += "! " } varDeclare += objectVar.type! + "\n" classText += varDeclare } classText += "\n" + " self.init(" index = 0 for objectVar in variables { var varDeclare = objectVar.name! + ": " + objectVar.name! if index != variables.count - 1 { varDeclare += ", " } classText += varDeclare index++ } classText += ")\n\n" + " }\n\n" classText += " func encodeWithCoder(coder: NSCoder) {\n\n" for objectVar in variables { var varDeclare = " coder.encodeObject(" + objectVar.name! + ", forKey: \"" + objectVar.name! + "\")\n" classText += varDeclare } classText += "\n" + " }\n\n" + "}" codeTextView.string = classText println(classText) } }
mit
c97e1229f7e41b6e226c781a9d451b8c
25.819355
129
0.429981
4.953516
false
false
false
false
codePrincess/playgrounds
GreatStuffWithThePencil.playground/Pages/Smooth Doodeling.xcplaygroundpage/Contents.swift
1
4938
/*: # Make your doodling smooth! In the previous playground we got a first feeling for how easy it is to draw with the Apple Pencil. So now we want to see our doodling a bit more smoother and not that edged, especially when drawing arcs and cicles. In this playground we will add some minor adjustment to our code to achieve this exact goal: smoooothen it! - - - */ import Foundation import UIKit import PlaygroundSupport public class SmoothCanvas : UIImageView { let pi = CGFloat(Double.pi) let forceSensitivity: CGFloat = 4.0 var pencilTexture = UIColor(patternImage: UIImage(named: "PencilTexture")!) let defaultLineWidth : CGFloat = 6 var eraserColor: UIColor { return backgroundColor ?? UIColor.white } /*: ### Again: Touches! Guess what - here the smoothening action will happen! The pencil generates not only touches - it generates coalescedTouches and predictedTouches as well along it's drawing way over our canvas. For smoothening the drawing line we will need the coalescedTouches. Those are - simply put - the intermediate touches which are generated on a higher scanning rate from the iPad's display. Because when the pencil touches the display the framerate will be doubled. Not for the drawing, but for detecting touches by the pencil. Crazy huh! But good for us because we use them to get more touches and therefore smoothen our drawing lines. */ override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) let context = UIGraphicsGetCurrentContext() // Draw previous image into context image?.draw(in: bounds) var touches = [UITouch]() //: The coalesced touches come withthe current event. So we find out which belong to our current touch and collect them in an array. if let coalescedTouches = event?.coalescedTouches(for: touch) { touches = coalescedTouches } else { touches.append(touch) } //: After we found all coalesced touches for our touch we draw them all. So not just the one touch, but with all it's intermediate "buddies". for touch in touches { drawStroke(context: context, touch: touch) } image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } //: The rest of the code stays exactly the same as in the first playground. We draw more strokes and therefore smoothen the drawing. That's it! func drawStroke(context: CGContext?, touch: UITouch) { let previousLocation = touch.previousLocation(in: self) let location = touch.location(in: self) // Calculate line width for drawing stroke var lineWidth : CGFloat = 1.0 if touch.type == .stylus { lineWidth = lineWidthForDrawing(context: context, touch: touch) pencilTexture.setStroke() } else { lineWidth = touch.majorRadius / 2 eraserColor.setStroke() } UIColor.darkGray.setStroke() context!.setLineWidth(lineWidth) context!.setLineCap(.round) context?.move(to: previousLocation) context?.addLine(to: location) // Draw the stroke context!.strokePath() } func lineWidthForDrawing(context: CGContext?, touch: UITouch) -> CGFloat { var lineWidth = defaultLineWidth if touch.force > 0 { lineWidth = touch.force * forceSensitivity } return lineWidth } func clearCanvas(_ animated: Bool) { if animated { UIView.animate(withDuration: 0.5, animations: { self.alpha = 0 }, completion: { finished in self.alpha = 1 self.image = nil }) } else { image = nil } } } /*: - - - ### Using the Doodle Canvas Now we build ourselves a nice smoooothe doodling canvas. So we want to use it, right? Just create a new SmoothCanvas, set a background color and give it a frame (for the Playgrounds app on the iPad just use the width: 1024). Attach the new view to the Playground's liveView and you are good to go. Let's doodle! */ var myCanvas = SmoothCanvas() myCanvas.backgroundColor = .white myCanvas.isUserInteractionEnabled = true var canvasView = UIView(frame: CGRect(x: 0, y: 0, width: 450, height: 630)) //: Use the wider view on the iPad with the Playgrounds app fullscreen mode. More space to draw! //var canvasView = UIView(frame: CGRect(x: 0, y: 0, width: 1024, height: 630)) myCanvas.frame = canvasView.frame canvasView.addSubview((myCanvas)) PlaygroundPage.current.liveView = canvasView
mit
1f88c7b6716e24b0fc74fb0e7d43b725
34.271429
143
0.656946
4.658491
false
false
false
false
neerajDamle/OpenWeatherForecast
OpenWeatherForecast/OpenWeatherForecast/ThirdParty/JLToast/JLToast.swift
1
3746
/* * JLToast.swift * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Copyright (C) 2013-2015 Su Yeol Jeon * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. * */ import UIKit public struct JLToastDelay { public static let ShortDelay: TimeInterval = 2.0 public static let LongDelay: TimeInterval = 3.5 } @objc open class JLToast: Operation { open var view: JLToastView = JLToastView() open var text: String? { get { return self.view.textLabel.text } set { self.view.textLabel.text = newValue } } open var delay: TimeInterval = 0 open var duration: TimeInterval = JLToastDelay.ShortDelay fileprivate var _executing = false override open var isExecuting: Bool { get { return self._executing } set { self.willChangeValue(forKey: "isExecuting") self._executing = newValue self.didChangeValue(forKey: "isExecuting") } } fileprivate var _finished = false override open var isFinished: Bool { get { return self._finished } set { self.willChangeValue(forKey: "isFinished") self._finished = newValue self.didChangeValue(forKey: "isFinished") } } open class func makeText(_ text: String) -> JLToast { return JLToast.makeText(text, delay: 0, duration: JLToastDelay.ShortDelay) } open class func makeText(_ text: String, duration: TimeInterval) -> JLToast { return JLToast.makeText(text, delay: 0, duration: duration) } open class func makeText(_ text: String, delay: TimeInterval, duration: TimeInterval) -> JLToast { let toast = JLToast() toast.text = text toast.delay = delay toast.duration = duration return toast } open func show() { JLToastCenter.defaultCenter().addToast(self) } override open func start() { if !Thread.isMainThread { DispatchQueue.main.async(execute: { self.start() }) } else { super.start() } } override open func main() { self.isExecuting = true DispatchQueue.main.async(execute: { self.view.updateView() self.view.alpha = 0 UIApplication.shared.windows.first?.addSubview(self.view) UIView.animate( withDuration: 0.5, delay: self.delay, options: .beginFromCurrentState, animations: { self.view.alpha = 1 }, completion: { completed in UIView.animate( withDuration: self.duration, animations: { self.view.alpha = 1.0001 }, completion: { completed in self.finish() UIView.animate(withDuration: 0.5, animations: { self.view.alpha = 0 }) } ) } ) }) } open func finish() { self.isExecuting = false self.isFinished = true } }
mit
92cfc900b280340cd07e1e0caf1dd9fd
26.955224
102
0.526962
5.082768
false
false
false
false
yzyzsun/CurriculaTable
CurriculaTable/CurriculaTableWeekday.swift
1
471
// // CurriculaTableWeekday.swift // CurriculaTable // // Created by Sun Yaozhu on 2016-09-10. // Copyright © 2016 Sun Yaozhu. All rights reserved. // import Foundation public enum CurriculaTableWeekday: Int { case sunday = 1 case monday = 2 case tuesday = 3 case wednesday = 4 case thursday = 5 case friday = 6 case saturday = 7 } public enum CurriculaTableWeekdaySymbolType: Int { case normal case short case veryShort }
mit
87a4e4ce6d309ebf916ababd2ab3ccde
17.8
53
0.676596
3.560606
false
false
false
false
firebase/firebase-ios-sdk
FirebaseCore/Tests/SwiftUnit/FirebaseOptionsTests.swift
2
6488
// Copyright 2020 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import FirebaseCore class FirebaseOptionsTests: XCTestCase { func testDefaultOptions() throws { let options = try XCTUnwrap( FirebaseOptions.defaultOptions(), "Default options could not be unwrapped" ) assertOptionsMatchDefaultOptions(options: options) } func testInitWithContentsOfFile() throws { let bundle = try XCTUnwrap( Bundle(for: type(of: self)), "Could not find bundle" ) let path = try XCTUnwrap( bundle.path(forResource: "GoogleService-Info", ofType: "plist"), "Could not find path for file" ) let options = FirebaseOptions(contentsOfFile: path) XCTAssertNotNil(options) } func testInitWithInvalidSourceFile() { let invalidPath = "path/to/non-existing/plist" let options = FirebaseOptions(contentsOfFile: invalidPath) XCTAssertNil(options) } func testInitWithCustomFields() throws { let googleAppID = "5:678:ios:678def" let gcmSenderID = "custom_gcm_sender_id" let options = FirebaseOptions(googleAppID: googleAppID, gcmSenderID: gcmSenderID) XCTAssertEqual(options.googleAppID, googleAppID) XCTAssertEqual(options.gcmSenderID, gcmSenderID) let bundleID = try XCTUnwrap(Bundle.main.bundleIdentifier, "Could not retrieve bundle identifier") XCTAssertEqual(options.bundleID, bundleID) assertNullableOptionsAreEmpty(options: options) } func testCustomizedOptions() { let googleAppID = Constants.Options.googleAppID let gcmSenderID = Constants.Options.gcmSenderID let options = FirebaseOptions(googleAppID: googleAppID, gcmSenderID: gcmSenderID) options.bundleID = Constants.Options.bundleID options.apiKey = Constants.Options.apiKey options.clientID = Constants.Options.clientID options.trackingID = Constants.Options.trackingID options.projectID = Constants.Options.projectID options.databaseURL = Constants.Options.databaseURL options.storageBucket = Constants.Options.storageBucket options.appGroupID = Constants.Options.appGroupID assertOptionsMatchDefaultOptions(options: options) } func testEditingCustomOptions() { let googleAppID = Constants.Options.googleAppID let gcmSenderID = Constants.Options.gcmSenderID let options = FirebaseOptions(googleAppID: googleAppID, gcmSenderID: gcmSenderID) let newGCMSenderID = "newgcmSenderID" options.gcmSenderID = newGCMSenderID XCTAssertEqual(options.gcmSenderID, newGCMSenderID) let newGoogleAppID = "newGoogleAppID" options.googleAppID = newGoogleAppID XCTAssertEqual(options.googleAppID, newGoogleAppID) XCTAssertNil(options.deepLinkURLScheme) options.deepLinkURLScheme = Constants.Options.deepLinkURLScheme XCTAssertEqual(options.deepLinkURLScheme, Constants.Options.deepLinkURLScheme) XCTAssertNil(options.androidClientID) options.androidClientID = Constants.Options.androidClientID XCTAssertEqual(options.androidClientID, Constants.Options.androidClientID) XCTAssertNil(options.appGroupID) options.appGroupID = Constants.Options.appGroupID XCTAssertEqual(options.appGroupID, Constants.Options.appGroupID) } func testCopyingProperties() { let googleAppID = Constants.Options.googleAppID let gcmSenderID = Constants.Options.gcmSenderID let options = FirebaseOptions(googleAppID: googleAppID, gcmSenderID: gcmSenderID) var apiKey = "123456789" options.apiKey = apiKey XCTAssertEqual(options.apiKey, apiKey) apiKey = "000000000" XCTAssertNotEqual(options.apiKey, apiKey) var deepLinkURLScheme = "comdeeplinkurl" options.deepLinkURLScheme = deepLinkURLScheme XCTAssertEqual(options.deepLinkURLScheme, deepLinkURLScheme) deepLinkURLScheme = "comlinkurl" XCTAssertNotEqual(options.deepLinkURLScheme, deepLinkURLScheme) } func testOptionsEquality() throws { let defaultOptions1 = try XCTUnwrap( FirebaseOptions.defaultOptions(), "Default options could not be unwrapped" ) let defaultOptions2 = try XCTUnwrap( FirebaseOptions.defaultOptions(), "Default options could not be unwrapped" ) XCTAssertEqual(defaultOptions1.hash, defaultOptions2.hash) XCTAssertTrue(defaultOptions1.isEqual(defaultOptions2)) let plainOptions = FirebaseOptions(googleAppID: Constants.Options.googleAppID, gcmSenderID: Constants.Options.gcmSenderID) XCTAssertFalse(plainOptions.isEqual(defaultOptions1)) } // MARK: - Helpers private func assertOptionsMatchDefaultOptions(options: FirebaseOptions) { XCTAssertEqual(options.apiKey, Constants.Options.apiKey) XCTAssertEqual(options.bundleID, Constants.Options.bundleID) XCTAssertEqual(options.clientID, Constants.Options.clientID) XCTAssertEqual(options.trackingID, Constants.Options.trackingID) XCTAssertEqual(options.gcmSenderID, Constants.Options.gcmSenderID) XCTAssertEqual(options.projectID, Constants.Options.projectID) XCTAssertNil(options.androidClientID) XCTAssertEqual(options.googleAppID, Constants.Options.googleAppID) XCTAssertEqual(options.databaseURL, Constants.Options.databaseURL) XCTAssertNil(options.deepLinkURLScheme) XCTAssertEqual(options.storageBucket, Constants.Options.storageBucket) XCTAssertNil(options.appGroupID) } private func assertNullableOptionsAreEmpty(options: FirebaseOptions) { XCTAssertNil(options.apiKey) XCTAssertNil(options.clientID) XCTAssertNil(options.trackingID) XCTAssertNil(options.projectID) XCTAssertNil(options.androidClientID) XCTAssertNil(options.databaseURL) XCTAssertNil(options.deepLinkURLScheme) XCTAssertNil(options.storageBucket) XCTAssertNil(options.appGroupID) } }
apache-2.0
ab068d1952a2442b5d29283542185628
36.72093
89
0.749075
4.813056
false
true
false
false
wireapp/wire-ios-sync-engine
Source/UserSession/PushNotificationStatus.swift
1
4228
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireDataModel private let zmLog = ZMSLog(tag: "PushNotificationStatus") extension UUID { func compare(withType1 uuid: UUID) -> ComparisonResult { return (self as NSUUID).compare(withType1UUID: uuid as NSUUID) } } @objcMembers open class PushNotificationStatus: NSObject { private var eventIdRanking = NSMutableOrderedSet() private var completionHandlers: [UUID: () -> Void] = [:] private let managedObjectContext: NSManagedObjectContext public var hasEventsToFetch: Bool { return eventIdRanking.count > 0 } public init(managedObjectContext: NSManagedObjectContext) { self.managedObjectContext = managedObjectContext } /// Schedule to fetch an event with a given UUID /// /// - parameter eventId: UUID of the event to fetch /// - parameter completionHandler: The completion handler will be run when event has been downloaded and when there's no more events to fetch @objc(fetchEventId:completionHandler:) public func fetch(eventId: UUID, completionHandler: @escaping () -> Void) { guard eventId.isType1UUID else { return zmLog.error("Attempt to fetch event id not conforming to UUID type1: \(eventId)") } if lastEventIdIsNewerThan(lastEventId: managedObjectContext.zm_lastNotificationID, eventId: eventId) { // We have already fetched the event and will therefore immediately call the completion handler Logging.eventProcessing.info("Already fetched event with [\(eventId)]") return completionHandler() } Logging.eventProcessing.info("Scheduling to fetch events notified by push [\(eventId)]") eventIdRanking.add(eventId) completionHandlers[eventId] = completionHandler RequestAvailableNotification.notifyNewRequestsAvailable(nil) } /// Report events that has successfully been downloaded from the notification stream /// /// - parameter eventIds: List of UUIDs for events that been downloaded /// - parameter finished: True when when all available events have been downloaded @objc(didFetchEventIds:lastEventId:finished:) public func didFetch(eventIds: [UUID], lastEventId: UUID?, finished: Bool) { let highestRankingEventId = eventIdRanking.firstObject as? UUID highestRankingEventId.apply(eventIdRanking.remove) eventIdRanking.minusSet(Set<UUID>(eventIds)) guard finished else { return } Logging.eventProcessing.info("Finished to fetching all available events") // We take all events that are older than or equal to lastEventId and add highest ranking event ID for eventId in completionHandlers.keys.filter({ self.lastEventIdIsNewerThan(lastEventId: lastEventId, eventId: $0) || highestRankingEventId == $0 }) { let completionHandler = completionHandlers.removeValue(forKey: eventId) completionHandler?() } } /// Report that events couldn't be fetched due to a permanent error public func didFailToFetchEvents() { for completionHandler in completionHandlers.values { completionHandler() } eventIdRanking.removeAllObjects() completionHandlers.removeAll() } private func lastEventIdIsNewerThan(lastEventId: UUID?, eventId: UUID) -> Bool { guard let order = lastEventId?.compare(withType1: eventId) else { return false } return order == .orderedDescending || order == .orderedSame } }
gpl-3.0
cd3068da349d7979e0fa650599269577
38.886792
159
0.709792
4.997636
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Settings/CustomSearchViewController.swift
2
11002
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import UIKit import Shared import SnapKit import Storage class CustomSearchError: MaybeErrorType { enum Reason { case DuplicateEngine, FormInput } var reason: Reason! internal var description: String { return "Search Engine Not Added" } init(_ reason: Reason) { self.reason = reason } } class CustomSearchViewController: SettingsTableViewController { fileprivate var urlString: String? fileprivate var engineTitle = "" fileprivate lazy var spinnerView: UIActivityIndicatorView = { let spinner = UIActivityIndicatorView(style: .medium) spinner.color = themeManager.currentTheme.colors.iconSpinner spinner.hidesWhenStopped = true return spinner }() override func viewDidLoad() { super.viewDidLoad() title = .SettingsAddCustomEngineTitle view.addSubview(spinnerView) spinnerView.snp.makeConstraints { make in make.center.equalTo(self.view.snp.center) } } var successCallback: (() -> Void)? fileprivate func addSearchEngine(_ searchQuery: String, title: String) { spinnerView.startAnimating() let trimmedQuery = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines) let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines) createEngine(forQuery: trimmedQuery, andName: trimmedTitle).uponQueue(.main) { result in self.spinnerView.stopAnimating() guard let engine = result.successValue else { let alert: UIAlertController let error = result.failureValue as? CustomSearchError alert = (error?.reason == .DuplicateEngine) ? ThirdPartySearchAlerts.duplicateCustomEngine() : ThirdPartySearchAlerts.incorrectCustomEngineForm() self.navigationItem.rightBarButtonItem?.isEnabled = true self.present(alert, animated: true, completion: nil) return } self.profile.searchEngines.addSearchEngine(engine) CATransaction.begin() // Use transaction to call callback after animation has been completed CATransaction.setCompletionBlock(self.successCallback) _ = self.navigationController?.popViewController(animated: true) CATransaction.commit() } } func createEngine(forQuery query: String, andName name: String) -> Deferred<Maybe<OpenSearchEngine>> { let deferred = Deferred<Maybe<OpenSearchEngine>>() guard let template = getSearchTemplate(withString: query), let url = URL(string: template.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!), url.isWebPage() else { deferred.fill(Maybe(failure: CustomSearchError(.FormInput))) return deferred } // ensure we haven't already stored this template guard engineExists(name: name, template: template) == false else { deferred.fill(Maybe(failure: CustomSearchError(.DuplicateEngine))) return deferred } FaviconFetcher.fetchFavImageForURL(forURL: url, profile: profile).uponQueue(.main) { result in let image = result.successValue ?? FaviconFetcher.letter(forUrl: url) let engine = OpenSearchEngine(engineID: nil, shortName: name, image: image, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true) // Make sure a valid scheme is used let url = engine.searchURLForQuery("test") let maybe = (url == nil) ? Maybe(failure: CustomSearchError(.FormInput)) : Maybe(success: engine) deferred.fill(maybe) } return deferred } private func engineExists(name: String, template: String) -> Bool { return profile.searchEngines.orderedEngines.contains { (engine) -> Bool in return engine.shortName == name || engine.searchTemplate == template } } func getSearchTemplate(withString query: String) -> String? { let SearchTermComponent = "%s" // Placeholder in User Entered String let placeholder = "{searchTerms}" // Placeholder looked for when using Custom Search Engine in OpenSearch.swift if query.contains(SearchTermComponent) { return query.replacingOccurrences(of: SearchTermComponent, with: placeholder) } return nil } func updateSaveButton() { let isEnabled = !self.engineTitle.isEmptyOrWhitespace() && !(self.urlString?.isEmptyOrWhitespace() ?? true) self.navigationItem.rightBarButtonItem?.isEnabled = isEnabled } override func generateSettings() -> [SettingSection] { func URLFromString(_ string: String?) -> URL? { guard let string = string else { return nil } return URL(string: string) } let titleField = CustomSearchEngineTextView( placeholder: .SettingsAddCustomEngineTitlePlaceholder, settingIsValid: { text in if let text = text { return !text.isEmpty } return false }, settingDidChange: {fieldText in guard let title = fieldText else { return } self.engineTitle = title self.updateSaveButton() }) titleField.textField.text = engineTitle titleField.textField.accessibilityIdentifier = "customEngineTitle" let urlField = CustomSearchEngineTextView( placeholder: .SettingsAddCustomEngineURLPlaceholder, height: 133, keyboardType: .URL, settingIsValid: { text in // Can check url text text validity here. return true }, settingDidChange: {fieldText in self.urlString = fieldText self.updateSaveButton() }) urlField.textField.autocapitalizationType = .none urlField.textField.text = urlString urlField.textField.accessibilityIdentifier = "customEngineUrl" let settings: [SettingSection] = [ SettingSection(title: NSAttributedString(string: .SettingsAddCustomEngineTitleLabel), children: [titleField]), SettingSection(title: NSAttributedString(string: .SettingsAddCustomEngineURLLabel), footerTitle: NSAttributedString(string: "https://youtube.com/search?q=%s"), children: [urlField]) ] self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(self.addCustomSearchEngine)) self.navigationItem.rightBarButtonItem?.accessibilityIdentifier = "customEngineSaveButton" self.navigationItem.rightBarButtonItem?.isEnabled = false return settings } @objc func addCustomSearchEngine(_ nav: UINavigationController?) { self.view.endEditing(true) if let url = self.urlString { navigationItem.rightBarButtonItem?.isEnabled = false self.addSearchEngine(url, title: self.engineTitle) } } } class CustomSearchEngineTextView: Setting, UITextViewDelegate { fileprivate let Padding: CGFloat = 8 fileprivate let TextLabelHeight: CGFloat = 44 fileprivate var TextLabelWidth: CGFloat { let width = textField.frame.width == 0 ? 360 : textField.frame.width return width } fileprivate var TextFieldHeight: CGFloat = 44 fileprivate let defaultValue: String? fileprivate let placeholder: String fileprivate let settingDidChange: ((String?) -> Void)? fileprivate let settingIsValid: ((String?) -> Bool)? let textField = UITextView() let placeholderLabel = UILabel() var keyboardType: UIKeyboardType = .default init( defaultValue: String? = nil, placeholder: String, height: CGFloat = 44, keyboardType: UIKeyboardType = .default, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil ) { self.defaultValue = defaultValue self.TextFieldHeight = height self.settingDidChange = settingDidChange self.settingIsValid = isValueValid self.placeholder = placeholder self.keyboardType = keyboardType textField.addSubview(placeholderLabel) super.init(cellHeight: TextFieldHeight) } override func onConfigureCell(_ cell: UITableViewCell, theme: Theme) { super.onConfigureCell(cell, theme: theme) if let id = accessibilityIdentifier { textField.accessibilityIdentifier = id + "TextField" } placeholderLabel.adjustsFontSizeToFitWidth = true placeholderLabel.textColor = theme.colors.textSecondary placeholderLabel.text = placeholder placeholderLabel.isHidden = !textField.text.isEmpty placeholderLabel.frame = CGRect(width: TextLabelWidth, height: TextLabelHeight) textField.font = placeholderLabel.font textField.textContainer.lineFragmentPadding = 0 textField.keyboardType = keyboardType if keyboardType == .default { textField.autocapitalizationType = .words } textField.autocorrectionType = .no textField.delegate = self textField.backgroundColor = theme.colors.layer2 textField.textColor = theme.colors.textPrimary cell.isUserInteractionEnabled = true cell.accessibilityTraits = UIAccessibilityTraits.none cell.contentView.addSubview(textField) cell.selectionStyle = .none textField.snp.makeConstraints { make in make.height.equalTo(TextFieldHeight) make.left.right.equalTo(cell.contentView).inset(Padding) } } override func onClick(_ navigationController: UINavigationController?) { textField.becomeFirstResponder() } fileprivate func isValid(_ value: String?) -> Bool { guard let test = settingIsValid else { return true } return test(prepareValidValue(userInput: value)) } func prepareValidValue(userInput value: String?) -> String? { return value } func textViewDidBeginEditing(_ textView: UITextView) { placeholderLabel.isHidden = !textField.text.isEmpty } func textViewDidChange(_ textView: UITextView) { placeholderLabel.isHidden = !textField.text.isEmpty settingDidChange?(textView.text) let color = isValid(textField.text) ? theme.colors.textPrimary : theme.colors.textWarning textField.textColor = color } func textViewDidEndEditing(_ textView: UITextView) { placeholderLabel.isHidden = !textField.text.isEmpty settingDidChange?(textView.text) } }
mpl-2.0
df3e864ca3a990d987d6da7a522ada5e
38.014184
193
0.664879
5.481814
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/ContextMenuItem+CodeImage.swift
1
2236
// // ContextMenuItem+CodeImage.swift // Wuakup // // Created by Guillermo Gutiérrez on 18/02/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import Foundation extension ContextMenuItem { convenience init(codeImage: CodeImage, size: CGSize, highlightedImage: CodeImage? = .none, titleText: String? = .none) { let frame = CGRect(origin: CGPoint.zero, size: size) let itemView = UIImageView(image: codeImage.getImage(frame)) itemView.frame = frame var highlightedView: UIImageView? if let highlightedImage = highlightedImage { highlightedView = UIImageView(image: highlightedImage.getImage(frame)) highlightedView!.frame = frame } self.init(itemView: itemView, highlightedItemView: highlightedView, titleText: titleText) } convenience init(codeIcon: CodeIcon, color: UIColor, size: CGSize, highlightedColor: UIColor? = .none, titleText: String? = .none) { let codeImage = codeIcon.getCodeImage(forColor: color) let highlightedImage = highlightedColor.map{ codeIcon.getCodeImage(forColor: $0) } self.init(codeImage: codeImage, size: size, highlightedImage: highlightedImage, titleText: titleText) } convenience init(iconIdentifier: String, color: UIColor, size: CGSize, highlightedColor: UIColor? = .none, titleText: String? = .none) { let codeIcon = CodeIcon(iconIdentifier: iconIdentifier) self.init(codeIcon: codeIcon, color: color, size: size, highlightedColor: highlightedColor, titleText: titleText) } class func withCustomView(_ iconIdentifier: String, titleText: String? = .none) -> ContextMenuItem { let view = loadViewFromNib("ContextItemView") as! ContextItemView view.iconIdentifier = iconIdentifier let highlightedView = loadViewFromNib("ContextItemView") as! ContextItemView highlightedView.iconIdentifier = iconIdentifier highlightedView.highlighted = true let menuItem = ContextMenuItem(itemView: view, highlightedItemView: highlightedView, titleText: titleText) menuItem.identifier = iconIdentifier return menuItem } }
mit
1425d48841a40a05fb5cac762bc8998a
43.7
140
0.695302
4.806452
false
false
false
false
adrfer/swift
stdlib/public/core/Collection.swift
1
27974
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @available(*, unavailable, message="access the 'count' property on the collection") public func count <T : CollectionType>(x: T) -> T.Index.Distance { fatalError("unavailable function can't be called") } /// A protocol representing the minimal requirements of /// `CollectionType`. /// /// - Note: In most cases, it's best to ignore this protocol and use /// `CollectionType` instead, as it has a more complete interface. // // This protocol is almost an implementation detail of the standard // library; it is used to deduce things like the `SubSequence` and // `Generator` type from a minimal collection, but it is also used in // exposed places like as a constraint on IndexingGenerator. public protocol Indexable { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. associatedtype Index : ForwardIndexType /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. /// /// - Complexity: O(1) var startIndex: Index { get } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. /// /// - Complexity: O(1) var endIndex: Index { get } // The declaration of _Element and subscript here is a trick used to // break a cyclic conformance/deduction that Swift can't handle. We // need something other than a CollectionType.Generator.Element that can // be used as IndexingGenerator<T>'s Element. Here we arrange for the // CollectionType itself to have an Element type that's deducible from // its subscript. Ideally we'd like to constrain this // Element to be the same as CollectionType.Generator.Element (see // below), but we have no way of expressing it today. associatedtype _Element /// Returns the element at the given `position`. /// /// - Complexity: O(1) subscript(position: Index) -> _Element { get } } public protocol MutableIndexable { associatedtype Index : ForwardIndexType var startIndex: Index { get } var endIndex: Index { get } associatedtype _Element subscript(position: Index) -> _Element { get set } } /// A *generator* for an arbitrary *collection*. Provided `C` /// conforms to the other requirements of `Indexable`, /// `IndexingGenerator<C>` can be used as the result of `C`'s /// `generate()` method. For example: /// /// struct MyCollection : CollectionType { /// struct Index : ForwardIndexType { /* implementation hidden */ } /// subscript(i: Index) -> MyElement { /* implementation hidden */ } /// func generate() -> IndexingGenerator<MyCollection> { // <=== /// return IndexingGenerator(self) /// } /// } public struct IndexingGenerator<Elements : Indexable> : GeneratorType, SequenceType { /// Create a *generator* over the given collection. public init(_ elements: Elements) { self._elements = elements self._position = elements.startIndex } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> Elements._Element? { if _position == _elements.endIndex { return nil } let element = _elements[_position] _position._successorInPlace() return element } internal let _elements: Elements internal var _position: Elements.Index } /// A multi-pass *sequence* with addressable positions. /// /// Positions are represented by an associated `Index` type. Whereas /// an arbitrary *sequence* may be consumed as it is traversed, a /// *collection* is multi-pass: any element may be revisited merely by /// saving its index. /// /// The sequence view of the elements is identical to the collection /// view. In other words, the following code binds the same series of /// values to `x` as does `for x in self {}`: /// /// for i in startIndex..<endIndex { /// let x = self[i] /// } public protocol CollectionType : Indexable, SequenceType { /// A type that provides the *sequence*'s iteration interface and /// encapsulates its iteration state. /// /// By default, a `CollectionType` satisfies `SequenceType` by /// supplying an `IndexingGenerator` as its associated `Generator` /// type. associatedtype Generator: GeneratorType = IndexingGenerator<Self> // FIXME: Needed here so that the Generator is properly deduced from // a custom generate() function. Otherwise we get an // IndexingGenerator. <rdar://problem/21539115> func generate() -> Generator // FIXME: should be constrained to CollectionType // (<rdar://problem/20715009> Implement recursive protocol // constraints) /// A `SequenceType` that can represent a contiguous subrange of `self`'s /// elements. /// /// - Note: This associated type appears as a requirement in /// `SequenceType`, but is restated here with stricter /// constraints: in a `CollectionType`, the `SubSequence` should /// also be a `CollectionType`. associatedtype SubSequence: Indexable, SequenceType = Slice<Self> /// Returns the element at the given `position`. subscript(position: Index) -> Generator.Element { get } /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) subscript(bounds: Range<Index>) -> SubSequence { get } /// Returns `self[startIndex..<end]` /// /// - Complexity: O(1) @warn_unused_result func prefixUpTo(end: Index) -> SubSequence /// Returns `self[start..<endIndex]` /// /// - Complexity: O(1) @warn_unused_result func suffixFrom(start: Index) -> SubSequence /// Returns `prefixUpTo(position.successor())` /// /// - Complexity: O(1) @warn_unused_result func prefixThrough(position: Index) -> SubSequence /// Returns `true` iff `self` is empty. var isEmpty: Bool { get } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndexType`; /// O(N) otherwise. var count: Index.Distance { get } // The following requirement enables dispatching for indexOf when // the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; /// `nil` otherwise. /// /// - Complexity: O(N). @warn_unused_result func _customIndexOfEquatableElement(element: Generator.Element) -> Index?? /// Returns the first element of `self`, or `nil` if `self` is empty. var first: Generator.Element? { get } } /// Supply the default `generate()` method for `CollectionType` models /// that accept the default associated `Generator`, /// `IndexingGenerator<Self>`. extension CollectionType where Generator == IndexingGenerator<Self> { public func generate() -> IndexingGenerator<Self> { return IndexingGenerator(self) } } /// Supply the default "slicing" `subscript` for `CollectionType` models /// that accept the default associated `SubSequence`, `Slice<Self>`. extension CollectionType where SubSequence == Slice<Self> { public subscript(bounds: Range<Index>) -> Slice<Self> { Index._failEarlyRangeCheck2( bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return Slice(base: self, bounds: bounds) } } extension CollectionType where SubSequence == Self { /// If `!self.isEmpty`, remove the first element and return it, otherwise /// return `nil`. /// /// - Complexity: O(`self.count`) @warn_unused_result public mutating func popFirst() -> Generator.Element? { guard !isEmpty else { return nil } let element = first! self = self[startIndex.successor()..<endIndex] return element } /// If `!self.isEmpty`, remove the last element and return it, otherwise /// return `nil`. /// /// - Complexity: O(`self.count`) @warn_unused_result public mutating func popLast() -> Generator.Element? { guard !isEmpty else { return nil } let lastElementIndex = startIndex.advancedBy(numericCast(count) - 1) let element = self[lastElementIndex] self = self[startIndex..<lastElementIndex] return element } } /// Default implementations of core requirements extension CollectionType { /// Returns `true` iff `self` is empty. /// /// - Complexity: O(1) public var isEmpty: Bool { return startIndex == endIndex } /// Returns the first element of `self`, or `nil` if `self` is empty. /// /// - Complexity: O(1) public var first: Generator.Element? { // NB: Accessing `startIndex` may not be O(1) for some lazy collections, // so instead of testing `isEmpty` and then returning the first element, // we'll just rely on the fact that the generator always yields the // first element first. var gen = generate() return gen.next() } /// Returns a value less than or equal to the number of elements in /// `self`, *nondestructively*. /// /// - Complexity: O(N). public func underestimateCount() -> Int { return numericCast(count) } /// Returns the number of elements. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndexType`; /// O(N) otherwise. public var count: Index.Distance { return startIndex.distanceTo(endIndex) } /// Customization point for `SequenceType.indexOf()`. /// /// Define this method if the collection can find an element in less than /// O(N) by exploiting collection-specific knowledge. /// /// - Returns: `nil` if a linear search should be attempted instead, /// `Optional(nil)` if the element was not found, or /// `Optional(Optional(index))` if an element was found. /// /// - Complexity: O(N). @warn_unused_result public // dispatching func _customIndexOfEquatableElement(_: Generator.Element) -> Index?? { return nil } } //===----------------------------------------------------------------------===// // Default implementations for CollectionType //===----------------------------------------------------------------------===// extension CollectionType { /// Return an `Array` containing the results of mapping `transform` /// over `self`. /// /// - Complexity: O(N). @warn_unused_result public func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] { let count: Int = numericCast(self.count) if count == 0 { return [] } var result = ContiguousArray<T>() result.reserveCapacity(count) var i = self.startIndex for _ in 0..<count { result.append(try transform(self[i])) i = i.successor() } _expectEnd(i, self) return Array(result) } /// Returns a subsequence containing all but the first `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropFirst(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let start = startIndex.advancedBy(numericCast(n), limit: endIndex) return self[start..<endIndex] } /// Returns a subsequence containing all but the last `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func dropLast(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let amount = max(0, numericCast(count) - n) let end = startIndex.advancedBy(numericCast(amount), limit: endIndex) return self[startIndex..<end] } /// Returns a subsequence, up to `maxLength` in length, containing the /// initial elements. /// /// If `maxLength` exceeds `self.count`, the result contains all /// the elements of `self`. /// /// - Requires: `maxLength >= 0` /// - Complexity: O(`maxLength`) @warn_unused_result public func prefix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = startIndex.advancedBy(numericCast(maxLength), limit: endIndex) return self[startIndex..<end] } /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `s`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `s`. /// /// - Requires: `maxLength >= 0` /// - Complexity: O(`self.count`) @warn_unused_result public func suffix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = max(0, numericCast(count) - maxLength) let start = startIndex.advancedBy(numericCast(amount), limit: endIndex) return self[start..<endIndex] } /// Returns `self[startIndex..<end]` /// /// - Complexity: O(1) @warn_unused_result public func prefixUpTo(end: Index) -> SubSequence { return self[startIndex..<end] } /// Returns `self[start..<endIndex]` /// /// - Complexity: O(1) @warn_unused_result public func suffixFrom(start: Index) -> SubSequence { return self[start..<endIndex] } /// Returns `prefixUpTo(position.successor())` /// /// - Complexity: O(1) @warn_unused_result public func prefixThrough(position: Index) -> SubSequence { return prefixUpTo(position.successor()) } /// Returns the maximal `SubSequence`s of `self`, in order, that /// don't contain elements satisfying the predicate `isSeparator`. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result public func split( maxSplit: Int = Int.max, allowEmptySlices: Bool = false, @noescape isSeparator: (Generator.Element) throws -> Bool ) rethrows -> [SubSequence] { _precondition(maxSplit >= 0, "Must take zero or more splits") var result: [SubSequence] = [] var subSequenceStart: Index = startIndex func appendSubsequence(end end: Index) -> Bool { if subSequenceStart == end && !allowEmptySlices { return false } result.append(self[subSequenceStart..<end]) return true } if maxSplit == 0 || isEmpty { appendSubsequence(end: endIndex) return result } var subSequenceEnd = subSequenceStart let cachedEndIndex = endIndex while subSequenceEnd != cachedEndIndex { if try isSeparator(self[subSequenceEnd]) { let didAppend = appendSubsequence(end: subSequenceEnd) subSequenceEnd._successorInPlace() subSequenceStart = subSequenceEnd if didAppend && result.count == maxSplit { break } continue } subSequenceEnd._successorInPlace() } if subSequenceStart != cachedEndIndex || allowEmptySlices { result.append(self[subSequenceStart..<cachedEndIndex]) } return result } } extension CollectionType where Generator.Element : Equatable { /// Returns the maximal `SubSequence`s of `self`, in order, around a /// `separator` element. /// /// - Parameter maxSplit: The maximum number of `SubSequence`s to /// return, minus 1. /// If `maxSplit + 1` `SubSequence`s are returned, the last one is /// a suffix of `self` containing the remaining elements. /// The default value is `Int.max`. /// /// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence` /// is produced in the result for each pair of consecutive elements /// satisfying `isSeparator`. /// The default value is `false`. /// /// - Requires: `maxSplit >= 0` @warn_unused_result public func split( separator: Generator.Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [SubSequence] { return split(maxSplit, allowEmptySlices: allowEmptySlices, isSeparator: { $0 == separator }) } } extension CollectionType where Index : BidirectionalIndexType { /// Returns a subsequence containing all but the last `n` elements. /// /// - Requires: `n >= 0` /// - Complexity: O(`n`) @warn_unused_result public func dropLast(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let end = endIndex.advancedBy(numericCast(-n), limit: startIndex) return self[startIndex..<end] } /// Returns a slice, up to `maxLength` in length, containing the /// final elements of `s`. /// /// If `maxLength` exceeds `s.count`, the result contains all /// the elements of `s`. /// /// - Requires: `maxLength >= 0` /// - Complexity: O(`maxLength`) @warn_unused_result public func suffix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = endIndex.advancedBy(numericCast(-maxLength), limit: startIndex) return self[start..<endIndex] } } extension CollectionType where SubSequence == Self { /// Remove the element at `startIndex` and return it. /// /// - Complexity: O(1) /// - Requires: `!self.isEmpty`. public mutating func removeFirst() -> Generator.Element { _precondition(!isEmpty, "can't remove items from an empty collection") let element = first! self = self[startIndex.successor()..<endIndex] return element } /// Remove the first `n` elements. /// /// - Complexity: /// - O(1) if `Index` conforms to `RandomAccessIndexType` /// - O(n) otherwise /// - Requires: `n >= 0 && self.count >= n`. public mutating func removeFirst(n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex.advancedBy(numericCast(n))..<endIndex] } } extension CollectionType where SubSequence == Self, Index : BidirectionalIndexType { /// Remove an element from the end. /// /// - Complexity: O(1) /// - Requires: `!self.isEmpty` public mutating func removeLast() -> Generator.Element { let element = last! self = self[startIndex..<endIndex.predecessor()] return element } /// Remove the last `n` elements. /// /// - Complexity: /// - O(1) if `Index` conforms to `RandomAccessIndexType` /// - O(n) otherwise /// - Requires: `n >= 0 && self.count >= n`. public mutating func removeLast(n: Int) { if n == 0 { return } _precondition(n >= 0, "number of elements to remove should be non-negative") _precondition(count >= numericCast(n), "can't remove more items from a collection than it contains") self = self[startIndex..<endIndex.advancedBy(numericCast(-n))] } } extension SequenceType where Self : _ArrayType, Self.Element == Self.Generator.Element { // A fast implementation for when you are backed by a contiguous array. public func _initializeTo(ptr: UnsafeMutablePointer<Generator.Element>) -> UnsafeMutablePointer<Generator.Element> { let s = self._baseAddressIfContiguous if s != nil { let count = self.count ptr.initializeFrom(s, count: count) _fixLifetime(self._owner) return ptr + count } else { var p = ptr for x in self { p.initialize(x) p += 1 } return p } } } extension CollectionType { public func _preprocessingPass<R>(@noescape preprocess: (Self) -> R) -> R? { return preprocess(self) } } /// Returns `true` iff `x` is empty. @available(*, unavailable, message="access the 'isEmpty' property on the collection") public func isEmpty<C: CollectionType>(x: C) -> Bool { fatalError("unavailable function can't be called") } /// Returns the first element of `x`, or `nil` if `x` is empty. @available(*, unavailable, message="access the 'first' property on the collection") public func first<C: CollectionType>(x: C) -> C.Generator.Element? { fatalError("unavailable function can't be called") } /// Returns the last element of `x`, or `nil` if `x` is empty. @available(*, unavailable, message="access the 'last' property on the collection") public func last<C: CollectionType where C.Index: BidirectionalIndexType>( x: C ) -> C.Generator.Element? { fatalError("unavailable function can't be called") } /// A *collection* that supports subscript assignment. /// /// For any instance `a` of a type conforming to /// `MutableCollectionType`, : /// /// a[i] = x /// let y = a[i] /// /// is equivalent to: /// /// a[i] = x /// let y = x /// public protocol MutableCollectionType : MutableIndexable, CollectionType { // FIXME: should be constrained to MutableCollectionType // (<rdar://problem/20715009> Implement recursive protocol // constraints) associatedtype SubSequence : CollectionType /*: MutableCollectionType*/ = MutableSlice<Self> /// Access the element at `position`. /// /// - Requires: `position` indicates a valid position in `self` and /// `position != endIndex`. /// /// - Complexity: O(1) subscript(position: Index) -> Generator.Element {get set} /// Returns a collection representing a contiguous sub-range of /// `self`'s elements. /// /// - Complexity: O(1) for the getter, O(`bounds.count`) for the setter. subscript(bounds: Range<Index>) -> SubSequence {get set} /// Call `body(p)`, where `p` is a pointer to the collection's /// mutable contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of mutable contiguous storage, `body` is not /// called and `nil` is returned. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func _withUnsafeMutableBufferPointerIfSupported<R>( @noescape body: (UnsafeMutablePointer<Generator.Element>, Int) throws -> R ) rethrows -> R? // FIXME: the signature should use UnsafeMutableBufferPointer, but the // compiler can't handle that. // // <rdar://problem/21933004> Restore the signature of // _withUnsafeMutableBufferPointerIfSupported() that mentions // UnsafeMutableBufferPointer } extension MutableCollectionType { public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( @noescape body: (UnsafeMutablePointer<Generator.Element>, Int) throws -> R ) rethrows -> R? { return nil } public subscript(bounds: Range<Index>) -> MutableSlice<Self> { get { Index._failEarlyRangeCheck2( bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return MutableSlice(base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } internal func _writeBackMutableSlice< Collection : MutableCollectionType, Slice_ : CollectionType where Collection._Element == Slice_.Generator.Element, Collection.Index == Slice_.Index >(inout self_: Collection, bounds: Range<Collection.Index>, slice: Slice_) { Collection.Index._failEarlyRangeCheck2( bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: self_.startIndex, boundsEnd: self_.endIndex) // FIXME(performance): can we use // _withUnsafeMutableBufferPointerIfSupported? Would that create inout // aliasing violations if the newValue points to the same buffer? var selfElementIndex = bounds.startIndex let selfElementsEndIndex = bounds.endIndex var newElementIndex = slice.startIndex let newElementsEndIndex = slice.endIndex while selfElementIndex != selfElementsEndIndex && newElementIndex != newElementsEndIndex { self_[selfElementIndex] = slice[newElementIndex] selfElementIndex._successorInPlace() newElementIndex._successorInPlace() } _precondition( selfElementIndex == selfElementsEndIndex, "Cannot replace a slice of a MutableCollectionType with a slice of a larger size") _precondition( newElementIndex == newElementsEndIndex, "Cannot replace a slice of a MutableCollectionType with a slice of a smaller size") } /// Returns the range of `x`'s valid index values. /// /// The result's `endIndex` is the same as that of `x`. Because /// `Range` is half-open, iterating the values of the result produces /// all valid subscript arguments for `x`, omitting its `endIndex`. @available(*, unavailable, message="access the 'indices' property on the collection") public func indices< C : CollectionType>(x: C) -> Range<C.Index> { fatalError("unavailable function can't be called") } /// A *generator* that adapts a *collection* `C` and any *sequence* of /// its `Index` type to present the collection's elements in a /// permuted order. public struct PermutationGenerator< C: CollectionType, Indices: SequenceType where C.Index == Indices.Generator.Element > : GeneratorType, SequenceType { var seq : C var indices : Indices.Generator /// The type of element returned by `next()`. public typealias Element = C.Generator.Element /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> Element? { return indices.next().map { seq[$0] } } /// Construct a *generator* over a permutation of `elements` given /// by `indices`. /// /// - Requires: `elements[i]` is valid for every `i` in `indices`. public init(elements: C, indices: Indices) { self.seq = elements self.indices = indices.generate() } } /// A *collection* with mutable slices. /// /// For example, /// /// x[i..<j] = someExpression /// x[i..<j].mutatingMethod() public protocol MutableSliceable : CollectionType, MutableCollectionType { subscript(_: Range<Index>) -> SubSequence { get set } } @available(*, unavailable, message="Use the dropFirst() method instead.") public func dropFirst<Seq : CollectionType>(s: Seq) -> Seq.SubSequence { fatalError("unavailable function can't be called") } @available(*, unavailable, message="Use the dropLast() method instead.") public func dropLast< S : CollectionType where S.Index: BidirectionalIndexType >(s: S) -> S.SubSequence { fatalError("unavailable function can't be called") } @available(*, unavailable, message="Use the prefix() method.") public func prefix<S : CollectionType>(s: S, _ maxLength: Int) -> S.SubSequence { fatalError("unavailable function can't be called") } @available(*, unavailable, message="Use the suffix() method instead.") public func suffix< S : CollectionType where S.Index: BidirectionalIndexType >(s: S, _ maxLength: Int) -> S.SubSequence { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="CollectionType") public struct Sliceable {}
apache-2.0
67e4f43f03d4d83676619e7d512f3558
32.825877
93
0.668228
4.264979
false
false
false
false
frootloops/swift
stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift
4
4287
//===--- SwiftPrivateLibcExtras.swift -------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftPrivate #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) import Glibc #elseif os(Windows) import ucrt #endif #if !os(Windows) public func _stdlib_mkstemps(_ template: inout String, _ suffixlen: CInt) -> CInt { #if os(Android) || os(Haiku) preconditionFailure("mkstemps doesn't work on your platform") #else var utf8CStr = template.utf8CString let (fd, fileName) = utf8CStr.withUnsafeMutableBufferPointer { (utf8CStr) -> (CInt, String) in let fd = mkstemps(utf8CStr.baseAddress!, suffixlen) let fileName = String(cString: utf8CStr.baseAddress!) return (fd, fileName) } template = fileName return fd #endif } #endif public var _stdlib_FD_SETSIZE: CInt { return 1024 } public struct _stdlib_fd_set { var _data: [UInt] static var _wordBits: Int { return MemoryLayout<UInt>.size * 8 } public init() { _data = [UInt]( repeating: 0, count: Int(_stdlib_FD_SETSIZE) / _stdlib_fd_set._wordBits) } public func isset(_ fd: CInt) -> Bool { let fdInt = Int(fd) return ( _data[fdInt / _stdlib_fd_set._wordBits] & UInt(1 << (fdInt % _stdlib_fd_set._wordBits)) ) != 0 } public mutating func set(_ fd: CInt) { let fdInt = Int(fd) _data[fdInt / _stdlib_fd_set._wordBits] |= UInt(1 << (fdInt % _stdlib_fd_set._wordBits)) } public mutating func clear(_ fd: CInt) { let fdInt = Int(fd) _data[fdInt / _stdlib_fd_set._wordBits] &= ~UInt(1 << (fdInt % _stdlib_fd_set._wordBits)) } public mutating func zero() { let count = _data.count return _data.withUnsafeMutableBufferPointer { (_data) in for i in 0..<count { _data[i] = 0 } return } } } #if !os(Windows) public func _stdlib_select( _ readfds: inout _stdlib_fd_set, _ writefds: inout _stdlib_fd_set, _ errorfds: inout _stdlib_fd_set, _ timeout: UnsafeMutablePointer<timeval>? ) -> CInt { return readfds._data.withUnsafeMutableBufferPointer { (readfds) in writefds._data.withUnsafeMutableBufferPointer { (writefds) in errorfds._data.withUnsafeMutableBufferPointer { (errorfds) in let readAddr = readfds.baseAddress let writeAddr = writefds.baseAddress let errorAddr = errorfds.baseAddress #if os(Cygwin) typealias fd_set = _types_fd_set #endif func asFdSetPtr( _ p: UnsafeMutablePointer<UInt>? ) -> UnsafeMutablePointer<fd_set>? { return UnsafeMutableRawPointer(p)? .assumingMemoryBound(to: fd_set.self) } return select( _stdlib_FD_SETSIZE, asFdSetPtr(readAddr), asFdSetPtr(writeAddr), asFdSetPtr(errorAddr), timeout) } } } } #endif /// Swift-y wrapper around pipe(2) public func _stdlib_pipe() -> (readEnd: CInt, writeEnd: CInt, error: CInt) { var fds: [CInt] = [0, 0] let ret = fds.withUnsafeMutableBufferPointer { unsafeFds -> CInt in #if os(Windows) return _pipe(unsafeFds.baseAddress, 0, 0) #else return pipe(unsafeFds.baseAddress) #endif } return (readEnd: fds[0], writeEnd: fds[1], error: ret) } // // Functions missing in `Darwin` module. // public func _WSTATUS(_ status: CInt) -> CInt { return status & 0x7f } public var _WSTOPPED: CInt { return 0x7f } public func WIFEXITED(_ status: CInt) -> Bool { return _WSTATUS(status) == 0 } public func WIFSIGNALED(_ status: CInt) -> Bool { return _WSTATUS(status) != _WSTOPPED && _WSTATUS(status) != 0 } public func WEXITSTATUS(_ status: CInt) -> CInt { return (status >> 8) & 0xff } public func WTERMSIG(_ status: CInt) -> CInt { return _WSTATUS(status) }
apache-2.0
d5e6173be41ce81c7da79168f70e6818
25.300613
85
0.62258
3.508183
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/SkeletonView/Sources/Debug/SkeletonDebug.swift
2
1426
// Copyright © 2018 SkeletonView. All rights reserved. import Foundation import UIKit enum SkeletonEnvironmentKey: String { case debugMode = "SKELETON_DEBUG" } extension Dictionary { subscript (_ key: SkeletonEnvironmentKey) -> Value? { return self[key.rawValue as! Key] } } func printSkeletonHierarchy(in view: UIView) { skeletonLog(view.skeletonHierarchy()) } func skeletonLog(_ message: String) { if let _ = ProcessInfo.processInfo.environment[.debugMode] { print(message) } } extension UIView { public var skeletonDescription: String { var description = "<\(type(of: self)): \(Unmanaged.passUnretained(self).toOpaque())" let subSkeletons = subviewsSkeletonables if subSkeletons.count != 0 { description += " | (\(subSkeletons.count)) subSkeletons" } if isSkeletonable { description += " | ☠️ " } return description + ">" } public func skeletonHierarchy(index: Int = 0) -> String { var description = index == 0 ? "\n ⬇⬇ ☠️ Root view hierarchy with Skeletons ⬇⬇ \n" : "" description += "\(index == 0 ? "\n" : 3.whitespaces) \(skeletonDescription) \n" subviewsToSkeleton.forEach { description += (index + 2).whitespaces description += $0.skeletonHierarchy(index: index + 1) } return description } }
mit
7b129214346666b027273a9b7c6bcfd1
27.18
95
0.617459
4.156342
false
false
false
false
yoshinorisano/RxSwift
RxDataSourceStarterKit/DataSources/RxCollectionViewSectionedDataSource.swift
13
5781
// // RxCollectionViewSectionedDataSource.swift // RxExample // // Created by Krunoslav Zaher on 7/2/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif public class _RxCollectionViewSectionedDataSource : NSObject , UICollectionViewDataSource { func _numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 0 } public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return _numberOfSectionsInCollectionView(collectionView) } func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _collectionView(collectionView, numberOfItemsInSection: section) } func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return (nil as UICollectionViewCell?)! } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return _collectionView(collectionView, cellForItemAtIndexPath: indexPath) } func _collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return (nil as UICollectionReusableView?)! } public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return _collectionView(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) } } public class RxCollectionViewSectionedDataSource<S: SectionModelType> : _RxCollectionViewSectionedDataSource { public typealias I = S.Item public typealias Section = S public typealias CellFactory = (UICollectionView, NSIndexPath, I) -> UICollectionViewCell public typealias SupplementaryViewFactory = (UICollectionView, String, NSIndexPath) -> UICollectionReusableView public typealias IncrementalUpdateObserver = ObserverOf<Changeset<S>> public typealias IncrementalUpdateDisposeKey = Bag<IncrementalUpdateObserver>.KeyType // This structure exists because model can be mutable // In that case current state value should be preserved. // The state that needs to be preserved is ordering of items in section // and their relationship with section. // If particular item is mutable, that is irrelevant for this logic to function // properly. public typealias SectionModelSnapshot = SectionModel<S, I> var sectionModels: [SectionModelSnapshot] = [] public func sectionAtIndex(section: Int) -> S { return self.sectionModels[section].model } public func itemAtIndexPath(indexPath: NSIndexPath) -> I { return self.sectionModels[indexPath.section].items[indexPath.item] } var incrementalUpdateObservers: Bag<IncrementalUpdateObserver> = Bag() public func setSections(sections: [S]) { self.sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) } } public var cellFactory: CellFactory! = nil public var supplementaryViewFactory: SupplementaryViewFactory public override init() { self.cellFactory = { _, _, _ in return (nil as UICollectionViewCell?)! } self.supplementaryViewFactory = { _, _, _ in (nil as UICollectionReusableView?)! } super.init() self.cellFactory = { [weak self] _ in precondition(false, "There is a minor problem. `cellFactory` property on \(self!) was not set. Please set it manually, or use one of the `rx_bindTo` methods.") return (nil as UICollectionViewCell!)! } self.supplementaryViewFactory = { [weak self] _, _, _ in precondition(false, "There is a minor problem. `supplementaryViewFactory` property on \(self!) was not set.") return (nil as UICollectionReusableView?)! } } // observers public func addIncrementalUpdatesObserver(observer: IncrementalUpdateObserver) -> IncrementalUpdateDisposeKey { return incrementalUpdateObservers.insert(observer) } public func removeIncrementalUpdatesObserver(key: IncrementalUpdateDisposeKey) { let element = incrementalUpdateObservers.removeKey(key) precondition(element != nil, "Element removal failed") } // UITableViewDataSource override func _numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return sectionModels.count } override func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return sectionModels[section].items.count } override func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { precondition(indexPath.item < sectionModels[indexPath.section].items.count) return cellFactory(collectionView, indexPath, itemAtIndexPath(indexPath)) } override func _collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return supplementaryViewFactory(collectionView, kind, indexPath) } }
mit
0333640157c84442dfecfade530be477
41.20438
181
0.717696
5.947531
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00794-swift-typebase-isspecialized.swift
11
1165
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func e<l { enum e { func p() { p d> Bool { } protocol f : b { func b } func a<g>func s<s : m, v : m u v.v == s> (m: v) { } func s<v l k : a { } protocol g { } struct n : g { } func i<h : h, f : g m f.n == h> (g: f) { } func i<n : g m n.n = o) { } } k e.w == l> { } func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) { struct d<f : e, g: e where g.h == f.h> {{ } struct B<T : A> { } protocol C { ty } } struct d<f : e, g: e where g.h ==ay) { } } extension NSSet { convenience init<T>(array: Array<T>) { } } class A { class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { } class e: k{ clq) { } } T) { } } } class A { class func a() -> Self { } } func b<T>(t: AnyObject.Type) -> T! { } class A { } class k: h{ class func r {} var k = 1
apache-2.0
8ff93cab6398dd10f6ad22d78847cd19
14.958904
78
0.563948
2.382413
false
false
false
false
mightydeveloper/swift
test/SILGen/metatypes.swift
9
4232
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s import Swift protocol SomeProtocol { func method() func static_method() } protocol Any {} struct SomeStruct : Any {} class SomeClass : SomeProtocol { func method() {} func static_method() {} } class SomeSubclass : SomeClass {} // CHECK-LABEL: sil hidden @_TF9metatypes16static_metatypes func static_metatypes() -> (SomeStruct.Type, SomeClass.Type, SomeClass.Type) { // CHECK: [[STRUCT:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: [[CLASS:%[0-9]+]] = metatype $@thick SomeClass.Type // CHECK: [[SUBCLASS:%[0-9]+]] = metatype $@thick SomeSubclass.Type // CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type // CHECK: tuple ([[STRUCT]] : {{.*}}, [[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}}) return (SomeStruct.self, SomeClass.self, SomeSubclass.self) } // CHECK-LABEL: sil hidden @_TF9metatypes16struct_metatypes func struct_metatypes(s: SomeStruct) -> (SomeStruct.Type, SomeStruct.Type) { // CHECK: [[STRUCT1:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: [[STRUCT2:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: tuple ([[STRUCT1]] : {{.*}}, [[STRUCT2]] : {{.*}}) return (s.dynamicType, SomeStruct.self) } // CHECK-LABEL: sil hidden @_TF9metatypes15class_metatypes func class_metatypes(c: SomeClass, s: SomeSubclass) -> (SomeClass.Type, SomeClass.Type) { // CHECK: [[CLASS:%[0-9]+]] = value_metatype $@thick SomeClass.Type, // CHECK: [[SUBCLASS:%[0-9]+]] = value_metatype $@thick SomeSubclass.Type, // CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type // CHECK: tuple ([[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}}) return (c.dynamicType, s.dynamicType) } // CHECK-LABEL: sil hidden @_TF9metatypes19archetype_metatypes // CHECK: bb0(%0 : $*T): func archetype_metatypes<T>(t: T) -> (T.Type, T.Type) { // CHECK: [[STATIC_T:%[0-9]+]] = metatype $@thick T.Type // CHECK: [[DYN_T:%[0-9]+]] = value_metatype $@thick T.Type, %0 // CHECK: tuple ([[STATIC_T]] : {{.*}}, [[DYN_T]] : {{.*}}) return (T.self, t.dynamicType) } // CHECK-LABEL: sil hidden @_TF9metatypes21existential_metatypes func existential_metatypes(p: SomeProtocol) -> SomeProtocol.Type { // CHECK: existential_metatype $@thick SomeProtocol.Type return p.dynamicType } struct SomeGenericStruct<T> {} func generic_metatypes<T>(x: T) -> (SomeGenericStruct<T>.Type, SomeGenericStruct<SomeStruct>.Type) { // CHECK: metatype $@thin SomeGenericStruct<T> // CHECK: metatype $@thin SomeGenericStruct<SomeStruct> return (SomeGenericStruct<T>.self, SomeGenericStruct<SomeStruct>.self) } // rdar://16610078 // CHECK-LABEL: sil hidden @_TF9metatypes30existential_metatype_from_thinFT_PMPS_3Any_ : $@convention(thin) () -> @thick Any.Type // CHECK: [[T0:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type // CHECK-NEXT: return [[T2]] : $@thick Any.Type func existential_metatype_from_thin() -> Any.Type { return SomeStruct.self } // CHECK-LABEL: sil hidden @_TF9metatypes36existential_metatype_from_thin_valueFT_PMPS_3Any_ : $@convention(thin) () -> @thick Any.Type // CHECK: [[T0:%.*]] = function_ref @_TFV9metatypes10SomeStructC // CHECK-NEXT: [[T1:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: debug_value [[T2]] : $SomeStruct // let s // CHECK-NEXT: [[T0:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type // CHECK-NEXT: return [[T2]] : $@thick Any.Type func existential_metatype_from_thin_value() -> Any.Type { let s = SomeStruct() return s.dynamicType } // CHECK-LABEL: sil hidden @_TF9metatypes20specialized_metatypeFT_GVs10DictionarySSSi_ // CHECK: metatype $@thin Dictionary<String, Int>.Type func specialized_metatype() -> Dictionary<String, Int> { let dict = Swift.Dictionary<Swift.String, Int>() return dict }
apache-2.0
083e169f141d89a136736f0c2a817ef0
38.185185
135
0.656664
3.491749
false
false
false
false
Holmusk/Alamofire
Source/Response.swift
1
3834
// // Response.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Result /// Used to store all response data returned from a completed `Request`. public struct Response<Value, Error: ErrorType> { /// The URL request sent to the server. public let request: NSURLRequest? /// The server's response to the URL request. public let response: NSHTTPURLResponse? /// The data returned by the server. public let data: NSData? /// The result of response serialization. public let result: Result<Value, Error> /// The timeline of the complete lifecycle of the `Request`. public let timeline: Timeline /** Initializes the `Response` instance with the specified URL request, URL response, server data and response serialization result. - parameter request: The URL request sent to the server. - parameter response: The server's response to the URL request. - parameter data: The data returned by the server. - parameter result: The result of response serialization. - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - returns: the new `Response` instance. */ public init( request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - CustomStringConvertible extension Response: CustomStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } } // MARK: - CustomDebugStringConvertible extension Response: CustomDebugStringConvertible { /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data and the response serialization result. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.length ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joinWithSeparator("\n") } }
mit
34bcf0c1b6ee8af71706d5431e033a5e
38.122449
119
0.691445
4.798498
false
false
false
false
ualch9/onebusaway-iphone
OneBusAway/ui/regions/RegionListViewController.swift
2
8728
// // RegionListViewController.swift // org.onebusaway.iphone // // Created by Aaron Brethorst on 8/14/16. // Copyright © 2016 OneBusAway. All rights reserved. // import UIKit import CoreLocation import OBAKit import PromiseKit import SVProgressHUD @objc protocol RegionListDelegate { func regionSelected() } @objc(OBARegionListViewController) class RegionListViewController: OBAStaticTableViewController, RegionBuilderDelegate { @objc weak var delegate: RegionListDelegate? private let application: OBAApplication @objc init(application: OBAApplication) { self.application = application super.init(nibName: nil, bundle: nil) title = NSLocalizedString("msg_pick_your_location", comment: "Title of the Region List Controller") navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .add, target: self, action: #selector(addCustomAPI)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UIViewController extension RegionListViewController { override func viewDidLoad() { super.viewDidLoad() updateData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(selectedRegionDidChange), name: NSNotification.Name.OBARegionDidUpdate, object: nil) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.OBARegionDidUpdate, object: nil) } } // MARK: - Region Builder extension RegionListViewController { @objc func addCustomAPI() { buildRegion(nil) } func buildRegion(_ region: OBARegionV2?) { let builder = RegionBuilderViewController.init() if region != nil { builder.region = region! } builder.delegate = self let nav = UINavigationController.init(rootViewController: builder) present(nav, animated: true, completion: nil) } func regionBuilderDidCreateRegion(_ region: OBARegionV2) { // If the user is editing an existing region, then we // can ensure that it is properly updated by removing // it and then re-adding it. application.modelDao.removeCustomRegion(region) application.modelDao.addCustomRegion(region) application.modelDao.automaticallySelectRegion = false application.modelDao.currentRegion = region loadData() } } // MARK: - Notifications extension RegionListViewController { @objc func selectedRegionDidChange(_ note: Notification) { SVProgressHUD.dismiss() loadData() } } // MARK: - Table View extension RegionListViewController { func tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool { guard let row = row(at: indexPath), let region = row.model as? OBARegionV2 else { return false } // Only custom regions can be edited or deleted. return region.custom } func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCell.EditingStyle, forRowAtIndexPath indexPath: IndexPath) { if editingStyle == .delete { deleteRow(at: indexPath) } } override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { guard let row = row(at: indexPath), let region = row.model as? OBARegionV2 else { return nil } // Only regions that were created in-app can be edited. guard region.custom else { return nil } let editAction = UIContextualAction(style: .normal, title: OBAStrings.edit) { _, _, _ in self.buildRegion(region) } let deleteAction = UIContextualAction(style: .destructive, title: OBAStrings.delete) { _, _, _ in self.deleteRow(at: indexPath) } return UISwipeActionsConfiguration(actions: [editAction, deleteAction]) } } // MARK: - Data Loading extension RegionListViewController { func updateData() { guard let promise = application.regionHelper.refreshData() else { return } promise.then { _ in self.loadData() }.catch { error in AlertPresenter.showWarning(NSLocalizedString("msg_unable_load_regions", comment: ""), body: (error as NSError).localizedDescription) } } /** Builds a list of sections and rows from available region and location data. */ func loadData() { let regions = application.regionHelper.regions let acceptableRegions = regions.filter { $0.active && $0.supportsObaRealtimeApis } let customRows = tableRowsFromRegions(application.modelDao.customRegions()) let activeRows = tableRowsFromRegions(acceptableRegions.filter { !$0.experimental }) let experimentalRows = tableRowsFromRegions(acceptableRegions.filter { $0.experimental }) let autoSelectRow = buildAutoSelectRow() var sections = [OBATableSection]() sections.append(OBATableSection.init(title: nil, rows: [autoSelectRow])) if customRows.count > 0 { sections.append(OBATableSection.init(title: NSLocalizedString("msg_custom_regions", comment: ""), rows: customRows)) } sections.append(OBATableSection.init(title: NSLocalizedString("msg_active_regions", comment: ""), rows: activeRows)) if experimentalRows.count > 0 && OBACommon.debugMode { sections.append(OBATableSection.init(title: NSLocalizedString("region_list_controller.experimental_section_title", comment: ""), rows: experimentalRows)) } self.sections = sections tableView.reloadData() } private func buildAutoSelectRow() -> OBASwitchRow { let autoSelectRow = OBASwitchRow.init(title: NSLocalizedString("msg_automatically_select_region", comment: ""), action: { _ in self.application.modelDao.automaticallySelectRegion = !self.application.modelDao.automaticallySelectRegion if self.application.modelDao.automaticallySelectRegion { if let refresh = self.application.regionHelper.refreshData() { SVProgressHUD.show() refresh.then { _ -> Void in // no-op? }.always { SVProgressHUD.dismiss() } } } else { self.loadData() } }, switchValue: application.modelDao.automaticallySelectRegion) return autoSelectRow } /** Builds a sorted array of `OBATableRow` objects from an array of `OBARegionV2` objects. - Parameter regions: The array of regions that will be used to build an array of rows - Returns: an array of `OBATableRow` */ func tableRowsFromRegions(_ regions: [OBARegionV2]) -> [OBATableRow] { return regions.sorted { r1, r2 -> Bool in r1.regionName < r2.regionName }.map { region in let autoSelect = application.modelDao.automaticallySelectRegion let row = OBATableRow.init(title: region.regionName) { _ in if autoSelect { return } self.application.modelDao.currentRegion = region self.loadData() if let delegate = self.delegate { delegate.regionSelected() } } row.model = region row.deleteModel = { row in let alert = UIAlertController.init(title: NSLocalizedString("msg_ask_delete_region", comment: ""), message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: OBAStrings.cancel, style: .cancel, handler: nil)) alert.addAction(UIAlertAction.init(title: OBAStrings.delete, style: .destructive, handler: { _ in self.application.modelDao.removeCustomRegion(region) })) self.present(alert, animated: true, completion: nil) } if autoSelect { row.titleColor = OBATheme.darkDisabledColor row.selectionStyle = .none } if application.modelDao.currentRegion?.identifier == region.identifier { row.accessoryType = .checkmark } return row } } }
apache-2.0
b4b74bf55c46b6ff00997ebb931a9334
34.47561
165
0.64203
4.902809
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/ThirdLibrary/ProgressHUD/ProgressHUD.swift
1
4464
// // ProgressHUD.swift // LimitFree1606 // // Created by gaokunpeng on 16/7/28. // Copyright © 2016年 apple. All rights reserved. // import UIKit public let kProgressImageName = "提示底.png" public let kProgressHUDTag = 10000 public let kProgressActivityTag = 20000 class ProgressHUD: UIView { var textLabel: UILabel? init(center: CGPoint){ super.init(frame: CGRect.zero) let bgImage = UIImage(named: kProgressImageName) self.bounds = CGRect(x: 0, y: 0, width: bgImage!.size.width, height: bgImage!.size.height) self.center = center let imageView = UIImageView(image: bgImage) imageView.frame = self.bounds self.addSubview(imageView) //self.backgroundColor = UIColor.grayColor() self.layer.cornerRadius = 6 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func show(){ let uaiView = UIActivityIndicatorView(activityIndicatorStyle: .white) uaiView.tag = kProgressActivityTag uaiView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2) uaiView.backgroundColor = UIColor.clear uaiView.startAnimating() self.addSubview(uaiView) self.textLabel = UILabel(frame: CGRect.zero) self.textLabel!.backgroundColor = UIColor.clear self.textLabel!.textColor = UIColor.white self.textLabel!.text = "加载中..." self.textLabel!.font = UIFont.systemFont(ofSize: 15) self.textLabel?.sizeToFit() self.textLabel!.center = CGPoint(x: uaiView.center.x, y: uaiView.frame.origin.y+uaiView.frame.size.height+5+self.textLabel!.bounds.size.height/2) self.addSubview(self.textLabel!) } fileprivate func hideActivityView(){ let tmpView = self.viewWithTag(kProgressActivityTag) if tmpView != nil { let uiaView = tmpView as! UIActivityIndicatorView uiaView.stopAnimating() uiaView.removeFromSuperview() } UIView.animate(withDuration: 0.5, animations: { self.alpha = 0 }, completion: { (finished) in self.superview?.isUserInteractionEnabled = true self.removeFromSuperview() }) } fileprivate func hideAfterSuccess(){ let successImage = UIImage(named: "保存成功.png") let successImageView = UIImageView(image: successImage) successImageView.sizeToFit() successImageView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2) self.addSubview(successImageView) self.textLabel!.text = "加载成功" self.textLabel!.sizeToFit() self.hideActivityView() } fileprivate func hideAfterFail(){ self.textLabel?.text = "加载失败" self.textLabel?.sizeToFit() self.hideActivityView() } class func showOnView(_ view: UIView){ let oldHud = view.viewWithTag(kProgressHUDTag) if (oldHud != nil) { oldHud?.removeFromSuperview() } let hud = ProgressHUD(center: view.center) hud.tag = kProgressHUDTag hud.show() view.isUserInteractionEnabled = false view.addSubview(hud) } class func hideAfterSuccessOnView(_ view: UIView){ let tmpView = view.viewWithTag(kProgressHUDTag) if tmpView != nil { let hud = tmpView as! ProgressHUD hud.hideAfterSuccess() } } class func hideAfterFailOnView(_ view: UIView){ let tmpView = view.viewWithTag(kProgressHUDTag) if tmpView != nil { let hud = tmpView as! ProgressHUD hud.hideAfterFail() } } fileprivate class func hideOnView(_ view: UIView){ let tmpView = view.viewWithTag(kProgressHUDTag) if tmpView != nil { let hud = tmpView as! ProgressHUD hud.hideActivityView() } } }
mit
361ff445c4bbf0d0380f379e9634c553
24.142045
153
0.567232
4.778618
false
false
false
false
revealapp/Revert
Revert/Sources/InfoViewController.swift
1
1391
// // Copyright © 2015 Itty Bitty Apps. All rights reserved. import UIKit final class InfoViewController: UIViewController, SettableHomeItem { var item: HomeItem? override func viewDidLoad() { super.viewDidLoad() guard let item = self.item else { fatalError("Item should be set before `-viewDidLoad`") } guard let infoFilename = item.infoFilename else { fatalError("Cannot display without a valid info filename") } // Configure the view self.imageView.image = UIImage(named: item.iconName) self.titleLabel.text = item.title let htmlString = infoHTMLWithContent(infoFilename) self.webView.loadHTMLString(htmlString, baseURL: nil) } // MARK: Private @IBOutlet private weak var imageView: UIImageView! @IBOutlet private weak var webView: UIWebView! @IBOutlet private weak var titleLabel: UILabel! @IBAction private func dismiss(_ sender: UIBarButtonItem) { self.presentingViewController?.dismiss(animated: true, completion: nil) } } // MARK: - UIWebViewDelegate extension InfoViewController: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { if let URL = request.url, URL != Foundation.URL(string: "about:blank") { UIApplication.shared.openURL(URL) return false } return true } }
bsd-3-clause
16ae2598e04f2f0bff9cc4a94b81efe6
27.367347
129
0.720863
4.587459
false
false
false
false
ricardopereira/Playgrounds
NumberPad.playground/Contents.swift
1
4276
//: Playground - noun: a place where people can play import UIKit import XCPlayground final class NumberPadView: UIView, ViewGradients { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .whiteColor() let newButton: (Int) -> UIButton = { number in let button = UIButton(type: .System) button.setTitle(String(number), forState: .Normal) button.tintColor = .whiteColor() button.titleLabel?.font = UIFont(name: "HelveticaNeue-Thin", size: 30) button.tag = number return button } let firstRow = UIStackView(arrangedSubviews: [ newButton(1), newButton(2), newButton(3) ] ) firstRow.distribution = .FillEqually let secondRow = UIStackView(arrangedSubviews: [ newButton(4), newButton(5), newButton(6) ] ) secondRow.distribution = .FillEqually let thirdRow = UIStackView(arrangedSubviews: [ newButton(7), newButton(8), newButton(9) ] ) thirdRow.distribution = .FillEqually let fourthRow = UIStackView(arrangedSubviews: [ newButton(0), newButton(0), newButton(0) ] ) fourthRow.distribution = .FillEqually let mainStackView = UIStackView(arrangedSubviews: [ firstRow, secondRow, thirdRow, fourthRow ] ) mainStackView.frame = self.bounds addSubview(mainStackView) mainStackView.distribution = .FillEqually mainStackView.axis = .Vertical } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() //mainStackView.frame = self.bounds } override func drawRect(rect: CGRect) { super.drawRect(rect) drawGradient(frame: rect) } } protocol ViewGradients { func drawGradient(frame frame: CGRect, gradient2Color: UIColor, gradient2Color2: UIColor) } extension ViewGradients { func drawGradient(frame frame: CGRect = CGRect(x: 29, y: 28, width: 136, height: 77), gradient2Color: UIColor = UIColor(red: 0.498, green: 0.271, blue: 0.878, alpha: 1.000), gradient2Color2: UIColor = UIColor(red: 0.543, green: 0.364, blue: 0.843, alpha: 1.000)) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Gradient Declarations let gradient2 = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [gradient2Color2.CGColor, gradient2Color.CGColor], [0, 1])! //// Rectangle Drawing let rectangleRect = CGRect(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height) let rectanglePath = UIBezierPath(rect: rectangleRect) CGContextSaveGState(context) rectanglePath.addClip() CGContextDrawLinearGradient(context, gradient2, CGPoint(x: rectangleRect.midX, y: rectangleRect.minY), CGPoint(x: rectangleRect.midX, y: rectangleRect.maxY), CGGradientDrawingOptions()) CGContextRestoreGState(context) } } final class DemoViewController : UIViewController { override func viewDidLoad() { super.viewDidLoad() let numberPadView = NumberPadView() numberPadView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(numberPadView) NSLayoutConstraint.activateConstraints([ numberPadView.topAnchor.constraintEqualToAnchor(self.view.topAnchor, constant: 60), numberPadView.leadingAnchor.constraintEqualToAnchor(self.view.leadingAnchor, constant: 20), numberPadView.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor, constant: -20), numberPadView.heightAnchor.constraintEqualToConstant(340), ]) numberPadView.layer.cornerRadius = 10.0 numberPadView.layer.masksToBounds = true } } XCPlaygroundPage.currentPage.liveView = DemoViewController()
mit
e99c8f112d0289f4798ec894b502d150
31.892308
268
0.621141
4.960557
false
false
false
false
inacioferrarini/glasgow
Example/Tests/Helpers/FixtureHelper.swift
1
2194
// The MIT License (MIT) // // Copyright (c) 2017 Inácio Ferrarini // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class FixtureHelper { func objectFixture(using fixtureFile: String) -> NSDictionary? { let bundle = Bundle(for: type(of: self)) guard let resourceUrl = bundle.url(forResource: fixtureFile, withExtension: "json") else { return nil } guard let fileContent = try? Data(contentsOf: resourceUrl) else { return nil } guard let parsedData = try? JSONSerialization.jsonObject(with: fileContent, options: []) else { return nil } return parsedData as? NSDictionary } func arrayFixture(using fixtureFile: String) -> NSArray? { let bundle = Bundle(for: type(of: self)) guard let resourceUrl = bundle.url(forResource: fixtureFile, withExtension: "json") else { return nil } guard let fileContent = try? Data(contentsOf: resourceUrl) else { return nil } guard let parsedData = try? JSONSerialization.jsonObject(with: fileContent, options: []) else { return nil } return parsedData as? NSArray } }
mit
06fab199680b0a68e1907e7158148f2b
48.840909
116
0.708162
4.530992
false
false
false
false
tjw/swift
test/multifile/batch_mode_external_definitions.swift
2
15673
// REQUIRES: objc_interop // RUN: %empty-directory(%t) // // Check that bit-field accessors for external structs are only lazily (and not multiply) emitted: // // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-neither-field.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FIELD1 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-field1.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FIELD2 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-field2.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FIELD1 -primary-file %S/Inputs/batch_mode_external_uses_2.swift -primary-file %S/Inputs/batch_mode_external_uses_1.swift > %t/two-primaries-field1-reorder.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FIELD2 -primary-file %S/Inputs/batch_mode_external_uses_2.swift -primary-file %S/Inputs/batch_mode_external_uses_1.swift > %t/two-primaries-field2-reorder.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FIELD1 -D FIELD2 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-both-fields.sil // // RUN: %FileCheck --check-prefix=CHECK-FIELD1-ONLY %s <%t/two-primaries-field1.sil // RUN: %FileCheck --check-prefix=CHECK-FIELD2-ONLY %s <%t/two-primaries-field2.sil // RUN: %FileCheck --check-prefix=CHECK-FIELD1-ONLY-REORDER %s <%t/two-primaries-field1-reorder.sil // RUN: %FileCheck --check-prefix=CHECK-FIELD2-ONLY-REORDER %s <%t/two-primaries-field2-reorder.sil // RUN: %FileCheck --check-prefix=CHECK-BOTH-FIELDS %s <%t/two-primaries-both-fields.sil // RUN: %FileCheck --check-prefix=CHECK-NEITHER-FIELD %s <%t/two-primaries-neither-field.sil // // CHECK-FIELD1-ONLY: sil_stage canonical // CHECK-FIELD1-ONLY: use_extern_struct_field_1 // CHECK-FIELD1-ONLY: sil shared{{.*}}extern_struct$field$getter // CHECK-FIELD1-ONLY-NOT: sil shared{{.*}}extern_struct$field$getter // CHECK-FIELD1-ONLY: sil_stage canonical // CHECK-FIELD1-ONLY-NOT: use_extern_struct_field_2 // CHECK-FIELD1-ONLY-NOT: sil shared{{.*}}extern_struct$field$getter // // CHECK-FIELD1-ONLY-REORDER: sil_stage canonical // CHECK-FIELD1-ONLY-REORDER-NOT: use_extern_struct_field_2 // CHECK-FIELD1-ONLY-REORDER-NOT: sil shared{{.*}}extern_struct$field$getter // CHECK-FIELD1-ONLY-REORDER: sil_stage canonical // CHECK-FIELD1-ONLY-REORDER: use_extern_struct_field_1 // CHECK-FIELD1-ONLY-REORDER: sil shared{{.*}}extern_struct$field$getter // CHECK-FIELD1-ONLY-REORDER-NOT: sil shared{{.*}}extern_struct$field$getter // // CHECK-FIELD2-ONLY: sil_stage canonical // CHECK-FIELD2-ONLY-NOT: use_extern_struct_field_1 // CHECK-FIELD2-ONLY-NOT: sil shared{{.*}}extern_struct$field$getter // CHECK-FIELD2-ONLY: sil_stage canonical // CHECK-FIELD2-ONLY: use_extern_struct_field_2 // CHECK-FIELD2-ONLY: sil shared{{.*}}extern_struct$field$getter // CHECK-FIELD2-ONLY-NOT: sil shared{{.*}}extern_struct$field$getter // // CHECK-FIELD2-ONLY-REORDER: sil_stage canonical // CHECK-FIELD2-ONLY-REORDER: use_extern_struct_field_2 // CHECK-FIELD2-ONLY-REORDER: sil shared{{.*}}extern_struct$field$getter // CHECK-FIELD2-ONLY-REORDER-NOT: sil shared{{.*}}extern_struct$field$getter // CHECK-FIELD2-ONLY-REORDER: sil_stage canonical // CHECK-FIELD2-ONLY-REORDER-NOT: use_extern_struct_field_1 // CHECK-FIELD2-ONLY-REORDER-NOT: sil shared{{.*}}extern_struct$field$getter // // CHECK-BOTH-FIELDS: sil_stage canonical // CHECK-BOTH-FIELDS: use_extern_struct_field_1 // CHECK-BOTH-FIELDS: sil shared{{.*}}extern_struct$field$getter // CHECK-BOTH-FIELDS-NOT: sil shared{{.*}}extern_struct$field$getter // CHECK-BOTH-FIELDS: sil_stage canonical // CHECK-BOTH-FIELDS: use_extern_struct_field_2 // CHECK-BOTH-FIELDS: sil shared{{.*}}extern_struct$field$getter // CHECK-BOTH-FIELDS-NOT: sil shared{{.*}}extern_struct$field$getter // // CHECK-NEITHER-FIELD: sil_stage canonical // CHECK-NEITHER-FIELD-NOT: use_extern_struct_field_1 // CHECK-NEITHER-FIELD-NOT: sil shared{{.*}}extern_struct$field$getter // CHECK-NEITHER-FIELD: sil_stage canonical // CHECK-NEITHER-FIELD-NOT: use_extern_struct_field_2 // CHECK-NEITHER-FIELD-NOT: sil shared{{.*}}extern_struct$field$getter // // Check that RawRepresentable conformances for external enums are only lazily (and not multiply) emitted: // // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-neither-rawrep.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D RAWREP1 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-rawrep1.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D RAWREP2 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-rawrep2.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D RAWREP1 -primary-file %S/Inputs/batch_mode_external_uses_2.swift -primary-file %S/Inputs/batch_mode_external_uses_1.swift > %t/two-primaries-rawrep1-reorder.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D RAWREP2 -primary-file %S/Inputs/batch_mode_external_uses_2.swift -primary-file %S/Inputs/batch_mode_external_uses_1.swift > %t/two-primaries-rawrep2-reorder.sil // RUN: %target-swift-frontend -emit-sil -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D RAWREP1 -D RAWREP2 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-both-rawreps.sil // // RUN: %FileCheck --check-prefix=CHECK-RAWREP1-ONLY %s <%t/two-primaries-rawrep1.sil // RUN: %FileCheck --check-prefix=CHECK-RAWREP2-ONLY %s <%t/two-primaries-rawrep2.sil // RUN: %FileCheck --check-prefix=CHECK-RAWREP1-ONLY-REORDER %s <%t/two-primaries-rawrep1-reorder.sil // RUN: %FileCheck --check-prefix=CHECK-RAWREP2-ONLY-REORDER %s <%t/two-primaries-rawrep2-reorder.sil // RUN: %FileCheck --check-prefix=CHECK-BOTH-RAWREPS %s <%t/two-primaries-both-rawreps.sil // RUN: %FileCheck --check-prefix=CHECK-NEITHER-RAWREP %s <%t/two-primaries-neither-rawrep.sil // // CHECK-RAWREP1-ONLY: sil_stage canonical // CHECK-RAWREP1-ONLY: take_rawrep_1 // CHECK-RAWREP1-ONLY: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP1-ONLY-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP1-ONLY: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-RAWREP1-ONLY-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-RAWREP1-ONLY: sil_stage canonical // CHECK-RAWREP1-ONLY-NOT: take_rawrep_1 // CHECK-RAWREP1-ONLY-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP1-ONLY-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // // CHECK-RAWREP2-ONLY: sil_stage canonical // CHECK-RAWREP2-ONLY-NOT: take_rawrep_2 // CHECK-RAWREP2-ONLY-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP2-ONLY-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-RAWREP2-ONLY: sil_stage canonical // CHECK-RAWREP2-ONLY: take_rawrep_2 // CHECK-RAWREP2-ONLY: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP2-ONLY-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP2-ONLY: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-RAWREP2-ONLY-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // // CHECK-RAWREP1-ONLY-REORDER: sil_stage canonical // CHECK-RAWREP1-ONLY-REORDER-NOT: take_rawrep_1 // CHECK-RAWREP1-ONLY-REORDER-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP1-ONLY-REORDER-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-RAWREP1-ONLY-REORDER: sil_stage canonical // CHECK-RAWREP1-ONLY-REORDER: take_rawrep_1 // CHECK-RAWREP1-ONLY-REORDER: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP1-ONLY-REORDER-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP1-ONLY-REORDER: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-RAWREP1-ONLY-REORDER-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // // CHECK-RAWREP2-ONLY-REORDER: sil_stage canonical // CHECK-RAWREP2-ONLY-REORDER: take_rawrep_2 // CHECK-RAWREP2-ONLY-REORDER: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP2-ONLY-REORDER-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP2-ONLY-REORDER: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-RAWREP2-ONLY-REORDER-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-RAWREP2-ONLY-REORDER: sil_stage canonical // CHECK-RAWREP2-ONLY-REORDER-NOT: take_rawrep_2 // CHECK-RAWREP2-ONLY-REORDER-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-RAWREP2-ONLY-REORDER-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // // CHECK-BOTH-RAWREPS: sil_stage canonical // CHECK-BOTH-RAWREPS: take_rawrep_1 // CHECK-BOTH-RAWREPS: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-BOTH-RAWREPS-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-BOTH-RAWREPS: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-BOTH-RAWREPS-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-BOTH-RAWREPS: sil_stage canonical // CHECK-BOTH-RAWREPS: take_rawrep_2 // CHECK-BOTH-RAWREPS: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-BOTH-RAWREPS-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-BOTH-RAWREPS: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-BOTH-RAWREPS-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // // CHECK-NEITHER-RAWREP: sil_stage canonical // CHECK-NEITHER-RAWREP-NOT: take_rawrep_1 // CHECK-NEITHER-RAWREP-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-NEITHER-RAWREP-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // CHECK-NEITHER-RAWREP: sil_stage canonical // CHECK-NEITHER-RAWREP-NOT: take_rawrep_2 // CHECK-NEITHER-RAWREP-NOT: sil shared{{.*}}SSo8ext_enumVs16RawRepresentableSCsACP8rawValue0cF0QzvgTW // CHECK-NEITHER-RAWREP-NOT: sil_witness_table{{.*}}ext_enum: RawRepresentable // Check external inline functions are only lazily (and not multiply) emitted: // // RUN: %target-swift-frontend -emit-ir -import-objc-header %S/Inputs/batch_mode_external_definitions.h -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-neither-func.ir // RUN: %target-swift-frontend -emit-ir -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FUNC1 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-func1.ir // RUN: %target-swift-frontend -emit-ir -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FUNC2 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-func2.ir // RUN: %target-swift-frontend -emit-ir -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FUNC1 -primary-file %S/Inputs/batch_mode_external_uses_2.swift -primary-file %S/Inputs/batch_mode_external_uses_1.swift > %t/two-primaries-func1-reorder.ir // RUN: %target-swift-frontend -emit-ir -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FUNC2 -primary-file %S/Inputs/batch_mode_external_uses_2.swift -primary-file %S/Inputs/batch_mode_external_uses_1.swift > %t/two-primaries-func2-reorder.ir // RUN: %target-swift-frontend -emit-ir -import-objc-header %S/Inputs/batch_mode_external_definitions.h -D FUNC1 -D FUNC2 -primary-file %S/Inputs/batch_mode_external_uses_1.swift -primary-file %S/Inputs/batch_mode_external_uses_2.swift > %t/two-primaries-both-funcs.ir // // RUN: %FileCheck --check-prefix=CHECK-FUNC1-ONLY %s <%t/two-primaries-func1.ir // RUN: %FileCheck --check-prefix=CHECK-FUNC2-ONLY %s <%t/two-primaries-func2.ir // RUN: %FileCheck --check-prefix=CHECK-FUNC1-ONLY-REORDER %s <%t/two-primaries-func1-reorder.ir // RUN: %FileCheck --check-prefix=CHECK-FUNC2-ONLY-REORDER %s <%t/two-primaries-func2-reorder.ir // RUN: %FileCheck --check-prefix=CHECK-BOTH-FUNCS %s <%t/two-primaries-both-funcs.ir // RUN: %FileCheck --check-prefix=CHECK-NEITHER-FUNC %s <%t/two-primaries-neither-func.ir // // CHECK-FUNC1-ONLY: ModuleID // CHECK-FUNC1-ONLY: use_func_1 // CHECK-FUNC1-ONLY: define internal i32 @extern_inline_function // CHECK-FUNC1-ONLY-NOT: define internal i32 @extern_inline_function // CHECK-FUNC1-ONLY: ModuleID // CHECK-FUNC1-ONLY-NOT: use_func_1 // CHECK-FUNC1-ONLY-NOT: define internal i32 @extern_inline_function // // CHECK-FUNC2-ONLY: ModuleID // CHECK-FUNC2-ONLY-NOT: use_func_2 // CHECK-FUNC2-ONLY-NOT: define internal i32 @extern_inline_function // CHECK-FUNC2-ONLY: ModuleID // CHECK-FUNC2-ONLY: use_func_2 // CHECK-FUNC2-ONLY: define internal i32 @extern_inline_function // CHECK-FUNC2-ONLY-NOT: define internal i32 @extern_inline_function // // CHECK-FUNC1-ONLY-REORDER: ModuleID // CHECK-FUNC1-ONLY-REORDER-NOT: use_func_1 // CHECK-FUNC1-ONLY-REORDER-NOT: define internal i32 @extern_inline_function // CHECK-FUNC1-ONLY-REORDER: ModuleID // CHECK-FUNC1-ONLY-REORDER: use_func_1 // CHECK-FUNC1-ONLY-REORDER: define internal i32 @extern_inline_function // CHECK-FUNC1-ONLY-REORDER-NOT: define internal i32 @extern_inline_function // // CHECK-FUNC2-ONLY-REORDER: ModuleID // CHECK-FUNC2-ONLY-REORDER: use_func_2 // CHECK-FUNC2-ONLY-REORDER: define internal i32 @extern_inline_function // CHECK-FUNC2-ONLY-REORDER-NOT: define internal i32 @extern_inline_function // CHECK-FUNC2-ONLY-REORDER: ModuleID // CHECK-FUNC2-ONLY-REORDER-NOT: use_func_2 // CHECK-FUNC2-ONLY-REORDER-NOT: define internal i32 @extern_inline_function // // CHECK-BOTH-FUNCS: ModuleID // CHECK-BOTH-FUNCS: use_func_1 // CHECK-BOTH-FUNCS: define internal i32 @extern_inline_function // CHECK-BOTH-FUNCS-NOT: define internal i32 @extern_inline_function // CHECK-BOTH-FUNCS: ModuleID // CHECK-BOTH-FUNCS: use_func_2 // CHECK-BOTH-FUNCS: define internal i32 @extern_inline_function // CHECK-BOTH-FUNCS-NOT: define internal i32 @extern_inline_function // // CHECK-NEITHER-FUNC: ModuleID // CHECK-NEITHER-FUNC-NOT: use_func_1 // CHECK-NEITHER-FUNC-NOT: define internal i32 @extern_inline_function // CHECK-NEITHER-FUNC: ModuleID // CHECK-NEITHER-FUNC-NOT: use_func_2 // CHECK-NEITHER-FUNC-NOT: define internal i32 @extern_inline_function
apache-2.0
c040ef1fcb7d5a2a7b49ca1d3761e986
71.560185
276
0.763606
2.864741
false
false
false
false
apple/swift
test/IDE/complete_result_builder.swift
4
7830
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_TOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_NONTOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_COLOR_CONTEXT | %FileCheck %s -check-prefix=IN_CLOSURE_COLOR_CONTEXT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_RESULT_BUILDER_DECL -code-completion-comments=true | %FileCheck %s -check-prefix=IN_RESULT_BUILDER_DECL // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_RESULT_BUILDER_DECL_PREFIX -code-completion-comments=true | %FileCheck %s -check-prefix=IN_RESULT_BUILDER_DECL_PREFIX struct Tagged<Tag, Entity> { let tag: Tag let entity: Entity static func fo } protocol Taggable { } extension Taggable { func tag<Tag>(_ tag: Tag) -> Tagged<Tag, Self> { return Tagged(tag: tag, entity: self) } } extension Int: Taggable { } extension String: Taggable { } @resultBuilder struct TaggedBuilder<Tag> { static func buildBlock() -> () { } static func buildBlock<T1>(_ t1: Tagged<Tag, T1>) -> Tagged<Tag, T1> { return t1 } static func buildBlock<T1, T2>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>) { return (t1, t2) } static func buildBlock<T1, T2, T3>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t2: Tagged<Tag, T3>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>) { return (t1, t2, t3) } } enum Color { case red, green, blue } func acceptColorTagged<Result>(@TaggedBuilder<Color> body: (Color) -> Result) { print(body(.blue)) } var globalIntVal: Int = 1 let globalStringVal: String = "" func testAcceptColorTagged(paramIntVal: Int, paramStringVal: String) { let taggedValue = paramIntVal.tag(Color.red) acceptColorTagged { color in #^IN_CLOSURE_TOP^# // IN_CLOSURE_TOP_CONTEXT: Begin completions // IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local{{.*}}: taggedValue[#Tagged<Color, Int>#]; name=taggedValue // IN_CLOSURE_TOP-DAG: Decl[GlobalVar]/CurrModule: globalIntVal[#Int#]; name=globalIntVal // IN_CLOSURE_TOP-DAG: Decl[GlobalVar]/CurrModule: globalStringVal[#String#]; name=globalStringVal // IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: color{{.*}}; name=color // IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: paramIntVal[#Int#]; name=paramIntVal // IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: paramStringVal[#String#]; name=paramStringVal // IN_CLOSURE_TOP: End completions } acceptColorTagged { color in paramIntVal.tag(.red) #^IN_CLOSURE_NONTOP^# // Same as IN_CLOSURE_TOP. } acceptColorTagged { color in paramIntVal.tag(#^IN_CLOSURE_COLOR_CONTEXT^#) // IN_CLOSURE_COLOR_CONTEXT: Begin completions // IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: color; name=color // IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: taggedValue[#Tagged<Color, Int>#]; name=taggedValue // IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: paramIntVal[#Int#]; name=paramIntVal // IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: paramStringVal[#String#]; name=paramStringVal // IN_CLOSURE_COLOR_CONTEXT: End completions } } enum MyEnum { case east, west case north, south } @resultBuilder struct EnumToVoidBuilder { static func buildBlock() {} static func buildBlock(_ :MyEnum) {} static func buildBlock(_ :MyEnum, _: MyEnum) {} static func buildBlock(_ :MyEnum, _: MyEnum, _: MyEnum) {} } func acceptBuilder(@EnumToVoidBuilder body: () -> Void) {} @resultBuilder struct AnyBuilder { static func buildBlock(_ components: Any...) -> Any { 5 } #^IN_RESULT_BUILDER_DECL_PREFIX^# static func #^IN_RESULT_BUILDER_DECL^# } // IN_RESULT_BUILDER_DECL: Begin completions, 10 items // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildBlock(_ components: Any...) -> Any {|}; name=buildBlock(_ components: Any...) -> Any; comment=Required by every // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildExpression(_ expression: <#Expression#>) -> Any {|}; name=buildExpression(_ expression: <#Expression#>) -> Any; comment= // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildOptional(_ component: Any?) -> Any {|}; name=buildOptional(_ component: Any?) -> Any; comment= // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildEither(first component: Any) -> Any {|}; name=buildEither(first component: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildEither(second component: Any) -> Any {|}; name=buildEither(second component: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildArray(_ components: [Any]) -> Any {|}; name=buildArray(_ components: [Any]) -> Any; comment= // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildLimitedAvailability(_ component: Any) -> Any {|}; name=buildLimitedAvailability(_ component: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildFinalResult(_ component: Any) -> <#Result#> {|}; name=buildFinalResult(_ component: Any) -> <#Result#>; comment= // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildPartialBlock(first: Any) -> Any {|}; name=buildPartialBlock(first: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL: Pattern/CurrNominal: buildPartialBlock(accumulated: Any, next: Any) -> Any {|}; name=buildPartialBlock(accumulated: Any, next: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL: End completions // IN_RESULT_BUILDER_DECL_PREFIX: Begin completions // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildBlock(_ components: Any...) -> Any {|}; name=static func buildBlock(_ components: Any...) -> Any; comment=Required by every // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildExpression(_ expression: <#Expression#>) -> Any {|}; name=static func buildExpression(_ expression: <#Expression#>) -> Any; comment= // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildOptional(_ component: Any?) -> Any {|}; name=static func buildOptional(_ component: Any?) -> Any; comment= // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildEither(first component: Any) -> Any {|}; name=static func buildEither(first component: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildEither(second component: Any) -> Any {|}; name=static func buildEither(second component: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildArray(_ components: [Any]) -> Any {|}; name=static func buildArray(_ components: [Any]) -> Any; comment= // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildLimitedAvailability(_ component: Any) -> Any {|}; name=static func buildLimitedAvailability(_ component: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildFinalResult(_ component: Any) -> <#Result#> {|}; name=static func buildFinalResult(_ component: Any) -> <#Result#>; comment= // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildPartialBlock(first: Any) -> Any {|}; name=static func buildPartialBlock(first: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL_PREFIX: Pattern/CurrNominal: static func buildPartialBlock(accumulated: Any, next: Any) -> Any {|}; name=static func buildPartialBlock(accumulated: Any, next: Any) -> Any; comment= // IN_RESULT_BUILDER_DECL_PREFIX: End completions
apache-2.0
9ea93abd54ab0b068621bde61a62ef96
58.318182
211
0.694764
3.75
false
false
false
false
Kawoou/KWDrawerController
DrawerController/Animator/DrawerAnimator.swift
1
3463
/* The MIT License (MIT) Copyright (c) 2017 Kawoou (Jungwon An) 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 open class DrawerAnimator { // MARK: - Define internal static let FrameRate: Double = 1.0 / 60.0 // MARK: - Property open var isTicked: Bool { return false } // MARK: - Internal private var startTime: TimeInterval = 0.0 private var durationTime: TimeInterval = 0.0 private var animationClosure: ((Float)->())? private var completionClosure: ((Bool)->())? private var displayLink: CADisplayLink? // MARK: - Public open func animate(duration: TimeInterval, animations: @escaping (Float)->(), completion: @escaping ((Bool)->())) {} open func tick(delta: TimeInterval, duration: TimeInterval, animations: @escaping (Float)->()) {} // MARK: - Private internal func doAnimate(duration: TimeInterval, animations: @escaping (Float)->(), completion: @escaping ((Bool)->())) { guard isTicked else { animate(duration: duration, animations: animations, completion: completion) return } if let display = displayLink { display.invalidate() displayLink = nil } startTime = CACurrentMediaTime() durationTime = duration animationClosure = animations completionClosure = completion displayLink = { [unowned self] in let displayLink = CADisplayLink(target: self, selector: #selector(render)) #if swift(>=4.2) displayLink.add(to: .current, forMode: .default) #else displayLink.add(to: .current, forMode: .defaultRunLoopMode) #endif return displayLink }() } @objc private func render() { guard let display = displayLink, let animationClosure = animationClosure else { return } let delta = CACurrentMediaTime() - startTime if delta > durationTime { tick(delta: durationTime, duration: durationTime, animations: animationClosure) completionClosure!(true) display.invalidate() displayLink = nil } else { tick(delta: delta, duration: durationTime, animations: animationClosure) } } // MARK: - Lifecycle public init() {} }
mit
8738a12c0fd0b22c0cf737ee0f2e8fb2
31.364486
124
0.642506
5.115214
false
false
false
false
Keanyuan/SwiftContact
SwiftContent/SwiftContent/Classes/闭包/ClosureE.swift
1
7797
// // ClosureE.swift // SwiftContent // // Created by 祁志远 on 2017/6/16. // Copyright © 2017年 祁志远. All rights reserved. // import UIKit class ClosureE: NSObject { //----------逃逸闭包 @escaping------------- //当一个闭包作为参数传到一个函数中,但是这个闭包在函数返回之后才被执行,我们称该闭包从函数中逃逸。当你定义接受闭包作为参数的函数时,你可以在参数名之前标注 @escaping,用来指明这个闭包是允许“逃逸”出这个函数的。 var completionHanders: [() -> Void] = [] var x = 10 func someFunctionWithEscapingClosure(completionHander: @escaping () -> Void){ completionHanders.append(completionHander) } func someFuncNone(closure:() -> Void){ closure() } //将一个闭包标记为 @escaping 意味着你必须在闭包中显式地引用 self。比如说,在下面的代码中,传递到 someFunctionWithEscapingClosure(_:) 中的闭包是一个逃逸闭包,这意味着它需要显式地引用 self。相对的,传递到 someFunctionWithNonescapingClosure(_:) 中的闭包是一个非逃逸闭包,这意味着它可以隐式引用 self。 func doSomething() { someFunctionWithEscapingClosure { self.x = 100 } someFuncNone { x = 2000 } } public class func setClosureE() { /* * 闭包是自包含的函数代码块,可以在代码中被传递和使用 * 闭包可以捕获和存储其所在上下文中任意常量和变量的引用。被称为包裹常量和变量。 * Swift 会为你管理在捕获过程中涉及到的所有内存操作。 * 全局函数是一个有名字但不会捕获任何值的闭包 * 嵌套函数是一个有名字并可以捕获其封闭函数域内值的闭包 * 闭包表达式是一个利用轻量级语法所写的可以捕获其上下文中变量或常量值的匿名闭包 */ //sorted(by:) 方法会返回一个与原数组大小相同,包含同类型元素且元素已正确排序的新数组。 let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] func backward(_ s1: String, _ s2: String) -> Bool { return s1 > s2 } //sorted(by:) 方法接受一个闭包,该闭包函数需要传入与数组元素类型相同的两个值,并返回一个布尔类型值来表明当排序结束后传入的第一个参数排在第二个参数前面还是后面。如果第一个参数值出现在第二个参数值前面,排序闭包函数需要返回true,反之返回false。 var reversedNames = names.sorted(by: backward) print(reversedNames) //以这种方式来编写一个实际上很简单的表达式(a > b),确实太过繁琐了。对于这个例子来说,利用闭包表达式语法可以更好地构造一个内联排序闭包。 /* 闭包表达式语法有如下的一般形式: { (parameters) -> returnType in statements } */ reversedNames = names.sorted(by: {(s1: String, s2: String) -> Bool in return s1 < s2}) print(reversedNames) //因为排序闭包函数是作为 sorted(by:) 方法的参数传入的,Swift 可以推断其参数和返回值的类型。sorted(by:) 方法被一个字符串数组调用,因此其参数必须是 (String, String) -> Bool 类型的函数。这意味着 (String, String) 和 Bool 类型并不需要作为闭包表达式定义的一部分。因为所有的类型都可以被正确推断,返回箭头(->)和围绕在参数周围的括号也可以被省略 reversedNames = names.sorted(by: { (s1, s2) -> Bool in s1 > s2 }) print(reversedNames) //参数名称缩写 //Swift 自动为内联闭包提供了参数名称缩写功能,你可以直接通过 $0,$1,$2 来顺序调用闭包的参数,以此类推。 reversedNames = names.sorted(by: {$0 < $1}) print(reversedNames) //运算符方法 //式。Swift 的 String 类型定义了关于大于号(>)的字符串实现,其作为一个函数接受两个 String 类型的参数并返回 Bool 类型的值 reversedNames = names.sorted(by: >) print(reversedNames) //尾随闭包 func someFuncThatTakesAClosureA(Clouse: () -> Void) { // 函数体部分 } //以下是不使用尾随闭包进行函数调用 someFuncThatTakesAClosureA(Clouse: { // 闭包主体部分 }) // 以下是使用尾随闭包进行函数调用 someFuncThatTakesAClosureA(){ // 闭包主体部分 } reversedNames = names.sorted(){$0 < $1} print(reversedNames) reversedNames = names.sorted{ $0 > $1} print(reversedNames) //--------------------- let digitNames = [ 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" ] let numbers = [16, 58, 510] let strings = numbers.map { (number) -> String in var number = number var output = "" repeat{ output = digitNames[number % 10]! + output number /= 10 }while number > 0 return output } print(strings) func makeIncrementer(forIncerment amout: Int) -> () -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amout return runningTotal } return incrementer } let incrementByTen = makeIncrementer(forIncerment: 10) print(incrementByTen()) print(incrementByTen()) //-------------- let instance = ClosureE() instance.doSomething() print(instance.x) instance.completionHanders.first?() print(instance.x) var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] print(customersInLine.count) // 打印出 "5" let customerProvider = { customersInLine.remove(at: 0) } print(customersInLine.count) // 打印出 "5" print("Now serving \(customerProvider())!") // Prints "Now serving Chris!" print(customersInLine.count) // 打印出 "4" // customersInLine is ["Alex", "Ewa", "Barry", "Daniella"] // func serve(customer customerProvider: () -> String) { // print("Now serving \(customerProvider())!") // } // serve(customer: { customersInLine.remove(at: 0) } ) //而是通过将参数标记为 @autoclosure 来接收一个自动闭包。现在你可以将该函数当作接受 String 类型参数(而非闭包)的函数来调用。customerProvider 参数将自动转化为一个闭包,因为该参数被标记了 @autoclosure 特性。 //注意 过度使用 autoclosures 会让你的代码变得难以理解。上下文和函数名应该能够清晰地表明求值是被延迟执行的。 // customersInLine is ["Ewa", "Barry", "Daniella"] func serve(customer customerProvider: @autoclosure () -> String) { print("Now serving \(customerProvider())!") } serve(customer: customersInLine.remove(at: 0)) // 打印 "Now serving Ewa!" } }
mit
61a6a9c5b2b8aea622da6d05e4fb2742
31.088889
219
0.556094
3.563233
false
false
false
false
Jordan150513/DDSwift3Demos
DayFour/DayFour/CustomTableViewController.swift
1
3614
// // CustomTableViewController.swift // DayFour // // Created by 乔丹丹 on 16/8/9. // Copyright © 2016年 Jordan. All rights reserved. // import UIKit class CustomTableViewController: UITableViewController { // private let dataArr:[String] = ["","",""] private var dataSource:[String] = ["练习1","练习2","练习3"] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // if cell.textLabel != nil { // cell.textLabel?.text = dataSource[indexPath.row] // } cell.textLabel?.text = dataSource[indexPath.row] // Configure the cell... return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } // // Override to support rearranging the table view. // override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { // // let itemToMove = dataSource[fromIndexPath.row] // dataSource.remove(at: fromIndexPath.row) //// dataSource.insert(itemToMove, at: IndexPath.row) // // } // // Override to support conditional rearranging of the table view. // override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // // Return false if you do not want the item to be re-orderable. // return true // } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
532e1ad990840f29cb9281f37548e263
33.548077
136
0.661564
4.997218
false
false
false
false
shvets/TVSetKit
Sources/Items.swift
1
2151
import Foundation open class Items { public var cellSelection: IndexPath? public var items: [Item] = [] public init() {} public var count: Int { return items.count } public subscript(index: Int) -> Item { get { return items[index] } set(newValue) { items[index] = newValue } } // public func loadMoreData(_ view: UIView?, onLoadCompleted: (([Item]) -> Void)?=nil) { // pageLoader.loadData { result in // var indexPaths: [IndexPath] = [] // // for (index, _) in result.enumerated() { // let indexPath = IndexPath(row: self.items.count + index, section: 0) // // indexPaths.append(indexPath) // } // // if let items = result as? [Item] { // self.items += items // // if let view = view as? UITableView { // view.insertRows(at: indexPaths, with: .none) // // let step = min(result.count, self.pageLoader.rowSize) // // view.scrollToRow(at: indexPaths[step-1], at: .middle, animated: false) // } // else if let view = view as? UICollectionView { // view.insertItems(at: indexPaths) // // let step = min(result.count, self.pageLoader.rowSize) // // view.scrollToItem(at: indexPaths[step-1], at: .left, animated: false) // } // } // // if let onLoadCompleted = onLoadCompleted { // onLoadCompleted(self.items) // } // } // } public func getSelectedItem() -> Item? { var item: Item? if let indexPath = cellSelection { item = items[indexPath.row] } return item } public func removeCell(_ onRemoveCompleted: (() -> Void)?=nil) { if let indexPath = cellSelection { _ = items.remove(at: indexPath.row) cellSelection = nil if let onRemoveCompleted = onRemoveCompleted { onRemoveCompleted() } } } public func getItem(for indexPath: IndexPath?) -> Item { if let indexPath = indexPath { return items[indexPath.row] } else { return Item() } } }
mit
280d9f20bd5d02431f6b58e349f2fd5f
22.9
91
0.548117
3.896739
false
false
false
false
StoicPenguin/Rational
Rational/Rational.swift
1
11467
// // Rational.swift // Rational // // Created by Michael Hendrickson on 10/24/16. // Copyright © 2016 Michael Hendrickson. All rights reserved. // import Foundation /// Represents a rational number, maintained in reduced form. struct Rational { /// The numerator var numerator: Int; /// The denominator var denominator: Int; /// Initialize the Rational as a whole number /// - Parameters: /// - numerator: The whole value to set to the Rational /// - Note: The denominator is initialized to 1 init(_ numerator: Int) { self.init(numerator, 1); } /// Initialize the Rational as a whole number /// - Parameters: /// - numerator: The "top" number of the Rational /// - denominator: The "bottom" number of the Rational /// - Note: The number will be normalized to divide out the common divisor of the numerator and denominator. /// In addition, for negative numbers, the numerator will be negative. The denominator will always be /// non-negative. A denominiator of 0 signifies an infinite value. init(_ numerator: Int, _ denominator: Int) { self.numerator = numerator; self.denominator = denominator; normalize(); } /// The multiplicative inverse of the the number. /// - Note: Essentially, this will swap the numerator and denominator, leaving the numerator negative. func inverse() -> Rational { return Rational(denominator, numerator); } /// Normalize the Rational by dividing out the common divisor of the numerator and denominator and, for negative /// numbers, making the numerator negative and the denominator positive. private mutating func normalize() { if denominator < 0 { numerator = -numerator; denominator = -denominator; } (numerator, denominator) = reducedTuple((numerator, denominator)); } /// Removes the common divisor from a tuple. /// - Parameters: /// - t: A tuple of integers /// - Returns: The tuple with the common divisor divided out private func reducedTuple(_ t: (Int, Int)) -> (Int, Int) { if t == (0, 0) { return (0, 0); } let gcd = Int.gcd(abs(t.0), abs(t.1)); return (t.0 / gcd, t.1 / gcd); } /// Is the Rational finite? /// Returns: False if the denominator is 0, True otherwise var isFinite : Bool { return denominator != 0; } /// Is the Rational infinite? /// Returns: True if the denominator is 0, False otherwise var isInfinite : Bool { return numerator != 0 && denominator == 0; } /// Is the Rational not a number? /// Returns: True if the numerator and denominator are 0, False otherwise var isNaN : Bool { return numerator == 0 && denominator == 0; } } // MARK: IntegerArithmetic extension Rational : IntegerArithmetic { static func + (lhs: Rational, rhs: Rational) -> Rational { if lhs.isInfinite || rhs.isInfinite { return Rational(lhs.numerator + rhs.numerator, 0); } let lcm = Int.lcm(lhs.denominator, rhs.denominator); return Rational((lhs.numerator * (lcm / lhs.denominator)) + (rhs.numerator * (lcm / rhs.denominator)), lcm); } static func addWithOverflow(_ lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { if lhs.isInfinite || rhs.isInfinite { return (Rational(lhs.numerator + rhs.numerator, 0), false); } let n1 = Int.multiplyWithOverflow(lhs.numerator, rhs.denominator); let n2 = Int.multiplyWithOverflow(rhs.numerator, lhs.denominator); let nTemp = Int.addWithOverflow(n1.0, n2.0); let dTemp = Int.multiplyWithOverflow(lhs.denominator, rhs.denominator); return (Rational(nTemp.0, dTemp.0), n1.1 || n2.1 || nTemp.1 || dTemp.1); } static func - (lhs: Rational, rhs: Rational) -> Rational { if lhs.isInfinite || rhs.isInfinite { return Rational(lhs.numerator - rhs.numerator, 0); } let lcm = Int.lcm(lhs.denominator, rhs.denominator); return Rational((lhs.numerator * (lcm / lhs.denominator)) - (rhs.numerator * (lcm / rhs.denominator)), lcm); } static func subtractWithOverflow(_ lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { if lhs.isInfinite || rhs.isInfinite { return (Rational(lhs.numerator - rhs.numerator, 0), false); } let n1 = Int.multiplyWithOverflow(lhs.numerator, rhs.denominator); let n2 = Int.multiplyWithOverflow(rhs.numerator, lhs.denominator); let nTemp = Int.subtractWithOverflow(n1.0, n2.0); let dTemp = Int.multiplyWithOverflow(lhs.denominator, rhs.denominator); return (Rational(nTemp.0, dTemp.0), n1.1 || n2.1 || nTemp.1 || dTemp.1); } static func * (lhs: Rational, rhs: Rational) -> Rational { if lhs.isInfinite || rhs.isInfinite { return Rational(lhs.numerator * rhs.numerator, 0); } let gcd1 = Int.gcd(lhs.numerator, rhs.denominator); let gcd2 = Int.gcd(lhs.denominator, rhs.numerator); return Rational((lhs.numerator / gcd1) * (rhs.numerator / gcd2), (lhs.denominator / gcd2) * (rhs.denominator / gcd1)); } static func multiplyWithOverflow(_ lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { if lhs.isInfinite || rhs.isInfinite { return (Rational(lhs.numerator * rhs.numerator, 0), false); } let gcd1 = Int.gcd(lhs.numerator, rhs.denominator); let gcd2 = Int.gcd(lhs.denominator, rhs.numerator); let nTemp = Int.multiplyWithOverflow(lhs.numerator / gcd1, rhs.numerator / gcd2); let dTemp = Int.multiplyWithOverflow(lhs.denominator / gcd2, rhs.denominator / gcd1); return (Rational(nTemp.0, dTemp.0), nTemp.1 || dTemp.1); } static func / (lhs: Rational, rhs: Rational) -> Rational { return lhs * rhs.inverse(); } static func divideWithOverflow(_ lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { return multiplyWithOverflow(lhs, rhs.inverse()); } static func % (lhs: Rational, rhs: Rational) -> Rational { if lhs.isInfinite || rhs.isInfinite { return Rational(lhs.numerator % rhs.numerator, 0); } let lcm = Int.lcm(lhs.denominator, rhs.denominator); return Rational((lhs.numerator * (lcm / lhs.denominator)) % (rhs.numerator * (lcm / rhs.denominator)), lcm); } static func remainderWithOverflow(_ lhs: Rational, _ rhs: Rational) -> (Rational, overflow: Bool) { if lhs.isInfinite || rhs.isInfinite { return (Rational(lhs.numerator % rhs.numerator, 0), false); } let n1 = Int.multiplyWithOverflow(lhs.numerator, rhs.denominator); let n2 = Int.multiplyWithOverflow(rhs.numerator, lhs.denominator); let nTemp = Int.remainderWithOverflow(n1.0, n2.0); let dTemp = Int.multiplyWithOverflow(lhs.denominator, rhs.denominator); return (Rational(nTemp.0, dTemp.0), n1.1 || n2.1 || nTemp.1 || dTemp.1); } func toIntMax() -> IntMax { return IntMax(numerator / denominator); } } // MARK: Comparable extension Rational : Comparable { static func < (lhs: Rational, rhs: Rational) -> Bool { return lhs.numerator * rhs.denominator < rhs.numerator * lhs.denominator; } static func == (lhs: Rational, rhs: Rational) -> Bool { return lhs.numerator * rhs.denominator == rhs.numerator * lhs.denominator; } } // MARK: Hashable extension Rational : Hashable { var hashValue : Int { return numerator ^ denominator; } } // MARK: ExpressibleByIntegerLiteral extension Rational : ExpressibleByIntegerLiteral { init(integerLiteral value: IntegerLiteralType) { self.init(value, 1); } } // MARK: ExpressibleByFloatLiteral extension Rational : ExpressibleByFloatLiteral { init(floatLiteral value: FloatLiteralType) { let r = Double.bestRationalApproxiation(Double(value)); numerator = r.numerator; denominator = r.denominator; } } // MARK: CustomStringConvertible extension Rational : CustomStringConvertible { var description : String { return "\(numerator)/\(denominator)"; } } // MARK: AbsoluteValuable extension Rational: AbsoluteValuable { static func abs(_ x: Rational) -> Rational { return Rational(Swift.abs(x.numerator), Swift.abs(x.denominator)); } } extension Integer { /// Find the Greatest Common Denominator of two Integers /// - Parameters: /// - a: First Integer /// - b: Second Integer /// - Returns: The GCD of the given Integers static func gcd(_ a: Self, _ b: Self) -> Self { return b == 0 ? a : gcd(b, a % b); } /// Find the Least Common Multiple of the two Integers /// - Parameters: /// - a: First Integer /// - b: Second Integer /// - Returns: The LCM of the given Integers static func lcm(_ a: Self, _ b: Self) -> Self { if a == 0 || b == 0 { return 0; } return (a / gcd(a, b)) * b; } } extension Double { /// Initialize a Double from a Rational /// - Note: If the denominator is zero, the Double will be initialized to +/- infinity init(_ number: Rational) { if number.isFinite { self = Double(number.numerator) / Double(number.denominator); } else if number.isInfinite { self = number.numerator > 0 ? .infinity : -.infinity; } else { self = .nan; } } /// Return the closest Rational within a given error with the smallest possible denominator /// - Parameters: /// - number: The number to be approximated /// - eps: The error target. Default value is 1.0e-15. /// - Returns: The Rational with smallest denominsator and within **eps** of number /// - Note: Because the numerator and denominator of Rational are Int, it is not always possible to meet the **eps** /// target. If **eps** cannot be met, the closest Rational with numerator and denominator fittable within an /// Int is returned. static func bestRationalApproxiation(_ number: Double, _ eps: Double = 1.0e-15) -> Rational { guard number.isFinite else { return Rational(1, 0); } var nTemp = abs(number); var p1 = 0.0, p2 = 1.0; var q1 = 1.0, q2 = 0.0; repeat { let a = floor(nTemp); let pTemp = a * p2 + p1; let qTemp = a * q2 + q1; if (pTemp > Double(Int.max) || pTemp < Double(Int.min) || qTemp > Double(Int.max) || qTemp < Double(Int.min)) { break; } p1 = p2; p2 = pTemp; q1 = q2; q2 = qTemp; nTemp = 1.0 / (nTemp - a) if nTemp.isNaN || nTemp.isInfinite { break; } } while abs((p2 / q2) - number) > eps return Rational(Int(number < 0 ? -p2 : p2), Int(q2)); } }
mit
a5102e29646e8e432bb414cf2559eabf
34.28
123
0.593494
4.212344
false
false
false
false
AndrewBennet/readinglist
ReadingList_Foundation/UI/EmptyDetectingTableDiffableDataSource.swift
1
1633
import Foundation import CoreData import UIKit import os.log public protocol UITableViewEmptyDetectingDataSource: UITableViewDataSource { var emptyDetectionDelegate: UITableViewEmptyDetectingDataSourceDelegate? { get set } } public protocol UITableViewEmptyDetectingDataSourceDelegate: AnyObject { func tableDidBecomeEmpty() func tableDidBecomeNonEmpty() } //swiftlint:disable:next generic_type_name open class EmptyDetectingTableDiffableDataSource<SectionIdentifierType, ItemIdentifierType>: UITableViewDiffableDataSource<SectionIdentifierType, ItemIdentifierType>, UITableViewEmptyDetectingDataSource where SectionIdentifierType: Hashable, ItemIdentifierType: Hashable { public weak var emptyDetectionDelegate: UITableViewEmptyDetectingDataSourceDelegate? var isEmpty = false public override init(tableView: UITableView, cellProvider: @escaping UITableViewDiffableDataSource<SectionIdentifierType, ItemIdentifierType>.CellProvider) { super.init(tableView: tableView, cellProvider: cellProvider) } override public func apply(_ snapshot: NSDiffableDataSourceSnapshot<SectionIdentifierType, ItemIdentifierType>, animatingDifferences: Bool = true, completion: (() -> Void)? = nil) { if snapshot.numberOfItems == 0 { if !isEmpty { emptyDetectionDelegate?.tableDidBecomeEmpty() isEmpty = true } } else if isEmpty { emptyDetectionDelegate?.tableDidBecomeNonEmpty() isEmpty = false } super.apply(snapshot, animatingDifferences: animatingDifferences, completion: completion) } }
gpl-3.0
d34aa1362413697e4c42f6fba4d2feec
44.361111
272
0.766075
5.938182
false
false
false
false
troystribling/BlueCap
Examples/CentralManager/CentralManager/ViewController.swift
1
13215
// // ViewController.swift // Beacon // // Created by Troy Stribling on 4/13/15. // Copyright (c) 2015 Troy Stribling. The MIT License (MIT). // import UIKit import CoreBluetooth import BlueCapKit public enum AppError : Error { case dataCharactertisticNotFound case enabledCharactertisticNotFound case updateCharactertisticNotFound case serviceNotFound case invalidState case resetting case poweredOff case unknown case unlikley } class ViewController: UITableViewController { struct MainStoryboard { static let updatePeriodValueSegue = "UpdatePeriodValue" static let updatePeriodRawValueSegue = "UpdatePeriodRawValue" } @IBOutlet var xAccelerationLabel: UILabel! @IBOutlet var yAccelerationLabel: UILabel! @IBOutlet var zAccelerationLabel: UILabel! @IBOutlet var xRawAccelerationLabel: UILabel! @IBOutlet var yRawAccelerationLabel: UILabel! @IBOutlet var zRawAccelerationLabel: UILabel! @IBOutlet var rawUpdatePeriodlabel: UILabel! @IBOutlet var updatePeriodLabel: UILabel! @IBOutlet var activateSwitch: UISwitch! @IBOutlet var enabledSwitch: UISwitch! @IBOutlet var enabledLabel: UILabel! @IBOutlet var statusLabel: UILabel! var peripheral: Peripheral? var accelerometerDataCharacteristic: Characteristic? var accelerometerEnabledCharacteristic: Characteristic? var accelerometerUpdatePeriodCharacteristic: Characteristic? let manager = CentralManager(options: [CBCentralManagerOptionRestoreIdentifierKey : "us.gnos.BlueCap.central-manager-example" as NSString]) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateUIStatus() readUpdatePeriod() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == MainStoryboard.updatePeriodValueSegue { let viewController = segue.destination as! SetUpdatePeriodViewController viewController.characteristic = accelerometerUpdatePeriodCharacteristic viewController.isRaw = false } else if segue.identifier == MainStoryboard.updatePeriodRawValueSegue { let viewController = segue.destination as! SetUpdatePeriodViewController viewController.characteristic = accelerometerUpdatePeriodCharacteristic viewController.isRaw = true } } @IBAction func toggleEnabled(_ sender: AnyObject) { guard let peripheral = peripheral, peripheral.state == .connected else { return } writeEnabled() } @IBAction func toggleActivate(_ sender: AnyObject) { if activateSwitch.isOn { activate() } else { deactivate() } } @IBAction func disconnect(_ sender: AnyObject) { guard let peripheral = self.peripheral, peripheral.state != .disconnected else { return } peripheral.disconnect() } func activate() { let serviceUUID = CBUUID(string: TiSensorTag.AccelerometerService.uuid) let dataUUID = CBUUID(string: TiSensorTag.AccelerometerService.Data.uuid) let enabledUUID = CBUUID(string: TiSensorTag.AccelerometerService.Enabled.uuid) let updatePeriodUUID = CBUUID(string: TiSensorTag.AccelerometerService.UpdatePeriod.uuid) // on power, start scanning. when peripheral is discovered connect and stop scanning let dataUpdateFuture = manager.whenStateChanges().flatMap { [unowned self] state -> FutureStream<Peripheral> in switch state { case .poweredOn: self.activateSwitch.isOn = true return self.manager.startScanning(forServiceUUIDs: [serviceUUID], capacity: 10) case .poweredOff: throw AppError.poweredOff case .unauthorized, .unsupported: throw AppError.invalidState case .resetting: throw AppError.resetting case .unknown: throw AppError.unknown } }.flatMap { [unowned self] peripheral -> FutureStream<Void> in self.manager.stopScanning() self.peripheral = peripheral return peripheral.connect(connectionTimeout: 10.0) }.flatMap { [unowned self] () -> Future<Void> in guard let peripheral = self.peripheral else { throw AppError.unlikley } self.updateUIStatus() return peripheral.discoverServices([serviceUUID]) }.flatMap { [unowned self] () -> Future<Void> in guard let peripheral = self.peripheral else { throw AppError.unlikley } guard let service = peripheral.services(withUUID: serviceUUID)?.first else { throw AppError.serviceNotFound } return service.discoverCharacteristics([dataUUID, enabledUUID, updatePeriodUUID]) }.flatMap { [unowned self] () -> Future<Void> in guard let peripheral = self.peripheral, let service = peripheral.services(withUUID: serviceUUID)?.first else { throw AppError.serviceNotFound } guard let dataCharacteristic = service.characteristics(withUUID: dataUUID)?.first else { throw AppError.dataCharactertisticNotFound } guard let enabledCharacteristic = service.characteristics(withUUID: enabledUUID)?.first else { throw AppError.enabledCharactertisticNotFound } guard let updatePeriodCharacteristic = service.characteristics(withUUID: updatePeriodUUID)?.first else { throw AppError.updateCharactertisticNotFound } self.accelerometerDataCharacteristic = dataCharacteristic self.accelerometerEnabledCharacteristic = enabledCharacteristic self.accelerometerUpdatePeriodCharacteristic = updatePeriodCharacteristic return enabledCharacteristic.write(TiSensorTag.AccelerometerService.Enabled.yes) }.flatMap { [unowned self] () -> Future<[Void]> in return [self.accelerometerEnabledCharacteristic, self.accelerometerUpdatePeriodCharacteristic, self.accelerometerDataCharacteristic].compactMap { $0 }.map { $0.read(timeout: 10.0) }.sequence() }.flatMap { [unowned self] _ -> Future<Void> in guard let accelerometerDataCharacteristic = self.accelerometerDataCharacteristic else { throw AppError.dataCharactertisticNotFound } self.updateEnabled() self.updatePeriod() return accelerometerDataCharacteristic.startNotifying() }.flatMap { [unowned self] () -> FutureStream<Data?> in guard let accelerometerDataCharacteristic = self.accelerometerDataCharacteristic else { throw AppError.dataCharactertisticNotFound } return accelerometerDataCharacteristic.receiveNotificationUpdates(capacity: 10) } dataUpdateFuture.onFailure { [unowned self] error in switch error { case AppError.dataCharactertisticNotFound: fallthrough case AppError.enabledCharactertisticNotFound: fallthrough case AppError.updateCharactertisticNotFound: fallthrough case AppError.serviceNotFound: self.peripheral?.disconnect() self.present(UIAlertController.alertOnError(error), animated:true, completion:nil) case AppError.invalidState: self.present(UIAlertController.alertWithMessage("Invalid state"), animated: true, completion: nil) case AppError.resetting: self.manager.reset() self.present(UIAlertController.alertWithMessage("Bluetooth service resetting"), animated: true, completion: nil) case AppError.poweredOff: self.present(UIAlertController.alertWithMessage("Bluetooth powered off"), animated: true, completion: nil) case AppError.unknown: break case PeripheralError.disconnected: self.peripheral?.reconnect() case PeripheralError.forcedDisconnect: break default: self.present(UIAlertController.alertOnError(error), animated:true, completion:nil) } self.updateUIStatus() } dataUpdateFuture.onSuccess { [unowned self] data in self.updateData(data) } } func updateUIStatus() { if let peripheral = peripheral { switch peripheral.state { case .connected: statusLabel.text = "Connected" statusLabel.textColor = UIColor(red:0.2, green:0.7, blue:0.2, alpha:1.0) case .connecting: statusLabel.text = "Connecting" statusLabel.textColor = UIColor(red:0.9, green:0.7, blue:0.0, alpha:1.0) case .disconnected: statusLabel.text = "Disconnected" statusLabel.textColor = UIColor.lightGray case .disconnecting: statusLabel.text = "Disconnecting" statusLabel.textColor = UIColor.lightGray } if peripheral.state == .connected { enabledLabel.textColor = UIColor.black enabledSwitch.isEnabled = true } else { enabledLabel.textColor = UIColor.lightGray enabledSwitch.isEnabled = false } } else { statusLabel.text = "Disconnected" statusLabel.textColor = UIColor.lightGray enabledLabel.textColor = UIColor.lightGray enabledSwitch.isOn = false enabledSwitch.isEnabled = false activateSwitch.isOn = false } } func updateEnabled() { guard let accelerometerEnabledCharacteristic = accelerometerEnabledCharacteristic, let value : TiSensorTag.AccelerometerService.Enabled = accelerometerEnabledCharacteristic.value()else { return } enabledSwitch.isOn = value.boolValue } func updatePeriod() { guard let accelerometerUpdatePeriodCharacteristic = accelerometerUpdatePeriodCharacteristic, let value : TiSensorTag.AccelerometerService.UpdatePeriod = accelerometerUpdatePeriodCharacteristic.value() else { return } updatePeriodLabel.text = "\(value.period)" rawUpdatePeriodlabel.text = "\(value.rawValue)" } func readUpdatePeriod() { guard let accelerometerUpdatePeriodCharacteristic = accelerometerUpdatePeriodCharacteristic else { return } let readFuture = accelerometerUpdatePeriodCharacteristic.read(timeout: 10.0) readFuture.onSuccess { [unowned self] _ in self.updatePeriod() } readFuture.onFailure{ [unowned self] error in self.present(UIAlertController.alertOnError(error), animated:true, completion:nil) } } func updateData(_ data:Data?) { if let data = data, let accelerometerData: TiSensorTag.AccelerometerService.Data = SerDe.deserialize(data) { xAccelerationLabel.text = NSString(format: "%.2f", accelerometerData.x) as String yAccelerationLabel.text = NSString(format: "%.2f", accelerometerData.y) as String zAccelerationLabel.text = NSString(format: "%.2f", accelerometerData.z) as String let rawValue = accelerometerData.rawValue xRawAccelerationLabel.text = "\(rawValue[0])" yRawAccelerationLabel.text = "\(rawValue[1])" zRawAccelerationLabel.text = "\(rawValue[2])" } } func writeEnabled() { if let accelerometerEnabledCharacteristic = accelerometerEnabledCharacteristic { let value = TiSensorTag.AccelerometerService.Enabled(boolValue: enabledSwitch.isOn) let writeFuture = accelerometerEnabledCharacteristic.write(value, timeout:10.0) writeFuture.onSuccess { [unowned self] _ in self.present(UIAlertController.alertWithMessage("Accelerometer is " + (self.enabledSwitch.isOn ? "on" : "off")), animated:true, completion:nil) } writeFuture.onFailure { [unowned self] error in self.present(UIAlertController.alertOnError(error), animated:true, completion:nil) } } } func deactivate() { guard let peripheral = self.peripheral else { return } peripheral.terminate() self.peripheral = nil updateUIStatus() } }
mit
790c34d4b55184855bd4500677290b98
41.491961
215
0.641619
5.44051
false
false
false
false
tjw/swift
test/SILGen/if_expr.swift
2
2298
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s func fizzbuzz(i: Int) -> String { return i % 3 == 0 ? "fizz" : i % 5 == 0 ? "buzz" : "\(i)" // CHECK: cond_br {{%.*}}, [[OUTER_TRUE:bb[0-9]+]], [[OUTER_FALSE:bb[0-9]+]] // CHECK: [[OUTER_TRUE]]: // CHECK: br [[OUTER_CONT:bb[0-9]+]] // CHECK: [[OUTER_FALSE]]: // CHECK: cond_br {{%.*}}, [[INNER_TRUE:bb[0-9]+]], [[INNER_FALSE:bb[0-9]+]] // CHECK: [[INNER_TRUE]]: // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_FALSE]]: // CHECK: function_ref {{.*}}stringInterpolation // CHECK: br [[INNER_CONT]] // CHECK: [[INNER_CONT]]({{.*}}): // CHECK: br [[OUTER_CONT]] // CHECK: [[OUTER_CONT]]({{.*}}): // CHECK: return } protocol AddressOnly {} struct A : AddressOnly {} struct B : AddressOnly {} func consumeAddressOnly(_: AddressOnly) {} // CHECK: sil hidden @$S7if_expr19addr_only_ternary_1{{[_0-9a-zA-Z]*}}F func addr_only_ternary_1(x: Bool) -> AddressOnly { // CHECK: bb0([[RET:%.*]] : @trivial $*AddressOnly, {{.*}}): // CHECK: [[a:%[0-9]+]] = alloc_box ${ var AddressOnly }, var, name "a" // CHECK: [[PBa:%.*]] = project_box [[a]] var a : AddressOnly = A() // CHECK: [[b:%[0-9]+]] = alloc_box ${ var AddressOnly }, var, name "b" // CHECK: [[PBb:%.*]] = project_box [[b]] var b : AddressOnly = B() // CHECK: cond_br {{%.*}}, [[TRUE:bb[0-9]+]], [[FALSE:bb[0-9]+]] // CHECK: [[TRUE]]: // CHECK: [[READa:%.*]] = begin_access [read] [unknown] [[PBa]] // CHECK: copy_addr [[READa]] to [initialization] [[RET]] // CHECK: br [[CONT:bb[0-9]+]] // CHECK: [[FALSE]]: // CHECK: [[READb:%.*]] = begin_access [read] [unknown] [[PBb]] // CHECK: copy_addr [[READb]] to [initialization] [[RET]] // CHECK: br [[CONT]] return x ? a : b } // <rdar://problem/31595572> - crash when conditional expression is an // lvalue of IUO type // CHECK-LABEL: sil hidden @$S7if_expr18iuo_lvalue_ternary1xSiSbSgz_tF : $@convention(thin) (@inout Optional<Bool>) -> Int // CHECK: [[IUO_BOOL_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*Optional<Bool> // CHECK: [[IUO_BOOL:%.*]] = load [trivial] [[IUO_BOOL_ADDR]] : $*Optional<Bool> // CHECK: switch_enum [[IUO_BOOL]] func iuo_lvalue_ternary(x: inout Bool!) -> Int { return x ? 1 : 0 }
apache-2.0
ed1968d3c02ebb7f4ed578a34729b3e7
35.47619
122
0.55483
3.027668
false
false
false
false
anthonypuppo/GDAXSwift
GDAXSwift/Classes/GDAXProductTicker.swift
1
1664
// // GDAXProductTicker.swift // GDAXSwift // // Created by Anthony on 6/4/17. // Copyright © 2017 Anthony Puppo. All rights reserved. // public struct GDAXProductTicker: JSONInitializable { public let tradeID: Int public let price: Double public let size: Double public let bid: Double public let ask: Double public let volume: Double public let time: Date internal init(json: Any) throws { var jsonData: Data? if let json = json as? Data { jsonData = json } else { jsonData = try JSONSerialization.data(withJSONObject: json, options: []) } guard let json = jsonData?.json else { throw GDAXError.invalidResponseData } guard let tradeID = json["trade_id"] as? Int else { throw GDAXError.responseParsingFailure("trade_id") } guard let price = Double(json["price"] as? String ?? "") else { throw GDAXError.responseParsingFailure("price") } guard let size = Double(json["size"] as? String ?? "") else { throw GDAXError.responseParsingFailure("size") } guard let bid = Double(json["bid"] as? String ?? "") else { throw GDAXError.responseParsingFailure("bid") } guard let ask = Double(json["ask"] as? String ?? "") else { throw GDAXError.responseParsingFailure("ask") } guard let volume = Double(json["volume"] as? String ?? "") else { throw GDAXError.responseParsingFailure("volume") } guard let time = (json["time"] as? String)?.dateFromISO8601 else { throw GDAXError.responseParsingFailure("time") } self.tradeID = tradeID self.price = price self.size = size self.bid = bid self.ask = ask self.volume = volume self.time = time } }
mit
cec86f19d816fd4a4cac4f7a2a39b4e1
23.101449
75
0.671076
3.599567
false
false
false
false
padawan/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/BlogListTableViewController.swift
1
8582
// // BlogListTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/05/19. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON import SVProgressHUD class BlogList: ItemList { override func toModel(json: JSON)->BaseObject { return Blog(json: json) } override func fetch(offset: Int, success: ((items:[JSON]!, total:Int!) -> Void)!, failure: (JSON! -> Void)!) { if working {return} self.working = true UIApplication.sharedApplication().networkActivityIndicatorVisible = true let api = DataAPI.sharedInstance let app = UIApplication.sharedApplication().delegate as! AppDelegate let authInfo = app.authInfo var success: (([JSON]!, Int!)-> Void) = { (result: [JSON]!, total: Int!)-> Void in LOG("\(result)") if self.refresh { self.items = [] } self.totalCount = total self.parseItems(result) for item in self.items as! [Blog] { item.endpoint = authInfo.endpoint item.loadSettings() } success(items: result, total: total) self.postProcess() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } var failure: (JSON!-> Void) = { (error: JSON!)-> Void in LOG("failure:\(error.description)") failure(error) self.postProcess() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } api.authentication(authInfo.username, password: authInfo.password, remember: true, success:{_ in var params = ["limit":"20"] params["fields"] = "id,name,url,parent" if !self.refresh { params["offset"] = "\(self.items.count)" } if !self.searchText.isEmpty { params["search"] = self.searchText params["searchFields"] = "name" } api.listBlogsForUser("me", options: params, success: success, failure: failure) }, failure: failure ) } } //MARK: - class BlogListTableViewController: BaseTableViewController, UISearchBarDelegate { var list: BlogList = BlogList() var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = NSLocalizedString("System", comment: "System") searchBar = UISearchBar() searchBar.frame = CGRectMake(0.0, 0.0, self.tableView.frame.size.width, 44.0) searchBar.barTintColor = Color.tableBg searchBar.placeholder = NSLocalizedString("Search", comment: "Search") searchBar.delegate = self var textField = Utils.getTextFieldFromView(searchBar) if textField != nil { textField!.enablesReturnKeyAutomatically = false } self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_setting"), left: true, target: self, action: "settingButtonPushed:") // self.tableView.estimatedRowHeight = 44.0 // self.tableView.rowHeight = UITableViewAutomaticDimension self.fetch() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) UIApplication.sharedApplication().networkActivityIndicatorVisible = false } 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. } */ // MARK: - Refresh @IBAction func refresh(sender:UIRefreshControl) { self.fetch() } // MARK: - fetch func fetch() { SVProgressHUD.showWithStatus(NSLocalizedString("Fetch sites...", comment: "Fetch sites...")) var success: (([JSON]!, Int!)-> Void) = { (result: [JSON]!, total: Int!)-> Void in SVProgressHUD.dismiss() self.tableView.reloadData() self.refreshControl!.endRefreshing() } var failure: (JSON!-> Void) = { (error: JSON!)-> Void in SVProgressHUD.showErrorWithStatus(NSLocalizedString("Fetch sites failured.", comment: "Fetch sites failured.")) self.refreshControl!.endRefreshing() } list.refresh(success, failure: failure) } func more() { var success: (([JSON]!, Int!)-> Void) = { (result: [JSON]!, total: Int!)-> Void in self.tableView.reloadData() self.refreshControl!.endRefreshing() } var failure: (JSON!-> Void) = { (error: JSON!)-> Void in self.refreshControl!.endRefreshing() } list.more(success, failure: failure) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.list.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("BlogCell", forIndexPath: indexPath) as! UITableViewCell self.adjustCellLayoutMargins(cell) // Configure the cell... cell.textLabel?.textColor = Color.cellText cell.textLabel?.font = UIFont.systemFontOfSize(21.0) cell.detailTextLabel?.font = UIFont.systemFontOfSize(15.0) let blog = self.list[indexPath.row] as! Blog cell.textLabel?.text = blog.name cell.detailTextLabel?.text = blog.parentName return cell } // MARK: - Table view delegte override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let storyboard: UIStoryboard = UIStoryboard(name: "Blog", bundle: nil) let vc = storyboard.instantiateInitialViewController() as! BlogTableViewController let blog = self.list[indexPath.row] as! Blog vc.blog = blog self.navigationController?.pushViewController(vc, animated: true) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 74.0 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44.0 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return searchBar } //MARK: - override func scrollViewDidScroll(scrollView: UIScrollView) { if (self.tableView.contentOffset.y >= (self.tableView.contentSize.height - self.tableView.bounds.size.height)) { if self.list.working {return} if self.list.isFinished() {return} self.more() } } //MARK: - func settingButtonPushed(sender: UIBarButtonItem) { let storyboard: UIStoryboard = UIStoryboard(name: "Setting", bundle: nil) let vc = storyboard.instantiateInitialViewController() as! UIViewController self.presentViewController(vc, animated: true, completion: nil) } // MARK: -- func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() self.list.searchText = searchBar.text if self.list.count > 0 { self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false) } self.fetch() } }
mit
ac75d57632c56d1d9890c7d8cb468d23
34.75
159
0.612354
5.206311
false
false
false
false
ugoArangino/MJPEG-Framework
MJPEG/Connection/URLConnectionDataDelegate.swift
1
2159
// // URLConnectionDataDelegate.swift // ip-camera-viewer // // Created by Ugo Arangino on 19.12.14. // Copyright (c) 2014 Ugo Arangino. All rights reserved. // import Foundation /** * A NSURLConnectionDataDelegate implementation */ public class URLConnectionDataDelegate: NSObject, NSURLConnectionDataDelegate { weak var connection: URLConnection? private var connectionData: ConnectionData private var data = NSMutableData() public init(connectionData: ConnectionData) { self.connectionData = connectionData } // MARK: - NSURLConnectionDelegate // ServerTrust and HTTPBasic public func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) { // NSURLAuthenticationMethod - ServerTrust if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust) challenge.sender.useCredential(credential , forAuthenticationChallenge: challenge) } // NSURLAuthenticationMethod - HTTPBasic if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic { if self.connectionData.user != nil && self.connectionData.password != nil { let credential = NSURLCredential(user: connectionData.user!, password: connectionData.password!, persistence: NSURLCredentialPersistence.Synchronizable) challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge) } } } // MARK: - NSURLConnectionDataDelegate public func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { // put through data self.connection?.delegate?.responseDidFinisch(data: self.data) // reset data self.data.length = 0 } public func connection(connection: NSURLConnection, didReceiveData data: NSData) { self.data.appendData(data) } }
mit
fb2fdfda489011a52a84a58307612fc8
33.83871
168
0.700787
5.947658
false
false
false
false
adriaan/DiskFiller
DiskFiller/DiskSpaceHelper.swift
1
1202
import Foundation final class DiskSpaceHelper { private let documentPath: String? var availableDiskSpace: Int? { guard let attributes = fileSystemAttributes, let freeSpaceInBytes = attributes[FileAttributeKey.systemFreeSize] as? NSNumber else { return nil } return freeSpaceInBytes.intValue } var fractionDiskSpaceUsed: Float? { guard let attributes = fileSystemAttributes, let freeSpaceInBytes = attributes[FileAttributeKey.systemFreeSize] as? NSNumber, let totalSpaceInBytes = attributes[FileAttributeKey.systemSize] as? NSNumber else { return nil } return (totalSpaceInBytes.floatValue - freeSpaceInBytes.floatValue)/totalSpaceInBytes.floatValue } private var fileSystemAttributes: [FileAttributeKey: Any]? { guard let path = documentPath else { return nil } do { let dictionary = try FileManager.default.attributesOfFileSystem(forPath: path) return dictionary } catch { return nil } } init() { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) documentPath = paths.last } }
mit
de40f171c7e54b57722c2014c96e9147
34.352941
152
0.69218
5.488584
false
false
false
false
mo3bius/My-Simple-Instagram
My-Simple-Instagram/Custom componets/LAButton.swift
1
884
// // LAButton.swift // My-Simple-Instagram // // Created by Luigi Aiello on 30/10/17. // Copyright © 2017 Luigi Aiello. All rights reserved. // import UIKit @IBDesignable public class LAButton: UIButton { @IBInspectable public var borderColor:UIColor = .black { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable public var borderWidth:CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable public var cornerRadius:CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable public var isCircle:Bool = false { didSet { layer.cornerRadius = self.frame.height/2 } } }
mit
4d34c28f14aa0a151bd2554312f30b24
20.536585
60
0.575311
4.696809
false
false
false
false
IngmarStein/swift
test/SILGen/objc_attr_NSManaged.swift
1
4453
// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen | %FileCheck %s // REQUIRES: objc_interop // This file is also used by objc_attr_NSManaged_multi.swift. import Foundation import gizmo @objc class X : NSObject { func foo() -> X { return self } } class SwiftGizmo : Gizmo { @NSManaged var x: X @NSManaged func kvc() // CHECK-NOT: sil hidden @_TToFC19objc_attr_NSManaged10SwiftGizmog1x // CHECK-NOT: sil hidden @_TToFC19objc_attr_NSManaged10SwiftGizmos1x // CHECK-NOT: sil hidden @_TToFC19objc_attr_NSManaged10SwiftGizmo3kvc // Make sure that we're calling through the @objc entry points. // CHECK-LABEL: sil hidden @_TFC19objc_attr_NSManaged10SwiftGizmo7modifyX{{.*}} : $@convention(method) (@guaranteed SwiftGizmo) -> () { func modifyX() { // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[SELF:%.*]] : $SwiftGizmo, #SwiftGizmo.x!getter.1.foreign : (SwiftGizmo) -> () -> X , $@convention(objc_method) (SwiftGizmo) -> @autoreleased X // CHECK-NEXT: apply [[GETTER]]([[SELF]]) : $@convention(objc_method) (SwiftGizmo) -> @autoreleased X // CHECK-NOT: return // CHECK: [[SETTER:%[0-9]+]] = class_method [volatile] [[SELF]] : $SwiftGizmo, #SwiftGizmo.x!setter.1.foreign : (SwiftGizmo) -> (X) -> () , $@convention(objc_method) (X, SwiftGizmo) -> () // CHECK: apply [[SETTER]]([[XMOD:%.*]], [[SELF]]) : $@convention(objc_method) (X, SwiftGizmo) -> () x = x.foo() // CHECK: return } // CHECK-LABEL: sil hidden @_TFC19objc_attr_NSManaged10SwiftGizmo8testFunc func testFunc() { // CHECK: = class_method [volatile] %0 : $SwiftGizmo, #SwiftGizmo.kvc!1.foreign : (SwiftGizmo) -> () -> () , $@convention(objc_method) (SwiftGizmo) -> () // CHECK: return kvc() } } extension SwiftGizmo { @NSManaged func extKVC() // CHECK-LABEL: _TFC19objc_attr_NSManaged10SwiftGizmo7testExt func testExt() { // CHECK: = class_method [volatile] %0 : $SwiftGizmo, #SwiftGizmo.extKVC!1.foreign : (SwiftGizmo) -> () -> () , $@convention(objc_method) (SwiftGizmo) -> () // CHECK: return extKVC() } } final class FinalGizmo : SwiftGizmo { @NSManaged var y: String @NSManaged func kvc2() } extension FinalGizmo { @NSManaged func extKVC2() // CHECK-LABEL: _TFC19objc_attr_NSManaged10FinalGizmo8testExt2 func testExt2() { // CHECK: = class_method [volatile] %0 : $FinalGizmo, #FinalGizmo.extKVC2!1.foreign : (FinalGizmo) -> () -> () , $@convention(objc_method) (FinalGizmo) -> () // CHECK: return extKVC2() } } // CHECK-LABEL: sil hidden @_TF19objc_attr_NSManaged9testFinalFCS_10FinalGizmoSS : $@convention(thin) (@owned FinalGizmo) -> @owned String { func testFinal(_ obj: FinalGizmo) -> String { // CHECK: class_method [volatile] %0 : $FinalGizmo, #FinalGizmo.kvc2!1.foreign : (FinalGizmo) -> () -> () , $@convention(objc_method) (FinalGizmo) -> () // CHECK-NOT: return // CHECK: class_method [volatile] %0 : $FinalGizmo, #FinalGizmo.y!getter.1.foreign : (FinalGizmo) -> () -> String , $@convention(objc_method) (FinalGizmo) -> @autoreleased NSString // CHECK: return obj.kvc2() return obj.y } // CHECK-NOT: sil hidden @_TToFC19objc_attr_NSManaged10SwiftGizmog1xCS_1X : $@convention(objc_method) (SwiftGizmo) -> @autoreleased X // CHECK-NOT: sil hidden @_TToFC19objc_attr_NSManaged10SwiftGizmos1xCS_1X // CHECK-NOT: sil hidden @_TToFC19objc_attr_NSManaged10FinalGizmog1y // The vtable should not contain any entry points for getters and setters. // CHECK-LABEL: sil_vtable SwiftGizmo { // CHECK-NEXT: #SwiftGizmo.modifyX!1: _TFC19objc_attr_NSManaged10SwiftGizmo7modifyX // CHECK-NEXT: #SwiftGizmo.testFunc!1: _TFC19objc_attr_NSManaged10SwiftGizmo8testFunc // CHECK-NEXT: #SwiftGizmo.init!initializer.1: _TFC19objc_attr_NSManaged10SwiftGizmoc // CHECK-NEXT: #SwiftGizmo.init!initializer.1: _TFC19objc_attr_NSManaged10SwiftGizmoc // CHECK-NEXT: #SwiftGizmo.deinit!deallocator: // CHECK-NEXT: } // CHECK-LABEL: sil_vtable FinalGizmo { // CHECK-NEXT: #SwiftGizmo.modifyX!1: _TFC19objc_attr_NSManaged10SwiftGizmo7modifyX // CHECK-NEXT: #SwiftGizmo.testFunc!1: _TFC19objc_attr_NSManaged10SwiftGizmo8testFunc // CHECK-NEXT: #SwiftGizmo.init!initializer.1: _TFC19objc_attr_NSManaged10FinalGizmoc // CHECK-NEXT: #SwiftGizmo.init!initializer.1: _TFC19objc_attr_NSManaged10FinalGizmoc // CHECK-NEXT: #FinalGizmo.deinit!deallocator: _TFC19objc_attr_NSManaged10FinalGizmoD // CHECK-NEXT: }
apache-2.0
a85b3ae09ac7dd20eb3539c54eaff5e8
42.656863
205
0.693241
3.404434
false
true
false
false
soapyigu/LeetCode_Swift
DFS/StrobogrammaticNumberII.swift
1
1490
/** * Question Link: https://leetcode.com/problems/strobogrammatic-number-ii/ * Primary idea: Classic DFS, set two places with correspond characters; * starting from head and tail, and then move towards middle to cover all places. * Time Complexity: O(m^n), here m is 5; Space Complexity: O(n) * */ class StrobogrammaticNumberII { func findStrobogrammatic(_ n: Int) -> [String] { var res = [String]() guard n >= 1 else { return res } let left = Array("01689"), right = Array("01986") var path = Array(repeating: Character("-"), count: n) dfs(&res, left, right, 0, n - 1, &path) return res } fileprivate func dfs(_ res: inout [String], _ left: [Character], _ right: [Character], _ leftIdx: Int, _ path: inout [Character]) { let rightIdx = path.count - leftIdx - 1 if leftIdx > rightIdx { res.append(String(path)) return } for i in 0..<left.count { if leftIdx == 0 && leftIdx != rightIdx && left[i] == "0" { continue } if leftIdx == rightIdx && (left[i] == "6" || left[i] == "9") { continue } path[leftIdx] = left[i] path[rightIdx] = right[i] dfs(&res, left, right, leftIdx + 1, rightIdx - 1, &path) } } }
mit
807d5ce5e3931588df09133e0ceb0bdf
29.428571
135
0.491275
3.962766
false
false
false
false
luosheng/OpenSim
OpenSim/MenuManager.swift
1
10249
// // MenuManager.swift // OpenSim // // Created by Luo Sheng on 16/3/24. // Copyright © 2016年 Luo Sheng. All rights reserved. // import Foundation import Cocoa protocol MenuManagerDelegate { func shouldQuitApp() } @objc final class MenuManager: NSObject, NSMenuDelegate { let statusItem: NSStatusItem var focusedMode: Bool = true var watcher: DirectoryWatcher! var subWatchers: [DirectoryWatcher?]? var block: dispatch_cancelable_block_t? var delegate: MenuManagerDelegate? var menuObserver: CFRunLoopObserver? override init() { statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) statusItem.image = NSImage(named: NSImage.Name(rawValue: "menubar")) statusItem.image!.isTemplate = true super.init() buildMenu() } deinit { stop() } func start() { buildWatcher() buildSubWatchers() } func stop() { watcher.stop() subWatchers?.forEach { $0?.stop() } } private func buildMenu() { let menu = NSMenu() menu.addItem(NSMenuItem.separator()) let refreshMenuItem = menu.addItem(withTitle: UIConstants.strings.menuRefreshButton, action: #selector(self.refreshItemClicked(_:)), keyEquivalent: "r") refreshMenuItem.target = self let focusedModeMenuItem = menu.addItem(withTitle: UIConstants.strings.menuFocusedModeButton, action: #selector(self.toggleFocusedMode), keyEquivalent: "") focusedModeMenuItem.target = self focusedModeMenuItem.state = self.focusedMode ? .on : .off let launchAtLoginMenuItem = menu.addItem(withTitle: UIConstants.strings.menuLaunchAtLoginButton, action: #selector(self.launchItemClicked(_:)), keyEquivalent: "") launchAtLoginMenuItem.target = self if existingItem(itemUrl: Bundle.main.bundleURL) != nil { launchAtLoginMenuItem.state = .on } else { launchAtLoginMenuItem.state = .off } DeviceManager.defaultManager.reload { (runtimes) in var sortedList = [Runtime]() _ = Dictionary(grouping: runtimes, by: { (runtime: Runtime) in return runtime.platform }).values.map({ (runtimeList: [Runtime]) -> [Runtime] in return runtimeList.sorted { $0.version ?? 0.0 > $1.version ?? 0.0 } }).forEach({ (list) in sortedList.append(contentsOf: list) }) sortedList.forEach { (runtime) in var devices = runtime.devices if self.focusedMode { devices = devices.filter { $0.state == .booted || $0.applications?.count ?? 0 > 0 } } if devices.count == 0 { return } menu.addItem(NSMenuItem.separator()) let titleItem = NSMenuItem(title: "\(runtime)", action: nil, keyEquivalent: "") titleItem.isEnabled = false menu.addItem(titleItem) devices.forEach({ (device) in let deviceMenuItem = menu.addItem(withTitle: device.name, action: nil, keyEquivalent: "") deviceMenuItem.onStateImage = NSImage(named: NSImage.Name(rawValue: "active")) deviceMenuItem.offStateImage = NSImage(named: NSImage.Name(rawValue: "inactive")) deviceMenuItem.state = device.state == .booted ? .on : .off let submenu = NSMenu() submenu.delegate = self // Launch Simulator let simulatorItem = SimulatorMenuItem(runtime:runtime, device:device) submenu.addItem(simulatorItem) submenu.addItem(NSMenuItem.separator()) // Sort applications by name let sortApplications = device.applications?.sorted(by: { (app1, app2) -> Bool in app1.bundleDisplayName.lowercased() < app2.bundleDisplayName.lowercased() }) sortApplications?.forEach { app in let appMenuItem = AppMenuItem(application: app) appMenuItem.submenu = ActionMenu(device: device, application: app) submenu.addItem(appMenuItem) } deviceMenuItem.submenu = submenu // Simulator Shutdown/Reset submenu.addItem(NSMenuItem.separator()) if device.state == .booted { submenu.addItem(SimulatorShutdownMenuItem(device: device)) } if device.applications?.count ?? 0 > 0 { submenu.addItem(SimulatorResetMenuItem(device: device)) } submenu.addItem(SimulatorEraseMenuItem(device: device)) }) } menu.addItem(NSMenuItem.separator()) let eraseAllSimulators = menu.addItem(withTitle: UIConstants.strings.menuShutDownAllSimulators, action: #selector(self.factoryResetAllSimulators), keyEquivalent: "") eraseAllSimulators.target = self let eraseAllShutdownSimulators = menu.addItem(withTitle: UIConstants.strings.menuShutDownAllBootedSimulators, action: #selector(self.factoryResetAllShutdownSimulators), keyEquivalent: "") eraseAllShutdownSimulators.target = self menu.addItem(NSMenuItem.separator()) let quitMenu = menu.addItem(withTitle: UIConstants.strings.menuQuitButton, action: #selector(self.quitItemClicked(_:)), keyEquivalent: "q") quitMenu.target = self if let versionNumber = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { menu.addItem(NSMenuItem.separator()) menu.addItem(withTitle: "\(UIConstants.strings.menuVersionLabel) \(versionNumber)", action: nil, keyEquivalent: "") } self.statusItem.menu = menu } } private func buildWatcher() { watcher = DirectoryWatcher(in: URLHelper.deviceURL) watcher.completionCallback = { [weak self] in self?.reloadWhenReady(delay: 5) self?.buildSubWatchers() } try? watcher.start() } private func buildSubWatchers() { subWatchers?.forEach { $0?.stop() } let deviceDirectories = try? FileManager.default.contentsOfDirectory(at: URLHelper.deviceURL as URL, includingPropertiesForKeys: FileInfo.prefetchedProperties, options: .skipsSubdirectoryDescendants) subWatchers = deviceDirectories?.map(createSubWatcherForURL) } private func createSubWatcherForURL(_ URL: Foundation.URL) -> DirectoryWatcher? { guard let info = FileInfo(URL: URL), info.isDirectory else { return nil } let watcher = DirectoryWatcher(in: URL) watcher.completionCallback = { [weak self] in self?.reloadWhenReady() } try? watcher.start() return watcher } @objc private func toggleFocusedMode() { focusedMode = !focusedMode reloadWhenReady(delay: 0) } private func reloadWhenReady(delay: TimeInterval = 1) { dispatch_cancel_block_t(self.block) self.block = dispatch_block_t(delay) { [weak self] in self?.watcher.stop() self?.buildMenu() try? self?.watcher.start() } } @objc func quitItemClicked(_ sender: AnyObject) { delegate?.shouldQuitApp() } @objc func refreshItemClicked(_ sender: AnyObject) { reloadWhenReady() } @objc func launchItemClicked(_ sender: NSMenuItem) { let wasOn = sender.state == .on sender.state = (wasOn ? .off : .on) setLaunchAtLogin(itemUrl: Bundle.main.bundleURL, enabled: !wasOn) } private func resetAllSimulators() { DeviceManager.defaultManager.reload { (runtimes) in runtimes.forEach({ (runtime) in let devices = runtime.devices.filter { $0.applications?.count ?? 0 > 0 } self.resetSimulators(devices) }) } } private func resetShutdownSimulators() { DeviceManager.defaultManager.reload { (runtimes) in runtimes.forEach({ (runtime) in var devices = runtime.devices.filter { $0.applications?.count ?? 0 > 0 } devices = devices.filter { $0.state == .shutdown } self.resetSimulators(devices) }) } } private func resetSimulators(_ devices: [Device]) { devices.forEach { (device) in if device.state == .booted { device.shutDown() } device.factoryReset() } } @objc func factoryResetAllSimulators() { let alert: NSAlert = NSAlert() alert.messageText = String(format: UIConstants.strings.actionFactoryResetAllSimulatorsMessage) alert.alertStyle = .critical alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertConfirmButton) alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertCancelButton) let response = alert.runModal() if response == NSApplication.ModalResponse.alertFirstButtonReturn { resetAllSimulators() } } @objc func factoryResetAllShutdownSimulators() { let alert: NSAlert = NSAlert() alert.messageText = String(format: UIConstants.strings.actionFactoryResetAllShutdownSimulatorsMessage) alert.alertStyle = .critical alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertConfirmButton) alert.addButton(withTitle: UIConstants.strings.actionFactoryResetAlertCancelButton) let response = alert.runModal() if response == NSApplication.ModalResponse.alertFirstButtonReturn { resetShutdownSimulators() } } }
mit
5ca093eb9af265d35c630852c45235b9
37.518797
207
0.599453
5.01763
false
false
false
false
MrZoidberg/metapp
metapp/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift
46
3524
// // Timeout.swift // RxSwift // // Created by Tomi Koskinen on 13/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class TimeoutSink<ElementType, O: ObserverType>: Sink<O>, LockOwnerType, ObserverType where O.E == ElementType { typealias E = ElementType typealias Parent = Timeout<E> private let _parent: Parent let _lock = NSRecursiveLock() private let _timerD = SerialDisposable() private let _subscription = SerialDisposable() private var _id = 0 private var _switched = false init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let original = SingleAssignmentDisposable() _subscription.disposable = original _createTimeoutTimer() original.setDisposable(_parent._source.subscribeSafe(self)) return Disposables.create(_subscription, _timerD) } func on(_ event: Event<E>) { switch event { case .next: var onNextWins = false _lock.performLocked() { onNextWins = !self._switched if onNextWins { self._id = self._id &+ 1 } } if onNextWins { forwardOn(event) self._createTimeoutTimer() } case .error, .completed: var onEventWins = false _lock.performLocked() { onEventWins = !self._switched if onEventWins { self._id = self._id &+ 1 } } if onEventWins { forwardOn(event) self.dispose() } } } private func _createTimeoutTimer() { if _timerD.isDisposed { return } let nextTimer = SingleAssignmentDisposable() _timerD.disposable = nextTimer let disposeSchedule = _parent._scheduler.scheduleRelative(_id, dueTime: _parent._dueTime) { state in var timerWins = false self._lock.performLocked() { self._switched = (state == self._id) timerWins = self._switched } if timerWins { self._subscription.disposable = self._parent._other.subscribeSafe(self.forwarder()) } return Disposables.create() } nextTimer.setDisposable(disposeSchedule) } } class Timeout<Element> : Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _dueTime: RxTimeInterval fileprivate let _other: Observable<Element> fileprivate let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, other: Observable<Element>, scheduler: SchedulerType) { _source = source _dueTime = dueTime _other = other _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mpl-2.0
7cd745e27b35bb661a2fa695f6e5c496
27.877049
145
0.549815
5.362253
false
false
false
false
imobilize/Molib
Molib/Classes/CoreDataUtils/NSManagedObject+Conversion.swift
1
4010
import Foundation import CoreData extension NSManagedObject { open override func value(forUndefinedKey key: String) -> Any? { debugPrint("Not able to set undefined key: %@", key) return nil } open override func setValue(_ value: Any?, forUndefinedKey key: String) { debugPrint("Couldn't set value for key: %@", key) } } public extension NSManagedObject { public func configureWithDictionary(dictionary: [String: Any]) { safeSetValuesForKeysWithDictionary(keyedValues: dictionary) } func safeSetValuesForKeysWithDictionary(keyedValues: Dictionary<String, Any>) { let dateFormatter: DateFormatter = DateFormatter() //The Z at the end of your string represents Zulu which is UTC dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" dateFormatter.timeZone = TimeZone(identifier: "UTC") safeSetValuesForKeysWithDictionary(keyedValues: keyedValues, dateFormatter:dateFormatter) } func safeSetValuesForKeysWithDictionary(keyedValues: Dictionary<String, Any>, dateFormatter:DateFormatter) { let attributes: [String: NSAttributeDescription] = self.entity.attributesByName for (key, _) in attributes { let valueOptional = keyedValues[key] as? AnyObject if var value: AnyObject = valueOptional { if let attribute = attributes[key] { let attributeType = attribute.attributeType switch attributeType { case .stringAttributeType: if let number = value as? NSNumber { value = number.stringValue as AnyObject } else if let _ = value as? NSNull { value = "" as AnyObject } else if let string = value as? NSString { let range = string.range(of: "^\\s*") if range.location != NSNotFound { let result = string.replacingCharacters(in: range, with: "") value = result as AnyObject } } case .integer16AttributeType, .integer32AttributeType, .integer64AttributeType, .booleanAttributeType: if let number = value as? NSString { value = NSNumber(value: number.integerValue) } case .floatAttributeType: if let number = value as? NSString { value = NSNumber(value: number.doubleValue) } case .dateAttributeType: if let number = value as? String { if let formattedDate = dateFormatter.date(from: number) { value = formattedDate as AnyObject } else { value = "" as AnyObject } } else if let number = value as? NSNumber { value = NSDate(timeIntervalSince1970: number.doubleValue / 1000) } default: break } if value.isKind(of: NSNull.self) == false { self.setValue(value, forKey:key ) } } } } } func dictionary() -> [String: AnyObject] { var dictionary = [String: AnyObject]() let attributes = self.entity.attributesByName for (key, _) in attributes { if let value: AnyObject = self.value(forKey: key) as AnyObject? { dictionary[key ] = value } } return dictionary } }
apache-2.0
46bef495e49c33183883e8767dedda2a
29.378788
122
0.502993
6.084977
false
false
false
false
SnowdogApps/Project-Needs-Partner
CooperationFinder/Model/Project.swift
1
9091
// // Project.swift // CooperationFinder // // Created by Rafal Kwiatkowski on 25.02.2015. // Copyright (c) 2015 Snowdog. All rights reserved. // let ProjectStatusOpen = "open" let ProjectStatusRejected = "rejected" let ProjectStatusArchived = "archived" let ProjectStatusWaitingForApproval = "waiting_for_approval" class Project { var id : String? var name : String? var createdAt : NSDate? var desc : String? var commercial : Bool? var author : User? var positions : [Position]? var applications : [Application]? var status : String init() { self.status = ProjectStatusOpen } class func saveProject(project: Project, completion: (success: Bool) -> Void) { if (project.id != nil) { let query : PFQuery = PFQuery(className: "Project") query.whereKey("objectId", equalTo: project.id) let pProject = query.getFirstObject() self.setParseProjectFields(pProject, fromProject:project) pProject.saveInBackgroundWithBlock({ (success: Bool, error: NSError!) -> Void in completion(success: success) }) } else { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in let pProject = self.serializeProject(project) pProject.saveInBackgroundWithBlock({ (success: Bool, error: NSError!) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(success: success) }) }) }) } } class func getProjects(myProjects: Bool?, searchPhrase: String?, tags: [String]?, statuses: [String]?, commercial: Bool?, partner: Bool?, completion: (success: Bool, projects: [Project]?) -> Void) { let query : PFQuery = PFQuery(className: "Project") if (myProjects != nil) { var userId = Defaults["user_id"].string if (userId != nil) { let subquery = PFQuery(className: "User") subquery.whereKey("objectId", equalTo: userId) query.whereKey("author", matchesQuery: subquery) } } if (searchPhrase != nil) { query.whereKey("name", containsString: searchPhrase) } if (tags != nil) { if (tags?.count > 0) { let subquery = PFQuery(className: "Position") subquery.whereKey("tags", containedIn: tags) query.whereKey("positions", matchesQuery: subquery) } } if (statuses != nil && statuses?.count > 0) { query.whereKey("status", containedIn: statuses) } if (commercial != nil) { query.whereKey("commercial", equalTo: commercial) } if (partner != nil && partner == true) { let subquery = PFQuery(className: "User") subquery.whereKey("partner", equalTo: partner) query.whereKey("author", matchesQuery:subquery) } query.findObjectsInBackgroundWithBlock({ (result: [AnyObject]!, error: NSError!) -> Void in if (error == nil) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in var projects : [Project] = [] let pResult = result as! [PFObject] for pProject: PFObject in pResult { let project = Project.parseProject(pProject) projects.append(project) } dispatch_async(dispatch_get_main_queue(), { () -> Void in completion(success: true, projects: projects) }) }) } else { completion(success: false, projects: nil) } }) } class func deleteProject(project: Project, completion: (success: Bool) -> Void) { if (project.id != nil) { let query : PFQuery = PFQuery(className: "Project") query.whereKey("objectId", equalTo: project.id) let pProject = query.getFirstObject() if (pProject != nil) { pProject.deleteInBackgroundWithBlock({ (success: Bool, error: NSError!) -> Void in completion(success: success) }) } else { completion(success: false) } } else { completion(success: false) } } class func parseProject(parseProject: PFObject, parseApplication: Bool = true) -> Project { let project = Project() project.id = parseProject.valueForKey("objectId") as? String project.name = parseProject.valueForKey("name") as? String project.createdAt = parseProject.createdAt project.desc = parseProject.valueForKey("desc") as? String project.commercial = parseProject.valueForKey("commercial") as? Bool if let status = parseProject.valueForKey("status") as? String { project.status = status as String } let posRelation = parseProject.relationForKey("positions"); let pPositions = posRelation.query().findObjects() as! [PFObject]! var positions : [Position] = [] for pPosition : PFObject in pPositions { let position = Position.parsePosition(pPosition) positions.append(position); } project.positions = positions let authorRelation = parseProject.relationForKey("author"); let pAuthor = authorRelation.query().getFirstObject() let author = User.parseUser(pAuthor) project.author = author if (parseApplication) { let query = PFQuery(className: "Application") query.whereKey("project", equalTo: parseProject) let pApplications = query.findObjects() as! [PFObject] var applications : [Application] = []; for pApplication : PFObject in pApplications { let application = Application.parseApplication(pApplication) application.project = project applications.append(application) } project.applications = applications } return project } class func serializeProject(project: Project) -> PFObject { var pProject : PFObject! if (project.id != nil) { let query : PFQuery = PFQuery(className: "Project") query.whereKey("objectId", equalTo: project.id) pProject = query.getFirstObject() } if (pProject == nil) { pProject = PFObject(className: "Project") } pProject.setIfNotNil(project.id, key: "objectId") pProject.setIfNotNil(project.name, key: "name") pProject.setIfNotNil(project.desc, key: "desc") pProject.setIfNotNil(project.status, key: "status") pProject.setIfNotNil(project.commercial, key: "commercial") if let positions = project.positions { let posRelation = pProject.relationForKey("positions"); for pos : Position in positions { if (pos.id != nil) { let query : PFQuery = PFQuery(className: "Position") query.whereKey("objectId", equalTo: pos.id) let pPos = query.getFirstObject() if (pPos != nil) { posRelation.addObject(pPos) } } else { let pPos = Position.serializePosition(pos) pPos.save() posRelation.addObject(pPos) } } } if let author = project.author { let authorRelation = pProject.relationForKey("author"); if (author.id != nil) { let query : PFQuery = PFQuery(className: "User") query.whereKey("objectId", equalTo: author.id) let pAuthor = query.getFirstObject() if (pAuthor != nil) { authorRelation.addObject(pAuthor) } } else { let pAuthor = User.serializeUser(author) pAuthor.save() authorRelation.addObject(pAuthor) } } return pProject } class func setParseProjectFields(pProject: PFObject, fromProject project: Project) { pProject.setIfNotNil(project.id, key: "objectId") pProject.setIfNotNil(project.name, key: "name") pProject.setIfNotNil(project.desc, key: "desc") pProject.setIfNotNil(project.status, key: "status") pProject.setIfNotNil(project.commercial, key: "commercial") } }
apache-2.0
1cf30f2eec311702a6865ba4d583f943
37.037657
202
0.544605
4.908747
false
false
false
false
egnwd/ic-bill-hack
quick-split/quick-split/FriendTotalCollectionViewCell.swift
1
2538
// // FriendTotalCollectionViewCell.swift // quick-split // // Created by Elliot Greenwood on 02.20.2016. // Copyright © 2016 stealth-phoenix. All rights reserved. // import UIKit class FriendTotalCollectionViewCell: UICollectionViewCell { let cellSize = CGSize(width: 80, height: 110) let defaultColour = UIColor.whiteColor() let defaultBorderWidth: CGFloat = 4.0 let maxBorderWidth: CGFloat = 6.0 var indicator: UIView = UIView() var total: Int = 0 { didSet { totalLabel.text = priceFormat(total) } } var totalLabel: UILabel = UILabel() var avatar: UIImageView = UIImageView() var friend: Friend? var isChosen = false required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) indicator.frame = CGRect(x: cellSize.width/8, y: -defaultBorderWidth, width: cellSize.width*3/4, height: defaultBorderWidth) self.addSubview(indicator) } func populateWithFriend(friend: Friend) { self.friend = friend let imageLength = 64 let imageX = (Int(cellSize.width) - imageLength) / 2 avatar = UIImageView(frame: CGRect(x: imageX, y: 10, width: imageLength, height: imageLength)) avatar.image = friend.picture let lyr = avatar.layer lyr.masksToBounds = true lyr.cornerRadius = avatar.bounds.size.width / 2 self.addSubview(avatar) totalLabel = UILabel(frame: CGRect(x: 0, y: imageLength+10, width: Int(cellSize.width), height: 24)) totalLabel.text = priceFormat(0) totalLabel.textAlignment = .Center self.addSubview(totalLabel) self.highlightCell(withColour: friend.colour!) } func highlightCell(withColour colour: UIColor) { setBorderWidth(defaultBorderWidth) self.avatar.layer.borderColor = colour.CGColor self.indicator.backgroundColor = colour friend!.colour = colour } func unhighlightCell() { setBorderWidth(0) friend!.colour = defaultColour } func selectCell() { showIndicator(true) } func deselectCell() { showIndicator(false) } private func showIndicator(show: Bool) { let amount = show ? defaultBorderWidth : -defaultBorderWidth UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseOut, animations: { self.indicator.frame.origin.y += amount }, completion: nil) } private func setBorderWidth(width: CGFloat) { self.avatar.layer.borderWidth = width } private func priceFormat(price: Int) -> String { return String(format: "£%d.%02d", arguments: [price / 100, price % 100]) } }
mit
786fc8f2dbd9145c42a5dc6b97f8f3ec
27.494382
128
0.691246
3.981162
false
false
false
false
ulrikdamm/Forbind
Forbind/Bind.swift
1
17775
// // Bind.swift // BindTest // // Created by Ulrik Damm on 30/01/15. // Copyright (c) 2015 Ufd.dk. All rights reserved. // import Foundation // A bind chains a value to an expression, like a function call. The difference // is that the bind can unpack a value before it's passed to the function. // This can be unwrapping an optional, checking a result for errors, or even // waiting for a promise to have a value. If the validation fails, the bind will // quit early. This allows you to chain operations together, such as: // // let result = getInput => sendNetworkRequest => parseJSON => parseResult // // All of these operations might fail. If it does, the chain of expressions is // ended early, and the result will be an error state. Before using the result // in the end, you will have to unpack it. // // Binds automatically upgrades to the required type. This means that if you // bind a non-optional value to an optional value, the result will be an // optional. It will even combine different types, so that if you bind a // result type to a promise, the final value will be a ResultPromise. // // If you bind an optional value to a result type, the final type will be // Result. In that case, if the optional is nil, the final value will be a // Result.Error with an NSError in the dk.ufd.Forbind domain. // // This file specifies how each type binds to another type. You can bind the // follow types: // T, T?, Result<T>, Promise<T>, Promise<T?>, Promise<Result<T>> infix operator => : AdditionPrecedence // Basic binds public func bind<T, U>(_ from : T, to : (T) -> U) -> U { return to(from) } public func =><T, U>(lhs : T, rhs : (T) -> U) -> U { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : T?, to : (T) -> U) -> U? { if let from = from { return to(from) } else { return nil } } public func =><T, U>(lhs : T?, rhs : (T) -> U) -> U? { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Result<T>, to : (T) -> U) -> Result<U> { switch from { case .ok(let value): return .ok(to(value)) case .error(let error): return .error(error) } } public func =><T, U>(lhs : Result<T>, rhs : (T) -> U) -> Result<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T>, to : @escaping (T) -> U) -> Promise<U> { let promise = Promise<U>() promise.previousPromise = from from.getValueWeak { [weak promise] value in promise?.setValue(to(value)) } return promise } public func =><T, U>(lhs : Promise<T>, rhs : @escaping (T) -> U) -> Promise<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T?>, to : @escaping (T) -> U) -> Promise<U?> { let promise = Promise<U?>() promise.previousPromise = from from.getValueWeak { [weak promise] value in if let value = value { promise?.setValue(to(value)) } else { promise?.setValue(nil) } } return promise } public func =><T, U>(lhs : Promise<T?>, rhs : @escaping (T) -> U) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<Result<T>>, to : @escaping (T) -> U) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in switch value { case .ok(let value): promise?.setValue(.ok(to(value))) case .error(let error): promise?.setValue(.error(error)) } } return promise } public func =><T, U>(lhs : Promise<Result<T>>, rhs : @escaping (T) -> U) -> Promise<Result<U>> { return bind(lhs, to: rhs) } // Bind to Optional public func bind<T, U>(_ from : T, to : (T) -> U?) -> U? { return to(from) } public func =><T, U>(lhs : T, rhs : (T) -> U?) -> U? { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : T?, to : (T) -> U?) -> U? { if let from = from { return to(from) } else { return nil } } public func =><T, U>(lhs : T?, rhs : (T) -> U?) -> U? { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Result<T>, to : (T) -> U?) -> Result<U> { switch from { case .ok(let value): if let v = to(value) { return .ok(v) } else { return .error(NilError()) } case .error(let error): return .error(error) } } public func =><T, U>(lhs : Result<T>, rhs : (T) -> U?) -> Result<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T>, to : @escaping (T) -> U?) -> Promise<U?> { let promise = Promise<U?>() promise.previousPromise = from from.getValueWeak { [weak promise] value in promise?.setValue(to(value)) } return promise } public func =><T, U>(lhs : Promise<T>, rhs : @escaping (T) -> U?) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T?>, to : @escaping (T) -> U?) -> Promise<U?> { let promise = Promise<U?>() promise.previousPromise = from from.getValueWeak { [weak promise] value in if let value = value { promise?.setValue(to(value)) } else { promise?.setValue(nil) } } return promise } public func =><T, U>(lhs : Promise<T?>, rhs : @escaping (T) -> U?) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<Result<T>>, to : @escaping (T) -> U?) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in switch value { case .ok(let value): if let v = to(value) { promise?.setValue(.ok(v)) } else { promise?.setValue(.error(NilError())) } case .error(let error): promise?.setValue(.error(error)) } } return promise } public func =><T, U>(lhs : Promise<Result<T>>, rhs : @escaping (T) -> U?) -> Promise<Result<U>> { return bind(lhs, to: rhs) } // Bind to Result public func bind<T, U>(_ from : T, to : (T) -> Result<U>) -> Result<U> { return to(from) } public func =><T, U>(lhs : T, rhs : (T) -> Result<U>) -> Result<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : T?, to : (T) -> Result<U>) -> Result<U> { if let from = from { return to(from) } else { return .error(NilError()) } } public func =><T, U>(lhs : T?, rhs : (T) -> Result<U>) -> Result<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Result<T>, to : (T) -> Result<U>) -> Result<U> { switch from { case .ok(let value): return to(value) case .error(let error): return .error(error) } } public func =><T, U>(lhs : Result<T>, rhs : (T) -> Result<U>) -> Result<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T>, to : @escaping (T) -> Result<U>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in promise?.setValue(to(value)) } return promise } public func =><T, U>(lhs : Promise<T>, rhs : @escaping (T) -> Result<U>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T?>, to : @escaping (T) -> Result<U>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in if let value = value { promise?.setValue(to(value)) } else { promise?.setValue(.error(NilError())) } } return promise } public func =><T, U>(lhs : Promise<T?>, rhs : @escaping (T) -> Result<U>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<Result<T>>, to : @escaping (T) -> Result<U>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in switch value { case .ok(let value): promise?.setValue(to(value)) case .error(let error): promise?.setValue(.error(error)) } } return promise } public func =><T, U>(lhs : Promise<Result<T>>, rhs : @escaping (T) -> Result<U>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } // Bind to throwing public func bind<T, U>(_ from : T, to : (T) throws -> U) -> Result<U> { return Result(from: from, to) } public func =><T, U>(lhs : T, rhs : (T) throws -> U) -> Result<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : T?, to : (T) throws -> U) -> Result<U> { if let from = from { return Result(from: from, to) } else { return .error(NilError()) } } public func =><T, U>(lhs : T?, rhs : (T) throws -> U) -> Result<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Result<T>, to : (T) throws -> U) -> Result<U> { switch from { case .ok(let value): return Result(from: value, to) case .error(let error): return .error(error) } } public func =><T, U>(lhs : Result<T>, rhs : (T) throws -> U) -> Result<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T>, to : @escaping (T) throws -> U) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in promise?.setValue(Result(from: value, to)) } return promise } public func =><T, U>(lhs : Promise<T>, rhs : @escaping (T) throws -> U) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T?>, to : @escaping (T) throws -> U) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in if let value = value { promise?.setValue(Result(from: value, to)) } else { promise?.setValue(.error(NilError())) } } return promise } public func =><T, U>(lhs : Promise<T?>, rhs : @escaping (T) throws -> U) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<Result<T>>, to : @escaping (T) throws -> U) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in switch value { case .ok(let value): promise?.setValue(Result(from: value, to)) case .error(let error): promise?.setValue(.error(error)) } } return promise } public func =><T, U>(lhs : Promise<Result<T>>, rhs : @escaping (T) throws -> U) -> Promise<Result<U>> { return bind(lhs, to: rhs) } // Bind to Promise public func bind<T, U>(_ from : T, to : @escaping (T) -> Promise<U>) -> Promise<U> { return to(from) } public func =><T, U>(lhs : T, rhs : @escaping (T) -> Promise<U>) -> Promise<U> { return rhs(lhs) } public func bind<T, U>(_ from : T?, to : @escaping (T) -> Promise<U>) -> Promise<U?> { let promise = Promise<U?>() if let from = from { let p = to(from) promise.previousPromise = p p.getValueWeak { [weak promise] value in promise?.setValue(value) } } else { promise.setValue(nil) } return promise } public func =><T, U>(lhs : T?, rhs : @escaping (T) -> Promise<U>) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Result<T>, to : @escaping (T) -> Promise<U>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() switch from { case .ok(let value): let p = to(value) promise.previousPromise = p p.getValueWeak { [weak promise] value in promise?.setValue(.ok(value)) } case .error(let error): promise.setValue(.error(error)) } return promise } public func =><T, U>(lhs : Result<T>, rhs : @escaping (T) -> Promise<U>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T>, to : @escaping (T) -> Promise<U>) -> Promise<U> { let promise = Promise<U>() promise.previousPromise = from from.getValueWeak { value in to(value).getValue { [weak promise] value in promise?.setValue(value) } } return promise } public func =><T, U>(lhs : Promise<T>, rhs : @escaping (T) -> Promise<U>) -> Promise<U> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T?>, to : @escaping (T) -> Promise<U>) -> Promise<U?> { let promise = Promise<U?>() promise.previousPromise = from from.getValueWeak { [weak promise] value in switch value { case .some(let v): to(v).getValue { [weak promise] value in promise?.setValue(value) } case .none: promise?.setValue(nil) } } return promise } public func =><T, U>(lhs : Promise<T?>, rhs : @escaping (T) -> Promise<U>) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<Result<T>>, to : @escaping (T) -> Promise<U>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in switch value { case .ok(let value): to(value).getValue { [weak promise] value in promise?.setValue(.ok(value)) } case .error(let error): promise?.setValue(.error(error)) } } return promise } public func =><T, U>(lhs : Promise<Result<T>>, rhs : @escaping (T) -> Promise<U>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } // Bind to OptionalPromise public func bind<T, U>(_ from : T, to : @escaping (T) -> Promise<U?>) -> Promise<U?> { return to(from) } public func =><T, U>(lhs : T, rhs : @escaping (T) -> Promise<U?>) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : T?, to : @escaping (T) -> Promise<U?>) -> Promise<U?> { if let from = from { return to(from) } else { return Promise(value: nil) } } public func =><T, U>(lhs : T?, rhs : @escaping (T) -> Promise<U?>) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Result<T>, to : @escaping (T) -> Promise<U?>) -> Promise<U?> { switch from { case .ok(let value): return to(value) case .error(_): return Promise(value: nil) } } public func =><T, U>(lhs : Result<T>, rhs : @escaping (T) -> Promise<U?>) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T>, to : @escaping (T) -> Promise<U?>) -> Promise<U?> { let promise = Promise<U?>() promise.previousPromise = from from.getValueWeak { value in to(value).getValue { [weak promise] value in promise?.setValue(value) } } return promise } public func =><T, U>(lhs : Promise<T>, rhs : @escaping (T) -> Promise<U?>) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T?>, to : @escaping (T) -> Promise<U?>) -> Promise<U?> { let promise = Promise<U?>() promise.previousPromise = from from.getValueWeak { [weak promise] value in if let v = value { to(v).getValue { [weak promise] value in promise?.setValue(value) } } else { promise?.setValue(nil) } } return promise } public func =><T, U>(lhs : Promise<T?>, rhs : @escaping (T) -> Promise<U?>) -> Promise<U?> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<Result<T>>, to : @escaping (T) -> Promise<U?>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in switch value { case .ok(let value): to(value).getValue { [weak promise] value in if let value = value { promise?.setValue(.ok(value)) } else { promise?.setValue(.error(NilError())) } } case .error(let error): promise?.setValue(.error(error)) } } return promise } public func =><T, U>(lhs : Promise<Result<T>>, rhs : @escaping (T) -> Promise<U?>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } // Bind to ResultPromise public func bind<T, U>(_ from : T, to : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { return to(from) } public func =><T, U>(lhs : T, rhs : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : T?, to : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { if let from = from { return to(from) } else { return Promise(value: .error(NilError())) } } public func =><T, U>(lhs : T?, rhs : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Result<T>, to : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { switch from { case .ok(let value): return to(value) case .error(let error): return Promise(value: .error(error)) } } public func =><T, U>(lhs : Result<T>, rhs : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T>, to : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { value in to(value).getValue { [weak promise] value in promise?.setValue(value) } } return promise } public func =><T, U>(lhs : Promise<T>, rhs : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<T?>, to : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in if let value = value { to(value).getValue { [weak promise] value in promise?.setValue(value) } } else { promise?.setValue(.error(NilError())) } } return promise } public func =><T, U>(lhs : Promise<T?>, rhs : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { return bind(lhs, to: rhs) } public func bind<T, U>(_ from : Promise<Result<T>>, to : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { let promise = Promise<Result<U>>() promise.previousPromise = from from.getValueWeak { [weak promise] value in switch value { case .ok(let value): to(value).getValue { [weak promise] value in promise?.setValue(value) } case .error(let error): promise?.setValue(.error(error)) } } return promise } public func =><T, U>(lhs : Promise<Result<T>>, rhs : @escaping (T) -> Promise<Result<U>>) -> Promise<Result<U>> { return bind(lhs, to: rhs) }
mit
5414b4c8ba446abfb2dc6736706fc359
22.511905
117
0.612433
2.863702
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKScripting/util/NKLogging.swift
1
5089
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright 2015 XWebView * Portions Copyright (c) 2014 Intel Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Darwin import Foundation public typealias asl_object_t = COpaquePointer @_silgen_name("asl_open") func asl_open(ident: UnsafePointer<Int8>, _ facility: UnsafePointer<Int8>, _ opts: UInt32) -> asl_object_t @_silgen_name("asl_close") func asl_close(obj: asl_object_t) @_silgen_name("asl_vlog") func asl_vlog(obj: asl_object_t, _ msg: asl_object_t, _ level: Int32, _ format: UnsafePointer<Int8>, _ ap: CVaListPointer) -> Int32 @_silgen_name("asl_add_output_file") func asl_add_output_file(client: asl_object_t, _ descriptor: Int32, _ msg_fmt: UnsafePointer<Int8>, _ time_fmt: UnsafePointer<Int8>, _ filter: Int32, _ text_encoding: Int32) -> Int32 @_silgen_name("asl_set_output_file_filter") func asl_set_output_file_filter(asl: asl_object_t, _ descriptor: Int32, _ filter: Int32) -> Int32 public class NKLogging { private static var logger = NKLogging(facility: "io.nodekit.core.consolelog") public class func log(message: String, level: NKLogging.Level? = nil) { logger.log(message, level: level) print(message) } @noreturn public class func die(@autoclosure message: ()->String, file: StaticString = #file, line: UInt = #line) { logger.log(message(), level: .Alert) fatalError(message, file: file, line: line) } public enum Level: Int32 { case Emergency = 0 case Alert = 1 case Critical = 2 case Error = 3 case Warning = 4 case Notice = 5 case Info = 6 case Debug = 7 private static let symbols: [Character] = [ "\0", "\0", "$", "!", "?", "-", "+", " " ] private init?(symbol: Character) { guard symbol != "\0", let value = Level.symbols.indexOf(symbol) else { return nil } self = Level(rawValue: Int32(value))! } } public struct Filter: OptionSetType { private var value: Int32 public var rawValue: Int32 { return value } public init(rawValue: Int32) { self.value = rawValue } public init(mask: Level) { self.init(rawValue: 1 << mask.rawValue) } public init(upto: Level) { self.init(rawValue: 1 << (upto.rawValue + 1) - 1) } public init(filter: Level...) { self.init(rawValue: filter.reduce(0) { $0 | $1.rawValue }) } } public var filter: Filter { didSet { asl_set_output_file_filter(client, STDERR_FILENO, filter.rawValue) } } private let client: asl_object_t private var lock: pthread_mutex_t = pthread_mutex_t() public init(facility: String, format: String? = nil) { client = asl_open(nil, facility, 0) pthread_mutex_init(&lock, nil) #if DEBUG filter = Filter(upto: .Debug) #else filter = Filter(upto: .Notice) #endif let format = format ?? "$((Time)(lcl)) $(Facility) <$((Level)(char))>: $(Message)" asl_add_output_file(client, STDERR_FILENO, format, "sec", filter.rawValue, 1) } deinit { asl_close(client) pthread_mutex_destroy(&lock) } public func log(message: String, level: Level) { pthread_mutex_lock(&lock) asl_vlog(client, nil, level.rawValue, message, getVaList([])) pthread_mutex_unlock(&lock) } public func log(message: String, level: Level? = nil) { var msg = message var lvl = level ?? .Debug if level == nil, let ch = msg.characters.first, l = Level(symbol: ch) { msg = msg[msg.startIndex.successor() ..< msg.endIndex] lvl = l } log(msg, level: lvl) } }
apache-2.0
c6cab97333da418645e4dc8b97c826ac
23.703883
219
0.532914
4.28367
false
false
false
false
Tanglo/PepperSpray
Spray/main.swift
1
5980
// // main.swift // PepperSpray // // Created by Lee Walsh on 15/01/2016. // Copyright © 2016 Lee David Walsh. All rights reserved. // This sofware is licensed under the The MIT License (MIT) // See: https://github.com/Tanglo/PepperSpray/blob/master/LICENSE.md // import Foundation let arguments = NSProcessInfo.processInfo().arguments let workingDirectoryString = String(NSString(string: arguments[0]).stringByDeletingLastPathComponent) var nextArg = 1 if (arguments.count > nextArg) && (arguments[1] == "-h"){ PSHelp.printHelp() exit(0) } else { //Get flags var flags = PSFlags("") if arguments.count > nextArg{ let index = arguments[1].startIndex if arguments[1][index] == "-"{ flags = PSFlags(arguments[nextArg]) nextArg++ } } let createKey = !flags.contains("p") var keyPath = workingDirectoryString if (arguments.count > nextArg){ let index = arguments[1].startIndex if !(arguments[nextArg][index] == "-"){ keyPath = arguments[nextArg] nextArg++ } } var sourcePath = workingDirectoryString if (arguments.count > nextArg+1) && (arguments[nextArg] == "-s"){ sourcePath = arguments[nextArg+1] var isDirectory: ObjCBool = true NSFileManager.defaultManager().fileExistsAtPath(sourcePath, isDirectory: &isDirectory) if !isDirectory{ print("Error: <source> is not a directory") exit(-1407) //code for getting a file instead of an folder } nextArg += 2 } let overwriteFiles = flags.contains("o") var destinationPath = workingDirectoryString if (arguments.count > nextArg+1) && (arguments[nextArg] == "-d"){ destinationPath = arguments[nextArg+1] nextArg += 2 } /* print("Main: flags - \(flags)") print("Main: key? - \(createKey), keyPath - \(keyPath)") print("Main: sourcePath - \(sourcePath)") print("Main: overwrite? - \(overwriteFiles), destinationPath - \(destinationPath)") */ //Get the keyPath ready to create or overwrite a file var isDirectory: ObjCBool = true let keyFileExists = NSFileManager.defaultManager().fileExistsAtPath(keyPath, isDirectory: &isDirectory) // print("\(keyFileExists), \(isDirectory)") if keyFileExists{ if !isDirectory{ var response: String? = "a" while (response != "y") && (response != "n"){ print("Overwrite existing key file: \(keyPath)? (y/n)") response = readLine() } if response == "n"{ exit(0) } } else if keyPath.characters.last! != "/"{ //if is directory without a / keyPath += "/key.csv" } else{ //directory with a / keyPath += "key.csv" } } else if keyPath.characters.last! == "/"{ //if user specified an non-existant path ending in a / do{ //try to create the new directory try NSFileManager.defaultManager().createDirectoryAtPath(keyPath, withIntermediateDirectories: true, attributes: nil) } catch{ let nsError = (error as NSError) print("\(nsError.localizedDescription)") exit(Int32(nsError.code)) } keyPath += "key.csv" } // print("keyPath: \(keyPath)") //Get the destination path and fileStem ready let destinationExists = NSFileManager.defaultManager().fileExistsAtPath(destinationPath, isDirectory: &isDirectory) var fileStem = "file" if destinationExists{ if !isDirectory{ fileStem = String(NSString(string: destinationPath).lastPathComponent) destinationPath = String(NSString(string: destinationPath).stringByDeletingLastPathComponent) } } else if destinationPath.characters.last! == "/"{ //if user specified an non-existant path ending in a / do{ //try to create the new directory try NSFileManager.defaultManager().createDirectoryAtPath(keyPath, withIntermediateDirectories: true, attributes: nil) } catch{ let nsError = (error as NSError) print("\(nsError.localizedDescription)") exit(Int32(nsError.code)) } } else{ fileStem = String(NSString(string: destinationPath).lastPathComponent) destinationPath = String(NSString(string: destinationPath).stringByDeletingLastPathComponent) } // print("destStem: \(fileStem)") // print("destPath: \(destinationPath)") //Ready to go var filenames = [NSURL]() do{ filenames = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(NSURL(fileURLWithPath: sourcePath, isDirectory: true), includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles) } catch { let nsError = (error as NSError) print("\(nsError.localizedDescription)") exit(Int32(nsError.code)) } // print("\(filenames)") var labels = [Int]() for i in 0...filenames.count{ labels.append(i) } // print("\(labels)") for url in filenames{ let fileSourcePath = url.path! let fileDestinationPathStem = destinationPath + "/" + fileStem let fileExtension = NSString(string: url.path!).pathExtension let numberIndex = Int(arc4random_uniform(UInt32(filenames.count))) let number = "\(labels[numberIndex])" labels.removeAtIndex(numberIndex) let numberString = number.stringByPaddingToLength(5, withString: "0", startingAtIndex: 0) number.str print("source: \(fileSourcePath)") print("destination: \(fileDestinationPathStem)") print("fileExtension: \(fileExtension)") print("numberString: \(numberString)") } }
mit
639057bb7362627bcd8f752f80e48b0a
39.127517
224
0.610804
4.737718
false
false
false
false
mownier/photostream
Photostream/Modules/Profile Edit/Module/ProfileEditModule.swift
1
2172
// // ProfileEditModule.swift // Photostream // // Created by Mounir Ybanez on 07/01/2017. // Copyright © 2017 Mounir Ybanez. All rights reserved. // import UIKit protocol ProfileEditModuleInterface: BaseModuleInterface { var displayItemCount: Int { get } var updateData: ProfileEditData! { get } func viewDidLoad() func uploadAvatar(with image: UIImage) func updateProfile() func displayItem(at index: Int) -> ProfileEditDisplayItem? func updateDisplayItem(with text: String, at index: Int) } protocol ProfileEditDelegate: BaseModuleDelegate { func profileEditDidUpdate(data: ProfileEditData) } protocol ProfileEditBuilder: BaseModuleBuilder { func build(root: RootWireframe?, data: ProfileEditData, delegate: ProfileEditDelegate?) } class ProfileEditModule: BaseModule, BaseModuleInteractable { typealias ModuleView = ProfileEditScene typealias ModuleInteractor = ProfileEditInteractor typealias ModulePresenter = ProfileEditPresenter typealias ModuleWireframe = ProfileEditWireframe var view: ModuleView! var interactor: ModuleInteractor! var presenter: ModulePresenter! var wireframe: ModuleWireframe! required init(view: ModuleView) { self.view = view } } extension ProfileEditModule: ProfileEditBuilder { func build(root: RootWireframe?) { let auth = AuthSession() let userService = UserServiceProvider(session: auth) let fileService = FileServiceProvider(session: auth) interactor = ProfileEditInteractor(userService: userService, fileService: fileService) presenter = ProfileEditPresenter() wireframe = ProfileEditWireframe(root: root) view.presenter = presenter interactor.output = presenter presenter.view = view presenter.interactor = interactor presenter.wireframe = wireframe } func build(root: RootWireframe?, data: ProfileEditData, delegate: ProfileEditDelegate? = nil) { build(root: root) presenter.updateData = data presenter.delegate = delegate } }
mit
f3d487a4ea2bfd7a6c37d8a4c8a19693
27.565789
99
0.699678
5.002304
false
false
false
false
qinting513/WeiBo-Swift
WeiBo_V3/WeiBo/Classes/Other/Extension/UIBarButtonItem+Extension.swift
1
2051
// // UIBarButtonItem+Extension.swift // WeiBo // // Created by Qinting on 16/9/6. // Copyright © 2016年 Qinting. All rights reserved. // import UIKit //便利初始化器最终一定以调用一个指定初始化器结束 extension UIBarButtonItem { convenience init(title:String, fontSize:CGFloat = 16.0,normalColor:UIColor, highlightedColor:UIColor, target:AnyObject?, action:Selector ) { let button : UIButton = UIButton(type: .custom) button.setTitle(title, for: UIControlState()) button.titleLabel?.font = UIFont.systemFont(ofSize: fontSize) button.setTitleColor(normalColor, for: UIControlState()) button.setTitleColor(highlightedColor, for: .highlighted) button.sizeToFit() button.addTarget(target, action: action, for: .touchUpInside) // 实例化 self.init(customView: button) } convenience init(imageName:String, highlightImageName:String,target:AnyObject?, action:Selector){ self.init(imageName:imageName, highlightImageName:highlightImageName,bgImageName:nil, highlightedBgImageName:nil, target:target, action:action) } convenience init( imageName:String, highlightImageName:String, bgImageName:String?, highlightedBgImageName:String?, target:AnyObject?, action:Selector){ let button : UIButton = UIButton(type: .custom) button.setImage(UIImage(named:imageName ), for: UIControlState()) button.setImage(UIImage(named:highlightImageName ), for: .highlighted) // 使用if let 后必定是有值的 if let bgImageName = bgImageName, highlightBgImageName = highlightedBgImageName { button.setBackgroundImage(UIImage(named: bgImageName), for: UIControlState()) button.setBackgroundImage(UIImage(named:highlightBgImageName), for: UIControlState()) } button.sizeToFit() button.addTarget(target, action: action, for: .touchUpInside) // 实例化 self.init(customView: button) } }
apache-2.0
e209e2416adf563f224187f3fcdf2937
40.957447
159
0.692698
4.533333
false
false
false
false
Toldy/Clock-In
ClockIn/Helpers/Date+Extension.swift
1
2404
// // Date+Extension.swift // ClockIn // // Created by Julien Colin on 06/09/16. // Copyright © 2016 Julien Colin. All rights reserved. // import Foundation public func <(lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == .orderedAscending } extension Date { func yearsFrom(_ date: Date) -> Int { return (Calendar.current as NSCalendar).components(.year, from: date, to: self, options: []).year! } func monthsFrom(_ date: Date) -> Int { return (Calendar.current as NSCalendar).components(.month, from: date, to: self, options: []).month! } func weeksFrom(_ date: Date) -> Int { return (Calendar.current as NSCalendar).components(.weekOfYear, from: date, to: self, options: []).weekOfYear! } func daysFrom(_ date: Date) -> Int { return (Calendar.current as NSCalendar).components(.day, from: date, to: self, options: []).day! } func hoursFrom(_ date: Date) -> Int { return (Calendar.current as NSCalendar).components(.hour, from: date, to: self, options: []).hour! } func minutesFrom(_ date: Date) -> Int { return (Calendar.current as NSCalendar).components(.minute, from: date, to: self, options: []).minute! } func secondsFrom(_ date: Date) -> Int { return (Calendar.current as NSCalendar).components(.second, from: date, to: self, options: []).second! } func offsetFrom(_ date: Date) -> String { if yearsFrom(date) > 0 { return "\(yearsFrom(date))y" } if monthsFrom(date) > 0 { return "\(monthsFrom(date))M" } if weeksFrom(date) > 0 { return "\(weeksFrom(date))w" } if daysFrom(date) > 0 { return "\(daysFrom(date))d" } if hoursFrom(date) > 0 { return "\(hoursFrom(date))h" } if minutesFrom(date) > 0 { return "\(minutesFrom(date))m" } if secondsFrom(date) > 0 { return "\(secondsFrom(date))s" } return "" } } private func getDayMonthYearOfDate(_ date: Date) -> (Int, Int, Int) { let calendar = Calendar.current let components = (calendar as NSCalendar).components([.day, .month, .year], from: date) return (components.year!, components.month!, components.day!) } extension Date { // Compare without taking care of the time func compareWithoutTime(_ rhs: Date) -> Bool { return self == rhs || getDayMonthYearOfDate(self) == getDayMonthYearOfDate(rhs) } }
mit
a0257a9453ebeea3a2dbbd640530c6a6
33.826087
118
0.625468
3.754688
false
false
false
false
Eitot/vienna-rss
Vienna/Sources/Main window/OverlayStatusBar.swift
1
11983
// // OverlayStatusBar.swift // Vienna // // Copyright 2017-2018 // // 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. // import Cocoa /// An overlay status bar can show context-specific information above a view. /// It is supposed to be a subview of another view. Once added, it will set its /// own frame and constraints. Removing the status bar from its superview will /// unwind the constraints. /// /// Setting or unsetting the `label` property will show or hide the status bar /// accordingly. It will not hide by itself. final class OverlayStatusBar: NSView { // MARK: Subviews private var backgroundView: NSVisualEffectView = { let backgroundView = NSVisualEffectView(frame: NSRect.zero) backgroundView.wantsLayer = true backgroundView.blendingMode = .withinWindow backgroundView.alphaValue = 0 backgroundView.layer?.cornerRadius = 3 return backgroundView }() private var addressField: NSTextField = { let addressField: NSTextField if #available(macOS 10.12, *) { addressField = NSTextField(labelWithString: "") } else { addressField = NSTextField(frame: NSRect.zero) addressField.isBezeled = false addressField.isSelectable = false addressField.drawsBackground = false addressField.textColor = .labelColor } addressField.font = .systemFont(ofSize: 12, weight: .medium) addressField.lineBreakMode = .byTruncatingMiddle addressField.allowsDefaultTighteningForTruncation = true return addressField }() // MARK: Initialization init() { super.init(frame: NSRect(x: 0, y: 0, width: 240, height: 26)) // Make sure that no other constraints are created. translatesAutoresizingMaskIntoConstraints = false backgroundView.translatesAutoresizingMaskIntoConstraints = false addressField.translatesAutoresizingMaskIntoConstraints = false // The text field should always be among the first views to shrink. addressField.setContentCompressionResistancePriority(.fittingSizeCompression, for: .horizontal) addSubview(backgroundView) backgroundView.addSubview(addressField) // Set the constraints. var backgroundViewConstraints: [NSLayoutConstraint] = [] backgroundViewConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-3-[view]-3-|", metrics: nil, views: ["view": backgroundView]) backgroundViewConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-3-[view]-3-|", metrics: nil, views: ["view": backgroundView]) var addressFieldConstraints: [NSLayoutConstraint] = [] addressFieldConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-2-[label]-2-|", metrics: nil, views: ["label": addressField]) addressFieldConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-6-[label]-6-|", metrics: nil, views: ["label": addressField]) NSLayoutConstraint.activate(backgroundViewConstraints) NSLayoutConstraint.activate(addressFieldConstraints) } // Make this initialiser unavailable. override private convenience init(frame frameRect: NSRect) { self.init() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("\(#function) has not been implemented") } // MARK: Setting the view hierarchy // When the status bar is added to the view hierarchy of another view, // perform additional setup, such as setting the constraints and creating // a tracking area for mouse movements. override func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() guard let superview = superview else { return } // Layer-backing will make sure that the visual-effect view redraws. superview.wantsLayer = true var baseContraints: [NSLayoutConstraint] = [] baseContraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|->=0-[view]-0-|", options: [], metrics: nil, views: ["view": self]) baseContraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|->=0-[view]->=0-|", options: [], metrics: nil, views: ["view": self]) NSLayoutConstraint.activate(baseContraints) // Pin the view to the left side. pin(to: .leadingEdge, of: superview) startTrackingMouse(on: superview) } // If the status bar is removed from the view hierarchy, then the tracking // area must be removed too. override func viewWillMove(toSuperview newSuperview: NSView?) { if let superview = superview { stopTrackingMouse(on: superview) isShown = false position = nil } } // MARK: Pinning the status bar private enum Position { case leadingEdge, trailingEdge } private var position: Position? private lazy var leadingConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]", options: [], metrics: nil, views: ["view": self]) private lazy var trailingConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-0-|", options: [], metrics: nil, views: ["view": self]) // The status bar is pinned simply by setting and unsetting constraints. private func pin(to position: Position, of positioningView: NSView) { guard position != self.position else { return } let oldConstraints: [NSLayoutConstraint] let newConstraints: [NSLayoutConstraint] switch position { case .leadingEdge: oldConstraints = trailingConstraints newConstraints = leadingConstraints case .trailingEdge: oldConstraints = leadingConstraints newConstraints = trailingConstraints } // Remove existing constraints. NSLayoutConstraint.deactivate(oldConstraints) // Add new constraints. NSLayoutConstraint.activate(newConstraints) self.position = position } // MARK: Handling status updates /// The label to show. Setting this property will show or hide the status /// bar. It will remain visible until the label is set to `nil`. @objc var label: String? { didSet { // This closure is meant to be called very often. It should not // cause any expensive computations. if let label = label, !label.isEmpty { if label != addressField.stringValue { addressField.stringValue = label } isShown = true } else { isShown = false } } } private var isShown = false { didSet { guard isShown != oldValue else { return } NSAnimationContext.runAnimationGroup({ context in context.duration = 0.4 backgroundView.animator().alphaValue = isShown ? 1 : 0 }, completionHandler: nil) } } // MARK: Setting up mouse tracking private var trackingArea: NSTrackingArea? private func startTrackingMouse(on trackingView: NSView) { if let trackingArea = self.trackingArea, trackingView.trackingAreas.contains(trackingArea) { return } let rect = trackingView.bounds let size = CGSize(width: rect.maxX, height: frame.height + 15) let origin = CGPoint(x: rect.minX, y: rect.minY) let trackingArea = NSTrackingArea(rect: NSRect(origin: origin, size: size), options: [.mouseEnteredAndExited, .mouseMoved, .activeInKeyWindow], owner: self, userInfo: nil) self.trackingArea = trackingArea trackingView.addTrackingArea(trackingArea) } // Remove the tracking area and unset the reference. private func stopTrackingMouse(on trackingView: NSView) { if let trackingArea = trackingArea { trackingView.removeTrackingArea(trackingArea) self.trackingArea = nil } } // This method is called often, thus only change the tracking area when // the superview's bounds width and the tracking area's width do not match. override func updateTrackingAreas() { super.updateTrackingAreas() guard let superview = superview, let trackingArea = trackingArea else { return } if superview.trackingAreas.contains(trackingArea), trackingArea.rect.width != superview.bounds.width { stopTrackingMouse(on: superview) startTrackingMouse(on: superview) } } // MARK: Responding to mouse movement private var widthConstraint: NSLayoutConstraint? // Once the mouse enters the tracking area, the width of the status bar // should shrink. This is done by adding a width constraint. override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) guard let superview = superview, event.trackingArea == trackingArea else { return } // Add the width constraint, if not already added. if widthConstraint == nil { let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: superview.bounds.midX - 8) self.widthConstraint = widthConstraint widthConstraint.isActive = true } } // Pin the status bar to the side, opposite of the mouse's position. override func mouseMoved(with event: NSEvent) { super.mouseMoved(with: event) guard let superview = superview else { return } // Map the mouse location to the superview's bounds. let point = superview.convert(event.locationInWindow, from: nil) if point.x <= superview.bounds.midX { pin(to: .trailingEdge, of: superview) } else { pin(to: .leadingEdge, of: superview) } } // Once the mouse exits the tracking area, the status bar's intrinsic width // should be restored, by removing the width constraint and pinning the view // back to the left side. override func mouseExited(with event: NSEvent) { super.mouseExited(with: event) guard let superview = superview, event.trackingArea == trackingArea else { return } pin(to: .leadingEdge, of: superview) if let constraint = widthConstraint { removeConstraint(constraint) // Delete the constraint to make sure that a new one is created, // appropriate for the superview size (which may change). widthConstraint = nil } } }
apache-2.0
ce7a3fe56cef3673c978690ee853299c
36.214286
157
0.621547
5.550255
false
false
false
false
patchthecode/JTAppleCalendar
Sources/JTAppleCalendar/CalendarEnums.swift
1
5897
// // CalendarEnums.swift // // Copyright (c) 2016-2020 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar) // // 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 /// Describes a scroll destination public enum SegmentDestination { /// next the destination is the following segment case next /// previous the destination is the previous segment case previous /// start the destination is the start segment case start /// end the destination is the end segment case end } /// Describes the types of out-date cells to be generated. public enum OutDateCellGeneration { /// tillEndOfRow will generate dates till it reaches the end of a row. /// endOfGrid will continue generating until it has filled a 6x7 grid. /// Off-mode will generate no postdates case tillEndOfRow, tillEndOfGrid, off } /// Describes the types of out-date cells to be generated. public enum InDateCellGeneration { /// forFirstMonthOnly will generate dates for the first month only /// forAllMonths will generate dates for all months /// off setting will generate no dates case forFirstMonthOnly, forAllMonths, off } /// Describes the calendar reading direction /// Useful for regions that read text from right to left public enum ReadingOrientation { /// Reading orientation is from right to left case rightToLeft /// Reading orientation is from left to right case leftToRight } /// Configures the behavior of the scrolling mode of the calendar public enum ScrollingMode: Equatable { /// stopAtEachCalendarFrame - non-continuous scrolling that will stop at each frame case stopAtEachCalendarFrame /// stopAtEachSection - non-continuous scrolling that will stop at each section case stopAtEachSection /// stopAtEach - non-continuous scrolling that will stop at each custom interval case stopAtEach(customInterval: CGFloat) /// nonStopToSection - continuous scrolling that will stop at a section case nonStopToSection(withResistance: CGFloat) /// nonStopToCell - continuous scrolling that will stop at a cell case nonStopToCell(withResistance: CGFloat) /// nonStopTo - continuous scrolling that will stop at acustom interval, do not use 0 as custom interval case nonStopTo(customInterval: CGFloat, withResistance: CGFloat) /// none - continuous scrolling that will eventually stop at a point case none func pagingIsEnabled() -> Bool { switch self { case .stopAtEachCalendarFrame: return true default: return false } } public static func ==(lhs: ScrollingMode, rhs: ScrollingMode) -> Bool { switch (lhs, rhs) { case (.none, .none), (.stopAtEachCalendarFrame, .stopAtEachCalendarFrame), (.stopAtEachSection, .stopAtEachSection): return true case (let .stopAtEach(customInterval: v1), let .stopAtEach(customInterval: v2)): return v1 == v2 case (let .nonStopToSection(withResistance: v1), let .nonStopToSection(withResistance: v2)): return v1 == v2 case (let .nonStopToCell(withResistance: v1), let .nonStopToCell(withResistance: v2)): return v1 == v2 case (let .nonStopTo(customInterval: v1, withResistance: x1), let .nonStopTo(customInterval: v2, withResistance: x2)): return v1 == v2 && x1 == x2 default: return false } } } /// Describes which month owns the date public enum DateOwner: Int { /// Describes which month owns the date case thisMonth = 0, previousMonthWithinBoundary, previousMonthOutsideBoundary, followingMonthWithinBoundary, followingMonthOutsideBoundary } /// Months of the year public enum MonthsOfYear: Int, CaseIterable { case jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec } /// Selection position of a range-selected date cell public enum SelectionRangePosition: Int { /// Selection position case left = 1, middle, right, full, none } /// Between month segments, the range selection can either be visually disconnected or connected public enum RangeSelectionMode { case segmented, continuous } /// Signifies whether or not a selection was done programatically or by the user public enum SelectionType: String { /// Selection type case programatic, userInitiated } /// Days of the week. By setting your calendar's first day of the week, /// you can change which day is the first for the week. Sunday is the default value. public enum DaysOfWeek: Int, CaseIterable { /// Days of the week. case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday } internal enum DelayedTaskType { case scroll, general } internal enum SelectionAction { case didSelect, didDeselect } internal enum ShouldSelectionAction { case shouldSelect, shouldDeselect }
mit
0264b0f87eb62f5497a488f524ec1496
38.577181
154
0.725284
4.440512
false
false
false
false
OscarSwanros/swift
test/Driver/tools_directory.swift
36
1483
//================================================= // ** GENERIC UNIX TARGETS - linking via clang++ ** //================================================= // RUN: %swiftc_driver -### -target x86_64-linux-unknown -tools-directory %S/Inputs/fake-toolchain %s 2>&1 | %FileCheck -check-prefix CLANGSUB %s // RUN: %swiftc_driver -### -target x86_64-linux-unknown -tools-directory /Something/obviously/fake %s 2>&1 | %FileCheck -check-prefix BINUTILS %s // CLANGSUB: swift // CLANGSUB-SAME: -o [[OBJECTFILE:.*]] // CLANGSUB: swift-autolink-extract [[OBJECTFILE]] // CLANGSUB-SAME: -o [[AUTOLINKFILE:.*]] // CLANGSUB: {{[^ ]+}}/Inputs/fake-toolchain/clang++ // CLANGSUB-DAG: [[OBJECTFILE]] // CLANGSUB-DAG: @[[AUTOLINKFILE]] // CLANGSUB: -o tools_directory // BINUTILS: swift // BINUTILS-SAME: -o [[OBJECTFILE:.*]] // BINUTILS: swift-autolink-extract [[OBJECTFILE]] // BINUTILS-SAME: -o [[AUTOLINKFILE:.*]] // BINUTILS: clang++ // BINUTILS-DAG: [[OBJECTFILE]] // BINUTILS-DAG: @[[AUTOLINKFILE]] // BINUTILS-DAG: -B /Something/obviously/fake // BINUTILS: -o tools_directory //====================================== // ** DARWIN TARGETS - linking via ld ** //====================================== // RUN: %swiftc_driver -### -target x86_64-apple-macosx10.9 -tools-directory %S/Inputs/fake-toolchain %s 2>&1 | %FileCheck -check-prefix LDSUB %s // LDSUB: swift // LDSUB-SAME: -o [[OBJECTFILE:.*]] // LDSUB: {{[^ ]+}}/Inputs/fake-toolchain/ld [[OBJECTFILE]] // LDSUB: -o tools_directory
apache-2.0
41c608b18c941a0ac299ac69844eec4b
40.194444
146
0.5853
3.679901
false
false
true
false
LoopKit/LoopKit
LoopKitUI/Views/GuideNavigationButton.swift
1
1446
// // GuideNavigationButton.swift // LoopKitUI // // Created by Pete Schwamb on 2020-03-04. // Copyright © 2020 LoopKit Authors. All rights reserved. // import SwiftUI public struct GuideNavigationButton<Destination>: View where Destination: View { @Binding var navigationLinkIsActive: Bool private let label: String private let buttonPressedAction: (() -> Void)? private let buttonStyle: ActionButton.ButtonType private let destination: () -> Destination public init(navigationLinkIsActive: Binding<Bool>, label: String, buttonPressedAction: (() -> Void)? = nil, buttonStyle: ActionButton.ButtonType = .primary, @ViewBuilder destination: @escaping () -> Destination) { self._navigationLinkIsActive = navigationLinkIsActive self.label = label self.buttonPressedAction = buttonPressedAction self.buttonStyle = buttonStyle self.destination = destination } public var body: some View { NavigationLink(destination: destination(), isActive: self.$navigationLinkIsActive) { Button(action: { self.buttonPressedAction?() self.navigationLinkIsActive = true }) { Text(label) .actionButtonStyle(buttonStyle) } } .isDetailLink(false) } }
mit
47a1b520e1f67cdd1153bec97fdef42d
31.111111
80
0.610381
5.351852
false
false
false
false
dsxNiubility/SXSwiftWeibo
SwiftJ2M/Sources/SXSwiftJ2M.swift
1
7515
// // SXSwiftJ2M.swift // 105 - SXSwiftJ2M // // Created by 董 尚先 on 15/3/4. // Copyright (c) 2015年 shangxianDante. All rights reserved. // import Foundation @objc protocol J2MProtocol{ /** 自定义的类型映射表 - returns: 返回[属性名:自定义对象名称] */ static func customeClassMapping()->[String:String]? } public class SXSwiftJ2M { /// 创建单例 public static let sharedManager = SXSwiftJ2M() /// MARK:- 使用字典转模型 /** 使用字典转模型 - parameter dict: 数据字典 - parameter cls: 模型的类 - returns: 实例化类的对象 */ public func swiftObjWithDict(dict:NSDictionary,cls:AnyClass) ->AnyObject?{ /// 取出模型类字典 let dictInfo = GetAllModelInfo(cls) /// 实例化对象 let obj:AnyObject = cls.alloc() for(k,v) in dictInfo{ if let value:AnyObject? = dict[k]{ // println("要设置数值的 \(value) + key \(k)") /// 如果是基本数据类型直接kvc if v.isEmpty && !(value === NSNull()){ // $$$$$ obj.setValue(value, forKey: k) }else { let type = "\(value!.classForCoder)" // $$$$$ 取出某一个对象所属的类 // println("自定义对象 \(value) \(k) \(v) 类型是 \(type) ") if type == "NSDictionary" { // value 是字典-> 将 value 的字典转换成 Info 的对象 if let subObj:AnyObject? = swiftObjWithDict(value as!NSDictionary, cls: NSClassFromString(v)){ obj.setValue(subObj, forKey: k) } } else if type == "NSArray" { // value 是数组 // 如果是数组如何处理? 遍历数组,继续处理数组中的字典 if let subObj:AnyObject? = swiftObjWithArray(value as!NSArray, cls: NSClassFromString(v)){ obj.setValue(subObj, forKey: k) } } } } } // println(dictInfo) return obj } /// MARK:- 将数组转化成模型数组 /** 将数组转化成模型数组 - parameter array: 数组 - parameter cls: 模型类 - returns: 模型数组 */ public func swiftObjWithArray(array:NSArray,cls:AnyClass) ->AnyObject?{ var result = [AnyObject]() for value in array{ let type = "\(value.classForCoder)" // $$$$$ if type == "NSDictionary"{ if let subObj:AnyObject = swiftObjWithDict(value as! NSDictionary, cls: cls){ result.append(subObj) // $$$$$ } } else if type == "NSArray"{ if let subObj:AnyObject = swiftObjWithArray(value as! NSArray, cls: cls){ result.append(subObj) } } } return result } /// 缓存字典 var modleCache = [String:[String:String]]() // $$$$$ /// MARK:- 获取模型类的所有信息 /** 获取模型类的所有信息 - parameter cls: 模型类 - returns: 完整信息字典 */ func GetAllModelInfo(cls:AnyClass)->[String:String]{ /// 先判断是否已经被缓存 if let cache = modleCache["\(cls)"]{ print("\(cls)类已经被缓存") return cache } /// 循环查找父类,但是不会处理NSObject var currentcls:AnyClass = cls /// 定义模型字典 var dictInfo = [String:String]() /// 循环遍历直到NSObject while let parent:AnyClass = currentcls.superclass(){ // $$$$$ dictInfo.merge(GetModelInfo(currentcls)) currentcls = parent } /// 写入缓存 modleCache["\(cls)"] = dictInfo return dictInfo } /// MARK:- 获取给定类的信息 func GetModelInfo(cls:AnyClass) ->[String:String]{ /// 判断是否遵循了协议,一旦遵循协议就是有自定义对象 var mapping:[String : String]? if (cls.respondsToSelector("customeClassMapping")){ // $$$$$ /// 得到属性字典 mapping = cls.customeClassMapping() // println(mapping!) } /// 必须用UInt32否则不能调用 var count:UInt32 = 0 let ivars = class_copyIvarList(cls, &count) print("有 \(count) 个属性") var dictInfo = [String:String]() for i in 0..<count{ /// 必须再强转成Int否则不能用来做下标 let ivar = ivars[Int(i)] let cname = ivar_getName(ivar) let name = String.fromCString(cname)! /// 去属性字典中取,如果没有就使用后面的变量 let type = mapping?[name] ?? "" // $$$$$ dictInfo[name] = type } /// 释放 free(ivars) return dictInfo } /// MARK:- 加载属性列表 func loadProperties(cls:AnyClass){ /// 必须用UInt32否则不能调用 var count:UInt32 = 0 let properties = class_copyPropertyList(cls, &count) print("有 \(count) 个属性") for i in 0..<count{ /// 必须再强转成Int否则不能用来做下标 let property = properties[Int(i)] let cname = property_getName(property) let name = String.fromCString(cname)! let ctype = property_getAttributes(property) let type = String.fromCString(ctype)! print(name + "--------" + type) } /// 释放 free(properties) /// 基本数据类型不对,swift数组和字符串不对 } /// MARK:- 加载成员变量 func loadIVars(cls:AnyClass){ /// 必须用UInt32否则不能调用 var count:UInt32 = 0 let ivars = class_copyIvarList(cls, &count) print("有 \(count) 个属性") for i in 0..<count{ /// 必须再强转成Int否则不能用来做下标 let ivar = ivars[Int(i)] let cname = ivar_getName(ivar) let name = String.fromCString(cname)! let ctype = ivar_getTypeEncoding(ivar) let type = String.fromCString(ctype)! print(name + "--------" + type) } /// 释放 free(ivars) /// 能够检测通过 } } /// 相当于添加分类,泛型,拼接字典 extension Dictionary{ mutating func merge<K,V>(dict:[K:V]){ for (k,v) in dict{ self.updateValue(v as! Value, forKey: k as! Key) } } }
mit
74e8818ebf88350d3fe3a8938e93c3af
24.909804
118
0.448464
4.431254
false
false
false
false
noveogroup/planetary-system
Planetary System/ViewController.swift
1
1282
// // ViewController.swift // Planetary System // // Created by Maxim Zabelin on 16/03/15. // Copyright (c) 2015 Noveo. All rights reserved. // import SpriteKit import UIKit class ViewController: UIViewController { private var spriteView : SKView? private var scene: SKScene? override func viewDidLoad() { super.viewDidLoad() let spriteView: SKView = SKView() #if DEBUG spriteView.showsFPS = true spriteView.showsDrawCount = true spriteView.showsNodeCount = true #endif self.view.addSubview(spriteView) self.spriteView = spriteView } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let spriteView = self.spriteView { spriteView.frame = self.view.bounds } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let spriteView = self.spriteView { let size: CGSize = self.view.bounds.size self.scene = PlanetarySystemScene(size: size) spriteView.presentScene(scene) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
363e8825b4a55169185fda082653391a
22.309091
58
0.641186
4.611511
false
false
false
false
nixzhu/AudioBot
VoiceMemo/VoiceMemoCell.swift
2
1452
// // VoiceMemoCell.swift // VoiceMemo // // Created by NIX on 15/11/28. // Copyright © 2015年 nixWork. All rights reserved. // import UIKit class VoiceMemoCell: UITableViewCell { @IBOutlet weak var playButton: UIButton! @IBOutlet weak var datetimeLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! var playing: Bool = false { willSet { if newValue != playing { if newValue { playButton.setImage(UIImage(named: "icon_pause"), for: UIControlState()) } else { playButton.setImage(UIImage(named: "icon_play"), for: UIControlState()) } } } } var playOrPauseAction: ((_ cell: VoiceMemoCell, _ progressView: UIProgressView) -> Void)? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func configureWithVoiceMemo(_ voiceMemo: VoiceMemo) { playing = voiceMemo.playing datetimeLabel.text = "\(voiceMemo.createdAt)" durationLabel.text = String(format: "%.1f", voiceMemo.duration) progressView.progress = Float(voiceMemo.progress) } @IBAction func playOrPause(_ sender: UIButton) { playOrPauseAction?(self, progressView) } }
mit
a7444b3282eea1777ff0c56770906616
24.875
93
0.619738
4.570978
false
false
false
false
jlecomte/iOSTwitterApp
Twiddlator/Tweet.swift
1
999
// // Tweet.swift // Twiddlator // // Created by Julien Lecomte on 9/26/14. // Copyright (c) 2014 Julien Lecomte. All rights reserved. // import Foundation class Tweet { var uid: String? var author: User? var body: String? var createdAt: String? init(jsonObject: NSDictionary) { uid = jsonObject["id_str"] as? String body = jsonObject["text"] as? String createdAt = jsonObject["created_at"] as? String author = User(jsonObject: jsonObject["user"] as NSDictionary) // &amp; -> & body = body?.stringByReplacingOccurrencesOfString("&amp;", withString: "&", options: NSStringCompareOptions.LiteralSearch, range: nil) // Format date let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" var date = dateFormatter.dateFromString(createdAt!) dateFormatter.dateFormat = "MM/dd, h:mm a" createdAt = dateFormatter.stringFromDate(date!) } }
mit
387dabe59e1f28a3078716cd94947772
28.382353
142
0.644645
4.343478
false
false
false
false
jpsim/Yams
Sources/Yams/Encoder.swift
1
9925
// // Encoder.swift // Yams // // Created by Norio Nomura on 5/2/17. // Copyright (c) 2017 Yams. All rights reserved. // /// `Codable`-style `Encoder` that can be used to encode an `Encodable` type to a YAML string using optional /// user info mapping. Similar to `Foundation.JSONEncoder`. public class YAMLEncoder { /// Options to use when encoding to YAML. public typealias Options = Emitter.Options /// Options to use when encoding to YAML. public var options = Options() /// Creates a `YAMLEncoder` instance. public init() {} /// Encode a value of type `T` to a YAML string. /// /// - parameter value: Value to encode. /// - parameter userInfo: Additional key/values which can be used when looking up keys to encode. /// /// - returns: The YAML string. /// /// - throws: `EncodingError` if something went wrong while encoding. public func encode<T: Swift.Encodable>(_ value: T, userInfo: [CodingUserInfoKey: Any] = [:]) throws -> String { do { let encoder = _Encoder(userInfo: userInfo, sequenceStyle: options.sequenceStyle, mappingStyle: options.mappingStyle) var container = encoder.singleValueContainer() try container.encode(value) return try serialize(node: encoder.node, options: options) } catch let error as EncodingError { throw error } catch { let description = "Unable to encode the given top-level value to YAML." let context = EncodingError.Context(codingPath: [], debugDescription: description, underlyingError: error) throw EncodingError.invalidValue(value, context) } } } private class _Encoder: Swift.Encoder { var node: Node = .unused init(userInfo: [CodingUserInfoKey: Any] = [:], codingPath: [CodingKey] = [], sequenceStyle: Node.Sequence.Style, mappingStyle: Node.Mapping.Style) { self.userInfo = userInfo self.codingPath = codingPath self.sequenceStyle = sequenceStyle self.mappingStyle = mappingStyle } // MARK: - Swift.Encoder Methods let codingPath: [CodingKey] let userInfo: [CodingUserInfoKey: Any] let sequenceStyle: Node.Sequence.Style let mappingStyle: Node.Mapping.Style func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> { if canEncodeNewValue { node = Node([(Node, Node)](), .implicit, mappingStyle) } else { precondition( node.isMapping, "Attempt to push new keyed encoding container when already previously encoded at this path." ) } return .init(_KeyedEncodingContainer<Key>(referencing: self)) } func unkeyedContainer() -> UnkeyedEncodingContainer { if canEncodeNewValue { node = Node([], .implicit, sequenceStyle) } else { precondition( node.isSequence, "Attempt to push new keyed encoding container when already previously encoded at this path." ) } return _UnkeyedEncodingContainer(referencing: self) } func singleValueContainer() -> SingleValueEncodingContainer { return self } // MARK: - var mapping: Node.Mapping { get { return node.mapping ?? [:] } set { node.mapping = newValue } } var sequence: Node.Sequence { get { return node.sequence ?? [] } set { node.sequence = newValue } } /// create a new `_ReferencingEncoder` instance as `key` inheriting `userInfo` func encoder(for key: CodingKey) -> _ReferencingEncoder { return .init(referencing: self, key: key) } /// create a new `_ReferencingEncoder` instance at `index` inheriting `userInfo` func encoder(at index: Int) -> _ReferencingEncoder { return .init(referencing: self, at: index) } private var canEncodeNewValue: Bool { return node == .unused } } private class _ReferencingEncoder: _Encoder { private enum Reference { case mapping(String), sequence(Int) } private let encoder: _Encoder private let reference: Reference init(referencing encoder: _Encoder, key: CodingKey) { self.encoder = encoder reference = .mapping(key.stringValue) super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath + [key], sequenceStyle: encoder.sequenceStyle, mappingStyle: encoder.mappingStyle) } init(referencing encoder: _Encoder, at index: Int) { self.encoder = encoder reference = .sequence(index) super.init(userInfo: encoder.userInfo, codingPath: encoder.codingPath + [_YAMLCodingKey(index: index)], sequenceStyle: encoder.sequenceStyle, mappingStyle: encoder.mappingStyle) } deinit { switch reference { case .mapping(let key): encoder.node[key] = node case .sequence(let index): encoder.node[index] = node } } } private struct _KeyedEncodingContainer<Key: CodingKey>: KeyedEncodingContainerProtocol { private let encoder: _Encoder init(referencing encoder: _Encoder) { self.encoder = encoder } // MARK: - Swift.KeyedEncodingContainerProtocol Methods var codingPath: [CodingKey] { return encoder.codingPath } func encodeNil(forKey key: Key) throws { encoder.mapping[key.stringValue] = .null } func encode<T>(_ value: T, forKey key: Key) throws where T: YAMLEncodable { try encoder(for: key).encode(value) } func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable { try encoder(for: key).encode(value) } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> { return encoder(for: key).container(keyedBy: type) } func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { return encoder(for: key).unkeyedContainer() } func superEncoder() -> Encoder { return encoder(for: _YAMLCodingKey.super) } func superEncoder(forKey key: Key) -> Encoder { return encoder(for: key) } // MARK: - private func encoder(for key: CodingKey) -> _ReferencingEncoder { return encoder.encoder(for: key) } } private struct _UnkeyedEncodingContainer: UnkeyedEncodingContainer { private let encoder: _Encoder init(referencing encoder: _Encoder) { self.encoder = encoder } // MARK: - Swift.UnkeyedEncodingContainer Methods var codingPath: [CodingKey] { return encoder.codingPath } var count: Int { return encoder.sequence.count } func encodeNil() throws { encoder.sequence.append(.null) } func encode<T>(_ value: T) throws where T: YAMLEncodable { try currentEncoder.encode(value) } func encode<T>(_ value: T) throws where T: Encodable { try currentEncoder.encode(value) } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> { return currentEncoder.container(keyedBy: type) } func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { return currentEncoder.unkeyedContainer() } func superEncoder() -> Encoder { return currentEncoder } // MARK: - private var currentEncoder: _ReferencingEncoder { defer { encoder.sequence.append("") } return encoder.encoder(at: count) } } extension _Encoder: SingleValueEncodingContainer { // MARK: - Swift.SingleValueEncodingContainer Methods func encodeNil() throws { assertCanEncodeNewValue() node = .null } func encode<T>(_ value: T) throws where T: YAMLEncodable { assertCanEncodeNewValue() node = value.box() } func encode<T>(_ value: T) throws where T: Encodable { assertCanEncodeNewValue() if let encodable = value as? YAMLEncodable { node = encodable.box() } else { try value.encode(to: self) } } // MARK: - /// Asserts that a single value can be encoded at the current coding path /// (i.e. that one has not already been encoded through this container). /// `preconditionFailure()`s if one cannot be encoded. private func assertCanEncodeNewValue() { precondition( canEncodeNewValue, "Attempt to encode value through single value container when previously value already encoded." ) } } // MARK: - CodingKey for `_UnkeyedEncodingContainer`, `_UnkeyedDecodingContainer`, `superEncoder` and `superDecoder` struct _YAMLCodingKey: CodingKey { // swiftlint:disable:this type_name var stringValue: String var intValue: Int? init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } init(index: Int) { self.stringValue = "Index \(index)" self.intValue = index } static let `super` = _YAMLCodingKey(stringValue: "super")! } // MARK: - private extension Node { static let null = Node("null", Tag(.null)) static let unused = Node("", .unused) } private extension Tag { static let unused = Tag(.unused) } private extension Tag.Name { static let unused: Tag.Name = "tag:yams.encoder:unused" } private func serialize(node: Node, options: Emitter.Options) throws -> String { return try serialize( nodes: [node], canonical: options.canonical, indent: options.indent, width: options.width, allowUnicode: options.allowUnicode, lineBreak: options.lineBreak, explicitStart: options.explicitStart, explicitEnd: options.explicitEnd, version: options.version, sortKeys: options.sortKeys) }
mit
5be2e2786171b480c7bb7f93f19a34e1
32.989726
185
0.644937
4.697113
false
false
false
false
jflinter/Reed
Reed/AppDelegate.swift
1
2120
// // AppDelegate.swift // Reed // // Created by Jack Flintermann on 12/24/15. // Copyright © 2015 jflinter. All rights reserved. // import UIKit import ReedCore @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.setMinimumBackgroundFetchInterval(NSTimeInterval(86400)) application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil)) self.window?.tintColor = UIColor(red: 255.0/255.0, green: 42.0/255.0, blue: 104.0/255.0, alpha: 1) visualEffectView.frame = application.statusBarFrame self.window?.rootViewController?.view?.addSubview(visualEffectView) return true } func application(application: UIApplication, willChangeStatusBarFrame newStatusBarFrame: CGRect) { self.visualEffectView.frame = newStatusBarFrame } func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { FirebaseStore.fetchNewStoriesForUser(User.activeUser) { stories in if stories.count > 0 { let notification = UILocalNotification() let plural = stories.count == 1 ? "story" : "stories" notification.alertBody = "\(stories.count) new \(plural)!" application.presentLocalNotificationNow(notification) completionHandler(UIBackgroundFetchResult.NewData) } else { completionHandler(UIBackgroundFetchResult.NoData) } } } func application(application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { return true } func application(application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { return true } }
mit
d120613dc0e53016ae2af1f1f29e9945
38.240741
138
0.70033
5.503896
false
false
false
false
jellybeansoup/ios-sherpa
example/SherpaExample/ViewController.swift
1
2342
// // Copyright © 2019 Daniel Farrelly // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list // of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit import Sherpa class ViewController: UIViewController { let guideURL = Bundle.main.url(forResource: "UserGuide", withExtension: "json")! @IBAction func openUserGuide() { let viewController = SherpaViewController(fileAtURL: guideURL) self.present(viewController, animated: true, completion: nil) } @IBAction func openArticle() { let viewController = SherpaViewController(fileAtURL: guideURL) viewController.articleKey = "body" self.present(viewController, animated: true, completion: nil) } @IBAction func pushUserGuide() { let viewController = SherpaViewController(fileAtURL: guideURL) self.navigationController?.pushViewController(viewController, animated: true) } @IBAction func pushArticle() { let viewController = SherpaViewController(fileAtURL: guideURL) viewController.articleKey = "body" viewController.articleCSS = "h1, h2, h3, h4, h5, h6 { color: magenta; }" self.navigationController?.pushViewController(viewController, animated: true) } }
bsd-2-clause
27800fd03feb0ccc54baec049470f631
41.563636
85
0.77232
4.39212
false
false
false
false