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
khawars/KSTokenView
Examples/Examples/ViewControllers/StackView.swift
1
2685
// // StackView.swift // Examples // // Created by Khawar Shahzad on 01/01/2015. // Copyright (c) 2015 Khawar Shahzad. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit class StackView: UIViewController { @IBOutlet var tokenView: KSTokenView! let names: Array<String> = List.names() override func viewDidLoad() { super.viewDidLoad() tokenView.delegate = self tokenView.promptText = "Top 5: " tokenView.placeholder = "Type to search" tokenView.descriptionText = "Languages" tokenView.maxTokenLimit = 5 tokenView.minimumCharactersToSearch = 0 // Show all results without without typing anything tokenView.style = .squared } } extension StackView: KSTokenViewDelegate { func tokenView(_ tokenView: KSTokenView, performSearchWithString string: String, completion: ((_ results: Array<AnyObject>) -> Void)?) { if (string.isEmpty){ completion!(names as Array<AnyObject>) return } var data: Array<String> = [] for value: String in names { if value.lowercased().range(of: string.lowercased()) != nil { data.append(value) } } completion!(data as Array<AnyObject>) } func tokenView(_ tokenView: KSTokenView, displayTitleForObject object: AnyObject) -> String { return object as! String } func tokenView(_ tokenView: KSTokenView, shouldAddToken token: KSToken) -> Bool { if token.title == "f" { return false } return true } }
mit
c84c081b5aae2648597b56db84ceab9f
36.816901
140
0.671881
4.438017
false
false
false
false
SunLiner/Floral
Floral/Floral/Classes/Home/Home/View/HomeArticleCell.swift
1
7173
// // HomeArticleCell.swift // Floral // // Created by ALin on 16/4/26. // Copyright © 2016年 ALin. All rights reserved. // import UIKit import SnapKit import Kingfisher class HomeArticleCell: UITableViewCell { var article : Article? { didSet{ if let art = article { // 设置数据 smallIconView.kf_setImageWithURL(NSURL(string: art.smallIcon!)!, placeholderImage: UIImage(named: "placehodler"), optionsInfo: [], progressBlock: nil, completionHandler: nil) headImgView.kf_setImageWithURL(NSURL(string: art.author!.headImg!)!, placeholderImage: UIImage(named: "pc_default_avatar"), optionsInfo: [], progressBlock: nil, completionHandler: nil) identityLabel.text = art.author!.identity! authorLabel.text = art.author!.userName ?? "佚名" categoryLabel.text = "[" + art.category!.name! + "]" titleLabel.text = art.title descLabel.text = art.desc bottomView.article = art authView.image = art.author?.authImage } } } var clickHeadImage : ((article: Article?)->())? // MARK: - 生命周期相关 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UI设置和布局 private func setupUI() { backgroundColor = UIColor(gray: 241) contentView.backgroundColor = UIColor.whiteColor() contentView.addSubview(smallIconView) contentView.addSubview(authorLabel) contentView.addSubview(identityLabel) contentView.addSubview(headImgView) contentView.addSubview(authView) contentView.addSubview(categoryLabel) contentView.addSubview(titleLabel) contentView.addSubview(descLabel) contentView.addSubview(underline) contentView.addSubview(bottomView) contentView.snp_makeConstraints { (make) in make.edges.equalTo(UIEdgeInsetsMake(8, 8, 0, -8)) } smallIconView.snp_makeConstraints { (make) in make.left.right.top.equalTo(contentView) make.height.equalTo(160) } headImgView.snp_makeConstraints { (make) in make.size.equalTo(CGSize(width: 51, height: 51)) make.right.equalTo(contentView).offset(-10) make.top.equalTo(smallIconView.snp_bottom).offset(-10) } authView.snp_makeConstraints { (make) in make.size.equalTo(CGSize(width: 14, height: 14)) make.bottom.right.equalTo(headImgView) } authorLabel.snp_makeConstraints { (make) in make.right.equalTo(headImgView.snp_left).offset(-10) make.top.equalTo(smallIconView.snp_bottom).offset(8) } identityLabel.snp_makeConstraints { (make) in make.right.equalTo(authorLabel) make.top.equalTo(authorLabel.snp_bottom).offset(4) } categoryLabel.snp_makeConstraints { (make) in make.left.equalTo(contentView).offset(10) make.top.equalTo(identityLabel.snp_bottom) } titleLabel.snp_makeConstraints { (make) in make.left.equalTo(categoryLabel) make.top.equalTo((categoryLabel.snp_bottom)).offset(10) make.width.lessThanOrEqualTo(contentView).offset(-20) } descLabel.snp_makeConstraints { (make) in make.left.equalTo(titleLabel) make.top.equalTo(titleLabel.snp_bottom).offset(5) make.width.lessThanOrEqualTo(contentView).offset(-40) make.height.equalTo(30) } underline.snp_makeConstraints { (make) in make.top.equalTo(descLabel.snp_bottom).offset(5) make.left.equalTo(descLabel).offset(5) make.right.equalTo(headImgView) } bottomView.snp_makeConstraints { (make) in make.top.equalTo(underline.snp_bottom).offset(5) make.left.right.equalTo(contentView) make.height.equalTo(30) } } // MARK: - 懒加载 /// 缩略图 private lazy var smallIconView : UIImageView = UIImageView() /// 作者 private lazy var authorLabel : UILabel = { let label = UILabel() label.font = UIFont.init(name: "CODE LIGHT", size: 14.0) label.text = "花田小憩"; return label }() /// 称号 private lazy var identityLabel : UILabel = { let label = UILabel() label.font = UIFont.init(name: "CODE LIGHT", size: 12.0) label.text = "资深专家"; label.textColor = UIColor.blackColor().colorWithAlphaComponent(0.9) return label }() /// 头像 private lazy var headImgView : UIImageView = { let headimage = UIImageView() headimage.image = UIImage(named: "pc_default_avatar") headimage.layer.cornerRadius = 51 * 0.5 headimage.layer.masksToBounds = true headimage.layer.borderWidth = 0.5 headimage.layer.borderColor = UIColor.lightGrayColor().CGColor headimage.userInteractionEnabled = true headimage.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(HomeArticleCell.toProfile))) return headimage }() /// 认证 private lazy var authView : UIImageView = { let auth = UIImageView() auth.image = UIImage(named: "personAuth") return auth }() /// 分类 private lazy var categoryLabel : UILabel = { let label = UILabel() label.font = UIFont.init(name: "CODE LIGHT", size: 14) label.textColor = UIColor(r: 199, g: 167, b: 98) label.text = "[家居庭院]"; return label }() /// 标题 private lazy var titleLabel : UILabel = { let label = UILabel() label.font = UIFont.init(name: "CODE LIGHT", size: 14) label.textColor = UIColor.blackColor() label.text = "旧物改造的灯旧物改造的灯旧物改造的"; return label }() /// 摘要 private lazy var descLabel : UILabel = { let label = UILabel() label.font = UIFont.init(name: "CODE LIGHT", size: 12) label.textColor = UIColor.blackColor().colorWithAlphaComponent(0.8) label.text = "呵呵呵呵呵呵呵阿里大好事老客服哈;是打发;圣达菲号;是都发生法adfasdfasdfasdf"; label.numberOfLines = 2 return label }() /// 下划线 private lazy var underline : UIImageView = UIImageView(image: UIImage(named: "underLine")) private lazy var bottomView : ToolBottomView = ToolBottomView() // MARK: - private method @objc private func toProfile() { clickHeadImage!(article: article) } }
mit
4e8adefeda6c12c8b6c4cd8c39613858
33.196078
200
0.598481
4.38191
false
false
false
false
MattKiazyk/Operations
framework/Operations/Conditions/ReachabilityCondition.swift
1
8693
// // ReachabilityCondition.swift // Operations // // Created by Daniel Thorpe on 19/07/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import Foundation import SystemConfiguration public final class Reachability { public enum NetworkStatus: Int { case NotConnected = 1, ReachableViaWiFi, ReachableViaWWAN } public typealias ObserverBlockType = (NetworkStatus) -> Void struct Observer { let reachabilityDidChange: ObserverBlockType } public static let sharedInstance = Reachability() public class func addObserver(observer: ObserverBlockType) -> String { let token = NSUUID().UUIDString sharedInstance.addObserverWithToken(token, observer: observer) return token } public class func removeObserverWithToken(token: String) { sharedInstance.removeObserverWithToken(token) } // Instance private var refs = [String: SCNetworkReachability]() private let queue = Queue.Utility.serial("me.danthorpe.Operations.Reachability") private var observers = [String: Observer]() private var isRunning = false private var defaultRouteReachability: SCNetworkReachability? private var previousReachabilityFlags: SCNetworkReachabilityFlags? = .None private var timer: dispatch_source_t? private lazy var timerQueue: dispatch_queue_t = Queue.Background.concurrent("me.danthorpe.Operations.Reachabiltiy.Timer") private var defaultRouteReachabilityFlags: SCNetworkReachabilityFlags? { get { if let ref = defaultRouteReachability { var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(ref, &flags) != 0 { return flags } } return .None } } private init() { defaultRouteReachability = { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) return withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } }() } public func addObserverWithToken(token: String, observer: ObserverBlockType) { observers.updateValue(Observer(reachabilityDidChange: observer), forKey: token) startNotifier() } public func removeObserverWithToken(token: String) { observers.removeValueForKey(token) stopNotifier() } public func requestReachabilityForURL(url: NSURL, completion: ObserverBlockType) { if let host = url.host { dispatch_async(queue) { var status = NetworkStatus.NotConnected let ref = self.refs[host] ?? SCNetworkReachabilityCreateWithName(nil, (host as NSString).UTF8String).takeRetainedValue() self.refs[host] = ref var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(ref, &flags) != 0 { status = self.networkStatusFromFlags(flags) } completion(status) } } } // Private private func startNotifier() { if !isRunning { isRunning = true if let _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerQueue) { // Fire every 250 milliseconds, with 250 millisecond leeway dispatch_source_set_timer(_timer, dispatch_walltime(nil, 0), 250 * NSEC_PER_MSEC, 250 * NSEC_PER_MSEC) dispatch_source_set_event_handler(_timer, timerDidFire) dispatch_resume(_timer) timer = _timer } } } private func stopNotifier() { if observers.count == 0 { if let _timer = timer { dispatch_source_cancel(_timer) timer = nil } isRunning = false } } private func timerDidFire() { if let currentReachabiltiyFlags = defaultRouteReachabilityFlags { if let previousReachabilityFlags = previousReachabilityFlags { if previousReachabilityFlags != currentReachabiltiyFlags { reachabilityFlagsDidChange(currentReachabiltiyFlags) } } previousReachabilityFlags = currentReachabiltiyFlags } } private func reachabilityFlagsDidChange(flags: SCNetworkReachabilityFlags) { let networkStatus = networkStatusFromFlags(flags) dispatch_async(Queue.Main.queue) { for (_, observer) in self.observers { observer.reachabilityDidChange(networkStatus) } } } private func networkStatusFromFlags(flags: SCNetworkReachabilityFlags) -> NetworkStatus { if isReachableViaWifi(flags) { return .ReachableViaWiFi } else if isReachableViaWWAN(flags) { return .ReachableViaWWAN } return .NotConnected } private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool { // return flags.contains(.Reachable) // Swift 2.0 return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable) != 0 } private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool { return flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired) != 0 } private func isReachableViaWifi(flags: SCNetworkReachabilityFlags) -> Bool { // return isReachable(flags) && !flags.contains(.ConnectionRequired) // Swift 2.0 return isReachable(flags) && !isConnectionRequired(flags) } private func isReachableViaWWAN(flags: SCNetworkReachabilityFlags) -> Bool { // return isReachable(flags) && flags.contains(.IsWWAN) // Swift 2.0 return isReachable(flags) && (flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsWWAN) != 0) } } public protocol HostReachability { func requestReachabilityForURL(url: NSURL, completion: Reachability.ObserverBlockType) } extension Reachability: HostReachability {} /** A condition that performs a single-shot reachability check. Reachability is evaluated once when the operation it is attached to is asked about its readiness. */ public class ReachabilityCondition: OperationCondition { static let defaultURL = NSURL(string: "http://apple.com") public enum Connectivity: Int { case AnyConnectionKind = 1, ConnectedViaWWAN, ConnectedViaWiFi } public enum Error: ErrorType, Equatable { case NotReachable case NotReachableWithConnectivity(Connectivity) } public let name = "Reachability" public let isMutuallyExclusive = false public var url: NSURL let connectivity: Connectivity let reachability: HostReachability public convenience init() { self.init(url:ReachabilityCondition.defaultURL!, connectivity:.AnyConnectionKind, reachability: Reachability.sharedInstance) } public convenience init(url: NSURL, connectivity: Connectivity = .AnyConnectionKind) { self.init(url: url, connectivity: connectivity, reachability: Reachability.sharedInstance) } public init(url: NSURL, connectivity: Connectivity = .AnyConnectionKind, reachability: HostReachability) { self.url = url self.connectivity = connectivity self.reachability = reachability } public func dependencyForOperation(operation: Operation) -> NSOperation? { return .None } public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { reachability.requestReachabilityForURL(url) { kind in switch (self.connectivity, kind) { case (_, .NotConnected): completion(.Failed(Error.NotReachable)) case (.AnyConnectionKind, _), (.ConnectedViaWWAN, _): completion(.Satisfied) case (.ConnectedViaWiFi, .ReachableViaWWAN): completion(.Failed(Error.NotReachableWithConnectivity(self.connectivity))) default: completion(.Failed(Error.NotReachable)) } } } } public func ==(a: ReachabilityCondition.Error, b: ReachabilityCondition.Error) -> Bool { switch (a, b) { case (.NotReachable, .NotReachable): return true case let (.NotReachableWithConnectivity(aConnectivity), .NotReachableWithConnectivity(bConnectivity)): return aConnectivity == bConnectivity default: return false } }
mit
de259203f118df33c764dec5c0c4bcbd
33.220472
136
0.659112
5.4325
false
false
false
false
natecook1000/swift
test/SILGen/switch_debuginfo.swift
3
2822
// RUN: %target-swift-emit-silgen -g -Xllvm -sil-print-debuginfo %s | %FileCheck %s func nop1() {} func nop2() {} enum Binary { case On case Off } func isOn(_ b: Binary) -> Bool { return b == .On } // CHECK: [[LOC:loc "[^"]+"]] // First, check that we don't assign fresh locations to each case statement, // except for any relevant debug value instructions. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test11iySi_tF func test1(i: Int) { switch i { // CHECK-NOT: [[LOC]]:[[@LINE+1]] case 0: // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]] // CHECK-NOT: [[LOC]]:[[@LINE-1]] nop1() // CHECK-NOT: [[LOC]]:[[@LINE+1]] case 1: // CHECK: debug_value {{.*}} : $Int, let, name "$match", [[LOC]]:[[@LINE]] // CHECK-NOT: [[LOC]]:[[@LINE-1]] nop1() default: // CHECK-NOT: [[LOC]]:[[@LINE]] nop1() } } // Next, check that case statements and switch subjects have the same locations. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test21sySS_tF func test2(s: String) { switch s { case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10 nop1() case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10 nop2() default: nop1() } } // Fallthrough shouldn't affect case statement locations. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test31sySS_tF func test3(s: String) { switch s { case "a", "b": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-2]]:10 // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-3]]:10 nop1() fallthrough case "b", "c": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-7]]:10 // CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE-8]]:10 nop2() fallthrough default: nop1() } } // It should be possible to set breakpoints on where clauses. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test41byAA6BinaryO_tF func test4(b: Binary) { switch b { case let _ // CHECK-NOT: [[LOC]]:[[@LINE]] where isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11 nop1() case let _ // CHECK-NOT: [[LOC]]:[[@LINE]] where !isOn(b): // CHECK: [[LOC]]:[[@LINE]]:11 nop2() default: nop1() } } // Check that we set the right locations before/after nested switches. // CHECK-LABEL: sil hidden @$S16switch_debuginfo5test51sySS_tF func test5(s: String) { switch s { case "a": // CHECK: string_literal utf8 "a", [[LOC]]:[[@LINE-1]]:10 switch "b" { case "b": // CHECK: string_literal utf8 "b", [[LOC]]:[[@LINE-1]]:12 nop1() default: nop2() } if "c" == "c" { // CHECK: string_literal utf8 "c", [[LOC]]:[[@LINE]] nop1() } default: nop1() } if "d" == "d" { // CHECK: string_literal utf8 "d", [[LOC]]:[[@LINE]] nop1() } }
apache-2.0
32612958caddf0cae37f8006bd6dad94
26.134615
85
0.559887
3.153073
false
true
false
false
kstaring/swift
stdlib/public/core/LazySequence.swift
4
7784
//===--- LazySequence.swift -----------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A sequence on which normally-eager operations such as `map` and /// `filter` are implemented lazily. /// /// Lazy sequences can be used to avoid needless storage allocation /// and computation, because they use an underlying sequence for /// storage and compute their elements on demand. For example, /// /// [1, 2, 3].lazy.map { $0 * 2 } /// /// is a sequence containing { `2`, `4`, `6` }. Each time an element /// of the lazy sequence is accessed, an element of the underlying /// array is accessed and transformed by the closure. /// /// Sequence operations taking closure arguments, such as `map` and /// `filter`, are normally eager: they use the closure immediately and /// return a new array. Using the `lazy` property gives the standard /// library explicit permission to store the closure and the sequence /// in the result, and defer computation until it is needed. /// /// To add new lazy sequence operations, extend this protocol with /// methods that return lazy wrappers that are themselves /// `LazySequenceProtocol`s. For example, given an eager `scan` /// method defined as follows /// /// extension Sequence { /// /// Returns an array containing the results of /// /// /// /// p.reduce(initial, nextPartialResult) /// /// /// /// for each prefix `p` of `self`, in order from shortest to /// /// longest. For example: /// /// /// /// (1..<6).scan(0, +) // [0, 1, 3, 6, 10, 15] /// /// /// /// - Complexity: O(n) /// func scan<ResultElement>( /// _ initial: ResultElement, /// _ nextPartialResult: (ResultElement, Iterator.Element) -> ResultElement /// ) -> [ResultElement] { /// var result = [initial] /// for x in self { /// result.append(nextPartialResult(result.last!, x)) /// } /// return result /// } /// } /// /// we can build a sequence that lazily computes the elements in the /// result of `scan`: /// /// struct LazyScanIterator<Base : IteratorProtocol, ResultElement> /// : IteratorProtocol { /// mutating func next() -> ResultElement? { /// return nextElement.map { result in /// nextElement = base.next().map { nextPartialResult(result, $0) } /// return result /// } /// } /// private var nextElement: ResultElement? // The next result of next(). /// private var base: Base // The underlying iterator. /// private let nextPartialResult: (ResultElement, Base.Element) -> ResultElement /// } /// /// struct LazyScanSequence<Base: Sequence, ResultElement> /// : LazySequenceProtocol // Chained operations on self are lazy, too /// { /// func makeIterator() -> LazyScanIterator<Base.Iterator, ResultElement> { /// return LazyScanIterator( /// nextElement: initial, base: base.makeIterator(), nextPartialResult) /// } /// private let initial: ResultElement /// private let base: Base /// private let nextPartialResult: /// (ResultElement, Base.Iterator.Element) -> ResultElement /// } /// /// and finally, we can give all lazy sequences a lazy `scan` method: /// /// extension LazySequenceProtocol { /// /// Returns a sequence containing the results of /// /// /// /// p.reduce(initial, nextPartialResult) /// /// /// /// for each prefix `p` of `self`, in order from shortest to /// /// longest. For example: /// /// /// /// Array((1..<6).lazy.scan(0, +)) // [0, 1, 3, 6, 10, 15] /// /// /// /// - Complexity: O(1) /// func scan<ResultElement>( /// _ initial: ResultElement, /// _ nextPartialResult: (ResultElement, Iterator.Element) -> ResultElement /// ) -> LazyScanSequence<Self, ResultElement> { /// return LazyScanSequence( /// initial: initial, base: self, nextPartialResult) /// } /// } /// /// - See also: `LazySequence`, `LazyCollectionProtocol`, `LazyCollection` /// /// - Note: The explicit permission to implement further operations /// lazily applies only in contexts where the sequence is statically /// known to conform to `LazySequenceProtocol`. Thus, side-effects such /// as the accumulation of `result` below are never unexpectedly /// dropped or deferred: /// /// extension Sequence where Iterator.Element == Int { /// func sum() -> Int { /// var result = 0 /// _ = self.map { result += $0 } /// return result /// } /// } /// /// [We don't recommend that you use `map` this way, because it /// creates and discards an array. `sum` would be better implemented /// using `reduce`]. public protocol LazySequenceProtocol : Sequence { /// A `Sequence` that can contain the same elements as this one, /// possibly with a simpler type. /// /// - See also: `elements` associatedtype Elements : Sequence = Self /// A sequence containing the same elements as this one, possibly with /// a simpler type. /// /// When implementing lazy operations, wrapping `elements` instead /// of `self` can prevent result types from growing an extra /// `LazySequence` layer. For example, /// /// _prext_ example needed /// /// Note: this property need not be implemented by conforming types, /// it has a default implementation in a protocol extension that /// just returns `self`. var elements: Elements { get } } /// When there's no special associated `Elements` type, the `elements` /// property is provided. extension LazySequenceProtocol where Elements == Self { /// Identical to `self`. public var elements: Self { return self } } /// A sequence containing the same elements as a `Base` sequence, but /// on which some operations such as `map` and `filter` are /// implemented lazily. /// /// - See also: `LazySequenceProtocol` public struct LazySequence<Base : Sequence> : LazySequenceProtocol, _SequenceWrapper { /// Creates a sequence that has the same elements as `base`, but on /// which some operations such as `map` and `filter` are implemented /// lazily. internal init(_base: Base) { self._base = _base } public var _base: Base /// The `Base` (presumably non-lazy) sequence from which `self` was created. public var elements: Base { return _base } } extension Sequence { /// A sequence containing the same elements as this sequence, /// but on which some operations, such as `map` and `filter`, are /// implemented lazily. /// /// - SeeAlso: `LazySequenceProtocol`, `LazySequence` public var lazy: LazySequence<Self> { return LazySequence(_base: self) } } /// Avoid creating multiple layers of `LazySequence` wrapper. /// Anything conforming to `LazySequenceProtocol` is already lazy. extension LazySequenceProtocol { /// Identical to `self`. public var lazy: Self { return self } } @available(*, unavailable, renamed: "LazySequenceProtocol") public typealias LazySequenceType = LazySequenceProtocol extension LazySequenceProtocol { @available(*, unavailable, message: "Please use Array initializer instead.") public var array: [Iterator.Element] { Builtin.unreachable() } }
apache-2.0
937413995f9a2f3783434dad62dc9469
36.423077
87
0.624872
4.358343
false
false
false
false
mdiep/Tentacle
Sources/Tentacle/File.swift
1
1985
// // File.swift // Tentacle // // Created by Romain Pouclet on 2016-12-21. // Copyright © 2016 Matt Diephouse. All rights reserved. // import Foundation extension Repository { /// A request to create a file at a given path in the repository. /// /// https://developer.github.com/v3/repos/contents/#create-a-file public func create(file: File, atPath path: String, inBranch branch: String? = nil) -> Request<FileResponse> { let queryItems: [URLQueryItem] if let branch = branch { queryItems = [ URLQueryItem(name: "branch", value: branch) ] } else { queryItems = [] } return Request( method: .put, path: "/repos/\(owner)/\(name)/contents/\(path)", queryItems: queryItems ) } } public struct File: ResourceType, Encodable { /// Commit message public let message: String /// The committer of the commit public let committer: Author? /// The author of the commit public let author: Author? /// Content of the file to create public let content: Data /// Branch in which the file will be created public let branch: String? public init(message: String, committer: Author?, author: Author?, content: Data, branch: String?) { self.message = message self.committer = committer self.author = author self.content = content self.branch = branch } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(message, forKey: .message) try container.encode(committer, forKey: .committer) try container.encode(author, forKey: .author) try container.encode(content.base64EncodedString(), forKey: .content) try container.encode(branch, forKey: .branch) } public func hash(into hasher: inout Hasher) { message.hash(into: &hasher) } }
mit
c56cbaf3c991321b8531cc49628719e6
31
114
0.63004
4.275862
false
false
false
false
maquannene/Track
Track/DiskCache.swift
1
20377
//The MIT License (MIT) // //Copyright (c) 2016 U Are My SunShine // //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. /** DiskCache thread safe = concurrent + semaphore lock sync thread safe write = write + semaphore lock thread safe read = read + semaphore lokc async thread safe write = async concurrent queue + thread safe sync write thread safe read = async concurrent queue + thread safe sync read */ import Foundation import QuartzCore /** * FastGeneratorType, inherit GeneratorType and provide a method to shift offset. */ public protocol FastGeneratorType: IteratorProtocol { /** Shift like next, but there is no return value. If you just shift offset, it`s implementation should fast than `next()` */ func shift() } /** DiskCacheGenerator, support `for...in` `map` `forEach`..., it is thread safe. */ open class DiskCacheGenerator : FastGeneratorType { public typealias Element = (String, Any) fileprivate var _lruGenerator: LRUGenerator<DiskCacheObject> fileprivate var _diskCache: DiskCache fileprivate var _completion: (() -> Void)? fileprivate init(generate: LRUGenerator<DiskCacheObject>, diskCache: DiskCache, completion: (() -> Void)?) { self._lruGenerator = generate self._diskCache = diskCache self._completion = completion } /** Advance to the next element and return it, or `nil` if no next element exists. - returns: next element */ open func next() -> Element? { if let key = _lruGenerator.next()?.key { if let value = _diskCache._unsafeObject(forKey: key) { return (key, value) } } return nil } /** Shift like next, but there is no return value and shift fast. */ open func shift() { let _ = _lruGenerator.shift() } deinit { _completion?() } } private class DiskCacheObject: LRUObject { var key: String = "" var cost: UInt = 0 var date: Date = Date() init (key: String, cost: UInt = 0, date: Date) { self.key = key self.cost = cost self.date = date } convenience init (key: String, cost: UInt = 0) { self.init(key: key, cost: cost, date: Date()) } } public typealias DiskCacheAsyncCompletion = (_ cache: DiskCache?, _ key: String?, _ object: Any?) -> Void /** DiskCache is a thread safe cache implement by dispatch_semaphore_t lock and DISPATCH_QUEUE_CONCURRENT Cache algorithms policy use LRU (Least Recently Used) implement by linked list. You can manage cache through functions to limit size, age of entries and memory usage to eliminate least recently used object. And support thread safe `for`...`in` loops, map, forEach... */ open class DiskCache { /** DiskCache folder name */ public let name: String /** DiskCache folder path URL */ public let cacheURL: URL /** Disk cache object total count */ open var totalCount: UInt { get { _lock() let count = _cache.count _unlock() return count } } /** Disk cache object total cost (byte) */ open var totalCost: UInt { get { _lock() let cost = _cache.cost _unlock() return cost } } fileprivate var _countLimit: UInt = UInt.max /** The maximum total quantity */ open var countLimit: UInt { set { _lock() _countLimit = newValue _unlock() trim(toCount: newValue) } get { _lock() let countLimit = _countLimit _unlock() return countLimit } } fileprivate var _costLimit: UInt = UInt.max /** The maximum disk cost limit */ open var costLimit: UInt { set { _lock() _costLimit = newValue _unlock() trim(toCost: newValue) } get { _lock() let costLimit = _costLimit _unlock() return costLimit } } fileprivate var _ageLimit: TimeInterval = Double.greatestFiniteMagnitude /** Disk cache object age limit */ open var ageLimit: TimeInterval { set { _lock() _ageLimit = newValue _unlock() trim(toAge: newValue) } get { _lock() let ageLimit = _ageLimit _unlock() return ageLimit } } fileprivate let _cache: LRU = LRU<DiskCacheObject>() fileprivate let _queue: DispatchQueue = DispatchQueue(label: TrackCachePrefix + (String(describing: DiskCache.self)), attributes: DispatchQueue.Attributes.concurrent) fileprivate let _semaphoreLock: DispatchSemaphore = DispatchSemaphore(value: 1) /** A share disk cache, name "defauleTrackCache" path "Library/Caches/" */ public static let shareInstance = DiskCache(name: TrackCacheDefauleName)! /** Design constructor The same name and path has the same disk folder Cache - parameter name: disk cache folder name - parameter path: disk cache folder path - returns: if no name or path will be fail */ public init?(name: String, path: String) { if name.count == 0 || path.count == 0 { return nil } self.name = name self.cacheURL = URL(fileURLWithPath: path).appendingPathComponent(TrackCachePrefix + name, isDirectory: false) _lock() _queue.async { _ = self._createCacheDir() _ = self._loadFilesInfo() self._unlock() } } /** convenience constructor - parameter name: disk cache foler name - returns: if no name will be fail */ public convenience init?(name: String) { self.init(name: name, path: NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]) } } // MARK: // MARK: Public public extension DiskCache { // MARK: Async /** Async store an object for the unique key in disk cache and store object info to linked list head completion will be call after object has been store in disk - parameter object: object must be implement NSCoding protocal - parameter key: unique key - parameter completion: stroe completion call back */ func set(object: NSCoding, forKey key: String, completion: DiskCacheAsyncCompletion?) { _queue.async { [weak self] in guard let strongSelf = self else { completion?(nil, key, object); return } strongSelf.set(object: object, forKey: key) completion?(strongSelf, key, object) } } /** Async search object according to unique key if find object, object info will move to linked list head */ func object(forKey key: String, completion: DiskCacheAsyncCompletion?) { _queue.async { [weak self] in guard let strongSelf = self else { completion?(nil, key, nil); return } let object = strongSelf.object(forKey: key) completion?(strongSelf, key, object) } } /** Async remove object according to unique key from disk and remove object info from linked list */ func removeObject(forKey key: String, completion: DiskCacheAsyncCompletion?) { _queue.async { [weak self] in guard let strongSelf = self else { completion?(nil, key, nil); return } strongSelf.removeObject(forKey: key) completion?(strongSelf, key, nil) } } /** Async remove all object and info from disk and linked list */ func removeAllObjects(_ completion: DiskCacheAsyncCompletion?) { _queue.async { [weak self] in guard let strongSelf = self else { completion?(nil, nil, nil); return } strongSelf.removeAllObjects() completion?(strongSelf, nil, nil) } } /** Async trim disk cache total to countLimit according LRU - parameter countLimit: maximum countLimit */ func trim(toCount countLimit: UInt, completion: DiskCacheAsyncCompletion?) { _queue.async { [weak self] in guard let strongSelf = self else { completion?(nil, nil, nil); return } strongSelf.trim(toCount: countLimit) completion?(strongSelf, nil, nil) } } /** Async trim disk cache totalcost to costLimit according LRU - parameter costLimit: maximum costLimit */ func trim(toCost costLimit: UInt, completion: DiskCacheAsyncCompletion?) { _queue.async { [weak self] in guard let strongSelf = self else { completion?(nil, nil, nil); return } strongSelf.trim(toCost: costLimit) completion?(strongSelf, nil, nil) } } /** Async trim disk cache objects which age greater than ageLimit - parameter ageLimit: maximum ageLimit */ func trim(toAge ageLimit: TimeInterval, completion: DiskCacheAsyncCompletion?) { _queue.async { [weak self] in guard let strongSelf = self else { completion?(nil, nil, nil); return } strongSelf.trim(toAge: ageLimit) completion?(strongSelf, nil, nil) } } // MARK: Sync /** Sync store an object for the unique key in disk cache and store object info to linked list head */ func set(object: NSCoding, forKey key: String) { guard let fileURL = _generateFileURL(key, path: cacheURL) else { return } let filePath = fileURL.path _lock() if NSKeyedArchiver.archiveRootObject(object, toFile: filePath) == true { do { let date: Date = Date() try FileManager.default.setAttributes([FileAttributeKey.modificationDate : date], ofItemAtPath: filePath) let infosDic: [URLResourceKey : AnyObject] = try (fileURL as NSURL).resourceValues(forKeys: [URLResourceKey.totalFileAllocatedSizeKey]) as [URLResourceKey : AnyObject] var fileSize: UInt = 0 if let fileSizeNumber = infosDic[URLResourceKey.totalFileAllocatedSizeKey] as? NSNumber { fileSize = fileSizeNumber.uintValue } _cache.set(object: DiskCacheObject(key: key, cost: fileSize, date: date), forKey: key) } catch {} } if _cache.cost > _costLimit { _unsafeTrim(toCost: _costLimit) } if _cache.count > _countLimit { _unsafeTrim(toCount: _countLimit) } _unlock() } /** Sync search object according to unique key if find object, object info will move to linked list head */ func object(forKey key: String) -> AnyObject? { _lock() let object = _unsafeObject(forKey: key) _unlock() return object } /** Sync remove object according to unique key from disk and remove object info from linked list */ func removeObject(forKey key: String) { guard let fileURL = _generateFileURL(key, path: cacheURL) else { return } let filePath = fileURL.path _lock() if FileManager.default.fileExists(atPath: filePath) { do { try FileManager.default.removeItem(atPath: filePath) _ = _cache.removeObject(forKey: key) } catch {} } _unlock() } /** Sync remove all object and info from disk and linked list */ func removeAllObjects() { _lock() if FileManager.default.fileExists(atPath: self.cacheURL.path) { do { try FileManager.default.removeItem(atPath: self.cacheURL.path) _cache.removeAllObjects() } catch {} } _unlock() } /** Async trim disk cache total to countLimit according LRU */ func trim(toCount countLimit: UInt) { if self.totalCount <= countLimit { return } if countLimit == 0 { removeAllObjects() return } _lock() _unsafeTrim(toCount: countLimit) _unlock() } /** Sync trim disk cache totalcost to costLimit according LRU */ func trim(toCost costLimit: UInt) { if self.totalCost <= costLimit { return } if costLimit == 0 { removeAllObjects() return } _lock() _unsafeTrim(toCost: costLimit) _unlock() } /** Sync trim disk cache objects which age greater than ageLimit */ func trim(toAge ageLimit: TimeInterval) { if ageLimit <= 0 { removeAllObjects() return } _lock() _unsafeTrim(toAge: ageLimit) _unlock() } subscript(key: String) -> NSCoding? { get { if let returnValue = object(forKey: key) as? NSCoding { return returnValue } return nil } set { if let newValue = newValue { set(object: newValue, forKey: key) } else { removeObject(forKey: key) } } } } // MARK: SequenceType extension DiskCache : Sequence { /** MemoryCacheGenerator */ public typealias Iterator = DiskCacheGenerator /** Returns a generator over the elements of this sequence. It is thread safe, if you call `generate()`, remember release it, otherwise maybe it lead to deadlock. - returns: A generator */ public func makeIterator() -> DiskCacheGenerator { var generatror: DiskCacheGenerator _lock() generatror = DiskCacheGenerator(generate: _cache.makeIterator(), diskCache: self) { self._unlock() } return generatror } } // MARK: // MARK: Private private extension DiskCache { func _createCacheDir() -> Bool { if FileManager.default.fileExists(atPath: cacheURL.path) { return false } do { try FileManager.default.createDirectory(atPath: cacheURL.path, withIntermediateDirectories: true, attributes: nil) } catch { return false } return true } func _loadFilesInfo() -> Bool { var fileInfos: [DiskCacheObject] = [DiskCacheObject]() let fileInfoKeys: [URLResourceKey] = [URLResourceKey.contentModificationDateKey, URLResourceKey.totalFileAllocatedSizeKey] do { let filesURL: [URL] = try FileManager.default.contentsOfDirectory(at: cacheURL, includingPropertiesForKeys: fileInfoKeys, options: .skipsHiddenFiles) for fileURL: URL in filesURL { do { let infosDic: [URLResourceKey : AnyObject] = try (fileURL as NSURL).resourceValues(forKeys: fileInfoKeys) as [URLResourceKey : AnyObject] if let key = fileURL.lastPathComponent as String?, let date = infosDic[URLResourceKey.contentModificationDateKey] as? Date, let fileSize = infosDic[URLResourceKey.totalFileAllocatedSizeKey] as? NSNumber { fileInfos.append(DiskCacheObject(key: key, cost: fileSize.uintValue, date: date)) } } catch { return false } } fileInfos.sort { $0.date.timeIntervalSince1970 < $1.date.timeIntervalSince1970 } fileInfos.forEach { _cache.set(object: $0, forKey: $0.key) } } catch { return false } return true } func _unsafeTrim(toCount countLimit: UInt) { if var lastObject: DiskCacheObject = _cache.lastObject() { while (_cache.count > countLimit) { if let fileURL = _generateFileURL(lastObject.key, path: cacheURL), FileManager.default.fileExists(atPath: fileURL.path) { do { try FileManager.default.removeItem(atPath: fileURL.path) _cache.removeLastObject() guard let newLastObject = _cache.lastObject() else { break } lastObject = newLastObject } catch {} } } } } func _unsafeTrim(toCost costLimit: UInt) { if var lastObject: DiskCacheObject = _cache.lastObject() { while (_cache.cost > costLimit) { if let fileURL = _generateFileURL(lastObject.key, path: cacheURL) , FileManager.default.fileExists(atPath: fileURL.path) { do { try FileManager.default.removeItem(atPath: fileURL.path) _cache.removeLastObject() guard let newLastObject = _cache.lastObject() else { break } lastObject = newLastObject } catch {} } } } } func _unsafeTrim(toAge ageLimit: TimeInterval) { if var lastObject: DiskCacheObject = _cache.lastObject() { while (lastObject.date.timeIntervalSince1970 < Date().timeIntervalSince1970 - ageLimit) { if let fileURL = _generateFileURL(lastObject.key, path: cacheURL) , FileManager.default.fileExists(atPath: fileURL.path) { do { try FileManager.default.removeItem(atPath: fileURL.path) _cache.removeLastObject() guard let newLastObject = _cache.lastObject() else { break } lastObject = newLastObject } catch {} } } } } func _unsafeObject(forKey key: String) -> AnyObject? { guard let fileURL = _generateFileURL(key, path: cacheURL) else { return nil } var object: AnyObject? = nil let date: Date = Date() if FileManager.default.fileExists(atPath: fileURL.path) { object = NSKeyedUnarchiver.unarchiveObject(withFile: fileURL.path) as AnyObject? do { try FileManager.default.setAttributes([FileAttributeKey.modificationDate : date], ofItemAtPath: fileURL.path) if object != nil { if let diskCacheObj = _cache.object(forKey: key) { diskCacheObj.date = date } } } catch { } } return object } func _generateFileURL(_ key: String, path: URL) -> URL? { return path.appendingPathComponent(key) } func _lock() { _ = _semaphoreLock.wait(timeout: DispatchTime.distantFuture) } func _unlock() { _semaphoreLock.signal() } }
mit
72e7121df259edc86ae338f8f71294b6
30.888889
183
0.576974
4.914858
false
false
false
false
crspybits/SyncServerII
Sources/Server/Database/MasterVersionRepository.swift
1
4054
// // MasterVersionRepository.swift // Server // // Created by Christopher Prince on 11/26/16. // // // This tracks an overall version of the fileIndex per sharingGroupUUID. import Foundation import SyncServerShared import LoggerAPI class MasterVersion : NSObject, Model { static let sharingGroupUUIDKey = "sharingGroupUUID" var sharingGroupUUID: String! static let masterVersionKey = "masterVersion" var masterVersion: MasterVersionInt! subscript(key:String) -> Any? { set { switch key { case MasterVersion.sharingGroupUUIDKey: sharingGroupUUID = newValue as? String case MasterVersion.masterVersionKey: masterVersion = newValue as? MasterVersionInt default: assert(false) } } get { return getValue(forKey: key) } } } class MasterVersionRepository : Repository, RepositoryLookup { private(set) var db:Database! required init(_ db:Database) { self.db = db } var tableName:String { return MasterVersionRepository.tableName } static var tableName:String { return "MasterVersion" } let initialMasterVersion = 0 func upcreate() -> Database.TableUpcreateResult { let createColumns = "(sharingGroupUUID VARCHAR(\(Database.uuidLength)) NOT NULL, " + "masterVersion BIGINT NOT NULL, " + "FOREIGN KEY (sharingGroupUUID) REFERENCES \(SharingGroupRepository.tableName)(\(SharingGroup.sharingGroupUUIDKey)), " + "UNIQUE (sharingGroupUUID))" return db.createTableIfNeeded(tableName: "\(tableName)", columnCreateQuery: createColumns) } enum LookupKey : CustomStringConvertible { case sharingGroupUUID(String) var description : String { switch self { case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID(\(sharingGroupUUID))" } } } // The masterVersion is with respect to the userId func lookupConstraint(key:LookupKey) -> String { switch key { case .sharingGroupUUID(let sharingGroupUUID): return "sharingGroupUUID = '\(sharingGroupUUID)'" } } func initialize(sharingGroupUUID:String) -> Bool { let query = "INSERT INTO \(tableName) (sharingGroupUUID, masterVersion) " + "VALUES('\(sharingGroupUUID)', \(initialMasterVersion)) " if db.query(statement: query) { return true } else { let error = db.error Log.error("Could not initialize MasterVersion: \(error)") return false } } enum UpdateToNextResult { case error(String) case didNotMatchCurrentMasterVersion case success case deadlock case waitTimeout } // Increments master version for specific sharingGroupUUID func updateToNext(current:MasterVersion) -> UpdateToNextResult { let query = "UPDATE \(tableName) SET masterVersion = masterVersion + 1 " + "WHERE sharingGroupUUID = '\(current.sharingGroupUUID!)' and " + "masterVersion = \(current.masterVersion!)" if db.query(statement: query) { if db.numberAffectedRows() == 1 { return UpdateToNextResult.success } else { return UpdateToNextResult.didNotMatchCurrentMasterVersion } } else if db.errorCode() == Database.deadlockError { return .deadlock } else if db.errorCode() == Database.lockWaitTimeout { return .waitTimeout } else { let message = "Could not updateToNext MasterVersion: \(db.error)" Log.error(message) return UpdateToNextResult.error(message) } } }
mit
6f201ddb409b093ec443ba8351aee892
28.165468
132
0.591021
5.500678
false
false
false
false
andrewBatutin/SwiftYamp
SwiftYampTests/Server/YampConnectionTest.swift
1
6230
// // YampConnectionTest.swift // SwiftYamp // // Created by Andrey Batutin on 6/22/17. // Copyright © 2017 Andrey Batutin. All rights reserved. // import Quick import Nimble @testable import SwiftYamp class TableOfContentsSpec: QuickSpec { override func spec() { describe("handshake") { context("succesfull connection"){ it("send handshake echo on handshake received") { let h = HandshakeFrame(version: 0x1) var isConnected = false var handshakeSend:HandshakeFrame? let sut = WebSocketConnection(url: "ws://localhost:8888")! sut.onConnect = { isConnected = true } sut.onDataReceived = { data in handshakeSend = try! HandshakeFrame(data: data!) } sut.webSocket?.onData?(try! h.toData()) expect(isConnected).toEventually(beTrue()) expect(handshakeSend!.version).toEventually(equal(UInt16(0x01))) } } context("version not supported"){ it("sends close.version_not_supported resp"){ let h = HandshakeFrame(version: 0x0) var closeCode:CloseCodeType? let sut = WebSocketConnection(url: "ws://localhost:8888")! sut.onClose = { reason, code in closeCode = code } sut.webSocket?.onData?(try! h.toData()) expect(closeCode).toEventually(equal(CloseCodeType.VersionNotSupported)) } } context("outgoing redirect"){ it("should redirect to new url if redirect callback is implemented"){ let h = HandshakeFrame(version: 0x1) var closeCode:CloseCodeType? var closeFrame:CloseFrame? let sut = WebSocketConnection(url: "ws://localhost:8888")! sut.onRedirect = { return "new_url" } sut.onDataSend = { data in closeFrame = try! CloseFrame(data: data!) } sut.onClose = { reason, code in closeCode = code } sut.webSocket?.onData?(try! h.toData()) expect(closeCode).toEventually(equal(CloseCodeType.Redirect)) expect(closeFrame?.message).toEventually(equal("new_url")) } } context("incoming redirect"){ it("should reconnect to new url if close.redirect received"){ let redirectClose = CloseFrame(closeCode: .Redirect, message: "ws://localhost:7777") var closeCode:CloseCodeType? let sut = WebSocketConnection(url: "ws://localhost:8888")! var reasonRedirect:String? var isConnected = false var handshakeSend:HandshakeFrame? sut.onClose = { reason, code in closeCode = code sut.reconnect(url: reason) let h = HandshakeFrame(version: 0x1) sut.onConnect = { isConnected = true } sut.onDataReceived = { data in handshakeSend = try! HandshakeFrame(data: data!) } sut.webSocket?.onData?(try! h.toData()) reasonRedirect = reason } sut.webSocket?.onData?(try! redirectClose.toData()) expect(closeCode).toEventually(equal(CloseCodeType.Redirect)) expect(isConnected).toEventually(beTrue()) expect(handshakeSend!.version).toEventually(equal(UInt16(0x01))) expect(reasonRedirect!).toEventually(equal("ws://localhost:7777")) } } } describe("normal operation"){ context("timeout"){ it("send close.timeout", closure: { var closeCode:CloseCodeType? let sut = WebSocketConnection(url: "ws://localhost:8888")! sut.onClose = { reason, code in closeCode = code } sut.timeout() expect(closeCode).toEventually(equal(CloseCodeType.Timeout)) }) it("received close.timeout", closure: { var closeCode:CloseCodeType? let c = CloseFrame(closeCode: .Timeout) let sut = WebSocketConnection(url: "ws://localhost:8888")! sut.onClose = { reason, code in closeCode = code } sut.webSocket?.onData?(try! c.toData()) expect(closeCode).toEventually(equal(CloseCodeType.Timeout)) }) } } } }
mit
0fe9cd10c88a1b6c2cc9656f222eb943
36.077381
104
0.40472
6.792803
false
false
false
false
sunlijian/sinaBlog_repository
sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Module/Compose/View/IWComposeView.swift
1
5830
// // IWComposeView.swift // sinaBlog_sunlijian // // Created by sunlijian on 15/10/18. // Copyright © 2015年 myCompany. All rights reserved. // import UIKit import pop let COMPOSE_BUTTON_MAGIN: CGFloat = (SCREEN_W - 3*COMPOSE_BUTTON_W) / 4 class IWComposeView: UIView { var targetVC : UIViewController? override init(frame: CGRect) { super.init(frame: frame) //设置大小 self.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H) //添加背景图片 let imageView = UIImageView(image: screenImage()) imageView.size = size addSubview(imageView) //添加 button addMeumButton() //添加compose_slogan addCompose_sloganImage() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //屏幕载图 private func screenImage() -> UIImage{ //取出 window let window = UIApplication.sharedApplication().keyWindow //开启图形上下文 UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_W, SCREEN_H), false, 0) //把当前 window 显示的图形添加到上下文中 window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: false) //获取图片 var image = UIGraphicsGetImageFromCurrentImageContext() //进行模糊渲染 image = image.applyLightEffect() //关闭图形上下文 UIGraphicsEndImageContext() return image } //添加 button private func addMeumButton(){ //解析 plist 文件 let path = NSBundle.mainBundle().pathForResource("compose", ofType: "plist") let composeButtonInfos = NSArray(contentsOfFile: path!) //遍历添加 button for i in 0..<composeButtonInfos!.count{ //创建 button let buttonInfo = IWComposeButton() //添加监听事件 buttonInfo.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside) //取出字典 let info = composeButtonInfos![i] as! [String: AnyObject] //给 button 赋值 buttonInfo.setImage(UIImage(named: (info["icon"] as! String)), forState: UIControlState.Normal) buttonInfo.setTitle((info["title"] as! String), forState: UIControlState.Normal) //设置 button 的 位置 let rowIndex = i / 3 let colIndex = i % 3 buttonInfo.x = CGFloat(colIndex) * COMPOSE_BUTTON_W + CGFloat(colIndex + 1) * COMPOSE_BUTTON_MAGIN buttonInfo.y = CGFloat(rowIndex) * COMPOSE_BUTTON_H + CGFloat(rowIndex + 1) * COMPOSE_BUTTON_MAGIN + SCREEN_H print(buttonInfo.x) //添加到当前 view 上 addSubview(buttonInfo) //添加到数组中 composeButtons.append(buttonInfo) } } //点击加号按钮 func show(target:UIViewController){ target.view.addSubview(self) self.targetVC = target //添加动画 for (index, value) in composeButtons.enumerate(){ anmi(value, centerY: value.centerY - 400, index: index) } } //点击屏幕消失 override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { dismiss() } func dismiss(){ for (index, value) in composeButtons.reverse().enumerate(){ anmi(value, centerY: value.centerY + 400, index: index) } dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.removeFromSuperview() } } //初始化添加顶部控件到 view 上 private func addCompose_sloganImage(){ addSubview(sloganImage) } //懒加载顶部的 logo控件 private lazy var sloganImage : UIImageView = { let imageView = UIImageView(image: UIImage(named: "compose_slogan")) imageView.centerX = SCREEN_W * 0.5 imageView.y = 100 return imageView }() //button 数组的懒加载 private lazy var composeButtons :[IWComposeButton] = [IWComposeButton]() //button 的点击事件 @objc private func composeButtonClick(button: IWComposeButton){ UIView.animateWithDuration(0.25, animations: { () -> Void in //改变 button 的 transform for value in self.composeButtons{ if value == button { value.transform = CGAffineTransformMakeScale(2, 2) }else{ value.transform = CGAffineTransformMakeScale(0, 0) } value.alpha = 0 } }) { (finish) -> Void in let vc = IWComposeViewController() let nv = IWNavigationController(rootViewController: vc) self.targetVC?.presentViewController(nv, animated: true, completion: { () -> Void in self.removeFromSuperview() }) } } //动画 private func anmi(value:UIButton, centerY:CGFloat, index: Int){ //初始化一个弹性动画对象 let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter) anim.toValue = NSValue(CGPoint: CGPointMake(value.centerX, centerY)) //动画的弹性幅度 anim.springBounciness = 10 //动画的速度 anim.springSpeed = 10 //动画的执行时间(相对于现在来说 向后延迟多少秒) anim.beginTime = CACurrentMediaTime() + Double(index) * 0.025 //给控件添加动画对象 value.pop_addAnimation(anim, forKey: nil) } }
apache-2.0
e99eb79fc276caae91323f8096a89615
32.233129
134
0.587595
4.521703
false
false
false
false
hayashi311/iosdcjp2016app
iOSApp/iOSDCJP2016/Style.swift
1
3804
// // Style.swift // iOSDCJP2016 // // Created by hayashi311 on 6/9/16. // Copyright © 2016 hayashi311. All rights reserved. // import UIKit extension UIColor { static func darkPrimaryTextColor() -> UIColor { return UIColor(red: 0.01, green: 0.14, blue: 0.31, alpha: 1.0) } static func primaryTextColor() -> UIColor { return UIColor(red: 0.29, green: 0.29, blue: 0.29, alpha: 1.0) } static func secondaryTextColor() -> UIColor { return UIColor(red: 0.29, green: 0.29, blue: 0.29, alpha: 0.5) } static func accentColor() -> UIColor { return UIColor(red: 0.0, green: 0.68, blue: 0.79, alpha: 1.0) } static func secondaryAccentColor() -> UIColor { return UIColor(red: 0.69, green: 0.82, blue: 0.03, alpha: 1.0) } static func twitterColor() -> UIColor { return UIColor(red: 0.0, green: 0.67, blue: 0.93, alpha: 1.0) } static func colorForRoom(room: Session.Room) -> UIColor { switch room { case .A: return UIColor.accentColor() case .B: return UIColor.secondaryAccentColor() } } } class AttributedStringBuilder { enum Weight { case Thin case Regular case Bold var fontWeight: CGFloat { get { switch self { case .Thin: return UIFontWeightThin case .Regular: return UIFontWeightRegular case .Bold: return UIFontWeightBold } } } } let size: CGFloat var color: UIColor var textAlignment: NSTextAlignment var weight: Weight init(size: CGFloat, color: UIColor, textAlignment: NSTextAlignment, weight: Weight) { self.size = size self.color = color self.textAlignment = textAlignment self.weight = weight } func build() -> [String: AnyObject] { let style = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle style.alignment = textAlignment return [ NSForegroundColorAttributeName: color, NSFontAttributeName: UIFont.systemFontOfSize(size, weight: weight.fontWeight), NSParagraphStyleAttributeName: style, ] } } enum TextStyle { case Title case Body case Small var builder: AttributedStringBuilder { // http://www.modularscale.com/?14&px&1.333&web&text let baseSize: CGFloat = 14 let scale: CGFloat = 1.333 switch self { case .Title: return AttributedStringBuilder(size: baseSize * scale, color: UIColor.primaryTextColor(), textAlignment: .Left, weight: .Thin) case .Body: return AttributedStringBuilder(size: 14, color: UIColor.primaryTextColor(), textAlignment: .Left, weight: .Regular) case .Small: return AttributedStringBuilder(size: 12, color: UIColor.secondaryTextColor(), textAlignment: .Left, weight: .Regular) } } } extension NSAttributedString { convenience init(string: String, style: TextStyle) { let attrs = style.builder.build() self.init(string: string, attributes: attrs) } convenience init(string: String, style: TextStyle, tweak: ((inout builder: AttributedStringBuilder) -> Void)) { var builder = style.builder tweak(builder: &builder) let attrs = builder.build() self.init(string: string, attributes: attrs) } } let defaultLineHeight: CGFloat = 4 let iconImageRadius: CGFloat = 36
mit
0303dfc9d69aa2599d7823c9325e2a7f
27.593985
115
0.577439
4.609697
false
false
false
false
OlafAndreas/SimpleNumpad
Classes/NumberpadViewController.swift
1
2562
// // NumberpadViewController.swift // SimpleNumpad // // Created by Olaf Øvrum on 07.06.2016. // Copyright © 2016 Viking Software Solutions. All rights reserved. // import UIKit open class NumberPadViewController : UIViewController { @IBOutlet var numberPadView: UIInputView! @IBOutlet var backspaceButton: UIButton! static var numpadPopover: CustomPopoverViewController? var onValueChanged: ((String) -> ())? var value: String = "" { didSet { self.onValueChanged?(value) } } @IBAction func numberPressed(_ sender: UIButton) { value = value + "\(sender.tag)" } @IBAction func backspace(_ sender: AnyObject) { if value.isEmpty { return } let index = value.index(before: value.endIndex) value = String(value[..<index]) } @IBAction func done(_ sender: AnyObject) { NumberPadViewController.numpadPopover?.dismissPopover() } open class func display(_ onViewController: UIViewController, fromView: UIView, value: Int, onValueChanged: @escaping (String) -> (), passthroughViews: [UIView]?) { if let popover = numpadPopover { popover.onPopoverDismissed = { numpadPopover = nil display(onViewController, fromView: fromView, value: value, onValueChanged: onValueChanged, passthroughViews: passthroughViews) } popover.dismissPopover(false) return } let storyboard = UIStoryboard(name: "SimpleNumpad", bundle: Bundle(for: NumberPadViewController.self)) let numpadViewController = storyboard.instantiateViewController(withIdentifier: "NumberPad") as! NumberPadViewController numpadViewController.value = value == 0 ? "" : "\(value)" numpadViewController.onValueChanged = onValueChanged numpadPopover = CustomPopoverViewController(presentingViewController: onViewController, contentViewController: numpadViewController) numpadPopover?.presentPopover(sourceView: fromView.superview!, sourceRect: fromView.frame, permittedArrowDirections: .down, passThroughViews: passthroughViews) numpadPopover?.onPopoverDismissed = { NumberPadViewController.numpadPopover = nil } } }
mit
69a583d358eb6182196dac2e31025d46
29.47619
168
0.605078
5.470085
false
false
false
false
Eonil/EditorLegacy
Modules/Editor/Sources/SpecificUIComponents/CodeEditing/SyntaxHighlighting/SyntaxHighlighting.swift
1
10175
//// //// SyntaxHighlighting.swift //// Editor //// //// Created by Hoon H. on 12/25/14. //// Copyright (c) 2014 Eonil. All rights reserved. //// // //import Foundation //import AppKit //import EonilDispatch // ///// Ad-hoc syntax highlighting. //class SyntaxHighlighting { // let targetTextView:CodeTextView // // init(targetTextView:CodeTextView) { // self.targetTextView = targetTextView // reset() // } // // func available() -> Bool { // return cursor!.available() // } // func reset() { // let c = Cursor(targetView: targetTextView.textStorage!.string.unicodeScalars) // self.cursor = c // self.singlelineCommentScanner = EnclosingBlockScanner(cursor: c, startMarkerString: "//", endMarkerString: "\n") // self.multilineCommentScanner = EnclosingBlockScanner(cursor: c, startMarkerString: "/*", endMarkerString: "*/") // self.attributeScanner1 = EnclosingBlockScanner(cursor: c, startMarkerString: "#[", endMarkerString: "]") // self.attributeScanner2 = EnclosingBlockScanner(cursor: c, startMarkerString: "#![", endMarkerString: "]") // self.stringScanner = EnclosingBlockScanner(cursor: c, startMarkerString: "\"", endMarkerString: "\"") // self.tokenScanner = TokenScanner(cursor: c, separators: punctuators()) // } // func step() { // assert(tokenScanner != nil) // assert(singlelineCommentScanner != nil) // assert(multilineCommentScanner != nil) // assertMainThread() // // //// // // if singlelineCommentScanner!.available() { // let r = singlelineCommentScanner!.scan() // setBlockTypeOnRange(CodeTextStorage.SyntacticType.Comment, r) //// setColorOnRange(commentColor(), r) // return // } // // if multilineCommentScanner!.available() { // let r = multilineCommentScanner!.scan() // setBlockTypeOnRange(CodeTextStorage.SyntacticType.Comment, r) //// setColorOnRange(commentColor(), r) // return // } // // if attributeScanner1!.available() { // let r = attributeScanner1!.scan() // setBlockTypeOnRange(CodeTextStorage.SyntacticType.Attribute, r) //// setColorOnRange(attributeColor(), attributeScanner1!.scan()) // return // } // if attributeScanner2!.available() { // let r = attributeScanner2!.scan() // setBlockTypeOnRange(CodeTextStorage.SyntacticType.Attribute, r) //// setColorOnRange(attributeColor(), attributeScanner2!.scan()) // return // } // // if stringScanner!.available() { // let r = stringScanner!.scan() // setBlockTypeOnRange(CodeTextStorage.SyntacticType.String, r) //// setColorOnRange(stringColor(), stringScanner!.scan()) // return // } // // if tokenScanner!.available() { // let ks = keywords() // let r = tokenScanner!.scan() // let s = String(cursor!.targetView[r]) // if contains(ks, s) { // setBlockTypeOnRange(CodeTextStorage.SyntacticType.Keyword, r) //// setColorOnRange(keywordColor(), r) // } else { // setBlockTypeOnRange(CodeTextStorage.SyntacticType.None, r) //// unsetColorOnRange(r) // } // return // } // // let r = cursor!.location..<cursor!.location.successor() // setBlockTypeOnRange(CodeTextStorage.SyntacticType.None, r) //// unsetColorOnRange(cursor!.location..<cursor!.location.successor()) // cursor!.step() // } // // //// // // private var cursor:Cursor? // private var singlelineCommentScanner:EnclosingBlockScanner? // private var multilineCommentScanner:EnclosingBlockScanner? // private var attributeScanner1:EnclosingBlockScanner? // private var attributeScanner2:EnclosingBlockScanner? // private var stringScanner:EnclosingBlockScanner? // private var tokenScanner:TokenScanner? // // private func setBlockTypeOnRange(blockType:CodeTextStorage.SyntacticType, _ r:URange) { // let s = targetTextView.textStorage!.string // let r1 = s.convertRangeToNSRange(r) // targetTextView.codeTextStorage.setSyntacticType(blockType, range: r1, notify:false) // } // //// private func setColorOnRange(c:NSColor, _ r:URange) { //// let s = targetTextView.textStorage!.string //// let r1 = s.convertRangeToNSRange(r) //// targetTextView.codeTextStorage.setSyntacticType(CodeTextStorage.SyntacticType.Comment, range: r1, notify:false) ////// targetTextView.textStorage!.addAttribute(NSForegroundColorAttributeName, value: c, range: r1) //// } //// private func unsetColorOnRange(r:URange) { //// let s = targetTextView.textStorage! //// let r1 = s.string.convertRangeToNSRange(r) //// targetTextView.codeTextStorage.setSyntacticType(CodeTextStorage.SyntacticType.None, range: r1, notify:false) //// ////// // Removing attribute takes too long time. Triggers layout. I don't know how to prevent it. ////// // Check before removing it. ////// ////// s.enumerateAttributesInRange(r1, options: NSAttributedStringEnumerationOptions.allZeros) { (map:[NSObject : AnyObject]!, r:NSRange, p:UnsafeMutablePointer<ObjCBool>) -> Void in ////// if contains(map.keys, NSForegroundColorAttributeName) { ////// s.removeAttribute(NSForegroundColorAttributeName, range: r1) ////// p.memory = false ////// } ////// } //// } //} // // // // // // // // // // // // // // // // // // // //private struct TokenScanner { // let separators:[UScalar] // var selectionStart:UIndex? // // unowned var cursor:Cursor // // init(cursor:Cursor, separators:[UScalar]) { // self.cursor = cursor // self.separators = separators // } // // func available() -> Bool { // return cursor.available() && contains(separators, cursor.currentScalar()) == false // } // // /// Returns zero-length range at EOF. // mutating func scan() -> URange { // assert(available()) // // let b = cursor.location // while available() { // cursor.step() // } // let e = cursor.location // return URange(start: b, end: e) // } //} // // // // // // // //private struct EnclosingBlockScanner { // let startMarkerString:String // let endMarkerString:String // // unowned let cursor:Cursor // // init(cursor:Cursor, startMarkerString:String, endMarkerString:String) { // self.cursor = cursor // self.startMarkerString = startMarkerString // self.endMarkerString = endMarkerString // } // // func available() -> Bool { // return cursor.available() && cursor.restString().hasPrefix(startMarkerString) // } // // mutating func scan() -> URange { // assert(available()) // // func skipBy(s:String) { // cursor.location = advance(cursor.location, countElements(s.unicodeScalars)) // } // // let b = cursor.location // skipBy(startMarkerString) // while cursor.available() && cursor.restString().hasPrefix(endMarkerString) == false { // cursor.step() // } // skipBy(endMarkerString) // let e = cursor.location // // return URange(start: b, end: e) // } //} // // // // // // // // // // //private class Cursor { // let targetView:UView // var location:UIndex // // init(targetView:UView) { // self.targetView = targetView // self.location = targetView.startIndex // } // func available() -> Bool { // return location < targetView.endIndex // } // func currentScalar() -> UScalar { // precondition(available()) // return targetView[location] // } // func restView() -> UView { // return targetView[location..<targetView.endIndex] // } // func restString() -> String { // return String(restView()) // } // // func step() { // precondition(location < targetView.endIndex) // location++ // } // //// func pastView() -> UView { //// return targetView[targetView.startIndex..<location] //// } //// func restView() -> UView { //// return targetView[location..<targetView.endIndex] //// } //// //// mutating func stepBackward() { //// precondition(location > targetView.startIndex) //// location-- //// } //} // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // ///// MARK: Utilities // // ////extension unichar: StringLiteralConvertible { //// public init(unicodeScalarLiteral value: String) { //// self.init(stringLiteral: value) //// } //// public init(extendedGraphemeClusterLiteral value: String) { //// self.init(stringLiteral: value) //// } //// public init(stringLiteral value: String) { //// let s1 = value as NSString //// assert(s1.length == 1) //// self = s1.characterAtIndex(0) //// } ////} // //extension String.UnicodeScalarView { // func subviewFromIndex(index:UIndex) -> String.UnicodeScalarView { // return self[index..<self.endIndex] // } // func subviewToIndex(index:UIndex) -> String.UnicodeScalarView { // return self[self.startIndex..<index] // } // func subviewWithRange(range:URange) -> String.UnicodeScalarView { // return self[range] // } // // func hasPrefix(s:String) -> Bool { // return String(self).hasPrefix(s) // } //} // // // // // // // // // // // // // // // // // // // // // // // // // ///// MARK: Data Section // ////private func stringColor() -> NSColor { //// return NSColor.withUInt8Components(red: 196, green: 26, blue: 22, alpha: 255) ////} ////private func attributeColor() -> NSColor { //// return NSColor.withUInt8Components(red: 131, green: 108, blue: 40, alpha: 255) ////} ////private func commentColor() -> NSColor { //// return NSColor.withUInt8Components(red: 0, green: 116, blue: 0, alpha: 255) ////} ////private func keywordColor() -> NSColor { //// return NSColor.withUInt8Components(red: 170, green: 13, blue: 145, alpha: 255) ////} // //private func keywords() -> [String] { // return [ // "abstract", // "alignof", // "as", // "be", // "box", // "break", // "const", // "continue", // "crate", // "do", // "else", // "enum", // "extern", // "false", // "final", // "fn", // "for", // "if", // "impl", // "in", // "let", // "loop", // "match", // "mod", // "move", // "mut", // "offsetof", // "once", // "override", // "priv", // "pub", // "pure", // "ref", // "return", // "sizeof", // "static", // "self", // "struct", // "super", // "true", // "trait", // "type", // "typeof", // "unsafe", // "unsized", // "use", // "virtual", // "where", // "while", // "yield", // ] //} // //private func punctuators() -> [UScalar] { // return ["\n", "\t", " ", ".", ",", ":", ";", "{", "}", "(", ")", "\"", "'", "*", "!", "=", "<", ">", "/", "+", "-", "&", "[", "]", "#", "`"] //} // // // // // //
mit
244c95c15e67c1570f7088943ac21947
21.968397
184
0.629091
2.866197
false
false
false
false
koba-uy/chivia-app-ios
src/Pods/PromiseKit/Extensions/UIKit/Sources/PMKAlertController.swift
12
3773
import UIKit #if !COCOAPODS import PromiseKit #endif //TODO tests //TODO NSCoding /** A “promisable” UIAlertController. UIAlertController is not a suitable API for an extension; it has closure handlers on its main API for each button and an extension would have to either replace all these when the controller is presented or force you to use an extended addAction method, which would be easy to forget part of the time. Hence we provide a facade pattern that can be promised. let alert = PMKAlertController("OHAI") let sup = alert.addActionWithTitle("SUP") let bye = alert.addActionWithTitle("BYE") promiseViewController(alert).then { action in switch action { case is sup: //… case is bye: //… } } */ public class PMKAlertController { /// The title of the alert. public var title: String? { return UIAlertController.title } /// Descriptive text that provides more details about the reason for the alert. public var message: String? { return UIAlertController.message } /// The style of the alert controller. public var preferredStyle: UIAlertControllerStyle { return UIAlertController.preferredStyle } /// The actions that the user can take in response to the alert or action sheet. public var actions: [UIAlertAction] { return UIAlertController.actions } /// The array of text fields displayed by the alert. public var textFields: [UITextField]? { return UIAlertController.textFields } #if !os(tvOS) /// The nearest popover presentation controller that is managing the current view controller. public var popoverPresentationController: UIPopoverPresentationController? { return UIAlertController.popoverPresentationController } #endif /// Creates and returns a view controller for displaying an alert to the user. public required init(title: String?, message: String? = nil, preferredStyle: UIAlertControllerStyle = .alert) { UIAlertController = UIKit.UIAlertController(title: title, message: message, preferredStyle: preferredStyle) } /// Attaches an action title to the alert or action sheet. public func addActionWithTitle(title: String, style: UIAlertActionStyle = .default) -> UIAlertAction { let action = UIAlertAction(title: title, style: style) { action in if style != .cancel { self.fulfill(action) } else { self.reject(Error.cancelled) } } UIAlertController.addAction(action) return action } /// Adds a text field to an alert. public func addTextFieldWithConfigurationHandler(configurationHandler: ((UITextField) -> Void)?) { UIAlertController.addTextField(configurationHandler: configurationHandler) } fileprivate let UIAlertController: UIKit.UIAlertController fileprivate let (promise, fulfill, reject) = Promise<UIAlertAction>.pending() fileprivate var retainCycle: PMKAlertController? /// Errors that represent PMKAlertController failures public enum Error: CancellableError { /// The user cancelled the PMKAlertController. case cancelled /// - Returns: true public var isCancelled: Bool { return self == .cancelled } } } extension UIViewController { /// Presents the PMKAlertController, resolving with the user action. public func promise(_ vc: PMKAlertController, animated: Bool = true, completion: (() -> Void)? = nil) -> Promise<UIAlertAction> { vc.retainCycle = vc present(vc.UIAlertController, animated: animated, completion: completion) _ = vc.promise.always { vc.retainCycle = nil } return vc.promise } }
lgpl-3.0
86a270cba27cd05a27d6d91ba31ddc9a
38.21875
137
0.694555
5.200276
false
false
false
false
klundberg/swift-corelibs-foundation
TestFoundation/TestNSRunLoop.swift
1
3914
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSRunLoop : XCTestCase { static var allTests : [(String, (TestNSRunLoop) -> () throws -> Void)] { return [ ("test_constants", test_constants), ("test_runLoopInit", test_runLoopInit), // these tests do not work the same as Darwin https://bugs.swift.org/browse/SR-399 // ("test_runLoopRunMode", test_runLoopRunMode), // ("test_runLoopLimitDate", test_runLoopLimitDate), ] } func test_constants() { XCTAssertEqual(RunLoopMode.commonModes.rawValue, "kCFRunLoopCommonModes", "\(RunLoopMode.commonModes.rawValue) is not equal to kCFRunLoopCommonModes") XCTAssertEqual(RunLoopMode.defaultRunLoopMode.rawValue, "kCFRunLoopDefaultMode", "\(RunLoopMode.defaultRunLoopMode.rawValue) is not equal to kCFRunLoopDefaultMode") } func test_runLoopInit() { let mainRunLoop = RunLoop.main() XCTAssertNotNil(mainRunLoop) let currentRunLoop = RunLoop.current() XCTAssertNotNil(currentRunLoop) let secondAccessOfMainLoop = RunLoop.main() XCTAssertEqual(mainRunLoop, secondAccessOfMainLoop, "fetching the main loop a second time should be equal") XCTAssertTrue(mainRunLoop === secondAccessOfMainLoop, "fetching the main loop a second time should be identical") let secondAccessOfCurrentLoop = RunLoop.current() XCTAssertEqual(currentRunLoop, secondAccessOfCurrentLoop, "fetching the current loop a second time should be equal") XCTAssertTrue(currentRunLoop === secondAccessOfCurrentLoop, "fetching the current loop a second time should be identical") // We can assume that the tests will be run on the main run loop // so the current loop should be the main loop XCTAssertEqual(mainRunLoop, currentRunLoop, "the current run loop should be the main loop") } func test_runLoopRunMode() { let runLoop = RunLoop.current() let timeInterval = TimeInterval(0.05) let endDate = Date(timeInterval: timeInterval, since: Date()) var flag = false let dummyTimer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: false) { _ in flag = true guard let runLoopMode = runLoop.currentMode else { XCTFail("Run loop mode is not defined") return } XCTAssertEqual(runLoopMode, RunLoopMode.defaultRunLoopMode) } runLoop.add(dummyTimer, forMode: .defaultRunLoopMode) let result = runLoop.run(mode: .defaultRunLoopMode, before: endDate) XCTAssertFalse(result) // should be .Finished XCTAssertTrue(flag) } func test_runLoopLimitDate() { let runLoop = RunLoop.current() let timeInterval = TimeInterval(1) let expectedTimeInterval = Date(timeInterval: timeInterval, since: Date()).timeIntervalSince1970 let dummyTimer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false) { _ in } runLoop.add(dummyTimer, forMode: .defaultRunLoopMode) guard let timerTickInterval = runLoop.limitDate(forMode: .defaultRunLoopMode)?.timeIntervalSince1970 else { return } XCTAssertLessThan(abs(timerTickInterval - expectedTimeInterval), 0.01) } }
apache-2.0
95136858dfd785bf117ac06161b093f8
41.086022
130
0.665304
5.163588
false
true
false
false
tiagomartinho/webhose-cocoa
webhose-cocoa/Pods/Nimble/Sources/Nimble/Matchers/BeCloseTo.swift
36
5050
import Foundation internal let DefaultDelta = 0.0001 internal func isCloseTo(_ actualValue: NMBDoubleConvertible?, expectedValue: NMBDoubleConvertible, delta: Double, failureMessage: FailureMessage) -> Bool { failureMessage.postfixMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))" failureMessage.actualValue = "<\(stringify(actualValue))>" return actualValue != nil && abs(actualValue!.doubleValue - expectedValue.doubleValue) < delta } /// A Nimble matcher that succeeds when a value is close to another. This is used for floating /// point values which can have imprecise results when doing arithmetic on them. /// /// @see equal public func beCloseTo(_ expectedValue: Double, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<Double> { return NonNilMatcherFunc { actualExpression, failureMessage in return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage) } } /// A Nimble matcher that succeeds when a value is close to another. This is used for floating /// point values which can have imprecise results when doing arithmetic on them. /// /// @see equal public func beCloseTo(_ expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> NonNilMatcherFunc<NMBDoubleConvertible> { return NonNilMatcherFunc { actualExpression, failureMessage in return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta, failureMessage: failureMessage) } } #if _runtime(_ObjC) public class NMBObjCBeCloseToMatcher: NSObject, NMBMatcher { var _expected: NSNumber var _delta: CDouble init(expected: NSNumber, within: CDouble) { _expected = expected _delta = within } public func matches(_ actualExpression: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let actualBlock: () -> NMBDoubleConvertible? = ({ return actualExpression() as? NMBDoubleConvertible }) let expr = Expression(expression: actualBlock, location: location) let matcher = beCloseTo(self._expected, within: self._delta) return try! matcher.matches(expr, failureMessage: failureMessage) } public func doesNotMatch(_ actualExpression: @escaping () -> NSObject!, failureMessage: FailureMessage, location: SourceLocation) -> Bool { let actualBlock: () -> NMBDoubleConvertible? = ({ return actualExpression() as? NMBDoubleConvertible }) let expr = Expression(expression: actualBlock, location: location) let matcher = beCloseTo(self._expected, within: self._delta) return try! matcher.doesNotMatch(expr, failureMessage: failureMessage) } public var within: (CDouble) -> NMBObjCBeCloseToMatcher { return ({ delta in return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta) }) } } extension NMBObjCMatcher { public class func beCloseToMatcher(_ expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher { return NMBObjCBeCloseToMatcher(expected: expected, within: within) } } #endif public func beCloseTo(_ expectedValues: [Double], within delta: Double = DefaultDelta) -> NonNilMatcherFunc <[Double]> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))" if let actual = try actualExpression.evaluate() { failureMessage.actualValue = "<\(stringify(actual))>" if actual.count != expectedValues.count { return false } else { for (index, actualItem) in actual.enumerated() { if fabs(actualItem - expectedValues[index]) > delta { return false } } return true } } return false } } // MARK: - Operators infix operator ≈ : ComparisonPrecedence public func ≈(lhs: Expectation<[Double]>, rhs: [Double]) { lhs.to(beCloseTo(rhs)) } public func ≈(lhs: Expectation<NMBDoubleConvertible>, rhs: NMBDoubleConvertible) { lhs.to(beCloseTo(rhs)) } public func ≈(lhs: Expectation<NMBDoubleConvertible>, rhs: (expected: NMBDoubleConvertible, delta: Double)) { lhs.to(beCloseTo(rhs.expected, within: rhs.delta)) } public func == (lhs: Expectation<NMBDoubleConvertible>, rhs: (expected: NMBDoubleConvertible, delta: Double)) { lhs.to(beCloseTo(rhs.expected, within: rhs.delta)) } // make this higher precedence than exponents so the Doubles either end aren't pulled in // unexpectantly precedencegroup PlusMinusOperatorPrecedence { higherThan: BitwiseShiftPrecedence } infix operator ± : PlusMinusOperatorPrecedence public func ±(lhs: NMBDoubleConvertible, rhs: Double) -> (expected: NMBDoubleConvertible, delta: Double) { return (expected: lhs, delta: rhs) }
mit
08e21c9c7c01670e23642ec5cd63b36b
40.311475
155
0.698413
5.02994
false
false
false
false
voytovichs/seventh-dimension-scrobbler
Seventh Dimension Scrobbler/LastfmRequestScheduler.swift
1
1122
// // Created by Sergey Voytovich on 17.07.16. // Copyright (c) 2016 voytovichs. All rights reserved. // import Foundation /** * * This class aim to handle timing * http://www.last.fm/api/scrobbling#when-is-a-scrobble-a-scrobble * **/ class LastfmRequestScheduler { private var state: State = State.NONE private let lock = Lock() func scheduleScrobbling(song: Song, scrobbleAction: () -> Bool) { withLock(lock, blk: { while (self.state == State.PENDING) { self.cancelPending() } self.state = State.PENDING self.waitUntilScrobbled(song) scrobbleAction() self.state = State.NONE }) } private func cancelPending() { } private func waitUntilScrobbled(song: Song) { } func songPaused(song: Song) { } private func withLock(obj: AnyObject, blk: () -> ()) { objc_sync_enter(obj) blk() objc_sync_exit(obj) } enum State { case PENDING case NONE } private class Lock { //Just an empty class } }
mit
f05c811e98a01dec658e7c3680194fac
17.393443
69
0.565954
3.715232
false
false
false
false
aahmedae/blitz-news-ios
Blitz News/Model/CoreDataManager.swift
1
3869
// // CoreDataManager.swift // Blitz News // // Created by Asad Ahmed on 5/20/17. // Core data class responsible for handling CRUD operations for this application // import CoreData class CoreDataManager { // MARK:- Properties // Singleton static let sharedInstance = CoreDataManager() private init() {} // MARK:- Public Functions // Creates or returns an existing news source for the given source ID and attributes func createOrGetNewsSource(sourceID: String, description: String, name: String, categoryID: String) -> NewsSource? { let context = CoreDataStack.sharedInstance.managedObjectContext let request = NSFetchRequest<NewsSource>(entityName: "NewsSource") request.predicate = NSPredicate(format: "sourceID = %@", sourceID) do { if let results = try? context.fetch(request) { if let source = results.first { return source } else { // this is a new news source being added to the DB let newSource = NSEntityDescription.insertNewObject(forEntityName: "NewsSource", into: context) as! NewsSource newSource.sourceID = sourceID newSource.sourceDescription = description newSource.sourceName = name newSource.categoryID = categoryID newSource.userSelected = false return newSource } } } return nil } // Returns a list of news sources with an option for only returning sources the user has selected func getNewsSources(userSelectedSources: Bool) -> [NewsSource] { // set optional predicate to fetch the news sources the user has selected var predicate: NSPredicate? = nil if userSelectedSources { predicate = NSPredicate(format: "userSelected = %@", NSNumber(booleanLiteral: true)) } let sources: [NewsSource] = fetchEntity(name: "NewsSource", predicate: predicate) return sources } // Returns the news source for the given ID func getNewsSourceForID(_ sourceID: String) -> NewsSource? { let context = CoreDataStack.sharedInstance.managedObjectContext let predicate = NSPredicate(format: "sourceID = %@", sourceID) let request = NSFetchRequest<NewsSource>(entityName: "NewsSource") request.predicate = predicate do { if let results = try? context.fetch(request) { if let source = results.first { return source } } } return nil } // Delete the given news source if it exists func deleteNewsSource(sourceID: String) { if let source = getNewsSourceForID(sourceID) { CoreDataStack.sharedInstance.managedObjectContext.delete(source) save() } } // Save changes to context func save() { CoreDataStack.sharedInstance.saveContext() } // MARK:- Private Functions // Returns a list of the given entity from the context fileprivate func fetchEntity<T: NSFetchRequestResult>(name: String, predicate: NSPredicate? = nil) -> [T] { let context = CoreDataStack.sharedInstance.managedObjectContext let request = NSFetchRequest<T>(entityName: name) request.predicate = predicate do { if let results = try? context.fetch(request) { return results } return [T]() } } }
mit
91e5678460770fcb5b862224d010fc32
30.201613
130
0.569398
5.623547
false
false
false
false
jfrowies/iEMI
iEMI/SettingsViewController.swift
1
1910
// // SettingsViewController.swift // iEMI // // Created by Fer Rowies on 2/19/15. // Copyright (c) 2015 Rowies. All rights reserved. // import UIKit class SettingsViewController: UITableViewController { @IBOutlet weak var licensePlateLabel: UILabel! @IBOutlet weak var appVersionLabel: UILabel! @IBOutlet weak var appBuildLabel: UILabel! @IBOutlet weak var autoLoginSwitch: UISwitch! @IBOutlet weak var logoutButton: UIButton! // MARK: - View controller life cycle private let kAppVersionKey:String = "CFBundleShortVersionString" private let kAppBuildKey:String = "CFBundleVersion" let licensePlateSotrage = LicensePlate() let settings = Settings() override func viewDidLoad() { super.viewDidLoad() if let appVersion = NSBundle.mainBundle().infoDictionary?[kAppVersionKey] as? String { self.appVersionLabel.text = appVersion } if let appBuild = NSBundle.mainBundle().infoDictionary?[kAppBuildKey] as? String { self.appBuildLabel.text = "(\(appBuild))" } if let currentLicensePlate = licensePlateSotrage.currentLicensePlate { self.licensePlateLabel.text = currentLicensePlate } self.autoLoginSwitch.on = settings.autoLogin } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - IBActions @IBAction func logoutButtonTouched(sender: AnyObject) { licensePlateSotrage.currentLicensePlate = nil self.settings.autoLogin = true self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } @IBAction func autoLoginSwitchChanged(sender: UISwitch) { self.settings.autoLogin = sender.on } }
apache-2.0
8bec219606d39755ed52961ecd637f62
27.939394
94
0.665969
5.039578
false
false
false
false
twostraws/HackingWithSwift
Classic/project30-files/Project30/AppDelegate.swift
1
2245
// // AppDelegate.swift // Project30 // // Created by TwoStraws on 20/08/2016. // Copyright (c) 2016 TwoStraws. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let vc = SelectionViewController(style: .plain) let nc = UINavigationController(rootViewController: vc) window?.rootViewController = nc window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
unlicense
9132ed264c5212452e121af8b58897a4
43.9
279
0.781737
4.944934
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Drawers/ChartLineDrawer.swift
4
702
// // ChartLineDrawer.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit class ChartLineDrawer: ChartContextDrawer { fileprivate let p1: CGPoint fileprivate let p2: CGPoint fileprivate let color: UIColor fileprivate let strokeWidth: CGFloat init(p1: CGPoint, p2: CGPoint, color: UIColor, strokeWidth: CGFloat = 0.2) { self.p1 = p1 self.p2 = p2 self.color = color self.strokeWidth = strokeWidth } override func draw(context: CGContext, chart: Chart) { ChartDrawLine(context: context, p1: p1, p2: p2, width: strokeWidth, color: color) } }
apache-2.0
41aacbbb13df25b669edab1e85fd0770
25
89
0.660969
3.754011
false
false
false
false
gravicle/library
Sources/UIStackView+Configuration.swift
1
2624
import UIKit // MARK: - Layout public extension UIStackView { public struct Layout { public var axis: UILayoutConstraintAxis public var distribution: UIStackViewDistribution public var alignment: UIStackViewAlignment public init( axis: UILayoutConstraintAxis = .vertical, distribution: UIStackViewDistribution = .equalSpacing, alignment: UIStackViewAlignment = .fill) { self.axis = axis self.distribution = distribution self.alignment = alignment } } } // MARK: Layouts public extension UIStackView.Layout { public static let verticalGrid = UIStackView.Layout( axis: .vertical, distribution: .fillEqually, alignment: .fill ) public static let horizontalGrid = UIStackView.Layout( axis: .horizontal, distribution: .fillEqually, alignment: .fill ) } // MARK: - Packing public extension UIStackView { public struct Packing { public var insets: UIEdgeInsets public var interspacing: CGFloat public var isLayoutMarginsRelativeArrangement: Bool public init( insets: UIEdgeInsets = UIEdgeInsets.zero, interspacing: CGFloat = 0, isLayoutMarginsRelativeArrangement: Bool = true) { self.insets = insets self.interspacing = interspacing self.isLayoutMarginsRelativeArrangement = isLayoutMarginsRelativeArrangement } } } // MARK: - UIStackView + Configuration public extension UIStackView { public var layout: Layout { get { return Layout(axis: axis, distribution: distribution, alignment: alignment) } set { apply(newValue) } } public var packing: Packing { get { return Packing(insets: layoutMargins, interspacing: self.spacing, isLayoutMarginsRelativeArrangement: isLayoutMarginsRelativeArrangement) } set { apply(newValue) } } public convenience init(arrangedSubviews: [UIView] = [], layout: Layout, packing: Packing = .init()) { self.init(arrangedSubviews: arrangedSubviews) self.apply(layout) self.apply(packing) } } private extension UIStackView { func apply(_ layout: Layout) { axis = layout.axis alignment = layout.alignment distribution = layout.distribution } func apply(_ packing: Packing) { self.spacing = packing.interspacing layoutMargins = packing.insets isLayoutMarginsRelativeArrangement = packing.isLayoutMarginsRelativeArrangement } }
mit
0c1f9528857c2e8b50543148aa2b8b4d
24.475728
153
0.653201
5.290323
false
false
false
false
raphaelmor/GeoJSON
GeoJSON/Feature.swift
1
4067
// Feature.swift // // The MIT License (MIT) // // Copyright (c) 2014 Raphaël Mor // // 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 public final class Feature : GeoJSONEncodable { /// Public geometry public var geometry: GeoJSON? { return _geometry } /// Public identifier public var identifier: String? { return _identifier } /// Public properties public var properties: JSON { return _properties } /// Prefix used for GeoJSON Encoding public var prefix: String { return "" } /// Private geometry private var _geometry: GeoJSON? = nil /// Private properties private var _properties: JSON /// Private identifier public var _identifier: String? /** Designated initializer for creating a Feature from a SwiftyJSON object :param: json The SwiftyJSON Object. :returns: The created Feature object. */ public init?(json: JSON) { _properties = json["properties"] if _properties.error != nil { return nil } let jsonGeometry = json["geometry"] if jsonGeometry.error != nil { return nil } if let _ = jsonGeometry.null { _geometry = nil } else { _geometry = GeoJSON(json: jsonGeometry) if _geometry?.error != nil { return nil } if _geometry?.isGeometry() == false { return nil } } let jsonIdentifier = json["id"] _identifier = jsonIdentifier.string } /** Designated initializer for creating a Feature from a objects :param: coordinates The coordinate array. :returns: The created Point object. */ public init?(geometry: GeoJSON? = nil, properties: JSON? = nil, identifier: String? = nil) { if let _ = properties { _properties = properties! if properties!.error != nil { return nil } } else { _properties = JSON.nullJSON } _geometry = geometry if _geometry?.error != nil { return nil } if _geometry?.isGeometry() == false { return nil } _identifier = identifier } /** Returns an object that can be serialized to JSON :returns: Representation of the Feature Object */ public func json() -> AnyObject { var geometryJSON : AnyObject = self.geometry?.json() ?? NSNull() var resultDict = [ "type" : "Feature", "properties" : self.properties.object, "geometry" : geometryJSON, ] if let id = _identifier { resultDict["id"] = identifier } return resultDict } } public extension GeoJSON { /// Optional Feature public var feature: Feature? { get { switch type { case .Feature: return object as? Feature default: return nil } } set { _object = newValue ?? NSNull() } } /** Convenience initializer for creating a GeoJSON Object from a Feature :param: feature The Feature object. :returns: The created GeoJSON object. */ convenience public init(feature: Feature) { self.init() object = feature } }
mit
13daff365d8136d36e5f7ff450f8d9d1
26.47973
93
0.655681
4.302646
false
false
false
false
tapglue/ios_sample
TapglueSample/PostVC.swift
1
12078
// // PostVC.swift // TapglueSample // // Created by Özgür Celebi on 17/12/15. // Copyright © 2015 Özgür Celebi. All rights reserved. // import UIKit import Tapglue import WSTagsField import AWSS3 class PostVC: UIViewController, UINavigationControllerDelegate { let appDel = UIApplication.sharedApplication().delegate! as! AppDelegate @IBOutlet weak var visibilitySegmentedControl: UISegmentedControl! @IBOutlet weak var postTextField: UITextField! @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var postUIBarButton: UIBarButtonItem! @IBOutlet weak var postImageView: UIImageView! @IBOutlet weak var cameraButton: UIButton! let imagePicker = UIImagePickerController() var postText: String? var tagArr: [String] = [] var postBeginEditing = false var tempPost: Post! @IBOutlet weak var wsTagsFieldView: UIView! let tagsField = WSTagsField() var selectedImageUrl: NSURL! var localFileName: String? var imageURL = NSURL() var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock? var progressBlock: AWSS3TransferUtilityProgressBlock? var latestUUID: String? override func viewDidLoad() { super.viewDidLoad() // Enable postUIBarButton postUIBarButton.enabled = false postTextField.becomeFirstResponder() addWSTagsField() if let profileImages = appDel.rxTapglue.currentUser?.images { self.userImageView.kf_setImageWithURL(NSURL(string: profileImages["profile"]!.url!)!) } // Prepare edit old post if postBeginEditing { postTextField.text = tempPost.attachments![0].contents!["en"] switch tempPost.visibility!.rawValue { case 10: visibilitySegmentedControl.selectedSegmentIndex = 0 case 20: visibilitySegmentedControl.selectedSegmentIndex = 1 case 30: visibilitySegmentedControl.selectedSegmentIndex = 2 default: print("default") } if let tags = tempPost.tags { tagsField.addTags(tags) } } // Listener imagePicker.delegate = self } @IBAction func cameraButtonPressed(sender: UIButton) { imagePicker.allowsEditing = false imagePicker.sourceType = .PhotoLibrary presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func postButtonPressed(sender: UIBarButtonItem) { if postText?.characters.count > 2 { if tagsField.tags.count != 0 { for tag in tagsField.tags { tagArr.append(tag.text) } } if postBeginEditing { let attachment = Attachment(contents: ["en":postText!], name: "status", type: .Text) tempPost.tags = tagArr tempPost.attachments = [attachment] switch visibilitySegmentedControl.selectedSegmentIndex { case 0: tempPost.visibility = Visibility.Private case 1: tempPost.visibility = Visibility.Connections case 2: tempPost.visibility = Visibility.Public default: "More options then expected" } // Update edited post appDel.rxTapglue.updatePost(tempPost.id!, post: tempPost).subscribe({ (event) in switch event { case .Next( _): print("Next") case .Error(let error): self.appDel.printOutErrorMessageAndCode(error as? TapglueError) case .Completed: break } }).addDisposableTo(self.appDel.disposeBag) } else { var attachments: [Attachment] = [] if postImageView.image != nil { let postImageURL = "public/" + latestUUID! + ".jpeg" attachments.append(Attachment(contents: ["en":postText!], name: "status", type: .Text)) attachments.append(Attachment(contents: ["en":postImageURL], name: "image", type: .URL)) } else { attachments.append(Attachment(contents: ["en":postText!], name: "status", type: .Text)) } let post = Post(visibility: .Connections, attachments: attachments) post.tags = tagArr switch visibilitySegmentedControl.selectedSegmentIndex { case 0: post.visibility = Visibility.Private case 1: post.visibility = Visibility.Connections case 2: post.visibility = Visibility.Public default: "More options then expected" } // Create new post appDel.rxTapglue.createPost(post).subscribe({ (event) in switch event { case .Next( _): print("Next") case .Error(let error): self.appDel.printOutErrorMessageAndCode(error as? TapglueError) case .Completed: break } }).addDisposableTo(self.appDel.disposeBag) } resignKeyboardAndDismissVC() } else { showAlert() } } @IBAction func dismissVC(sender: AnyObject) { resignKeyboardAndDismissVC() } func resignKeyboardAndDismissVC(){ postTextField.resignFirstResponder() self.dismissViewControllerAnimated(true, completion: nil) } func showAlert() { let alertController = UIAlertController(title: "Post Error", message: "You can not post empty or less then two characters of text.", preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true) { } } func addWSTagsField() { tagsField.placeholder = "Add hashtags to your post" tagsField.font = UIFont(name:"HelveticaNeue-Light", size: 14.0) tagsField.tintColor = UIColor(red:0.18, green:0.28, blue:0.3, alpha:1.0) tagsField.textColor = .whiteColor() tagsField.selectedColor = .lightGrayColor() tagsField.selectedTextColor = .whiteColor() tagsField.spaceBetweenTags = 4.0 tagsField.padding.left = 0 tagsField.padding.top = wsTagsFieldView.frame.height/8 tagsField.frame = CGRect(x: 0, y: 0, width: wsTagsFieldView.frame.width, height: wsTagsFieldView.frame.height) wsTagsFieldView.addSubview(tagsField) } } extension PostVC: UITextFieldDelegate { // Mark: - TextField func textFieldShouldReturn(textField: UITextField) -> Bool { let textFieldText = textField.text postText = textFieldText! textField.resignFirstResponder() return false } // If textField has more then 3 characters enable posUIBarbutton func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if range.location >= 3 { postUIBarButton.enabled = true postText = textField.text } else { postUIBarButton.enabled = false } // Keep it true return true } } extension PostVC: UIImagePickerControllerDelegate { // MARK: - UIImagePicker func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { // If you like to change the aspect programmatically // myImageView.contentMode = .ScaleAspectFit postImageView.image = pickedImage cameraButton.setImage(nil, forState: .Normal) //getting details of image let uploadFileURL = info[UIImagePickerControllerReferenceURL] as! NSURL let imageName = uploadFileURL.lastPathComponent let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String // getting local path let localPath = (documentDirectory as NSString).stringByAppendingPathComponent(imageName!) //getting actual image let originalImg = info[UIImagePickerControllerOriginalImage] as! UIImage let size = CGSizeApplyAffineTransform(originalImg.size, CGAffineTransformMakeScale(0.4, 0.4)) let resizedImg = scaleImageToSize(originalImg, size: size) let data = UIImageJPEGRepresentation(resizedImg, 0.6) data!.writeToFile(localPath, atomically: true) let imageData = NSData(contentsOfFile: localPath)! imageURL = NSURL(fileURLWithPath: localPath) uploadData(imageData) picker.dismissViewControllerAnimated(true, completion: nil) } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func uploadData(data: NSData) { //defining bucket and upload file name latestUUID = NSUUID().UUIDString let S3UploadKeyName: String = "public/" + latestUUID! + ".jpeg" let S3BucketName: String = "tapglue-sample" let expression = AWSS3TransferUtilityUploadExpression() expression.progressBlock = progressBlock let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility() transferUtility.uploadData( data, bucket: S3BucketName, key: S3UploadKeyName, contentType: "image/jpg", expression: expression, completionHander: completionHandler).continueWithBlock { (task) -> AnyObject! in if let error = task.error { print("Error: %@",error.localizedDescription) } if let exception = task.exception { print("Exception: %@",exception.description) } if let _ = task.result { print("Upload Starting!") expression.progressBlock = { (task: AWSS3TransferUtilityTask, progress: NSProgress) in dispatch_async(dispatch_get_main_queue(), { print(Float(progress.fractionCompleted)) }) } } if task.completed { print("UPLOAD COMPLETED") } if task.cancelled { print("UPLOAD CANCELLED") } return nil } } func scaleImageToSize(img: UIImage, size: CGSize) -> UIImage { UIGraphicsBeginImageContext(size) img.drawInRect(CGRect(origin: CGPointZero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } }
apache-2.0
98814ba27bd045871a9dfc76194bad54
35.038806
164
0.566388
5.762768
false
false
false
false
lazersly/ImageFilterz
ImageFilterz/FilterService.swift
1
1436
// // FilterService.swift // ImageFilterz // // Created by Brandon Roberts on 4/6/15. // Copyright (c) 2015 BR World. All rights reserved. // import UIKit import CoreImage class FilterService { private var context : CIContext init() { let contextOptions = [kCIContextWorkingColorSpace: NSNull()] let eglContext = EAGLContext(API: EAGLRenderingAPI.OpenGLES2) self.context = CIContext(EAGLContext: eglContext, options: contextOptions) } func sepia(originalImage : UIImage) -> UIImage? { let sepia = CIFilter(name: "CISepiaTone") return self.imageUsingFilter(originalImage, filter: sepia) } func gaussianBlur(originalImage : UIImage) -> UIImage? { let gaussian = CIFilter(name: "CIGaussianBlur") return self.imageUsingFilter(originalImage, filter: gaussian) } func crystallize(originalImage : UIImage) -> UIImage? { let crystallize = CIFilter(name: "CICrystallize") return self.imageUsingFilter(originalImage, filter: crystallize) } private func imageUsingFilter(originalImage: UIImage, filter: CIFilter) -> UIImage? { let newCIImage = CIImage(image: originalImage) filter.setValue(newCIImage, forKey: kCIInputImageKey) let filteredImageRef = filter.valueForKey(kCIOutputImageKey) as! CIImage let newCGImage = self.context.createCGImage(filteredImageRef, fromRect: filteredImageRef.extent()) return UIImage(CGImage: newCGImage) } }
mit
197be69d7cee033db80a30cfa2f56402
30.911111
102
0.730501
4.079545
false
false
false
false
Legoless/Alpha
Demo/UIKitCatalog/CollectionViewContainerViewController.swift
1
2908
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A `UICollectionViewController` who's cells each contain a `UICollectionView`. This class demonstrates how to ensure focus behaves correctly in this situation. */ import UIKit class CollectionViewContainerViewController: UICollectionViewController { // MARK: Properties private static let minimumEdgePadding = CGFloat(90.0) private let dataItemsByGroup: [[DataItem]] = { return DataItem.Group.allGroups.map { group in return DataItem.sampleItems.filter { $0.group == group } } }() // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Make sure their is sufficient padding above and below the content. guard let collectionView = collectionView, let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return } collectionView.contentInset.top = CollectionViewContainerViewController.minimumEdgePadding - layout.sectionInset.top collectionView.contentInset.bottom = CollectionViewContainerViewController.minimumEdgePadding - layout.sectionInset.bottom } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // Our collection view displays 1 section per group of items. return dataItemsByGroup.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // Each section contains a single `CollectionViewContainerCell`. return 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // Dequeue a cell from the collection view. return collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewContainerCell.reuseIdentifier, for: indexPath) } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? CollectionViewContainerCell else { fatalError("Expected to display a `CollectionViewContainerCell`.") } // Configure the cell. let sectionDataItems = dataItemsByGroup[indexPath.section] cell.configure(with: sectionDataItems) } override func collectionView(_ collectionView: UICollectionView, canFocusItemAt indexPath: IndexPath) -> Bool { /* Return `false` because we don't want this `collectionView`'s cells to become focused. Instead the `UICollectionView` contained in the cell should become focused. */ return false } }
mit
fa43b5a8881dab7b6f0b3e5d9dd8d832
41.115942
162
0.715072
5.967146
false
false
false
false
taketin/KINNOSUKE-Agent
KINNOSUKE-Agent/Config.swift
1
335
// // Config.swift // KINNOSUKE-Agent // // Created by Takeshita Hidenori on 2016/02/12. // Copyright © 2016年 taketin. All rights reserved. // import Foundation let AppName = "KINNOSUKE-Agent" let SCHEME = "https://" let URL_4628 = "www.4628.jp" let URL_E4628 = "www.e4628.jp" let PATROL_INTERVAL_SEC: TimeInterval = 60 * 120
mit
527a0afa9ead3d45b7230c5f6c5b5c8c
21.133333
51
0.692771
2.59375
false
true
false
false
amujic5/AFEA
AFEA-EndProject/AFEA-EndProject/List/ListToDetailsSegue.swift
1
7142
// // ListToDetailsSegue.swift // AFEA-EndProject // // Created by Azzaro Mujic on 27/09/2017. // Copyright © 2017 Azzaro Mujic. All rights reserved. // import UIKit class ListToDetailsSegue: UIStoryboardSegue { override func perform() { let listViewController = source as! ListViewController let detailsViewController = destination as! DetailsViewController listViewController.navigationController?.delegate = self listViewController.navigationController?.pushViewController(detailsViewController, animated: true) } } // MARK: UINavigationControllerDelegate extension ListToDetailsSegue: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { return self } } // MARK: UIViewControllerAnimatedTransitioning extension ListToDetailsSegue: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let listViewController: ListViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! ListViewController let detailsViewController: DetailsViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! DetailsViewController let containerView = transitionContext.containerView containerView.addSubview(detailsViewController.view) detailsViewController.view.alpha = 0 let selectedCell = listViewController.collectionView.cellForItem(at: listViewController.lastSelectedIndexPath) as! ListItemCollectionViewCell let selectedImageView = selectedCell.imageView let selectedLabel = selectedCell.titleLabel let selectedCircleView = selectedCell.circleView let circleCopyView = UIView() circleCopyView.backgroundColor = UIColor.clear circleCopyView.layer.cornerRadius = selectedCircleView!.layer.cornerRadius circleCopyView.layer.borderWidth = selectedCircleView!.layer.borderWidth circleCopyView.layer.borderColor = selectedCircleView!.layer.borderColor containerView.addSubview(circleCopyView) circleCopyView.frame = (selectedCell.circleView.superview?.convert(selectedCell.circleView.frame, to: containerView))! let selectedLabelFromFrame = selectedLabel!.frame let selectedImageViewFromFrame = selectedImageView!.frame let selectedLabelFromFont = selectedLabel?.font listViewController.collectionView.visibleCells.forEach({ (cell) in let listItemCell = cell as! ListItemCollectionViewCell if selectedCell != listItemCell { listItemCell.animatedCircleView.animateCircle(duration: 0.25, percentage: 1) } }) let centerPoint = selectedImageView!.center selectedImageView?.frame.size.width = min(selectedImageView!.image!.size.width, selectedImageView!.frame.size.width) selectedImageView?.frame.size.height = min(selectedImageView!.image!.size.height, selectedImageView!.frame.size.height) if selectedImageView!.image!.size.width > selectedImageView!.image!.size.height { selectedImageView?.frame.size.height = selectedImageView!.frame.size.width * (selectedImageView!.image!.size.height / selectedImageView!.image!.size.width) } else { selectedImageView?.frame.size.width = selectedImageView!.frame.size.height * (selectedImageView!.image!.size.width / selectedImageView!.image!.size.height) } selectedImageView?.contentMode = .scaleAspectFill selectedImageView?.center = centerPoint DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { listViewController.collectionView.visibleCells.forEach({ (cell) in let listItemCell = cell as! ListItemCollectionViewCell listItemCell.animatedCircleView.isHidden = true listItemCell.circleView.isHidden = true }) } DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { selectedLabel?.animateToFont(detailsViewController.titleLabel.font, withDuration: 0.45) } UIView.animate(withDuration: 0.45, delay: 0.3, options: .curveEaseInOut, animations: { listViewController.collectionView.visibleCells.forEach({ (cell) in let listItemCell = cell as! ListItemCollectionViewCell if selectedCell != listItemCell { listItemCell.alpha = 0 listItemCell.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) } }) selectedImageView?.frame = (detailsViewController.imageView.superview?.convert(detailsViewController.imageView.frame, to: selectedImageView?.superview))! selectedLabel?.center = (detailsViewController.titleLabel.superview?.convert(detailsViewController.titleLabel.center, to: selectedLabel?.superview))! circleCopyView.frame = (detailsViewController.bigCircleView.superview?.convert(detailsViewController.bigCircleView.frame, to: containerView))! circleCopyView.layer.cornerRadius = circleCopyView.frame.width/2 circleCopyView.layer.borderColor = UIColor.darkGrey.cgColor }) { (_) in UIView.animate(withDuration: 0.4, animations: { circleCopyView.alpha = 0 circleCopyView.layer.borderColor = UIColor.coolGrey.cgColor }, completion: { (_) in circleCopyView.removeFromSuperview() }) selectedImageView?.frame = detailsViewController.imageView.frame transitionContext.completeTransition(!transitionContext.transitionWasCancelled) detailsViewController.updateView() detailsViewController.view.alpha = 1 listViewController.collectionView.visibleCells.forEach({ (cell) in let listItemCell = cell as! ListItemCollectionViewCell listItemCell.transform = .identity listItemCell.alpha = 1 listItemCell.animatedCircleView.isHidden = false listItemCell.animatedCircleView.setPercentage(0) listItemCell.circleView.isHidden = false selectedLabel?.frame = selectedLabelFromFrame selectedImageView?.frame = selectedImageViewFromFrame selectedImageView?.contentMode = .scaleAspectFit selectedLabel?.font = selectedLabelFromFont selectedLabel?.transform = .identity }) } } }
mit
04f27957043567e245ad71e8693f72fb
48.248276
246
0.69108
6.056828
false
false
false
false
ta2yak/loqui
Pods/SwiftIconFont/SwiftIconFont/Classes/FontLoader.swift
1
1584
// // FontLoader.swift // SwiftIconFont // // Created by Sedat Ciftci on 18/03/16. // Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved. // import UIKit import Foundation import CoreText class FontLoader: NSObject { class func loadFont(_ fontName: String) { let bundle = Bundle(for: FontLoader.self) let paths = bundle.paths(forResourcesOfType: "ttf", inDirectory: nil) var fontURL = URL(string: "") var error: Unmanaged<CFError>? paths.forEach { guard let filename = NSURL(fileURLWithPath: $0).lastPathComponent, filename.lowercased().range(of: fontName.lowercased()) != nil else { return } fontURL = NSURL(fileURLWithPath: $0) as URL } guard let unwrappedFontURL = fontURL, let data = try? Data(contentsOf: unwrappedFontURL), let provider = CGDataProvider(data: data as CFData) else { return } let font = CGFont.init(provider) guard !CTFontManagerRegisterGraphicsFont(font, &error), let unwrappedError = error, let nsError = (unwrappedError.takeUnretainedValue() as AnyObject) as? NSError else { return } let errorDescription: CFString = CFErrorCopyDescription(unwrappedError.takeUnretainedValue()) NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } }
mit
6a3278f979c9b62ecf3d73af144207b9
28.867925
101
0.620973
4.977987
false
false
false
false
romankisil/eqMac2
native/app/Source/UI/ViewController.swift
1
2343
// // ViewController.swift // eqMac // // Created by Roman Kisil on 10/12/2017. // Copyright © 2017 Roman Kisil. All rights reserved. // import Cocoa import WebKit import EmitterKit import Shared class ViewController: NSViewController, WKNavigationDelegate { // MARK: - Properties @IBOutlet var parentView: View! @IBOutlet var webView: WKWebView! @IBOutlet var draggableView: DraggableView! @IBOutlet var loadingView: NSView! @IBOutlet var loadingSpinner: NSProgressIndicator! let loaded = Event<Void>() var height: Double { get { return Double(webView.frame.size.height) } set { let newHeight = CGFloat(newValue) let newSize = NSSize(width: webView.frame.size.width, height: newHeight) self.view.setFrameSize(newSize) } } var width: Double { get { return Double(webView.frame.size.width) } set { let newWidth = CGFloat(newValue) let newSize = NSSize(width: newWidth, height: CGFloat(height)) self.view.setFrameSize(newSize) } } // MARK: - Initialization override func viewDidLoad () { super.viewDidLoad() loadingSpinner.startAnimation(nil) loaded.emit() } func load (_ url: URL) { let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData) if self.webView.isLoading { self.webView.stopLoading() } self.webView.load(request) Async.delay(1000) { self.loadingView.isHidden = true self.loadingSpinner.stopAnimation(nil) } if Constants.DEBUG { Console.log("Enabling DevTools") self.webView.configuration.preferences.setValue(true, forKey: "developerExtrasEnabled") } } // MARK: - Listeners override func viewWillAppear() { super.viewWillAppear() } func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let cred = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, cred) } } class View: NSView { override var acceptsFirstResponder: Bool { true } override func keyDown(with event: NSEvent) { // This is an override to disable OS sound effects (beeps and boops) when pressing keys inside the view } }
mit
bd739e8fcab2dd1935dceb43fe9b034c
25.314607
180
0.694705
4.369403
false
false
false
false
darrinhenein/firefox-ios
Storage/StorageTests/MockFiles.swift
3
1551
import Foundation import XCTest class MockFiles : FileAccessor { func getDir(name: String?, basePath: String? = nil) -> String? { var path = basePath if path == nil { path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as? String path?.stringByAppendingPathExtension("testing") } if let name = name { path = path?.stringByAppendingPathExtension(name) } return path } func move(src: String, srcBasePath: String? = nil, dest: String, destBasePath: String? = nil) -> Bool { if let f = get(src, basePath: srcBasePath) { if let f2 = get(dest, basePath: destBasePath) { return NSFileManager.defaultManager().moveItemAtPath(f, toPath: f2, error: nil) } } return false } func get(path: String, basePath: String? = nil) -> String? { return getDir(nil, basePath: basePath)?.stringByAppendingPathComponent(path) } func remove(filename: String, basePath: String? = nil) { let fileManager = NSFileManager.defaultManager() if var file = get(filename, basePath: nil) { fileManager.removeItemAtPath(file, error: nil) } } func exists(filename: String, basePath: String? = nil) -> Bool { if var file = get(filename, basePath: nil) { return NSFileManager.defaultManager().fileExistsAtPath(file) } return false } }
mpl-2.0
9a4efffe809cff015eb69ed67256d22d
32.717391
154
0.620245
4.757669
false
false
false
false
schibsted/layout
Layout/LayoutError+LayoutNode.swift
1
5459
// Copyright © 2017 Schibsted. All rights reserved. import Foundation extension LayoutError { init(_ message: String, for node: LayoutNode?) { self.init(LayoutError.message(message), for: node) } init(_ error: Error, for node: LayoutNode?) { guard let node = node else { self.init(error) return } let rootURL = (node.rootURL != node.parent?.rootURL) ? node.rootURL : nil switch error { case let error as SymbolError where error.description.contains("Unknown property"): if error.description.contains("expression") { let symbol: String if let subError = error.error as? SymbolError { symbol = subError.symbol } else { symbol = error.symbol } let suggestions = bestMatches( for: symbol, in: node.availableSymbols(forExpression: error.symbol) ) self.init(LayoutError.unknownSymbol(error, suggestions), for: node) } else { let suggestions = bestMatches(for: error.symbol, in: node.availableExpressions) self.init(LayoutError.unknownExpression(error, suggestions), for: node) } case let error as SymbolError where error.description.contains("static property"): if error.description.contains("expression") { let symbol: String if let subError = error.error as? SymbolError { symbol = subError.symbol } else { symbol = error.symbol } guard let suggestions = staticPropertyMatches(for: symbol) else { fallthrough } self.init(LayoutError.unknownSymbol(error, suggestions), for: node) } else { let suggestions = bestMatches(for: error.symbol, in: node.availableExpressions) self.init(LayoutError.unknownExpression(error, suggestions), for: node) } default: self.init(error, in: nameOfClass(node._class), in: rootURL) } } static func wrap<T>(_ closure: () throws -> T, for node: LayoutNode) throws -> T { do { return try closure() } catch { throw self.init(error, for: node) } } } private func staticPropertyMatches(for key: String) -> [String]? { var tail = key var head = "" while tail.isCapitalized, let range = tail.range(of: ".") { if !head.isEmpty { head += "." } head += String(tail[..<range.lowerBound]) tail = String(tail[range.upperBound...]) } guard !head.isEmpty, let type = RuntimeType.type(named: head) else { return nil } switch type.kind { case let .options(_, values): return bestMatches(for: tail, in: Set(values.keys)) case let .any(type as NSObject.Type): var suffix = head.components(separatedBy: ".").last! for prefix in ["UI", "NS"] { if suffix.hasPrefix(prefix) { suffix = String(suffix[prefix.endIndex ..< suffix.endIndex]) break } } var keys = Set<String>() var numberOfMethods: CUnsignedInt = 0 let methods = class_copyMethodList(object_getClass(type.self), &numberOfMethods)! for i in 0 ..< Int(numberOfMethods) { let selector: Selector = method_getName(methods[i]) var name = String(describing: selector) guard !name.contains(":"), !name.hasPrefix("_") else { continue } if name.hasSuffix(suffix) { name.removeLast(suffix.count) } keys.insert(name) } return bestMatches(for: tail, in: keys) default: return nil } } func bestMatches(for symbol: String, in suggestions: Set<String>) -> [String] { func levenshtein(_ lhs: String, _ rhs: String) -> Int { var dist = [[Int]]() for i in 0 ... lhs.count { dist.append([i]) } for j in 1 ... rhs.count { dist[0].append(j) } for i in 1 ... lhs.count { let lhs = lhs[lhs.index(lhs.startIndex, offsetBy: i - 1)] for j in 1 ... rhs.count { if lhs == rhs[rhs.index(rhs.startIndex, offsetBy: j - 1)] { dist[i].append(dist[i - 1][j - 1]) } else { dist[i].append(min(min(dist[i - 1][j] + 1, dist[i][j - 1] + 1), dist[i - 1][j - 1] + 1)) } } } return dist[lhs.count][rhs.count] } let lowercasedSymbol = symbol.lowercased() // Sort suggestions by Levenshtein distance return suggestions .compactMap { (string) -> (String, Int)? in let lowercaseString = string.lowercased() // Eliminate keyPaths unless symbol itself is a keyPath or is part of result guard !lowercaseString.contains(".") || symbol.contains(".") || lowercaseString.hasPrefix("\(lowercasedSymbol).") else { return nil } return (string, levenshtein(lowercaseString, lowercasedSymbol)) } // Sort by Levenshtein distance .sorted { $0.1 < $1.1 } .map { $0.0 } }
mit
b861f86358a53d667ea0bfee5be13ca1
37.167832
108
0.535178
4.514475
false
false
false
false
ben-ng/swift
test/SourceKit/CursorInfo/cursor_invalid.swift
10
2940
class C { func foo() { for child : AnyObject in childs! { let c : C } } var over under: Int var bad: IDontExist let var: Int } { class MyCoolClass: Undeclared {} } func resyncParser1() {} func == func ==() func ==(x: C) func ==(x: C, y: C) func resyncParser2() {} // RUN: %sourcekitd-test -req=cursor -pos=4:13 %s -- %s | %FileCheck -check-prefix=CHECK1 %s // CHECK1: source.lang.swift.decl.var.local (4:13-4:14) // CHECK1: c // CHECK1: <Declaration>let c</Declaration> // CHECK1: OVERRIDES BEGIN // CHECK1: OVERRIDES END // RUN: %sourcekitd-test -req=cursor -pos=13:10 %s -- %s | %FileCheck -check-prefix=CHECK2 %s // CHECK2: source.lang.swift.decl.class (13:9-13:20) // CHECK2: MyCoolClass // CHECK2: <Declaration>class MyCoolClass : Undeclared</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=7:7 %s -- %s | %FileCheck -check-prefix=CHECK3 %s // CHECK3: source.lang.swift.decl.var.instance (7:7-7:11) // CHECK3: over // CHECK3: <Declaration>var over{{.*}}</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=8:7 %s -- %s | %FileCheck -check-prefix=CHECK4 %s // CHECK4: source.lang.swift.decl.var.instance (8:7-8:10) // CHECK4: bad // CHECK4: <Declaration>var bad: IDontExist</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=7:12 %s -- %s | %FileCheck -check-prefix=EMPTY %s // RUN: %sourcekitd-test -req=cursor -pos=9:7 %s -- %s | %FileCheck -check-prefix=EMPTY %s // EMPTY: <empty cursor info> // RUN: %sourcekitd-test -req=cursor -pos=18:6 %s -- %s | %FileCheck -check-prefix=EQEQ1 %s // RUN: %sourcekitd-test -req=cursor -pos=19:6 %s -- %s | %FileCheck -check-prefix=EQEQ1 %s // Note: we can't find the operator decl so the decl kind is a fallback. // EQEQ1: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>==</decl.name>() // RUN: %sourcekitd-test -req=cursor -pos=20:6 %s -- %s | %FileCheck -check-prefix=EQEQ2 %s // Note: we can't find the operator decl so the decl kind is a fallback. // EQEQ2: <decl.function.free><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>==</decl.name>(<decl.var.parameter><decl.var.parameter.name>x</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr="s:C14cursor_invalid1C">C</ref.class></decl.var.parameter.type></decl.var.parameter>)</decl.function.free> // RUN: %sourcekitd-test -req=cursor -pos=21:6 %s -- %s | %FileCheck -check-prefix=EQEQ3 %s // EQEQ3: <decl.function.operator.infix><syntaxtype.keyword>func</syntaxtype.keyword> <decl.name>==</decl.name>(<decl.var.parameter><decl.var.parameter.name>x</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr="s:C14cursor_invalid1C">C</ref.class></decl.var.parameter.type></decl.var.parameter>, <decl.var.parameter><decl.var.parameter.name>y</decl.var.parameter.name>: <decl.var.parameter.type><ref.class usr="s:C14cursor_invalid1C">C</ref.class></decl.var.parameter.type></decl.var.parameter>)</decl.function.operator.infix>
apache-2.0
c799ed7187fd8c2283c4abbd1abcd422
47.196721
542
0.689796
2.84058
false
true
false
false
manavgabhawala/MGDocIt
MGDocIt/File.swift
1
12938
// // File.swift // MGDocIt // // Created by Manav Gabhawala on 14/08/15. // Copyright © 2015 Manav Gabhawala. All rights reserved. // import Foundation import XPC /// Represents a source file. public struct File { /// File path. Nil if initialized directly with `File(contents:)`. public let path: String? /// File contents. public let contents: String /** Failable initializer by path. Fails if file contents could not be read as a UTF8 string. - parameter path: File path. */ public init?(path: String) { self.path = path do { self.contents = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String } catch { print("Could not read contents of `\(path)`") return nil } } /// Initializer by file contents. File path is nil. /// /// - parameter contents: File contents. public init(contents: String) { path = nil self.contents = contents } /* /** Parse source declaration string from XPC dictionary. - parameter dictionary: XPC dictionary to extract declaration from. - returns: Source declaration if successfully parsed. */ public func parseDeclaration(dictionary: XPCDictionary) -> String? { if !shouldParseDeclaration(dictionary) { return nil } return SwiftDocKey.getOffset(dictionary).flatMap { start in let end = SwiftDocKey.getBodyOffset(dictionary).map { Int($0) } let start = Int(start) let length = (end ?? start) - start return contents.substringLinesWithByteRange(start: start, length: length)? .stringByTrimmingWhitespaceAndOpeningCurlyBrace() } } /** Parse line numbers containing the declaration's implementation from XPC dictionary. - parameter dictionary: XPC dictionary to extract declaration from. - returns: Line numbers containing the declaration's implementation. */ public func parseScopeRange(dictionary: XPCDictionary) -> (start: Int, end: Int)? { if !shouldParseDeclaration(dictionary) { return nil } return SwiftDocKey.getOffset(dictionary).flatMap { start in let start = Int(start) let end = SwiftDocKey.getBodyOffset(dictionary).flatMap { bodyOffset in return SwiftDocKey.getBodyLength(dictionary).map { bodyLength in return Int(bodyOffset + bodyLength) } } ?? start let length = end - start return contents.lineRangeWithByteRange(start: start, length: length) } } /** Extract mark-style comment string from doc dictionary. e.g. '// MARK: - The Name' - parameter dictionary: Doc dictionary to parse. - returns: Mark name if successfully parsed. */ private func markNameFromDictionary(dictionary: XPCDictionary) -> String? { precondition(SwiftDocKey.getKind(dictionary)! == SyntaxKind.CommentMark.rawValue) let offset = Int(SwiftDocKey.getOffset(dictionary)!) let length = Int(SwiftDocKey.getLength(dictionary)!) if let fileContentsData = contents.dataUsingEncoding(NSUTF8StringEncoding), subdata = Optional(fileContentsData.subdataWithRange(NSRange(location: offset, length: length))), substring = NSString(data: subdata, encoding: NSUTF8StringEncoding) as String? { return substring } return nil } /** Returns a copy of the input dictionary with comment mark names, cursor.info information and parsed declarations for the top-level of the input dictionary and its substructures. - parameter dictionary: Dictionary to process. - parameter cursorInfoRequest: Cursor.Info request to get declaration information. */ public func processDictionary(var dictionary: XPCDictionary, cursorInfoRequest: xpc_object_t? = nil, syntaxMap: SyntaxMap? = nil) -> XPCDictionary { if let cursorInfoRequest = cursorInfoRequest { dictionary = merge( dictionary, dictWithCommentMarkNamesCursorInfo(dictionary, cursorInfoRequest: cursorInfoRequest) ) } // Parse declaration and add to dictionary if let parsedDeclaration = parseDeclaration(dictionary) { dictionary[SwiftDocKey.ParsedDeclaration.rawValue] = parsedDeclaration } // Parse scope range and add to dictionary if let parsedScopeRange = parseScopeRange(dictionary) { dictionary[SwiftDocKey.ParsedScopeStart.rawValue] = Int64(parsedScopeRange.start) dictionary[SwiftDocKey.ParsedScopeEnd.rawValue] = Int64(parsedScopeRange.end) } // Parse `key.doc.full_as_xml` and add to dictionary if let parsedXMLDocs = (SwiftDocKey.getFullXMLDocs(dictionary).flatMap(parseFullXMLDocs)) { dictionary = merge(dictionary, parsedXMLDocs) // Parse documentation comment and add to dictionary if let commentBody = (syntaxMap.flatMap { getDocumentationCommentBody(dictionary, syntaxMap: $0) }) { dictionary[SwiftDocKey.DocumentationComment.rawValue] = commentBody } } // Update substructure if let substructure = newSubstructure(dictionary, cursorInfoRequest: cursorInfoRequest, syntaxMap: syntaxMap) { dictionary[SwiftDocKey.Substructure.rawValue] = substructure } return dictionary } /** Returns a copy of the input dictionary with additional cursorinfo information at the given `documentationTokenOffsets` that haven't yet been documented. - parameter dictionary: Dictionary to insert new docs into. - parameter documentedTokenOffsets: Offsets that are likely documented. - parameter cursorInfoRequest: Cursor.Info request to get declaration information. */ internal func furtherProcessDictionary(var dictionary: XPCDictionary, documentedTokenOffsets: [Int], cursorInfoRequest: xpc_object_t, syntaxMap: SyntaxMap) -> XPCDictionary { let offsetMap = generateOffsetMap(documentedTokenOffsets, dictionary: dictionary) for offset in offsetMap.keys.array.reverse() { // Do this in reverse to insert the doc at the correct offset let response = processDictionary(Request.sendCursorInfoRequest(cursorInfoRequest, atOffset: Int64(offset))!, cursorInfoRequest: nil, syntaxMap: syntaxMap) if let kind = SwiftDocKey.getKind(response), _ = SwiftDeclarationKind(rawValue: kind), parentOffset = offsetMap[offset].flatMap({ Int64($0) }), inserted = insertDoc(response, parent: dictionary, offset: parentOffset) { dictionary = inserted } } return dictionary } /** Update input dictionary's substructure by running `processDictionary(_:cursorInfoRequest:syntaxMap:)` on its elements, only keeping comment marks and declarations. - parameter dictionary: Input dictionary to process its substructure. - parameter cursorInfoRequest: Cursor.Info request to get declaration information. - returns: A copy of the input dictionary's substructure processed by running `processDictionary(_:cursorInfoRequest:syntaxMap:)` on its elements, only keeping comment marks and declarations. */ private func newSubstructure(dictionary: XPCDictionary, cursorInfoRequest: xpc_object_t?, syntaxMap: SyntaxMap?) -> XPCArray? { return SwiftDocKey.getSubstructure(dictionary)? .map({ $0 as! XPCDictionary }) .filter(isDeclarationOrCommentMark) .map { processDictionary($0, cursorInfoRequest: cursorInfoRequest, syntaxMap: syntaxMap) } } /** Returns an updated copy of the input dictionary with comment mark names and cursor.info information. - parameter dictionary: Dictionary to update. - parameter cursorInfoRequest: Cursor.Info request to get declaration information. */ private func dictWithCommentMarkNamesCursorInfo(dictionary: XPCDictionary, cursorInfoRequest: xpc_object_t) -> XPCDictionary? { if let kind = SwiftDocKey.getKind(dictionary) { // Only update dictionaries with a 'kind' key if kind == SyntaxKind.CommentMark.rawValue { // Update comment marks if let markName = markNameFromDictionary(dictionary) { return [SwiftDocKey.Name.rawValue: markName] } } else if let decl = SwiftDeclarationKind(rawValue: kind) where decl != .VarParameter { // Update if kind is a declaration (but not a parameter) var updateDict = Request.sendCursorInfoRequest(cursorInfoRequest, atOffset: SwiftDocKey.getNameOffset(dictionary)!) ?? XPCDictionary() // Skip kinds, since values from editor.open are more accurate than cursorinfo updateDict.removeValueForKey(SwiftDocKey.Kind.rawValue) return updateDict } } return nil } /** Returns whether or not a doc should be inserted into a parent at the provided offset. - parameter parent: Parent dictionary to evaluate. - parameter offset: Offset to search for in parent dictionary. - returns: True if a doc should be inserted in the parent at the provided offset. */ private func shouldInsert(parent: XPCDictionary, offset: Int64) -> Bool { return (offset == 0) || (shouldTreatAsSameFile(parent) && SwiftDocKey.getOffset(parent) == offset) } /** Inserts a document dictionary at the specified offset. Parent will be traversed until the offset is found. Returns nil if offset could not be found. - parameter doc: Document dictionary to insert. - parameter parent: Parent to traverse to find insertion point. - parameter offset: Offset to insert document dictionary. - returns: Parent with doc inserted if successful. */ private func insertDoc(doc: XPCDictionary, var parent: XPCDictionary, offset: Int64) -> XPCDictionary? { if shouldInsert(parent, offset: offset) { var substructure = SwiftDocKey.getSubstructure(parent)! var insertIndex = substructure.count for (index, structure) in substructure.reverse().enumerate() { if SwiftDocKey.getOffset(structure as! XPCDictionary)! < offset { break } insertIndex = substructure.count - index } substructure.insert(doc, atIndex: insertIndex) parent[SwiftDocKey.Substructure.rawValue] = substructure return parent } for key in parent.keys { if var subArray = parent[key] as? XPCArray { for i in 0..<subArray.count { if let subDict = insertDoc(doc, parent: subArray[i] as! XPCDictionary, offset: offset) { subArray[i] = subDict parent[key] = subArray return parent } } } } return nil } /** Returns true if path is nil or if path has the same last path component as `key.filepath` in the input dictionary. - parameter dictionary: Dictionary to parse. */ internal func shouldTreatAsSameFile(dictionary: XPCDictionary) -> Bool { return path == SwiftDocKey.getFilePath(dictionary) } /** Returns true if the input dictionary contains a parseable declaration. - parameter dictionary: Dictionary to parse. */ private func shouldParseDeclaration(dictionary: XPCDictionary) -> Bool { let sameFile = shouldTreatAsSameFile(dictionary) let hasTypeName = SwiftDocKey.getTypeName(dictionary) != nil let hasAnnotatedDeclaration = SwiftDocKey.getAnnotatedDeclaration(dictionary) != nil let hasOffset = SwiftDocKey.getOffset(dictionary) != nil let isntExtension = SwiftDocKey.getKind(dictionary) != SwiftDeclarationKind.Extension.rawValue return sameFile && hasTypeName && hasAnnotatedDeclaration && hasOffset && isntExtension } /** Parses `dictionary`'s documentation comment body. - parameter dictionary: Dictionary to parse. - parameter syntaxMap: SyntaxMap for current file. - returns: `dictionary`'s documentation comment body as a string, without any documentation syntax (`/** ... */` or `/// ...`). */ public func getDocumentationCommentBody(dictionary: XPCDictionary, syntaxMap: SyntaxMap) -> String? { return SwiftDocKey.getOffset(dictionary).flatMap { offset in return syntaxMap.commentRangeBeforeOffset(Int(offset)).flatMap { commentByteRange in return contents.byteRangeToNSRange(start: commentByteRange.start, length: commentByteRange.length).flatMap { nsRange in return contents.commentBody(nsRange) } } } }*/ } /** Returns true if the dictionary represents a source declaration or a mark-style comment. - parameter dictionary: Dictionary to parse. private func isDeclarationOrCommentMark(dictionary: XPCDictionary) -> Bool { if let kind = SwiftDocKey.getKind(dictionary) { return kind != SwiftDeclarationKind.VarParameter.rawValue && (kind == SyntaxKind.CommentMark.rawValue || SwiftDeclarationKind(rawValue: kind) != nil) } return false } */ /** Traverse the dictionary replacing SourceKit UIDs with their string value. - parameter dictionary: Dictionary to replace UIDs. - returns: Dictionary with UIDs replaced by strings. */ internal func replaceUIDsWithSourceKitStrings(var dictionary: XPCDictionary) -> XPCDictionary { for key in dictionary.keys { if let uid = dictionary[key] as? UInt64, uidString = stringForSourceKitUID(uid) { dictionary[key] = uidString } else if let array = dictionary[key] as? XPCArray { dictionary[key] = array.map { replaceUIDsWithSourceKitStrings($0 as! XPCDictionary) } as XPCArray } else if let dict = dictionary[key] as? XPCDictionary { dictionary[key] = replaceUIDsWithSourceKitStrings(dict) } } return dictionary }
mit
827f1f35d10dd4760d2e04984cd13947
35.238095
175
0.74198
4.161145
false
false
false
false
eselkin/DirectionFieldiOS
Pods/GRDB.swift/GRDB/Foundation/Row+Foundation.swift
1
1430
import Foundation /// Foundation support for Row extension Row { /// Builds a row from an NSDictionary. /// /// The result is nil unless all dictionary keys are strings, and values /// adopt DatabaseValueConvertible (NSData, NSDate, NSNull, NSNumber, /// NSString, NSURL). /// /// - parameter dictionary: An NSDictionary. public convenience init?(_ dictionary: NSDictionary) { var initDictionary = [String: DatabaseValueConvertible?]() for (key, value) in dictionary { guard let columnName = key as? String else { return nil } guard let databaseValue = DatabaseValue(object: value) else { return nil } initDictionary[columnName] = databaseValue } self.init(initDictionary) } /// Converts a row to an NSDictionary. /// /// When the row contains duplicated column names, the dictionary contains /// the value of the leftmost column. /// /// - returns: An NSDictionary. public func toNSDictionary() -> NSDictionary { let dictionary = NSMutableDictionary(capacity: count) // Reverse so that the result dictionary contains values for the leftmost columns. for (columnName, databaseValue) in reverse() { dictionary[columnName] = databaseValue.toAnyObject() } return dictionary } }
gpl-3.0
6ef8ca16c68329a96c639f57e3717eed
33.878049
90
0.62028
5.478927
false
false
false
false
Bartlebys/Bartleby
Bartleby.xOS/_generated/operations/ReadLockersByQuery.swift
1
9099
// // ReadLockersByQuery.swift // Bartleby // // THIS FILE AS BEEN GENERATED BY BARTLEBYFLEXIONS for [Benoit Pereira da Silva] (https://pereira-da-silva.com/contact) // DO NOT MODIFY THIS FILE YOUR MODIFICATIONS WOULD BE ERASED ON NEXT GENERATION! // // Copyright (c) 2016 [Bartleby's org] (https://bartlebys.org) All rights reserved. // import Foundation #if !USE_EMBEDDED_MODULES import Alamofire #endif @objc public class ReadLockersByQueryParameters : ManagedModel { // Universal type support override open class func typeName() -> String { return "ReadLockersByQueryParameters" } // public var result_fields:[String]? // the sort (MONGO DB) public var sort:[String:Int] = [String:Int]() // the query (MONGO DB) public var query:[String:String] = [String:String]() required public init(){ super.init() } // MARK: - Exposed (Bartleby's KVC like generative implementation) /// Return all the exposed instance variables keys. (Exposed == public and modifiable). override open var exposedKeys:[String] { var exposed=super.exposedKeys exposed.append(contentsOf:["result_fields","sort","query"]) return exposed } /// Set the value of the given key /// /// - parameter value: the value /// - parameter key: the key /// /// - throws: throws an Exception when the key is not exposed override open func setExposedValue(_ value:Any?, forKey key: String) throws { switch key { case "result_fields": if let casted=value as? [String]{ self.result_fields=casted } case "sort": if let casted=value as? [String:Int]{ self.sort=casted } case "query": if let casted=value as? [String:String]{ self.query=casted } default: return try super.setExposedValue(value, forKey: key) } } /// Returns the value of an exposed key. /// /// - parameter key: the key /// /// - throws: throws Exception when the key is not exposed /// /// - returns: returns the value override open func getExposedValueForKey(_ key:String) throws -> Any?{ switch key { case "result_fields": return self.result_fields case "sort": return self.sort case "query": return self.query default: return try super.getExposedValueForKey(key) } } // MARK: - Codable public enum CodingKeys: String,CodingKey{ case result_fields case sort case query } required public init(from decoder: Decoder) throws{ try super.init(from: decoder) try self.quietThrowingChanges { let values = try decoder.container(keyedBy: CodingKeys.self) self.result_fields = try values.decodeIfPresent([String].self,forKey:.result_fields) self.sort = try values.decode([String:Int].self,forKey:.sort) self.query = try values.decode([String:String].self,forKey:.query) } } override open func encode(to encoder: Encoder) throws { try super.encode(to:encoder) var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(self.result_fields,forKey:.result_fields) try container.encode(self.sort,forKey:.sort) try container.encode(self.query,forKey:.query) } } @objc(ReadLockersByQuery) open class ReadLockersByQuery : ManagedModel{ // Universal type support override open class func typeName() -> String { return "ReadLockersByQuery" } public static func execute(from documentUID:String, parameters:ReadLockersByQueryParameters, sucessHandler success:@escaping(_ lockers:[Locker])->(), failureHandler failure:@escaping(_ context:HTTPContext)->()){ if let document = Bartleby.sharedInstance.getDocumentByUID(documentUID) { let pathURL=document.baseURL.appendingPathComponent("lockersByQuery") let dictionary:[String:Any]? = parameters.dictionaryRepresentation() let urlRequest=HTTPManager.requestWithToken(inDocumentWithUID:document.UID,withActionName:"ReadLockersByQuery" ,forMethod:"GET", and: pathURL) do { let r=try URLEncoding().encode(urlRequest,with:dictionary) request(r).responseData(completionHandler: { (response) in let request=response.request let result=response.result let timeline=response.timeline let statusCode=response.response?.statusCode ?? 0 let context = HTTPContext( code: 1469328942, caller: "ReadLockersByQuery.execute", relatedURL:request?.url, httpStatusCode: statusCode) if let request=request{ context.request=HTTPRequest(urlRequest: request) } if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { context.responseString=utf8Text } let metrics=Metrics() metrics.httpContext=context metrics.operationName="ReadLockersByQuery" metrics.latency=timeline.latency metrics.requestDuration=timeline.requestDuration metrics.serializationDuration=timeline.serializationDuration metrics.totalDuration=timeline.totalDuration document.report(metrics) // React according to the situation var reactions = Array<Reaction> () if result.isFailure { let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Unsuccessfull attempt",comment: "Unsuccessfull attempt"), body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit:{ (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) }else{ if 200...299 ~= statusCode { do{ if let data = response.data{ let instance = try JSON.decoder.decode([Locker].self,from:data) success(instance) }else{ throw BartlebyOperationError.dataNotFound } }catch{ let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title:"\(error)", body: "\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit: { (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } }else{ // Bartlby does not currenlty discriminate status codes 100 & 101 // and treats any status code >= 300 the same way // because we consider that failures differentiations could be done by the caller. let failureReaction = Reaction.dispatchAdaptiveMessage( context: context, title: NSLocalizedString("Unsuccessfull attempt",comment: "Unsuccessfull attempt"), body:"\(String(describing: result.value))\n\(#file)\n\(#function)\nhttp Status code: (\(statusCode))", transmit:{ (selectedIndex) -> () in }) reactions.append(failureReaction) failure(context) } } //Let s react according to the context. document.perform(reactions, forContext: context) }) }catch{ let context = HTTPContext( code:2 , caller: "ReadLockersByQuery.execute", relatedURL:nil, httpStatusCode:500) failure(context) } }else{ let context = HTTPContext( code: 1, caller: "ReadLockersByQuery.execute", relatedURL:nil, httpStatusCode: 417) failure(context) } } }
apache-2.0
2eb9bec10caef547d130aa271b3c055d
38.733624
154
0.542477
5.100336
false
false
false
false
noremac/UIKitExtensions
Extensions/Source/General/Utils/CoalescedTimer.swift
1
2327
/* The MIT License (MIT) Copyright (c) 2017 Cameron Pulsford 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 public class CoalescedTimer<Key: Hashable> { let duration: TimeInterval private var closures: [Key: () -> Void] = [:] private let workOrder: [Key]? private var timer: Timer? init(duration: TimeInterval, workOrder: [Key]?) { self.duration = duration self.workOrder = workOrder } deinit { timer?.invalidate() } func add(key: Key, work: (() -> Void)?) { closures[key] = work if closures.isEmpty { timer?.invalidate() timer = nil } else if timer == nil { timer = Timer(timeInterval: duration, repeats: false, block: { [weak self] _ in self?.performWork() }) } } func removeAllWork() { timer?.invalidate() timer = nil closures.removeAll() } private func performWork() { let closures = self.closures self.closures.removeAll() timer = nil if let workOrder = workOrder { for key in workOrder { closures[key]?() } } else { for value in closures.values { value() } } } }
mit
a9131e43cdbe89885d1fc4da700f5d63
28.0875
91
0.63988
4.729675
false
false
false
false
jtway/JTNetworkUtils
Shared Framework Sources/SocketAddress.swift
1
3434
// // SocketAddress.swift // JTNetworkUtilities // // Created by Josh Tway on 9/24/15. // Sourced from: https://developer.apple.com/library/ios/samplecode/SimpleTunnel/Introduction/Intro.html#//apple_ref/doc/uid/TP40016140 // import Foundation /// Protocol for SocketAddresses to conform to public protocol SocketAddress { /// IP address as a string var stringValue: String? { get } /// Family (AF_INET or AF_INET6) var family: Int32 { get } /// Set SocketAddress from IP address string func setFromString(str: String) -> Bool /// Set port func setPort(port: Int) } /// A object containing a sockaddr_in6 structure. public class SocketAddress6: SocketAddress { // MARK: Properties /// The sockaddr_in6 structure. public var sin6: sockaddr_in6 /// The IPv6 address as a string. public var stringValue: String? { return withUnsafePointer(&sin6) { saToString(UnsafePointer<sockaddr>($0)) } } public var family: Int32 { return AF_INET6 } // MARK: Initializers public init() { sin6 = sockaddr_in6() sin6.sin6_len = __uint8_t(sizeof(sockaddr_in6)) sin6.sin6_family = sa_family_t(AF_INET6) sin6.sin6_port = in_port_t(0) sin6.sin6_addr = in6addr_any sin6.sin6_scope_id = __uint32_t(0) sin6.sin6_flowinfo = __uint32_t(0) } public convenience init(otherAddress: SocketAddress6) { self.init() sin6 = otherAddress.sin6 } /// Set the IPv6 address from a string. public func setFromString(str: String) -> Bool { return str.withCString({ cs in inet_pton(AF_INET6, cs, &sin6.sin6_addr) }) == 1 } /// Set the port. public func setPort(port: Int) { sin6.sin6_port = in_port_t(UInt16(port).bigEndian) } } /// An object containing a sockaddr_in structure. public class SocketAddress4: SocketAddress { // MARK: Properties /// The sockaddr_in structure. public var sin: sockaddr_in /// The IPv4 address in string form. public var stringValue: String? { return withUnsafePointer(&sin) { saToString(UnsafePointer<sockaddr>($0)) } } public var family: Int32 { return AF_INET } // MARK: Initializers public init() { sin = sockaddr_in(sin_len:__uint8_t(sizeof(sockaddr_in.self)), sin_family:sa_family_t(AF_INET), sin_port:in_port_t(0), sin_addr:in_addr(s_addr: 0), sin_zero:(Int8(0), Int8(0), Int8(0), Int8(0), Int8(0), Int8(0), Int8(0), Int8(0))) } public convenience init(otherAddress: SocketAddress4) { self.init() sin = otherAddress.sin } /// Set the IPv4 address from a string. public func setFromString(str: String) -> Bool { return str.withCString({ cs in inet_pton(AF_INET, cs, &sin.sin_addr) }) == 1 } /// Set the port. public func setPort(port: Int) { sin.sin_port = in_port_t(UInt16(port).bigEndian) } /// Increment the address by a given amount. public func increment(amount: UInt32) { let networkAddress = sin.sin_addr.s_addr.byteSwapped + amount sin.sin_addr.s_addr = networkAddress.byteSwapped } /// Get the difference between this address and another address. public func difference(otherAddress: SocketAddress4) -> Int64 { return Int64(sin.sin_addr.s_addr.byteSwapped - otherAddress.sin.sin_addr.s_addr.byteSwapped) } }
mit
5a9ffbf19775bb7e81466cb9391ba8fa
27.616667
238
0.639487
3.522051
false
false
false
false
HarrisLee/Utils
MySampleCode-master/Streamable/Streamable/Print.swift
1
2504
// // Print.swift // Streamable // // Created by 张星宇 on 16/1/26. // Copyright © 2016年 zxy. All rights reserved. // import Foundation struct Person { var name: String private var age: Int init(name: String, age: Int) { self.name = name self.age = age } } // 1. 调用不带`output`参数的`print`函数,函数内部生成`_Stdout `类型的输出流,调用`_print`函数 // 2. 在`_print`函数中国处理完`separator`和`terminator `等格式参数后,调用`_print_unlocked `函数处理字符串输出。 // 3. 在`_print_unlocked `函数的第一个if判断中,因为字符串类型实现了`Streamable `协议,所以调用字符串的`writeTo`函数,写入到输出流中。 // 4. 根据字符串的`writeTo`函数的定义,它在内部调用了输出流的`write`方法 // 5. `_Stdout`在其`write`方法中,调用C语言的`putchar`函数输出字符串的每个字符 func testPrintString() { print("Hello, world!") } // 1. 调用不带`output`参数的`print`函数,函数内部生成`_Stdout `类型的输出流,调用`_print`函数 // 2. 在`_print`函数中国处理完`separator`和`terminator `等格式参数后,调用`_print_unlocked `函数处理字符串输出。 // 3. 截止目前和输出字符串一致,不过Int类型(以及其他除了和字符有关的几乎所有类型)没有实现`Streamable `协议,它实现的是`CustomStringConvertible `协议,定义了自己的计算属性`description` // 4. `description`是一个字符串类型,调用字符串的`writeTo`方法此前已经讲过,就不再赘述了。 func testPrintInteger() { print(123) } //1. 调用不带`output`参数的`print`函数,函数内部生成`_Stdout `类型的输出流,调用`_print`函数 //2. 在`_print`函数中国处理完`separator`和`terminator `等格式参数后,调用`_print_unlocked `函数处理字符串输出。 //3. 在`_print_unlocked `中调用`_adHocPrint `函数 //4. switch语句匹配,参数类型是结构体,执行对应case语句中的代码 func testPrintStruct() { print("测试直接打印结构体") let kt = Person(name: "kt", age: 21) print(kt) print("") } // 字符串的初始化方法中调用`_print_unlocked `函数 func testCreateString() { print("测试通过结构体创建字符串并输出到屏幕") let kt = Person(name: "kt", age: 21) let string = String(kt) print(string) print("") }
mit
0759820311dd0b2a9a6ce005e22e621d
28.122807
126
0.679928
2.502262
false
true
false
false
devpunk/velvet_room
Source/Model/SaveData/MSaveDataRecordFactory.swift
1
4868
import UIKit extension MSaveDataRecord { private static let kNewLine:String = "\n" private static let kTitleFontSize:CGFloat = 15 private static let kDescrFontSize:CGFloat = 15 private static let kDateFontSize:CGFloat = 13 //MARK: private private static func factoryTitle( coredataModel:DVitaItemDirectory, attributesTitle:[NSAttributedStringKey:Any]) -> NSAttributedString? { guard let title:String = coredataModel.sfoSavedDataTitle else { return nil } let attributedString:NSAttributedString = NSAttributedString( string:title, attributes:attributesTitle) return attributedString } private static func factoryNewLine() -> NSAttributedString { let attributedString:NSAttributedString = NSAttributedString( string:kNewLine) return attributedString } private static func factoryDescr( coredataModel:DVitaItemDirectory, attributesDescr:[NSAttributedStringKey:Any]) -> NSAttributedString? { guard let descr:String = coredataModel.sfoSavedDataDetail else { return nil } let attributedString:NSAttributedString = NSAttributedString( string:descr, attributes:attributesDescr) return attributedString } private static func factoryDate( coredataModel:DVitaItemDirectory, dateFormater:DateFormatter, attributesDate:[NSAttributedStringKey:Any]) -> NSAttributedString { let date:Date = Date(timeIntervalSince1970:coredataModel.dateModified) let string:String = dateFormater.string(from:date) let attributedString:NSAttributedString = NSAttributedString( string:string, attributes:attributesDate) return attributedString } //MARK: internal static func factoryDateFormatter() -> DateFormatter { let dateFormatter:DateFormatter = DateFormatter() dateFormatter.timeStyle = DateFormatter.Style.short dateFormatter.dateStyle = DateFormatter.Style.short return dateFormatter } static func factoryAttributesTitle() -> [ NSAttributedStringKey:Any] { let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font: UIFont.regular(size:kTitleFontSize), NSAttributedStringKey.foregroundColor: UIColor.colourBackgroundDark] return attributes } static func factoryAttributesDescr() -> [ NSAttributedStringKey:Any] { let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font: UIFont.regular(size:kDescrFontSize), NSAttributedStringKey.foregroundColor: UIColor(white:0.5, alpha:1)] return attributes } static func factoryAttributesDate() -> [ NSAttributedStringKey:Any] { let attributes:[NSAttributedStringKey:Any] = [ NSAttributedStringKey.font: UIFont.regular(size:kDateFontSize), NSAttributedStringKey.foregroundColor: UIColor(white:0.65, alpha:1)] return attributes } static func factoryRecord( coredataModel:DVitaItemDirectory, dateFormatter:DateFormatter, attributesTitle:[NSAttributedStringKey:Any], attributesDescr:[NSAttributedStringKey:Any], attributesDate:[NSAttributedStringKey:Any]) -> MSaveDataRecord? { guard let title:NSAttributedString = factoryTitle( coredataModel:coredataModel, attributesTitle:attributesTitle) else { return nil } let date:NSAttributedString = factoryDate( coredataModel:coredataModel, dateFormater:dateFormatter, attributesDate:attributesDate) let newLine:NSAttributedString = factoryNewLine() let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(title) if let descr:NSAttributedString = factoryDescr( coredataModel:coredataModel, attributesDescr:attributesDescr) { mutableString.append(newLine) mutableString.append(descr) } mutableString.append(newLine) mutableString.append(date) let record:MSaveDataRecord = MSaveDataRecord( record:mutableString) return record } }
mit
b29e9b0b0eac359569974dc9bb7ad6d0
28.50303
81
0.612777
6.185515
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/SystemManager/Network/BFNetworkManager.swift
1
4045
// // BFNetworkManager.swift // BeeFun // // Created by wenghengcong on 16/1/10. // Copyright © 2016年 JungleSong. All rights reserved. // import UIKit import WebKit import Reachability class BFNetworkManager: NSObject { static let shared = BFNetworkManager() var lastState: Reachability.Connection = .none let reachabilityManager = Reachability()! var isReachable: Bool { lastState = reachabilityManager.connection return reachabilityManager.connection != .none } var isReachableOnCellular: Bool { lastState = reachabilityManager.connection return reachabilityManager.connection == .cellular } var isReachableOnWiFi: Bool { lastState = reachabilityManager.connection return reachabilityManager.connection == .wifi } func startListening() { reachabilityManager.whenReachable = { reachability in if reachability.connection == .wifi { print("The network is reachable via WiFi: \(self.reachabilityManager.connection)") NotificationCenter.default.post(name: NSNotification.Name.BeeFun.ReachableWiFi, object: nil) } else { print("The network is reachable via Cellular: \(self.reachabilityManager.connection)") NotificationCenter.default.post(name: NSNotification.Name.BeeFun.ReachableCellular, object: nil) } if self.lastState == .none && (reachability.connection == .wifi || reachability.connection == .cellular) { print("The network is reachable after unreachable: \(self.reachabilityManager.connection)") NotificationCenter.default.post(name: NSNotification.Name.BeeFun.ReachableAfterUnreachable, object: nil) } self.lastState = reachability.connection } reachabilityManager.whenUnreachable = { reachability in print("The network is not reachable: \(self.reachabilityManager.connection)") NotificationCenter.default.post(name: NSNotification.Name.BeeFun.NotReachable, object: nil) if (self.lastState == .wifi || self.lastState == .cellular) && reachability.connection == .none { print("The network is not reachable after reachable: \(self.reachabilityManager.connection)") NotificationCenter.default.post(name: NSNotification.Name.BeeFun.UnReachableAfterReachable, object: nil) } self.lastState = reachability.connection } do { try reachabilityManager.startNotifier() } catch { print("Unable to start notifier") } } func stopListening() { lastState = .none reachabilityManager.stopNotifier() } // MARK: - 清除工具 /// 清除Cookies class func clearCookies() { let storage: HTTPCookieStorage = HTTPCookieStorage.shared for cookie in storage.cookies! { storage.deleteCookie(cookie) } } /// 清除缓存 class func clearCache() { if #available(iOS 9.0, *) { let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache, WKWebsiteDataTypeOfflineWebApplicationCache, WKWebsiteDataTypeCookies, WKWebsiteDataTypeSessionStorage, WKWebsiteDataTypeLocalStorage]) let date = NSDate(timeIntervalSince1970: 0) WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler: { }) } else { var libraryPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, false).first! libraryPath += "/Cookies" do { try FileManager.default.removeItem(atPath: libraryPath) } catch { print("error") } URLCache.shared.removeAllCachedResponses() } } }
mit
47f9f7305ae86718f74834adb042acf4
38.821782
242
0.655147
5.524725
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Services/Service.Window.swift
1
1624
import Foundation extension Service { open class Window: Service { public init(characteristics: [AnyCharacteristic] = []) { var unwrapped = characteristics.map { $0.wrapped } currentPosition = getOrCreateAppend( type: .currentPosition, characteristics: &unwrapped, generator: { PredefinedCharacteristic.currentPosition() }) positionState = getOrCreateAppend( type: .positionState, characteristics: &unwrapped, generator: { PredefinedCharacteristic.positionState() }) targetPosition = getOrCreateAppend( type: .targetPosition, characteristics: &unwrapped, generator: { PredefinedCharacteristic.targetPosition() }) name = get(type: .name, characteristics: unwrapped) obstructionDetected = get(type: .obstructionDetected, characteristics: unwrapped) holdPosition = get(type: .holdPosition, characteristics: unwrapped) super.init(type: .window, characteristics: unwrapped) } // MARK: - Required Characteristics public let currentPosition: GenericCharacteristic<UInt8> public let positionState: GenericCharacteristic<Enums.PositionState> public let targetPosition: GenericCharacteristic<UInt8> // MARK: - Optional Characteristics public let name: GenericCharacteristic<String>? public let obstructionDetected: GenericCharacteristic<Bool>? public let holdPosition: GenericCharacteristic<Bool?>? } }
mit
2dfc3ec0bd6f5ff8a01edd692d9a254f
45.4
93
0.648399
6.082397
false
false
false
false
mosesoak/iOS-CircleProgressView
ProgressView/CircleProgressView.swift
1
5099
// // CircleProgressView.swift // // // Created by Eric Rolf on 8/11/14. // Copyright (c) 2014 Eric Rolf, Cardinal Solutions Group. All rights reserved. // import UIKit @objc @IBDesignable public class CircleProgressView: UIView { internal struct Constants { let circleDegress = 360.0 let minimumValue = 0.000001 let maximumValue = 0.999999 let ninetyDegrees = 90.0 let twoSeventyDegrees = 270.0 var contentView:UIView = UIView() } let constants = Constants() private var internalProgress:Double = 0.0 @IBInspectable public var progress: Double = 0.000001 { didSet { internalProgress = progress setNeedsDisplay() } } @IBInspectable public var clockwise: Bool = true { didSet { setNeedsDisplay() } } @IBInspectable public var trackWidth: CGFloat = 10 { didSet { setNeedsDisplay() } } @IBInspectable public var trackImage: UIImage? { didSet { setNeedsDisplay() } } @IBInspectable public var trackBackgroundColor: UIColor = UIColor.grayColor() { didSet { setNeedsDisplay() } } @IBInspectable public var trackFillColor: UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } } @IBInspectable public var trackBorderColor:UIColor = UIColor.clearColor() { didSet { setNeedsDisplay() } } @IBInspectable public var trackBorderWidth: CGFloat = 0 { didSet { setNeedsDisplay() } } @IBInspectable public var centerFillColor: UIColor = UIColor.whiteColor() { didSet { setNeedsDisplay() } } @IBInspectable public var centerImage: UIImage? { didSet { setNeedsDisplay() } } @IBInspectable public var contentView: UIView { return self.constants.contentView } required override public init(frame: CGRect) { super.init(frame: frame) self.addSubview(contentView) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addSubview(contentView) } override public func drawRect(rect: CGRect) { super.drawRect(rect) let innerRect = CGRectInset(rect, trackBorderWidth, trackBorderWidth) internalProgress = (internalProgress/1.0) == 0.0 ? constants.minimumValue : progress internalProgress = (internalProgress/1.0) == 1.0 ? constants.maximumValue : internalProgress internalProgress = clockwise ? (-constants.twoSeventyDegrees + ((1.0 - internalProgress) * constants.circleDegress)) : (constants.ninetyDegrees - ((1.0 - internalProgress) * constants.circleDegress)) let context = UIGraphicsGetCurrentContext() // background Drawing trackBackgroundColor.setFill() let circlePath = UIBezierPath(ovalInRect: CGRectMake(innerRect.minX, innerRect.minY, CGRectGetWidth(innerRect), CGRectGetHeight(innerRect))) circlePath.fill(); if trackBorderWidth > 0 { circlePath.lineWidth = trackBorderWidth trackBorderColor.setStroke() circlePath.stroke() } // progress Drawing let progressPath = UIBezierPath() let progressRect: CGRect = CGRectMake(innerRect.minX, innerRect.minY, CGRectGetWidth(innerRect), CGRectGetHeight(innerRect)) let center = CGPointMake(progressRect.midX, progressRect.midY) let radius = progressRect.width / 2.0 let startAngle:CGFloat = clockwise ? CGFloat(-internalProgress * M_PI / 180.0) : CGFloat(constants.twoSeventyDegrees * M_PI / 180) let endAngle:CGFloat = clockwise ? CGFloat(constants.twoSeventyDegrees * M_PI / 180) : CGFloat(-internalProgress * M_PI / 180.0) progressPath.addArcWithCenter(center, radius:radius, startAngle:startAngle, endAngle:endAngle, clockwise:!clockwise) progressPath.addLineToPoint(CGPointMake(progressRect.midX, progressRect.midY)) progressPath.closePath() CGContextSaveGState(context) progressPath.addClip() if trackImage != nil { trackImage!.drawInRect(innerRect) } else { trackFillColor.setFill() circlePath.fill() } CGContextRestoreGState(context) // center Drawing let centerPath = UIBezierPath(ovalInRect: CGRectMake(innerRect.minX + trackWidth, innerRect.minY + trackWidth, CGRectGetWidth(innerRect) - (2 * trackWidth), CGRectGetHeight(innerRect) - (2 * trackWidth))) centerFillColor.setFill() centerPath.fill() if let centerImage = centerImage { CGContextSaveGState(context) centerPath.addClip() centerImage.drawInRect(rect) CGContextRestoreGState(context) } else { let layer = CAShapeLayer() layer.path = centerPath.CGPath contentView.layer.mask = layer } } }
mit
c6be17893141d86c672c834416c9ed88
33.452703
212
0.633458
5.160931
false
false
false
false
Onix-Systems/ios-mazazine-reader
Pods/PKHUD/PKHUD/PKHUDErrorView.swift
4
3113
// // PKHUDErrorAnimation.swift // PKHUD // // Created by Philip Kluz on 9/27/15. // Copyright (c) 2016 NSExceptional. All rights reserved. // Licensed under the MIT license. // import UIKit /// PKHUDErrorView provides an animated error (cross) view. open class PKHUDErrorView: PKHUDSquareBaseView, PKHUDAnimating { var dashOneLayer = PKHUDErrorView.generateDashLayer() var dashTwoLayer = PKHUDErrorView.generateDashLayer() class func generateDashLayer() -> CAShapeLayer { let dash = CAShapeLayer() dash.frame = CGRect(x: 0.0, y: 0.0, width: 88.0, height: 88.0) dash.path = { let path = UIBezierPath() path.move(to: CGPoint(x: 0.0, y: 44.0)) path.addLine(to: CGPoint(x: 88.0, y: 44.0)) return path.cgPath }() dash.lineCap = kCALineCapRound dash.lineJoin = kCALineJoinRound dash.fillColor = nil dash.strokeColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0).cgColor dash.lineWidth = 6 dash.fillMode = kCAFillModeForwards return dash } public init(title: String? = nil, subtitle: String? = nil) { super.init(title: title, subtitle: subtitle) layer.addSublayer(dashOneLayer) layer.addSublayer(dashTwoLayer) dashOneLayer.position = layer.position dashTwoLayer.position = layer.position } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.addSublayer(dashOneLayer) layer.addSublayer(dashTwoLayer) dashOneLayer.position = layer.position dashTwoLayer.position = layer.position } func rotationAnimation(_ angle: CGFloat) -> CABasicAnimation { var animation: CABasicAnimation if #available(iOS 9.0, *) { let springAnimation = CASpringAnimation(keyPath:"transform.rotation.z") springAnimation.damping = 1.5 springAnimation.mass = 0.22 springAnimation.initialVelocity = 0.5 animation = springAnimation } else { animation = CABasicAnimation(keyPath:"transform.rotation.z") } animation.fromValue = 0.0 animation.toValue = angle * CGFloat(M_PI / 180.0) animation.duration = 1.0 animation.timingFunction = CAMediaTimingFunction(name:kCAMediaTimingFunctionEaseInEaseOut) return animation } public func startAnimation() { let dashOneAnimation = rotationAnimation(-45.0) let dashTwoAnimation = rotationAnimation(45.0) dashOneLayer.transform = CATransform3DMakeRotation(-45 * CGFloat(M_PI/180), 0.0, 0.0, 1.0) dashTwoLayer.transform = CATransform3DMakeRotation(45 * CGFloat(M_PI/180), 0.0, 0.0, 1.0) dashOneLayer.add(dashOneAnimation, forKey: "dashOneAnimation") dashTwoLayer.add(dashTwoAnimation, forKey: "dashTwoAnimation") } public func stopAnimation() { dashOneLayer.removeAnimation(forKey: "dashOneAnimation") dashTwoLayer.removeAnimation(forKey: "dashTwoAnimation") } }
apache-2.0
39d53b3b2480002e416ddd78b48abfc2
35.197674
98
0.650819
4.18414
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/CountryCode.swift
1
10778
// // CountryCode.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// The code designating a country/region, which generally follows ISO 3166-1 /// alpha-2 guidelines. If a territory doesn't have a country code value in the /// `CountryCode` enum, then it might be considered a subdivision of another /// country. For example, the territories associated with Spain are represented /// by the country code `ES`, and the territories associated with the United /// States of America are represented by the country code `US`. public enum CountryCode: String { /// Ascension Island. case ac = "AC" /// Andorra. case ad = "AD" /// United Arab Emirates. case ae = "AE" /// Afghanistan. case af = "AF" /// Antigua & Barbuda. case ag = "AG" /// Anguilla. case ai = "AI" /// Albania. case al = "AL" /// Armenia. case am = "AM" /// Netherlands Antilles. case an = "AN" /// Angola. case ao = "AO" /// Argentina. case ar = "AR" /// Austria. case at = "AT" /// Australia. case au = "AU" /// Aruba. case aw = "AW" /// Åland Islands. case ax = "AX" /// Azerbaijan. case az = "AZ" /// Bosnia & Herzegovina. case ba = "BA" /// Barbados. case bb = "BB" /// Bangladesh. case bd = "BD" /// Belgium. case be = "BE" /// Burkina Faso. case bf = "BF" /// Bulgaria. case bg = "BG" /// Bahrain. case bh = "BH" /// Burundi. case bi = "BI" /// Benin. case bj = "BJ" /// St. Barthélemy. case bl = "BL" /// Bermuda. case bm = "BM" /// Brunei. case bn = "BN" /// Bolivia. case bo = "BO" /// Caribbean Netherlands. case bq = "BQ" /// Brazil. case br = "BR" /// Bahamas. case bs = "BS" /// Bhutan. case bt = "BT" /// Bouvet Island. case bv = "BV" /// Botswana. case bw = "BW" /// Belarus. case by = "BY" /// Belize. case bz = "BZ" /// Canada. case ca = "CA" /// Cocos (Keeling) Islands. case cc = "CC" /// Congo - Kinshasa. case cd = "CD" /// Central African Republic. case cf = "CF" /// Congo - Brazzaville. case cg = "CG" /// Switzerland. case ch = "CH" /// Côte d’Ivoire. case ci = "CI" /// Cook Islands. case ck = "CK" /// Chile. case cl = "CL" /// Cameroon. case cm = "CM" /// China. case cn = "CN" /// Colombia. case co = "CO" /// Costa Rica. case cr = "CR" /// Cuba. case cu = "CU" /// Cape Verde. case cv = "CV" /// Curaçao. case cw = "CW" /// Christmas Island. case cx = "CX" /// Cyprus. case cy = "CY" /// Czechia. case cz = "CZ" /// Germany. case de = "DE" /// Djibouti. case dj = "DJ" /// Denmark. case dk = "DK" /// Dominica. case dm = "DM" /// Dominican Republic. case `do` = "DO" /// Algeria. case dz = "DZ" /// Ecuador. case ec = "EC" /// Estonia. case ee = "EE" /// Egypt. case eg = "EG" /// Western Sahara. case eh = "EH" /// Eritrea. case er = "ER" /// Spain. case es = "ES" /// Ethiopia. case et = "ET" /// Finland. case fi = "FI" /// Fiji. case fj = "FJ" /// Falkland Islands. case fk = "FK" /// Faroe Islands. case fo = "FO" /// France. case fr = "FR" /// Gabon. case ga = "GA" /// United Kingdom. case gb = "GB" /// Grenada. case gd = "GD" /// Georgia. case ge = "GE" /// French Guiana. case gf = "GF" /// Guernsey. case gg = "GG" /// Ghana. case gh = "GH" /// Gibraltar. case gi = "GI" /// Greenland. case gl = "GL" /// Gambia. case gm = "GM" /// Guinea. case gn = "GN" /// Guadeloupe. case gp = "GP" /// Equatorial Guinea. case gq = "GQ" /// Greece. case gr = "GR" /// South Georgia & South Sandwich Islands. case gs = "GS" /// Guatemala. case gt = "GT" /// Guinea-Bissau. case gw = "GW" /// Guyana. case gy = "GY" /// Hong Kong SAR. case hk = "HK" /// Heard & McDonald Islands. case hm = "HM" /// Honduras. case hn = "HN" /// Croatia. case hr = "HR" /// Haiti. case ht = "HT" /// Hungary. case hu = "HU" /// Indonesia. case id = "ID" /// Ireland. case ie = "IE" /// Israel. case il = "IL" /// Isle of Man. case im = "IM" /// India. case `in` = "IN" /// British Indian Ocean Territory. case io = "IO" /// Iraq. case iq = "IQ" /// Iran. case ir = "IR" /// Iceland. case `is` = "IS" /// Italy. case it = "IT" /// Jersey. case je = "JE" /// Jamaica. case jm = "JM" /// Jordan. case jo = "JO" /// Japan. case jp = "JP" /// Kenya. case ke = "KE" /// Kyrgyzstan. case kg = "KG" /// Cambodia. case kh = "KH" /// Kiribati. case ki = "KI" /// Comoros. case km = "KM" /// St. Kitts & Nevis. case kn = "KN" /// North Korea. case kp = "KP" /// South Korea. case kr = "KR" /// Kuwait. case kw = "KW" /// Cayman Islands. case ky = "KY" /// Kazakhstan. case kz = "KZ" /// Laos. case la = "LA" /// Lebanon. case lb = "LB" /// St. Lucia. case lc = "LC" /// Liechtenstein. case li = "LI" /// Sri Lanka. case lk = "LK" /// Liberia. case lr = "LR" /// Lesotho. case ls = "LS" /// Lithuania. case lt = "LT" /// Luxembourg. case lu = "LU" /// Latvia. case lv = "LV" /// Libya. case ly = "LY" /// Morocco. case ma = "MA" /// Monaco. case mc = "MC" /// Moldova. case md = "MD" /// Montenegro. case me = "ME" /// St. Martin. case mf = "MF" /// Madagascar. case mg = "MG" /// North Macedonia. case mk = "MK" /// Mali. case ml = "ML" /// Myanmar (Burma). case mm = "MM" /// Mongolia. case mn = "MN" /// Macao SAR. case mo = "MO" /// Martinique. case mq = "MQ" /// Mauritania. case mr = "MR" /// Montserrat. case ms = "MS" /// Malta. case mt = "MT" /// Mauritius. case mu = "MU" /// Maldives. case mv = "MV" /// Malawi. case mw = "MW" /// Mexico. case mx = "MX" /// Malaysia. case my = "MY" /// Mozambique. case mz = "MZ" /// Namibia. case na = "NA" /// New Caledonia. case nc = "NC" /// Niger. case ne = "NE" /// Norfolk Island. case nf = "NF" /// Nigeria. case ng = "NG" /// Nicaragua. case ni = "NI" /// Netherlands. case nl = "NL" /// Norway. case no = "NO" /// Nepal. case np = "NP" /// Nauru. case nr = "NR" /// Niue. case nu = "NU" /// New Zealand. case nz = "NZ" /// Oman. case om = "OM" /// Panama. case pa = "PA" /// Peru. case pe = "PE" /// French Polynesia. case pf = "PF" /// Papua New Guinea. case pg = "PG" /// Philippines. case ph = "PH" /// Pakistan. case pk = "PK" /// Poland. case pl = "PL" /// St. Pierre & Miquelon. case pm = "PM" /// Pitcairn Islands. case pn = "PN" /// Palestinian Territories. case ps = "PS" /// Portugal. case pt = "PT" /// Paraguay. case py = "PY" /// Qatar. case qa = "QA" /// Réunion. case re = "RE" /// Romania. case ro = "RO" /// Serbia. case rs = "RS" /// Russia. case ru = "RU" /// Rwanda. case rw = "RW" /// Saudi Arabia. case sa = "SA" /// Solomon Islands. case sb = "SB" /// Seychelles. case sc = "SC" /// Sudan. case sd = "SD" /// Sweden. case se = "SE" /// Singapore. case sg = "SG" /// St. Helena. case sh = "SH" /// Slovenia. case si = "SI" /// Svalbard & Jan Mayen. case sj = "SJ" /// Slovakia. case sk = "SK" /// Sierra Leone. case sl = "SL" /// San Marino. case sm = "SM" /// Senegal. case sn = "SN" /// Somalia. case so = "SO" /// Suriname. case sr = "SR" /// South Sudan. case ss = "SS" /// São Tomé & Príncipe. case st = "ST" /// El Salvador. case sv = "SV" /// Sint Maarten. case sx = "SX" /// Syria. case sy = "SY" /// Eswatini. case sz = "SZ" /// Tristan da Cunha. case ta = "TA" /// Turks & Caicos Islands. case tc = "TC" /// Chad. case td = "TD" /// French Southern Territories. case tf = "TF" /// Togo. case tg = "TG" /// Thailand. case th = "TH" /// Tajikistan. case tj = "TJ" /// Tokelau. case tk = "TK" /// Timor-Leste. case tl = "TL" /// Turkmenistan. case tm = "TM" /// Tunisia. case tn = "TN" /// Tonga. case to = "TO" /// Turkey. case tr = "TR" /// Trinidad & Tobago. case tt = "TT" /// Tuvalu. case tv = "TV" /// Taiwan. case tw = "TW" /// Tanzania. case tz = "TZ" /// Ukraine. case ua = "UA" /// Uganda. case ug = "UG" /// U.S. Outlying Islands. case um = "UM" /// United States. case us = "US" /// Uruguay. case uy = "UY" /// Uzbekistan. case uz = "UZ" /// Vatican City. case va = "VA" /// St. Vincent & Grenadines. case vc = "VC" /// Venezuela. case ve = "VE" /// British Virgin Islands. case vg = "VG" /// Vietnam. case vn = "VN" /// Vanuatu. case vu = "VU" /// Wallis & Futuna. case wf = "WF" /// Samoa. case ws = "WS" /// Kosovo. case xk = "XK" /// Yemen. case ye = "YE" /// Mayotte. case yt = "YT" /// South Africa. case za = "ZA" /// Zambia. case zm = "ZM" /// Zimbabwe. case zw = "ZW" /// Unknown Region. case zz = "ZZ" case unknownValue = "" } }
mit
2756d708e2ea605be5c8e50ce1f64a90
12.912145
81
0.51198
2.567477
false
false
false
false
SSU-CS-Department/ssumobile-ios
SSUMobile/Modules/Maps/Outdoor/Model/Builders/SSUMapBuilder.swift
1
5660
// // SSUMapBuilder.swift // SSUMobile // // Created by Eric Amorde on 7/1/18. // Copyright © 2018 Sonoma State University Department of Computer Science. All rights reserved. // import Foundation import SwiftyJSON /** Provides helper functions accessible to Objective-C */ @objc class SSUMapBuilder: SSUMoonlightBuilder { @objc static func perimeterForBuilding(_ building: SSUBuilding, inContext context: NSManagedObjectContext) -> SSUMapBuildingPerimeter { let predicate = NSPredicate(format: "buildingID = %d", building.id) return SSUBuildingPerimetersBuilder.object(matchingPredicate: predicate, context: context) } @objc static func mapPointWithID(_ id: SSUMapPoint.IdentifierType, inContext context: NSManagedObjectContext) -> SSUMapPoint { return SSUPointsBuilder.object(id: id, context: context) } @objc static func perimeterExistsForBuilding(_ building: SSUBuilding, inContext context: NSManagedObjectContext) -> Bool { let predicate = NSPredicate(format: "buildingID = %d", building.id) let results = SSUBuildingPerimetersBuilder.allObjects(withEntityName: SSUBuildingPerimetersBuilder.entityName, matchingPredicate: predicate, context: context) return results.count > 0 } } class SSUPointsBuilder: SSUJSONEntityBuilder<SSUMapPoint> { override func didFinishBuilding(objects: [SSUMapPoint]) { super.didFinishBuilding(objects: objects) SSUConfiguration.instance.set(Date(), forKey: SSUMapPointsUpdatedDateKey) } } @objc class SSUConnectionsBuilder: SSUMoonlightBuilder { struct Keys { static let pointA = "point_a" static let pointB = "point_b" } override func buildJSON(_ json: JSON) { let connections: [JSON] = json.arrayValue guard connections.count > 0 else { return } let mapPoints: [SSUMapPoint] = SSUPointsBuilder.allObjects(context: context) let mapPointsById = [Int32:SSUMapPoint](uniqueKeysWithValues: mapPoints.map { ($0.id, $0) }) // Clear existing connections for point in mapPoints { if let pointConnections = point.connections { point.removeFromConnections(NSSet(set: pointConnections)) } } for connection in connections { let pointAId = connection[Keys.pointA].int32Value let pointBId = connection[Keys.pointB].int32Value let a: SSUMapPoint = mapPointsById[pointAId] ?? SSUPointsBuilder.object(id: pointAId, context: context) let b: SSUMapPoint = mapPointsById[pointBId] ?? SSUPointsBuilder.object(id: pointBId, context: context) a.addToConnections(b) b.addToConnections(a) } SSUConfiguration.instance.set(Date(), forKey: SSUMapPerimetersUpdatedDateKey) saveContext() } } class SSUBuildingPerimetersBuilder: SSUJSONEntityBuilder<SSUMapBuildingPerimeter> { typealias Keys = SSUMapBuildingPerimeter.Keys override func buildJSON(_ json: JSON) { let perimeters: [JSON] = json.arrayValue guard perimeters.count > 0 else { return } let directoryContext: NSManagedObjectContext = SSUDirectoryModule.instance.backgroundContext var perimetersByBuilding: [SSUBuilding.IdentifierType:[JSON]] = [:] for perimeterData in perimeters { let buildingId = perimeterData[Keys.buildingId].intValue if perimetersByBuilding[buildingId] == nil { perimetersByBuilding[buildingId] = [JSON]() } perimetersByBuilding[buildingId]?.append(perimeterData) } // Now sort the perimeters by their respective indices for buildingId in perimetersByBuilding.keys { let buildingPerimeters: [JSON] = perimetersByBuilding[buildingId]! let result = buildingPerimeters.sorted(by: { $0[Keys.index].intValue < $1[Keys.index].intValue }) perimetersByBuilding[buildingId] = result } var results: [SSUMapBuildingPerimeter] = [] for (buildingId, perimeterEntries) in perimetersByBuilding { var buildingName: String? directoryContext.performAndWait { let building = SSUBuildingBuilder.object(id: buildingId, context: directoryContext) buildingName = building.displayName } let perimeter: SSUMapBuildingPerimeter = SSUBuildingPerimetersBuilder.object(id: buildingId, context: context) let locations = NSMutableOrderedSet() for pointData: JSON in perimeterEntries { let pID = pointData[Keys.pointId].int32Value let point = SSUPointsBuilder.object(id: pID, context: self.context) locations.add(point) } perimeter.locations = locations perimeter.buildingName = buildingName perimeter.buildingID = buildingId results.append(perimeter) } // If a building has been deleted, we need to delete the perimeters for it let deletePredicate = NSPredicate(format: "NOT (buildingID in %@)", Array(perimetersByBuilding.keys)) SSUBuildingPerimetersBuilder.deleteObjects(matchingPredicate: deletePredicate, context: context) willFinishBuilding(objects: results) saveContext() didFinishBuilding(objects: results) SSUConfiguration.instance.set(Date(), forKey: SSUMapPerimetersUpdatedDateKey) } }
apache-2.0
16db34ba6a9d7ac52673a493da8c59f1
38.573427
166
0.662661
4.711907
false
false
false
false
WalterCreazyBear/Swifter30
ViewControllerTransitionDemo/ViewControllerTransitionDemo/NavigationTransitionManager.swift
1
3926
// // TransitionManager.swift // ViewControllerTransitionDemo // // Created by Bear on 2017/6/30. // Copyright © 2017年 Bear. All rights reserved. // import UIKit class NavigationPushTransitionManager :NSObject, UIViewControllerAnimatedTransitioning{ func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{ return 1.0 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning){ let container = transitionContext.containerView let vcTwo = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! as! ViewControllerTwo let vcOne = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! as! ViewController let vcTwoView = vcTwo.view let vcOneView = vcOne.view container.addSubview(vcTwoView!) container.bringSubview(toFront: vcOneView!) vcTwo.imageView.transform = CGAffineTransform(translationX: -400, y: 0) let duration = self.transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: [], animations: { vcOneView?.alpha = 0.0 vcOneView?.transform = CGAffineTransform(scaleX: 0.2, y: 0.2) vcTwoView?.alpha = 1.0 vcTwo.imageView.transform = CGAffineTransform.identity }, completion: { finished in vcOneView?.transform = CGAffineTransform(scaleX: 1, y: 1) vcOneView?.alpha = 1.0 transitionContext.completeTransition(true) }) } } class NavigationPopTransitionManager: NSObject,UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval{ return 1.0 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning){ let container = transitionContext.containerView let vcTwo = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! as! ViewControllerTwo let vcOne = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! as! ViewController let vcTwoView = vcTwo.view let vcOneView = vcOne.view container.addSubview(vcOneView!) container.bringSubview(toFront: vcTwoView!) let duration = self.transitionDuration(using: transitionContext) vcOne.button.transform = CGAffineTransform(translationX: 400, y: 0) UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: [], animations: { vcTwoView?.alpha = 0.0 vcTwoView?.transform = CGAffineTransform(scaleX: 0.2, y: 0.2) vcOneView?.alpha = 1.0 vcOne.button.transform = CGAffineTransform.identity }, completion: { finished in vcTwoView?.transform = CGAffineTransform(scaleX: 1, y: 1) vcTwoView?.alpha = 1.0 transitionContext.completeTransition(true) }) } } class NavigationTransitionManager:NSObject, UINavigationControllerDelegate{ func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if fromVC.isKind(of: ViewController.self) { return NavigationPushTransitionManager() } else { return NavigationPopTransitionManager() } } }
mit
2849c11bf615db9509efa14d30937fe7
37.460784
246
0.675758
5.612303
false
false
false
false
novastorm/Udacity-On-The-Map
On the Map/UdacityParseClientConvenience.swift
1
4359
// // UdacityParseClientConvenience.swift // On the Map // // Created by Adland Lee on 3/24/16. // Copyright © 2016 Adland Lee. All rights reserved. // import UIKit import Foundation // MARK: - UdacityParseClient (Convenient Resource Methods) extension UdacityParseClient { // MARK: - GET Convenience Methods func getStudentInformationList(_ completionHandler: @escaping (_ studentInformationList: [StudentInformation]?, _ error: NSError?) -> Void) { // (1) let parameters: [String: AnyObject] = [ ParameterKeys.Limit: ParameterValues.Limit as AnyObject, ParameterKeys.Order: ParameterValues.UpdatedAtDescending as AnyObject ] // (2) let _ = taskForGETMethod(Resources.ClassesStudentLocation, parameters: parameters) { (data, error) in // error function func sendError(_ code: Int, errorString:String) { var userInfo = [String: Any]() userInfo[NSLocalizedDescriptionKey] = errorString userInfo[NSUnderlyingErrorKey] = error completionHandler(nil, NSError(domain: "getStudentInformationList", code: code, userInfo: userInfo)) } // (3) if let error = error { if error.code == ErrorCodes.httpUnsucessful.rawValue { completionHandler(nil, NSError(domain: "getStudentInformationList", code: error.code, userInfo: error.userInfo)) } sendError(error.code, errorString: error.localizedDescription) return } let data = data as! [String: AnyObject] guard let responseResults = data[JSONResponseKeys.Results] as? [[String:AnyObject]] else { sendError(ErrorCodes.dataError.rawValue, errorString: "Could not find \(JSONResponseKeys.Results) in \(data)") return } var studentInformationList = [StudentInformation]() for record in responseResults { studentInformationList.append(StudentInformation(dictionary: record)) } StudentInformation.list = studentInformationList completionHandler(studentInformationList, nil) } } // MARK: - POST Convenience Methods func storeStudentInformation(_ student: StudentInformation, completionHandler: @escaping (_ success: Bool, _ error: NSError?) -> Void) { // 1 let parameters = [String:AnyObject]() let JSONBody: [String:AnyObject] = [ JSONParameterKeys.UniqueKey: student.uniqueKey! as AnyObject, JSONParameterKeys.FirstName: student.firstName! as AnyObject, JSONParameterKeys.LastName: student.lastName! as AnyObject, JSONParameterKeys.MapString: student.mapString! as AnyObject, JSONParameterKeys.MediaURL: student.mediaURL! as AnyObject, JSONParameterKeys.Latitude: student.latitude! as AnyObject, JSONParameterKeys.Longitude: student.longitude! as AnyObject ] // 2 let _ = taskForPOSTMethod(Resources.ClassesStudentLocation, parameters: parameters, JSONBody: JSONBody) { (results, error) in // Custom error function func sendError(_ code: Int, errorString:String) { var userInfo = [String: Any]() userInfo[NSLocalizedDescriptionKey] = errorString userInfo[NSUnderlyingErrorKey] = error completionHandler(false, NSError(domain: "storeStudentInformation", code: code, userInfo: userInfo)) } // (3) Send to completion handler if let error = error { if error.code == ErrorCodes.httpUnsucessful.rawValue { completionHandler(false, NSError(domain: "storeStudentInformation", code: error.code, userInfo: error.userInfo)) } sendError(error.code, errorString: error.localizedDescription) return } completionHandler(true, nil) } } // MARK: - DELETE Convenience Methods }
mit
497040a5c28ecb5f8e18a5bcd74c4d40
39.351852
145
0.594309
5.530457
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Controllers/Base/Containers/MyTBAContainerViewController.swift
1
1681
import CoreData import Foundation import MyTBAKit import TBAKit import UIKit class MyTBAContainerViewController: ContainerViewController, Subscribable { let myTBA: MyTBA lazy var favoriteBarButtonItem: UIBarButtonItem = { return UIBarButtonItem(image: UIImage.starIcon, style: .plain, target: self, action: #selector(myTBAPreferencesTapped)) }() var subscribableModel: MyTBASubscribable { fatalError("Implement subscribableModel in subclass") } // MARK: - Init init(viewControllers: [ContainableViewController], navigationTitle: String? = nil, navigationSubtitle: String? = nil, segmentedControlTitles: [String]? = nil, myTBA: MyTBA, dependencies: Dependencies) { self.myTBA = myTBA super.init(viewControllers: viewControllers, navigationTitle: navigationTitle, navigationSubtitle: navigationSubtitle, segmentedControlTitles: segmentedControlTitles, dependencies: dependencies) updateFavoriteButton() myTBA.authenticationProvider.add(observer: self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Interface Methods func updateFavoriteButton() { if myTBA.isAuthenticated { rightBarButtonItems = [favoriteBarButtonItem] } else { rightBarButtonItems = [] } } @objc func myTBAPreferencesTapped() { presentMyTBAPreferences() } } extension MyTBAContainerViewController: MyTBAAuthenticationObservable { func authenticated() { updateFavoriteButton() } func unauthenticated() { updateFavoriteButton() } }
mit
d7f731bc4a202f8483cd10f75d18a2d3
26.557377
207
0.704343
5.47557
false
false
false
false
topmonks/monk-saver
Monk/MainView.swift
1
2583
// // MainView.swift // Monk // // Created by Robert Vojta on 24.06.15. // Copyright © 2015 TopMonks, s.r.o. All rights reserved. // import Foundation import ScreenSaver import Cocoa /// /// Simple wrapper around `MonkView` in case you would like to test and /// debug it in application, because screen saver debugging is not so easy. /// class MainView: ScreenSaverView { // MARK: - Properties private var preferencesObserver: NSObjectProtocol? private var monkView: MonkView? { didSet { oldValue?.removeFromSuperview() guard let newView = self.monkView else { return } newView.autoresizingMask = [ NSAutoresizingMaskOptions.ViewHeightSizable, NSAutoresizingMaskOptions.ViewWidthSizable ] newView.frame = self.bounds self.addSubview(newView) } } let preferencesWindowController: PreferencesWindowController = { let controller = PreferencesWindowController() controller.loadWindow() return controller }() // MARK: - Initialization deinit { if let observer = self.preferencesObserver { NSNotificationCenter.defaultCenter().removeObserver(observer) } } override init?(frame: NSRect, isPreview: Bool) { super.init(frame: frame, isPreview:isPreview) self.registerObserver() self.reloadScene() } required init?(coder: NSCoder) { super.init(coder: coder) self.registerObserver() self.reloadScene() } private func registerObserver() { if let observer = self.preferencesObserver { NSNotificationCenter.defaultCenter().removeObserver(observer) } self.preferencesObserver = NSNotificationCenter.defaultCenter().addObserverForName(PreferencesDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { [weak self] (note) -> Void in self?.reloadScene() }) } private func reloadScene() { let preferences = MonkSettings.load() self.preferencesWindowController.preferencesModel = PreferencesModel() self.animationTimeInterval = preferences.animationTimeInterval let view = MonkView(frame: NSZeroRect) view.scene = preferences.generateScene() self.monkView = view } // MARK: - Animation override func animateOneFrame() { guard let monkView = self.monkView else { return } monkView.animateOneFrame() } // MARK: - Preferences override func hasConfigureSheet() -> Bool { return true } override func configureSheet() -> NSWindow? { return self.preferencesWindowController.window } }
mit
d8eefa5cb3ad17b7a85ab44b987451d1
25.618557
124
0.697521
4.618962
false
false
false
false
cotkjaer/Silverback
Silverback/Int.swift
1
7325
// // Int.swift // SilverbackFramework // // Created by Christian Otkjær on 20/04/15. // Copyright (c) 2015 Christian Otkjær. All rights reserved. // import Foundation public extension Int { /** Calls function self times. - parameter function: Function to call */ func times <T> (function: () -> T) -> Array<T> { return Array(0..<self).map { _ in return function() } } /** Calls function self times. - parameter function: Function to call */ func times (function: () -> ()) { for _ in (0..<self) { function() } } /** Calls function self times passing a value from 0 to self on each call. - parameter function: Function to call */ func times <T> (function: (Int) -> T) -> Array<T> { return Array(0..<self).map { function($0) } } /** Checks if a number is even. - returns: **true** if self is even */ var even: Bool { return (self % 2) == 0 } /** Checks if a number is odd. - returns: true if self is odd */ var odd: Bool { return !even } /** Iterates function, passing in integer values from self up to and including limit. - parameter limit: Last value to pass - parameter function: Function to invoke */ func upTo(limit: Int, @noescape function: (Int) -> ()) { self.stride(to: limit, by: 1).forEach { function($0) } } /** Iterates function, passing in integer values from self down to and including limit. - parameter limit: Last value to pass - parameter function: Function to invoke */ func downTo(limit: Int, function: (Int) -> ()) { if limit > self { return } for index in Array(Array(limit...self).reverse()) { function(index) } } /** Clamps self to a specified range. - parameter range: Clamping range - returns: Clamped value */ func clamp(range: Range<Int>) -> Int { return clamp(range.startIndex, range.endIndex - 1) } /** Clamps self to a specified range. - parameter lower: Lower bound (included) - parameter upper: Upper bound (included) - returns: Clamped value */ func clamp(lower: Int, _ upper: Int) -> Int { return Swift.max(lower, Swift.min(upper, self)) } /** Checks if self is included a specified range. - parameter range: Range - parameter string: If true, "<" is used for comparison - returns: true if in range */ func isIn(range: Range<Int>, strict: Bool = false) -> Bool { if strict { return range.startIndex < self && self < range.endIndex - 1 } return range.startIndex <= self && self <= range.endIndex - 1 } /** Checks if self is included in a closed interval. - parameter interval: Interval to check - returns: true if in the interval */ func isIn(interval: ClosedInterval<Int>) -> Bool { return interval.contains(self) } /** Checks if self is included in an half open interval. - parameter interval: Interval to check - returns: true if in the interval */ func isIn(interval: HalfOpenInterval<Int>) -> Bool { return interval.contains(self) } /** Returns an [Int] containing the digits in self. :return: Array of digits */ var digits: [Int] { var result = [Int]() for char in String(self).characters { let string = String(char) if let toInt = Int(string) { result.append(toInt) } } return result } /** Absolute value. - returns: abs(self) */ var abs: Int { return Swift.abs(self) } /** Calculates greatest common divisor (GCD) of self and n. - parameter n: - returns: Greatest common divisor */ func gcd(n: Int) -> Int { return n == 0 ? self : n.gcd(self % n) } /** Calculates least common multiple (LCM) of self and n - parameter n: - returns: Least common multiple */ func lcm(n: Int) -> Int { return (self * n).abs / gcd(n) } /** Computes the factorial of self - returns: Factorial */ var factorial: Int { return self == 0 ? 1 : self * (self - 1).factorial } } public extension Int { public func format(format: String? = "") -> String { return String(format: "%\(format)d", self) } } // MARK: - Primes let SomeSafePrimes = [5, 7, 11, 23, 47, 59, 83, 107, 167, 179, 227, 263, 347, 359, 383, 467, 479, 503, 563, 587, 719, 839, 863, 887, 983, 1019, 1187, 1283, 1307, 1319, 1367, 1439, 1487, 1523, 1619, 1823, 1907] let PrimesLessThan1000 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997] extension Int { var prime : Bool { if self <= 1 { return false } else if self <= 3 { return true } else if self % 2 == 0 { return false } else if self % 3 == 0 { return false } for var i = 5 ; i * i < self; i += 6 { if self % i == 0 { return false } if self % (i + 2) == 0 { return false } } return true } } /** NSTimeInterval conversion extensions */ public extension Int { var years: NSTimeInterval { return 365 * self.days } var year: NSTimeInterval { return self.years } var weeks: NSTimeInterval { return 7 * self.days } var week: NSTimeInterval { return self.weeks } var days: NSTimeInterval { return 24 * self.hours } var day: NSTimeInterval { return self.days } var hours: NSTimeInterval { return 60 * self.minutes } var hour: NSTimeInterval { return self.hours } var minutes: NSTimeInterval { return 60 * self.seconds } var minute: NSTimeInterval { return self.minutes } var seconds: NSTimeInterval { return NSTimeInterval(self) } var second: NSTimeInterval { return self.seconds } }
mit
65893cda955c86196fcc2a74aadd286f
23.328904
836
0.529974
3.822025
false
false
false
false
alexmx/Insider
Insider/LocalWebServerResponse.swift
1
626
// // LocalWebServerResponse.swift // Insider // // Created by Alexandru Maimescu on 2/19/16. // Copyright © 2016 Alex Maimescu. All rights reserved. // import Foundation enum LocalWebServerResponseStatusCode: Int { case success = 200 case notFound = 404 } final class LocalWebServerResponse { var statusCode: LocalWebServerResponseStatusCode var response: InsiderMessage? init(statusCode: LocalWebServerResponseStatusCode) { self.statusCode = statusCode } init(response: InsiderMessage?) { self.statusCode = .success self.response = response } }
mit
c1f4de34ea9515f8dd44c75495b84336
20.551724
56
0.6912
4.340278
false
false
false
false
Zglove/DouYu
DYTV/DYTV/Classes/Home/View/CollectionGameCell.swift
1
1265
// // CollectionGameCell.swift // DYTV // // Created by people on 2016/11/7. // Copyright © 2016年 people2000. All rights reserved. // import UIKit import Kingfisher class CollectionGameCell: UICollectionViewCell { //MARK:- 控件属性 @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! //MARK:- 定义模型属性 var baseGame: BaseGameModel? { didSet{ titleLabel.text = baseGame?.tag_name if baseGame?.icon_url == "" {//“更多” iconImageView.image = UIImage(named: "home_more_btn") }else{ let iconURL = URL(string: (baseGame?.icon_url)!) let resource = ImageResource.init(downloadURL: iconURL!) /* 这里Resource直接填iconURL也可以 iconImageView.kf.setImage(with: iconURL, placeholder: UIImage(named: "home_more_btn")) */ iconImageView.kf.setImage(with: resource, placeholder: UIImage(named: "home_more_btn")) } } } //MARK:- 系统回调 override func awakeFromNib() { super.awakeFromNib() } }
mit
2b87af8f8c47372f824818aa5599971d
25.888889
103
0.547934
4.801587
false
false
false
false
awsdocs/aws-doc-sdk-examples
swift/example_code/iam/CreateServiceLinkedRole/Tests/CreateServiceLinkedRoleTests/ServiceHandler_Ext.swift
1
2528
/* Extensions to the `ServiceHandler` class to handle tasks we need for testing that aren't the purpose of this example. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ import Foundation import AWSIAM import AWSClientRuntime import ClientRuntime import SwiftUtilities @testable import ServiceHandler public extension ServiceHandler { /// Get the ID of an AWS Identity and Access Management (IAM) role. /// /// - Parameter name: The name of the IAM role. /// /// - Returns: A `String` containing the role's ID. func getRoleID(name: String) async throws -> String { let input = GetRoleInput( roleName: name ) do { let output = try await client.getRole(input: input) guard let role = output.role, let id = role.roleId else { throw ServiceHandlerError.noSuchRole } return id } catch { throw error } } /// Delete an IAM role. /// /// - Parameter name: The name of the IAM role to delete. func deleteRole(name: String) async throws { let input = DeleteRoleInput( roleName: name ) do { _ = try await client.deleteRole(input: input) } catch { throw error } } /// Delete a service-linked role, given its name. /// /// - Parameter name: The name of the service-linked role to delete. func deleteServiceLinkedRole(name: String) async throws { let input = DeleteServiceLinkedRoleInput( roleName: name ) do { _ = try await client.deleteServiceLinkedRole(input: input) } catch { throw error } } /// Get information about the specified user. /// /// - Parameter name: A `String` giving the name of the user to get. If /// this parameter is `nil`, the default user's information is returned. /// - Returns: An `IamClientTypes.User` record describing the user. func getUser(name: String?) async throws -> IamClientTypes.User { let input = GetUserInput( userName: name ) do { let output = try await client.getUser(input: input) guard let user = output.user else { throw ServiceHandlerError.noSuchUser } return user } catch { throw error } } }
apache-2.0
1a4f6cd2192f59de124485b0df97b73a
27.41573
78
0.581092
4.613139
false
false
false
false
24/ios-o2o-c
gxc/Model/GX_ShopNewOrder.swift
1
3425
// // GX_ShopOrder.swift // gxc // // Created by gx on 14/11/24. // Copyright (c) 2014年 zheng. All rights reserved. // import Foundation class GX_ShopNewOrder :Deserializable{ var code: Int? var message: String? var shopOrderdata:ShopOrderdata? var page: String? var foot :Foot? required init(data: [String : AnyObject]) { code <<< data["code"] shopOrderdata <<<< data["data"] message <<< data["message"] foot <<<< data["foot"] page <<< data["page"] } } class ShopOrderdata :Deserializable { var addressMsg :AddressMsg? var orderTimes :[OrderTimes]? var cmmunitys :[String]? var isServer :Int? var shopId: Int? required init(data: [String : AnyObject]) { addressMsg <<<< data["Address"] orderTimes <<<<* data["OrderTimes"] cmmunitys <<<* data["Communitys"] isServer <<< data["IsServer"] shopId <<< data["ShopId"] } } class AddressMsg :Deserializable{ var UserAddressId: String? var UserCommunity: String? var UserName: String? var UserPhone: String? var UserRoomNo: String? required init(data: [String : AnyObject]) { UserAddressId <<< data["UserAddressId"] UserCommunity <<< data["UserCommunity"] UserName <<< data["UserName"] UserPhone <<< data["UserPhone"] UserRoomNo <<< data["UserRoomNo"] } } class OrderTimes : Deserializable{ var Date: String? var DateTime: String? var Tip: String? required init(data: [String : AnyObject]) { Date <<< data["Date"] DateTime <<< data["DateTime"] Tip <<< data["Tip"] } } // //{ // code = 200; // data = { // Address = { // UserAddressId = 0d57ffb29ba84c34be5317b6d7de2e8c; // UserCommunity = ""; // UserName = 55555; // UserPhone = 110; // UserRoomNo = 555555; // }; // Communitys = ( // ); // IsServer = 1; // OrderTimes = ( // { // Date = "2014-11-25"; // DateTime = "2014-11-25 10:00"; // Tip = "10:00-11:00"; // }, // { // Date = "2014-11-26"; // DateTime = "2014-11-26 10:00"; // Tip = "10:00-11:00"; // }, // { // Date = "2014-11-27"; // DateTime = "2014-11-27 10:00"; // Tip = "10:00-11:00"; // }, // { // Date = "2014-11-28"; // DateTime = "2014-11-28 10:00"; // Tip = "10:00-11:00"; // }, // { // Date = "2014-11-29"; // DateTime = "2014-11-29 10:00"; // Tip = "10:00-11:00"; // }, // { // Date = "2014-11-30"; // DateTime = "2014-11-30 10:00"; // Tip = "10:00-11:00"; // }, // { // Date = "2014-12-01"; // DateTime = "2014-12-01 10:00"; // Tip = "10:00-11:00"; // } // ); // ShopId = 57883769; // }; // foot = { // operationTime = "2014-11-24 23:52:12"; // servicePhone = "110"; // }; // message = ""; // page = "<null>"; //}
mit
9bc8234d716f2e5f0cd53cda6b08a1e3
24.544776
63
0.442886
3.485743
false
false
false
false
Rep2/IRSocket
SimpleSocketExample/SimpleSocketExample/IRSocket/IRSocket.swift
1
1813
// // IRSocket.swift // RASUSLabos // // Created by Rep on 12/14/15. // Copyright © 2015 Rep. All rights reserved. // import Foundation enum IRSocketError: ErrorType{ case BindFailed(error: Int32) case CloseFailed(error: Int32) case GetNameFailed(error: Int32) } /// Basic C socket binding class IRSocket{ /// C socket let cSocket:Int32 /// Creates new instance of IRSocket containing C socket /// - Returns: IRSocket nil if creation fails init?(domain:Int32, type:Int32, proto:Int32){ cSocket = socket(domain, type, proto) if cSocket == -1{ return nil } } /// Binds socket to addres and updates address /// - Parameter addr: Binding address /// - Parameter update: If set updates addr fields /// /// - Throws: IRSocketError func bind(addr:IRSockaddr, update:Bool = true) throws{ let bindRet = withUnsafePointer(&addr.cSockaddr) { Darwin.bind(cSocket, UnsafePointer<sockaddr>($0), 16) } if bindRet != 0{ throw IRSocketError.BindFailed(error: bindRet) } if update{ try getName(addr) } } /// Updates addr to correct value /// - Parameter addr: Binding address /// /// - Throws: IRSocketError func getName(addr:IRSockaddr) throws{ var src_addr_len = socklen_t(sizeofValue(socket)) let err = withUnsafePointer(&addr.cSockaddr) { return getsockname(self.cSocket, UnsafeMutablePointer($0), &src_addr_len) } if err == -1{ throw IRSocketError.GetNameFailed(error: err) } } /// Closes socket deinit{ close(cSocket) } }
mit
8bf37a1627f64918a753a0387605cfa9
22.24359
85
0.568985
4.204176
false
false
false
false
punty/FPActivityIndicator
FPActivityLoaderDemo/FPActivityLoaderDemo/FPActivityLoader.swift
1
5331
// // FPActivityLoader.swift // FPActivityLoader // // Created by Francesco Puntillo on 04/04/2016. // Copyright © 2016 Francesco Puntillo. All rights reserved. // import UIKit @IBDesignable class FPActivityLoader: UIView { static let defaultColor = UIColor.black static let defaultLineWidth: CGFloat = 2.0 static let defaultCircleTime: Double = 1.5 fileprivate var circleLayer: CAShapeLayer = CAShapeLayer() @IBInspectable var strokeColor: UIColor = UIColor.black { didSet { circleLayer.strokeColor = strokeColor.cgColor } } @IBInspectable var animating: Bool = true { didSet { updateAnimation() } } @IBInspectable var hideWhenNotAnimating: Bool = true { didSet { isHidden = (hideWhenNotAnimating) && (!animating) } } @IBInspectable var lineWidth: CGFloat = CGFloat(2) { didSet { circleLayer.lineWidth = lineWidth } } fileprivate func pauseLayer(_ layer: CALayer) { let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil) layer.speed = 0 layer.timeOffset = pausedTime } fileprivate func resumeLayer(_ layer: CALayer) { let pausedTime = layer.timeOffset layer.speed = 1 layer.timeOffset = 0 layer.beginTime = 0 let timeSincePaused = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime layer.beginTime = timeSincePaused } @IBInspectable var circleTime: Double = 1.5 { didSet { circleLayer.add(generateAnimation(), forKey: "strokeLineAnimation") circleLayer.add(generateRotationAnimation(), forKey: "rotationAnimation") updateAnimation() } } //init methods override init(frame: CGRect) { lineWidth = FPActivityLoader.defaultLineWidth circleTime = FPActivityLoader.defaultCircleTime strokeColor = FPActivityLoader.defaultColor super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { lineWidth = FPActivityLoader.defaultLineWidth circleTime = FPActivityLoader.defaultCircleTime strokeColor = FPActivityLoader.defaultColor super.init(coder: aDecoder) setupView() } convenience init() { self.init(frame: CGRect.zero) lineWidth = FPActivityLoader.defaultLineWidth circleTime = FPActivityLoader.defaultCircleTime strokeColor = FPActivityLoader.defaultColor setupView() } func generateAnimation() -> CAAnimationGroup { let headAnimation = CABasicAnimation(keyPath: "strokeStart") headAnimation.beginTime = self.circleTime/3.0 headAnimation.fromValue = 0 headAnimation.toValue = 1 headAnimation.duration = self.circleTime/1.5 headAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let tailAnimation = CABasicAnimation(keyPath: "strokeEnd") tailAnimation.fromValue = 0 tailAnimation.toValue = 1 tailAnimation.duration = self.circleTime/1.5 tailAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) let groupAnimation = CAAnimationGroup() groupAnimation.duration = self.circleTime groupAnimation.repeatCount = Float.infinity groupAnimation.animations = [headAnimation, tailAnimation] return groupAnimation } func generateRotationAnimation() -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "transform.rotation") animation.fromValue = 0 animation.toValue = 2*M_PI animation.duration = self.circleTime animation.repeatCount = Float.infinity return animation } func setupView() { layer.addSublayer(self.circleLayer) backgroundColor = UIColor.clear circleLayer.fillColor = nil circleLayer.lineWidth = lineWidth circleLayer.lineCap = kCALineCapRound circleLayer.strokeColor = strokeColor.cgColor circleLayer.add(generateAnimation(), forKey: "strokeLineAnimation") circleLayer.add(generateRotationAnimation(), forKey: "rotationAnimation") } override func layoutSubviews() { super.layoutSubviews() let center = CGPoint(x: bounds.size.width/2.0, y: bounds.size.height/2.0) let radius = min(bounds.size.width, bounds.size.height)/2.0 - circleLayer.lineWidth/2.0 let endAngle = CGFloat(2*M_PI) let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true) circleLayer.path = path.cgPath circleLayer.frame = bounds } func updateAnimation() { isHidden = (hideWhenNotAnimating) && (!animating) if animating { resumeLayer(circleLayer) } else { pauseLayer(circleLayer) } } override func prepareForInterfaceBuilder() { setupView() } deinit { circleLayer.removeAllAnimations() circleLayer.removeFromSuperlayer() } }
mit
f04c7f468aeb6c246eb0a1cca0c8e23d
30.352941
118
0.645028
5.272008
false
false
false
false
at-internet/atinternet-ios-swift-sdk
Tracker/Tracker/CustomTreeStructure.swift
1
3318
/* This SDK is licensed under the MIT license (MIT) Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France) 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. */ // // CustomTreeStructure.swift // Tracker // import UIKit public class CustomTreeStructure: ScreenInfo { /// Custom tree structure first category label public var category1: Int = 0 /// Custom tree structure first category label public var category2: Int = 0 /// Custom tree structure first category label public var category3: Int = 0 /// Set parameters in buffer override func setEvent() { _ = tracker.setParam("ptype", value: String(format: "%d-%d-%d", category1, category2, category3)) } } public class CustomTreeStructures { /// Tracker instance var tracker: Tracker /** CustomTreeStructures initializer - parameter tracker: the tracker instance - returns: CustomTreeStructures instance */ init(tracker: Tracker) { self.tracker = tracker; } /** Add a custom tree structure info to screen hit - parameter category1: category1 label - returns: CustomTreeStructure instance */ public func add(_ category1: Int) -> CustomTreeStructure { let cts = CustomTreeStructure(tracker: tracker) cts.category1 = category1 tracker.businessObjects[cts.id] = cts return cts } /** Add a custom tree structure info to screen hit - parameter category1: category1 label - parameter category2: category2 label - returns: CustomTreeStructure instance */ public func add(_ category1: Int, category2: Int) -> CustomTreeStructure { let cts = add(category1) cts.category2 = category2 return cts } /** Add a custom tree structure info to screen hit - parameter category1: category1 label - parameter category2: category2 label - parameter category3: category3 label - returns: CustomTreeStructure instance */ public func add(_ category1: Int, category2: Int, category3: Int) -> CustomTreeStructure { let cts = add(category1, category2: category2) cts.category3 = category3 return cts } }
mit
e1369f122fe1ddfc9667c887a9bb11e1
31.831683
141
0.703257
4.631285
false
false
false
false
bryansum/LDL
LDL/AppDelegate.swift
1
2685
// // AppDelegate.swift // LDL // // Created by Bryan Summersett on 12/9/16. // Copyright © 2016 Bryan Summersett. All rights reserved. // import AVFoundation import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let audioSession = AVAudioSession.sharedInstance() try! audioSession.setCategory(AVAudioSessionCategoryPlayback) application.beginReceivingRemoteControlEvents() let navigationController = UINavigationController(rootViewController: StoriesViewController()) audioPlayer.autoresizingMask = .flexibleWidth audioPlayer.frame = navigationController.toolbar.bounds let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = navigationController window.makeKeyAndVisible() self.window = window // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
0fa167ff7b321ca7f5cf4f3f3b3a4c91
43
281
0.780551
5.638655
false
false
false
false
skyfe79/RxPlayground
RxToDoList-MVVM/Pods/RxCocoa/RxCocoa/iOS/UIImageView+Rx.swift
25
1716
// // UIImageView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/1/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit extension UIImageView { /** Bindable sink for `image` property. */ public var rx_image: AnyObserver<UIImage?> { return self.rx_imageAnimated(nil) } /** Bindable sink for `image` property. - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...) */ public func rx_imageAnimated(transitionType: String?) -> AnyObserver<UIImage?> { return AnyObserver { [weak self] event in MainScheduler.ensureExecutingOnScheduler() switch event { case .Next(let value): if let transitionType = transitionType { if value != nil { let transition = CATransition() transition.duration = 0.25 transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = transitionType self?.layer.addAnimation(transition, forKey: kCATransition) } } else { self?.layer.removeAllAnimations() } self?.image = value case .Error(let error): bindingErrorToInterface(error) break case .Completed: break } } } } #endif
mit
981b135c5bdd7eb43001e166340c729a
27.114754
126
0.546939
5.410095
false
false
false
false
ManuelAurora/RxQuickbooksService
RxQuickbooksService/Classes/QBService + QBNetworkRouter.swift
1
4222
import Alamofire import Foundation import RxSwift import RxAlamofire import OAuthSwift import OAuthSwiftAlamofire import SwiftyJSON extension QBService { enum NetworkRouter { fileprivate static let baseUrl = "https://quickbooks.api.intuit.com/v3/company/" fileprivate static let sandboxUrl = "https://sandbox-quickbooks.api.intuit.com/v3/company/" fileprivate static let bag = DisposeBag() case authorization(handler: OAuthSwiftURLHandlerType) case query(QBQueryRequest) case report(QBReportRequest) static private(set) var oauthswiftParameters: OauthParameters! private static var sessionManager: SessionManager = { let sm = SessionManager() sm.adapter = oauthswift.requestAdapter return sm }() static var oauthswift: OAuth1Swift = { let oauthswift = OAuth1Swift( consumerKey: oauthswiftParameters.consumerKey, consumerSecret: oauthswiftParameters.consumerSecret, requestTokenUrl: oauthswiftParameters.requestTokenUrl, authorizeUrl: oauthswiftParameters.authorizeUrl, accessTokenUrl: oauthswiftParameters.accessTokenUrl ) return oauthswift }() static var realmId: String? private var pathComponent: String { switch self { case .report(let report): return "reports/\(report.stringRepresentation())" case .query: return "query" case .authorization: return "" } } private var parameters: Parameters { var parametersToReturn = Parameters() switch self { case .authorization: break case .query(let queryString): parametersToReturn["query"] = queryString.stringRepresentation() case .report(let reportRequest): parametersToReturn["date_macro"] = reportRequest.periodStringRepresentation() } return parametersToReturn } private var headers: HTTPHeaders { return ["Accept":"application/json"] } static func set(oauthParameters: OauthParameters) { oauthswiftParameters = oauthParameters } func makeRequest() -> Observable<JSON> { guard var mutableUrl = URL(string: NetworkRouter.baseUrl) else { fatalError("Unable to create url") } if let realmId = NetworkRouter.realmId { mutableUrl.appendPathComponent(realmId) } mutableUrl.appendPathComponent(pathComponent) switch self { case .authorization(let handler): let oauthswift = NetworkRouter.oauthswift oauthswift.authorizeURLHandler = handler guard let callbackUrl = NetworkRouter.oauthswiftParameters.callbackUrl else { fatalError("There is no callback url") } return oauthswift.rx_authorize(withCallbackURL: callbackUrl) .map { _, _, parameters in JSON(parameters) } case .query: guard let _ = NetworkRouter.realmId else { fatalError("No realm Id found") } case .report: guard let _ = NetworkRouter.realmId else { fatalError("No realm Id found") } } let requestObservable = NetworkRouter.sessionManager.rx.responseJSON(.get, mutableUrl, parameters: parameters, headers: headers) return requestObservable.map { return JSON(object: $0.1) } } } }
mit
2c145b2321b72364aa577e8c99b0c8ac
37.381818
122
0.532212
6.320359
false
false
false
false
wordlesser/AutoLayout
CQAutoLayout/UIView_AutoLayout.swift
1
12108
// // CQView.swift // CQAutolayout // // Created by Y_CQ on 2017/7/22. // Copyright © 2017年 YCQ. All rights reserved. // import Foundation import UIKit private var xoAssociationKey1: UInt8 = 12 private var xoAssociationKey2: UInt8 = 11 extension UIView { /// Add an additional attribute to store some info var _model: [String: Any]? { get { return objc_getAssociatedObject(self, &xoAssociationKey2) as? [String: Any] } set(newValue) { objc_setAssociatedObject(self, &xoAssociationKey2, newValue,objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } } /// store layout info private var _constraints: [String: NSLayoutConstraint]? { get { return objc_getAssociatedObject(self, &xoAssociationKey1) as? [String: NSLayoutConstraint] } set(newValue) { objc_setAssociatedObject(self, &xoAssociationKey1, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } } // MARK: You can also extend other views if needed /// Add a view /// /// - Returns: view func createSubView()->UIView { let v = UIView() v.translatesAutoresizingMaskIntoConstraints = false v.isOpaque = true self.addSubview(v) return v } func createSubButton()->UIButton { let b = UIButton() b.translatesAutoresizingMaskIntoConstraints = false b.isOpaque = true self.addSubview(b) return b } func createSubLabel()->UILabel { let lb = UILabel() lb.translatesAutoresizingMaskIntoConstraints = false lb.isOpaque = true self.addSubview(lb) return lb } func createSubImageView()-> UIImageView { let iv = UIImageView() iv.translatesAutoresizingMaskIntoConstraints = false iv.isOpaque = true self.addSubview(iv) return iv } func createSubTextView()-> UITextView { let tv = UITextView() tv.translatesAutoresizingMaskIntoConstraints = false self.addSubview(tv) return tv } func createSubTextField()-> UITextField { let tf = UITextField() tf.translatesAutoresizingMaskIntoConstraints = false self.addSubview(tf) return tf } func createSubScrollView()-> UIScrollView { let scv = UIScrollView() scv.translatesAutoresizingMaskIntoConstraints = false self.addSubview(scv) return scv } /// top layout /// /// - Parameters: /// - value: distance /// - toItem: distance from the target view /// - Returns: self @discardableResult func top(_ value: CGFloat, toItem: UIView?=nil)->UIView { if toItem == nil { if !checkAndModify("top", value: value) { let constraint = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: self.superview, attribute: .top, multiplier: 1.0, constant: value ) self._addSaveContraint("top", constraint: constraint) } } else { if !checkAndModify("top:", value: -value) { let constraint = NSLayoutConstraint( item: self, attribute: .bottom, relatedBy: .equal, toItem: toItem, attribute: .top, multiplier: 1.0, constant: -value ) self._addSaveContraint("top:", constraint: constraint) } } return self } /// bottom layout /// /// - Parameters: /// - value: distance /// - toItem: distance from the target view(if 'toItem' is nil, default is superView) /// - Returns: self @discardableResult func bottom(_ value: CGFloat, toItem: UIView?=nil) -> UIView { if toItem == nil { if !checkAndModify("bottom", value: -value) { let constraint = NSLayoutConstraint( item: self, attribute: .bottom, relatedBy: .equal, toItem: self.superview, attribute: .bottom, multiplier: 1.0, constant: -value ) self._addSaveContraint("bottom", constraint: constraint) } } else { if !checkAndModify("bottom:", value: value) { let constraint = NSLayoutConstraint( item: self, attribute: .top, relatedBy: .equal, toItem: toItem, attribute: .bottom, multiplier: 1.0, constant: value ) self._addSaveContraint("bottom:", constraint: constraint) } } return self } /// left layout /// /// - Parameters: /// - value: distance /// - toItem: distance from the target view /// - Returns: self @discardableResult func left(_ value: CGFloat, toItem: UIView?=nil)->UIView { if toItem == nil { if !checkAndModify("left", value: value) { let constraint = NSLayoutConstraint( item: self, attribute: .left, relatedBy: .equal, toItem: self.superview, attribute: .left, multiplier: 1.0, constant: value ) self._addSaveContraint("left", constraint: constraint) } } else { if !checkAndModify("left:", value: -value) { let constraint = NSLayoutConstraint( item: self, attribute: .right, relatedBy: .equal, toItem: toItem, attribute: .left, multiplier: 1.0, constant: -value ) self._addSaveContraint("top:CGFloat", constraint: constraint) } } return self } /// right layout /// /// - Parameters: /// - value: distance /// - toItem: distance from the target view /// - Returns: self @discardableResult func right(_ value: CGFloat, toItem: UIView?=nil) -> UIView { if toItem == nil { if !checkAndModify("right", value: -value) { let constraint = NSLayoutConstraint( item: self, attribute: .right, relatedBy: .equal, toItem: self.superview, attribute: .right, multiplier: 1.0, constant: -value ) self._addSaveContraint("right", constraint: constraint) } } else { if !checkAndModify("right:", value: value) { let constraint = NSLayoutConstraint( item: self, attribute: .left, relatedBy: .equal, toItem: toItem, attribute: .right, multiplier: 1.0, constant: value ) self._addSaveContraint("right:", constraint: constraint) } } return self } /// width layout /// /// - Parameter width: distance /// - Returns: self @discardableResult func width(_ width: CGFloat)->UIView { if !checkAndModify("width", value: width) { let constraint = NSLayoutConstraint( item: self, attribute: .width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: width ) self._addSaveContraint("width", constraint: constraint) } return self } /// height layout /// /// - Parameter width: distance /// - Returns: self @discardableResult func height(_ height: CGFloat) -> UIView { if !checkAndModify("height", value: height) { let constraint = NSLayoutConstraint( item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: height ) self._addSaveContraint("height", constraint: constraint) } return self } /// center.x layout /// /// - Returns: self @discardableResult func centerX() -> UIView { let constraint = NSLayoutConstraint( item: self, attribute: .centerX, relatedBy: .equal, toItem: self.superview, attribute: .centerX, multiplier: 1.0, constant: 0 ) self.addConstraintByType("centerX", constraint: constraint) return self } /// center.y layout /// /// - Returns: self @discardableResult func centerY() -> UIView { let constraint = NSLayoutConstraint( item: self, attribute: .centerY, relatedBy: .equal, toItem: self.superview, attribute: .centerY, multiplier: 1.0, constant: 0 ) self.addConstraintByType("centerY", constraint: constraint) return self } /// clear layout /// /// - Parameter type: remove a layout fileprivate func _clearSaveContraint(_ type: String) { if self._constraints?[type] != nil { let con = self._constraints![type]! self.superview?.removeConstraint(con) } } /// add layout /// /// - Parameters: /// - type: layout of type /// - constraint: layout fileprivate func _addSaveContraint(_ type: String, constraint: NSLayoutConstraint) { var cons = self._constraints ?? [:] cons[type] = constraint self._constraints = cons constraint.priority = 999 self.superview?.addConstraint(constraint) } /// add a layout /// /// - Parameters: /// - type: type of layout /// - constraint: layout fileprivate func addConstraintByType(_ type: String, constraint: NSLayoutConstraint) { //clear first self._clearSaveContraint(type) // then add self._addSaveContraint(type, constraint: constraint) } /// check if it's already owned and then if has midify it /// /// - Parameters: /// - type: type of layout /// - value: modify value /// - Returns: Is it already owned fileprivate func checkAndModify(_ type: String, value: CGFloat) -> Bool { //这里的逻辑是 看看 这个约束是不是已经有了. 如果已经有了, 就只修改const //这样的性能会好些 let con = self._constraints?[type] if con != nil { con!.constant = value return true } return false } /// clear a layout /// /// - Parameter type: type of clean func clear(_ type: String) { let constraint = self._constraints?[type] if constraint != nil { self.superview?.removeConstraint(constraint!) } } /// clear all layout func clearAll() { if self._constraints == nil || self._constraints?.count == 0 { return } for (_, value) in self._constraints! { self.superview?.removeConstraint(value) } } }
apache-2.0
23b29f65833c9da64a3b5adb67ea5648
28.779703
118
0.504447
5.208225
false
false
false
false
psoamusic/PourOver
PourOver/POMainTableViewController.swift
1
6980
// // POMainTableViewController.swift // PourOver // // Created by kevin on 6/19/16. // Copyright © 2016 labuser. All rights reserved. // import UIKit class POMainTableViewController: POTableViewController { //=================================================================================== //MARK: Private Properties //=================================================================================== private var selectedIndexPath: NSIndexPath? private lazy var presetTableViewController: POPresetsTableViewController = { return POPresetsTableViewController() }() private lazy var userDocumentsTableViewController: POUserDocumentsTableViewController = { return POUserDocumentsTableViewController() }() private lazy var googleDriveTableViewController: POGoogleDriveTableViewController = { return POGoogleDriveTableViewController() }() private lazy var settingsTableViewController: POSettingsTableViewController = { return POSettingsTableViewController() }() private let kPresetsTitle = "Presets" private let kUserDocumentsTitle = "User Documents" private let kGoogleDriveTitle = "Google Drive" private let kSettingsTitle = "Settings" //=================================================================================== //MARK: Lifecycle //=================================================================================== override func viewDidLoad() { super.viewDidLoad() scrollViewContentOffsetStart = 0 let coffeeImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 150)) coffeeImageView.image = UIImage(named: "coffee")?.imageWithRenderingMode(.AlwaysTemplate) titleView = coffeeImageView refreshSections() } //=================================================================================== //MARK: Refresh //=================================================================================== private func refreshDocumentsListAndTableView() { //first close the current file if let appDelegate = UIApplication.sharedApplication().delegate as? POAppDelegate { appDelegate.controllerCoordinator.stopUpdatingGenerators() appDelegate.controllerCoordinator.cleanupGenerators() POPdFileLoader.sharedPdFileLoader.closePdFile() { //then reload the table self.refreshSections() self.tableView.reloadData() self.presetTableViewController.removeFromParentViewController() } } } private func refreshSections() { cellDictionaries.removeAll(keepCapacity: false) let presets: [String : AnyObject] = ["title" : kPresetsTitle, "detailImage" : (UIImage(named: "play-button")?.imageWithRenderingMode(.AlwaysTemplate))!] let fileSharing: [String : AnyObject] = ["title" : kUserDocumentsTitle, "detailImage" : (UIImage(named: "itunes-icon-fake")?.imageWithRenderingMode(.AlwaysTemplate))!] let googleDrive: [String : AnyObject] = ["title" : kGoogleDriveTitle, "detailImage" : (UIImage(named: "google-drive-logo-vector")?.imageWithRenderingMode(.AlwaysTemplate))!] let settings: [String : AnyObject] = ["title" : kSettingsTitle, "detailImage" : (UIImage(named: "settings-button-outline")?.imageWithRenderingMode(.AlwaysTemplate))!] cellDictionaries.append(presets) cellDictionaries.append(fileSharing) cellDictionaries.append(googleDrive) cellDictionaries.append(settings) //add spacer cells to the top and bottom for correct scrolling behavior cellDictionaries.insert(Dictionary(), atIndex: 0) cellDictionaries.append(Dictionary()) } //=================================================================================== //MARK: TableView Data Source //=================================================================================== override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if let pieceTableViewCell = cell as? POTableViewCell { pieceTableViewCell.setDetailImage(cellDictionaries[indexPath.row]["detailImage"] as? UIImage) return pieceTableViewCell } else { return cell } } //=================================================================================== //MARK: Table View Delegate Methods //=================================================================================== override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { super.tableView(tableView, didSelectRowAtIndexPath: indexPath) if let currentMiddleIndexPath = indexPathForCentermostCellInTableview(tableView) { if indexPath == currentMiddleIndexPath { //middle cell selected for playback //transition to zoomed in, load pd patch, etc. //insert detail view controller and animate in: if let title = cellDictionaries[indexPath.row]["title"] as? String { switch title { case kPresetsTitle: presetTableViewController.title = title navigationController?.pushViewController(presetTableViewController, animated: true) case kUserDocumentsTitle: userDocumentsTableViewController.title = title navigationController?.pushViewController(userDocumentsTableViewController, animated: true) case kGoogleDriveTitle: googleDriveTableViewController.title = title navigationController?.pushViewController(googleDriveTableViewController, animated: true) case kSettingsTitle: settingsTableViewController.title = title navigationController?.pushViewController(settingsTableViewController, animated: true) default: print("no view controller with that title") return } } //store selected indexPath for loading on successful view controller push did finish selectedIndexPath = indexPath } } //always deselect tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
gpl-3.0
b6b576c91706cd93b2ee2199e33c312a
45.526667
152
0.54707
6.869094
false
false
false
false
Rain-dew/YLCycleView
YLCycleViewDemo/YLCycleViewDemo/YLCycleView/YLCycleCell.swift
1
1646
// QQ: 896525689 QQ群:511860085 // gitHub:https://github.com/Rain-dew // Email:[email protected] // _ // /\ /\ | | // \ \_/ / _ _ | | _ _ // \_ _/ | | | | | | | | | | // / \ | |_| | | |__/\| |_| | // \_/ \__,_| |_|__,/ \__,_| // YLCycleCell.swift // YLCycleView // // Created by Raindew on 2016/11/1. // Copyright © 2016年 Raindew. All rights reserved. // import UIKit class YLCycleCell: UICollectionViewCell { //声明属性 // var dataSource : [[String]]! lazy var iconImageView = UIImageView() lazy var titleLabel = UILabel() lazy var bottomView = UIView() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { setupUI() } } extension YLCycleCell { fileprivate func setupUI() { iconImageView.frame = self.bounds bottomView.frame = CGRect(x: 0, y: iconImageView.bounds.height - 30, width: iconImageView.bounds.width, height: 30) titleLabel.frame = CGRect(x: 10, y: iconImageView.bounds.height - 25, width: iconImageView.bounds.width / 2, height: 20) //设置属性 bottomView.backgroundColor = .black bottomView.alpha = 0.3 titleLabel.textAlignment = .left titleLabel.textColor = .white titleLabel.font = UIFont.systemFont(ofSize: 14) contentView.addSubview(iconImageView) contentView.addSubview(bottomView) contentView.addSubview(titleLabel) } }
mit
4add95f15ea4e9f5f21442c37ff453a2
26.083333
128
0.584
3.752887
false
false
false
false
GrandCentralBoard/GrandCentralBoard
GrandCentralBoard/Widgets/Watch/WatchWidgetViewModel.swift
2
5008
// // Created by Oktawian Chojnacki on 24.02.2016. // Copyright © 2016 Oktawian Chojnacki. All rights reserved. // import UIKit import GCBCore struct WatchWidgetViewModel { let watchFaceImage: UIImage? let centeredTimeText: String? let alignedTimeText: String? let eventText: NSAttributedString? init(date: NSDate, timeZone: NSTimeZone, event: Event? = nil, calendarName: String? = nil) { if let event = event { let timeToEvent = event.time.timeIntervalSinceDate(date) let minutesToEvent = Int(ceil(timeToEvent / 60)) // 10 seconds is "1 minute left"; 1 minute and 10 seconds is "2 minutes left" centeredTimeText = nil alignedTimeText = WatchWidgetViewModel.dateFormatterWithTimeZone(timeZone).stringFromDate(date) eventText = WatchWidgetViewModel.descriptionForEvent(event, fromCalendar: calendarName, startingInMinutes: minutesToEvent) watchFaceImage = WatchWidgetViewModel.watchFaceImageForEventStartingInMinutes(minutesToEvent) } else { centeredTimeText = WatchWidgetViewModel.dateFormatterWithTimeZone(timeZone).stringFromDate(date) alignedTimeText = nil eventText = nil watchFaceImage = nil } } private static func watchFaceImageForEventStartingInMinutes(minutesToEvent: Int) -> UIImage? { guard minutesToEvent > 0 else { return nil } let minutesInSlot = 5 let numberOfSlots = 12 let slotIndex = min(Int(ceil(Float(minutesToEvent) / Float(minutesInSlot))), numberOfSlots) return UIImage(named: "\(slotIndex)") } // MARK: Event description formatting private static let nextMeetingInFont = UIFont.systemFontOfSize(24, weight: UIFontWeightSemibold) private static let minutesFont = UIFont.systemFontOfSize(50, weight: UIFontWeightSemibold) private static let nowFont = UIFont.systemFontOfSize(50, weight: UIFontWeightSemibold) private static let calendarNameFont = UIFont.systemFontOfSize(22, weight: UIFontWeightBold) private static let eventNameFont = UIFont.systemFontOfSize(22, weight: UIFontWeightBold) private static let highLineSpacingStyle: NSParagraphStyle = { let style = NSMutableParagraphStyle() style.lineSpacing = 34 style.alignment = .Center return style }() private static let lowLineSpacingStyle: NSParagraphStyle = { let style = NSMutableParagraphStyle() style.lineSpacing = 12 style.alignment = .Center return style }() private static func descriptionForEvent(event: Event, fromCalendar calendarName: String?, startingInMinutes minutesToEvent: Int) -> NSAttributedString { let resultString = NSMutableAttributedString() if minutesToEvent > 0 { let nextMeetingIn = NSAttributedString( string: "NEXT MEETING IN" + "\n", attributes: [NSFontAttributeName : nextMeetingInFont, NSParagraphStyleAttributeName : lowLineSpacingStyle] ) let minutes = NSMutableAttributedString( string: "\(minutesToEvent) MIN" + "\n", attributes: [NSFontAttributeName : minutesFont, NSParagraphStyleAttributeName : lowLineSpacingStyle] ) resultString.appendAttributedString(nextMeetingIn) resultString.appendAttributedString(minutes) } else { let now = NSAttributedString( string: "NOW" + "\n", attributes: [NSFontAttributeName : nowFont, NSParagraphStyleAttributeName : highLineSpacingStyle] ) resultString.appendAttributedString(now) } if let calendarName = calendarName { let calendarNameString = NSMutableAttributedString( string: "@\(calendarName.uppercaseString)" + "\n", attributes: [NSFontAttributeName : calendarNameFont, NSForegroundColorAttributeName : UIColor.gcb_greenColor()] ) resultString.appendAttributedString(calendarNameString) } let eventNameString = NSMutableAttributedString( string: event.name.uppercaseString, attributes: [NSFontAttributeName : eventNameFont] ) resultString.appendAttributedString(eventNameString) return resultString } // MARK: Date formatting private static var cachedFormatter: NSDateFormatter? private static func dateFormatterWithTimeZone(timeZone: NSTimeZone) -> NSDateFormatter { if let formatter = cachedFormatter where formatter.timeZone == timeZone { return formatter } let formatter = NSDateFormatter() formatter.dateStyle = .NoStyle formatter.timeStyle = .ShortStyle formatter.timeZone = timeZone cachedFormatter = formatter return formatter } }
gpl-3.0
8be960a20efb8283b2e7e64922374cf1
38.738095
138
0.667865
5.594413
false
true
false
false
AblePear/Peary
Peary/FileDescriptor.swift
1
1290
import Foundation import Darwin.POSIX.unistd private func unistd_close(_ filedes: CInt) -> CInt { return close(filedes) } public typealias FileDescriptor = CInt public extension FileDescriptor { public var isOpen: Bool { return self >= 0 } public mutating func close() throws { defer { self = -1 } _ = try interruptibleSystemCall { unistd_close(self) } } public func getFlags() throws -> CInt { return try failableSystemCall { fcntl(self, F_GETFL) } } public func setFlags(_ flags: CInt) throws { _ = try failableSystemCall { fcntl(self, F_SETFL, flags) } } public func getFlag(_ flag: CInt) throws -> Bool { return try getFlags().hasBitsSet(flag) } public func setFlag(_ flag: CInt, newValue: Bool) throws { let flags = try getFlags() let newFlags = newValue ? flags.settingBits(flag) : flags.clearingBits(flag) try setFlags(newFlags) } public func getNonBlock() throws -> Bool { return try getFlag(O_NONBLOCK) } public func setNonBlock(_ newValue: Bool) throws { try setFlag(O_NONBLOCK, newValue: newValue) } }
bsd-2-clause
0896c3e56c262218c65f292d20f74d05
22.035714
84
0.57907
4.201954
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeLoading/AwesomeLoading/Classes/View/AwesomeLoadingView.swift
1
7621
// // LoadingView.swift // Micro Learning App // // Created by Evandro Harrison Hoffmann on 10/08/2016. // Copyright © 2016 Mindvalley. All rights reserved. // import UIKit import Lottie class AwesomeLoadingView: UIView { @IBOutlet weak var visualEffectView: UIVisualEffectView! @IBOutlet weak var iconImageView: UIImageView! fileprivate var animating = false fileprivate var maxScale: CGFloat = 1.0 fileprivate var pulseTimer: Timer? fileprivate var animationView: LOTAnimationView? fileprivate let activityIndicator = UIActivityIndicatorView() static func newInstance() -> AwesomeLoadingView { return Bundle(for: self).loadNibNamed("AwesomeLoadingView", owner: self, options: nil)![0] as! AwesomeLoadingView } override func awakeFromNib() { self.isHidden = true } } // MARK: - Animations extension AwesomeLoadingView { func show(json: [AnyHashable: Any]?, size: CGSize?) { animating = true if self.frame.size.width < self.iconImageView.frame.size.width*1.2 { maxScale = self.frame.size.width/(self.iconImageView.frame.size.width*1.2) } self.isHidden = false self.alpha = 0 UIView.animate(withDuration: 0.3, animations: { self.alpha = 1 }, completion: { (_) in }) self.alpha = 0 UIView.animate(withDuration: 0.4, delay: 0.1, options: .curveEaseOut, animations: { self.alpha = 1 }) //pulse() //pulseTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(MVLoadingView.pulse), userInfo: nil, repeats: true) if let json = json { animationView = LOTAnimationView(json: json) } else { // load default animation activityIndicator.center = self.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = .whiteLarge activityIndicator.startAnimating() self.addSubview(activityIndicator) } if let animationView = self.animationView { animationView.loopAnimation = true animationView.animationSpeed = 1 //animationView.frame = CGRect(x: (self.frame.size.width/2)-240, y: (self.frame.size.height/2)-135, width: 480, height: 270) self.addSubview(animationView) //animationView.addShadowLayer(size: CGSize(width: 90, height: 90)) animationView.translatesAutoresizingMaskIntoConstraints = false if let size = size { addConstraint(NSLayoutConstraint(item: animationView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size.width)) addConstraint(NSLayoutConstraint(item: animationView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: size.height)) } else { addConstraint(NSLayoutConstraint(item: animationView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: animationView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0)) } addConstraint(NSLayoutConstraint(item: animationView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: animationView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) animationView.play(completion: { (finished) in print("did complete \(finished)") }) } } func pulse() { UIView.animate(withDuration: 0.8, delay: 0, options: .curveEaseIn, animations: { self.iconImageView.transform = CGAffineTransform(scaleX: self.maxScale*1.1, y: self.maxScale*1.1) self.iconImageView.alpha = 0.8 }) { (_) in UIView.animate(withDuration: 0.8, delay: 0, options: .curveEaseOut, animations: { self.iconImageView.transform = CGAffineTransform(scaleX: self.maxScale*1, y: self.maxScale*1) self.iconImageView.alpha = 1 }) } } func hide() { animating = false animationView?.stop() pulseTimer?.invalidate() pulseTimer = nil UIView.animate(withDuration: 0.1, animations: { self.animationView?.transform = CGAffineTransform(scaleX: self.maxScale*0.9, y: self.maxScale*0.9) }, completion: { (_) in UIView.animate(withDuration: 0.3, animations: { self.animationView?.transform = CGAffineTransform(scaleX: self.maxScale*2, y: self.maxScale*2) self.alpha = 0 }, completion: { (_) in self.removeFromSuperview() }) }) } } extension UIView { public func startLoadingAnimationDelayed(_ delay: Double, withJson: String, bundle: Bundle? = nil) { let delayTime = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime) { self.startLoadingAnimation(json: withJson, bundle: bundle) } } public func startLoadingAnimation(json: String? = AwesomeLoading.defaultAnimationJson, bundle: Bundle? = AwesomeLoading.defaultAnimationBundle, size: CGSize? = AwesomeLoading.defaultAnimationSize) { stopLoadingAnimation() DispatchQueue.main.async { let loadingView = AwesomeLoadingView.newInstance() let jsonAnimation = FileLoader.shared.loadJSONFrom(file: json, fromBundle: bundle) as? [AnyHashable: Any] loadingView.frame = self.bounds self.addSubview(loadingView) loadingView.constraintToSuperview() loadingView.show(json: jsonAnimation, size: size) } } public func stopLoadingAnimation() { DispatchQueue.main.async { for subview in self.subviews { if let subview = subview as? AwesomeLoadingView { subview.hide() } else if let subview = subview as? UIActivityIndicatorView { subview.stopAnimating() } } } } public func constraintToSuperview() { guard let superview = superview else { return } translatesAutoresizingMaskIntoConstraints = false superview.addConstraint(NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: superview, attribute: .leading, multiplier: 1, constant: 0)) superview.addConstraint(NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: superview, attribute: .trailing, multiplier: 1, constant: 0)) superview.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1, constant: 0)) superview.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom, multiplier: 1, constant: 0)) } }
mit
e66413e8b114eee7ee3a71cdfbd0c614
41.333333
188
0.621785
4.948052
false
false
false
false
huonw/swift
test/SILGen/testable-multifile-other.swift
3
2668
// This test is paired with testable-multifile.swift. // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module %S/Inputs/TestableMultifileHelper.swift -enable-testing -o %t // RUN: %target-swift-emit-silgen -enable-sil-ownership -I %t %s %S/testable-multifile.swift -module-name main | %FileCheck %s // RUN: %target-swift-emit-silgen -enable-sil-ownership -I %t %S/testable-multifile.swift %s -module-name main | %FileCheck %s // RUN: %target-swift-emit-silgen -enable-sil-ownership -I %t -primary-file %s %S/testable-multifile.swift -module-name main | %FileCheck %s // Just make sure we don't crash later on. // RUN: %target-swift-emit-ir -enable-sil-ownership -I %t -primary-file %s %S/testable-multifile.swift -module-name main -o /dev/null // RUN: %target-swift-emit-ir -enable-sil-ownership -I %t -O -primary-file %s %S/testable-multifile.swift -module-name main -o /dev/null @testable import TestableMultifileHelper func use<F: Fooable>(_ f: F) { f.foo() } func test(internalFoo: FooImpl, publicFoo: PublicFooImpl) { use(internalFoo) use(publicFoo) internalFoo.foo() publicFoo.foo() } // CHECK-LABEL: sil hidden @$S4main4test11internalFoo06publicD0yAA0D4ImplV_AA06PublicdF0VtF // CHECK: [[USE_1:%.+]] = function_ref @$S4main3useyyxAA7FooableRzlF // CHECK: = apply [[USE_1]]<FooImpl>({{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Fooable> (@in_guaranteed τ_0_0) -> () // CHECK: [[USE_2:%.+]] = function_ref @$S4main3useyyxAA7FooableRzlF // CHECK: = apply [[USE_2]]<PublicFooImpl>({{%.+}}) : $@convention(thin) <τ_0_0 where τ_0_0 : Fooable> (@in_guaranteed τ_0_0) -> () // CHECK: [[IMPL_1:%.+]] = function_ref @$S23TestableMultifileHelper13HasDefaultFooPAAE3fooyyF // CHECK: = apply [[IMPL_1]]<FooImpl>({{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaultFoo> (@in_guaranteed τ_0_0) -> () // CHECK: [[IMPL_2:%.+]] = function_ref @$S23TestableMultifileHelper13HasDefaultFooPAAE3fooyyF // CHECK: = apply [[IMPL_2]]<PublicFooImpl>({{%.+}}) : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaultFoo> (@in_guaranteed τ_0_0) -> () // CHECK: } // end sil function '$S4main4test11internalFoo06publicD0yAA0D4ImplV_AA06PublicdF0VtF' func test(internalSub: Sub, publicSub: PublicSub) { internalSub.foo() publicSub.foo() } // CHECK-LABEL: sil hidden @$S4main4test11internalSub06publicD0yAA0D0C_AA06PublicD0CtF // CHECK: bb0([[ARG0:%.*]] : @guaranteed $Sub, [[ARG1:%.*]] : @guaranteed $PublicSub): // CHECK: = class_method [[ARG0]] : $Sub, #Sub.foo!1 // CHECK: = class_method [[ARG1]] : $PublicSub, #PublicSub.foo!1 // CHECK: } // end sil function '$S4main4test11internalSub06publicD0yAA0D0C_AA06PublicD0CtF'
apache-2.0
7e3bac01829dd93e3c770392b9b3cf6e
55.510638
140
0.696536
2.974244
false
true
false
false
spark/photon-tinker-ios
Photon-Tinker/DeviceInspectorVariablesViewController.swift
1
7579
// // DeviceInspectorFunctionsViewController.swift // Particle // // Created by Raimundas Sakalauskas on 05/16/19. // Copyright (c) 2019 Particle. All rights reserved. // class DeviceInspectorVariablesViewController: DeviceInspectorChildViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, DeviceVariableTableViewCellDelegate { @IBOutlet weak var noVariablesMessage: UILabel! @IBOutlet var noVariablesMessageView: UIView! var variableValues: [String: String?] = [:] var variableNames: [String] = [] override func viewDidLoad() { super.viewDidLoad() self.addRefreshControl() self.noVariablesMessageView.removeFromSuperview() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func resetUserAppData() { super.resetUserAppData() self.variableNames = [] self.variableValues = [:] } override func update() { super.update() self.variableNames = self.device.variables.keys.sorted() self.loadAllVariables() self.tableView.reloadData() self.tableView.isUserInteractionEnabled = true self.refreshControl.endRefreshing() self.setupTableViewHeader() } private func setupTableViewHeader() { if (self.device.connected) { self.noVariablesMessage.text = TinkerStrings.Variables.NoExposedVariables } else { self.noVariablesMessage.text = TinkerStrings.Variables.DeviceIsOffline } self.tableView.tableHeaderView = nil self.noVariablesMessageView.removeFromSuperview() self.tableView.tableHeaderView = (self.variableNames.count > 0) ? nil : self.noVariablesMessageView self.adjustTableViewHeaderViewConstraints() } override func showTutorial() { if (variableNames.count > 0) { if ParticleUtils.shouldDisplayTutorialForViewController(self) { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) { // 1 let firstCell = self.tableView.cellForRow(at: IndexPath(row: 0, section: 0)) // var tutorial = YCTutorialBox(headline: TinkerStrings.Variables.Tutorial.Tutorial1.Title, withHelpText: TinkerStrings.Variables.Tutorial.Tutorial1.Message) tutorial?.showAndFocus(firstCell) ParticleUtils.setTutorialWasDisplayedForViewController(self) } } } } func loadAllVariables() { if (!self.device.connected) { return } self.variableValues.removeAll() if (self.shouldLoadVariables()) { for name in self.variableNames { self.loadVariable(name) } } } func shouldLoadVariables() -> Bool { if (self.device.connected && self.variableNames.count <= 20) { return true } else { return false } } func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { return false } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 48.0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.variableNames.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: DeviceVariableTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "variableCell") as! DeviceVariableTableViewCell let name = variableNames[indexPath.row] var type: String! switch self.device.variables[name] { case "int32": type = "Integer" case "double": type = "Float" case "bool": type = "Bool" default: type = "String" } if self.variableValues.keys.contains(name) { let value = self.variableValues[name]! cell.setup(variableName: name, variableType: type, variableValue: value) if (value == nil) { cell.startUpdating() } else { cell.stopUpdating() } } else { cell.setup(variableName: name, variableType: type, variableValue: nil) cell.stopUpdating() } cell.delegate = self cell.selectionStyle = .none return cell } func loadVariable(_ name: String) { if (!self.device.connected) { DispatchQueue.main.async { RMessage.showNotification(withTitle: TinkerStrings.Variables.Error.DeviceOffline.Title, subtitle: TinkerStrings.Variables.Error.DeviceOffline.Message, type: .error, customTypeName: nil, duration: -1, callback: nil) } return } if self.variableValues.keys.contains(name) && self.variableValues[name] == nil { //already loading return } variableValues.updateValue(nil, forKey: name) self.device.getVariable(name) { [weak self, name] variableValue, error in if let self = self { if let error = error { self.variableValues[name] = nil } else { if let resultValue = variableValue as? String { self.variableValues[name] = resultValue } else if let resultValue = variableValue as? NSNumber { self.variableValues[name] = resultValue.stringValue } else { self.variableValues[name] = nil } } DispatchQueue.main.async { self.updateCellForVariable(name) } } } } func updateCellForVariable(_ name: String) { for cell in tableView.visibleCells as! [DeviceVariableTableViewCell] { if (cell.variableName == name) { if self.variableValues.keys.contains(name) { if let value = self.variableValues[name] { cell.setVariableValue(value: value) } else { cell.setVariableError() } } else { cell.setVariableError() } return } } } //MARK - Value cell delegate func tappedOnVariableName(_ sender: DeviceVariableTableViewCell, name: String) { self.loadVariable(name) } func tappedOnVariableValue(_ sender: DeviceVariableTableViewCell, name: String, value: String) { let alert = UIAlertController(title: name, message: value, preferredStyle: .alert) alert.addAction(UIAlertAction(title: TinkerStrings.Action.CopyToClipboard, style: .default) { [weak self] action in UIPasteboard.general.string = value RMessage.showNotification(withTitle: TinkerStrings.Variables.Prompt.VariableCopied.Title, subtitle: TinkerStrings.Variables.Prompt.VariableCopied.Message, type: .success, customTypeName: nil, callback: nil) SEGAnalytics.shared().track("DeviceInspector_VariableCopied") }) alert.addAction(UIAlertAction(title: TinkerStrings.Action.Close, style: .cancel) { action in }) self.present(alert, animated: true) } }
apache-2.0
07c6f7931f692c78019226b7f3454383
32.387665
230
0.601135
5.138305
false
false
false
false
huonw/swift
validation-test/compiler_crashers_fixed/01291-swift-type-walk.swift
65
1052
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func f<e>() -> (e, e -> e) -> e { { { } } protocol f { } class e: f { class funT>: NSObject { init(foo: T) { B>(t: T) { } x x) { } class a { var _ = i() { } } func i(c: () -> ()) { } class a { var _ = i() { } } } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { } } func n<q>() { b b { } } func n(j: Any, t: Any) -> (((Any, Any) -> Any) -> Any) { k { } } var d = b protocol a { } protocol b : a { } protocol c : a { } protocol d { } struct e : d { } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } protocol b { } struct c { func e() { } } struct c<e> { } func b(g: f) -> <e>(()-> e) -> i
apache-2.0
f38585ca03a241d373b8aa48e0d1e780
13.611111
79
0.55038
2.429561
false
false
false
false
maxoly/PulsarKit
PulsarKit/PulsarKit/Sources/Plugin/Plugins/GroupedCollectionPlugin.swift
1
1890
// // GroupedCollectionPlugin.swift // PulsarKit // // Created by Massimo Oliviero on 01/03/2019. // Copyright © 2019 Nacoon. All rights reserved. // import Foundation public protocol Groupable { func groupNotification(sectionPosition: GroupedCollectionPlugin.Position, itemPosition: GroupedCollectionPlugin.Position) } open class GroupedCollectionPlugin { public enum Position { case first case middle case last case single } public init() {} } extension GroupedCollectionPlugin: SourcePlugin { public var filter: SourcePluginFilter? { self } public var events: SourcePluginEvents? { nil } public var lifecycle: SourcePluginLifecycle? { nil } } extension GroupedCollectionPlugin: SourcePluginFilter { public func filter<Cell>(source: CollectionSource, cell: Cell, at indexPath: IndexPath) -> Cell where Cell: UICollectionReusableView { guard let groupable = cell as? Groupable else { return cell } let sectionsCount = source.sections.count let modelCount = source.sections[indexPath.section].models.count let sectionPosition = position(count: sectionsCount, index: indexPath.section) let itemPosition = position(count: modelCount, index: indexPath.item) groupable.groupNotification(sectionPosition: sectionPosition, itemPosition: itemPosition) return cell } } private extension GroupedCollectionPlugin { func position(count: Int, index: Int) -> Position { switch (count, index) { case (1, _): return .single case (_, let rowIndex) where rowIndex == 0: return .first case (let rowsCount, let rowIndex) where rowIndex == (rowsCount - 1): return .last default: return .middle } } }
mit
dcbdaffb6b9ec9bb9acf7e64341be050
28.984127
138
0.657491
4.734336
false
false
false
false
biohazardlover/ROer
Roer/StatusCalculatorStatusCell.swift
1
1169
import UIKit class StatusCalculatorStatusCell: UICollectionViewCell { @IBOutlet var status1Label: UILabel! @IBOutlet var status1Button: StatusCalculatorSelectButton! @IBOutlet var status1PlusLabel: UILabel! @IBOutlet var status2Label: UILabel! @IBOutlet var status2Button: StatusCalculatorSelectButton! @IBOutlet var status2PlusLabel: UILabel! } extension StatusCalculatorStatusCell: StatusCalculatorElementCell { func configureWithElement(_ element: AnyObject) { guard let status = element as? [StatusCalculator.Element] else { return } status1Label.text = status[0].description status1Button.selectElement = status[0] as! StatusCalculator.SelectElement status1Button.reloadData() status1PlusLabel.text = (status[1] as! StatusCalculator.StaticTextElement).textContent status2Label.text = status[2].description status2Button.selectElement = status[2] as! StatusCalculator.SelectElement status2Button.reloadData() status2PlusLabel.text = (status[3] as! StatusCalculator.StaticTextElement).textContent } }
mit
79146ac4f1db601075aa265f8752ed0c
34.424242
94
0.718563
4.657371
false
false
false
false
zhenghuadong11/firstGitHub
旅游app_useSwift/旅游app_useSwift/AppDelegate.swift
1
3522
// // AppDelegate.swift // 旅游app_useSwift // // Created by zhenghuadong on 16/4/15. // Copyright © 2016年 zhenghuadong. All rights reserved. // import UIKit let appkey = "5715ed5c67e58edd150011b5" let shareAppjey = "2896135387" let shareAppSecret = "3afdd132da4cb1e71ac92a8ce1e1690c" let shareUri = "https://www.baidu.com" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.window = UIWindow() self.window?.frame = UIScreen.mainScreen().bounds self.window?.makeKeyAndVisible() // if isNewVersion() // { // // self.window?.rootViewController = MYNewFeatureViewController() // } // else // { self.window?.rootViewController = ViewController() // } return true } func isNewVersion() -> Bool { let currentVersionObject = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] let currentVersion = currentVersionObject as! String if let lastString = NSUserDefaults.standardUserDefaults().valueForKey("CFBundleShortVersionString") { let lastVersion = lastString as! String if(currentVersion == lastVersion) { return false } } NSUserDefaults.standardUserDefaults().setValue(currentVersion, forKey: "CFBundleShortVersionString") NSUserDefaults.standardUserDefaults().synchronize() return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { print(url) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
dd0241ff8e778c6f9c151c6af62cd315
40.845238
285
0.701849
5.23845
false
false
false
false
artyom-stv/TextInputKit
TextInputKit/TextInputKit/Code/UIKitExtensions/UITextInput+TextInputKit.swift
1
1288
// // UITextInput+TextInputKit.swift // TextInputKit // // Created by Artem Starosvetskiy on 22/11/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit extension UITextInput { var selectedUTF16IntRange: Range<Int>? { get { if let selectedTextRange = selectedTextRange { return Range<Int>(uncheckedBounds: ( lower: offset(from: beginningOfDocument, to: selectedTextRange.start), upper: offset(from: beginningOfDocument, to: selectedTextRange.end) )) } return nil } set { selectedTextRange = { if let range = newValue { guard let start = position(from: beginningOfDocument, offset: range.lowerBound), let end = position(from: beginningOfDocument, offset: range.upperBound) else { fatalError("New selected range is out of text bounds.") } return textRange(from: start, to: end) } return selectedTextRange }() } } } #endif
mit
2d267523a386d0d1417a691a212cbf51
27.6
98
0.525253
5.407563
false
false
false
false
Ryce/flickrpickr
Carthage/Checkouts/judokit/Source/JudoKit.swift
2
19992
// // JudoKit.swift // Judo // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import PassKit import DeviceDNA let JudoKitVersion = "6.2.14" /** A method that checks if the device it is currently running on is jailbroken or not - returns: true if device is jailbroken */ public func isCurrentDeviceJailbroken() -> Bool { let fileManager = FileManager.default return fileManager.fileExists(atPath: "/private/var/lib/apt/") } /// Entry point for interacting with judoKit public class JudoKit { /// JudoKit local judo session public var apiSession = Session() /// the theme of the current judoKitSession public var theme: Theme = Theme() /// currently active JudoPayViewController if available public weak var activeViewController: JudoPayViewController? /// Fraud Prevention fileprivate let deviceDNA: DeviceDNA private var deviceSignals: JSONDictionary? /** designated initializer of JudoKit - Parameter token: a string object representing the token - Parameter secret: a string object representing the secret - parameter allowJailbrokenDevices: boolean that indicates whether jailbroken devices are restricted - Throws JailbrokenDeviceDisallowedError: In case jailbroken devices are not allowed, this method will throw an exception if it is run on a jailbroken device - returns: a new instance of JudoKit */ public init(token: String, secret: String, allowJailbrokenDevices: Bool) throws { // Check if device is jailbroken and SDK was set to restrict access if !allowJailbrokenDevices && isCurrentDeviceJailbroken() { throw JudoError(.jailbrokenDeviceDisallowedError) } let credentials = Credentials(token: token, secret: secret) self.deviceDNA = DeviceDNA(credentials: credentials) self.setToken(token, secret: secret) } /** convenience initializer of JudoKit - Parameter token: a string object representing the token - Parameter secret: a string object representing the secret - returns: a new instance of JudoKit */ public convenience init(token: String, secret: String) { try! self.init(token: token, secret: secret, allowJailbrokenDevices: true) } /** Completion caller - this method will automatically trigger a Session Call to the judo REST API and execute the request based on the information that were set in the previous methods - Parameter transaction: the transaction to be completed - Parameter block: a completion block that is called when the request finishes */ open func completion(_ transaction: Transaction, block: @escaping JudoCompletionBlock) throws { if let device = self.deviceSignals { _ = try transaction.deviceSignal(device).completion(block) } else { self.deviceDNA.getDeviceSignals({ (device, error) in if let device = device as JSONDictionary? { _ = transaction.deviceSignal(device) } do { _ = try transaction.completion(block) } catch let error as JudoError{ block(nil, error) } catch { block(nil, JudoError(.unknown)) } }) } } // MARK: Configuration /** Set the app to sandboxed mode - parameter enabled: true to set the SDK to sandboxed mode */ public func sandboxed(_ enabled: Bool) { self.apiSession.sandboxed = enabled } /** A mandatory function that sets the token and secret for making payments with judo - Parameter token: a string object representing the token - Parameter secret: a string object representing the secret */ public func setToken(_ token: String, secret: String) { let plainString = token + ":" + secret let plainData = plainString.data(using: String.Encoding.isoLatin1) let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0)) self.apiSession.authorizationHeader = "Basic " + base64String } /** A function to check whether a token and secret has been set - Returns: a Boolean indicating whether the parameters have been set */ public func didSetTokenAndSecret() -> Bool { return self.apiSession.authorizationHeader != nil } // MARK: Transactions /** Main payment method - parameter judoId: The judoId of the merchant to receive the payment - parameter amount: The amount and currency of the payment (default is GBP) - parameter reference: Reference object that holds consumer and payment reference and a meta data dictionary which can hold any kind of JSON formatted information - parameter completion: The completion handler which will respond with a Response Object or an NSError */ public func invokePayment(_ judoId: String, amount: Amount, reference: Reference, cardDetails: CardDetails? = nil, completion: @escaping (Response?, JudoError?) -> ()) throws { let judoPayViewController = try JudoPayViewController(judoId: judoId, amount: amount, reference: reference, completion: completion, currentSession: self, cardDetails: cardDetails) self.initiateAndShow(judoPayViewController) } /** Make a pre-auth using this method - parameter judoId: The judoId of the merchant to receive the pre-auth - parameter amount: The amount and currency of the payment (default is GBP) - parameter reference: Reference object that holds consumer and payment reference and a meta data dictionary which can hold any kind of JSON formatted information - parameter completion: The completion handler which will respond with a Response Object or an NSError */ public func invokePreAuth(_ judoId: String, amount: Amount, reference: Reference, cardDetails: CardDetails? = nil, completion: @escaping (Response?, JudoError?) -> ()) throws { let judoPayViewController = try JudoPayViewController(judoId: judoId, amount: amount, reference: reference, transactionType: .PreAuth, completion: completion, currentSession: self, cardDetails: cardDetails) self.initiateAndShow(judoPayViewController) } // MARK: Register Card /** Initiates a card registration - parameter judoId: The judoId of the merchant to receive the pre-auth - parameter amount: The amount and currency of the payment (default is GBP) - parameter reference: Reference object that holds consumer and payment reference and a meta data dictionary which can hold any kind of JSON formatted information - parameter completion: The completion handler which will respond with a Response Object or an NSError */ public func invokeRegisterCard(_ judoId: String, amount: Amount, reference: Reference, cardDetails: CardDetails? = nil, completion: @escaping (Response?, JudoError?) -> ()) throws { let judoPayViewController = try JudoPayViewController(judoId: judoId, amount: amount, reference: reference, transactionType: .RegisterCard, completion: completion, currentSession: self, cardDetails: cardDetails) self.initiateAndShow(judoPayViewController) } // MARK: Token Transactions /** Initiates the token payment process - parameter judoId: The judoId of the merchant to receive the payment - parameter amount: The amount and currency of the payment (default is GBP) - parameter reference: Reference object that holds consumer and payment reference and a meta data dictionary which can hold any kind of JSON formatted information - parameter cardDetails: The card details to present in the input fields - parameter paymentToken: The consumer and card token to make a token payment with - parameter completion: The completion handler which will respond with a Response Object or an NSError */ public func invokeTokenPayment(_ judoId: String, amount: Amount, reference: Reference, cardDetails: CardDetails, paymentToken: PaymentToken, completion: @escaping (Response?, JudoError?) -> ()) throws { let judoPayViewController = try JudoPayViewController(judoId: judoId, amount: amount, reference: reference, transactionType: .Payment, completion: completion, currentSession: self, cardDetails: cardDetails, paymentToken: paymentToken) self.initiateAndShow(judoPayViewController) } /** Initiates the token pre-auth process - parameter judoId: The judoId of the merchant to receive the pre-auth - parameter amount: The amount and currency of the payment (default is GBP) - parameter reference: Reference object that holds consumer and payment reference and a meta data dictionary which can hold any kind of JSON formatted information - parameter cardDetails: The card details to present in the input fields - parameter paymentToken: The consumer and card token to make a token payment with - parameter completion: The completion handler which will respond with a Response Object or an NSError */ public func invokeTokenPreAuth(_ judoId: String, amount: Amount, reference: Reference, cardDetails: CardDetails, paymentToken: PaymentToken, completion: @escaping (Response?, JudoError?) -> ()) throws { let judoPayViewController = try JudoPayViewController(judoId: judoId, amount: amount, reference: reference, transactionType: .PreAuth, completion: completion, currentSession: self, cardDetails: cardDetails, paymentToken: paymentToken) self.initiateAndShow(judoPayViewController) } /** Starting point and a reactive method to create a transaction that is sent to a certain judo ID - Parameter transactionType: The type of the transaction (payment, pre-auth or registercard) - Parameter judoId: The recipient - has to be between 6 and 10 characters and luhn-valid - Parameter amount: The amount of the Payment - Parameter reference: The reference - Throws: JudoIDInvalidError judoId does not match the given length or is not luhn valid - Throws: InvalidOperationError if you call this method with .Refund as a transactionType - Returns: a Payment Object */ public func transaction(_ transactionType: TransactionType, judoId: String, amount: Amount, reference: Reference) throws -> Transaction { switch transactionType { case .Payment: return try self.payment(judoId, amount: amount, reference: reference) case .PreAuth: return try self.preAuth(judoId, amount: amount, reference: reference) case .RegisterCard: return try self.registerCard(judoId, reference: reference) default: throw JudoError(.invalidOperationError) } } /** Starting point and a reactive method to create a payment that is sent to a certain judo ID - Parameter judoId: The recipient - has to be between 6 and 10 characters and luhn-valid - Parameter amount: The amount of the Payment - Parameter reference: The reference - Throws: JudoIDInvalidError judoId does not match the given length or is not luhn valid - Returns: a Payment Object */ public func payment(_ judoId: String, amount: Amount, reference: Reference) throws -> Payment { return try Payment(judoId: judoId, amount: amount, reference: reference).apiSession(self.apiSession) } /** Starting point and a reactive method to create a pre-auth that is sent to a certain judo ID - Parameter judoId: The recipient - has to be between 6 and 10 characters and LUHN valid - Parameter amount: The amount of the pre-auth - Parameter reference: The reference - Throws: JudoIDInvalidError judoId does not match the given length or is not LUHN valid - Returns: pre-auth Object */ public func preAuth(_ judoId: String, amount: Amount, reference: Reference) throws -> PreAuth { return try PreAuth(judoId: judoId, amount: amount, reference: reference).apiSession(self.apiSession) } /** Starting point and a reactive method to create a RegisterCard that is sent to a certain judo ID - Parameter judoId: The recipient - has to be between 6 and 10 characters and LUHN valid - Parameter amount: The amount of the RegisterCard - Parameter reference: The reference - Throws: JudoIDInvalidError judoId does not match the given length or is not LUHN valid - Returns: a RegisterCard Object */ public func registerCard(_ judoId: String, reference: Reference) throws -> RegisterCard { return try RegisterCard(judoId: judoId, amount: nil, reference: reference).apiSession(self.apiSession) } /** Creates a Receipt object which can be used to query for the receipt of a given ID. The receipt ID has to be LUHN valid, an error will be thrown if the receipt ID does not pass the LUHN check. If you want to use the receipt function - you need to enable that in the judo Dashboard - Your Apps - Permissions for the given App - Parameter receiptId: The receipt ID as a String - Throws: LuhnValidationError if the receiptId does not match - Returns: a Receipt Object for reactive usage */ public func receipt(_ receiptId: String? = nil) throws -> Receipt { return try Receipt(receiptId: receiptId).apiSession(self.apiSession) } /** Creates a Collection object which can be used to collect a previously pre-authorized transaction - Parameter receiptId: The receipt of the previously authorized transaction - Parameter amount: The amount to be transacted - Parameter paymentReference: The payment reference string - Throws: LuhnValidationError judoId does not match the given length or is not LUHN valid - Returns: a Collection object for reactive usage */ public func collection(_ receiptId: String, amount: Amount) throws -> Collection { return try Collection(receiptId: receiptId, amount: amount).apiSession(self.apiSession) } /** Creates a Refund object which can be used to refund a previous transaction - Parameter receiptId: The receipt of the previous transaction - Parameter amount: The amount to be refunded (will check if funds are available in your account) - Parameter paymentReference: The payment reference string - Throws: LuhnValidationError judoId does not match the given length or is not LUHN valid - Returns: a Refund object for reactive usage */ public func refund(_ receiptId: String, amount: Amount) throws -> Refund { return try Refund(receiptId: receiptId, amount: amount).apiSession(self.apiSession) } /** Creates a VoidTransaction object which can be used to void a previous preAuth - Parameter receiptId: The receipt of the previous transaction - Parameter amount: The amount to be refunded (will check if funds are available in your account) - Parameter paymentReference: The payment reference string - Throws: LuhnValidationError judoId does not match the given length or is not LUHN valid - Returns: a Void object for reactive usage */ public func voidTransaction(_ receiptId: String, amount: Amount) throws -> VoidTransaction { return try VoidTransaction(receiptId: receiptId, amount: amount).apiSession(self.apiSession) } /** Creates an instance of a class that conforms to SessionProtocol. This means that anything related to Payments or PreAuths can be queried for a list - parameter type: the type - returns: a new instance that can be used to fetch information */ public func list<T:SessionProtocol>(_ type: T.Type) -> T { var transaction = T() transaction.APISession = self.apiSession return transaction } // MARK: Helper methods /** Helper method to initiate, pass information and show a JudoPay ViewController - parameter viewController: the viewController to initiate and show - parameter cardDetails: optional dictionary that contains card info */ func initiateAndShow(_ viewController: JudoPayViewController) { self.deviceDNA.getDeviceSignals { (device, error) in if let device = device as JSONDictionary? { self.deviceSignals = device } } self.activeViewController = viewController self.showViewController(viewController) //self.showViewController(UINavigationController(rootViewController: viewController)) } /** Helper method to show a given ViewController on the top most view - parameter vc: the viewController to show */ func showViewController(_ vc: UIViewController) { vc.modalPresentationStyle = .formSheet var viewController = UIApplication.shared.keyWindow?.rootViewController // if let presented = viewController?.presentedViewController { switch viewController { case is UINavigationController: let navigationController = viewController as! UINavigationController viewController = navigationController.viewControllers.last! if let presentedVC = viewController?.presentedViewController { viewController = presentedVC } navigationController.pushViewController(vc, animated: true) case is UITabBarController: let tabBarController = viewController as! UITabBarController viewController = tabBarController.selectedViewController! if let presentedVC = viewController?.presentedViewController { viewController = presentedVC } tabBarController.addChildViewController(vc) default: viewController?.present(vc, animated:true, completion:nil) // } } } }
mit
682661a26420ba4002d5ca3634cb364c
42.746171
242
0.679072
5.145946
false
false
false
false
wangCanHui/weiboSwift
weiboSwift/Classes/Lib/Emoticon/CZEmoticon.swift
1
13490
// // CZEmoticon.swift // 表情键盘 // // Created by zhangping on 15/11/4. // Copyright © 2015年 zhangping. All rights reserved. // import UIKit // MARK: - 表情包模型 /// 表情包模型 class CZEmoticonPackage: NSObject { // MARK: - 属性 private static let bundlePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")! /// 表示文件夹名称 var id: String? /// 表情包名称 var group_name_cn: String? /// 所有表情 var emoticons: [CZEmoticon]? /// 构造方法,通过表情包路径 init(id: String) { self.id = id super.init() } /// 对象打印方法 override var description: String { return "\n\t表情包模型: id: \(id), group_name_cn:\(group_name_cn), emoticons: \(emoticons)" } // 每次进入发微博界面弹出自定义表情键盘都会去磁盘加载所有的表情,比较耗性能, // 只加载一次,然后保存到内存中,以后访问内存中的表情数据 // packages保存所有的表情包数据,只加载一次 static let packages = CZEmoticonPackage.loadPackages() /// 加载所有表情包 class func loadPackages() -> [CZEmoticonPackage] { // 获取Emoticons.bundle的路径 // 拼接 emoticons.plist 的路径 let plistPath = bundlePath + "/emoticons.plist" // 加载plist let plistDict = NSDictionary(contentsOfFile: plistPath)! // print("plistDict:\(plistDict)") /// 表情包数组 var packages = [CZEmoticonPackage]() // 手动添加 `最近` 的表情包 // 创建表情包模型 let recent = CZEmoticonPackage(id: "") // 设置表情包名称 recent.group_name_cn = "最近" // 添加到表情包数组 packages.append(recent) // 初始化表情数组 recent.emoticons = [CZEmoticon]() // 追加空白按钮和删除按钮 recent.appendEmptyEmoticon() // 获取packages数组里面每个字典的key为id的值 if let packageArray = plistDict["packages"] as? [[String: AnyObject]] { // 遍历数组 for dict in packageArray { // 获取字典里面的key为id的值 let id = dict["id"] as! String // 对应表情包的路径 // 创建表情包,表情包里面只有id,其他的数据需要知道表情包的文件名称才能进行 let package = CZEmoticonPackage(id: id) // 让表情包去进一步加载数据(表情模型,表情包名称) package.loadEmoticon() packages.append(package) } } return packages } /// 加载表情包里面的表情和其他数据 func loadEmoticon() { // 获取表情包文件夹里面的info.plist // info.plist = bundle + 表情包文件夹名称 + info.plist let infoPath = CZEmoticonPackage.bundlePath + "/" + id! + "/info.plist" // 加载info.plist let infoDict = NSDictionary(contentsOfFile: infoPath)! // print("infoDict:\(infoDict)") // 获取表情包名称 group_name_cn = infoDict["group_name_cn"] as? String // 创建表情模型数组 emoticons = [CZEmoticon]() // 记录当前是第几个按钮 var index = 0 // 获取表情模型 if let array = infoDict["emoticons"] as? [[String: String]] { // 遍历表情数据数组 for dict in array { // 字典转模型,创建表情模型 emoticons?.append(CZEmoticon(id: id, dict: dict)) index++ // 如果是最后一个按钮就添加一个带删除按钮的表情模型 if index == 20 { emoticons?.append(CZEmoticon(removeEmoticon: true)) // 记得重置为0在重新计算 index = 0 } } } // 判断如果最后一个不够21个,需要追加空白表情和删除按钮 appendEmptyEmoticon() } /** 追加空白表情和删除按钮 */ private func appendEmptyEmoticon() { // 判断最后一页,表情是否满21个 let count = emoticons!.count % 21 // 不够就追加 // 最后一页不满21个,有count个表情 // 如果是 最近 表情包 emoticons!.count == 0 if count > 0 || emoticons!.count == 0 { // 追加多少个? // count == 1, 追加20 - 1 = 19 (1..<20) 加上删除按钮 // count == 2, 追加20 - 2 = 18 (2..<20)加上删除按钮 for _ in count..<20 { // 追加空白按钮 emoticons?.append(CZEmoticon(removeEmoticon: false)) } // 追加删除按钮 emoticons?.append(CZEmoticon(removeEmoticon: true)) } } /** 添加表情到最近表情包 - parameter emoticon: 要添加的表情 */ class func addFavourite(emoticon: CZEmoticon) { if emoticon.removeEmoticon { return // 点击的是删除按钮,直接返回 } // 表情模型的使用次数加1 emoticon.times++ // 找到 最近 表情包的所有模型 var recentEmoticons = packages[0].emoticons // 不管添加多少个表情,最多只有20个表情+1删除按钮表情 let removeEmoticon = recentEmoticons!.removeLast() // 如果最近表情包已经有这个表情,就不需要重复添加 let contains = recentEmoticons!.contains(emoticon) // 表情包没有这个表情 if !contains { recentEmoticons?.append(emoticon) } // 根据使用次数排序,次数多得放在前面 recentEmoticons = recentEmoticons?.sort({ (e1, e2) -> Bool in // 根据 times 降序排序, 数组中,times大的排在前面, return e1.times > e2.times }) // 如果前面有添加,就删除最后一个,如果没有添加不删除 if !contains { // 如果前面有添加,就删除最后一个 recentEmoticons?.removeLast() } // 在把删除按钮添加回来 recentEmoticons?.append(removeEmoticon) // 记住要复制回去 packages[0].emoticons = recentEmoticons // print("packages[0].emoticons:\(packages[0].emoticons)") // print("packages[0].emoticons count: \(packages[0].emoticons?.count)") } } // MARK: - 表情模型 /// 表情模型 class CZEmoticon: NSObject { // 表情包文件夹名称 var id: String? // 表情名称,用于网络传输 var chs: String? // 表情图片对应的名称 // 直接使用这个名称是加载不到图片的,因为图片的是保存在对应的文件夹里面 var png: String? { didSet { // 拼接完成路径 pngPath = CZEmoticonPackage.bundlePath + "/" + id! + "/" + png! } } // 完整的图片路径 = bundle + id + png var pngPath: String? // emoji表情对应的16进制字符串 var code: String? { didSet { guard let co = code else { // 表示code没值 return } // 将code转成emoji表情 let scanner = NSScanner(string: co) // 存储扫描结果 // UnsafeMutablePointer<UInt32>: UInt32类型的可变指针 var value: UInt32 = 0 scanner.scanHexInt(&value) let c = Character(UnicodeScalar(value)) emoji = String(c) } } // emoji表情 var emoji: String? /// 记录点击次数 var times = 0 /// true表示 带删除按钮的表情模型, false 表示空的表情模型 var removeEmoticon: Bool = false /// 带删除按钮的表情模型, 空模型 /// 通过这个构造方法创建的模型, 要么是 带删除按钮的表情模型, 要么是 空模型 init(removeEmoticon: Bool) { self.removeEmoticon = removeEmoticon super.init() } /// 字典转模型, 创建出来的不是 图片表情模型 就是emoji表情模型 init(id: String?, dict: [String: String]) { self.id = id super.init() // KVC 赋值 setValuesForKeysWithDictionary(dict) } /// 字典的key在模型里面没有对应的属性 override func setValue(value: AnyObject?, forUndefinedKey key: String) {} /// 打印方法 override var description: String { return "\n\t\t表情模型: chs: \(chs), png: \(png), code: \(code))" } // MARK: - 将表情模型转成带表情图片的属性文本 /// 将表情模型转成带表情图片的属性文本 func emoticonToAttrString(font: UIFont) -> NSAttributedString { guard let pngP = pngPath else { print("没有图片") return NSAttributedString(string: "") } // 创建附件 let attachment = CZTextAttachment() // 创建 image let image = UIImage(contentsOfFile: pngP) // 将 image 添加到附件 attachment.image = image // 将表情图片的名称赋值 attachment.name = chs // 获取font的高度 let height = font.lineHeight ?? 10 // 设置附件大小 attachment.bounds = CGRect(x: 0, y: -(height * 0.25), width: height, height: height) // 创建属性文本 let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment)) // 发现在表情图片后面在添加表情会很小.原因是前面的这个表请缺少font属性 // 给属性文本(附件) 添加 font属性 attrString.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: 1)) return attrString } /// 根据表情文本找到对应的表情模型 class func emoticonStringToEmoticon(emoticonString: String) -> CZEmoticon? { // 接收查找的结果 var emoticon: CZEmoticon? // 遍历所有的表情模型,判断表情模型的名称 = emoticonString for package in CZEmoticonPackage.packages { // 获取对应的表情包 let result = package.emoticons?.filter({ (e1) -> Bool in // 判断表情模型的表情名称是否等于 emoticonString // 满足条件的元素会放到数组里面作为返回结果 return e1.chs == emoticonString }) emoticon = result?.first // 有结果就不需要在遍历了 if emoticon != nil { break } } return emoticon } /** 表情字符串转带表情图片的属性文本 - parameter string: 表情字符串 - returns: 带表情图片的属性文本 */ class func emoticonStringToEmoticonAttrString(string: String, font: UIFont) -> NSAttributedString { // 1.解析字符串中表情文本 // 2.根据表情文本找到对应的表情模型(表情模型里面有表情图片的完整路径) * // 3.将表情模型转成带表情图片的属性文本 * // 4.将 表情文本 替换成 表情图片的属性文本 // 解析字符串中表情文本 使用正则表达式 let pattern = "\\[.*?\\]" let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators) // 查找 string中的表情字符串 let results = regular.matchesInString(string, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: string.characters.count)) // 将传进来的文本转成属性文本 let attrText = NSMutableAttributedString(string: string) // 反过来替换文本 var count = results.count while count > 0 { // 从最后开始获取范围 let result = results[--count] // print("结果数量:\(result.numberOfRanges): result:\(result)") let range = result.rangeAtIndex(0) // 获取到对应的表情文本 let emoticonString = (string as NSString).substringWithRange(range) // 根据表情文本找到对应的表情模型 if let emoticon = CZEmoticon.emoticonStringToEmoticon(emoticonString) { // 将表情模型转成带表情图片的属性文本 let attrString = emoticon.emoticonToAttrString(font) // 将 表情文本 替换成 表情图片的属性文本 attrText.replaceCharactersInRange(range, withAttributedString: attrString) } } return attrText } }
apache-2.0
525fd25ac1215b4bde65609207b70b38
27.605333
156
0.529878
4.268603
false
false
false
false
zvonler/PasswordElephant
external/github.com/CryptoSwift/Sources/CryptoSwift/UInt16+Extension.swift
8
1631
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /** array of bytes */ extension UInt16 { @_specialize(exported: true, where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T) where T.Element == UInt8, T.Index == Int { self = UInt16(bytes: bytes, fromIndex: bytes.startIndex) } @_specialize(exported: true, where T == ArraySlice<UInt8>) init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int { if bytes.isEmpty { self = 0 return } let count = bytes.count let val0 = count > 0 ? UInt16(bytes[index.advanced(by: 0)]) << 8 : 0 let val1 = count > 1 ? UInt16(bytes[index.advanced(by: 1)]) : 0 self = val0 | val1 } }
gpl-3.0
a5731adf54ce7ef3ac23b1417fafaf4b
43.054054
217
0.682822
4.064838
false
false
false
false
dominickhera/Projects
personal/iOU/iOU 4.0/NewWebsiteViewController.swift
2
990
// // NewWebsiteViewController.swift // iOU 4.0 // // Created by Dominick Hera on 1/29/15. // Copyright (c) 2015 Posa. All rights reserved. // import UIKit class NewWebsiteViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "www.apple.com") let request = NSURLRequest(URL: url!) //webView.loadRequest(request) // let url = NSURL(string: "www.dominickhera.com") //let request = NSURLRequest(URL: url!) //newWebView.loadRequest(request) // Do any additional setup after loading the view. } @IBAction func openInSafari(sender: AnyObject) { var url : NSURL url = NSURL(string: "http://www.dominickhera.com")! UIApplication.sharedApplication().openURL(url) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
97460788978f6f9f19ceb4fc546d2dbf
26.5
59
0.637374
4.142259
false
false
false
false
ladanv/EmailNotifier
EmailNotifier/EmailListController.swift
1
6772
// // AppController.swift // EmailNotifier // // Created by Vitaliy.Ladan on 07.12.14. // Copyright (c) 2014 Vitaliy.Ladan. All rights reserved. // import Cocoa class EmailListController: NSObject { @IBOutlet weak var noEmailView: NSView! @IBOutlet weak var emailTableView: NSTableView! var emailTableViewContents: NSMutableArray! var aboutController: AboutController! var settingController: SettingController! var initialize = true var emailCheckingTimer: NSTimer? override func awakeFromNib() { objc_sync_enter(self) if initialize { initialize = false NSNotificationCenter.defaultCenter().addObserver(self, selector: "startEmailChecking", name: "restartEmailChecking", object: nil) initMainView() let emailService = EmailService.instance if let error = emailService.initWithSettingService() { println("Error in EmailListController:awakeFromNib -> \(error.localizedDescription)") } else { startEmailChecking() } } objc_sync_exit(self) } func startEmailChecking() { let minutes = NSTimeInterval(SettingService.interval) * 60 if let isTimerValid = emailCheckingTimer?.valid { emailCheckingTimer!.invalidate() } emailCheckingTimer = NSTimer.scheduledTimerWithTimeInterval(minutes, target: self, selector: "doCheckEmail", userInfo: nil, repeats: true) } func doCheckEmail() { checkEmail(nil) } func checkEmail(callback: (() -> Void)?) { emailTableViewContents = NSMutableArray() let emailService = EmailService.instance emailService.fetchUnread { (error, messages) -> Void in if let callbackFn = callback { callbackFn() } if let err = error { println(err.description) return } if let msgs = messages { for var i = msgs.count - 1; i >= 0; i-- { if let msg = msgs[i] as? MCOIMAPMessage { self.emailTableViewContents.addObject(EmailEntity(message: msg)) } } } self.showEmailList() self.notifyUser() } } func notifyUser() { if emailTableViewContents != nil && emailTableViewContents.count > 0 { NSNotificationCenter.defaultCenter().postNotificationName("notifyUser", object: nil) } } func initMainView() { // Painting noEmailView white noEmailView.wantsLayer = true noEmailView.layer?.backgroundColor = NSColor.whiteColor().CGColor } func showEmailList() { noEmailView.hidden = emailTableViewContents != nil && emailTableViewContents.count > 0 emailTableView.reloadData() } func numberOfRowsInTableView(tableView: NSTableView) -> NSInteger { if emailTableViewContents == nil { return 0 } return emailTableViewContents.count } func tableView(tableView: NSTableView!, viewForTableColumn tableColumn: NSTableColumn!, row: NSInteger) -> NSView! { if emailTableViewContents.count == 0 { return nil } if let contents = emailTableViewContents { let emailEntity = contents[row] as EmailEntity if let identifier = tableColumn.identifier { if identifier == "MainCell" { if let cellViewObj: AnyObject = tableView.makeViewWithIdentifier("MainCell", owner: self) { let cellView = cellViewObj as EmailTableCellView cellView.senderTextField.stringValue = emailEntity.sender let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle dateFormatter.doesRelativeDateFormatting = true cellView.dateTextField.stringValue = dateFormatter.stringFromDate(emailEntity.date) cellView.subjectTextField.stringValue = emailEntity.subject return cellView } } } } return nil } @IBAction func showAboutWindow(sender: AnyObject) { if aboutController == nil { aboutController = AboutController(windowNibName: "AboutWindow") } aboutController.showWindow(self) } @IBAction func showSettingWindow(sender: AnyObject) { if settingController == nil { settingController = SettingController(windowNibName: "SettingWindow") } settingController.showWindow(self) } @IBAction func reloadEmailList(button: NSButton) { button.enabled = false checkEmail({() -> Void in button.enabled = true }) } @IBAction func removeEmail(button: NSButton) { let emailService = EmailService.instance markEmail(button, markFn: emailService.markAsDeleted) } @IBAction func markEmailAsRead(button: NSButton) { let emailService = EmailService.instance markEmail(button, markFn: emailService.markAsRead) } func markEmail(button: NSButton, markFn: (idx: UInt64, callback: (NSError?) -> Void) -> Void) { button.enabled = false let rowIndex = emailTableView.rowForView(button) let emailEntity = getEntityForRow(rowIndex) markFn(idx: emailEntity.uid, { (error: NSError?) -> Void in button.enabled = true if let errorMsg = error { println(errorMsg) } else { let rowIndex = self.emailTableView.rowForView(button) self.removeEmailFromListViewByIndex(rowIndex) self.showEmailList() self.resetStatusIcon() } }) } func getEntityForRow(row: Int) -> EmailEntity { return emailTableViewContents.objectAtIndex(row) as EmailEntity } func removeEmailFromListViewByIndex(index: Int) -> Void { if index < emailTableViewContents.count { emailTableViewContents.removeObjectAtIndex(index) } } func resetStatusIcon() { if emailTableViewContents.count == 0 { NSNotificationCenter.defaultCenter().postNotificationName("resetStatusIcon", object: nil) } } }
mit
9e5b55fa1b279933b40e1d590e4767ae
33.55102
146
0.590224
5.361837
false
false
false
false
Yalantis/AppearanceNavigationController
AppearanceNavigationController/Misc/UIColor+Extension.swift
1
1348
import Foundation import UIKit extension UIColor { // used solution from http://stackoverflow.com/a/29806108/4405316 var brightness: CGFloat { let colorSpace = cgColor.colorSpace let colorSpaceModel = colorSpace?.model var brightness: CGFloat = 0.0 if colorSpaceModel == .rgb { guard let components = cgColor.components else { return 0 } brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000 } else { getWhite(&brightness, alpha: nil) } return brightness } var isBright: Bool { return brightness > 0.5 } func inverse() -> UIColor { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) return UIColor(red: 1 - red, green: 1 - green, blue: 1 - blue, alpha: alpha) } class func randomColor() -> UIColor { return UIColor( red: CGFloat(arc4random_uniform(255)) / 255, green: CGFloat(arc4random_uniform(255)) / 255, blue: CGFloat(arc4random_uniform(255)) / 255, alpha: CGFloat(arc4random_uniform(100)) / 100 ) } }
mit
42a71f8f1209e52e4674dfcf8077a2cf
28.304348
103
0.551929
4.265823
false
false
false
false
qiandashuai/YH-IOS
YH-IOS/Components/Mine/UserViewController.swift
1
2118
// // UserViewController.swift // YH-IOS // // Created by 钱宝峰 on 2017/6/7. // Copyright © 2017年 com.intfocus. All rights reserved. // import UIKit class UserViewController: UIViewController { var person:Person? { return YHNetworkTool.shareNetWork().loadUserInfo() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.yellow; // loadUserDate() setupTableView() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupTableView(){ let tableView:UITableView = UITableView(frame: view.bounds) view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none tableView.tableHeaderView = headerView headerView.userHead = person } var headerView:MineHeadView = { let headerView = MineHeadView() headerView.frame = CGRect(x: 0, y: 0, width: SCREENWIDTH, height: 300) return headerView }() /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension UserViewController:UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 6 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: "cell") return cell } }
gpl-3.0
49ca0bfa97fa2d15473fcd16d236b309
27.890411
106
0.656235
5.081928
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/Root/Controllers/LeftViewController.swift
1
5935
// // LeftViewController.swift // zhuishushenqi // // Created by Nory Cao on 16/9/16. // Copyright © 2016年 QS. All rights reserved. // import UIKit class LeftViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,XYCActionSheetDelegate { var images = ["hsm_default_avatar","hsm_icon_1","hsm_icon_2","hsm_icon_3"] var selectedIndex = 1 override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) view.backgroundColor = UIColor.brown } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return images.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.qs_dequeueReusableCell(ZSLeftViewCell.self) cell?.backgroundColor = UIColor ( red: 0.16, green: 0.16, blue: 0.16, alpha: 1.0 ) cell?.selectionStyle = .none if indexPath.row == 0 { if ZSLogin.share.hasLogin() { cell?.iconView.qs_setAvatarWithURLString(urlString: ZSThirdLogin.share.userInfo?.user?.avatar ?? "") cell?.nameLabel.text = ZSThirdLogin.share.userInfo?.user?.nickname ?? "" } else { cell?.iconView.image = UIImage(named: images[indexPath.row]) cell?.nameLabel.text = "登录" } } else { cell?.iconView.image = UIImage(named: images[indexPath.row]) cell?.nameLabel.text = "" } if indexPath.row == selectedIndex { cell?.selectedView.isHidden = false } else { cell?.selectedView.isHidden = true } return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedIndex = indexPath.row if indexPath.row == 0 { if ZSLogin.share.hasLogin() { let myVC = ZSMyViewController.init(style: .grouped) myVC.backHandler = { self.selectedIndex = 1 self.tableView.reloadData() } SideVC.closeSideViewController() SideVC.navigationController?.pushViewController(myVC, animated: true) } else { let loginVC = ZSLoginViewController() loginVC.backHandler = { self.selectedIndex = 1 self.tableView.reloadData() } loginVC.loginResultHandler = { success in NotificationCenter.qs_postNotification(name: LoginSuccess, obj: nil) } SideVC.closeSideViewController() SideVC.present(loginVC, animated: true, completion: nil) } }else{ SideVC.closeSideViewController() } self.tableView.reloadData() } func showShare(){ maskView.addSubview(shareActionSheet) KeyWindow?.addSubview(maskView) UIView.animate(withDuration: 0.35, animations: { self.shareActionSheet.frame = CGRect(x: 0, y: ScreenHeight - 200, width: ScreenWidth, height: 200) }, completion: { (finished) in }) } func didSelectedAtIndex(_ index:Int,sheet:XYCActionSheet){ SideVC.closeSideViewController() self.maskView.removeFromSuperview() self.tableView.reloadData() // let indexPath = IndexPath(row: 1, section: 0) // self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle) if index == 1 { ZSThirdLogin.share.successHandler = { self.tableView.reloadData() } ZSThirdLogin.share.QQAuth() self.shareActionSheet.removeFromSuperview() } else if index == 2 { ZSThirdLogin.share.successHandler = { self.tableView.reloadData() } ZSThirdLogin.share.WXAuth() self.shareActionSheet.removeFromSuperview() } if index == 3 { UIView.animate(withDuration: 0.35, animations: { sheet.frame = CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: 200) }, completion: { (finished) in self.maskView.removeFromSuperview() self.shareActionSheet.removeFromSuperview() }) } } fileprivate lazy var tableView:UITableView = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight), style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none tableView.backgroundColor = UIColor(red: 0.211, green: 0.211, blue: 0.211, alpha: 1.00) tableView.qs_registerCellClass(ZSLeftViewCell.self) return tableView }() fileprivate lazy var maskView:UIView = { let maskView = UIView() maskView.frame = self.view.bounds maskView.backgroundColor = UIColor(white: 0.00, alpha: 0.2) return maskView }() fileprivate lazy var shareActionSheet:XYCActionSheet = { let showActionSheet = XYCActionSheet(frame: CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: 200), titles: ["新浪微博账号登录","QQ账号登录","微信登录"]) showActionSheet.delegate = self return showActionSheet }() }
mit
dfe9c1feffbe3f2da431c1244e53bd87
36.081761
153
0.595319
4.860676
false
false
false
false
kissybnts/v-project
Sources/App/Droplet+JWT.swift
1
596
import Vapor import HTTP import JWT extension Droplet { func createJwtToken(_ userId: Int) throws -> String { guard let sig = self.signers?.first?.value else { throw Abort.unauthorized } let timeToLive = 60 * 60.0 // 60min let claims:[Claim] = [ ExpirationTimeClaim(date: Date().addingTimeInterval(timeToLive)), SubjectClaim(string: String(userId)) ] let payload = JSON(claims) let jwt = try JWT(payload: payload, signer: sig) return try jwt.createToken() } }
mit
d523a16cb8fbc1080bc56dffcf8cb31f
26.090909
77
0.575503
4.515152
false
false
false
false
brave/browser-ios
Client/Frontend/Browser/BrowserViewController/BrowserViewController+KeyCommands.swift
1
4696
/* 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 Shared extension BrowserViewController { @objc func reloadTab(){ if homePanelController == nil { tabManager.selectedTab?.reload() } } @objc func goBack(){ if tabManager.selectedTab?.canGoBack == true && homePanelController == nil { tabManager.selectedTab?.goBack() } } @objc func goForward(){ if tabManager.selectedTab?.canGoForward == true && homePanelController == nil { tabManager.selectedTab?.goForward() } } @objc func findOnPage(){ if let tab = tabManager.selectedTab, homePanelController == nil { browser(tab, didSelectFindInPageForSelection: "") } } @objc func selectLocationBar() { urlBar.browserLocationViewDidTapLocation(urlBar.locationView) } @objc func newTab() { openBlankNewTabAndFocus(isPrivate: PrivateBrowsing.singleton.isOn) self.selectLocationBar() } @objc func newPrivateTab() { openBlankNewTabAndFocus(isPrivate: true) let profile = getApp().profile if PinViewController.isBrowserLockEnabled && profile?.prefs.boolForKey(kPrefKeyPopupForDDG) == true { self.selectLocationBar() } } @objc func closeTab() { guard let tab = tabManager.selectedTab else { return } let priv = tab.isPrivate nextOrPrevTabShortcut(false) tabManager.removeTab(tab, createTabIfNoneLeft: !priv) if priv && tabManager.tabs.privateTabs.count == 0 { urlBarDidPressTabs(urlBar) } } fileprivate func nextOrPrevTabShortcut(_ isNext: Bool) { guard let tab = tabManager.selectedTab else { return } let step = isNext ? 1 : -1 let tabList: [Browser] = tabManager.tabs.displayedTabsForCurrentPrivateMode func wrappingMod(_ val:Int, mod:Int) -> Int { return ((val % mod) + mod) % mod } assert(wrappingMod(-1, mod: 10) == 9) let index = wrappingMod((tabList.index(of: tab)! + step), mod: tabList.count) tabManager.selectTab(tabList[index]) } @objc func nextTab() { nextOrPrevTabShortcut(true) } @objc func previousTab() { nextOrPrevTabShortcut(false) } override var keyCommands: [UIKeyCommand]? { let result = [ UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(BrowserViewController.reloadTab), discoverabilityTitle: Strings.ReloadPageTitle), UIKeyCommand(input: "[", modifierFlags: .command, action: #selector(BrowserViewController.goBack), discoverabilityTitle: Strings.BackTitle), UIKeyCommand(input: "]", modifierFlags: .command, action: #selector(BrowserViewController.goForward), discoverabilityTitle: Strings.ForwardTitle), UIKeyCommand(input: "f", modifierFlags: .command, action: #selector(BrowserViewController.findOnPage), discoverabilityTitle: Strings.FindTitle), UIKeyCommand(input: "l", modifierFlags: .command, action: #selector(BrowserViewController.selectLocationBar), discoverabilityTitle: Strings.SelectLocationBarTitle), UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle), //#if DEBUG UIKeyCommand(input: "t", modifierFlags: .control, action: #selector(BrowserViewController.newTab), discoverabilityTitle: Strings.NewTabTitle), //#endif UIKeyCommand(input: "p", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newPrivateTab), discoverabilityTitle: Strings.NewPrivateTabTitle), UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(BrowserViewController.closeTab), discoverabilityTitle: Strings.CloseTabTitle), UIKeyCommand(input: "\t", modifierFlags: .control, action: #selector(BrowserViewController.nextTab), discoverabilityTitle: Strings.ShowNextTabTitle), UIKeyCommand(input: "\t", modifierFlags: [.control, .shift], action: #selector(BrowserViewController.previousTab), discoverabilityTitle: Strings.ShowPreviousTabTitle), ] #if DEBUG // in simulator, CMD+t is slow-mo animation return result + [ UIKeyCommand(input: "t", modifierFlags: [.command, .shift], action: #selector(BrowserViewController.newTab))] #else return result #endif } }
mpl-2.0
0759293cf15554878261ab7a92de4802
45.49505
198
0.666738
5.038627
false
false
false
false
Fiskie/jsrl
jsrl/Library.swift
1
3355
// // MediaPlayer.swift // jsrl // import CoreData import UIKit /** Manages data stored between JSRl playlists and tracks stored in Core Data. Offers a simple API to get tracks by station. */ class Library { static let shared = Library() let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext var list = [Track]() /** Get all tracks belonging to Station. */ func getTracksIn(station: Station) -> [Track] { return self.list.filter({ (track: Track) -> Bool in return station.source == "" || track.station == station.name }) } /** Load library from Core Data. - returns: True if loading from Core Data was successful. */ func loadFromCoreData() -> Bool { let request: NSFetchRequest<Track> = Track.fetchRequest() do { list = try context.fetch(request) return true; } catch { return false; } } func downloadStationPlaylist(_ station: Station, jsrl: JSRL, onComplete: @escaping ()->()) { if (station.source == "") { onComplete() return } let tracklists = jsrl.getTrackLists() print("Populating \(station.name)...") tracklists.parseUrl(source: station.source) { (_, strings: [String]) in let trackList: [NSManagedObject] = strings.map {string in let entity = NSEntityDescription.entity(forEntityName: "Track", in: self.context) let track = NSManagedObject(entity: entity!, insertInto: self.context) track.setValue(string, forKey: "filename") track.setValue(station.name, forKey: "station") return track } print("Found \(trackList.count) songs for \(station.name)") do { try self.context.save() } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } onComplete() } } /** Get library data from the network. */ func populateFrom(jsrl: JSRL, onComplete: @escaping ()->()) { print("Downloading library...") var remaining = Stations.shared.list.count _ = Stations.shared.list.map { downloadStationPlaylist($0, jsrl: jsrl, onComplete: { remaining -= 1 if (remaining == 0) { onComplete() } }) } } } /** Simple class to extract song metadata. We could use the actual metadata but JSRL's MP3's are largely untagged. Instead we split the filename as all songs are stored as Artist - Song Name.mp3 */ class JSRLSongMetadata { var artist = "Unknown Artist" var title = "Unknown Track" init(_ track: Track) { if let currentTrackFile = track.filename { let values = currentTrackFile.components(separatedBy: " - ") if (values.count == 2) { artist = values[0] title = values[1] } else { title = values[0] } } } }
gpl-3.0
f64b3d467baf276248cc5f0b575eef52
27.675214
97
0.528465
4.827338
false
false
false
false
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveMapKitTests/MKMapViewSpec.swift
4
2389
import ReactiveSwift import ReactiveCocoa import ReactiveMapKit import Quick import Nimble import enum Result.NoError import MapKit @available(tvOS 9.2, *) class MKMapViewSpec: QuickSpec { override func spec() { var mapView: MKMapView! weak var _mapView: MKMapView? beforeEach { mapView = MKMapView(frame: .zero) _mapView = mapView } afterEach { autoreleasepool { mapView = nil } // FIXME: SDK_ISSUE // // Temporarily disabled since the expectation keeps failing with // Xcode 8.3 and macOS Sierra 10.12.4. #if !os(macOS) // using toEventually(beNil()) here // since it takes time to release MKMapView expect(_mapView).toEventually(beNil()) #endif } it("should accept changes from bindings to its map type") { expect(mapView.mapType) == MKMapType.standard let (pipeSignal, observer) = Signal<MKMapType, NoError>.pipe() mapView.reactive.mapType <~ pipeSignal observer.send(value: MKMapType.satellite) expect(mapView.mapType) == MKMapType.satellite observer.send(value: MKMapType.hybrid) expect(mapView.mapType) == MKMapType.hybrid } it("should accept changes from bindings to its zoom enabled state") { expect(mapView.isZoomEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isZoomEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isZoomEnabled) == false } it("should accept changes from bindings to its scroll enabled state") { expect(mapView.isScrollEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isScrollEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isScrollEnabled) == false } #if !os(tvOS) it("should accept changes from bindings to its pitch enabled state") { expect(mapView.isPitchEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isPitchEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isPitchEnabled) == false } it("should accept changes from bindings to its rotate enabled state") { expect(mapView.isRotateEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isRotateEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isRotateEnabled) == false } #endif } }
gpl-3.0
4ce7e8b0073b4957e96f739acd00a4e5
24.147368
73
0.710758
3.8224
false
false
false
false
rnystrom/GitHawk
Classes/Issues/Commit/IssueCommitCell.swift
1
3485
// // IssueCommitCell.swift // Freetime // // Created by Ryan Nystrom on 7/26/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import SnapKit import SDWebImage protocol IssueCommitCellDelegate: class { func didTapAvatar(cell: IssueCommitCell) } final class IssueCommitCell: UICollectionViewCell { weak var delegate: IssueCommitCellDelegate? private let commitImageView = UIImageView(image: UIImage(named: "git-commit-small").withRenderingMode(.alwaysTemplate)) private let avatarImageView = UIImageView() private let messageLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) isAccessibilityElement = true accessibilityTraits = UIAccessibilityTraitButton commitImageView.contentMode = .scaleAspectFit commitImageView.tintColor = Styles.Colors.Gray.light.color contentView.addSubview(commitImageView) commitImageView.snp.makeConstraints { make in make.centerY.equalToSuperview() make.left.equalToSuperview() make.size.equalTo(Styles.Sizes.icon) } avatarImageView.contentMode = .scaleAspectFill avatarImageView.backgroundColor = Styles.Colors.Gray.lighter.color avatarImageView.layer.cornerRadius = Styles.Sizes.avatarCornerRadius avatarImageView.layer.borderColor = Styles.Colors.Gray.light.color.cgColor avatarImageView.layer.borderWidth = 1.0 / UIScreen.main.scale avatarImageView.clipsToBounds = true avatarImageView.isUserInteractionEnabled = true avatarImageView.addGestureRecognizer(UITapGestureRecognizer( target: self, action: #selector(IssueCommitCell.onAvatar)) ) avatarImageView.accessibilityIgnoresInvertColors = true contentView.addSubview(avatarImageView) avatarImageView.snp.makeConstraints { make in make.centerY.equalToSuperview() make.left.equalTo(commitImageView.snp.right).offset(Styles.Sizes.columnSpacing) make.size.equalTo(Styles.Sizes.icon) } messageLabel.backgroundColor = .clear messageLabel.font = Styles.Text.secondaryCode.preferredFont messageLabel.textColor = Styles.Colors.Gray.medium.color contentView.addSubview(messageLabel) messageLabel.snp.makeConstraints { make in make.centerY.equalToSuperview() make.left.equalTo(avatarImageView.snp.right).offset(Styles.Sizes.columnSpacing) make.right.lessThanOrEqualToSuperview() } // always collapse and truncate messageLabel.lineBreakMode = .byTruncatingMiddle messageLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentView() } // MARK: Public API func configure(_ model: IssueCommitModel) { avatarImageView.sd_setImage(with: model.avatarURL) messageLabel.text = model.message let labelFormat = NSLocalizedString("%@ committed \"%@\"", comment: "") accessibilityLabel = String(format: labelFormat, arguments: [model.login, model.message]) } // MARK: Private API @objc func onAvatar() { delegate?.didTapAvatar(cell: self) } }
mit
15ea4a73fb4657802a108a835da87ae1
34.191919
123
0.698622
5.231231
false
false
false
false
garvankeeley/winter2017
notes/week_07/CanadaAdd/Classes/Model.swift
2
2959
// // Model.swift // Classes // // Created by Peter McIntyre on 2015-02-01. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import CoreData // Needed for CoreData code generation @objc(Province) class Province : NSManagedObject {} // // This model uses Core Data for storage. // class Model { let cdStack: CDStack let frc_province: NSFetchedResultsController<Province> // MARK: - Public methods init() { var useStoreInitializer = false if Model.isFirstLaunch() { // URL to the object store file in the app bundle let storeFileInBundle = Bundle.main.url(forResource: "ObjectStore", withExtension: "sqlite") // Check whether the app is supplied with starter data in the app bundle let hasStarterData = storeFileInBundle != nil if hasStarterData { // Use the supplied starter data, abort if error copying try! FileManager.default.copyItem(at: storeFileInBundle!, to: Model.pathToStoreFileInDocumentsDir()) } else { useStoreInitializer = true } } cdStack = CDStack() frc_province = cdStack.frcForEntityNamed("Province", withPredicateFormat: nil, predicateObject: nil, sortDescriptors: [NSSortDescriptor(key: "provinceName", ascending: true)], andSectionNameKeyPath: nil) if useStoreInitializer { StoreInitializer.populateInitialData(model: self) } } static func pathToStoreFileInDocumentsDir() -> URL { let applicationDocumentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] return applicationDocumentsDirectory.appendingPathComponent("ObjectStore.sqlite") } static func isFirstLaunch() -> Bool { // Check whether this is the first launch of the app return !FileManager.default.fileExists(atPath: pathToStoreFileInDocumentsDir().path) } func saveChanges() { cdStack.save() } // Add more methods here for data maintenance // For example, get-all, get-some, get-one, add, update, delete // And other command-oriented operations func addNewProvince() -> Province { guard let entity = NSEntityDescription.entity(forEntityName: "Province", in: cdStack.managedObjectContext) else { fatalError("Can't create entity named Province") } return Province(entity: entity, insertInto: cdStack.managedObjectContext) } // Even more specific 'add new province' method func addNewProvince(provinceName: String, premierName: String, areaInKm: Int32, dateCreated: NSDate) -> Province { let newProvince = addNewProvince() newProvince.provinceName = provinceName newProvince.premierName = premierName newProvince.areaInKm = areaInKm newProvince.dateCreated = dateCreated return newProvince } }
mit
d966ce67a53785e507cbd9b3118e74f2
32.625
211
0.672862
4.667192
false
false
false
false
kripple/bti-watson
ios-app/Carthage/Checkouts/ios-sdk/WatsonDeveloperCloud/SpeechToText/SpeechToText.swift
1
8820
/** * Copyright IBM Corporation 2015 * * 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 ObjectMapper /** The IBM® Speech to Text service provides an Application Programming Interface (API) that enables you to add speech transcription capabilities to your applications. */ public class SpeechToText: WatsonService { private let tokenURL = "https://stream.watsonplatform.net/authorization/api/v1/token" private let serviceURL = "/speech-to-text/api" private let serviceURLFull = "https://stream.watsonplatform.net/speech-to-text/api" private let WATSON_AUDIO_SAMPLE_RATE = 16000 private let WATSON_AUDIO_FRAME_SIZE = 160 // NSOperationQueues var transcriptionQueue: NSOperationQueue! public var delegate : SpeechToTextDelegate? private let opus: OpusHelper = OpusHelper() private let ogg: OggHelper = OggHelper() private let watsonSocket: WatsonSocket var audioState: AudioRecorderState? var audioData: NSData? // If set, contains the callback function after a transcription request. var callback: ((SpeechToTextResponse?, NSError?) -> Void)? struct AudioRecorderState { var dataFormat: AudioStreamBasicDescription var queue: AudioQueueRef var buffers: [AudioQueueBufferRef] var bufferByteSize: UInt32 var currentPacket: Int64 var isRunning: Bool var opusEncoder: OpusHelper var oggEncoder: OggHelper var watsonSocket: WatsonSocket } let NUM_BUFFERS = 3 let BUFFER_SIZE: UInt32 = 4096 // The shared WatsonGateway singleton. let gateway = WatsonGateway.sharedInstance // The authentication strategy to obtain authorization tokens. let authStrategy: AuthenticationStrategy public required init(authStrategy: AuthenticationStrategy) { watsonSocket = WatsonSocket(authStrategy: authStrategy) opus.createEncoder(Int32(WATSON_AUDIO_SAMPLE_RATE)) self.authStrategy = authStrategy watsonSocket.delegate = self } public convenience required init(username: String, password: String) { let authStrategy = BasicAuthenticationStrategy( tokenURL: "https://stream.watsonplatform.net/authorization/api/v1/token", serviceURL: "https://stream.watsonplatform.net/speech-to-text/api", username: username, password: password) self.init(authStrategy: authStrategy) } public func startListening() { //var queue = AudioQueueRef() // let buffers:[AudioQueueBufferRef] = [AudioQueueBufferRef(), // AudioQueueBufferRef(), // AudioQueueBufferRef()] // connectWebsocket() let format = AudioStreamBasicDescription( mSampleRate: 16000, mFormatID: kAudioFormatLinearPCM, mFormatFlags: kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked, mBytesPerPacket: 2, mFramesPerPacket: 1, mBytesPerFrame: 2, mChannelsPerFrame: 1, mBitsPerChannel: 8 * 2, mReserved: 0) audioState = AudioRecorderState( dataFormat: format, queue: AudioQueueRef(), buffers: [AudioQueueBufferRef(), AudioQueueBufferRef(), AudioQueueBufferRef()], bufferByteSize: BUFFER_SIZE, currentPacket: 0, isRunning: true, opusEncoder: opus, oggEncoder: ogg, watsonSocket: watsonSocket ) if var audioState = audioState { AudioQueueNewInput(&audioState.dataFormat, recordCallback, &audioState, nil, kCFRunLoopCommonModes, 0, &audioState.queue) for index in 1...NUM_BUFFERS { AudioQueueAllocateBuffer(audioState.queue, BUFFER_SIZE, &audioState.buffers[index-1]) AudioQueueEnqueueBuffer(audioState.queue, audioState.buffers[index-1], 0, nil) } AudioQueueStart(audioState.queue, nil) } else { Log.sharedLogger.error("No audio state object was created.") } } public func stopListening() { if var audioState = audioState { AudioQueueStop(audioState.queue, true) audioState.isRunning = false AudioQueueDispose(audioState.queue, true) } else { Log.sharedLogger.error("Audio state not created") } } /// Callback function when the audio buffer is full var recordCallback : AudioQueueInputCallback = { inUserData, inAQ, inBuffer, inStartTime, inNumberPacketDescriptions, inPacketDescs in let watsonFrameSize = 160 let pUserData = UnsafeMutablePointer<AudioRecorderState>(inUserData) let data: AudioRecorderState = pUserData.memory let buffer = inBuffer.memory let length: Int = Int(buffer.mAudioDataByteSize) if length == 0 { return } let chunkSize: Int = watsonFrameSize * 2 var offset : Int = 0 var ptr = UnsafeMutablePointer<UInt8>(buffer.mAudioData) let newData = NSData(bytesNoCopy: ptr, length: Int(buffer.mAudioDataByteSize), freeWhenDone: false) data.watsonSocket.send(newData) // Log.sharedLogger.info("Added the audio to the queue") //let o1 = AudioUploadOperation(data: newData, socket: data.socket!) //data.audioUploadQueue.addOperation(o1) // Tell the buffer it's free to accept more data AudioQueueEnqueueBuffer(data.queue, inBuffer, 0, nil) } /** This function takes audio data a returns a callback with the string transcription - parameter audio: <#audio description#> - parameter callback: A function that will return the string */ public func transcribe(audioData: NSData, format: MediaType = .FLAC, completionHandler: (SpeechToTextResponse?, NSError?) -> Void) { watsonSocket.format = format watsonSocket.send(audioData) self.callback = completionHandler // connectWebsocket() // // // self.audioData = audioData // self.format = format // // self.callback = completionHandler } /** Description - parameter data: PCM data - returns: Opus encoded audio */ public func encodeOpus(data: NSData) -> NSData { let length: Int = data.length let chunkSize: Int = WATSON_AUDIO_FRAME_SIZE * 2 var offset : Int = 0 var ptr = UnsafeMutablePointer<UInt8>(data.bytes) repeat { let thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset ptr += offset let chunk = NSData(bytesNoCopy: ptr, length: thisChunkSize, freeWhenDone: false) let compressed : NSData = opus.encode(chunk, frameSize: Int32(WATSON_AUDIO_FRAME_SIZE)) if compressed.length != 0 { let newData = ogg.writePacket(compressed, frameSize: Int32(WATSON_AUDIO_FRAME_SIZE)) if newData != nil { // send to websocket Log.sharedLogger.info("Writing a chunk with \(newData.length) bytes") } } offset += thisChunkSize } while offset < length let data = opus.encode(data, frameSize: Int32(WATSON_AUDIO_FRAME_SIZE)) return data } } extension SpeechToText: WatsonSocketDelegate { func onConnected() {} func onListening() {} func onDisconnected() {} func onMessageReceived(result: SpeechToTextResponse) { callback?(result, nil) } }
mit
d826c502a264594c93e0ebf020296dca
29.835664
107
0.603016
5.019351
false
false
false
false
Mazy-ma/DemoBySwift
Solive/Solive/Home/Model/AnchorModel.swift
1
475
// // AnchorModel.swift // Solive // // Created by Mazy on 2017/8/30. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class AnchorModel: BaseModel { var roomid : Int = 0 var name : String = "" var pic51 : String = "" var pic74 : String = "" var live : Int = 0 // 是否在直播 var push : Int = 0 // 直播显示方式 var focus : Int = 0 // 关注数 var uid : String = "" var isEvenIndex : Bool = false }
apache-2.0
0bcdf804a55b04fc092a2993ac438d37
18.304348
48
0.567568
3.264706
false
false
false
false
songhailiang/NLScrollingNavigationBar
NLScrollingNavigationBarDemo/MultiScrollViewController.swift
1
3211
// // MultiScrollViewController.swift // NLScrollingNavigationBarDemo // // Created by songhailiang on 15/06/2017. // Copyright © 2017 hailiang.song. All rights reserved. // import UIKit import NLScrollingNavigationBar class MultiScrollViewController: UIViewController { @IBOutlet weak var headerView: UIView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var leftTable: UITableView! @IBOutlet weak var rightTable: UITableView! var currentIndex = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. leftTable.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") rightTable.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") navigationItem.title = "Multi ScrollView Demo" navigationController?.navigationBar.isTranslucent = false } deinit { print("\(self.classForCoder) \(#function)") } override func viewDidLayoutSubviews() { print("\(self.classForCoder) \(#function)") } func scrollToIndex(_ index: Int) { currentIndex = index if index == 0 { navigationController?.nl_followScrollView(leftTable, followers: [], delegate: self) } else { navigationController?.nl_followScrollView(rightTable, followers: [], delegate: self) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) scrollToIndex(currentIndex) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.nl_showNavigationBar() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) navigationController?.nl_stopFollowScrollView() } } extension MultiScrollViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == leftTable { return 50 } return 80 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let table = tableView == leftTable ? "Left" : "Right" cell.textLabel?.text = "\(table): Row \(indexPath.row)" return cell } } extension MultiScrollViewController: UITableViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.scrollView { let dIndex = scrollView.contentOffset.x / scrollView.bounds.size.width let index = Int(dIndex+0.5) scrollToIndex(index) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) performSegue(withIdentifier: "nobar", sender: nil) // navigationController?.nl_showNavigationBar() } } extension MultiScrollViewController: NLNavigationBarScrollingDelegate { }
mit
824dfd37b43f716d2468d6c7bc6a019e
29.865385
100
0.663551
5.31457
false
false
false
false
PureSwift/BlueZ
Sources/BluetoothLinux/BluetoothProtocol.swift
2
409
// // BluetoothProtocol.swift // BluetoothLinux // // Created by Alsey Coleman Miller on 3/1/16. // Copyright © 2016 PureSwift. All rights reserved. // /// BTPROTO_* public enum BluetoothProtocol: CInt { case l2cap = 0 case hci = 1 case sco = 2 case rfcomm = 3 case bnep = 4 case cmtp = 5 case hidp = 6 case avdtp = 7 }
mit
9d67423e47847784c644fb79a1df1de4
19.4
52
0.539216
3.428571
false
false
false
false
lseeker/HeidiKit
HeidiKit/HDImagePickerController.swift
1
3269
// // HDImagePickerControllerViewController.swift // HeidiKit // // Created by Yun-young LEE on 2015. 1. 29.. // Copyright (c) 2015년 inode.kr. All rights reserved. // import UIKit import Photos open class HDImagePickerController: UINavigationController, PHPhotoLibraryChangeObserver { @IBOutlet open var imagePickerDelegate : HDImagePickerControllerDelegate? @IBInspectable open var maxImageCount = 5 var selectedAssets = [PHAsset]() { willSet { willChangeValue(forKey: "selectedAssets") } didSet { didChangeValue(forKey: "selectedAsstes") } } class open func newImagePickerController() -> HDImagePickerController { return UIStoryboard(name: "HDImagePickerController", bundle: Bundle(for: HDImagePickerController.self)).instantiateInitialViewController() as! HDImagePickerController } public init() { super.init(rootViewController: UIStoryboard(name: "HDImagePickerController", bundle: Bundle(for: HDImagePickerController.self)).instantiateViewController(withIdentifier: "HDIPCAssetCollectionViewController") ) PHPhotoLibrary.shared().register(self) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func awakeFromNib() { super.awakeFromNib() PHPhotoLibrary.shared().register(self) } deinit { PHPhotoLibrary.shared().unregisterChangeObserver(self) } open func photoLibraryDidChange(_ changeInstance: PHChange) { var selectedAssets = self.selectedAssets var removedAssetIndexes = [Int]() for (idx, asset) in selectedAssets.enumerated() { guard let details = changeInstance.changeDetails(for: asset) else { continue } if details.objectWasDeleted { removedAssetIndexes.append(idx) } else if let changed = details.objectAfterChanges as? PHAsset { selectedAssets[idx] = changed } } // reverse for index based remove for removedAssetIndex in removedAssetIndexes.reversed() { selectedAssets.remove(at: removedAssetIndex) } // trigger observation self.selectedAssets = selectedAssets } // behave first responser for doDone and doCancel open override var canBecomeFirstResponder : Bool { return true } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) becomeFirstResponder() } // MARK: - Actions @IBAction func doDone() { if let delegate = imagePickerDelegate { delegate.imagePickerController(self, didFinishWithPhotoAssets: selectedAssets) } else { dismiss(animated: true, completion: nil) } } @IBAction func doCancel() { if let delegate = imagePickerDelegate { if let didCancel = delegate.imagePickerControllerDidCancel { didCancel(self) return } } dismiss(animated: true, completion: nil) } }
apache-2.0
9c0846fb4c3cfa0b375b525946da9591
30.114286
217
0.627181
5.594178
false
false
false
false
LKY769215561/KYHandMade
KYHandMade/KYHandMade/Class/Other(其他)/AppDelegate.swift
1
1066
// // AppDelegate.swift // KYHandMade // // Created by Kerain on 2017/6/8. // Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame:UIScreen.main.bounds) window?.rootViewController = KYCommonTool.chooseRootViewController() configApper() window?.makeKeyAndVisible() KYProgressHUD.setUPHUD() return true } func configApper() { let appearance = UINavigationBar.appearance() let textAttrs : [String : Any] = [ NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont.systemFont(ofSize: 18) ] appearance.titleTextAttributes = textAttrs } }
apache-2.0
dc62827a8f606036d8b113ce094ae2e3
21.543478
144
0.63838
5.211055
false
false
false
false
ArthurKK/SwiftColorArt
Border.swift
2
1984
// // Border.swift // SwiftColorArt // // Created by Jan Gregor Triebel on 11.01.15. // Copyright (c) 2015 Jan Gregor Triebel. All rights reserved. // import Foundation import UIKit import CoreGraphics /// Border /// /// A struct to keep trac of dimensions and border width to check a point's location /// public struct Border { public let rect: CGRect public let width: CGFloat let top: Bool let right: Bool let bottom: Bool let left: Bool public init (rect: CGRect, width: CGFloat, top: Bool, right: Bool, bottom: Bool, left: Bool ){ self.rect = rect self.width = width self.top = top self.right = right self.bottom = bottom self.left = left } public func isPointInBorder(point: CGPoint) -> Bool { if top && point.y <= width { return true } else if right && point.x >= rect.maxX - width { return true } else if bottom && point.y >= rect.maxY - width { return true } else if left && point.x <= width { return true } return false } public func createBorderSet() -> [CGPoint] { var borderSet: [CGPoint] = Array() if top { for x in 0...Int(rect.maxX) { for y in 0...Int(width) { let point = CGPoint(x: x, y: y) borderSet.append(point) } } } if bottom { for x in 0...Int(rect.maxX) { for y in Int(rect.maxY - width)...Int(rect.maxY) { let point = CGPoint(x: x, y: y) borderSet.append(point) } } } if right { for x in Int(rect.maxX - width)...Int(rect.maxX) { for y in 0...Int(rect.maxY) { let point = CGPoint(x: x, y: y) borderSet.append(point) } } } if left { for x in 0...Int(width) { for y in 0...Int(rect.maxY) { let point = CGPoint(x: x, y: y) borderSet.append(point) } } } return borderSet } }
mit
4c816459cda6c49f16d9c15c5303c9a5
20.333333
96
0.543851
3.613843
false
false
false
false
PangeaSocialNetwork/PangeaGallery
PangeaMediaPicker/ImagePicker/BrowserViewController.swift
1
6471
// // BrowserViewController.swift // PangeaMediaPicker // // Created by Roger Li on 2017/9/26. // Copyright © 2017年 Roger Li. All rights reserved. // import UIKit import Photos protocol ImageBrowserDelegate: NSObjectProtocol { func getTheThumbnailImage(_ indexRow: Int) -> UIImage func selectedImageAction(indexItme: IndexPath) -> String? func imageSelectStatus(index: Int) -> String? } class BrowserViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet var mainCollectionView: UICollectionView! fileprivate let imageManager = PHCachingImageManager() fileprivate var thumnailSize = CGSize() // The screen height var screenHeight = UIScreen.main.bounds.size.height // The width of the screen var screenWidth = UIScreen.main.bounds.size.width // Animation time let animationTime = 0.5 weak var delegate: ImageBrowserDelegate? var bottomView: UIView! var isShow = false var defaultImage: UIImage! var indexImage: Int! var number: IndexPath! var arrayImage: PHFetchResult<PHAsset>! @IBOutlet var bottomLeftButton: UIButton! @IBOutlet var bottomRightButton: UIButton! @IBAction func selcetAction(_ sender: UIButton) { if let selectStr = self.delegate?.selectedImageAction(indexItme:number) { bottomRightButton.setTitle(selectStr, for: .selected) bottomRightButton.isSelected = true } else { bottomRightButton.isSelected = false } } @IBAction func cancelAction(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if screenWidth != UIScreen.main.bounds.width { screenWidth = UIScreen.main.bounds.width screenHeight = UIScreen.main.bounds.height isShow = false creatCollectionView() } if isShow == false { self.mainCollectionView.contentOffset = CGPoint(x: screenWidth * CGFloat(self.indexImage), y: 0) isShow = true } } override func viewDidLoad() { super.viewDidLoad() UIApplication.shared.isStatusBarHidden = true creatCollectionView() } deinit { self.mainCollectionView = nil } } extension BrowserViewController { func creatCollectionView() { let fowLayout = UICollectionViewFlowLayout() fowLayout.minimumLineSpacing = 0 fowLayout.minimumInteritemSpacing = 0 fowLayout.scrollDirection = .horizontal fowLayout.itemSize = CGSize(width: screenWidth, height: screenHeight) mainCollectionView.setCollectionViewLayout(fowLayout, animated: false) mainCollectionView.isPagingEnabled = true mainCollectionView.delegate = self mainCollectionView.dataSource = self if let selectStatus = self.delegate?.imageSelectStatus(index: indexImage) { self.bottomRightButton.isSelected = true self.bottomRightButton.setTitle(selectStatus, for: .selected) } else { self.bottomRightButton.isSelected = false } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) if let browserCell = cell as? BrowserCell { thumnailSize = CGSize(width: screenWidth * UIScreen.main.scale, height: screenWidth * UIScreen.main.scale) if (self.delegate?.getTheThumbnailImage(indexPath.row)) != nil { let asset = arrayImage.object(at: indexPath.item) let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true options.deliveryMode = .highQualityFormat options.resizeMode = .none imageManager.requestImage(for: asset, targetSize: thumnailSize, contentMode: .aspectFit, options: options) { img, _ in if let imge = img { browserCell.setImageWithImage(imge,defaultImage: self.defaultImage) } else { browserCell.setImageWithImage(self.defaultImage,defaultImage: self.defaultImage) } } } else { if self.defaultImage == nil { self.defaultImage = UIImage() } let asset = arrayImage.object(at: indexPath.item) imageManager.requestImage(for: asset, targetSize: thumnailSize, contentMode: .aspectFit, options: nil) { img, _ in browserCell.setImageWithImage(img!, defaultImage: self.defaultImage) } } return browserCell } else { return cell } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return arrayImage.count } func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let firstIndexPath = self.mainCollectionView.indexPathsForVisibleItems.first indexImage = firstIndexPath?.row } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.dismiss(animated: true, completion: nil) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { number = self.mainCollectionView.indexPathsForVisibleItems.first if let itemNumber = number?.item, let selectStatus = self.delegate?.imageSelectStatus(index: itemNumber) { self.bottomRightButton.isSelected = true self.bottomRightButton.setTitle(selectStatus, for: .selected) } else { self.bottomRightButton.isSelected = false } } }
mit
1887f101b9365918accd0fef97244ae5
41.27451
128
0.616883
5.648908
false
false
false
false
charmaex/JDCoordinator
Example/JDCoordinator/AppDelegate.swift
1
2498
// // AppDelegate.swift // Demo // // Created by Jan Dammshäuser on 05.09.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import UIKit import JDCoordinator @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var rootViewController: UINavigationController! func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let windowFrame = UIScreen.main.bounds let window = UIWindow(frame: windowFrame) rootViewController = AppCoordinator.main.navigationController // rootViewController.setNavigationBarHidden(true, animated: false) window.rootViewController = rootViewController AppCoordinator.main.start() window.makeKeyAndVisible() self.window = window return true } func applicationWillResignActive(_: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ab8755bbef726258da8eb7185cb94c1e
41.288136
285
0.740681
5.709382
false
false
false
false
hardikdevios/HKKit
Pod/Classes/HKExtensions/Foundation+Extension/Date+Extension.swift
1
6869
// // UIButton+Extension.swift // HKCustomization // // Created by Hardik on 10/18/15. // Copyright © 2015 . All rights reserved. // import UIKit extension Date{ public static func hk_getOnlydate()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MMM-dd" let date = dateFormatter.string(from: Date()) return date } public func hk_getOnlydate()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MMM-dd" let date = dateFormatter.string(from: self) return date } public func hk_getOnlydateStartWithDD()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MMM-yyyy" let date = dateFormatter.string(from: self) return date } public func hk_getOnlyDateWithMM()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let date = dateFormatter.string(from: self) return date } public static func hk_getOnlyTime()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let date = dateFormatter.string(from: Date()) return date } public func hk_getOnlyTime()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let date = dateFormatter.string(from: self) return date } public func hk_getOnlyTimeWithAMPM()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm a" let date = dateFormatter.string(from: self) return date } public func hk_getAMPM()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "a" let date = dateFormatter.string(from: self) return date } public func hk_getOnlyTimeWithDot()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let date = dateFormatter.string(from: self) return date } public func hk_getOnlyTimeWithDotWithSecond()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss" let date = dateFormatter.string(from: self) return date } public func hk_getOnlyTimeWithSeconds()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm:ss a" let date = dateFormatter.string(from: self) return date } public static func hk_getDateFromStringValue(_ str:String)->Date{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MMM-dd" let date = dateFormatter.date(from: str) ?? Date() return date } public static func hk_getDateFromStringWithSeconds(_ dateString:String)->Date{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MMM-dd hh:mm:ss a" let date = dateFormatter.date(from: dateString) return date! } public func hk_getOnlydateWithMonthString()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MMM-dd" let date = dateFormatter.string(from: self) return date } public func hk_getTodayMedicineDate()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "E, MMM dd, yyyy" let date = dateFormatter.string(from: self) return date } public func hk_getDateAndTimeString()->String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MMM-dd hh:mm:ss a" let date = dateFormatter.string(from: self) return date } public static func hk_getCurrentTimeStemp()->Int{ return Int(Date().timeIntervalSince1970) } public func hk_getCurrentTimeStemp()->Int{ return Int(self.timeIntervalSince1970) } public static func hk_getCurrentDateTimeStemp()->Int{ return hk_getDatebyRemovingTimeFromTimeStamp(Date.hk_getOnlydate()) } public func hk_getCurrentDateTimeStemp()->Int{ return Date.hk_getDatebyRemovingTimeFromTimeStamp(self.hk_getOnlydate()) } fileprivate static func hk_getDatebyRemovingTimeFromTimeStamp(_ date:String)->Int{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MMM-dd" let date = dateFormatter.date(from: date) return Int(date!.timeIntervalSince1970) } public static func hk_getTimeStampFromString(_ str:String)->Int{ return Int(hk_getDateFromStringValue(str).timeIntervalSince1970) } public static func hk_getStringDateFromTimeStamp(_ timestamp:Int)->String{ return Date(timeIntervalSince1970: Double(timestamp)).hk_getOnlydateWithMonthString() } public static func hk_getStringDateAndTimeFromTimeStamp(_ timestamp:Int)->String{ return Date(timeIntervalSince1970: Double(timestamp)).hk_getDateAndTimeString() } public static func hk_getStringTimeFromTimeStamp(_ timestamp:Int)->String{ return Date(timeIntervalSince1970: Double(timestamp)).hk_getOnlyTimeWithSeconds() } public static func hk_getTimeStampFromStringWithDateandTime(_ timestamp:Int)->String{ return Date(timeIntervalSince1970: Double(timestamp)).hk_getOnlyTimeWithSeconds() } public static func hk_getHourMinwithDate(_ time:String)->Date!{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm" let date = dateFormatter.date(from: time) ?? Date() return date } public static func hk_getHourMinwithDateDot(_ time:String)->Date!{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH.mm" let date = dateFormatter.date(from: time ) ?? Date() return date } public static func hk_getHourMinSecondswithDate(_ time:String)->Date!{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm:ss a" let date = dateFormatter.date(from: time ) ?? Date() return date } public func hk_getNextDay()->String{ return (Calendar.current as NSCalendar).date( byAdding: .day, value: 1, to: self, options: NSCalendar.Options(rawValue: 0))!.hk_getOnlydate() } public func hk_isGreaterThanDate(_ dateToCompare : Date) -> Bool { var isGreater = false if self.compare(dateToCompare) == ComparisonResult.orderedDescending { isGreater = true } return isGreater } }
mit
293e9a529bc72a3ba77a8816331b4945
32.019231
94
0.635411
4.730028
false
false
false
false
Look-ARound/LookARound2
lookaround2/Models/Annotation.swift
1
5113
// // AugmentedViewController.swift // lookaround2 // // Created by Angela Yu on 10/20/17. // Copyright © 2017 Angela Yu. All rights reserved. // Forked from MapBox + ARKit by MapBox at https://github.com/mapbox/mapbox-arkit-ios // import UIKit import CoreLocation import Mapbox import HDAugmentedReality // Used for AR Callouts public class HDAnnotation: ARAnnotation { // MARK: - Inherited Properties // title: String // location: CLLocation // MARK: - Stored Properties public var leftImage: UIImage? public var anchor: LookAnchor? var place: Place? public var coordinate: CLLocationCoordinate2D public var subtitle: String? // Custom properties that we will use to customize the annotation's image. var image: UIImage? var reuseIdentifier: String? init?(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?) { self.coordinate = coordinate self.subtitle = subtitle let loc = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) super.init(identifier: subtitle, title: title, location: loc) } init?(location: CLLocation, leftImage: UIImage?, place: Place?) { var placeTitle = "" self.coordinate = location.coordinate if let myPlace = place { self.place = myPlace placeTitle = myPlace.name if let checkinCount = myPlace.checkins { if let friendCount = myPlace.contextCount { switch friendCount { case 1: self.subtitle = "\(friendCount) friend likes this" case _ where friendCount > 1: self.subtitle = "\(friendCount) friends like this" case 0: self.subtitle = "\(checkinCount) checkins here" default: self.subtitle = nil } } } } if let leftImage = leftImage { self.leftImage = leftImage } super.init(identifier: subtitle, title: placeTitle, location: location) } } // MARK: - Annotation class // Used for 2D map annotations & callouts and for AR directions public class Annotation: NSObject, MGLAnnotation { public var location: CLLocation public var nodeImage: UIImage? public var calloutImage: UIImage? public var anchor: LookAnchor? var place: Place? public var coordinate: CLLocationCoordinate2D public var title: String? public var subtitle: String? // Custom properties that we will use to customize the annotation's image. var image: UIImage? var reuseIdentifier: String? init(coordinate: CLLocationCoordinate2D, title: String?, subtitle: String?) { self.coordinate = coordinate self.title = title self.subtitle = subtitle self.location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) } init(location: CLLocation, calloutImage: UIImage?, place: Place?) { self.location = location self.coordinate = location.coordinate if let myPlace = place { self.place = myPlace self.title = myPlace.name if let checkinCount = myPlace.checkins { if let friendCount = myPlace.contextCount { switch friendCount { case 1: self.subtitle = "\(friendCount) friend likes this" case _ where friendCount > 1: self.subtitle = "\(friendCount) friends like this" case 0: self.subtitle = "\(checkinCount) checkins here" default: self.subtitle = nil } } } } if let image = calloutImage { self.calloutImage = image } } init(location: CLLocation, nodeImage: UIImage?, calloutImage: UIImage?, place: Place?) { self.location = location self.coordinate = location.coordinate if let myPlace = place { self.place = myPlace self.title = myPlace.name if let checkinCount = myPlace.checkins { if let friendCount = myPlace.contextCount { switch friendCount { case 1: self.subtitle = "\(friendCount) friend likes this" case _ where friendCount > 1: self.subtitle = "\(friendCount) friends like this" case 0: self.subtitle = "\(checkinCount) checkins here" default: self.subtitle = nil } } } } if let nodeImage = nodeImage { self.nodeImage = nodeImage } if let calloutImage = calloutImage { self.calloutImage = calloutImage } } }
apache-2.0
c8e5e1e22c42fc570cda28b2cfcbfc6e
33.540541
98
0.563185
5.09671
false
false
false
false
aestusLabs/ASChatApp
HistoryViewController.swift
1
6086
// // HistoryViewController.swift // breathe by aestus.health // // Created by Ian Kohlert on 2017-08-18. // Copyright © 2017 aestusLabs. All rights reserved. // import UIKit import CoreData class HistoryViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate { let historyCellIdentifier = "historyCellReuseIdentifier" var topLabel = UILabel() var tableView = UITableView() var topBar = UIView() var coreDataStack = CoreDataStack(modelName: appInfo.dataModelName) // will need to grab this from elsewhere to make it re-usable var managedContext : NSManagedObjectContext! var fetchedResultsController: NSFetchedResultsController<History>! override func viewDidLoad() { super.viewDidLoad() print(self.view.frame.width) // Do any additional setup after loading the view. topBar = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 70)) topBar.backgroundColor = UIColor.white self.view.addSubview(topBar) topLabel = UILabel(frame: CGRect(x: 10, y: topBar.frame.maxY - 45, width: self.view.frame.width, height: 40)) topLabel.text = "History" topLabel.font = UIFont.systemFont(ofSize: 35, weight: UIFontWeightHeavy) // topLabel.center.y = topBar.center.y topLabel.textAlignment = .left self.view.addSubview(topLabel) tableView = UITableView(frame: CGRect(x: 0, y: topBar.frame.maxY, width: self.view.frame.width, height: self.view.frame.height - topBar.frame.height)) tableView.register(HistoryTableViewCell.self, forCellReuseIdentifier: historyCellIdentifier) tableView.rowHeight = 100 tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none // tableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell") self.view.addSubview(tableView) let fetchRequest: NSFetchRequest<History> = History.fetchRequest() let dateSort = NSSortDescriptor(key: #keyPath(History.date), ascending: false) fetchRequest.sortDescriptors = [dateSort] fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: coreDataStack.managedContext, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController.delegate = self do { try fetchedResultsController.performFetch() print(fetchedResultsController) } catch let error as NSError { print("Fetching error: \(error), \(error.userInfo)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { print("##") guard let sections = fetchedResultsController.sections else { return 0 } print(sections.count) return sections.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let sectionInfo = fetchedResultsController.sections?[section] else { print("0") return 0 } print(sectionInfo.numberOfObjects) return sectionInfo.numberOfObjects } func configure(cell: UITableViewCell, for indexPath: IndexPath) { // this will need to be moved to an app specific place // this will send the object to a app specific function and recieve back a view guard let cell = cell as? HistoryTableViewCell else { return } let session = fetchedResultsController.object(at: indexPath) print(fetchedResultsController.object(at: indexPath)) print(cell.frame.width) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .long dateFormatter.timeStyle = .short cell.dateLabel.text = String(describing: dateFormatter.string(from: session.date! as Date)) // TODO this will need to be be moved to an appSpecific file // Have the history cell have a UIView that is filled with a session widget that is created elsewhere let widget = createUpdatedSessionWidgetForHistory(session: session) //createSessionWidgetForHistory(session: session) cell.module = widget // cell.addSubview(widget) // cell.sessionWidget.title.text = session.metaData!.sessionType! // // below will need to grab the session type and get correct image for that type // cell.sessionWidget.imageView.image = #imageLiteral(resourceName: "Lungs") // cell.sessionWidget.time.text = "\(session.metaData!.minutesSpent)m" // cell.sessionWidget.exhale = 4 } func createSessionWidgetForHistory(session: History) -> SessionWidget{ let widget = createSessionWidget(screenWidth: self.view.frame.width, title: session.metaData!.sessionType!, image: #imageLiteral(resourceName: "Lungs"), text: "LLALALLLA", time: "\(session.metaData!.minutesSpent)m", numberOfDots: 4, exhale: 1, duration: 49, tag: .calmExercises) return widget } func createUpdatedSessionWidgetForHistory(session: History) -> UpdatedSessionWidget { let widget = createUpdatedSessionWidget(screenWidth: self.view.frame.width, title: session.metaData!.sessionType!, image: #imageLiteral(resourceName: "Lungs"), time: "\(session.metaData!.minutesSpent)m", numberOfDots: 3) return widget } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: historyCellIdentifier, for: indexPath) as! HistoryTableViewCell cell.module.backgroundColor = UIColor.blue configure(cell: cell, for: indexPath) // cell.textLabel!.text = "HHHHHH" print("!!!") return cell } }
mit
bcbcc6807e0ff1a88f872a623b2f3c82
43.742647
286
0.680855
4.963295
false
false
false
false