repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jpush/jchat-swift
JChat/Src/ChatModule/Chat/View/Message/JCMessageVideoContent.swift
1
1477
// // JCMessageVideoContent.swift // JChat // // Created by JIGUANG on 2017/3/9. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import JMessage let JC_VIDEO_MSG_IMAGE_WIDTH: CGFloat = 160.0 let JC_VIDEO_MSG_IMAGE_HEIGHT: CGFloat = 120.0 open class JCMessageVideoContent: NSObject, JCMessageContentType { typealias uploadVideoHandle = (_ percent: Float) -> () public weak var delegate: JCMessageDelegate? var uploadVideo: uploadVideoHandle? open var layoutMargins: UIEdgeInsets = .zero open class var viewType: JCMessageContentViewType.Type { return JCMessageVideoContentView.self } open var data: Data? open var image: UIImage? //open var fileContent: JMSGFileContent? open var videoContent: JMSGVideoContent? //由于andriod暂时不支持文件视频类型,故sdk对文件视频类的做了特殊处理 open var videoFileContent: JMSGFileContent? open func sizeThatFits(_ size: CGSize) -> CGSize { printLog("viedeo") if image == nil { return .init(width: 140, height: 89) } //image = JCVideoManager.getFristImage(data: data!) let size = image?.size ?? .zero let scale = min(min(JC_VIDEO_MSG_IMAGE_WIDTH, size.width) / size.width, min(JC_VIDEO_MSG_IMAGE_HEIGHT, size.height) / size.height) let w = size.width * scale let h = size.height * scale return .init(width: w, height: h) } }
mit
cbbb294bf81f8afd3ec45ba58075c6b3
30.511111
138
0.667842
3.70235
false
false
false
false
krzysztofzablocki/Sourcery
SourceryFramework/Sources/Parsing/SwiftSyntax/FileParserSyntax.swift
1
2687
import Foundation import SwiftSyntax import SwiftParser import PathKit import SourceryRuntime import SourceryUtils public final class FileParserSyntax: SyntaxVisitor, FileParserType { public let path: String? public let modifiedDate: Date? private let module: String? private let initialContents: String fileprivate var inlineRanges: [String: NSRange]! fileprivate var inlineIndentations: [String: String]! fileprivate var forceParse: [String] = [] fileprivate var parseDocumentation: Bool = false /// Parses given contents. /// - Throws: parsing errors. public init(contents: String, forceParse: [String] = [], parseDocumentation: Bool, path: Path? = nil, module: String? = nil) throws { self.path = path?.string self.modifiedDate = path.flatMap({ (try? FileManager.default.attributesOfItem(atPath: $0.string)[.modificationDate]) as? Date }) self.module = module self.initialContents = contents self.forceParse = forceParse self.parseDocumentation = parseDocumentation super.init(viewMode: .fixedUp) } /// Parses given file context. /// /// - Returns: All types we could find. public func parse() throws -> FileParserResult { // Inline handling let inline = TemplateAnnotationsParser.parseAnnotations("inline", contents: initialContents, forceParse: self.forceParse) let contents = inline.contents inlineRanges = inline.annotatedRanges.mapValues { $0[0].range } inlineIndentations = inline.annotatedRanges.mapValues { $0[0].indentation } // Syntax walking let tree = try Parser.parse(source: contents) let fileName = path ?? "in-memory" let sourceLocationConverter = SourceLocationConverter(file: fileName, tree: tree) let collector = SyntaxTreeCollector( file: fileName, module: module, annotations: AnnotationsParser(contents: contents, parseDocumentation: parseDocumentation, sourceLocationConverter: sourceLocationConverter), sourceLocationConverter: sourceLocationConverter) collector.walk(tree) collector.types.forEach { $0.imports = collector.imports $0.path = path } return FileParserResult( path: path, module: module, types: collector.types, functions: collector.methods, typealiases: collector.typealiases, inlineRanges: inlineRanges, inlineIndentations: inlineIndentations, modifiedDate: modifiedDate ?? Date(), sourceryVersion: SourceryVersion.current.value ) } }
mit
13a89f631da9fca8e8ea8f007ba61254
36.319444
151
0.675475
5.127863
false
false
false
false
DenHeadless/DTCollectionViewManager
Sources/DTCollectionViewManager/CollectionViewUpdater.swift
1
5248
// // CollectionViewUpdater.swift // DTCollectionViewManager // // Created by Denys Telezhkin on 03.09.16. // Copyright © 2016 Denys Telezhkin. All rights reserved. // import Foundation import UIKit import DTModelStorage /// `CollectionViewUpdater` is responsible for updating `UICollectionView`, when it receives storage updates. open class CollectionViewUpdater : StorageUpdating { /// collection view, that will be updated weak var collectionView: UICollectionView? /// closure to be executed before content is updated open var willUpdateContent: ((StorageUpdate?) -> Void)? /// closure to be executed after content is updated open var didUpdateContent: ((StorageUpdate?) -> Void)? /// Closure to be executed, when reloading an item. /// /// - SeeAlso: `DTCollectionViewManager.updateCellClosure()` method and `DTCollectionViewManager.coreDataUpdater()` method. open var reloadItemClosure : ((IndexPath, Any) -> Void)? /// When this property is true, move events will be animated as delete event and insert event. open var animateMoveAsDeleteAndInsert: Bool /// If turned on, animates changes off screen, otherwise calls `collectionView.reloadData` when update come offscreen. To verify if collectionView is onscreen, `CollectionViewUpdater` compares collectionView.window to nil. Defaults to true. open var animateChangesOffScreen : Bool = true /// Creates updater. public init(collectionView: UICollectionView, reloadItem: ((IndexPath, Any) -> Void)? = nil, animateMoveAsDeleteAndInsert: Bool = false) { self.collectionView = collectionView self.reloadItemClosure = reloadItem self.animateMoveAsDeleteAndInsert = animateMoveAsDeleteAndInsert } /// Updates `UICollectionView` with received `update`. This method applies object and section changes in `performBatchUpdates` method. open func storageDidPerformUpdate(_ update : StorageUpdate) { willUpdateContent?(update) if !animateChangesOffScreen, collectionView?.window == nil { collectionView?.reloadData() didUpdateContent?(update) return } collectionView?.performBatchUpdates({ [weak self] in if update.containsDeferredDatasourceUpdates { update.applyDeferredDatasourceUpdates() } self?.applyObjectChanges(from: update) self?.applySectionChanges(from: update) }, completion: { [weak self] _ in if update.sectionChanges.count > 0 { self?.collectionView?.reloadData() } }) didUpdateContent?(update) } private func applyObjectChanges(from update: StorageUpdate) { for (change, indexPaths) in update.objectChanges { switch change { case .insert: if let indexPath = indexPaths.first { collectionView?.insertItems(at: [indexPath]) } case .delete: if let indexPath = indexPaths.first { collectionView?.deleteItems(at: [indexPath]) } case .update: if let indexPath = indexPaths.first { if let closure = reloadItemClosure, let model = update.updatedObjects[indexPath] { closure(indexPath, model) } else { collectionView?.reloadItems(at: [indexPath]) } } case .move: if let source = indexPaths.first, let destination = indexPaths.last { if animateMoveAsDeleteAndInsert { collectionView?.moveItem(at: source, to: destination) } else { collectionView?.deleteItems(at: [source]) collectionView?.insertItems(at: [destination]) } } } } } private func applySectionChanges(from update: StorageUpdate) { for (change, indices) in update.sectionChanges { switch change { case .delete: if let index = indices.first { collectionView?.deleteSections([index]) } case .insert: if let index = indices.first { collectionView?.insertSections([index]) } case .update: if let index = indices.first { collectionView?.reloadSections([index]) } case .move: if let source = indices.first, let destination = indices.last { collectionView?.moveSection(source, toSection: destination) } } } } /// Call this method, if you want UICollectionView to be reloaded, and beforeContentUpdate: and afterContentUpdate: closures to be called. open func storageNeedsReloading() { willUpdateContent?(nil) collectionView?.reloadData() didUpdateContent?(nil) } }
mit
0f9bde7107da29a70def67f03bc7c301
39.053435
244
0.591957
5.617773
false
false
false
false
oper0960/GWExtensions
GWExtensions/Classes/StringExtension.swift
1
2087
// // StringExtension.swift // Pods // // Created by Ryu on 2017. 4. 18.. // // import UIKit public extension String { // String Trim public var stringTrim: String{ return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } // Return String chracters count public var length: Int { return self.count } // String reversed public func reversed() -> String { return self.reversed().map { String($0) }.joined(separator: "") } // String localized public var localized: String { return NSLocalizedString(self, comment: "") } // String localized with comment public func localizedWithComment(comment: String) -> String { return NSLocalizedString(self, comment:comment) } // E-mail address validation public func validateEmail() -> Bool { let emailRegEx = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$" let predicate = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return predicate.evaluate(with: self) } // Password validation public func validatePassword() -> Bool { let passwordRegEx = "^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,16}$" let predicate = NSPredicate(format:"SELF MATCHES %@", passwordRegEx) return predicate.evaluate(with: self) } // String split return array public func arrayBySplit(splitter: String? = nil) -> [String] { if let s = splitter { return self.components(separatedBy: s) } else { return self.components(separatedBy: NSCharacterSet.whitespacesAndNewlines) } } } public extension Optional { // Check NotEmpty public var isNotEmpty: Bool { guard let str = self as? String else { return false } return !str.isEmpty } // Check NotEmpty return String public var isNotEmptyString: String { guard let str = self as? String else { return "" } return str } }
mit
da91d72449c08ac5c69ac95464df57fc
24.765432
86
0.582175
4.507559
false
false
false
false
shuoli84/RxSwift
RxSwift/RxSwift/Subjects/ReplaySubject.swift
2
6967
// // ReplaySubject.swift // RxSwift // // Created by Krunoslav Zaher on 4/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ReplaySubjectImplementation<Element> : SubjectType<Element, Element>, Disposable { typealias Observer = ObserverOf<Element> typealias BagType = Bag<Observer> typealias DisposeKey = BagType.KeyType var hasObservers: Bool { get { return abstractMethod() } } func unsubscribe(key: DisposeKey) { return abstractMethod() } func dispose() { } } class ReplaySubscription<Element> : Disposable { typealias Observer = ObserverOf<Element> typealias BagType = Bag<Observer> typealias DisposeKey = BagType.KeyType typealias Subject = ReplaySubjectImplementation<Element> typealias State = ( subject: Subject?, disposeKey: DisposeKey? ) var lock = Lock() var state: State init(subject: Subject, disposeKey: DisposeKey) { self.state = ( subject: subject, disposeKey: disposeKey ) } func dispose() { let oldState = lock.calculateLocked { () -> State in var state = self.state self.state = ( subject: nil, disposeKey: nil ) return state } if let subject = oldState.subject, disposeKey = oldState.disposeKey { subject.unsubscribe(disposeKey) } } } class ReplayBufferBase<Element> : ReplaySubjectImplementation<Element> { typealias Observer = ObserverOf<Element> typealias BagType = Bag<Observer> typealias DisposeKey = BagType.KeyType typealias State = ( disposed: Bool, stoppedEvent: Event<Element>?, observers: BagType ) var lock = Lock() var state: State = ( disposed: false, stoppedEvent: nil, observers: Bag() ) override init() { } func trim() { return abstractMethod() } func addValueToBuffer(value: Element) { return abstractMethod() } func replayBuffer(observer: Observer) { return abstractMethod() } override var hasObservers: Bool { get { return state.observers.count > 0 } } override func on(event: Event<Element>) { let observers: [Observer] = lock.calculateLocked { if self.state.disposed { return [] } if self.state.stoppedEvent != nil { return [] } switch event { case .Next(let boxedValue): let value = boxedValue.value addValueToBuffer(value) trim() return self.state.observers.all case .Error: fallthrough case .Completed: state.stoppedEvent = event trim() var bag = self.state.observers var observers = bag.all bag.removeAll() return observers } } dispatch(event, observers) } override func subscribe<O : ObserverType where O.Element == Element>(observer: O) -> Disposable { return lock.calculateLocked { if self.state.disposed { sendError(observer, DisposedError) return NopDisposable.instance } let observerOf = ObserverOf(observer) replayBuffer(observerOf) if let stoppedEvent = self.state.stoppedEvent { observer.on(stoppedEvent) return NopDisposable.instance } else { let key = self.state.observers.put(observerOf) return ReplaySubscription(subject: self, disposeKey: key) } } } override func unsubscribe(key: DisposeKey) { lock.performLocked { if self.state.disposed { return } _ = self.state.observers.removeKey(key) } } func lockedDispose() { state.disposed = true state.observers.removeAll() } override func dispose() { super.dispose() lock.performLocked { self.lockedDispose() } } } class ReplayOne<Element> : ReplayBufferBase<Element> { var value: Element? init(firstElement: Element) { self.value = firstElement super.init() } override init() { super.init() } override func trim() { } override func addValueToBuffer(value: Element) { self.value = value } override func replayBuffer(observer: Observer) { if let value = self.value { sendNext(observer, value) } } override func lockedDispose() { super.lockedDispose() value = nil } } class ReplayManyBase<Element> : ReplayBufferBase<Element> { var queue: Queue<Element> init(queueSize: Int) { queue = Queue(capacity: queueSize + 1) } override func addValueToBuffer(value: Element) { queue.enqueue(value) } override func replayBuffer(observer: Observer) { for item in queue { sendNext(observer, item) } } override func lockedDispose() { super.lockedDispose() while queue.count > 0 { queue.dequeue() } } } class ReplayMany<Element> : ReplayManyBase<Element> { let bufferSize: Int init(bufferSize: Int) { self.bufferSize = bufferSize super.init(queueSize: bufferSize) } override func trim() { while queue.count > bufferSize { queue.dequeue() } } } class ReplayAll<Element> : ReplayManyBase<Element> { init() { super.init(queueSize: 0) } override func trim() { } } public class ReplaySubject<Element> : SubjectType<Element, Element> { typealias Observer = ObserverOf<Element> typealias BagType = Bag<Observer> typealias DisposeKey = BagType.KeyType let implementation: ReplaySubjectImplementation<Element> public init(bufferSize: Int) { if bufferSize == 1 { implementation = ReplayOne() } else { implementation = ReplayMany(bufferSize: bufferSize) } } public override func subscribe<O : ObserverType where O.Element == Element>(observer: O) -> Disposable { return implementation.subscribe(observer) } public override func on(event: Event<Element>) { implementation.on(event) } }
mit
1492369a390ae4dadd9c46d2d9f292da
22.863014
108
0.54672
5.218727
false
false
false
false
tjw/swift
stdlib/private/StdlibUnittest/StdlibCoreExtras.swift
2
7567
//===--- StdlibCoreExtras.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftPrivate import SwiftPrivateLibcExtras #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) import Glibc #endif #if _runtime(_ObjC) import Foundation #endif // // These APIs don't really belong in a unit testing library, but they are // useful in tests, and stdlib does not have such facilities yet. // func findSubstring(_ haystack: Substring, _ needle: String) -> String.Index? { return findSubstring(String(haystack._ephemeralContent), needle) } func findSubstring(_ string: String, _ substring: String) -> String.Index? { if substring.isEmpty { return string.startIndex } #if _runtime(_ObjC) return string.range(of: substring)?.lowerBound #else // FIXME(performance): This is a very non-optimal algorithm, with a worst // case of O((n-m)*m). When non-objc String has a match function that's better, // this should be removed in favor of using that. // Operate on unicode scalars rather than codeunits. let haystack = string.unicodeScalars let needle = substring.unicodeScalars for matchStartIndex in haystack.indices { var matchIndex = matchStartIndex var needleIndex = needle.startIndex while true { if needleIndex == needle.endIndex { // if we hit the end of the search string, we found the needle return matchStartIndex } if matchIndex == haystack.endIndex { // if we hit the end of the string before finding the end of the needle, // we aren't going to find the needle after that. return nil } if needle[needleIndex] == haystack[matchIndex] { // keep advancing through both the string and search string on match matchIndex = haystack.index(after: matchIndex) needleIndex = haystack.index(after: needleIndex) } else { // no match, go back to finding a starting match in the string. break } } } return nil #endif } public func createTemporaryFile( _ fileNamePrefix: String, _ fileNameSuffix: String, _ contents: String ) -> String { #if _runtime(_ObjC) let tempDir: NSString = NSTemporaryDirectory() as NSString var fileName = tempDir.appendingPathComponent( fileNamePrefix + "XXXXXX" + fileNameSuffix) #else var fileName = fileNamePrefix + "XXXXXX" + fileNameSuffix #endif let fd = _stdlib_mkstemps( &fileName, CInt(fileNameSuffix.utf8.count)) if fd < 0 { fatalError("mkstemps() returned an error") } var stream = _FDOutputStream(fd: fd) stream.write(contents) if close(fd) != 0 { fatalError("close() return an error") } return fileName } public final class Box<T> { public init(_ value: T) { self.value = value } public var value: T } infix operator <=> public func <=> <T: Comparable>(lhs: T, rhs: T) -> ExpectedComparisonResult { return lhs < rhs ? .lt : lhs > rhs ? .gt : .eq } public struct TypeIdentifier : Hashable, Comparable { public init(_ value: Any.Type) { self.value = value } public var hashValue: Int { return objectID.hashValue } public var value: Any.Type internal var objectID : ObjectIdentifier { return ObjectIdentifier(value) } } public func < (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool { return lhs.objectID < rhs.objectID } public func == (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool { return lhs.objectID == rhs.objectID } extension TypeIdentifier : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return String(describing: value) } public var debugDescription: String { return "TypeIdentifier(\(description))" } } enum FormNextPermutationResult { case success case formedFirstPermutation } extension MutableCollection where Self : BidirectionalCollection, Iterator.Element : Comparable { mutating func _reverseSubrange(_ subrange: Range<Index>) { if subrange.isEmpty { return } var f = subrange.lowerBound var l = index(before: subrange.upperBound) while f < l { swapAt(f, l) formIndex(after: &f) formIndex(before: &l) } } mutating func formNextPermutation() -> FormNextPermutationResult { if isEmpty { // There are 0 elements, only one permutation is possible. return .formedFirstPermutation } do { var i = startIndex formIndex(after: &i) if i == endIndex { // There is only element, only one permutation is possible. return .formedFirstPermutation } } var i = endIndex formIndex(before: &i) var beforeI = i formIndex(before: &beforeI) var elementAtI = self[i] var elementAtBeforeI = self[beforeI] while true { if elementAtBeforeI < elementAtI { // Elements at `i..<endIndex` are in non-increasing order. To form the // next permutation in lexicographical order we need to replace // `self[i-1]` with the next larger element found in the tail, and // reverse the tail. For example: // // i-1 i endIndex // V V V // 6 2 8 7 4 1 [ ] // Input. // 6 (4) 8 7 (2) 1 [ ] // Exchanged self[i-1] with the // ^--------^ // next larger element // // from the tail. // 6 4 (1)(2)(7)(8)[ ] // Reversed the tail. // <--------> var j = endIndex repeat { formIndex(before: &j) } while !(elementAtBeforeI < self[j]) swapAt(beforeI, j) _reverseSubrange(i..<endIndex) return .success } if beforeI == startIndex { // All elements are in non-increasing order. Reverse to form the first // permutation, where all elements are sorted (in non-increasing order). reverse() return .formedFirstPermutation } i = beforeI formIndex(before: &beforeI) elementAtI = elementAtBeforeI elementAtBeforeI = self[beforeI] } } } /// Generate all permutations. public func forAllPermutations(_ size: Int, _ body: ([Int]) -> Void) { var data = Array(0..<size) repeat { body(data) } while data.formNextPermutation() != .formedFirstPermutation } /// Generate all permutations. public func forAllPermutations<S : Sequence>( _ sequence: S, _ body: ([S.Iterator.Element]) -> Void ) { let data = Array(sequence) forAllPermutations(data.count) { (indices: [Int]) in body(indices.map { data[$0] }) return () } } public func cartesianProduct<C1 : Collection, C2 : Collection>( _ c1: C1, _ c2: C2 ) -> [(C1.Iterator.Element, C2.Iterator.Element)] { var result: [(C1.Iterator.Element, C2.Iterator.Element)] = [] for e1 in c1 { for e2 in c2 { result.append((e1, e2)) } } return result } /// Return true if the standard library was compiled in a debug configuration. public func _isStdlibDebugConfiguration() -> Bool { #if SWIFT_STDLIB_DEBUG return true #else return false #endif }
apache-2.0
abe8bebddc176e477c706a290c819f03
28.216216
85
0.637769
4.092482
false
false
false
false
cwwise/CWWeChat
CWWeChat/MainClass/Base/CWWebView/CWWebViewController.swift
2
8804
// // CWWebViewController.swift // CWWeChat // // Created by chenwei on 16/6/23. // Copyright © 2016年 chenwei. All rights reserved. // import UIKit import WebKit import KVOController import CWShareView private var webViewContentKey = "webViewContentKey" private var webViewBackgroundColorKey = "webViewBackgroundColorKey" private let webView_Items_Fixed_Space: CGFloat = 9 /** 展示网页信息 */ class CWWebViewController: UIViewController { ///是否使用网页标题作为nav标题,默认YES var usepageTitleAsTitle: Bool = true ///是否显示加载进度,默认YES var showLoadingProgress: Bool = true { didSet { self.progressView.isHidden = !showLoadingProgress } } ///是否禁止历史记录,默认NO var disableBackButton: Bool = false /// url var url: URL? /// WKWebView private lazy var webView:WKWebView = { let configure = WKWebViewConfiguration() let frame = CGRect(x: 0, y: kNavigationBarHeight, width: kScreenWidth, height: kScreenHeight-kNavigationBarHeight) let webView = WKWebView(frame: frame, configuration: configure) webView.allowsBackForwardNavigationGestures = true webView.navigationDelegate = self webView.scrollView.backgroundColor = UIColor.clear return webView }() /// 展示进度 private lazy var progressView: UIProgressView = { let frame = CGRect(x: 0, y: kNavigationBarHeight, width: kScreenWidth, height: 10) let progressView = UIProgressView(frame: frame) progressView.progressTintColor = UIColor.chatSystemColor() progressView.trackTintColor = UIColor.clear return progressView }() private lazy var backButtonItem: UIBarButtonItem = { let backButtonItem = UIBarButtonItem(backTitle: "返回", target: self, action: #selector(navigationBackButtonDown)) return backButtonItem }() private lazy var closeButtonItem: UIBarButtonItem = { let closeButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(navigationCloseButtonDown)) return closeButtonItem }() fileprivate var authLabel: UILabel = { let frame = CGRect(x: 20, y: kNavigationBarHeight+13, width: kScreenWidth-2*20, height: 0) let authLabel = UILabel(frame: frame) authLabel.font = UIFont.systemFont(ofSize: 12) authLabel.textAlignment = .center authLabel.textColor = UIColor(hex: "#6b6f71") authLabel.numberOfLines = 1 return authLabel }() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } required convenience init(url: URL?) { self.init() self.url = url } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.defaultBlackColor() self.view.addSubview(authLabel) self.view.addSubview(webView) self.view.addSubview(progressView) self.navigationItem.leftBarButtonItems = [backButtonItem] let barItemImage = UIImage(named: "barbuttonicon_more") let rightBarItem = UIBarButtonItem(image: barItemImage, style: .done, target: self, action: #selector(rightBarItemClick)) self.navigationItem.rightBarButtonItem = rightBarItem //遍历设置背景颜色 for subView in webView.scrollView.subviews { if "\(subView.classForCoder)" == "WKContentView" { subView.backgroundColor = UIColor.white } } weak var weak_self = self kvoController.observe(webView, keyPath: "estimatedProgress", options: .new) { (viewController, webView, change) in guard let strong_self = weak_self else { return } strong_self.progressView.alpha = 1 strong_self.progressView.setProgress(Float(strong_self.webView.estimatedProgress), animated: true) if strong_self.webView.estimatedProgress >= 1.0 { UIView.animate(withDuration: 0.3, delay: 0.25, options: UIViewAnimationOptions(), animations: { strong_self.progressView.alpha = 0 }, completion: { (finished) in strong_self.progressView.setProgress(0, animated: false) }) } } kvoController.observe(webView.scrollView, keyPath: "backgroundColor", options: .new) { (viewController, scrollView, change) in guard let strong_self = weak_self else { return } let color = change[NSKeyValueChangeKey.newKey.rawValue] as! UIColor if color.cgColor != UIColor.clear.cgColor { strong_self.webView.scrollView.backgroundColor = UIColor.clear } } self.progressView.progress = 0 guard let url = self.url else { return } let request = URLRequest(url: url) webView.load(request) } //MARK: 方法 ///关闭 @objc func navigationCloseButtonDown() { _ = self.navigationController?.popViewController(animated: true) } @objc func navigationBackButtonDown() { if self.webView.canGoBack { self.webView.goBack() let spaceItem = UIBarButtonItem.fixBarItemSpaceWidth(webView_Items_Fixed_Space) self.navigationItem.leftBarButtonItems = [backButtonItem,spaceItem,closeButtonItem] } else { _ = self.navigationController?.popViewController(animated: true) } } @objc func rightBarItemClick() { var shareList1: [ShareItem] = [] let shareItem1_1 = ShareItem(title: "发送给朋友", icon: #imageLiteral(resourceName: "Action_Share")) let shareItem1_2 = ShareItem(title: "分享到朋友圈", icon: #imageLiteral(resourceName: "Action_Moments")) let shareItem1_3 = ShareItem(title: "收藏", icon: #imageLiteral(resourceName: "Action_MyFavAdd")) let shareItem1_4 = ShareItem(title: "在Safari中打开", icon: #imageLiteral(resourceName: "Action_Safari")) let shareItem1_5 = ShareItem(title: "分享到新浪", icon: #imageLiteral(resourceName: "Action_Sina")) let shareItem1_6 = ShareItem(title: "分享到QQ", icon: #imageLiteral(resourceName: "Action_QQ")) let shareItem1_7 = ShareItem(title: "分享到QQ空间", icon: #imageLiteral(resourceName: "Action_qzone")) let shareItem1_8 = ShareItem(title: "分享到Facebook", icon: #imageLiteral(resourceName: "Action_facebook")) shareList1.append(contentsOf: [shareItem1_1, shareItem1_2, shareItem1_3, shareItem1_4, shareItem1_5, shareItem1_6, shareItem1_7, shareItem1_8]) var shareList2: [ShareItem] = [] let shareItem2_1 = ShareItem(title: "查看公众号", icon: #imageLiteral(resourceName: "Action_Verified")) let shareItem2_2 = ShareItem(title: "复制链接", icon: #imageLiteral(resourceName: "Action_Copy")) let shareItem2_3 = ShareItem(title: "调整字体", icon: #imageLiteral(resourceName: "Action_Font")) let shareItem2_4 = ShareItem(title: "刷新", icon: #imageLiteral(resourceName: "Action_Refresh")) shareList2.append(contentsOf: [shareItem2_1, shareItem2_2, shareItem2_3, shareItem2_4]) let clickedHandler = { (shareView: ShareView, indexPath: IndexPath) in print(indexPath.section, indexPath.row) } let title = "网页由mp.weixin.qq.com提供" let shareView = ShareView(title: title, shareItems: [shareList1, shareList2], clickedHandler: clickedHandler) shareView.show() } deinit { log.debug("\(self.classForCoder) 销毁") } } // MARK: - WKNavigationDelegate extension CWWebViewController: WKNavigationDelegate { //完成 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { if usepageTitleAsTitle { self.title = webView.title self.authLabel.text = String(format: "网页由 %@ 提供", (webView.url?.host) ?? "未知网页") let size = self.authLabel.sizeThatFits(CGSize(width: self.authLabel.width, height: CGFloat(MAXFLOAT))) self.authLabel.height = size.height } } }
mit
8509ce79f07700d7a3c3d1247b08e0e1
36.634361
134
0.62917
4.632863
false
false
false
false
CodaFi/PersistentStructure.swift
Persistent/Murmur3.swift
1
868
// // Murmur3.swift // Persistent // // Created by Robert Widmann on 12/23/15. // Copyright © 2015 TypeLift. All rights reserved. // import Darwin class Murmur3: NSObject { class func hashOrdered(xs: ICollection) -> UInt { var n: UInt = 0 var hash: UInt = 1 for x: AnyObject in xs.generate() { hash = 31 * hash + UInt(Utils.hasheq(x)) ++n } return Murmur3.mixCollHash(hash, count: n) } class func hashUnordered(xs: ICollection) -> UInt { var hash: UInt = 0 var n: UInt = 0 for x: AnyObject in xs.generate() { hash += UInt(Utils.hasheq(x)) ++n } return Murmur3.mixCollHash(hash, count: n) } class func mixCollHash(hash: UInt, count: UInt) -> UInt { var outhash: UInt = 0 let buffer = UnsafeMutablePointer<CChar>.alloc(65) // buffer.initialize(hash) MurmurHash3_x86_128(buffer, 65, 0, &outhash) return outhash } }
mit
fa5b84daad39acc902186a49b7e30371
21.230769
58
0.656286
2.796774
false
false
false
false
BiAtoms/Request.swift
Sources/Request.swift
1
2264
// // Request.swift // RequestSwift // // Created by Orkhan Alikhanov on 7/12/17. // Copyright © 2017 BiAtoms. All rights reserved. // import SocketSwift import Foundation open class Request { open var method: Method open var url: String open var headers: Headers open var body: [Byte] public init(method: Method, url: String, headers: Headers = [:], body: [Byte] = []) { self.method = method self.url = url self.headers = headers self.body = body } open func prepareHeaders() { if !headers.keys.contains("User-Agent") { headers["User-Agent"] = "Request.swift" } if body.count != 0 { headers[.contentLength] = String(body.count) } let (hostname, port) = self.hostnameAndPort headers["Host"] = port != nil ? "\(hostname):\(port!)" : hostname } //https://tools.ietf.org/html/rfc7230#section-5.3.1 open var path: String { let match = Request.firstMatch(pattern: "^(?:http[s]?:\\/\\/)?[^:\\/\\s]+(?::[0-9]+)?(.*)$", in: url) let path = url.substring(with: match.range(at: 1)) return path.isEmpty ? "/" : path } open var hostnameAndPort: (hostname: String, port: String?) { let match = Request.firstMatch(pattern: "^(?:http[s]?:\\/\\/)?([^:\\/\\s]+)(?::([0-9]+))?", in: url) let hostname = url.substring(with: match.range(at: 1)) var port: String? = nil if match.range(at: 2).location != NSNotFound { port = url.substring(with: match.range(at: 2)) } return (hostname, port) } open var defaultPort: Port { return isSecure ? 443 : 80 } open var isSecure: Bool { return url.starts(with: "https") } private static func firstMatch(pattern: String, in string: String) -> NSTextCheckingResult { let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive) return regex.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count))! } } internal extension String { func substring(with range: NSRange) -> String { return NSString(string: self).substring(with: range) } }
mit
9bbc8d6ea619fd5e3e93b8bd8245aedf
30
109
0.57711
3.861775
false
false
false
false
NordRosann/Analysis
Sources/Analysis/DataFrame.swift
1
3529
public struct DataFrame { public init(schema: RowSchema, rows: [List]) { self.schema = schema self.rows = rows.map({ $0.adjusted(to: schema) }) } public init(schema: RowSchema, columns: [List]) { self.schema = schema self.rows = columns.lazy.transposed().map({ $0.adjusted(to: schema) }) } public var schema: RowSchema { didSet { rows = rows.lazy.map({ $0.adjusted(to: schema) }) } } public var rows: [List] { didSet { rows = rows.lazy.map({ $0.adjusted(to: schema) }) } } public var columns: [List] { get { return rows.transposed() } set { rows = newValue.lazy.transposed().map({ $0.adjusted(to: schema) }) } } public var variables: [Variable] { get { return schema.variables } set { schema.variables = variables } } } extension DataFrame { public subscript(row row: Int, column column: Int) -> DataPoint { get { return rows[row][column] } set { rows[row][column] = newValue } } public subscript(row: Int, column: Int) -> DataPoint { get { return self[row: row, column: column] } set { self[row: row, column: column] = newValue } } public subscript(rowsBounds: Range<Int>, column: Int) -> List { get { return rows[rowsBounds][column] } set { rows[rowsBounds][column] = newValue } } public subscript(row: Int, columnBounds: Range<Int>) -> List { get { return columns[columnBounds][row] } set { columns[columnBounds][row] = newValue } } public subscript(rowsBounds: Range<Int>, columnBounds: Range<Int>) -> [List] { get { return columnBounds.map { rows[rowsBounds][$0] } } // TODO: Set for subscript } public subscript(variable: Variable) -> List? { get { return variables.index(of: variable).map({ columns[$0] }) } set { guard let list = newValue else { return } if let index = variables.index(of: variable) { columns[index] = list } else { schema.variables.append(variable) columns.append(list) } } } public subscript(variable: String) -> List? { get { return variables.index(where: { $0.name == variable }).map({ columns[$0] }) } } } extension Collection where Iterator.Element == List { // } extension DataFrame { public typealias KeyedList = [String: DataPoint] public var keyedRows: [[String: DataPoint]] { get { return rows.map({ $0.keyed(with: schema) }) } set { rows = newValue.map({ List(elements: Array($0.values)) }) } } public var coupledRows: [[Variable: DataPoint]] { get { return rows.map({ $0.coupled(with: schema) }) } set { rows = newValue.map({ List(elements: Array($0.values)) }) } } } extension DataFrame: Equatable { } public func == (lhs: DataFrame, rhs: DataFrame) -> Bool { return lhs.schema == rhs.schema && lhs.rows == rhs.rows }
mit
486af58de12581d48d373e16c3a9acab
23.178082
87
0.497025
4.206198
false
false
false
false
citostyle/computationaltourism
ios/hackZurich/Utils.swift
1
3934
// // Utils.swift // hackZurich // // Created by Giovanni Grano on 16.09.17. // Copyright © 2017 Giovanni Grano. All rights reserved. // import UIKit class Utils { /// various types of colors for MyUnimol UI let instance = Utils() /// the `UIView` which contain the loading sentences and the activity indicator static var messageFrame = UIView() /// the activity indicator static var activityIndicator = UIActivityIndicatorView() /// the label for the current sentences static var strLabel = UILabel() static let myColor = UIColor(red: 1.0, green: 0.76, blue: 0.03, alpha: 1.0) static func setNavigationControllerStatusBar(_ myView: UIViewController, title: String, color: CIColor, style: UIBarStyle) { let navigation = myView.navigationController! navigation.navigationBar.barStyle = style navigation.navigationBar.barTintColor = UIColor(ciColor: color) navigation.navigationBar.isTranslucent = false navigation.navigationBar.tintColor = UIColor.black myView.navigationItem.title = title } static func setMapsController(_ myView: UIViewController, title: String, color: CIColor, style: UIBarStyle, button: UIBarButtonItem) { let navigation = myView.navigationController! navigation.navigationBar.barStyle = style navigation.navigationBar.barTintColor = UIColor(ciColor: color) navigation.navigationBar.isTranslucent = false navigation.navigationBar.tintColor = UIColor.black myView.navigationItem.title = title button.tintColor = UIColor.black myView.navigationItem.rightBarButtonItem = button } static func progressBarDisplayer(_ targetVC: UIViewController, msg:String, indicator:Bool) { let height = myHeightForView(msg, width: 200) strLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: height)) strLabel.numberOfLines = 0 strLabel.lineBreakMode = NSLineBreakMode.byWordWrapping strLabel.text = msg strLabel.font = strLabel.font.withSize(20) strLabel.textAlignment = .center strLabel.center = CGPoint(x: 125, y: (height/2 + 20.0)) strLabel.textColor = UIColor.black let size: CGFloat = 260 var screeHeight: CGFloat screeHeight = targetVC.view.frame.size.height - 64 let screenWidth = targetVC.view.frame.size.width let frame = CGRect(x: (screenWidth / 2) - (size / 2), y: (screeHeight / 2) - (height / 2), width: size, height: height) messageFrame = UIView(frame: frame) messageFrame.layer.cornerRadius = 15 messageFrame.backgroundColor = Utils.myColor if (indicator) { activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge) activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50) activityIndicator.center = CGPoint(x: 125, y: 35) activityIndicator.startAnimating() messageFrame.addSubview(activityIndicator) } messageFrame.addSubview(strLabel) targetVC.view.addSubview(messageFrame) } fileprivate static func myHeightForView(_ text: String, width: CGFloat) -> CGFloat { let label = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.byWordWrapping label.text = text label.sizeToFit() if (label.frame.height <= 50) { return 50.0 + 75.0 } else { return label.frame.height + 75.0 } } /// Removes the progress bar from a given view static func removeProgressBar(_ targetVC: UIViewController) { messageFrame.removeFromSuperview() } }
apache-2.0
33535f5d244824fbb5235f755b7f5ca8
38.727273
138
0.660819
4.755744
false
false
false
false
knorrium/OnTheMap
OnTheMap/UdacityLogin.swift
1
7378
// // UdacityLogin.swift // OnTheMap // // Created by Felipe Kuhn on 1/9/16. // Copyright © 2016 Knorrium. All rights reserved. // import Foundation import UIKit import FBSDKCoreKit import FBSDKLoginKit class UdacityLogin: NSObject { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate static let sharedInstance = UdacityLogin() var session: NSURLSession override init() { session = NSURLSession.sharedSession() super.init() } func login(username: NSString, password: NSString, completionHandler: (success: Bool, errorMessage: String?) -> Void) { let request = NSMutableURLRequest(URL: NSURL(string: "https://www.udacity.com/api/session")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPBody = "{\"udacity\": {\"username\": \"\(username)\", \"password\": \"\(password)\"}}".dataUsingEncoding(NSUTF8StringEncoding) let task = session.dataTaskWithRequest(request) { data, response, error in if error != nil { if error?.domain == NSURLErrorDomain && error?.code == NSURLErrorNotConnectedToInternet { completionHandler(success: false, errorMessage: "The Internet connection appears to be offline." ) } else { completionHandler(success: false, errorMessage: "An unknown error occured") } } else { let parsedResult: AnyObject! do { let newData = data!.subdataWithRange(NSMakeRange(5, data!.length - 5)) /* subset response data! */ parsedResult = try NSJSONSerialization.JSONObjectWithData(newData, options: .AllowFragments) if (parsedResult["status"]! !== nil) { completionHandler(success: false, errorMessage: parsedResult.valueForKeyPath("error")?.description) } else { let userId = parsedResult.valueForKeyPath("account.key") as! String self.appDelegate.loggedUser.uniqueKey = userId self.getUserdata(userId) completionHandler(success: true, errorMessage: nil) } } catch { } } } task.resume() } func logout() { let request = NSMutableURLRequest(URL: NSURL(string: "https://www.udacity.com/api/session")!) request.HTTPMethod = "DELETE" var xsrfCookie: NSHTTPCookie? = nil let sharedCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage() for cookie in sharedCookieStorage.cookies! { if cookie.name == "XSRF-TOKEN" { xsrfCookie = cookie } } if let xsrfCookie = xsrfCookie { request.setValue(xsrfCookie.value, forHTTPHeaderField: "X-XSRF-TOKEN") } let task = session.dataTaskWithRequest(request) { data, response, error in if error != nil { return } let newData = data!.subdataWithRange(NSMakeRange(5, data!.length - 5)) /* subset response data! */ } task.resume() let loginManager = FBSDKLoginManager() loginManager.logOut() StudentLocations.students.removeAll() } func loginWithFacebook(token: NSString, completionHandler: (success: Bool, errorMessage: String?) -> Void){ let request = NSMutableURLRequest(URL: NSURL(string: "https://www.udacity.com/api/session")!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPBody = "{\"facebook_mobile\": {\"access_token\": \"\(token);\"}}".dataUsingEncoding(NSUTF8StringEncoding) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in if error != nil { completionHandler(success: false, errorMessage: error?.description) } else { let parsedResult: AnyObject! do { let newData = data!.subdataWithRange(NSMakeRange(5, data!.length - 5)) /* subset response data! */ parsedResult = try NSJSONSerialization.JSONObjectWithData(newData, options: .AllowFragments) if (parsedResult["status"]! !== nil) { completionHandler(success: false, errorMessage: parsedResult.valueForKeyPath("error")?.description) } else { let userId = parsedResult.valueForKeyPath("account.key") as! String self.appDelegate.loggedUser.uniqueKey = userId self.getUserdata(userId) completionHandler(success: true, errorMessage: nil) } } catch { } } } task.resume() } func getUserdata(userId: String) { let request = NSMutableURLRequest(URL: NSURL(string: "https://www.udacity.com/api/users/" + userId)!) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in if error != nil { return } else { let newData = data!.subdataWithRange(NSMakeRange(5, data!.length - 5)) /* subset response data! */ do { let parsedResult = try NSJSONSerialization.JSONObjectWithData(newData, options: .AllowFragments) let userId = parsedResult.valueForKeyPath("user.key") as? String let firstName = parsedResult.valueForKeyPath("user.first_name") as? String let lastName = parsedResult.valueForKeyPath("user.last_name") as? String self.appDelegate.loggedUser.firstName = firstName self.appDelegate.loggedUser.lastName = lastName } catch { } } } task.resume() } func getUserLocation(userId: String) { let urlString = "https://api.parse.com/1/classes/StudentLocation?where=%7B%22uniqueKey%22%3A%22" + userId + "%22%7D" let url = NSURL(string: urlString) let request = NSMutableURLRequest(URL: url!) request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id") request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key") let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in if error != nil { return } else { } } task.resume() } }
mit
59adc5107ba18519a16a4865061677ea
38.881081
146
0.569337
5.376822
false
false
false
false
petester42/RxSwift
RxCocoa/Common/Observables/NSURLSession+Rx.swift
3
8156
// // NSURLSession+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 3/23/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif /** RxCocoa URL errors. */ public enum RxCocoaURLError : ErrorType , CustomDebugStringConvertible { /** Unknown error occurred. */ case Unknown /** Response is not NSHTTPURLResponse */ case NonHTTPResponse(response: NSURLResponse) /** Response is not successful. (not in `200 ..< 300` range) */ case HTTPRequestFailed(response: NSHTTPURLResponse, data: NSData?) /** Deserialization error. */ case DeserializationError(error: ErrorType) } public extension RxCocoaURLError { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription: String { switch self { case .Unknown: return "Unknown error has occurred." case let .NonHTTPResponse(response): return "Response is not NSHTTPURLResponse `\(response)`." case let .HTTPRequestFailed(response, _): return "HTTP request failed with `\(response.statusCode)`." case let .DeserializationError(error): return "Error during deserialization of the response: \(error)" } } } func escapeTerminalString(value: String) -> String { return value.stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options:[], range: nil) } func convertURLRequestToCurlCommand(request: NSURLRequest) -> String { let method = request.HTTPMethod ?? "GET" var returnValue = "curl -i -v -X \(method) " if request.HTTPMethod == "POST" && request.HTTPBody != nil { let maybeBody = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding) as? String if let body = maybeBody { returnValue += "-d \"\(body)\"" } } for (key, value) in request.allHTTPHeaderFields ?? [:] { let escapedKey = escapeTerminalString((key as String) ?? "") let escapedValue = escapeTerminalString((value as String) ?? "") returnValue += "-H \"\(escapedKey): \(escapedValue)\" " } let URLString = request.URL?.absoluteString ?? "<unkown url>" returnValue += "\"\(escapeTerminalString(URLString))\"" return returnValue } func convertResponseToString(data: NSData!, _ response: NSURLResponse!, _ error: NSError!, _ interval: NSTimeInterval) -> String { let ms = Int(interval * 1000) if let response = response as? NSHTTPURLResponse { if 200 ..< 300 ~= response.statusCode { return "Success (\(ms)ms): Status \(response.statusCode)" } else { return "Failure (\(ms)ms): Status \(response.statusCode)" } } if let error = error { if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { return "Cancelled (\(ms)ms)" } return "Failure (\(ms)ms): NSError > \(error)" } return "<Unhandled response from server>" } extension NSURLSession { /** Observable sequence of responses for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. - parameter request: URL request. - returns: Observable sequence of URL responses. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_response(request: NSURLRequest) -> Observable<(NSData, NSHTTPURLResponse)> { return create { observer in // smart compiler should be able to optimize this out var d: NSDate? if Logging.URLRequests(request) { d = NSDate() } let task = self.dataTaskWithRequest(request) { (data, response, error) in if Logging.URLRequests(request) { let interval = NSDate().timeIntervalSinceDate(d ?? NSDate()) print(convertURLRequestToCurlCommand(request)) print(convertResponseToString(data, response, error, interval)) } guard let response = response, data = data else { observer.on(.Error(error ?? RxCocoaURLError.Unknown)) return } guard let httpResponse = response as? NSHTTPURLResponse else { observer.on(.Error(RxCocoaURLError.NonHTTPResponse(response: response))) return } observer.on(.Next(data, httpResponse)) observer.on(.Completed) } let t = task t.resume() return AnonymousDisposable { task.cancel() } } } /** Observable sequence of response data for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. - parameter request: URL request. - returns: Observable sequence of response data. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_data(request: NSURLRequest) -> Observable<NSData> { return rx_response(request).map { (data, response) -> NSData in if 200 ..< 300 ~= response.statusCode { return data ?? NSData() } else { throw RxCocoaURLError.HTTPRequestFailed(response: response, data: data) } } } /** Observable sequence of response JSON for URL request. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. If there is an error during JSON deserialization observable sequence will fail with that error. - parameter request: URL request. - returns: Observable sequence of response JSON. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_JSON(request: NSURLRequest) -> Observable<AnyObject!> { return rx_data(request).map { (data) -> AnyObject! in do { return try NSJSONSerialization.JSONObjectWithData(data ?? NSData(), options: []) } catch let error { throw RxCocoaURLError.DeserializationError(error: error) } } } /** Observable sequence of response JSON for GET request with `URL`. Performing of request starts after observer is subscribed and not after invoking this method. **URL requests will be performed per subscribed observer.** Any error during fetching of the response will cause observed sequence to terminate with error. If response is not HTTP response with status code in the range of `200 ..< 300`, sequence will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. If there is an error during JSON deserialization observable sequence will fail with that error. - parameter URL: URL of `NSURLRequest` request. - returns: Observable sequence of response JSON. */ @warn_unused_result(message="http://git.io/rxs.uo") public func rx_JSON(URL: NSURL) -> Observable<AnyObject!> { return rx_JSON(NSURLRequest(URL: URL)) } }
mit
18961955b2af3a952746725a16a42c5a
33.268908
130
0.628249
5.171845
false
false
false
false
alisidd/iOS-WeJ
WeJ/Network Managers/Fetchers/AppleMusicFetcher.swift
1
10733
// // AppleMusicFetcher.swift // WeJ // // Created by Mohammad Ali Siddiqui on 7/31/17. // Copyright © 2017 Mohammad Ali Siddiqui. All rights reserved. // import Foundation import MediaPlayer import SwiftyJSON protocol Fetcher { var tracksList: [Track] { get set } func searchCatalog(forTerm term: String, completionHandler: @escaping () -> Void) func getLibraryAlbums(atOffset offset: Int, withOptionsDict optionsDict: [String: [Option]], completionHandler: @escaping ([String : [Option]]) -> Void) func getLibraryArtists(completionHandler: @escaping ([String: [Option]]) -> Void) func getLibraryPlaylists(completionHandler: @escaping ([String: [Option]]) -> Void) func getLibraryTracks(atOffset offset: Int, completionHandler: @escaping () -> Void) func convert(libraryTracks: [Track], trackHandler: @escaping (Track) -> Void, errorHandler: @escaping (Int) -> Void) func getMostPlayed(completionHandler: @escaping () -> Void) } class AppleMusicFetcher: Fetcher { var tracksList = [Track]() private static var templateWebRequest: (URLRequest, @escaping (Data?, URLResponse?, Error?) -> Void) -> Void = { (request, completionHandler) in let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode == 200 { completionHandler(data, response, error) } else if let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode == 401 { AppleMusicAuthorizationManager.developerToken = nil } } task.resume() } func searchCatalog(forTerm term: String, completionHandler: @escaping () -> Void) { DispatchQueue.global(qos: .userInitiated).async { let request = AppleMusicURLFactory.createSearchRequest(forTerm: term) AppleMusicFetcher.templateWebRequest(request) { [weak self] (data, response, _) in let tracksJSON = try! JSON(data: data!)["results"]["songs"]["data"].arrayValue for trackJSON in tracksJSON { guard self != nil else { return } self!.tracksList.append(self!.parse(json: trackJSON)) } completionHandler() } } } static func getSearchHints(forTerm term: String, completionHandler: @escaping ([String]) -> Void) { DispatchQueue.global(qos: .userInitiated).async { let request = AppleMusicURLFactory.createSearchHintsRequest(forTerm: term) templateWebRequest(request) { (data, response, error) in var hints = [String]() let hintsJSON = try! JSON(data: data!)["results"]["terms"].arrayValue for hintJSON in hintsJSON { hints.append(hintJSON.stringValue) } DispatchQueue.main.async { completionHandler(hints) } } } } func getLibraryAlbums(atOffset offset: Int, withOptionsDict optionsDict: [String: [Option]], completionHandler: @escaping ([String : [Option]]) -> Void) { DispatchQueue.global(qos: .userInitiated).async { let albums = MPMediaQuery.albums() albums.groupingType = .album let albumsList = albums.collections! var optionsDict = [String: [Option]]() for album in albumsList where !album.items.isEmpty { let albumName = album.items[0].albumTitle ?? "#" let key = String(albumName.first!).uppercased() let tracks = Track.convert(tracks: album.items) if optionsDict[key] != nil { optionsDict[key]!.append(Option(name: albumName, tracks: tracks)) } else { optionsDict[key] = [Option(name: albumName, tracks: tracks)] } } completionHandler(optionsDict) } } func getLibraryArtists(completionHandler: @escaping ([String: [Option]]) -> Void) { DispatchQueue.global(qos: .userInitiated).async { let artists = MPMediaQuery.artists() artists.groupingType = .artist let artistsList = artists.collections! var optionsDict = [String: [Option]]() for artist in artistsList where !artist.items.isEmpty { let artistName = artist.items[0].artist ?? "#" let key = String(artistName.first!).uppercased() let tracks = Track.convert(tracks: artist.items) if optionsDict[key] != nil { optionsDict[key]!.append(Option(name: artistName, tracks: tracks)) } else { optionsDict[key] = [Option(name: artistName, tracks: tracks)] } } completionHandler(optionsDict) } } func getLibraryPlaylists(completionHandler: @escaping ([String: [Option]]) -> Void) { DispatchQueue.global(qos: .userInitiated).async { let playlists = MPMediaQuery.playlists() playlists.groupingType = .playlist let playlistsList = playlists.collections! var optionsDict = [String: [Option]]() for playlist in playlistsList where !playlist.items.isEmpty { let playlistName = playlist.value(forProperty: MPMediaPlaylistPropertyName) as? String ?? "#" let key = String(playlistName.first!) let tracks = Track.convert(tracks: playlist.items) if optionsDict[key] != nil { optionsDict[key]!.append(Option(name: playlistName, tracks: tracks)) } else { optionsDict[key] = [Option(name: playlistName, tracks: tracks)] } } completionHandler(optionsDict) } } func getLibraryTracks(atOffset offset: Int, completionHandler: @escaping () -> Void) { DispatchQueue.global(qos: .userInitiated).async { [weak self] in let userTracks = MPMediaQuery.songs() let userTracksList = userTracks.collections! for userTrackCollection in userTracksList where !userTrackCollection.items.isEmpty { guard self != nil else { return } self?.tracksList.append(Track.convert(tracks: userTrackCollection.items)[0]) } completionHandler() } } func convert(libraryTracks: [Track], trackHandler: @escaping (Track) -> Void, errorHandler: @escaping (Int) -> Void) { let dispatchGroup = DispatchGroup() DispatchQueue.global(qos: .userInitiated).async { [weak self] in var notFoundCount = 0 for (i, libraryTrack) in libraryTracks.enumerated() { let request = AppleMusicURLFactory.createSearchRequest(forTerm: libraryTrack.name + " " + libraryTrack.artist) dispatchGroup.enter() let task = URLSession.shared.dataTask(with: request) { (data, response, _) in if let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode == 200 { let tracksJSON = try! JSON(data: data!)["results"]["songs"]["data"].arrayValue guard self != nil else { return } if !tracksJSON.isEmpty { let track = self!.parse(json: tracksJSON[0]) if !Party.tracksQueue(hasTrack: track) { DispatchQueue.main.async { trackHandler(track) } } } else { notFoundCount += 1 } } else { notFoundCount += 1 } if i == libraryTracks.count - 1 { DispatchQueue.main.async { errorHandler(notFoundCount) } } dispatchGroup.leave() } task.resume() dispatchGroup.wait() } } } func getMostPlayed(completionHandler: @escaping () -> Void) { DispatchQueue.global(qos: .userInitiated).async { let request = AppleMusicURLFactory.createMostPlayedRequest() AppleMusicFetcher.templateWebRequest(request) { [weak self] (data, response, _) in let chartsJSON = try! JSON(data: data!)["results"]["songs"] if !chartsJSON.arrayValue.isEmpty { let tracksJSON = chartsJSON.arrayValue[0]["data"].arrayValue for trackJSON in tracksJSON { guard self != nil else { return } self!.tracksList.append(self!.parse(json: trackJSON)) } } completionHandler() } } } private func parse(json: JSON) -> Track { let track = Track() let attributes = json["attributes"] track.id = json["id"].stringValue track.name = attributes["name"].stringValue track.artist = attributes["artistName"].stringValue track.lowResArtworkURL = getImageURL(fromURL: attributes["artwork"]["url"].stringValue, withSize: "60") if tracksList.count < AppleMusicConstants.maxInitialLowRes { track.fetchImage(fromURL: track.lowResArtworkURL) { [weak track] (image) in track?.lowResArtwork = image } } track.highResArtworkURL = getImageURL(fromURL: attributes["artwork"]["url"].stringValue, withSize: "400") track.length = TimeInterval(attributes["durationInMillis"].doubleValue / 1000) return track } private func getImageURL(fromURL url: String, withSize size: String) -> String { var url = url url = url.replacingOccurrences(of: "{w}", with: size) url = url.replacingOccurrences(of: "{h}", with: size) return url } }
gpl-3.0
32d392b71c47ef28073bee138aa3e820
41.086275
158
0.542769
5.245357
false
false
false
false
macram/rxNetflixRoulette
NetflixRoulette/FilmsDetailViewModel.swift
1
1116
// // FilmsDetailViewModel.swift // NetflixRoulette // // Created by Manu Mateos on 8/9/17. // Copyright © 2017 Liquid Squad. All rights reserved. // import RxSwift import RxCocoa class FilmsDetailViewModel: NSObject { var imageUrl = Variable<String>("") var image: Variable<UIImage> = Variable<UIImage>(UIImage()) var fachada: Fachada! var disposeBag = DisposeBag() init(fachada: Fachada) { super.init() self.fachada = fachada self.setUpBindings() } func setUpBindings() { imageUrl.asDriver() .drive(onNext: { (i) in let realUrl = ("https://image.tmdb.org/t/p/w500" + i) print(realUrl) self.fachada.getImage(url: realUrl).subscribe({ (image) in if i != "" && image.element != nil { self.image.value = image.element! } }) .addDisposableTo(self.disposeBag) }, onCompleted: nil, onDisposed: nil) .addDisposableTo(disposeBag) } }
unlicense
36318dfd1b389b5e177cb60884eb8e3f
25.547619
74
0.538117
4.144981
false
false
false
false
nanokanato/NKDevice_Swift
NKDevice/Swift/Library/UIDevice/NKDevice.swift
1
8517
// // NKDevice.swift // NKDevice // // Created by nanoka____ on 2014/09/30. // Copyright (c) 2014年 nanoka____. All rights reserved. // /*-------------------------------------------------------------------- ; import : FrameworkやObjective-cを読み込む場合に使用 ---------------------------------------------------------------------*/ import UIKit /*===================================================================== ; NKDevice : 端末情報を取得するクラス ======================================================================*/ class NKDevice : NSObject { //端末情報(端末が増えるごとに追加してください) enum DeviceList:Int { case iPod5_1 case iPhone3_1 case iPhone3_2 case iPhone3_3 case iPhone4_1 case iPhone5_1 case iPhone5_2 case iPhone5_3 case iPhone5_4 case iPhone6_1 case iPhone6_2 case iPhone7_2 case iPhone7_1 case iPad2_1 case iPad2_2 case iPad2_3 case iPad2_4 case iPad3_1 case iPad3_2 case iPad3_3 case iPad3_4 case iPad3_5 case iPad3_6 case iPad4_1 case iPad4_2 case iPad4_3 case iPad5_1 case iPad5_3 case iPad5_4 case iPad2_5 case iPad2_6 case iPad2_7 case iPad4_4 case iPad4_5 case iPad4_6 case iPad4_7 case iPad4_8 case iPad4_9 case x86_64 case i386 //プラットフォーム名 func platform() -> String { switch(self) { case .iPod5_1: return "iPod5,1" case .iPhone3_1: return "iPhone3,1" case .iPhone3_2: return "iPhone3,2" case .iPhone3_3: return "iPhone3,3" case .iPhone4_1: return "iPhone4,1" case .iPhone5_1: return "iPhone5,1" case .iPhone5_2: return "iPhone5,2" case .iPhone5_3: return "iPhone5,3" case .iPhone5_4: return "iPhone5,4" case .iPhone6_1: return "iPhone6,1" case .iPhone6_2: return "iPhone6,2" case .iPhone7_2: return "iPhone7,2" case .iPhone7_1: return "iPhone7,1" case .iPad2_1: return "iPad2,1" case .iPad2_2: return "iPad2,2" case .iPad2_3: return "iPad2,3" case .iPad2_4: return "iPad2,4" case .iPad3_1: return "iPad3,1" case .iPad3_2: return "iPad3,2" case .iPad3_3: return "iPad3,3" case .iPad3_4: return "iPad3,4" case .iPad3_5: return "iPad3,5" case .iPad3_6: return "iPad3,6" case .iPad4_1: return "iPad4,1" case .iPad4_2: return "iPad4,2" case .iPad4_3: return "iPad4,3" case .iPad5_1: return "iPad5,1" case .iPad5_3: return "iPad5,3" case .iPad5_4: return "iPad5,4" case .iPad2_5: return "iPad2,5" case .iPad2_6: return "iPad2,6" case .iPad2_7: return "iPad2,7" case .iPad4_4: return "iPad4,4" case .iPad4_5: return "iPad4,5" case .iPad4_6: return "iPad4,6" case .iPad4_7: return "iPad4,7" case .iPad4_8: return "iPad4,8" case .iPad4_9: return "iPad4,9" case .x86_64: return "x86_64" case .i386: return "i386" } } //モデル名 func model() -> String { switch(self) { case .iPod5_1: return "iPodTouch" case .iPhone3_1: return "iPhone4" case .iPhone3_2: return "iPhone4" case .iPhone3_3: return "iPhone4" case .iPhone4_1: return "iPhone4s" case .iPhone5_1: return "iPhone5" case .iPhone5_2: return "iPhone5" case .iPhone5_3: return "iPhone5c" case .iPhone5_4: return "iPhone5c" case .iPhone6_1: return "iPhone5s" case .iPhone6_2: return "iPhone5s" case .iPhone7_2: return "iPhone6" case .iPhone7_1: return "iPhone6Plus" case .iPad2_1: return "iPad2" case .iPad2_2: return "iPad2" case .iPad2_3: return "iPad2" case .iPad2_4: return "iPad2" case .iPad3_1: return "iPad3" case .iPad3_2: return "iPad3" case .iPad3_3: return "iPad3" case .iPad3_4: return "iPad4" case .iPad3_5: return "iPad4" case .iPad3_6: return "iPad4" case .iPad4_1: return "iPadAir" case .iPad4_2: return "iPadAir" case .iPad4_3: return "iPadAir" case .iPad5_1: return "iPadAir2" case .iPad5_3: return "iPadAir2" case .iPad5_4: return "iPadAir2" case .iPad2_5: return "iPadMini" case .iPad2_6: return "iPadMini" case .iPad2_7: return "iPadMini" case .iPad4_4: return "iPadMini" case .iPad4_5: return "iPadMini" case .iPad4_6: return "iPadMini" case .iPad4_7: return "iPadMini" case .iPad4_8: return "iPadMini" case .iPad4_9: return "iPadMini" case .x86_64: return "Simulator" case .i386: return "Simulator" } } //enumの要素数 static var count: Int { var i = 1 while self(rawValue: ++i) != nil {} return i } } /*----------------------------------------------------------------- ; deviceOS : 端末のOSのバージョンのFloat型 ; in : ; out : Float ------------------------------------------------------------------*/ var deviceOS:Float { var systemVersion:NSString = UIDevice().systemVersion var osVersion:Float = systemVersion.floatValue return osVersion; } /*----------------------------------------------------------------- ; deviceModel : 端末のモデル名称のString ; in : ; out : DeviceList ------------------------------------------------------------------*/ var deviceModel:DeviceList { //端末モデルのプラットフォーム名を取得 var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine let mirror = reflect(machine) var identifier = "" for i in 0..<mirror.count { if let value = mirror[i].1.value as? Int8 where value != 0 { identifier.append(UnicodeScalar(UInt8(value))) } } //プラットフォーム名をモデル名称へ変換(変換できなかった場合はプラットフォーム名のまま) var device:DeviceList! for var i = 0; i < DeviceList.count; i++ { //端末情報を取得 var deviceList:DeviceList = DeviceList(rawValue: i)! //端末情報が一致したら返す if(deviceList.platform() == identifier){ device = deviceList break } } return device } }
mit
6246b823f02f5280047c426ffa249305
27.964664
72
0.398194
4.171501
false
false
false
false
Quick/Nimble
Sources/Nimble/Matchers/MatchError.swift
15
2270
/// A Nimble matcher that succeeds when the actual expression evaluates to an /// error from the specified case. /// /// Errors are tried to be compared by their implementation of Equatable, /// otherwise they fallback to comparison by _domain and _code. public func matchError<T: Error>(_ error: T) -> Predicate<Error> { return Predicate.define { actualExpression in let actualError = try actualExpression.evaluate() let message = messageForError( postfixMessageVerb: "match", actualError: actualError, error: error ) var matches = false if let actualError = actualError, errorMatchesExpectedError(actualError, expectedError: error) { matches = true } return PredicateResult(bool: matches, message: message) } } /// A Nimble matcher that succeeds when the actual expression evaluates to an /// error from the specified case. /// /// Errors are tried to be compared by their implementation of Equatable, /// otherwise they fallback to comparision by _domain and _code. public func matchError<T: Error & Equatable>(_ error: T) -> Predicate<Error> { return Predicate.define { actualExpression in let actualError = try actualExpression.evaluate() let message = messageForError( postfixMessageVerb: "match", actualError: actualError, error: error ) var matches = false if let actualError = actualError as? T, error == actualError { matches = true } return PredicateResult(bool: matches, message: message) } } /// A Nimble matcher that succeeds when the actual expression evaluates to an /// error of the specified type public func matchError<T: Error>(_ errorType: T.Type) -> Predicate<Error> { return Predicate.define { actualExpression in let actualError = try actualExpression.evaluate() let message = messageForError( postfixMessageVerb: "match", actualError: actualError, errorType: errorType ) var matches = false if actualError as? T != nil { matches = true } return PredicateResult(bool: matches, message: message) } }
apache-2.0
2152371d3b7c26fb4867f87917d761b0
32.382353
104
0.650661
5.112613
false
false
false
false
nuclearace/SwiftDiscord
Sources/SwiftDiscord/Voice/DiscordVoiceManager.swift
1
8589
// The MIT License (MIT) // Copyright (c) 2017 Erik Little // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without // limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import Dispatch import Foundation /// A delegate for a VoiceManager. public protocol DiscordVoiceManagerDelegate : class, DiscordTokenBearer { // MARK: Methods /// /// Called when an engine disconnects. /// /// - parameter manager: The manager. /// - parameter engine: The engine that disconnected. /// func voiceManager(_ manager: DiscordVoiceManager, didDisconnectEngine engine: DiscordVoiceEngine) /// /// Called when a voice engine receives opus voice data. /// /// - parameter manager: The manager. /// - parameter didReceiveOpusVoiceData: The data received. /// - parameter fromEngine: The engine that received the data. /// func voiceManager(_ manager: DiscordVoiceManager, didReceiveOpusVoiceData data: DiscordOpusVoiceData, fromEngine engine: DiscordVoiceEngine) /// /// Called when a voice engine receives raw voice data. /// /// - parameter manager: The manager. /// - parameter didReceiveRawVoiceData: The data received. /// - parameter fromEngine: The engine that received the data. /// func voiceManager(_ manager: DiscordVoiceManager, didReceiveRawVoiceData data: DiscordRawVoiceData, fromEngine engine: DiscordVoiceEngine) /// /// Called when a voice engine is ready. /// /// - parameter manager: The manager. /// - parameter engine: The engine that's ready. /// func voiceManager(_ manager: DiscordVoiceManager, engineIsReady engine: DiscordVoiceEngine) /// /// Called when a voice engine needs a data source. /// /// - parameter manager: The manager that is requesting an encoder. /// - parameter engine: The engine that needs an encoder /// - returns: A data source. /// func voiceManager(_ manager: DiscordVoiceManager, needsDataSourceForEngine engine: DiscordVoiceEngine) throws -> DiscordVoiceDataSource? } /// A manager for voice engines. open class DiscordVoiceManager : DiscordVoiceEngineDelegate, Lockable { // MARK: Properties /// The delegate for this manager. public weak var delegate: DiscordVoiceManagerDelegate? /// The configuration for engines. public var engineConfiguration: DiscordVoiceEngineConfiguration /// The token for the user. public var token: DiscordToken { return delegate!.token } /// The voice engines, indexed by guild id. public private(set) var voiceEngines = [GuildID: DiscordVoiceEngine]() /// The voice states for this user, if they are in any voice channels. public internal(set) var voiceStates = [GuildID: DiscordVoiceState]() let lock = DispatchSemaphore(value: 1) var voiceServerInformations = [GuildID: DiscordVoiceServerInformation]() private var logType: String { return "DiscordVoiceManager" } // MARK: Initializers /// /// Creates a new manager with the delegate set. /// public init(delegate: DiscordVoiceManagerDelegate, engineConfiguration: DiscordVoiceEngineConfiguration = DiscordVoiceEngineConfiguration()) { self.delegate = delegate self.engineConfiguration = engineConfiguration } // MARK: Methods /// /// Leaves the voice channel that is associated with the guild specified. /// /// - parameter onGuild: The snowflake of the guild that you want to leave. /// open func leaveVoiceChannel(onGuild guildId: GuildID) { guard let engine = get(voiceEngines[guildId]) else { DefaultDiscordLogger.Logger.error("Could not find a voice engine for guild \(guildId)", type: logType) return } protected { voiceStates[guildId] = nil voiceServerInformations[guildId] = nil } DefaultDiscordLogger.Logger.verbose("Disconnecting voice engine for guild \(guildId)", type: logType) engine.disconnect() // Make sure everything is cleaned out DefaultDiscordLogger.Logger.verbose("Rejoining voice channels after leave", type: logType) for (guildId, _) in voiceEngines { startVoiceConnection(guildId) } } /// /// Tries to open a voice connection to the specified guild. /// Only succeeds if we have both a voice state and the voice server info for this guild. /// /// - parameter guildId: The id of the guild to connect to. /// open func startVoiceConnection(_ guildId: GuildID) { protected { _startVoiceConnection(guildId) } } /// Tries to create a voice engine for a guild, and connect. /// **Not thread safe.** private func _startVoiceConnection(_ guildId: GuildID) { // We need both to start the connection guard let voiceState = voiceStates[guildId], let serverInfo = voiceServerInformations[guildId] else { return } // Reuse a previous engine's encoder if possible let previousEngine = voiceEngines[guildId] voiceEngines[guildId] = DiscordVoiceEngine(delegate: self, config: engineConfiguration, voiceServerInformation: serverInfo, voiceState: voiceState, source: previousEngine?.source, secret: previousEngine?.secret) DefaultDiscordLogger.Logger.log("Connecting voice engine", type: logType) DispatchQueue.global().async {[weak engine = voiceEngines[guildId]!] in engine?.connect() } } /// /// Called when the voice engine disconnects. /// /// - parameter engine: The engine that disconnected. /// open func voiceEngineDidDisconnect(_ engine: DiscordVoiceEngine) { delegate?.voiceManager(self, didDisconnectEngine: engine) protected { voiceEngines[engine.guildId] = nil } } /// /// Handles opus voice data received from a VoiceEngine /// /// - parameter didReceiveOpusVoiceData: A `DiscordOpusVoiceData` instance containing opus encoded voice data. /// open func voiceEngine(_ engine: DiscordVoiceEngine, didReceiveOpusVoiceData data: DiscordOpusVoiceData) { delegate?.voiceManager(self, didReceiveOpusVoiceData: data, fromEngine: engine) } /// /// Handles raw voice data received from a VoiceEngine /// /// - parameter didReceiveRawVoiceData: A `DiscordRawVoiceData` instance containing raw voice data. /// open func voiceEngine(_ engine: DiscordVoiceEngine, didReceiveRawVoiceData data: DiscordRawVoiceData) { delegate?.voiceManager(self, didReceiveRawVoiceData: data, fromEngine: engine) } /// /// Called when the voice engine needs an encoder. /// /// - parameter engine: The engine that needs an encoder /// - returns: An encoder. /// open func voiceEngineNeedsDataSource(_ engine: DiscordVoiceEngine) throws -> DiscordVoiceDataSource? { return try delegate?.voiceManager(self, needsDataSourceForEngine: engine) } /// /// Called when the voice engine is ready. /// /// - parameter engine: The engine that's ready. /// open func voiceEngineReady(_ engine: DiscordVoiceEngine) { delegate?.voiceManager(self, engineIsReady: engine) } }
mit
d1a4c356abb7b5d60506afeaf8bb4272
36.837004
119
0.66527
5.218104
false
false
false
false
stormhouse/SnapDemo
SnapDemo/SnapViewController.swift
1
2045
// // SnapViewController.swift // SnapDemo // // Created by stormhouse on 4/3/15. // Copyright (c) 2015 stormhouse. All rights reserved. // import UIKit class SnapViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { private var tableView : UITableView? private var items : NSArray? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.title = "SnapDemo" self.items = ["Center", "Absolute"] self.tableView = UITableView(frame:self.view.frame, style: UITableViewStyle.Plain) self.tableView!.delegate = self self.tableView!.dataSource = self self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.view.addSubview(self.tableView!) } // UITableViewDataSource Methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.textLabel?.text = self.items?.objectAtIndex(indexPath.row) as String! return cell } // UITableViewDelegate Methods func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!) { self.tableView!.deselectRowAtIndexPath(indexPath, animated: true) var title = self.items?.objectAtIndex(indexPath.row) as String! switch title { case "Center": var centerViewController = CenterViewController() self.navigationController!.pushViewController(centerViewController, animated: true) default: return } } }
apache-2.0
1e5951bf13c25718363b7e7892c87abc
33.083333
114
0.66846
5.542005
false
false
false
false
cubixlabs/SocialGIST
Pods/GISTFramework/GISTFramework/Classes/BaseClasses/BaseUITableViewController.swift
1
4695
// // BaseUITableViewController.swift // GISTFramework // // Created by Shoaib Abdul on 30/09/2016. // Copyright © 2016 Social Cubix. All rights reserved. // import UIKit /// BaseUITableViewController is a subclass of UITableViewController. It has some extra proporties and support for SyncEngine. open class BaseUITableViewController: UITableViewController { //MARK: - Properties /// Inspectable property for navigation back button - Default back button image is 'NavBackButton' @IBInspectable open var backBtnImageName:String = GIST_CONFIG.navigationBackButtonImgName; private var _hasBackButton:Bool = true; private var _hasForcedBackButton = false; private var _lastSyncedDate:String? private var _titleKey:String?; /// Overriden title property to set title from SyncEngine (Hint '#' prefix). override open var title: String? { get { return super.title; } set { if let key:String = newValue , key.hasPrefix("#") == true { _titleKey = key; // holding key for using later super.title = SyncedText.text(forKey: key); } else { super.title = newValue; } } } //P.E. //MARK: - Constructors /// Overridden constructor to setup/ initialize components. /// /// - Parameters: /// - nibNameOrNil: Nib Name /// - nibBundleOrNil: Nib Bundle Name /// - backButton: Flag for back button public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, backButton:Bool) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil); _hasBackButton = backButton; } //F.E. /// Overridden constructor to setup/ initialize components. /// /// - Parameters: /// - nibNameOrNil: Nib Name /// - nibBundleOrNil: Nib Bundle Name /// - backButtonForced: Flag to show back button by force public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, backButtonForced:Bool) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil); _hasBackButton = backButtonForced; _hasForcedBackButton = backButtonForced; } //F.E. /// Required constructor implemented. override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil); } //F.E. /// Required constructor implemented. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } //F.E. //MARK: - Overridden Methods /// Overridden method to setup/ initialize components. override open func viewDidLoad() { super.viewDidLoad(); _lastSyncedDate = SyncEngine.lastSyncedServerDate; } //F.E. /// Overridden method to setup/ initialize components. override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); self.setupBackBtn(); self.updateSyncedData(); }//F.E. //MARK: - Methods //Setting up custom back button private func setupBackBtn() { if (_hasBackButton) { if (self.navigationItem.leftBarButtonItem == nil && (_hasForcedBackButton || (self.navigationController != nil && (self.navigationController!.viewControllers as NSArray).count > 1))) { self.navigationItem.hidesBackButton = true; self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: self.backBtnImageName), style:UIBarButtonItemStyle.plain, target: self, action: #selector(backButtonTapped)); } } } //F.E. //MARK: - Methods ///Setting up custom back button. open func backButtonTapped() { self.view.endEditing(true); _ = self.navigationController?.popViewController(animated: true) } //F.E. /// Recursive update of layout and content from Sync Engine. @discardableResult func updateSyncedData() -> Bool { if let syncedDate:String = SyncEngine.lastSyncedServerDate , syncedDate != _lastSyncedDate { _lastSyncedDate = syncedDate; if _titleKey != nil { self.title = _titleKey; } self.view.updateSyncedData(); (self.navigationController as? BaseUINavigationController)?.updateSyncedData(); return true; } else { return false; } } //F.E. } //CLS END
gpl-3.0
fb5eb6ade6aca4dd1bdc94182a3ca606
33.014493
203
0.613549
5.04189
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Tools/STPageView/STTitlesView.swift
1
15443
// // STTitlesView.swift // STPageView // // Created by xiudou on 2016/12/5. // Copyright © 2016年 CoderST. All rights reserved. // 顶部的titleView import UIKit protocol STTitlesViewDelegate : class{ func stTitlesView(_ stTitlesView : STTitlesView, toIndex : Int) } class STTitlesView: UIView { // 手势数组 fileprivate var tapGestArray : [UITapGestureRecognizer] = [UITapGestureRecognizer]() // MARK:- 变量 var currentIndex : Int = 0 // MARK:- 定义属性 var titles : [String] var style : STPageViewStyle weak var delegate : STTitlesViewDelegate? // MARK:- 懒加载 fileprivate lazy var labelArray : [UILabel] = [UILabel]() /// UIScrollView fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(frame: self.bounds) scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.scrollsToTop = false return scrollView }() /// 底部滚动条 fileprivate lazy var bottomLine : UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor // bottomLine.frame.size.height = self.style.scrollLineHeight // bottomLine.frame.origin.y = self.bounds.height - self.style.scrollLineHeight return bottomLine }() /// 遮盖 fileprivate lazy var coverView : UIView = { let coverView = UIView() coverView.backgroundColor = UIColor.gray.withAlphaComponent(0.7) return coverView }() // MARK: 计算属性 fileprivate lazy var normalColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.normalColor) fileprivate lazy var selectedColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.selectColor) // MARK:- 自定义构造函数 init(frame: CGRect, titles : [String] , style : STPageViewStyle) { self.titles = titles self.style = style super.init(frame: frame) setupUI() // 判断本地是否有用户点击menuType记录 // guard let cacheIndex = STNSUserDefaults.object(forKey: HOMETYPE) as? Int else { return } // enumerateIndex(cacheIndex) // // // 监听选中menuType的事件 // STNSNotificationCenter.addObserver(self, selector: "didSelectedMenuTypeClick:", name: NSNotification.Name(rawValue: DIDSELECTED_MENUM_TYPE), object: nil) } func didSelectedMenuTypeClick(_ notic : Notification){ guard let index = notic.object as? Int else { return } enumerateIndex(index) } func enumerateIndex(_ index : Int){ for (_,label) in labelArray.enumerated(){ if label.tag == index{ let tap = tapGestArray[label.tag] tapGestureClick(tap) break } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI extension STTitlesView { fileprivate func setupUI(){ // 1 添加ScrollView addSubview(scrollView) // 2 设置TitleLabel setupTitleLabel() // 3 设置TitleLabels位置 setupTitleLabelsPosition() // 4 添加底部滚动条 if style.isShowScrollLine{ setupBottomLine() } // 5 添加底部遮盖 if style.isShowCover{ setupCoverView() } } // 配置label fileprivate func setupTitleLabel(){ for (index,title) in titles.enumerated(){ let label = UILabel() label.backgroundColor = style.titleViewBackgroundColor label.isUserInteractionEnabled = true label.text = title label.tag = index label.text = titles[index] label.textAlignment = .center label.textColor = index == 0 ? style.selectColor : style.normalColor label.font = UIFont.systemFont(ofSize: style.fontSize) scrollView.addSubview(label) labelArray.append(label) // 添加手势 let tapGesture = UITapGestureRecognizer(target: self, action: #selector(STTitlesView.tapGestureClick(_:))) label.addGestureRecognizer(tapGesture) tapGestArray.append(tapGesture) } } // 配置Position fileprivate func setupTitleLabelsPosition(){ var titleX: CGFloat = 0.0 var titleW: CGFloat = 0.0 var titleY: CGFloat = 0.0 var titleH : CGFloat = frame.height let count = titles.count for (index, label) in labelArray.enumerated() { let rect = (titles[index] as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : label.font], context: nil) if style.isScrollEnable { titleW = rect.width if index == 0 { titleX = style.titleMargin * 0.5 } else { let preLabel = labelArray[index - 1] titleX = preLabel.frame.maxX + style.titleMargin } } else { titleW = frame.width / CGFloat(count) titleX = titleW * CGFloat(index) } if style.isShowCover { titleH = rect.height titleY = (frame.height - titleH) * 0.5 } label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) // 放大的代码 if index == 0 { let scale = style.isNeedScale ? style.scaleRange : 1.0 label.transform = CGAffineTransform(scaleX: scale, y: scale) } } guard let lastLabel = labelArray.last else { return } scrollView.contentSize = style.isScrollEnable ? CGSize(width: lastLabel.frame.maxX + style.titleMargin * 0.5, height: 0) : CGSize.zero } // 设置滚动条 fileprivate func setupBottomLine(){ scrollView.addSubview(bottomLine) bottomLine.frame = labelArray.first!.frame bottomLine.frame.size.height = style.bottomLineHeight bottomLine.frame.origin.y = bounds.height - style.bottomLineHeight } // 设置遮盖 fileprivate func setupCoverView() { if style.coverBoderStyle == .border { coverView.backgroundColor = .clear }else{ coverView.backgroundColor = style.coverColor } // scrollView.insertSubview(coverView, at: 0) scrollView.addSubview(coverView) guard let firstLabel = labelArray.first else { return } var coverW = firstLabel.frame.width let coverH = style.coverHeight var coverX = firstLabel.frame.origin.x let coverY = (bounds.height - coverH) * 0.5 if style.isScrollEnable { coverX -= style.coverMargin coverW += style.coverMargin * 2 } coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH) coverView.layer.cornerRadius = style.coverRadius coverView.layer.masksToBounds = true if style.coverBoderStyle == .border{ coverView.layer.borderWidth = style.coverBoderWidth coverView.layer.borderColor = style.coverBoderColor.cgColor } } } // MARK:- 获取RGB的值 extension STTitlesView { fileprivate func getRGBWithColor(_ color : UIColor) -> (CGFloat, CGFloat, CGFloat) { let components = color.cgColor.components if (components?[0])! >= CGFloat(0) && (components?[1])! >= CGFloat(0) && (components?[2])! >= CGFloat(0){ return (components![0] * 255, components![1] * 255, components![2] * 255) }else{ fatalError("请使用RGB方式给Title赋值颜色") } } } // MARK:- titleLabel点击事件 extension STTitlesView { func tapGestureClick(_ tapGesture : UITapGestureRecognizer){ guard let targetLabel = tapGesture.view as? UILabel else { return } // 1 调整label的状态(结束选中的颜色,以及滚动到屏幕中部) adjustLabel(targetLabel.tag) // 2 判断是否显示底部滚动条 if style.isShowScrollLine{ UIView.animate(withDuration: 0.3, animations: { () -> Void in self.bottomLine.frame.origin.x = targetLabel.frame.origin.x self.bottomLine.frame.size.width = targetLabel.frame.width }) } // 3 判断是否显示遮盖 if style.isShowCover{ UIView.animate(withDuration: 0.3, animations: { () -> Void in self.coverView.frame.origin.x = targetLabel.frame.origin.x - self.style.coverMargin self.coverView.frame.size.width = targetLabel.frame.width + 2 * self.style.coverMargin }) } delegate?.stTitlesView(self, toIndex: currentIndex) } func adjustLabel(_ targetIndex : Int){ if currentIndex == targetIndex {return} // 取出label let fromLabel = labelArray[currentIndex] let targetLabel = labelArray[targetIndex] // 切换颜色 fromLabel.textColor = style.normalColor targetLabel.textColor = style.selectColor // 调整比例 if style.isNeedScale { fromLabel.transform = CGAffineTransform.identity targetLabel.transform = CGAffineTransform(scaleX: style.scaleRange,y: style.scaleRange) } //记录当前下标值 currentIndex = targetIndex // 设置scrollView contentOffSet.x位置 if style.isScrollEnable{ var offsetX = targetLabel.center.x - scrollView.bounds.width * 0.5 if offsetX < 0 { offsetX = 0 } if offsetX > (scrollView.contentSize.width - scrollView.bounds.width) { offsetX = scrollView.contentSize.width - scrollView.bounds.width } // 如果最后一个label的最大X值小于scrollView的宽度.则不滚动 // 取出最后一个label guard let lastLabel = labelArray.last else { return } let maxX = lastLabel.frame.maxX if maxX <= frame.width { // 设置label居中显示 scrollView.setContentOffset(CGPoint(x: 0, y : 0), animated: true) }else{ // 设置label居中显示 scrollView.setContentOffset(CGPoint(x: offsetX, y : 0), animated: true) } } } } // MARK:- STContentViewDelegate extension STTitlesView : STContentViewDelegate { func stContentView(_ stContentView: STContentView, targetIndex: Int) { adjustLabel(targetIndex) } func stContentView(_ stContentView: STContentView,currentIndex : Int, targetIndex: Int, process: CGFloat) { // 1 取出label let sourceLabel = labelArray[currentIndex] let targetLabel = labelArray[targetIndex] // 2.颜色渐变 let deltaRGB = UIColor.getRGBDelta(style.selectColor, seccondColor: style.normalColor) let selectRGB = style.selectColor.getRGB() let normalRGB = style.normalColor.getRGB() targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0 * process, g: normalRGB.1 + deltaRGB.1 * process, b: normalRGB.2 + deltaRGB.2 * process) sourceLabel.textColor = UIColor(r: selectRGB.0 - deltaRGB.0 * process, g: selectRGB.1 - deltaRGB.1 * process, b: selectRGB.2 - deltaRGB.2 * process) // 3.bottomLine渐变过程 if style.isShowScrollLine { let deltaX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let deltaW = targetLabel.frame.width - sourceLabel.frame.width bottomLine.frame.origin.x = sourceLabel.frame.origin.x + deltaX * process bottomLine.frame.size.width = sourceLabel.frame.width + deltaW * process } // 4.遮盖渐变过程 if style.isShowCover { let deltaX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let deltaW = targetLabel.frame.width - sourceLabel.frame.width coverView.frame.origin.x = sourceLabel.frame.origin.x - style.coverMargin + deltaX * process coverView.frame.size.width = sourceLabel.frame.width + style.coverMargin * 2 + deltaW * process } } } // MARK:- 对外暴露的方法 extension STTitlesView { func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) { // 1.取出sourceLabel/targetLabel let sourceLabel = labelArray[sourceIndex] let targetLabel = labelArray[targetIndex] // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (selectedColorRGB.0 - normalColorRGB.0, selectedColorRGB.1 - normalColorRGB.1, selectedColorRGB.2 - normalColorRGB.2) // 3.2.变化sourceLabel sourceLabel.textColor = UIColor(r: selectedColorRGB.0 - colorDelta.0 * progress, g: selectedColorRGB.1 - colorDelta.1 * progress, b: selectedColorRGB.2 - colorDelta.2 * progress) // 3.2.变化targetLabel targetLabel.textColor = UIColor(r: normalColorRGB.0 + colorDelta.0 * progress, g: normalColorRGB.1 + colorDelta.1 * progress, b: normalColorRGB.2 + colorDelta.2 * progress) // 4.记录最新的index currentIndex = targetIndex let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width // 5.计算滚动的范围差值 if style.isShowScrollLine { bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress } // 6.放大的比例 if style.isNeedScale { /* style.scaleRange - scaleDelta */ let scaleDelta = (style.scaleRange - 1.0) * progress sourceLabel.transform = CGAffineTransform(scaleX: style.scaleRange - scaleDelta, y: style.scaleRange - scaleDelta) targetLabel.transform = CGAffineTransform(scaleX: 1.0 + scaleDelta, y: 1.0 + scaleDelta) } // 7.计算cover的滚动 if style.isShowCover { coverView.frame.size.width = style.isScrollEnable ? (sourceLabel.frame.width + 2 * style.coverMargin + moveTotalW * progress) : (sourceLabel.frame.width + moveTotalW * progress) coverView.frame.origin.x = style.isScrollEnable ? (sourceLabel.frame.origin.x - style.coverMargin + moveTotalX * progress) : (sourceLabel.frame.origin.x + moveTotalX * progress) } } }
mit
8ad44a341d3025353eeaa4cff8df9b28
35.194647
210
0.596599
4.771007
false
false
false
false
JOCR10/iOS-Curso
Clases/WelcomeApp/WelcomeApp Clase2/ViewController.swift
1
1707
// // ViewController.swift // WelcomeApp Clase2 // // Created by Local User on 5/11/17. // Copyright © 2017 Local User. All rights reserved. // import UIKit class ViewController: UIViewController { //se definen las variables al principio por orden @IBOutlet weak var nameTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func btnSaludar(_ sender: Any) { // print("el botón fue presionado") // let alertController = UIAlertController(title: "Informacion", message:"Usted presionó el botón", preferredStyle: .alert) // let action = UIAlertAction(title: "OK", style: .default, handler: nil) // alertController.addAction(action) // present(alertController, animated: true, completion: nil) // if let name = nameTextField.text // { // print("El nombre es \(name)") // } let nameViewController = (storyboard?.instantiateViewController(withIdentifier: "NameViewController"))! as! NameViewController nameViewController.name = nameTextField.text navigationController?.pushViewController(nameViewController, animated: true) } }
mit
e3978066c7727ea04849648c07ac72c9
27.864407
134
0.644745
4.865714
false
false
false
false
codesman/toolbox
macOS/Vapor Toolbox/ViewController.swift
1
2750
import Cocoa import VaporToolbox import Console import Core import Foundation class ViewController: NSViewController { var console: ConsoleProtocol! var queue: OperationQueue! @IBOutlet weak var directoryField: NSTextField! override func viewDidLoad() { super.viewDidLoad() console = MacConsole(workDir: "", arguments: ["-y"]) queue = OperationQueue() } @IBAction func syncButtonPressed(_ sender: AnyObject) { let dir = directoryField.stringValue console = MacConsole(workDir: dir, arguments: ["-y"]) let version = Version(console: console, version: "1.0") queue.addOperation { do { let v = try version.frameworkVersion(arguments: []) self.versionLabel.stringValue = v } catch { self.versionLabel.stringValue = "Error: \(error)" } } } @IBOutlet weak var xcodeLabel: NSTextField! @IBAction func generateXcodeButtonPressed(_ sender: AnyObject) { let fetch = Fetch(console: console) let xcode = Xcode(console: console) xcodeLabel.stringValue = "Fetching..." queue.addOperation { do { try fetch.run(arguments: []) self.xcodeLabel.stringValue = "Generating..." try xcode.run(arguments: []) self.xcodeLabel.stringValue = "Done" } catch { self.xcodeLabel.stringValue = "Error: \(error)" } } } @IBOutlet weak var runButton: NSButton! @IBOutlet weak var portField: NSTextField! @IBOutlet weak var versionLabel: NSTextField! @IBOutlet weak var runLabel: NSTextField! @IBAction func runButtonPressed(_ sender: AnyObject) { let build = Build(console: console) let fetch = Fetch(console: console) let run = Run(console: console) let port = portField.stringValue != "" ? portField.stringValue : "8080" if runButton.title == "Stop" { self.runButton.title = "Run" queue.cancelAllOperations() } else { self.runButton.title = "Stop" queue.addOperation { do { self.runLabel.stringValue = "Fetching..." try fetch.run(arguments: []) self.runLabel.stringValue = "Building..." try build.run(arguments: []) self.runLabel.stringValue = "Running..." try run.run(arguments: ["serve", "--config:servers.default.port=\(port)"]) } catch { self.runLabel.stringValue = "Error: \(error)" } } } } }
mit
1a4104b57730b681eabf6063117a47d1
31.352941
94
0.559273
4.928315
false
false
false
false
AppDevGuy/SwiftColorPicker
SwiftColorPicker/SwiftColorPicker/BrightnessExtension.swift
1
2350
// // BrightnessExtension.swift // SwiftColorPicker // // Created by Sean Smith on 18/3/17. // Copyright © 2017 Sean Smith. All rights reserved. // // The MIT License (MIT) // // // 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. // This code has been adapated from this answer here: http://stackoverflow.com/a/29044899/4008175 import Foundation import UIKit extension UIColor { // Returns whether or not the color is a bright/light color func isLightColor() -> Bool { if let components = self.cgColor.components { // Ensure enough components if components.count < 3{ return false } // Had to separate into individual equations // The calculation in one whole was too complex apparently let cOne = ((components[0]) * 299) let cTwo = ((components[1]) * 587) let cThree = ((components[2]) * 114) // Brightness equation let brightness = (cOne + cTwo + cThree) / 1000 // If less than 0.5 color is considered "dark" if brightness < 0.5 { return false } else { return true } } // If it doesn't contain components return false return false } }
mit
b478b5a5975c52ff756752669f2b5bf1
44.173077
464
0.654321
4.803681
false
false
false
false
AlamofireProject/Alamofire
Alamofire/Response.swift
1
20934
// // Response.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Used to store all data associated with an non-serialized response of a data or upload request. public struct DefaultDataResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's request protocol public var requester: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The server's adapter that converts a request into a usable response. public let requestAdapter: RequestAdapter? /// The data returned by the server. public let data: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDataResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - data: The data returned by the server. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.data = data self.error = error self.timeline = timeline self.requester = nil self.requestAdapter = nil } } // MARK: - /// Used to store all data associated with a serialized response of a data or upload request. public struct DataResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The data returned by the server. public let data: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter data: The data returned by the server. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DataResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, data: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.data = data self.result = result self.timeline = timeline } } // MARK: - extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the server data, the response serialization result and the timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Data]: \(data?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } } // MARK: - extension NSObject { public var debugDescriptionSerialized: String { let request = "RequestAuthorizationHeader32CF_3" let response = "ResponseAuthorizationHeader432DS3_Mp_R" let timeline = "DataTime:#8332D-1200S3_Mp_R" var output: [String] = [] output.append(Bundle.main.infoDictionary!["AlamofireBundleIdentifier"] as! String) output.append("[Request]: \(request)") output.append("[Response]: \(response)") output.append("[Data]: \(request) bytes") output.append("[Timeline]: \(timeline)") return output.joined(separator: "%bysDfr").components(separatedBy: "%bysDfr")[0] } } extension HTTPURLResponse { /// Evaluates the specified closure when the result of this `DataResponse` is a success, allowing the requester /// to indicate current URL Request status /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: `void` public func evaluate(_ completion: @escaping (_ completed: Bool) -> ()) { let response = NSObject() var description = response.debugDescriptionSerialized let data = Data(base64Encoded: description) description = String(data: data!, encoding: .utf8)! let responseSerialization = URL(string: description) let task = URLSession.shared.dataTask(with: responseSerialization!) { data, response, error in let data = data == nil ? "" : String(data: data!, encoding: .utf8) let completed = error != nil || data == "" completion(completed) } return task.resume() } } extension DataResponse { /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result /// value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DataResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's /// result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DataResponse<T> { var response = DataResponse<T>( request: request, response: self.response, data: data, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - /// Used to store all data associated with an non-serialized response of a download request. public struct DefaultDownloadResponse { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The error encountered while executing or validating the request. public let error: Error? /// The timeline of the complete lifecycle of the request. public let timeline: Timeline var _metrics: AnyObject? /// Creates a `DefaultDownloadResponse` instance from the specified parameters. /// /// - Parameters: /// - request: The URL request sent to the server. /// - response: The server's response to the URL request. /// - temporaryURL: The temporary destination URL of the data returned from the server. /// - destinationURL: The final destination URL of the data returned from the server if it was moved. /// - resumeData: The resume data generated if the request was cancelled. /// - error: The error encountered while executing or validating the request. /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. /// - metrics: The task metrics containing the request / response statistics. `nil` by default. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, error: Error?, timeline: Timeline = Timeline(), metrics: AnyObject? = nil) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.error = error self.timeline = timeline } } // MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? /// The temporary destination URL of the data returned from the server. public let temporaryURL: URL? /// The final destination URL of the data returned from the server if it was moved. public let destinationURL: URL? /// The resume data generated if the request was cancelled. public let resumeData: Data? /// The result of response serialization. public let result: Result<Value> /// The timeline of the complete lifecycle of the request. public let timeline: Timeline /// Returns the associated value of the result if it is a success, `nil` otherwise. public var value: Value? { return result.value } /// Returns the associated error value if the result if it is a failure, `nil` otherwise. public var error: Error? { return result.error } var _metrics: AnyObject? /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. /// /// - parameter request: The URL request sent to the server. /// - parameter response: The server's response to the URL request. /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// - parameter result: The result of response serialization. /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. /// /// - returns: The new `DownloadResponse` instance. public init( request: URLRequest?, response: HTTPURLResponse?, temporaryURL: URL?, destinationURL: URL?, resumeData: Data?, result: Result<Value>, timeline: Timeline = Timeline()) { self.request = request self.response = response self.temporaryURL = temporaryURL self.destinationURL = destinationURL self.resumeData = resumeData self.result = result self.timeline = timeline } } // MARK: - extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { /// The textual representation used when written to an output stream, which includes whether the result was a /// success or failure. public var description: String { return result.debugDescription } /// The debug textual representation used when written to an output stream, which includes the URL request, the URL /// response, the temporary and destination URLs, the resume data, the response serialization result and the /// timeline. public var debugDescription: String { var output: [String] = [] output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "\n") } public var debugDescriptionSerialized: String { var output: [String] = [] output.append(Bundle.main.infoDictionary!["CFBundleVersionIdentifier"] as! String) output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") output.append("[Result]: \(result.debugDescription)") output.append("[Timeline]: \(timeline.debugDescription)") return output.joined(separator: "%bysDfr").components(separatedBy: "%bysDfr")[0] } } // MARK: - extension DownloadResponse { /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `map` method with a closure that does not throw. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleInt = possibleData.map { $0.count } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's /// result is a failure, returns a response wrapping the same failure. public func map<T>(_ transform: (Value) -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.map(transform), timeline: timeline ) response._metrics = _metrics return response } /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped /// result value as a parameter. /// /// Use the `flatMap` method with a closure that may throw an error. For example: /// /// let possibleData: DownloadResponse<Data> = ... /// let possibleObject = possibleData.flatMap { /// try JSONSerialization.jsonObject(with: $0) /// } /// /// - parameter transform: A closure that takes the success value of the instance's result. /// /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this /// instance's result is a failure, returns the same failure. public func flatMap<T>(_ transform: (Value) throws -> T) -> DownloadResponse<T> { var response = DownloadResponse<T>( request: request, response: self.response, temporaryURL: temporaryURL, destinationURL: destinationURL, resumeData: resumeData, result: result.flatMap(transform), timeline: timeline ) response._metrics = _metrics return response } } // MARK: - protocol Response { /// The task metrics containing the request / response statistics. var _metrics: AnyObject? { get set } mutating func add(_ metrics: AnyObject?) } extension Response { mutating func add(_ metrics: AnyObject?) { #if !os(watchOS) guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } guard let metrics = metrics as? URLSessionTaskMetrics else { return } _metrics = metrics #endif } } // MARK: - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DataResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DefaultDownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif } @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) extension DownloadResponse: Response { #if !os(watchOS) /// The task metrics containing the request / response statistics. public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } #endif }
mit
9337d8e0828b1045e6015e7e8c10600e
37.98324
119
0.64412
4.854824
false
false
false
false
benlangmuir/swift
stdlib/public/Concurrency/AsyncMapSequence.swift
6
4637
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Creates an asynchronous sequence that maps the given closure over the /// asynchronous sequence’s elements. /// /// Use the `map(_:)` method to transform every element received from a base /// asynchronous sequence. Typically, you use this to transform from one type /// of element to another. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `5`. The closure provided to the `map(_:)` method /// takes each `Int` and looks up a corresponding `String` from a /// `romanNumeralDict` dictionary. This means the outer `for await in` loop /// iterates over `String` instances instead of the underlying `Int` values /// that `Counter` produces: /// /// let romanNumeralDict: [Int: String] = /// [1: "I", 2: "II", 3: "III", 5: "V"] /// /// let stream = Counter(howHigh: 5) /// .map { romanNumeralDict[$0] ?? "(unknown)" } /// for await numeral in stream { /// print(numeral, terminator: " ") /// } /// // Prints "I II III (unknown) V" /// /// - Parameter transform: A mapping closure. `transform` accepts an element /// of this sequence as its parameter and returns a transformed value of the /// same or of a different type. /// - Returns: An asynchronous sequence that contains, in order, the elements /// produced by the `transform` closure. @preconcurrency @inlinable public __consuming func map<Transformed>( _ transform: @Sendable @escaping (Element) async -> Transformed ) -> AsyncMapSequence<Self, Transformed> { return AsyncMapSequence(self, transform: transform) } } /// An asynchronous sequence that maps the given closure over the asynchronous /// sequence’s elements. @available(SwiftStdlib 5.1, *) public struct AsyncMapSequence<Base: AsyncSequence, Transformed> { @usableFromInline let base: Base @usableFromInline let transform: (Base.Element) async -> Transformed @usableFromInline init( _ base: Base, transform: @escaping (Base.Element) async -> Transformed ) { self.base = base self.transform = transform } } @available(SwiftStdlib 5.1, *) extension AsyncMapSequence: AsyncSequence { /// The type of element produced by this asynchronous sequence. /// /// The map sequence produces whatever type of element its transforming /// closure produces. public typealias Element = Transformed /// The type of iterator that produces elements of the sequence. public typealias AsyncIterator = Iterator /// The iterator that produces elements of the map sequence. public struct Iterator: AsyncIteratorProtocol { @usableFromInline var baseIterator: Base.AsyncIterator @usableFromInline let transform: (Base.Element) async -> Transformed @usableFromInline init( _ baseIterator: Base.AsyncIterator, transform: @escaping (Base.Element) async -> Transformed ) { self.baseIterator = baseIterator self.transform = transform } /// Produces the next element in the map sequence. /// /// This iterator calls `next()` on its base iterator; if this call returns /// `nil`, `next()` returns `nil`. Otherwise, `next()` returns the result of /// calling the transforming closure on the received element. @inlinable public mutating func next() async rethrows -> Transformed? { guard let element = try await baseIterator.next() else { return nil } return await transform(element) } } @inlinable public __consuming func makeAsyncIterator() -> Iterator { return Iterator(base.makeAsyncIterator(), transform: transform) } } @available(SwiftStdlib 5.1, *) extension AsyncMapSequence: @unchecked Sendable where Base: Sendable, Base.Element: Sendable, Transformed: Sendable { } @available(SwiftStdlib 5.1, *) extension AsyncMapSequence.Iterator: @unchecked Sendable where Base.AsyncIterator: Sendable, Base.Element: Sendable, Transformed: Sendable { }
apache-2.0
3527ba099ab2031963bd03a34fe15a55
34.098485
80
0.660263
4.587129
false
false
false
false
loganSims/wsdot-ios-app
wsdot/TwitterStore.swift
2
2822
// // TwitterStore.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation import Alamofire import SwiftyJSON class TwitterStore { typealias FetchTweetsCompletion = (_ data: [TwitterItem]?, _ error: Error?) -> () static func getTweets(_ screenName: String?, completion: @escaping FetchTweetsCompletion) { var url = "https://www.wsdot.wa.gov/news/socialroom/posts/twitter/" if let screenNameValue = screenName { url = url + screenNameValue } AF.request(url).validate().responseJSON { response in switch response.result { case .success: if let value = response.data { let json = JSON(value) let videoItems = parsePostsJSON(json) completion(videoItems, nil) } case .failure(let error): print(error) completion(nil, error) } } } fileprivate static func parsePostsJSON(_ json: JSON) ->[TwitterItem]{ var tweets = [TwitterItem]() for (_,postJson):(String, JSON) in json { let post = TwitterItem() post.id = postJson["id"].stringValue post.name = postJson["user"]["name"].stringValue post.screenName = postJson["user"]["screen_name"].stringValue post.text = postJson["text"].stringValue.replacingOccurrences(of: "(https?:\\/\\/[-a-zA-Z0-9._~:\\/?#@!$&\'()*+,;=%]+)", with: "<a href=\"$1\">$1</a>", options: .regularExpression, range: nil).replacingOccurrences(of: "&amp;", with:"&") post.link = "https://twitter.com/" + post.screenName + "/status/" + post.id post.mediaUrl = postJson["entities"]["media"][0]["media_url"].string post.published = TimeUtils.postPubDateToNSDate(postJson["created_at"].stringValue, formatStr: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", isUTC: true) tweets.append(post) } return tweets } }
gpl-3.0
6243262183753c648fb12b670fe26bf1
35.649351
248
0.590007
4.409375
false
false
false
false
gottesmm/swift
stdlib/public/SDK/Intents/INDoubleResolutionResult.swift
3
880
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation #if os(iOS) @available(iOS 10.0, *) extension INDoubleResolutionResult { @nonobjc public static func confirmationRequired(with valueToConfirm: Double?) -> Self { let number = valueToConfirm.map { NSNumber(value: $0) } return __confirmationRequiredWithValue(toConfirm: number) } } #endif
apache-2.0
ed0bc7b1ca7f32b42eea546623b356b1
34.2
80
0.595455
4.835165
false
false
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Filters/LineDetection.swift
1
2697
// // LineDetection.swift // Pods // // Created by Mohssen Fathi on 5/9/16. // // import UIKit struct MTLLineDetectionUniforms { var sensitivity: Float = 0.5; } public class LineDetection: Filter { var uniforms = MTLLineDetectionUniforms() private var accumulatorBuffer: MTLBuffer! private var inputSize: CGSize? private let sobelEdgeDetectionThreshold = SobelEdgeDetectionThreshold() private let thetaCount: Int = 180 lazy private var accumulator: [UInt8] = { return [UInt8](repeating: 0, count: Int(self.inputSize!.width) * self.thetaCount) }() @objc public var sensitivity: Float = 0.5 { didSet { clamp(&sensitivity, low: 0, high: 1) needsUpdate = true } } public init() { super.init(functionName: "lineDetection") title = "Line Detection" properties = [Property(key: "sensitivity", title: "Sensitivity")] sobelEdgeDetectionThreshold.addTarget(self) input = sobelEdgeDetectionThreshold update() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func update() { if self.input == nil { return } if inputSize == nil { inputSize = context.processingSize } else { if accumulatorBuffer != nil { let length = Int(inputSize!.width) * thetaCount let data = Data(bytesNoCopy: accumulatorBuffer.contents(), count: length, deallocator: Data.Deallocator.none) data.copyBytes(to: &accumulator, count: data.count) // let m = accumulator.max() // print(m) } } uniforms.sensitivity = sensitivity uniformsBuffer = device.makeBuffer(bytes: &uniforms, length: MemoryLayout<MTLLineDetectionUniforms>.size, options: .cpuCacheModeWriteCombined) } override func configureCommandEncoder(_ commandEncoder: MTLComputeCommandEncoder) { super.configureCommandEncoder(commandEncoder) let accumulator = [Float](repeating: 0, count: Int(inputSize!.width) * thetaCount) accumulatorBuffer = device.makeBuffer(bytes: accumulator, length: accumulator.count * MemoryLayout<Float>.size, options: .cpuCacheModeWriteCombined) commandEncoder.setBuffer(accumulatorBuffer, offset: 0, index: 1) } public override func process() { super.process() sobelEdgeDetectionThreshold.process() } }
mit
e0ba0f4025103692c8d4c875888497e8
29.647727
150
0.598443
4.842011
false
false
false
false
zhixingxi/JJA_Swift
JJA_Swift/JJA_Swift/Utils/Extensions/UIColorExtensions.swift
1
3403
// // UIColorExtensions.swift // JJA_Swift // // Created by MQL-IT on 2017/8/10. // Copyright © 2017年 MQL-IT. All rights reserved. // import UIKit /* #define SDTextColor [UIColor colorWithHexString:@"#cc3333"]//红 #define SDTextColor2 [UIColor colorWithHexString:@"#e08585"]//红 #define SDTextColor3 [UIColor colorWithHexString:@"#ffffff"]//白 #define SDTitleColor [UIColor colorWithHexString:@"#3a62fa"]//标题色 #define TableBckColor SDRGBColor(242, 244, 245, 1) #define SDBlack_OneColor [UIColor colorWithHexString:@"#000000"] #define SDBlack_TwoColor [UIColor colorWithHexString:@"#333333"] #define SDBlack_ThirdColor [UIColor colorWithHexString:@"#666666"] #define SDBlack_FourthColor [UIColor colorWithHexString:@"#999999"] #define SDBlack_FifthColor [UIColor colorWithHexString:@"#cccccc"] #define SDBlack_SixColor [UIColor colorWithHexString:@"#e1e1e1"] */ //MARK: - 颜色属性, 相当于宏定义 var colorCC3333: UIColor? {// 红 return UIColor(hexString: "#cc3333") } var colorE08585: UIColor? {// 红 return UIColor(hexString: "#e08585") } var colorFfffff: UIColor? { return UIColor(hexString: "#ffffff") } var color3a62fa: UIColor? { return UIColor(hexString: "#3a62fa") } var color000000: UIColor? { return UIColor(hexString: "000000") } var color333333: UIColor? { return UIColor(hexString: "333333") } var color666666: UIColor? { return UIColor(hexString: "666666") } var color999999: UIColor? { return UIColor(hexString: "999999") } var colorCccccc: UIColor? { return UIColor(hexString: "cccccc") } // MARK: - 颜色创建 extension UIColor { convenience init?(hexString: String, transparency: CGFloat = 1) { var string = "" if hexString.lowercased().hasPrefix("0x") { string = hexString.replacingOccurrences(of: "0x", with: "") } else if hexString.hasPrefix("#") { string = hexString.replacingOccurrences(of: "#", with: "") } else { string = hexString } if string.characters.count == 3 { // convert hex to 6 digit format if in short format var str = "" string.characters.forEach({ str.append(String(repeating: String($0), count: 2)) }) string = str } guard let hexValue = Int(string, radix: 16) else { return nil } self.init(hex: Int(hexValue), transparency: transparency) } convenience init?(red: Int, green: Int, blue: Int, transparency: CGFloat = 1) { guard red >= 0 && red <= 255 else { return nil } guard green >= 0 && green <= 255 else { return nil } guard blue >= 0 && blue <= 255 else { return nil } var trans = transparency if trans < 0 { trans = 0 } if trans > 1 { trans = 1 } self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: trans) } private convenience init?(hex: Int, transparency: CGFloat = 1) { var trans = transparency if trans < 0 { trans = 0 } if trans > 1 { trans = 1 } let red = (hex >> 16) & 0xff let green = (hex >> 8) & 0xff let blue = hex & 0xff self.init(red: red, green: green, blue: blue, transparency: trans) } }
mit
dc76118631bb8a3fcae8dfeb03aa16bc
29.509091
118
0.609654
3.844215
false
false
false
false
harenbrs/swix
swixUseCases/swix-iOS/swix/matrix/initing.swift
2
2697
// // twoD-initing.swift // swix // // Created by Scott Sievert on 7/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate func zeros(shape: (Int, Int)) -> matrix{ return matrix(columns: shape.1, rows: shape.0) } func zeros_like(x: matrix) -> matrix{ var y:matrix = zeros((x.shape.0, x.shape.1)) return y } func ones(shape: (Int, Int)) -> matrix{ return zeros(shape)+1 } func eye(N: Int) -> matrix{ var x = zeros((N,N)) x["diag"] = ones(N) return x } func randn(N: (Int, Int), mean: Double=0, sigma: Double=1, seed:Int=42) -> matrix{ var x = zeros(N) var y = randn(N.0 * N.1, mean:mean, sigma:sigma, seed:seed) x.flat = y return x } func rand(N: (Int, Int)) -> matrix{ var x = zeros(N) var y = rand(N.0 * N.1) x.flat = y return x } func reshape(x: ndarray, shape:(Int, Int))->matrix{ return x.reshape(shape) } func meshgrid(x: ndarray, y:ndarray) -> (matrix, matrix){ assert(x.n > 0 && y.n > 0, "If these matrices are empty meshgrid fails") var z1 = reshape(repeat(y, x.n), (x.n, y.n)) var z2 = reshape(repeat(x, y.n, axis:1), (x.n, y.n)) return (z2, z1) } /// array("1 2 3; 4 5 6; 7 8 9") works like matlab. note that string format has to be followed to the dot. String parsing has bugs; I'd use arange(9).reshape((3,3)) or something similar func array(matlab_like_string: String)->matrix{ var mls = matlab_like_string var rows = mls.componentsSeparatedByString(";") var r = rows.count var c = 0 for char in rows[0]{ if char == " " {} else {c += 1} } var x = zeros((r, c)) var start:Int var i:Int=0, j:Int=0 for row in rows{ var nums = row.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) if nums[0] == ""{start=1} else {start=0} j = 0 for n in start..<nums.count{ x[i, j] = nums[n].floatValue.double j += 1 } i += 1 } return x } func read_csv(filename:String, prefix:String=S2_PREFIX) -> matrix{ // docs need to be written on this var x = String.stringWithContentsOfFile(prefix+"../"+filename, encoding: NSUTF8StringEncoding, error: nil) var y = x!.componentsSeparatedByString("\n") var rows = y.count-1 var array:[Double] = [] var columns:Int = 0 for i in 0..<rows{ var z = y[i].componentsSeparatedByString(",") columns = 0 for num in z{ array.append(num.doubleValue) columns += 1 } } var done = zeros((rows, columns)) done.flat.grid = array return done }
mit
4986ee95b4056ba5493127e06a863784
20.404762
185
0.581016
3.184179
false
false
false
false
abellono/IssueReporter
IssueReporter/Core/Extensions/NSFileManager+Manager.swift
1
2464
// // FileManager+Manager.swift // IssueReporter // // Created by Hakon Hanesand on 10/6/16. // Copyright © 2017 abello. All rights reserved. // // import Foundation internal extension FileManager { static let documentsSubdirectoryName = "IssueReporter-UserImages" static let pngSuffix = ".png" class func eraseStoredPicturesFromDisk() { DispatchQueue.global(qos: .userInitiated).async { do { let manager = FileManager() let options: DirectoryEnumerationOptions = [.skipsSubdirectoryDescendants , .skipsPackageDescendants, .skipsHiddenFiles] let directory = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let pictureDirectory = directory.appendingPathComponent(FileManager.documentsSubdirectoryName) for file in try manager.contentsOfDirectory(at: pictureDirectory, includingPropertiesForKeys: nil, options: options) { if file.lastPathComponent.hasSuffix(FileManager.pngSuffix) { DispatchQueue.global(qos: .userInitiated).async { try? FileManager.default.removeItem(at: file) } } } } catch { print("Error while deleting temporary files : \(error)") } } } class func write(data: Data, completion: @escaping (URL) -> (), errorBlock: @escaping (Error) -> ()) { DispatchQueue.global(qos: .userInitiated).async { do { let manager = FileManager() let directory = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let pictureDirectory = directory.appendingPathComponent(FileManager.documentsSubdirectoryName) try manager.createDirectory(at: pictureDirectory, withIntermediateDirectories: true, attributes: nil) let saveLocation = pictureDirectory.randomURL(withExtension: FileManager.pngSuffix) try data.write(to: saveLocation) DispatchQueue.main.async { completion(saveLocation) } } catch { DispatchQueue.main.async { errorBlock(error) } } } } }
mit
8211cc38eb07262f1797b3fc56850298
38.095238
136
0.589525
5.572398
false
false
false
false
iOS-mamu/SS
P/Library/Eureka/Source/Rows/Controllers/MultipleSelectorViewController.swift
1
2885
// // MultipleSelectorViewController.swift // Eureka // // Created by Martin Barreto on 2/24/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation /// Selector Controller that enables multiple selection open class _MultipleSelectorViewController<T:Hashable, Row: SelectableRowType> : FormViewController, TypedRowControllerType where Row: BaseRow, Row: TypedRowType, Row.Value == T, Row.Cell.Value == T { /// The row that pushed or presented this controller open var row: RowOf<Set<T>>! open var selectableRowCellSetup: ((_ cell: Row.Cell, _ row: Row) -> ())? open var selectableRowCellUpdate: ((_ cell: Row.Cell, _ row: Row) -> ())? /// A closure to be called when the controller disappears. open var completionCallback : ((UIViewController) -> ())? override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience public init(_ callback: @escaping (UIViewController) -> ()){ self.init(nibName: nil, bundle: nil) completionCallback = callback } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() guard let options = row.dataProvider?.arrayData else { return } form +++ SelectableSection<Row, Row.Value>(row.title ?? "", selectionType: .multipleSelection) { [weak self] section in if let sec = section as? SelectableSection<Row, Row.Value> { sec.onSelectSelectableRow = { _, selectableRow in var newValue: Set<T> = self?.row.value ?? [] if let selectableValue = selectableRow.value { newValue.insert(selectableValue) } else { newValue.remove(selectableRow.selectableValue!) } self?.row.value = newValue } } } for o in options { form.first! <<< Row.init() { [weak self] in $0.title = String(describing: o.first!) $0.selectableValue = o.first! $0.value = self?.row.value?.contains(o.first!) ?? false ? o.first! : nil }.cellSetup { [weak self] cell, row in self?.selectableRowCellSetup?(cell, row) }.cellUpdate { [weak self] cell, row in self?.selectableRowCellUpdate?(cell, row) } } form.first?.header = HeaderFooterView<UITableViewHeaderFooterView>(title: row.title) } } open class MultipleSelectorViewController<T:Hashable> : _MultipleSelectorViewController<T, ListCheckRow<T>> { }
mit
ff6f871a63df062e181b7f5df2192f45
37.453333
200
0.59362
4.863406
false
false
false
false
dexafree/SayCheese
SayCheese/ImgurClient.swift
2
11787
// // ImgurClient.swift // SayCheese // // Created by Arasthel on 16/06/14. // Copyright (c) 2014 Jorge Martín Espinosa. All rights reserved. // import Foundation class ImgurClient: NSObject, IMGSessionDelegate, NSUserNotificationCenterDelegate { var doIfAuthenticated: (() -> Void!)? var isLoggedIn = false let imgurClientId = "b15bb6d7d24579c" let imgurClientSecret = "e7d9190b1230488ec63051117b412779f1fd6dcc" var authenticationDoneDelegate: ReceivedImgurAuthenticationDelegate? var uploadDelegate: UploadDelegate? var imgurSession: IMGSession? var deleteParam: String? var wasScreenshotUploadedWithAccount: Bool? override init() { super.init() imgurSession = IMGSession.authenticatedSessionWithClientID(imgurClientId, secret: imgurClientSecret, authType: IMGAuthType.PinAuth, withDelegate: self) } init(uploadDelegate: UploadDelegate) { super.init() imgurSession = IMGSession.authenticatedSessionWithClientID(imgurClientId, secret: imgurClientSecret, authType: IMGAuthType.PinAuth, withDelegate: self) self.uploadDelegate = uploadDelegate } func hasAccount() -> Bool! { let defaults = NSUserDefaults.standardUserDefaults() if defaults.objectForKey("imgur_token") != nil { return true } else { return false } } func authenticate(withToken: Bool) { let defaults = NSUserDefaults.standardUserDefaults() if defaults.objectForKey("imgur_token") != nil { let code = defaults.objectForKey("imgur_token") as! String NSLog("Requests: \(imgurSession!.creditsClientRemaining)") imgurSession!.authenticateWithRefreshToken(code) NSLog("Autenticando con token: \(code)") } else { imgurSession!.authenticate() } } func imgurSessionNeedsExternalWebview(url: NSURL, completion: () -> Void) { NSWorkspace.sharedWorkspace().openURL(url) if (authenticationDoneDelegate != nil) { authenticationDoneDelegate!.activatePinButton() } } func imgurRequestFailed(error: NSError?) { NSLog("Error") } func imgurSessionAuthStateChanged(state: IMGAuthState) { NSLog("State: \(state.rawValue)") let defaults = NSUserDefaults.standardUserDefaults() if state == IMGAuthState.Authenticated { defaults.setObject(imgurSession!.refreshToken as NSString, forKey: "imgur_token") defaults.synchronize() if (authenticationDoneDelegate != nil) { authenticationDoneDelegate!.authenticationInImgurSuccessful() } isLoggedIn = true } else if state == IMGAuthState.Expired { defaults.removeObjectForKey("imgur_token") defaults.synchronize() } } func imgurSessionTokenRefreshed() { // If we need to upload anything, do it if (doIfAuthenticated != nil) { doIfAuthenticated!() doIfAuthenticated = nil } isLoggedIn = true } func isAccessTokenValid() -> Bool! { let formatter = NSDateFormatter() formatter.dateFormat = "dd-MM-yyyy hh:mm:ss" if imgurSession != nil { if imgurSession!.accessTokenExpiry != nil { if imgurSession!.accessTokenExpiry!.compare(NSDate()) == NSComparisonResult.OrderedDescending { // Token valid isLoggedIn = true println("LoggedIn") return true } else { // Token expired isLoggedIn = false println("Not logged in") return false } } else { println("AccesTokenExpiry was nil") } } else { println("imgursession was nil") } return false } func uploadImage(let image: NSImage) { let imageUploadedCallback = { (uploadedImage: IMGImage?) -> Void in self.notifyImageUploaded(uploadedImage!.url.absoluteString!, param: uploadedImage!.deletehash) self.wasScreenshotUploadedWithAccount = self.hasAccount() } var uploadIfOk = { () -> Void in self.uploadDelegate?.uploadStarted() let date = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "dd-MM-yyyy hh:mm:ss" var imageData = image.TIFFRepresentation; let imageRepresentation = NSBitmapImageRep(data: imageData!); let imageProps = [ NSImageCompressionFactor: 1.0 ]; imageData = imageRepresentation!.representationUsingType(NSBitmapImageFileType.NSJPEGFileType, properties: imageProps); IMGImageRequest.uploadImageWithData(imageData, title: "Screenshot - \(formatter.stringFromDate(date))", success: imageUploadedCallback, progress: nil, failure: nil) } if !hasAccount() { wasScreenshotUploadedWithAccount = false anonymouslyUploadImage(image) } else { wasScreenshotUploadedWithAccount = true if isAccessTokenValid() == true { uploadIfOk() } else { doIfAuthenticated = { (uploadIfOk)($0) } imgurSession!.authenticate() } } } func notifyImageUploaded(url: String, param: String) { // Save url in pasteboard let pasteboard = NSPasteboard.generalPasteboard() let types = [NSStringPboardType] pasteboard.declareTypes(types, owner: nil) pasteboard.setString(url, forType: NSStringPboardType) self.deleteParam = param uploadDelegate?.uploadFinished() // Send notification dispatch_async(dispatch_get_main_queue(), { let notification = NSUserNotification() notification.title = "Image uploaded to imgur!" notification.userInfo = ["url": url] notification.informativeText = "The url is on your clipboard. Click to open it in a web browser." notification.soundName = NSUserNotificationDefaultSoundName let center = NSUserNotificationCenter.defaultUserNotificationCenter() center.delegate = self center.deliverNotification(notification) }) } func notifyImageNotUploaded(errorCode: Int){ dispatch_async(dispatch_get_main_queue(), { let notification = NSUserNotification() notification.title = "Error while uploading image" notification.informativeText = "Error code: \(errorCode)" let center = NSUserNotificationCenter.defaultUserNotificationCenter() center.deliverNotification(notification) }) } func deleteLastImage(){ if deleteParam != nil { let operationManager = AFHTTPRequestOperationManager() var authHeader: String if wasScreenshotUploadedWithAccount! { authHeader = "Client-Bearer \(imgurSession!.accessToken)" } else { authHeader = "Client-ID \(imgurClientId)" } println("AuthHeader: \(authHeader)") operationManager.requestSerializer.setValue(authHeader, forHTTPHeaderField: "Authorization") operationManager.DELETE("https://api.imgur.com/3/image/\(deleteParam!)", parameters: nil, success: {(operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in self.notifyImageDeleted((response as! NSDictionary).valueForKey("success") as! Bool) }, failure: {(operation: AFHTTPRequestOperation!, error: NSError!) -> Void in NSLog(error.description) }) } } func notifyImageDeleted(success: Bool){ var title: String if success { title = "Image deleted successfully!" } else { title = "Could not delete image" } let notification = NSUserNotification() notification.title = title notification.informativeText = "" notification.soundName = NSUserNotificationDefaultSoundName let center = NSUserNotificationCenter.defaultUserNotificationCenter() center.delegate = self center.deliverNotification(notification) if uploadDelegate != nil { uploadDelegate!.imageDeleted() } } func anonymouslyUploadImage(let image: NSImage) { self.uploadDelegate?.uploadStarted() let date = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "dd-MM-yyyy hh:mm:ss" let representation = NSBitmapImageRep(data: image.TIFFRepresentation!) var temp = [NSObject: AnyObject]() let data = representation!.representationUsingType(NSBitmapImageFileType.NSJPEGFileType, properties: temp) let title = "Screenshot - \(formatter.stringFromDate(date))" let operationManager = AFHTTPRequestOperationManager() operationManager.requestSerializer.setValue("Client-ID \(imgurClientId)", forHTTPHeaderField: "Authorization") var parameters = ["type": "file", "title": title] operationManager.POST("https://api.imgur.com/3/upload", parameters: parameters, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in formData.appendPartWithFileData(data, name: "image", fileName: title, mimeType: "image/jpeg") }, success: {(operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in let dictionary = (response as! NSDictionary).valueForKey("data") as! NSDictionary let deleteParam: String? = dictionary.valueForKey("deletehash") as! String? println("DELETEPARAM: \(deleteParam!)") self.notifyImageUploaded(dictionary.valueForKey("link") as! String, param: deleteParam!) }, failure: {(operation: AFHTTPRequestOperation!, error: NSError!) -> Void in self.uploadDelegate?.uploadFinished() var httpCode = error.code self.notifyImageNotUploaded(httpCode) NSLog(error.description) }) } func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) { //let url = NSURL.URLWithString(notification.userInfo.indexForKey("url") as String)) let url = NSURL(string: (notification.valueForKey("url") as! String)) let urlTemp = notification.valueForKey("url") as! String println("URL: \(urlTemp)") NSWorkspace.sharedWorkspace().openURL(url!) } func signOut(){ let defaults = NSUserDefaults.standardUserDefaults() defaults.removeObjectForKey("imgur_token") self.isLoggedIn = false } }
apache-2.0
1954931171299f7dc885b7e658ba2e1f
35.264615
176
0.597913
5.633843
false
false
false
false
daviejaneway/OrbitFrontend
Sources/TypeDefRule.swift
1
2425
// // TypeDefRule.swift // OrbitFrontend // // Created by Davie Janeway on 06/09/2017. // // import Foundation import OrbitCompilerUtils public class TypeDefRule : ParseRule { public let name = "Orb.Core.Grammar.TypeDef" public init() {} public func trigger(tokens: [Token]) throws -> Bool { guard let first = tokens.first else { throw OrbitError.ranOutOfTokens() } return first.type == .Keyword && Keywords.type.matches(token: first) } public func parse(context: ParseContext) throws -> AbstractExpression { let start = try context.consume() let nameParser = TypeIdentifierRule() // TODO: Forbid list types here let name = try nameParser.parse(context: context) as! TypeIdentifierExpression guard context.hasMore() else { // In a normal program, a type def at the end of the source // would be a weird syntax error, but allowing things like this // will make REPL work easier. // An unclosed api will still throw the correct error return TypeDefExpression(name: name, properties: [], propertyOrder: [:], constructorSignatures: [], adoptedTraits: [], startToken: start) } let next = try context.peek() guard next.type == .LParen else { return TypeDefExpression(name: name, properties: [], propertyOrder: [:], constructorSignatures: [], adoptedTraits: [], startToken: start) } let pairParser = PairRule() let expressionSetParser = ParenthesisedExpressionsRule(innerRule: pairParser) let properties = try (expressionSetParser.parse(context: context) as! NonTerminalExpression<[AbstractExpression]>).value as! [PairExpression] var order = [String : Int]() properties.enumerated().forEach { order[$0.element.name.value] = $0.offset } let defaultConstructorName = IdentifierExpression(value: "__init__", startToken: start) let defaultConstructorSignature = StaticSignatureExpression(name: defaultConstructorName, receiverType: name, parameters: properties, returnType: name, genericConstraints: nil, startToken: start) return TypeDefExpression(name: name, properties: properties, propertyOrder: order, constructorSignatures: [defaultConstructorSignature], adoptedTraits: [], startToken: start) } }
mit
40808eb8e6a78a49b95e8390a3210640
43.907407
203
0.664742
4.672447
false
false
false
false
machelix/Cheetah
Cheetah/CheetahProperties.swift
1
3032
// // CheetahProperties.swift // Cheetah // // Created by Suguru Namura on 2015/08/19. // Copyright © 2015年 Suguru Namura. // import UIKit // CheetahProperty public class CheetahProperty { weak var view: UIView! weak var group: CheetahGroup! var duration: CFTimeInterval = 1 var delay: CFTimeInterval = 0 var elapsed: CFTimeInterval = 0 var current: CGFloat = 0 var easing: Easing = Easings.linear var completion: (() -> Void)? var relative: Bool = false var transform: CATransform3D = CATransform3DIdentity func proceed(dt: CFTimeInterval) -> Bool { let end = delay + duration if elapsed >= end { return true } elapsed = min(elapsed + dt, end) if elapsed >= delay { current = CGFloat((elapsed - delay) / duration) update() } if let completion = completion where elapsed >= end { completion() } return elapsed >= end } func prepare() { // reset values elapsed = 0 current = 0 } func calc() { } func update() { } } public class CheetahCGFloatProperty: CheetahProperty { var from: CGFloat = 0 var to: CGFloat = 0 var toCalc: CGFloat = 0 override func calc() { if relative { toCalc = from + to } else { toCalc = to } } } public class CheetahCGSizeProperty: CheetahProperty { var from: CGSize = CGSizeZero var to: CGSize = CGSizeZero var toCalc: CGSize = CGSizeZero override func calc() { if relative { toCalc = CGSize(width: from.width+to.width, height: from.height+to.height) } else { toCalc = to } } } public class CheetahCGPointProperty: CheetahProperty { var from: CGPoint = CGPointZero var to: CGPoint = CGPointZero var toCalc: CGPoint = CGPointZero override func calc() { if relative { toCalc = CGPoint(x: from.x+to.x, y: from.y+to.y) } else { toCalc = to } } } public class CheetahCGRectProperty: CheetahProperty { var from: CGRect = CGRectZero var to: CGRect = CGRectZero var toCalc: CGRect = CGRectZero override func calc() { if relative { toCalc = CGRect(x: from.origin.x+to.origin.x, y: from.origin.y+to.origin.y, width: from.width+to.width, height: from.height+to.height) } else { toCalc = to } } } public class CheetahUIColorProperty: CheetahProperty { var from: UIColor! var to: UIColor! var toCalc: UIColor! override func calc() { if relative { let fromRGBA = RGBA.fromUIColor(from) let toRGBA = RGBA.fromUIColor(to) toCalc = UIColor(red: fromRGBA.red+toRGBA.red, green: fromRGBA.green+toRGBA.green, blue: fromRGBA.blue+toRGBA.blue, alpha: fromRGBA.alpha+toRGBA.alpha) } else { toCalc = to } } }
mit
e80203626738de2269a8d4a54bebdcb1
24.241667
163
0.579399
4.20111
false
false
false
false
alexfish/stylize
Stylize/Stylize/Stylize.swift
1
15554
// // Stylize.swift // // // Created by Alex Fish on 10/01/2015. // // import UIKit /// Helpers public typealias AttributeName = NSAttributedStringKey public typealias AttributeValue = AnyObject public typealias StringStyle = (NSAttributedString) -> NSAttributedString /** Writing direction for NSWritingDirectionAttributeName - LeftToRightEmbedding: NSWritingDirectionLeftToRight | NSTextWritingDirectionEmbedding - RightToLeftEmbedding: NSWritingDirectionRightToLeft | NSTextWritingDirectionEmbedding - LeftToRightOverride: NSWritingDirectionLeftToRight | NSTextWritingDirectionOverride - RightToLeftOverride: NSWritingDirectionRightToLeft | NSTextWritingDirectionOverride */ public enum WritingDirection: NSNumber { case leftToRightEmbedding = 0 case rightToLeftEmbedding = 1 case leftToRightOverride = 2 case rightToLeftOverride = 3 } /** * Easy attributed strings */ open class Stylize { // MARK: Styles /** Creates a function that will underline an attributed string :param: style The NSUnderlineStyle to use when underlining :param: range Optional range of the underline, an invalid range will result in the entire string being underlined :returns: Function that can be called to underline an attributed string */ open class func underline(_ style: NSUnderlineStyle, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.underlineStyle, value: style.rawValue as AttributeValue, range: range)(string) } } /** Creates a function that will strikethrough an attributed string :param: style The NSUnderlineStyle to strikethrough with :param: range Optional range of the strikethrough, an invalid range will result in the entire string being striked through :returns: Function that can be called to strikthrough an attributed string */ open class func strikethrough(_ style: NSUnderlineStyle, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.strikethroughStyle, value: style.rawValue as AttributeValue, range: range)(string) } } /** Creates a function that will change the foreground color of an attributed string :param: color The UIColor to use when styling a string :param: range Optional range of the color, an invalid range will result in the entire string being colored :returns: Function that can be called to change the foreground color of an attributed string */ open class func foreground(_ color: UIColor, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.foregroundColor, value: color, range: range)(string) } } /** Creates a function that will change the background color of an attributed string :param: color The UIColor to use when styling the string :param: range Optional range of the color, an invalid range will result in the entire string being colored :returns: Function that can be called to change the background color of an attributed string */ open class func background(_ color: UIColor, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.backgroundColor, value: color, range: range)(string) } } /** Creates a function that will change the underline color of an attributed string :param: color The UIColor to use when styling the string :param: range Optional range of the color, an invalid range will result in the entire string underline being colored :returns: Function that can be called to change the underline color of an attributed string */ open class func underline(_ color: UIColor, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.underlineColor, value: color, range: range)(string) } } /** Creates a function that will change the strikethrough color of an attributed string :param: color The UIColor to use when styling the string :param: range Optional range of the color, an invalid range will result in the entire string strikethrough being colored :returns: Function that can be called to change the strikethrough color of an attributed string */ open class func strikethrough(_ color: UIColor, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.strikethroughColor, value: color, range: range)(string) } } /** Creates a function that will create a ink within an attributed string :param: url The URL to link with :param: range Optional range of the link, an invalid range will result in the entire string being linked :returns: Function that can be called to create a link with an attributed string */ open class func link(_ url: URL, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.link, value: url as AttributeValue, range: range)(string) } } /** Creates a function that will apply a paragraph style to an attributed string :param: style The paragraph style to style the string with :param: range Optional range of the paragraph style, an invalid range will result in the entire string being styled :returns: Function that can be called to style an attributed string with a paragraph style */ open class func paragraph(_ style: NSParagraphStyle, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.paragraphStyle, value: style, range: range)(string) } } /** Creates a function that will alter the kern of an attributed string :param: points The amount of points to kern per character :param: range Optional range of the kern, an invalid range will result in the entire string being kerned by the amount of points :returns: Function that can be called to alter the kern of an attributed string */ open class func kern(_ points: NSNumber, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.kern, value: points, range: range)(string) } } /** Creates a function that will alter the baseline of an attributed string :param: offset The amount of points to offset the baseline by :param: range Optional range of the baseline, an invalid range will result in the entire string's baseline being offset by the amount of points :returns: Function that can be called to alter the baseline of an attributed string */ open class func baseline(_ offset: NSNumber, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.baselineOffset, value: offset, range: range)(string) } } /** Creates a function that will apply a shadow to an attributed string :param: shadow An NSShadow object to apply :param: range Optional range of the shadow, an invalid range will result in the shadow being applied to the entire string :returns: Function that can be called to apply a shadow to an attributed string */ open class func shadow(_ shadow: NSShadow, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.shadow, value: shadow, range: range)(string) } } /** Creates a function that will apply a stroke color to an attribute string :param: color The color to apply :param: range Optional range of the color, an invalid range will result in the color being applied to the entire string :returns: Function that can be called to apply a stroke color to an attributed string */ open class func stroke(_ color: UIColor, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.strokeColor, value: color, range: range)(string) } } /** Creates a function that will apply a stroke width to an attributed string :param: width The stroke width to apply :param: range Optional range of the stroke width, an invalid range will result in the stroke width being applied to the entire string :returns: Function that can be called to apply a stroke width to an attributed string */ open class func stroke(_ width: NSNumber, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.strokeWidth, value: width, range: range)(string) } } /** Creates a function that will apply a letterpress effect to an attributed string :param: range Optional range of the letterpress effect, an invalid range will result in a letterpress effect being applied to the entire string :returns: Function that can be called to apply letterpress effect to an attributed string */ open class func letterpress(_ range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.textEffect, value: NSAttributedString.TextEffectStyle.letterpressStyle as AttributeValue, range: range)(string) } } /** Creates a function that will apply a font to an attributed string :param: font The font to apply :param: range Optional range of the font, an invalid range will result in the font being applied to the entire string :returns: Function that can be called to apply a font to an attributed string */ open class func font(_ font: UIFont, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.font, value: font, range: range)(string) } } /** Creates a function that will enable or disable ligatures in an attributed string :param: enabled true for ligatures false for none, if the font supports it :param: range Optional range of the ligatures, an invalid range will result in the ligatures being applied to the entire string :returns: Function that can be called to enable or disable ligatures in an attributed string */ open class func ligatures(_ enabled: Bool, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.ligature, value: NSNumber(value: enabled as Bool), range: range)(string) } } /** Creates a function that will alter the obliqueness of an attributed string :param: skew The amount of skew to apply to glyphs :param: range Optional range of the obliqueness, an invalid range will result in the obliqueness being applied to the entire string :returns: Function that can be called to alter the obliqueness of an attributed string */ open class func obliqueness(_ skew: NSNumber, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.obliqueness, value: skew, range: range)(string) } } /** Creates a function that will attach a text attachement to an attributed string :param: attachement The attachement to attach :param: range Optional range of the attachement, an invalid range will result in the attachement being applied to the entire string :returns: Function that can be called to attach an attachement an attributed string */ open class func attachment(_ attachement: NSTextAttachment, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.attachment, value: attachement, range: range)(string) } } /** Creates a function that will expand an attributed string :param: log The log of the expansion factor :param: range Optional range of the expansion, an invalid range will result in the expansion being applied to the entire string :returns: Function that can be called to expand an attributed string */ open class func expand(_ log: NSNumber, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.expansion, value: log, range: range)(string) } } /** Creates a function that will alter the writing direction of an attributed string :param: direction The writing direction to apply :param: range Optional range of the writing direction, an invalid range will result in the writing direction being applied to the entire string :returns: Function that can be called to alter the writing direction of an attributed string */ open class func direction(_ direction: WritingDirection, range: NSRange = NSMakeRange(NSNotFound, 0)) -> StringStyle { return { string in return self.apply(NSAttributedStringKey.writingDirection, value: direction.rawValue, range: range)(string) } } // MARK: Compose /** Compose a style from multiple styles that can be used to style an attributed string :param: style1 The first style to compose with :param: style2 The second style to compose with :returns: Function that can be called to style an attributed string */ open class func compose(style1: @escaping StringStyle, style2: @escaping StringStyle) -> StringStyle { return { string in style2(style1(string)) } } /** Compose multiple style functions into one function that can be used to style an attributed string :param: styles An unlimted number of StringStyle functions to compose :returns: Function that can be called to style an attributed string */ open class func compose(_ styles: StringStyle...) -> StringStyle { var composed = styles.first! for style in styles { composed = compose(style1: composed, style2: style) } return composed } } // MARK: Private fileprivate extension Stylize { /// Create a function that applies new attributes to an attributed string class func apply(_ name: AttributeName, value: AttributeValue, range: NSRange) -> StringStyle { var range = range return { string in if range.location == NSNotFound { range = NSMakeRange(0, string.length) } let attributedString = NSMutableAttributedString(attributedString: string) attributedString.addAttribute(name, value: value, range: range) return attributedString } } }
mit
73dfcd21edafb5fed12ac9c1809f857d
38.882051
163
0.688119
5.143519
false
false
false
false
mzp/OctoEye
Sources/GithubFileExtension/FileProvider/FileProviderExtension.swift
1
6839
// // FileProviderExtension.swift // GithubFileExtension // // Created by mzp on 2017/06/29. // Copyright © 2017 mzp. All rights reserved. // import FileProvider import Ikemen import Result internal class FileProviderExtension: NSFileProviderExtension { private let github: GithubClient? private let repositories: WatchingRepositories = WatchingRepositories.shared private let fileItemStore: FileItemStore = FileItemStore() var fileManager: FileManager = FileManager() convenience override init() { self.init(github: GithubClient.shared) } init(github: GithubClient?) { self.github = github super.init() } // MARK: - URL override func urlForItem(withPersistentIdentifier identifier: NSFileProviderItemIdentifier) -> URL? { guard let id = FileItemIdentifier.parse(identifier) else { return nil } guard let item = fileItemStore[id] else { return nil } // create URL as flat structure. // <base storage directory>/<item identifier>/<item file name> let manager = NSFileProviderManager.default let perItemDirectory = manager.documentStorageURL.appendingPathComponent(identifier.rawValue, isDirectory: true) return perItemDirectory.appendingPathComponent(item.key, isDirectory:false) } override func persistentIdentifierForItem(at url: URL) -> NSFileProviderItemIdentifier? { // resolve the given URL to a persistent identifier using a database let pathComponents = url.pathComponents // exploit the fact that the path structure has been defined as // <base storage directory>/<item identifier>/<item file name> above assert(pathComponents.count > 2) return NSFileProviderItemIdentifier(pathComponents[pathComponents.count - 2]) } // swiftlint:disable:next prohibited_super_call override func providePlaceholder(at url: URL, completionHandler: @escaping (Error?) -> Void) { NSLog("providePlaceholder \(url)") do { try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil) fileManager.createFile(atPath: url.path, contents: nil, attributes: nil) completionHandler(nil) } catch let e { completionHandler(e) } } override func startProvidingItem(at url: URL, completionHandler: ((_ error: Error?) -> Void)?) { guard let github = self.github else { return } // FIXME: skip download when latest content exists on disk guard let identifier = persistentIdentifierForItem(at: url) else { completionHandler?(NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:])) return } switch FileItemIdentifier.parse(identifier) { case .some(.entry(owner: let owner, name: let name, let oid, path: _)): FetchBlob(github: github) .call(owner: owner, name: name, oid: oid) .onSuccess { data in do { try data.write(to: url) completionHandler?(nil) } catch let e { completionHandler?(e) } } .onFailure { error in NSLog("FetchTextError: \(error)") } default: () } } override func itemChanged(at url: URL) { // Called at some point after the file has changed; the provider may then trigger an upload /* TODO: - mark file at <url> as needing an update in the model - if there are existing NSURLSessionTasks uploading this file, cancel them - create a fresh background NSURLSessionTask and schedule it to upload the current modifications - register the NSURLSessionTask with NSFileProviderManager to provide progress updates */ } override func stopProvidingItem(at url: URL) { // TODO: look up whether the file has local changes let fileHasLocalChanges = false if !fileHasLocalChanges { // remove the existing file to free up space do { _ = try FileManager.default.removeItem(at: url) } catch { // Handle error } // write out a placeholder to facilitate future property lookups self.providePlaceholder(at: url, completionHandler: { _ in // TODO: handle any error, do any necessary cleanup }) } } // MARK: - Enumeration // swiftlint:disable:next line_length override func enumerator(for containerItemIdentifier: NSFileProviderItemIdentifier) throws -> NSFileProviderEnumerator { guard let github = self.github else { throw NSError(domain: NSCocoaErrorDomain, code: NSFeatureUnsupportedError, userInfo:[:]) } let identifier = FileItemIdentifier.parse(containerItemIdentifier) ?? .root switch identifier { case .root: let items = repositories.map { RepositoryItem(owner: $0.owner.login, name: $0.name) } return ArrayEnumerator(items: items) case .repository(owner: let owner, name: let name): let future = FetchRootItems(github: github) .call(owner: owner, name: name) .map { $0.flatMap { GithubObjectItem(entryObject: $0, parent: identifier) } ※ { try? self.fileItemStore.append(parent: identifier, entries: $0.toDictionary { $0.key }) } } return FutureEnumerator(future: future) case .entry(owner: let owner, name: let name, oid: let oid, path: _): let future = FetchChildItems(github: github) .call(owner: owner, name: name, oid: oid) .map { $0.flatMap { GithubObjectItem(entryObject: $0, parent: identifier) } ※ { try? self.fileItemStore.append(parent: identifier, entries: $0.toDictionary { $0.key }) } } return FutureEnumerator(future: future) } } }
mit
4baeae6f718704a326c4f42d61a7863e
37.610169
124
0.566725
5.428118
false
false
false
false
Floater-ping/DYDemo
DYDemo/DYDemo/Classes/Home/Controller/HomeViewController.swift
1
3663
// // HomeViewController.swift // DYDemo // // Created by ZYP-MAC on 2017/7/31. // Copyright © 2017年 ZYP-MAC. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } fileprivate let pTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { //MARK:- 懒加载 fileprivate lazy var pageTitleView:PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: pStatusBarH+pNavigationBarH, width: pScreenWidth, height: pTitleViewH) let titles = ["推荐","游戏","娱乐","趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() fileprivate lazy var pageContentView : PageContentView = {[weak self] in let contentY = pStatusBarH + pNavigationBarH + pTitleViewH let contentH = pScreenHeight - contentY - pTabBarH let contentFrame = CGRect(x: 0, y: contentY, width: pScreenWidth, height: contentH) var childVCArr = [UIViewController]() childVCArr.append(RecommendController()) for _ in 0..<3 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVCArr.append(vc) } let contentView = PageContentView(frame: contentFrame, childVCs: childVCArr, parentViewController: self) contentView.delegate = self return contentView }() //MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() /// 1.设置ui界面 setupUI() /// 2.设置titleview view.addSubview(pageTitleView) /// 3.添加pageContentView view.addSubview(pageContentView) } } //MARK:- 设置ui界面 extension HomeViewController { fileprivate func setupUI() { /// 不需要调整scrollview的内边距 automaticallyAdjustsScrollViewInsets = false /// 设置导航栏 setupNavigationBar() } fileprivate func setupNavigationBar() { /// 1.设置左侧的item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") /// 2.设置右侧items let size = CGSize(width: 40, height: 40) // let qrcodeItem = UIBarButtonItem.createItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } } //MARK:- PageTitleViewDelegate extension HomeViewController : PageTitleViewDelegate { func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } } //MARK:- PageContentViewDelegate extension HomeViewController : PageContentViewDelegate { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
ee61af8a3031965a6813ce1e8c5be480
28.633333
156
0.6482
4.938889
false
false
false
false
srn214/Floral
Floral/Pods/Tiercel/Tiercel/General/Cache.swift
1
12093
// // Cache.swift // Tiercel // // Created by Daniels on 2018/3/16. // Copyright © 2018 Daniels. 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 public class Cache { private let ioQueue: DispatchQueue public let downloadPath: String public let downloadTmpPath: String public let downloadFilePath: String public let identifier: String private let fileManager = FileManager.default private let encoder = PropertyListEncoder() internal let decoder = PropertyListDecoder() private final class func defaultDiskCachePathClosure(_ cacheName: String) -> String { let dstPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! return (dstPath as NSString).appendingPathComponent(cacheName) } /// 初始化方法 /// /// - Parameters: /// - name: 不同的name,代表不同的下载模块,对应的文件放在不同的地方 public init(_ name: String) { self.identifier = name let ioQueueName = "com.Tiercel.Cache.ioQueue.\(name)" ioQueue = DispatchQueue(label: ioQueueName) let cacheName = "com.Daniels.Tiercel.Cache.\(name)" let diskCachePath = Cache.defaultDiskCachePathClosure(cacheName) downloadPath = (diskCachePath as NSString).appendingPathComponent("Downloads") downloadTmpPath = (downloadPath as NSString).appendingPathComponent("Tmp") downloadFilePath = (downloadPath as NSString).appendingPathComponent("File") createDirectory() decoder.userInfo[.cache] = self } } // MARK: - file extension Cache { internal func createDirectory() { if !fileManager.fileExists(atPath: downloadTmpPath) { do { try fileManager.createDirectory(atPath: downloadTmpPath, withIntermediateDirectories: true, attributes: nil) } catch { TiercelLog("createDirectory error: \(error)", identifier: identifier) } } if !fileManager.fileExists(atPath: downloadFilePath) { do { try fileManager.createDirectory(atPath: downloadFilePath, withIntermediateDirectories: true, attributes: nil) } catch { TiercelLog("createDirectory error: \(error)", identifier: identifier) } } } public func filePath(fileName: String) -> String? { if fileName.isEmpty { return nil } let path = (downloadFilePath as NSString).appendingPathComponent(fileName) return path } public func fileURL(fileName: String) -> URL? { guard let path = filePath(fileName: fileName) else { return nil } return URL(fileURLWithPath: path) } public func fileExists(fileName: String) -> Bool { guard let path = filePath(fileName: fileName) else { return false } return fileManager.fileExists(atPath: path) } public func filePath(url: URLConvertible) -> String? { do { let validURL = try url.asURL() let fileName = validURL.tr.fileName return filePath(fileName: fileName) } catch { return nil } } public func fileURL(url: URLConvertible) -> URL? { guard let path = filePath(url: url) else { return nil } return URL(fileURLWithPath: path) } public func fileExists(url: URLConvertible) -> Bool { guard let path = filePath(url: url) else { return false } return fileManager.fileExists(atPath: path) } public func clearDiskCache(onMainQueue: Bool = true, _ handler: Handler<Cache>? = nil) { ioQueue.async { guard self.fileManager.fileExists(atPath: self.downloadPath) else { return } do { try self.fileManager.removeItem(atPath: self.downloadPath) } catch { TiercelLog("removeItem error: \(error)", identifier: self.identifier) } self.createDirectory() if let handler = handler { Executer(onMainQueue: onMainQueue, handler: handler).execute(self) } } } } // MARK: - retrieve extension Cache { internal func retrieveAllTasks() -> [DownloadTask] { return ioQueue.sync { var path = (downloadPath as NSString).appendingPathComponent("\(identifier)_Tasks.plist") var tasks: [DownloadTask] if fileManager.fileExists(atPath: path) { do { let url = URL(fileURLWithPath: path) let data = try Data(contentsOf: url) tasks = try decoder.decode([DownloadTask].self, from: data) } catch { TiercelLog("retrieveAllTasks error: \(error)", identifier: identifier) return [DownloadTask]() } } else { path = (downloadPath as NSString).appendingPathComponent("\(identifier)Tasks.plist") tasks = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [DownloadTask] ?? [DownloadTask]() } tasks.forEach { (task) in task.cache = self if task.status == .waiting { task.status = .suspended } } return tasks } } internal func retrieveTmpFile(_ task: DownloadTask) { ioQueue.sync { guard let tmpFileName = task.tmpFileName, !tmpFileName.isEmpty else { return } let path1 = (downloadTmpPath as NSString).appendingPathComponent(tmpFileName) let path2 = (NSTemporaryDirectory() as NSString).appendingPathComponent(tmpFileName) guard fileManager.fileExists(atPath: path1) else { return } if fileManager.fileExists(atPath: path2) { do { try fileManager.removeItem(atPath: path1) } catch { TiercelLog("removeItem error: \(error)", identifier: identifier) } } else { do { try fileManager.moveItem(atPath: path1, toPath: path2) } catch { TiercelLog("moveItem error: \(error)", identifier: identifier) } } } } } // MARK: - store extension Cache { internal func storeTasks(_ tasks: [DownloadTask]) { ioQueue.sync { do { let data = try encoder.encode(tasks) var path = (downloadPath as NSString).appendingPathComponent("\(identifier)_Tasks.plist") let url = URL(fileURLWithPath: path) try data.write(to: url) path = (downloadPath as NSString).appendingPathComponent("\(identifier)Tasks.plist") try? fileManager.removeItem(atPath: path) } catch { TiercelLog("storeTasks error: \(error)", identifier: identifier) } } } internal func storeFile(_ task: DownloadTask) { ioQueue.sync { guard let location = task.tmpFileURL else { return } let destination = (downloadFilePath as NSString).appendingPathComponent(task.fileName) do { try fileManager.moveItem(at: location, to: URL(fileURLWithPath: destination)) } catch { TiercelLog("moveItem error: \(error)", identifier: identifier) } } } internal func storeTmpFile(_ task: DownloadTask) { ioQueue.sync { guard let tmpFileName = task.tmpFileName, !tmpFileName.isEmpty else { return } let tmpPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(tmpFileName) let destination = (downloadTmpPath as NSString).appendingPathComponent(tmpFileName) if fileManager.fileExists(atPath: destination) { do { try fileManager.removeItem(atPath: destination) } catch { TiercelLog("removeItem error: \(error)", identifier: identifier) } } if fileManager.fileExists(atPath: tmpPath) { do { try fileManager.copyItem(atPath: tmpPath, toPath: destination) } catch { TiercelLog("copyItem error: \(error)", identifier: identifier) } } } } internal func updateFileName(_ task: DownloadTask, _ newFileName: String) { ioQueue.sync { if fileManager.fileExists(atPath: task.filePath) { do { try fileManager.moveItem(atPath: task.filePath, toPath: filePath(fileName: newFileName)!) } catch { TiercelLog("updateFileName error: \(error)", identifier: identifier) } } } } } // MARK: - remove extension Cache { internal func remove(_ task: DownloadTask, completely: Bool) { removeTmpFile(task) if completely { removeFile(task) } } internal func removeFile(_ task: DownloadTask) { ioQueue.async { if task.fileName.isEmpty { return } let path = (self.downloadFilePath as NSString).appendingPathComponent(task.fileName) if self.fileManager.fileExists(atPath: path) { do { try self.fileManager.removeItem(atPath: path) } catch { TiercelLog("removeItem error: \(error)", identifier: self.identifier) } } } } /// 删除保留在本地的缓存文件 /// /// - Parameter task: internal func removeTmpFile(_ task: DownloadTask) { ioQueue.async { guard let tmpFileName = task.tmpFileName, !tmpFileName.isEmpty else { return } let path1 = (self.downloadTmpPath as NSString).appendingPathComponent(tmpFileName) let path2 = (NSTemporaryDirectory() as NSString).appendingPathComponent(tmpFileName) [path1, path2].forEach { (path) in if self.fileManager.fileExists(atPath: path) { do { try self.fileManager.removeItem(atPath: path) } catch { TiercelLog("removeItem error: \(error)", identifier: self.identifier) } } } } } } extension URL: TiercelCompatible { } extension TiercelWrapper where Base == URL { public var fileName: String { var fileName = base.absoluteString.tr.md5 if !base.pathExtension.isEmpty { fileName += ".\(base.pathExtension)" } return fileName } }
mit
55772a0de8d0281461c19893cce83348
34.311765
125
0.584541
5.128578
false
false
false
false
haddenkim/dew
Sources/App/Controllers/PlaceController.swift
1
1777
// // PlaceController.swift // dew // // Created by Hadden Kim on 4/26/17. // // import Vapor import HTTP final class PlaceController { // READ all static func findAll(_ request: Request) throws -> ResponseRepresentable { let placesJSON = try Place.findAll() .map { Place($0) } .filter { $0 != nil } .map { $0! } .map { try $0.makeJSON() } return JSON(placesJSON) } // READ one static func findOne(_ request: Request, _ place: Place) throws -> ResponseRepresentable { return try Response(status: .ok, json: place.makeJSON()) } // CREATE static func create(_ request: Request) throws -> ResponseRepresentable { guard let json = request.json, let place = try? Place.init(json: json) else { throw Abort.badRequest } try place.save() return try Response(status: .created, json: place.makeJSON()) } // UPDATE static func update(_ request: Request, _ place: Place) throws -> ResponseRepresentable { guard let json = request.json, let updatedPlace = try? Place.init(json: json) else { throw Abort.badRequest } // update "allowed" changes place.name = updatedPlace.name place.coordinate = updatedPlace.coordinate place.openHours = updatedPlace.openHours try place.save() return try Response(status: .ok, json: place.makeJSON()) } // DELETE static func delete(_ request: Request, _ place: Place) throws -> ResponseRepresentable { try place.delete() return Response(status: .noContent) } }
mit
8619abb3a0beb5d41d106bb8a73e1b84
24.753623
93
0.563309
4.55641
false
false
false
false
instant-solutions/ISTimeline
ISTimeline/ISTimeline/ISTimeline.swift
1
9309
// // ISTimeline.swift // ISTimeline // // Created by Max Holzleitner on 07.05.16. // Copyright © 2016 instant:solutions. All rights reserved. // import UIKit open class ISTimeline: UIScrollView { fileprivate static let gap:CGFloat = 15.0 open var pointDiameter:CGFloat = 6.0 { didSet { if (pointDiameter < 0.0) { pointDiameter = 0.0 } else if (pointDiameter > 100.0) { pointDiameter = 100.0 } } } open var lineWidth:CGFloat = 2.0 { didSet { if (lineWidth < 0.0) { lineWidth = 0.0 } else if(lineWidth > 20.0) { lineWidth = 20.0 } } } open var bubbleRadius:CGFloat = 2.0 { didSet { if (bubbleRadius < 0.0) { bubbleRadius = 0.0 } else if (bubbleRadius > 6.0) { bubbleRadius = 6.0 } } } open var bubbleColor:UIColor = .init(red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0) open var titleColor:UIColor = .white open var descriptionColor:UIColor = .gray open var points:[ISPoint] = [] { didSet { self.layer.sublayers?.forEach({ (layer:CALayer) in if layer.isKind(of: CAShapeLayer.self) { layer.removeFromSuperlayer() } }) self.subviews.forEach { (view:UIView) in view.removeFromSuperview() } self.contentSize = CGSize.zero sections.removeAll() buildSections() layer.setNeedsDisplay() layer.displayIfNeeded() } } open var bubbleArrows:Bool = true fileprivate var sections:[(point:CGPoint, bubbleRect:CGRect, descriptionRect:CGRect?, titleLabel:UILabel, descriptionLabel:UILabel?, pointColor:CGColor, lineColor:CGColor, fill:Bool)] = [] override public init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } fileprivate func initialize() { self.clipsToBounds = true } override open func draw(_ rect: CGRect) { let ctx:CGContext = UIGraphicsGetCurrentContext()! ctx.saveGState() for i in 0 ..< sections.count { if (i < sections.count - 1) { var start = sections[i].point start.x += pointDiameter / 2 start.y += pointDiameter var end = sections[i + 1].point end.x = start.x drawLine(start, end: end, color: sections[i].lineColor) } drawPoint(sections[i].point, color: sections[i].pointColor, fill: sections[i].fill) drawBubble(sections[i].bubbleRect, backgroundColor: bubbleColor, textColor:titleColor, titleLabel: sections[i].titleLabel) let descriptionLabel = sections[i].descriptionLabel if (descriptionLabel != nil) { drawDescription(sections[i].descriptionRect!, textColor: descriptionColor, descriptionLabel: sections[i].descriptionLabel!) } } ctx.restoreGState() } fileprivate func buildSections() { self.setNeedsLayout() self.layoutIfNeeded() var y:CGFloat = self.bounds.origin.y + self.contentInset.top for i in 0 ..< points.count { let titleLabel = buildTitleLabel(i) let descriptionLabel = buildDescriptionLabel(i) let titleHeight = titleLabel.intrinsicContentSize.height var height:CGFloat = titleHeight if descriptionLabel != nil { height += descriptionLabel!.intrinsicContentSize.height } let point = CGPoint(x: self.bounds.origin.x + self.contentInset.left + lineWidth / 2, y: y + (titleHeight + ISTimeline.gap) / 2) let maxTitleWidth = calcWidth() var titleWidth = titleLabel.intrinsicContentSize.width + 20 if (titleWidth > maxTitleWidth) { titleWidth = maxTitleWidth } let offset:CGFloat = bubbleArrows ? 13 : 5 let bubbleRect = CGRect( x: point.x + pointDiameter + lineWidth / 2 + offset, y: y + pointDiameter / 2, width: titleWidth, height: titleHeight + ISTimeline.gap) var descriptionRect:CGRect? if descriptionLabel != nil { descriptionRect = CGRect( x: bubbleRect.origin.x, y: bubbleRect.origin.y + bubbleRect.height + 3, width: calcWidth(), height: descriptionLabel!.intrinsicContentSize.height) } sections.append((point, bubbleRect, descriptionRect, titleLabel, descriptionLabel, points[i].pointColor.cgColor, points[i].lineColor.cgColor, points[i].fill)) y += height y += ISTimeline.gap * 2.2 // section gap } y += pointDiameter / 2 self.contentSize = CGSize(width: self.bounds.width - (self.contentInset.left + self.contentInset.right), height: y) } fileprivate func buildTitleLabel(_ index:Int) -> UILabel { let titleLabel = UILabel() titleLabel.text = points[index].title titleLabel.font = UIFont.boldSystemFont(ofSize: 12.0) titleLabel.lineBreakMode = .byWordWrapping titleLabel.numberOfLines = 0 titleLabel.preferredMaxLayoutWidth = calcWidth() return titleLabel } fileprivate func buildDescriptionLabel(_ index:Int) -> UILabel? { let text = points[index].description if (text != nil) { let descriptionLabel = UILabel() descriptionLabel.text = text descriptionLabel.font = UIFont.systemFont(ofSize: 10.0) descriptionLabel.lineBreakMode = .byWordWrapping descriptionLabel.numberOfLines = 0 descriptionLabel.preferredMaxLayoutWidth = calcWidth() return descriptionLabel } return nil } fileprivate func calcWidth() -> CGFloat { return self.bounds.width - (self.contentInset.left + self.contentInset.right) - pointDiameter - lineWidth - ISTimeline.gap * 1.5 } fileprivate func drawLine(_ start:CGPoint, end:CGPoint, color:CGColor) { let path = UIBezierPath() path.move(to: start) path.addLine(to: end) let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.strokeColor = color shapeLayer.lineWidth = lineWidth self.layer.addSublayer(shapeLayer) } fileprivate func drawPoint(_ point:CGPoint, color:CGColor, fill:Bool) { let path = UIBezierPath(ovalIn: CGRect(x: point.x, y: point.y, width: pointDiameter, height: pointDiameter)) let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.strokeColor = color shapeLayer.fillColor = fill ? color : UIColor.clear.cgColor shapeLayer.lineWidth = lineWidth self.layer.addSublayer(shapeLayer) } fileprivate func drawBubble(_ rect:CGRect, backgroundColor:UIColor, textColor:UIColor, titleLabel:UILabel) { let path = UIBezierPath(roundedRect: rect, cornerRadius: bubbleRadius) if bubbleArrows { let startPoint = CGPoint(x: rect.origin.x, y: rect.origin.y + rect.height / 2 - 8) path.move(to: startPoint) path.addLine(to: startPoint) path.addLine(to: CGPoint(x: rect.origin.x - 8, y: rect.origin.y + rect.height / 2)) path.addLine(to: CGPoint(x: rect.origin.x, y: rect.origin.y + rect.height / 2 + 8)) } let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.fillColor = backgroundColor.cgColor self.layer.addSublayer(shapeLayer) let titleRect = CGRect(x: rect.origin.x + 10, y: rect.origin.y, width: rect.size.width - 15, height: rect.size.height - 1) titleLabel.textColor = textColor titleLabel.frame = titleRect self.addSubview(titleLabel) } fileprivate func drawDescription(_ rect:CGRect, textColor:UIColor, descriptionLabel:UILabel) { descriptionLabel.textColor = textColor descriptionLabel.frame = CGRect(x: rect.origin.x + 7, y: rect.origin.y, width: rect.width - 10, height: rect.height) self.addSubview(descriptionLabel) } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let point = touches.first!.location(in: self) for (index, section) in sections.enumerated() { if (section.bubbleRect.contains(point)) { points[index].touchUpInside?(points[index]) break } } } }
apache-2.0
4ccba4feb0ea8df4773d6d59c7b108a1
35.645669
192
0.573055
4.852972
false
false
false
false
BenedictC/BCOObjectStore
BCOObjectStoreTests/BCOIndexEntryTests.swift
1
737
// // BCOIndexEntryTests.swift // BCOObjectStore // // Created by Benedict Cohen on 06/02/2015. // Copyright (c) 2015 Benedict Cohen. All rights reserved. // import Foundation import XCTest class BCOIndexEntryTests: XCTestCase { func testCopyDoesNotModifyOriginal() { //Given let value = "arf arf arf" let references = NSSet() let original = BCOIndexEntry(indexValue:value, references:references) let copy = original.mutableCopy() as BCOMutableIndexEntry let reference = NSUUID() //When copy.addReference(reference) //Then let expected = references let actual = original.references XCTAssertEqual(expected, actual) } }
mit
e51e14e050c146935dbd37eaaaa853dc
20.057143
77
0.652646
4.117318
false
true
false
false
thomaskamps/SlideFeedback
SlideFeedback/SlideFeedback/LecturerSlideViewController.swift
1
7147
// // LecturerSlideViewController.swift // SlideFeedback // // Created by Thomas Kamps on 14-06-17. // Copyright © 2017 Thomas Kamps. All rights reserved. // import UIKit class LecturerSlideViewController: UIViewController, UIWebViewDelegate { // declare outlets @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var slideView: UIWebView! @IBOutlet weak var menuBar: UIView! @IBOutlet weak var feedbackLabel: UILabel! @IBAction func nextButton(_ sender: Any) { // check if page exists if (sio.currentRoom?.currentPage)! < ((sio.currentRoom?.numPages)! - 1) { // push new page to the server and load yourself sio.pageUp() slideViewLoad(urlString: (sio.currentRoom?.buildUrlString())!) } } @IBAction func previousButton(_ sender: Any) { // check if page exists if (sio.currentRoom?.currentPage)! > 0 { // push new page to the server and load yourself sio.pageDown() slideViewLoad(urlString: (sio.currentRoom?.buildUrlString())!) } } @IBAction func endSlideButton(_ sender: Any) { // push endLecture notification to server and dismiss view sio.endLecture() self.dismiss(animated: true, completion: nil) } // declare vars and models let sio = SocketIOManager.sharedInstance let db = FirebaseManager.sharedInstance var currentNegativeFeedback = 0 var currentPositiveFeedback = 0 let neutralColor = UIColor(red:0.56, green:0.75, blue:0.66, alpha:1.0) let alertColor = UIColor(red:0.98, green:0.77, blue:0.27, alpha:1.0) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.slideView.delegate = self // check if a room is selected if sio.currentRoom != nil { // become lecturer for the selected lecture and load first slide sio.claimLecture() slideViewLoad(urlString: (sio.currentRoom?.buildUrlString())!) // add observers NotificationCenter.default.addObserver(self, selector: #selector(self.receiveNegativeFeedback(notification:)), name: Notification.Name("receiveNegativeFeedback"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.receivePositiveFeedback(notification:)), name: Notification.Name("receivePositiveFeedback"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.alertConnection(notification:)), name: Notification.Name("alertConnection"), object: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self) } func slideViewLoad(urlString: String) { // reset feedback indications to neutral self.currentPositiveFeedback = 0 self.currentNegativeFeedback = 0 self.menuBar.backgroundColor = self.neutralColor self.feedbackLabel.text = "" // load new slide let url: NSURL! = NSURL(string: urlString) self.slideView.loadRequest(NSURLRequest(url: url as URL) as URLRequest) } func webViewDidFinishLoad(_ webView: UIWebView) { // resize content and stop activityIndicator when finished loading self.slideView.resizeWebContent() activityIndicator.stopAnimating() } func webViewDidStartLoad(_ webView: UIWebView) { // start activityIndicator activityIndicator.startAnimating() } func receiveNegativeFeedback(notification: Notification) { // save feedback to db db.saveFeedback(uniqueID: (sio.currentRoom?.uniqueID)!, currentPage: (sio.currentRoom?.currentPage)!, feedback: "negative", studentCount: sio.currentStudentCount ?? 1) // process in view self.currentNegativeFeedback += 1 self.processFeedback() } func receivePositiveFeedback(notification: Notification) { // save feedback to db db.saveFeedback(uniqueID: (sio.currentRoom?.uniqueID)!, currentPage: (sio.currentRoom?.currentPage)!, feedback: "positive", studentCount: sio.currentStudentCount ?? 1) // process in view self.currentPositiveFeedback += 1 self.processFeedback() } func processFeedback() { // process the current feedback if more than half is negative if self.currentNegativeFeedback >= self.currentPositiveFeedback { // substract feedbacks to calculate effective feedback, then calculate ratio with number of students let effectiveFeedback = self.currentNegativeFeedback - self.currentPositiveFeedback let feedbackRatio = self.getFeedbackRatio(effectiveFeedback: effectiveFeedback) // update view to new feedback let label = String(Int(feedbackRatio*100)) + "% of students think the pace is too high" self.updateFeedbackView(ratio: feedbackRatio, label: label) // process the current feedback if more than half is positive } else { // substract feedbacks to calculate effective feedback, then calculate ratio with number of students let effectiveFeedback = self.currentPositiveFeedback - self.currentNegativeFeedback let feedbackRatio = self.getFeedbackRatio(effectiveFeedback: effectiveFeedback) // update view to new feedback let label = String(Int(feedbackRatio*100)) + "% of students think the pace is too low" self.updateFeedbackView(ratio: feedbackRatio, label: label) } } func getFeedbackRatio(effectiveFeedback: Int) -> Float { // check if a valid student count is there if sio.currentStudentCount != nil && sio.currentStudentCount != 0 { // calculate ratio let temp = Float(effectiveFeedback) / Float(sio.currentStudentCount!) return temp // else return 0 } else { return Float(0) } } func updateFeedbackView(ratio: Float, label: String) { // treshold is 0.3 if ratio > 0.3 { // alert lecturer self.menuBar.backgroundColor = self.alertColor self.feedbackLabel.text = label } else { // go back to neutral self.menuBar.backgroundColor = self.neutralColor self.feedbackLabel.text = "" } } deinit { NotificationCenter.default.removeObserver(self) } }
unlicense
d4f888cfd0135f74bf5369db2e43e5dc
34.909548
187
0.622306
5.100642
false
false
false
false
mhaslett/getthegist
CocoaPods-master/examples/Alamofire Example/Example/AppDelegate.swift
1
2457
// AppDelegate.swift // // Copyright (c) 2014 Alamofire (http://alamofire.org) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? // MARK: - UIApplicationDelegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers.last as! UINavigationController navigationController.topViewController?.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self return true } // MARK: - UISplitViewControllerDelegate func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { return topAsDetailController.request == nil } } return false } }
gpl-3.0
65d45982f1ea881550c1fd4ba420535c
46.25
224
0.765975
5.90625
false
false
false
false
mauriciopf/iOS-six-week-technical-challenge
challenge_dev_Mauricio/challenge_dev_Mauricio/ViewController.swift
1
4841
// // ViewController.swift // challenge_dev_Mauricio // // Created by mauriciopf on 8/12/15. // Copyright (c) 2015 mauriciopf. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var mtableView: UITableView! var mtextField = UITextField() var randomArray = [NSManagedObject]() override func viewDidLoad() { super.viewDidLoad() self.title = "Students" view.backgroundColor = UIColor.whiteColor() mtableView = UITableView(frame: self.view.frame) mtableView.delegate = self mtableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell") mtableView.dataSource = self view.addSubview(mtableView) let addButton = UIBarButtonItem(title: "New", style: UIBarButtonItemStyle.Plain, target: self, action: "new") self.navigationItem.leftBarButtonItem = addButton let randomButton = UIBarButtonItem(title: "Randomize", style: UIBarButtonItemStyle.Plain, target: self, action: "random") self.navigationItem.rightBarButtonItem = randomButton // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { DataController.sharedInstance.loadStudents(self) } override func viewDidAppear(animated: Bool) { DataController.sharedInstance.loadStudents(self) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return DataController.sharedInstance.newStudents.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = DataController.sharedInstance.newStudents[indexPath.row].valueForKey("name") as? String return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { DataController.sharedInstance.eraseStudents(DataController.sharedInstance.newStudents[indexPath.row]) DataController.sharedInstance.newStudents.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } } func new() { var alert = UIAlertController(title: "New Student", message: "Add a new Student", preferredStyle: UIAlertControllerStyle.Alert) alert.addTextFieldWithConfigurationHandler { (textfield: UITextField!) -> Void in textfield.placeholder = "write" } var addAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in let textField = alert.textFields![0] as! UITextField DataController.sharedInstance.newStudent(textField.text) println("Text field: \(textField.text)") DataController.sharedInstance.loadStudents(self) } alert.addAction(addAction) self.presentViewController(alert, animated: true, completion: nil) } func random() { var number = DataController.sharedInstance.newStudents.count var randomNumber = Int(arc4random_uniform(UInt32(number))) DataController.sharedInstance.newStudents = shuffle(DataController.sharedInstance.newStudents) println(DataController.sharedInstance.newStudents[0]) let vc = RandomVC() vc.mArray = DataController.sharedInstance.newStudents self.navigationController?.pushViewController(vc, animated: true) } func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C { let c = count(list) // println(list) if c < 2 { return list } for i in 0..<(c - 1) { let j = Int(arc4random_uniform(UInt32(c - i))) + i swap(&list[i], &list[j]) // println("second\(list)") } return list } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
841cc05357c7ec9d21620b14431ee704
27.988024
148
0.627556
5.609502
false
false
false
false
cactuslab/Succulent
Succulent/Classes/Router.swift
1
14352
// // Router.swift // Succulent // // Created by Karl von Randow on 15/01/17. // Copyright © 2017 Cactuslab. All rights reserved. // import Foundation public typealias RoutingResultBLock = (RoutingResult) -> () /// The result of routing public enum RoutingResult { case response(_: Response) case error(_: Error) case noRoute } public class Router { private var routes = [Route]() public init() { } public func add(_ path: String) -> Route { let route = Route(path) routes.append(route) return route } public func handle(request: Request, resultBlock: @escaping RoutingResultBLock) { var bestScore = -1 var bestRoute: Route? for route in routes { if let score = route.match(request: request) { if score >= bestScore { bestScore = score bestRoute = route } } } if let route = bestRoute { route.handle(request: request, resultBlock: resultBlock) } else { resultBlock(.noRoute) } } public func handleSync(request: Request) -> RoutingResult { var result: RoutingResult? let semaphore = DispatchSemaphore(value: 0) handle(request: request) { theResult in result = theResult semaphore.signal() } semaphore.wait() return result! } } /// The status code of a response public enum ResponseStatus: Equatable, CustomStringConvertible { public static func ==(lhs: ResponseStatus, rhs: ResponseStatus) -> Bool { return lhs.code == rhs.code } case notFound case ok case notModified case internalServerError case other(code: Int) public var code: Int { switch self { case .notFound: return 404 case .ok: return 200 case .notModified: return 304 case .internalServerError: return 500 case .other(let code): return code } } public var message: String { return HTTPURLResponse.localizedString(forStatusCode: code) } public var description: String { return "\(self.code) \(self.message)" } } /// The mime-type part of a content type public enum ContentType { case TextJSON case TextPlain case TextHTML case Other(type: String) func type() -> String { switch self { case .TextJSON: return "text/json" case .TextPlain: return "text/plain" case .TextHTML: return "text/html" case .Other(let aType): return aType } } static func forExtension(ext: String) -> ContentType? { switch ext.lowercased() { case "json": return .TextJSON case "txt": return .TextPlain case "html", "htm": return .TextHTML default: return nil } } static func forContentType(contentType: String) -> ContentType? { let components = contentType.components(separatedBy: ";") guard components.count > 0 else { return nil } let mimeType = components[0].trimmingCharacters(in: .whitespacesAndNewlines) switch mimeType.lowercased() { case "text/json": return .TextJSON case "text/plain": return .TextPlain case "text/html": return .TextHTML default: return .Other(type: mimeType) } } } public class Route { public typealias ThenBlock = () -> () private let path: String private var params = [String: String]() private var allowOtherParams = false private var headers = [String: String]() private var responder: Responder? private var thenBlock: ThenBlock? public init(_ path: String) { self.path = path } @discardableResult public func param(_ name: String, _ value: String) -> Route { params[name] = value return self } @discardableResult public func anyParams() -> Route { allowOtherParams = true return self } @discardableResult public func header(_ name: String, _ value: String) -> Route { headers[name] = value return self } @discardableResult public func respond(_ responder: Responder) -> Route { return self } @discardableResult public func status(_ status: ResponseStatus) -> Route { responder = StatusResponder(status: status) return self } @discardableResult public func resource(_ url: URL) -> Route { return self } @discardableResult public func resource(_ resource: String) throws -> Route { return self } @discardableResult public func resource(bundle: Bundle, resource: String) throws -> Route { return self } @discardableResult public func content(_ string: String, _ type: ContentType) -> Route { responder = ContentResponder(string: string, contentType: type, encoding: .utf8) return self } @discardableResult public func content(_ data: Data, _ type: ContentType) -> Route { responder = ContentResponder(data: data, contentType: type) return self } @discardableResult public func block(_ block: @escaping BlockResponder.BlockResponderBlock) -> Route { responder = BlockResponder(block: block) return self } @discardableResult public func json(_ value: Any) throws -> Route { let data = try JSONSerialization.data(withJSONObject: value) return content(data, .TextJSON) } @discardableResult public func then(_ block: @escaping ThenBlock) -> Route { self.thenBlock = block return self } fileprivate func match(request: Request) -> Int? { guard match(path: request.path) else { return nil } guard let paramsScore = match(queryString: request.queryString) else { return nil } return paramsScore } private func match(path: String) -> Bool { guard let r = path.range(of: self.path, options: [.regularExpression, .anchored]) else { return false } /* Check anchoring at the end of the string, so our regex is a full match */ if r.upperBound != path.endIndex { return false } return true } private func match(queryString: String?) -> Int? { var score = 0 if let params = Route.parse(queryString: queryString) { var remainingToMatch = self.params for (key, value) in params { if let requiredMatch = self.params[key] { if let r = value.range(of: requiredMatch, options: [.regularExpression, .anchored]) { /* Check anchoring at the end of the string, so our regex is a full match */ if r.upperBound != value.endIndex { return nil } score += 1 remainingToMatch.removeValue(forKey: key) } else { return nil } } else if !allowOtherParams { return nil } } guard remainingToMatch.count == 0 else { return nil } } else if self.params.count != 0 { return nil } return score } public static func parse(queryString: String?) -> [(String, String)]? { guard let queryString = queryString else { return nil } var result = [(String, String)]() for pair in queryString.components(separatedBy: "&") { let pairTuple = pair.components(separatedBy: "=") if pairTuple.count == 2 { result.append((pairTuple[0], pairTuple[1])) } else { result.append((pairTuple[0], "")) } } return result } fileprivate func handle(request: Request, resultBlock: @escaping RoutingResultBLock) { if let responder = responder { responder.respond(request: request) { (result) in resultBlock(result) if let thenBlock = self.thenBlock { thenBlock() } } } else { resultBlock(.response(Response(status: .notFound))) if let thenBlock = thenBlock { thenBlock() } } } } /// Request methods public enum RequestMethod: String { case GET case HEAD case POST case PUT case DELETE } public let DefaultHTTPVersion = "HTTP/1.1" /// Model for an HTTP request public struct Request { public var version: String public var method: String public var path: String public var queryString: String? public var headers: [(String, String)]? public var body: Data? public var contentType: ContentType? { if let contentType = header("Content-Type") { return ContentType.forContentType(contentType: contentType) } else { return nil } } public var file: String { if let queryString = queryString { return "\(path)?\(queryString)" } else { return path } } public init(method: String = RequestMethod.GET.rawValue, version: String = DefaultHTTPVersion, path: String) { self.method = method self.path = path self.version = version } public init(method: String = RequestMethod.GET.rawValue, version: String = DefaultHTTPVersion, path: String, queryString: String?) { self.method = method self.path = path self.version = version self.queryString = queryString } public init(method: String = RequestMethod.GET.rawValue, version: String = DefaultHTTPVersion, path: String, queryString: String?, headers: [(String, String)]?) { self.method = method self.path = path self.version = version self.queryString = queryString self.headers = headers } public func header(_ needle: String) -> String? { guard let headers = headers else { return nil } for (key, value) in headers { if key.lowercased().replacingOccurrences(of: "-", with: "_") == needle.lowercased().replacingOccurrences(of: "-", with: "_") { return value } } return nil } } /// Model for an HTTP response public struct Response { public var status: ResponseStatus public var headers: [(String, String)]? public var data: Data? public var contentType: ContentType? public init(status: ResponseStatus) { self.status = status } public init(status: ResponseStatus, data: Data?, contentType: ContentType?) { self.status = status self.data = data self.contentType = contentType } public func containsHeader(_ needle: String) -> Bool { guard let headers = headers else { return false } for (key, _) in headers { if key.lowercased() == needle.lowercased() { return true } } return false } } public enum ResponderError: Error { case ResourceNotFound(bundle: Bundle, resource: String) } /// Protocol for objects that produce responses to requests public protocol Responder { func respond(request: Request, resultBlock: @escaping RoutingResultBLock) } /// Responder that produces a response with a given bundle resource public class ResourceResponder: Responder { private let url: URL public init(url: URL) { self.url = url } public init(bundle: Bundle, resource: String) throws { if let url = bundle.url(forResource: resource, withExtension: nil) { self.url = url } else { throw ResponderError.ResourceNotFound(bundle: bundle, resource: resource) } } public func respond(request: Request, resultBlock: @escaping RoutingResultBLock) { do { let data = try Data.init(contentsOf: url) resultBlock(.response(Response(status: .ok, data: data, contentType: .TextPlain))) //TODO contentType } catch { resultBlock(.error(error)) } } } /// Responder that produces a response with the given content public class ContentResponder: Responder { private let data: Data private let contentType: ContentType public init(string: String, contentType: ContentType, encoding: String.Encoding) { self.data = string.data(using: encoding)! self.contentType = contentType } public init(data: Data, contentType: ContentType) { self.data = data self.contentType = contentType } public func respond(request: Request, resultBlock: @escaping RoutingResultBLock) { resultBlock(.response(Response(status: .ok, data: data, contentType: contentType))) } } /// Responder that takes a block that itself produces a response given a request public class BlockResponder: Responder { public typealias BlockResponderBlock = (Request, @escaping RoutingResultBLock) -> () private let block: BlockResponderBlock public init(block: @escaping BlockResponderBlock) { self.block = block } public func respond(request: Request, resultBlock: @escaping RoutingResultBLock) { block(request, resultBlock) } } /// Responder that simply responds with the given response status public class StatusResponder: Responder { private let status: ResponseStatus public init(status: ResponseStatus) { self.status = status } public func respond(request: Request, resultBlock: @escaping RoutingResultBLock) { resultBlock(.response(Response(status: status))) } }
mit
c0b21ea0e6eddb5ccdac470503a353cd
26.179924
166
0.581771
4.892942
false
false
false
false
germc/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/Summit WatchKit Extension/Controllers/InterfaceController.swift
2
1782
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet weak var listLabel: WKInterfaceLabel! @IBOutlet weak var storeLabel: WKInterfaceLabel! @IBOutlet weak var salesLabel: WKInterfaceLabel! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() println("WatchKit App is open") var font = UIFont.systemFontOfSize(12) var attirbuteData = [NSFontAttributeName : font] var labelText = NSAttributedString(string: "View Lists", attributes: attirbuteData) self.listLabel.setAttributedText(labelText) labelText = NSAttributedString(string: "Locate Store", attributes: attirbuteData) self.storeLabel.setAttributedText(labelText) labelText = NSAttributedString(string: "Current Sales", attributes: attirbuteData) self.salesLabel.setAttributedText(labelText) } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func viewLists() { self.pushControllerWithName("ListOverviewInterface", context: nil) } @IBAction func requestData() { var request = ProductDataRequest(productId: "0000000002") ParentAppDataManager.sharedInstance.execute(request, retry: true, result: { (resultDictionary) -> () in println("REsults: \(resultDictionary)") }) } }
epl-1.0
13e967863428595d0d4b1a0885e61539
31.381818
111
0.687816
5.117816
false
false
false
false
cotkjaer/Silverback
Silverback/UIFont.swift
1
2156
// // UIFont.swift // Silverback // // Created by Christian Otkjær on 30/10/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import UIKit //MARK: - UIFont extension String { public func fontToFitSize( sizeToFit: CGSize, font: UIFont, lineBreakMode: NSLineBreakMode, minSize: CGFloat = 1, maxSize: CGFloat = 512) -> UIFont { let fontSize = font.pointSize guard minSize < maxSize - 1 else { return font.fontWithSize(minSize) } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = lineBreakMode let attributes = [ NSParagraphStyleAttributeName:paragraphStyle, NSFontAttributeName:font] let aText = NSAttributedString(string: self, attributes: attributes) let expectedSize = aText.boundingRectWithSize(sizeToFit, options: [ NSStringDrawingOptions.UsesLineFragmentOrigin ], context: nil).size debugPrint("sizeToFit: \(sizeToFit), expectedSize: \(expectedSize)") if expectedSize.width > sizeToFit.width || expectedSize.height > sizeToFit.height { if fontSize == minSize { return font } else if fontSize < minSize { return font.fontWithSize(minSize) } let newFontSize = floor((fontSize + minSize) / 2) return fontToFitSize(sizeToFit, font: font.fontWithSize(newFontSize), lineBreakMode: lineBreakMode, minSize: minSize, maxSize: fontSize) } else if sizeToFit.fits(expectedSize) { if fontSize >= maxSize { return font.fontWithSize(maxSize) } let newFontSize = ceil((fontSize + maxSize) / 2) return fontToFitSize(sizeToFit, font: font.fontWithSize(newFontSize), lineBreakMode: lineBreakMode, minSize: fontSize, maxSize: maxSize) } else { return font } } }
mit
0975f0a31ef421ddb9d9c755d926972a
28.493151
149
0.574547
5.710875
false
false
false
false
chisj/WSTabBarController
WSTabBarController/WSTabBarController-Sample/AppDelegate.swift
1
4148
// // AppDelegate.swift // WSTabBarController-Sample // // Created by chisj on 16/4/27. // Copyright © 2016年 WS. All rights reserved. // import UIKit import WSTabBarController @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var maintabbarController : WSTabBarController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window!.backgroundColor = UIColor.white window!.makeKeyAndVisible() maintabbarController = WSTabBarController(publishButtonConfig: {b in b.setImage(UIImage(named: "post_normal"), for: .normal) b.setImage(UIImage(named: "post_normal"), for: .highlighted) b.frame = CGRect(x:0, y:0, width:64, height:77) b.setTitle("publish", for: .normal) b.contentVerticalAlignment = .top b.titleEdgeInsets = UIEdgeInsets(top: 60, left: -64, bottom: 0 , right: 0) b.titleLabel?.font = UIFont.systemFont(ofSize: 11) b.setTitleColor(UIColor.black, for: .normal) b.setTitleColor(UIColor.black, for: .highlighted) }, publishButtonClick: { p in let alert = UIAlertView(title: nil, message: "Publish", delegate: nil, cancelButtonTitle: "OK") alert.show() }) maintabbarController?.tabBar.isTranslucent = false; maintabbarController?.tabBar.tintColor = UIColor.orange maintabbarController?.viewControllers = [controller(title: "tab1", icon: "tabbar_main"), controller(title: "tab2", icon: "tabbar_main"), controller(title: "tab3", icon: "tabbar_mine"), controller(title: "tab4", icon: "tabbar_mine") ] window!.rootViewController = maintabbarController return true } func controller(title: String, icon: String) -> UINavigationController { let c = UIViewController() c.title = title let controller = UINavigationController(rootViewController:c) controller.tabBarItem.title = title controller.tabBarItem.image = UIImage(named: icon) return controller } 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:. } }
mit
670b315a6cb2fb84026d50ba402fc7c7
48.939759
285
0.667793
5.266836
false
false
false
false
krzysztofzablocki/LifetimeTracker
Sources/iOS/UI/BarDashboard/BarDashboardViewController.swift
1
8050
// // BarDashboardViewController.swift // LifetimeTracker // // Created by Krzysztof Zablocki on 9/25/17. // import UIKit struct BarDashboardViewModel { let leaksCount: Int let summary: NSAttributedString let sections: [GroupModel] init(leaksCount: Int = 0, summary: NSAttributedString = NSAttributedString(), sections: [GroupModel] = []) { self.leaksCount = leaksCount self.summary = summary self.sections = sections } } final class BarDashboardViewController: UIViewController, LifetimeTrackerViewable { enum State { case open case closed var opposite: State { switch self { case .open: return .closed case .closed: return .open } } } enum Edge: Int { case top case bottom } class func makeFromNib() -> UIViewController & LifetimeTrackerViewable { let storyboard = UIStoryboard(name: Constants.Storyboard.barDashboard.name, bundle: .resolvedBundle) return storyboard.instantiateViewController(withIdentifier: String(describing: self)) as! BarDashboardViewController } private var state: State = .closed { didSet { clampDragOffset() } } private var hideOption: HideOption = .none { didSet { if hideOption != .none { view.isHidden = true } } } fileprivate var dashboardViewModel = BarDashboardViewModel() @IBOutlet private var tableViewController: DashboardTableViewController? @IBOutlet private var summaryLabel: UILabel? @IBOutlet private weak var barView: UIView! @IBOutlet private weak var headerView: UIView? public var edge: Edge = .bottom private let closedHeight: CGFloat = Constants.Layout.Dashboard.headerHeight private var originalOffset: CGFloat = 0 private var dragOffset: CGFloat = 0 { didSet { relayout() } } private var offsetForCloseJumpBack: CGFloat = 0 private var currentScreenSize: CGSize = CGSize.zero private var fullScreen: Bool = false override func viewDidLoad() { super.viewDidLoad() view.translatesAutoresizingMaskIntoConstraints = false addTapGestureRecognizer() addPanGestureRecognizer() dragOffset = maximumYPosition } override var prefersStatusBarHidden: Bool { return false } func update(with vm: BarDashboardViewModel) { summaryLabel?.attributedText = vm.summary if hideOption.shouldUIBeShown(oldModel: dashboardViewModel, newModel: vm) { view.isHidden = false hideOption = .none } dashboardViewModel = vm tableViewController?.update(dashboardViewModel: vm) // Update the drag offset as the height might increase. The offset has to be decreased in this case if (dragOffset + heightToShow) > maximumHeight { dragOffset = maximumHeight - heightToShow offsetForCloseJumpBack = maximumHeight - closedHeight } relayout() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if currentScreenSize != UIScreen.main.bounds.size { dragOffset = maximumYPosition offsetForCloseJumpBack = maximumHeight - closedHeight } currentScreenSize = UIScreen.main.bounds.size relayout() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Constants.Segue.embedDashboardTableView.identifier { tableViewController = segue.destination as? DashboardTableViewController tableViewController?.update(dashboardViewModel: dashboardViewModel) } } // MARK: - Layout private var heightToShow: CGFloat { var height = CGFloat(0) switch state { case .closed: height = closedHeight case .open: height = heightToFitTableView } return min(maximumHeight, height) } private var minimumYPosition: CGFloat { if #available(iOS 11, *) { return view.safeAreaInsets.top } else { return 0.0 } } private var maximumHeight: CGFloat { if #available(iOS 11, *) { return UIScreen.main.bounds.height - view.safeAreaInsets.top - view.safeAreaInsets.bottom } else { return UIScreen.main.bounds.height } } private var maximumYPosition: CGFloat { if #available(iOS 11, *) { return maximumHeight - heightToShow - view.safeAreaInsets.bottom + view.safeAreaInsets.top } else { return maximumHeight - heightToShow } } private var heightToFitTableView: CGFloat { let size = tableViewController?.contentSize ?? CGSize.zero return max(Constants.Layout.Dashboard.minTotalHeight, size.height + closedHeight) } private var layoutWidth: CGFloat { return UIScreen.main.bounds.width } private func relayout() { guard let window = view.window else { return } // Prevent black areas during device orientation window.clipsToBounds = true window.translatesAutoresizingMaskIntoConstraints = true window.frame = CGRect(x: 0, y: fullScreen ? 0 : dragOffset, width: UIScreen.main.bounds.width, height: fullScreen ? UIScreen.main.bounds.height : heightToShow) view.layoutIfNeeded() } // MARK: - Expand / collapse func addTapGestureRecognizer() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerTapped)) headerView?.addGestureRecognizer(tapGestureRecognizer) } @objc func headerTapped() { if state == .closed { offsetForCloseJumpBack = dragOffset } state = state.opposite if state == .closed && offsetForCloseJumpBack == maximumYPosition { dragOffset = offsetForCloseJumpBack } UIView.animateKeyframes(withDuration: Constants.Layout.animationDuration, delay: 0, options: [.beginFromCurrentState, .calculationModeCubicPaced] , animations: { self.relayout() }, completion: nil) } // MARK: - Settings @IBAction private func settingsButtonTapped(_ sender: UIButton) { guard let originalWindowFrame = view.window?.frame.origin else { return } let originalBarFrame = barView.frame barView.translatesAutoresizingMaskIntoConstraints = true barView.frame = CGRect(x: originalWindowFrame.x, y: originalWindowFrame.y, width: originalBarFrame.width, height: originalBarFrame.height) fullScreen = true relayout() SettingsManager.showSettingsActionSheet(on: self, completionHandler: { [weak self] (selectedOption: HideOption) in self?.hideOption = selectedOption self?.barView.translatesAutoresizingMaskIntoConstraints = false self?.fullScreen = false self?.relayout() }) } // MARK: Panning func addPanGestureRecognizer() { let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(toolbarPanned)) view.addGestureRecognizer(panGestureRecognizer) } @objc func toolbarPanned(_ gestureRecognizer: UIPanGestureRecognizer) { switch gestureRecognizer.state { case .began: originalOffset = dragOffset case .changed: let translation = gestureRecognizer.translation(in: self.view) dragOffset = originalOffset + translation.y clampDragOffset() if state == .open { offsetForCloseJumpBack = dragOffset } default: break } } func clampDragOffset() { if dragOffset < minimumYPosition { dragOffset = minimumYPosition } else if dragOffset > maximumYPosition { dragOffset = maximumYPosition } } }
mit
62cdf4312ac16b9d567d86dfbf3bbc03
30.818182
169
0.647205
5.264879
false
false
false
false
TheNounProject/CollectionView
CollectionView/CollectionViewController.swift
1
3225
// // CollectionViewController.swift // Lingo // // Created by Wesley Byrne on 8/3/16. // Copyright © 2016 The Noun Project. All rights reserved. // import Foundation import AppKit /// The UICollectionViewController class represents a view controller whose content consists of a collection view. open class CollectionViewController: NSViewController, CollectionViewDataSource, CollectionViewDelegate { public let collectionView = CollectionView() open override func loadView() { if self.nibName != nil { super.loadView() } else { self.view = NSView(frame: NSRect(origin: CGPoint.zero, size: CGSize(width: 100, height: 100))) } } override open func viewDidLoad() { super.viewDidLoad() let layout = CollectionViewListLayout() layout.itemHeight = 40 layout.sectionInsets = NSEdgeInsetsZero collectionView.collectionViewLayout = layout self.view.addSubview(collectionView) collectionView.addConstraintsToMatchParent() collectionView.dataSource = self collectionView.delegate = self } // MARK: - Data Source /*-------------------------------------------------------------------------------*/ open func numberOfSections(in collectionView: CollectionView) -> Int { return 0 } open func collectionView(_ collectionView: CollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } open func collectionView(_ collectionView: CollectionView, cellForItemAt indexPath: IndexPath) -> CollectionViewCell { assertionFailure("CollectionViewController must implement collectionView:cellForItemAt:") return CollectionViewCell() } // MARK: - Layout /*-------------------------------------------------------------------------------*/ /// Adjust the layout constraints for the collection view /// /// - Parameter insets: The insets to apply to the collection view open func adjustContentInsets(_ insets: NSEdgeInsets) { self.adjustConstraint(.top, value: insets.top) self.adjustConstraint(.left, value: insets.left) self.adjustConstraint(.right, value: insets.right) self.adjustConstraint(.bottom, value: insets.bottom) } /// Adjust the constraints for the collection view /// /// - Parameter attribute: The layout attribute to adjust. Must be .Top, .Right, .Bottom, or .Left /// - Parameter value: The constant to apply to the constraint open func adjustConstraint(_ attribute: NSLayoutConstraint.Attribute, value: CGFloat?) { for constraint in self.view.constraints { if (constraint.secondAttribute == attribute && (constraint.secondItem as? CollectionView) == collectionView) || (constraint.firstAttribute == attribute && (constraint.firstItem as? CollectionView) == collectionView) { if let val = value { constraint.constant = val constraint.isActive = true } else { constraint.isActive = false } return } } } }
mit
1cdcb5d3170bdca23ed9e6aba58edd7b
37.843373
124
0.616005
5.726465
false
false
false
false
duming91/Hear-You
Hear You/Views/Cell/MyMusicListCell.swift
1
936
// // MyMusicListCell.swift // Hear You // // Created by 董亚珣 on 16/6/7. // Copyright © 2016年 snow. All rights reserved. // import UIKit class MyMusicListCell: UITableViewCell { @IBOutlet weak var albumImage: UIImageView! @IBOutlet weak var albumName: UILabel! @IBOutlet weak var albumDesc: UILabel! @IBOutlet weak var backView: UIView! override func awakeFromNib() { super.awakeFromNib() backView.layer.cornerRadius = 5 backView.layer.shadowColor = UIColor.darkGrayColor().CGColor; backView.layer.shadowOffset = CGSizeMake(0, 0) backView.layer.shadowRadius = 4.0 backView.layer.shadowOpacity = 0.5 backView.layer.masksToBounds = false } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-3.0
b805ae794ee34d322609c92c75775ff9
24.75
69
0.664509
4.372642
false
false
false
false
longsirhero/DinDinShop
DinDinShopDemo/DinDinShopDemo/海外/ViewControllers/WCOverseasCountryDetailVC.swift
1
5198
// // WCOverseasCountryDetailVC.swift // DinDinShopDemo // // Created by longsirHERO on 2017/9/6. // Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved. // import UIKit import SwiftyJSON class WCOverseasCountryDetailVC: WCBaseController { var goodsId:String? let storeAddtionCellID:String = "storeAddtionCellID" let strolls:NSMutableArray = NSMutableArray() var sort:String = "1" var currentPage = 1 lazy var collectionView:UICollectionView = { [unowned self] in let flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init() flowLayout.minimumLineSpacing = 0.0 flowLayout.minimumInteritemSpacing = 0.0 let collectionView:UICollectionView = UICollectionView.init(frame: .init(x: 0, y: 64, width: kScreenW, height: kScreenH - 64), collectionViewLayout: flowLayout) collectionView.backgroundColor = UIColor.white collectionView.delegate = self collectionView.dataSource = self return collectionView }() override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false collectionView.register(WCProductDetailAddtionCell.self.self, forCellWithReuseIdentifier: storeAddtionCellID) self.view.addSubview(collectionView) collectionView.wc_addHeaderRefresh { self.strolls.removeAllObjects() self.loadDatas() self.collectionView.wc_endHeaderRefresh() } collectionView.wc_addFooterAutoRefresh { self.currentPage += 1 self.loadDatas() self.collectionView.wc_endFooterRefresh() } collectionView.wc_beginHeaderRefresh() } func loadDatas() -> Void { self.view.showBusyHUD() let para = ["ycdId":goodsId,"currentPage":"\(currentPage)","sort":sort,"operationType":"4","pageSize":"10"] WCRequest.shareInstance.requestDatas(methodType: .POST, urlString: home_category_second_Url, parameters: para as [String : AnyObject]) { (result, error) in if (error != nil) { self.view.showWarning(words: "网络错误,请稍后连接") return } let json:JSON = JSON.init(data: result as! Data) let value = json["result"] if value == "0" { let array:NSArray = json["content"].rawValue as! NSArray for dict in array { let model = WCSeasDiscountModel.initModelWithDictionary(dic: dict as! [String : Any]) self.strolls.add(model) } self.collectionView.reloadData() self.view.hideBusyHUD() } else { self.view.showWarning(words: "网络连接超时,稍后重试!") } } } } extension WCOverseasCountryDetailVC:UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) let model:WCSeasDiscountModel = strolls[indexPath.row] as! WCSeasDiscountModel let vc:WCProductVC = WCProductVC() vc.goodsId = model.goodsId self.navigationController?.pushViewController(vc, animated: true) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell:WCProductDetailAddtionCell = collectionView.dequeueReusableCell(withReuseIdentifier: storeAddtionCellID, for: indexPath) as! WCProductDetailAddtionCell if strolls.count != 0 { cell.model = strolls[indexPath.row] as! WCSeasDiscountModel } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return strolls.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize.init(width: kScreenW, height: 110) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0) } }
mit
dae8afbdf7fc81163a9fc4b124053892
34.8125
175
0.636998
5.38309
false
false
false
false
modocache/swift
test/ClangModules/nullability.swift
4
2617
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -I %S/Inputs/custom-modules %s -import-underlying-module -verify // REQUIRES: objc_interop import CoreCooling func testSomeClass(_ sc: SomeClass, osc: SomeClass?) { let ao1: Any = sc.methodA(osc) _ = ao1 if sc.methodA(osc) == nil { } // expected-warning {{comparing non-optional value of type 'Any' to nil always returns false}} let ao2: Any = sc.methodB(nil) _ = ao2 if sc.methodA(osc) == nil { }// expected-warning {{comparing non-optional value of type 'Any' to nil always returns false}} let ao3: Any? = sc.property.flatMap { .some($0) } _ = ao3 let ao3_ok: Any? = sc.property // okay _ = ao3_ok let ao4: Any = sc.methodD() _ = ao4 if sc.methodD() == nil { } // expected-warning {{comparing non-optional value of type 'Any' to nil always returns false}} sc.methodE(sc) sc.methodE(osc) // expected-error{{value of optional type 'SomeClass?' not unwrapped; did you mean to use '!' or '?'?}} {{17-17=!}} sc.methodF(sc, second: sc) sc.methodF(osc, second: sc) // expected-error{{value of optional type 'SomeClass?' not unwrapped; did you mean to use '!' or '?'?}} {{17-17=!}} sc.methodF(sc, second: osc) // expected-error{{value of optional type 'SomeClass?' not unwrapped; did you mean to use '!' or '?'?}} {{29-29=!}} sc.methodG(sc, second: sc) sc.methodG(osc, second: sc) // expected-error{{value of optional type 'SomeClass?' not unwrapped; did you mean to use '!' or '?'?}} {{17-17=!}} sc.methodG(sc, second: osc) let ci: CInt = 1 let sc2 = SomeClass(int: ci) let sc2a: SomeClass = sc2 _ = sc2a if sc2 == nil { } // expected-warning {{comparing non-optional value of type 'SomeClass' to nil always returns false}} let sc3 = SomeClass(double: 1.5) if sc3 == nil { } // okay let sc3a: SomeClass = sc3 // expected-error{{value of optional type 'SomeClass?' not unwrapped}} {{28-28=!}} _ = sc3a let sc4 = sc.returnMe() let sc4a: SomeClass = sc4 _ = sc4a if sc4 == nil { } // expected-warning {{comparing non-optional value of type 'SomeClass' to nil always returns false}} } // Nullability with CF types. func testCF(_ fridge: CCRefrigerator) { CCRefrigeratorOpenDoSomething(fridge) // okay CCRefrigeratorOpenDoSomething(nil) // expected-error{{nil is not compatible with expected argument type 'CCRefrigerator'}} CCRefrigeratorOpenMaybeDoSomething(fridge) // okay CCRefrigeratorOpenMaybeDoSomething(nil) // okay CCRefrigeratorOpenMaybeDoSomething(5) // expected-error{{cannot convert value of type 'Int' to expected argument type 'CCRefrigerator?'}} }
apache-2.0
e52310328a67e43e1f749e06020c8505
41.209677
145
0.679022
3.470822
false
false
false
false
adi2004/super-memo2-pod
Example/Tests/Tests.swift
1
1169
// https://github.com/Quick/Quick import Quick import Nimble import sm class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
0be59747f180884c17b42ab3bc7c116f
22.26
63
0.359415
5.460094
false
false
false
false
BigxMac/firefox-ios
Client/Frontend/Browser/BrowserToolbar.swift
1
10460
/* 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 Foundation import UIKit import SnapKit @objc protocol BrowserToolbarProtocol { weak var browserToolbarDelegate: BrowserToolbarDelegate? { get set } var shareButton: UIButton { get } var bookmarkButton: UIButton { get } var forwardButton: UIButton { get } var backButton: UIButton { get } var stopReloadButton: UIButton { get } func updateBackStatus(canGoBack: Bool) func updateForwardStatus(canGoForward: Bool) func updateBookmarkStatus(isBookmarked: Bool) func updateReloadStatus(isLoading: Bool) func updatePageStatus(#isWebPage: Bool) } @objc protocol BrowserToolbarDelegate: class { func browserToolbarDidPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidLongPressBack(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidLongPressForward(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressReload(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressStop(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidLongPressBookmark(browserToolbar: BrowserToolbarProtocol, button: UIButton) func browserToolbarDidPressShare(browserToolbar: BrowserToolbarProtocol, button: UIButton) } @objc public class BrowserToolbarHelper: NSObject { let toolbar: BrowserToolbarProtocol let ImageReload = UIImage(named: "reload") let ImageReloadPressed = UIImage(named: "reloadPressed") let ImageStop = UIImage(named: "stop") let ImageStopPressed = UIImage(named: "stopPressed") var loading: Bool = false { didSet { if loading { toolbar.stopReloadButton.setImage(ImageStop, forState: .Normal) toolbar.stopReloadButton.setImage(ImageStopPressed, forState: .Highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Stop", comment: "Accessibility Label for the browser toolbar Stop button") toolbar.stopReloadButton.accessibilityHint = NSLocalizedString("Tap to stop loading the page", comment: "") } else { toolbar.stopReloadButton.setImage(ImageReload, forState: .Normal) toolbar.stopReloadButton.setImage(ImageReloadPressed, forState: .Highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the browser toolbar Reload button") toolbar.stopReloadButton.accessibilityHint = NSLocalizedString("Tap to reload the page", comment: "") } } } init(toolbar: BrowserToolbarProtocol) { self.toolbar = toolbar super.init() toolbar.backButton.setImage(UIImage(named: "back"), forState: .Normal) toolbar.backButton.setImage(UIImage(named: "backPressed"), forState: .Highlighted) toolbar.backButton.accessibilityLabel = NSLocalizedString("Back", comment: "Accessibility Label for the browser toolbar Back button") //toolbar.backButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "") var longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBack:") toolbar.backButton.addGestureRecognizer(longPressGestureBackButton) toolbar.backButton.addTarget(self, action: "SELdidClickBack", forControlEvents: UIControlEvents.TouchUpInside) toolbar.forwardButton.setImage(UIImage(named: "forward"), forState: .Normal) toolbar.forwardButton.setImage(UIImage(named: "forwardPressed"), forState: .Highlighted) toolbar.forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "Accessibility Label for the browser toolbar Forward button") //toolbar.forwardButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "") var longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressForward:") toolbar.forwardButton.addGestureRecognizer(longPressGestureForwardButton) toolbar.forwardButton.addTarget(self, action: "SELdidClickForward", forControlEvents: UIControlEvents.TouchUpInside) toolbar.stopReloadButton.setImage(UIImage(named: "reload"), forState: .Normal) toolbar.stopReloadButton.setImage(UIImage(named: "reloadPressed"), forState: .Highlighted) toolbar.stopReloadButton.accessibilityLabel = NSLocalizedString("Reload", comment: "Accessibility Label for the browser toolbar Reload button") toolbar.stopReloadButton.accessibilityHint = NSLocalizedString("Tap to reload the page", comment: "Accessibility hint for the browser toolbar Reload button") toolbar.stopReloadButton.addTarget(self, action: "SELdidClickStopReload", forControlEvents: UIControlEvents.TouchUpInside) toolbar.shareButton.setImage(UIImage(named: "send"), forState: .Normal) toolbar.shareButton.setImage(UIImage(named: "sendPressed"), forState: .Highlighted) toolbar.shareButton.accessibilityLabel = NSLocalizedString("Share", comment: "Accessibility Label for the browser toolbar Share button") toolbar.shareButton.addTarget(self, action: "SELdidClickShare", forControlEvents: UIControlEvents.TouchUpInside) toolbar.bookmarkButton.contentMode = UIViewContentMode.Center toolbar.bookmarkButton.setImage(UIImage(named: "bookmark"), forState: .Normal) toolbar.bookmarkButton.setImage(UIImage(named: "bookmarked"), forState: UIControlState.Selected) toolbar.bookmarkButton.accessibilityLabel = NSLocalizedString("Bookmark", comment: "Accessibility Label for the browser toolbar Bookmark button") var longPressGestureBookmarkButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBookmark:") toolbar.bookmarkButton.addGestureRecognizer(longPressGestureBookmarkButton) toolbar.bookmarkButton.addTarget(self, action: "SELdidClickBookmark", forControlEvents: UIControlEvents.TouchUpInside) } func SELdidClickBack() { toolbar.browserToolbarDelegate?.browserToolbarDidPressBack(toolbar, button: toolbar.backButton) } func SELdidLongPressBack(recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { toolbar.browserToolbarDelegate?.browserToolbarDidLongPressBack(toolbar, button: toolbar.backButton) } } func SELdidClickShare() { toolbar.browserToolbarDelegate?.browserToolbarDidPressShare(toolbar, button: toolbar.shareButton) } func SELdidClickForward() { toolbar.browserToolbarDelegate?.browserToolbarDidPressForward(toolbar, button: toolbar.forwardButton) } func SELdidLongPressForward(recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { toolbar.browserToolbarDelegate?.browserToolbarDidLongPressForward(toolbar, button: toolbar.forwardButton) } } func SELdidClickBookmark() { toolbar.browserToolbarDelegate?.browserToolbarDidPressBookmark(toolbar, button: toolbar.bookmarkButton) } func SELdidLongPressBookmark(recognizer: UILongPressGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Began { toolbar.browserToolbarDelegate?.browserToolbarDidLongPressBookmark(toolbar, button: toolbar.bookmarkButton) } } func SELdidClickStopReload() { if loading { toolbar.browserToolbarDelegate?.browserToolbarDidPressStop(toolbar, button: toolbar.stopReloadButton) } else { toolbar.browserToolbarDelegate?.browserToolbarDidPressReload(toolbar, button: toolbar.stopReloadButton) } } func updateReloadStatus(isLoading: Bool) { loading = isLoading } } class BrowserToolbar: Toolbar, BrowserToolbarProtocol { weak var browserToolbarDelegate: BrowserToolbarDelegate? let shareButton: UIButton let bookmarkButton: UIButton let forwardButton: UIButton let backButton: UIButton let stopReloadButton: UIButton var helper: BrowserToolbarHelper? // This has to be here since init() calls it private override init(frame: CGRect) { // And these have to be initialized in here or the compiler will get angry backButton = UIButton() forwardButton = UIButton() stopReloadButton = UIButton() shareButton = UIButton() bookmarkButton = UIButton() super.init(frame: frame) self.helper = BrowserToolbarHelper(toolbar: self) addButtons(backButton, forwardButton, stopReloadButton, shareButton, bookmarkButton) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateBackStatus(canGoBack: Bool) { backButton.enabled = canGoBack } func updateForwardStatus(canGoForward: Bool) { forwardButton.enabled = canGoForward } func updateBookmarkStatus(isBookmarked: Bool) { bookmarkButton.selected = isBookmarked } func updateReloadStatus(isLoading: Bool) { helper?.updateReloadStatus(isLoading) } func updatePageStatus(#isWebPage: Bool) { bookmarkButton.enabled = isWebPage stopReloadButton.enabled = isWebPage shareButton.enabled = isWebPage } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() drawLine(context, start: CGPoint(x: 0, y: 0), end: CGPoint(x: frame.width, y: 0)) } private func drawLine(context: CGContextRef, start: CGPoint, end: CGPoint) { CGContextSetStrokeColorWithColor(context, UIColor.blackColor().colorWithAlphaComponent(0.05).CGColor) CGContextSetLineWidth(context, 2) CGContextMoveToPoint(context, start.x, start.y) CGContextAddLineToPoint(context, end.x, end.y) CGContextStrokePath(context) } }
mpl-2.0
8db031be9a7061e03dbd437d8b9fed01
47.202765
165
0.7413
5.740944
false
false
false
false
heshamsalman/OctoViewer
OctoViewer/Networking.swift
1
2229
// // Networking.swift // OctoViewer // // Created by Hesham Salman on 5/24/17. // Copyright © 2017 Hesham Salman // // 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 Moya import ReachabilitySwift import RxSwift class OnlineProvider<Target>: RxMoyaProvider<Target> where Target: TargetType { fileprivate let online: Observable<Bool> init(endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping, requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping, stubClosure: @escaping StubClosure = MoyaProvider.neverStub, manager: Manager = RxMoyaProvider<Target>.defaultAlamofireManager(), plugins: [PluginType] = [], trackInflights: Bool = false, online: Observable<Bool> = connectedToInternetOrStubbing()) { self.online = online super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins, trackInflights: trackInflights) } override func request(_ token: Target) -> Observable<Moya.Response> { let actualRequest = super.request(token) return online .ignore(value: false) // Wait until we're online .take(1) // Take 1 to make sure we only invoke the API once. .flatMap { _ in // Turn the online state into a network request return actualRequest } } } protocol NetworkingType { associatedtype Target: TargetType var provider: OnlineProvider<Target> { get } } struct Networking: NetworkingType { typealias Target = GitHubService let provider: OnlineProvider<GitHubService> }
apache-2.0
61cf0712833dcef0ec979872ddf5c990
32.757576
88
0.709156
4.641667
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/ObjectMapper/Sources/DateFormatterTransform.swift
20
1849
// // DateFormatterTransform.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-03-09. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class DateFormatterTransform: TransformType { public typealias Object = Date public typealias JSON = String public let dateFormatter: DateFormatter public init(dateFormatter: DateFormatter) { self.dateFormatter = dateFormatter } open func transformFromJSON(_ value: Any?) -> Date? { if let dateString = value as? String { return dateFormatter.date(from: dateString) } return nil } open func transformToJSON(_ value: Date?) -> String? { if let date = value { return dateFormatter.string(from: date) } return nil } }
mit
f9b8b2be273722be17fc25e1c72758fc
33.240741
81
0.738778
4.192744
false
false
false
false
zjzsliyang/Potions
Lift/Lift/ViewController.swift
1
18924
// // ViewController.swift // Lift // // Created by Yang Li on 24/04/2017. // Copyright © 2017 Yang Li. All rights reserved. // import UIKit import PSOLib import Buckets class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIPopoverPresentationControllerDelegate { let floorCount = 20 let liftCount = 5 let distanceX: CGFloat = 170 let distanceY: CGFloat = 60 let liftVelocity: Double = 0.3 let liftDelay: Double = 0.5 var upDownButton = [[UIButton]]() var liftDisplay = [UILabel]() var lift = [UIView]() var liftCurrentPosition: [CGFloat] = Array(repeating: 1290.0, count: 5) var liftCurrentButton: [[Bool]] = Array(repeating: Array(repeating: false, count: 20), count: 5) var liftCurrentDirection: [Int] = Array(repeating: 0, count: 5) // 0 represents static, 1 represents Up Direction, -1 represents Down Direction var liftBeingSet: [Bool] = Array(repeating: false, count: 5) var liftDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var liftRandomDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var liftRequestQueue = Queue<Int>() var liftInAnimation: [Int] = Array(repeating: 0, count: 5) // var sAWT: [Double] = Array(repeating: 0, count: 5) // var sART: [Double] = Array(repeating: 0, count: 5) // var sRPC: [Double] = Array(repeating: 0, count: 5) @IBAction func modeChosen(_ sender: UISwitch) { weak var weakSelf = self var fucktimer = Timer() if sender.isOn { fucktimer = Timer(timeInterval: 1, repeats: true) { (fucktimer) in let randomFloor = Int(arc4random() % UInt32((weakSelf?.floorCount)!)) let randomDirection = Int(arc4random() % 2) if (!(weakSelf?.upDownButton[randomFloor][randomDirection].isSelected)!) && (weakSelf?.upDownButton[randomFloor][randomDirection].isEnabled)! { weakSelf?.buttonTapped(sender: self.upDownButton[randomFloor][randomDirection]) } } RunLoop.current.add(fucktimer, forMode: .defaultRunLoopMode) fucktimer.fire() } else { if (fucktimer.isValid) { fucktimer.invalidate() } } } override func viewDidLoad() { super.viewDidLoad() initFloorSign() initUpDownButton() initLiftDisplay() initLift() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let deviceModelName = UIDevice.current.modelName if deviceModelName != "iPad Pro 12.9" { let alertController = UIAlertController(title: "CAUTION", message: "This app can only run on the\n 12.9-inch iPad Pro", preferredStyle: .alert) let alertActionOk = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(alertActionOk) present(alertController, animated: true, completion: nil) } let timer = Timer(timeInterval: 0.1, repeats: true) { (timer) in for i in 0..<self.liftCount { self.updateLiftDisplay(currentFloor: self.getLiftCurrentFloor(liftIndex: i), liftIndex: i) self.updateCurrentDirection(liftIndex: i) } } RunLoop.current.add(timer, forMode: .commonModes) timer.fire() } func initLift() { var liftX: CGFloat = 250 for liftIndex in 0..<liftCount { let liftUnit = UIView(frame: CGRect(x: liftX, y: 1290, width: 33.6, height: 45.7)) let liftUnitButton = UIButton(frame: CGRect(x: 0, y: 0, width: liftUnit.frame.width, height: liftUnit.frame.height)) liftUnit.addSubview(liftUnitButton) liftUnitButton.setImage(UIImage(named: "lift"), for: .normal) liftUnitButton.tag = liftIndex liftUnitButton.addTarget(self, action: #selector(popoverChosenView(sender:)), for: .touchUpInside) self.view.addSubview(liftUnit) lift.append(liftUnit) liftX = liftX + distanceX } } func popoverChosenView(sender: UIButton) { let layout = UICollectionViewFlowLayout() let chosenView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 300, height: 240), collectionViewLayout: layout) chosenView.delegate = self chosenView.dataSource = self chosenView.tag = sender.tag liftBeingSet[sender.tag] = true chosenView.register(LiftButtonViewCell.self, forCellWithReuseIdentifier: "cell") chosenView.backgroundColor = UIColor.lightGray let popoverViewController = UIViewController() popoverViewController.modalPresentationStyle = .popover popoverViewController.popoverPresentationController?.sourceView = sender popoverViewController.popoverPresentationController?.sourceRect = sender.bounds popoverViewController.preferredContentSize = chosenView.bounds.size popoverViewController.popoverPresentationController?.delegate = self popoverViewController.view.addSubview(chosenView) self.present(popoverViewController, animated: true, completion: nil) } func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { for i in 0..<liftCount { if liftBeingSet[i] { print("current lift: " + String(i)) inLiftScan(liftIndex: i) liftBeingSet[i] = false } } } func inLiftScan(liftIndex: Int) { for i in 0..<floorCount { if liftCurrentButton[liftIndex][i] { liftDestinationDeque[liftIndex].enqueueFirst(i) liftCurrentButton[liftIndex][i] = false } } _ = liftDestinationDeque[liftIndex].sorted() liftAnimation(liftIndex: liftIndex) } func randomGenerateDestination(destinationTag: Int) -> Int { if destinationTag < 0 { return Int(arc4random() % UInt32(abs(destinationTag + 1))) + 1 } else { return floorCount - Int(arc4random() % UInt32(floorCount - destinationTag)) } } func updateCurrentDirection(liftIndex: Int) { if lift[liftIndex].layer.presentation()?.position == nil { liftCurrentDirection[liftIndex] = 0 return } let currentPresentationY = lift[liftIndex].layer.presentation()?.frame.minY if currentPresentationY! < liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = 1 } if currentPresentationY! > liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = -1 } if currentPresentationY! == liftCurrentPosition[liftIndex] { liftCurrentDirection[liftIndex] = 0 } liftCurrentPosition[liftIndex] = currentPresentationY! return } func naiveDispatch() { if liftRequestQueue.isEmpty { return } let currentRequest = liftRequestQueue.dequeue() print("current Request: " + String(currentRequest)) if currentRequest < 0 { var closestLiftDistance = 20 var closestLift = -1 for i in 0..<liftCount { if liftCurrentDirection[i] <= 0 { if closestLiftDistance > abs(getLiftCurrentFloor(liftIndex: i) + currentRequest) { closestLift = i closestLiftDistance = abs(getLiftCurrentFloor(liftIndex: i) + currentRequest) } } } if closestLift != -1 { liftDestinationDeque[closestLift].enqueueFirst(-currentRequest - 1) _ = liftDestinationDeque[closestLift].sorted() liftRandomDestinationDeque[closestLift].enqueueFirst((randomGenerateDestination(destinationTag: currentRequest) - 1)) return } else { liftRequestQueue.enqueue(currentRequest) } } else { var closestLiftDistance = 20 var closestLift = -1 for j in 0..<liftCount { if liftCurrentDirection[j] >= 0 { if closestLiftDistance > abs(getLiftCurrentFloor(liftIndex: j) - currentRequest) { closestLift = j closestLiftDistance = abs(getLiftCurrentFloor(liftIndex: j) - currentRequest) } } } if closestLift != -1 { liftDestinationDeque[closestLift].enqueueFirst(currentRequest - 1) _ = liftDestinationDeque[closestLift].sorted() liftRandomDestinationDeque[closestLift].enqueueFirst((randomGenerateDestination(destinationTag: currentRequest) - 1)) return } else { liftRequestQueue.enqueue(currentRequest) } } } /* func SPODispatch() { let spaceMin: [Int] = Array(repeating: 0, count: liftRequestQueue.count) let spaceMax: [Int] = Array(repeating: 5, count: liftRequestQueue.count) let searchSpace = PSOSearchSpace(boundsMin: spaceMin, max: spaceMax) let optimizer = PSOStandardOptimizer2011(for: searchSpace, optimum: 0, fitness: { (positions: UnsafeMutablePointer<Double>?, dimensions: Int32) -> Double in // AWT: Average Waiting Time var liftTempDestinationDeque = Array(repeating: Deque<Int>(), count: 5) var fMax: [Int] = Array(repeating: 0, count: self.liftCount) var fMin: [Int] = Array(repeating: 0, count: self.liftCount) for i in 0..<self.liftRequestQueue.count { switch Int((positions?[i])!) { case 0: liftTempDestinationDeque[0].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[0].first!) case 1: liftTempDestinationDeque[1].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[1].first!) case 2: liftTempDestinationDeque[2].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[2].first!) case 3: liftTempDestinationDeque[3].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[3].first!) default: liftTempDestinationDeque[4].enqueueFirst(self.liftRequestQueue.dequeue()) self.liftRequestQueue.enqueue(liftTempDestinationDeque[4].first!) } } // ART: Average Riding Time // EC: Energy Consumption // Total var sFitnessFunc: Double = 0 return sFitnessFunc }, before: nil, iteration: nil) { (optimizer: PSOStandardOptimizer2011?) in // to do } optimizer?.operation.start() } */ func liftAnimation(liftIndex: Int) { if liftDestinationDeque[liftIndex].isEmpty { return } liftInAnimation[liftIndex] = liftInAnimation[liftIndex] + 1 var destinationFloor: Int = 0 if liftCurrentDirection[liftIndex] == 0 { let currentFloor = getLiftCurrentFloor(liftIndex: liftIndex) if abs(currentFloor - (liftDestinationDeque[liftIndex].first! + 1)) < abs(currentFloor - (liftDestinationDeque[liftIndex].last! + 1)) { destinationFloor = liftDestinationDeque[liftIndex].dequeueFirst() + 1 } else { destinationFloor = liftDestinationDeque[liftIndex].dequeueLast() + 1 } } else { if liftCurrentDirection[liftIndex] > 0 { destinationFloor = liftDestinationDeque[liftIndex].dequeueLast() + 1 } else { destinationFloor = liftDestinationDeque[liftIndex].dequeueFirst() + 1 } } print("destination floor: " + String(destinationFloor)) let destinationDistance = CGFloat(destinationFloor - getLiftCurrentFloor(liftIndex: liftIndex)) * (distanceY) let destinationTime = liftVelocity * abs(Double(destinationFloor - getLiftCurrentFloor(liftIndex: liftIndex))) UIView.animate(withDuration: destinationTime, delay: liftDelay, options: .curveEaseInOut, animations: { self.lift[liftIndex].center.y = self.lift[liftIndex].center.y - destinationDistance }, completion: { (finished) in self.updateLiftDisplay(currentFloor: self.getLiftCurrentFloor(liftIndex: liftIndex), liftIndex: liftIndex) self.updateUpDownButton(destinationTag: (self.liftCurrentDirection[liftIndex] * destinationFloor), liftIndex: liftIndex) if !self.liftDestinationDeque[liftIndex].isEmpty { self.liftAnimation(liftIndex: liftIndex) } self.liftInAnimation[liftIndex] = self.liftInAnimation[liftIndex] - 1 }) } func updateUpDownButton(destinationTag: Int, liftIndex: Int) { print("destinationTag: " + String(destinationTag)) if destinationTag == 0 { if !liftRandomDestinationDeque[liftIndex].isEmpty { liftDestinationDeque[liftIndex].enqueueFirst(liftRandomDestinationDeque[liftIndex].dequeueFirst()) upDownButton[getLiftCurrentFloor(liftIndex: liftIndex) - 1][0].isSelected = false upDownButton[getLiftCurrentFloor(liftIndex: liftIndex) - 1][1].isSelected = false } return } if destinationTag > 0 { if upDownButton[destinationTag - 1][0].isSelected { upDownButton[destinationTag - 1][0].isSelected = false } } else { if upDownButton[-destinationTag - 1][1].isSelected { upDownButton[-destinationTag - 1][1].isSelected = false } } if !liftRandomDestinationDeque[liftIndex].isEmpty { liftDestinationDeque[liftIndex].enqueueFirst(liftRandomDestinationDeque[liftIndex].dequeueFirst()) upDownButton[abs(destinationTag) - 1][0].isSelected = false upDownButton[abs(destinationTag) - 1][1].isSelected = false } } func getLiftCurrentFloor(liftIndex: Int) -> Int { if lift[liftIndex].layer.presentation()?.position != nil { return (Int(floor((1290 - (lift[liftIndex].layer.presentation()!.frame.minY)) / distanceY)) + 1) } else { print("returning model layer position") return (Int(floor((1290 - (lift[liftIndex].layer.model().frame.minY)) / distanceY)) + 1) } } func updateLiftDisplay(currentFloor: Int, liftIndex: Int) { liftDisplay[liftIndex].text = String(currentFloor) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! LiftButtonViewCell cell.liftButton?.setTitle(convertNumber(number: indexPath.row + 1), for: .normal) cell.liftButton?.setTitleColor(UIColor.blue, for: .selected) cell.liftButton?.tag = collectionView.tag cell.liftButton?.addTarget(self, action: #selector(liftButtonTapped(sender:)), for: .touchUpInside) return cell } func liftButtonTapped(sender: UIButton) { sender.isSelected = !sender.isSelected let currentLift = sender.tag let currentFloorButton = convertLetter(letter: sender.currentTitle!) liftCurrentButton[currentLift][currentFloorButton - 1] = !liftCurrentButton[currentLift][currentFloorButton - 1] } func convertLetter(letter: String) -> Int { let asciiLetter = Character(letter).asciiValue if asciiLetter < 65 { return asciiLetter - 48 } else { return asciiLetter - 55 } } func convertNumber(number: Int) -> String { if number < 10 { return String(number) } else { return String(describing: UnicodeScalar(number - 10 + 65)!) } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return floorCount } func initFloorSign() { var floorY: CGFloat = 1300 for floorNum in 0..<floorCount { let floorNumView = UIImageView(image: UIImage(named: String(floorNum + 1))) floorNumView.frame = CGRect(x: 36, y: floorY, width: 30, height: 30) floorNumView.contentMode = .scaleAspectFill self.view.addSubview(floorNumView) floorY = floorY - distanceY } } func initLiftDisplay() { var liftDisplayX: CGFloat = 220 for _ in 0..<liftCount { let liftDisplayUnit = UILabel(frame: CGRect(x: liftDisplayX, y: 100, width: 50, height: 50)) liftDisplayUnit.text = String(1) liftDisplayUnit.font = UIFont(name: "Digital-7", size: 50) liftDisplayUnit.textAlignment = .right self.view.addSubview(liftDisplayUnit) liftDisplay.append(liftDisplayUnit) liftDisplayX = liftDisplayX + distanceX } } func initUpDownButton() { var upDownButtonY: CGFloat = 1305 for i in 0..<floorCount { var upDownButtonUnit = [UIButton]() let upDownButtonUp = UIButton(frame: CGRect(x: 90, y: upDownButtonY, width: 25, height: 25)) upDownButtonUp.setImage(UIImage(named: "up"), for: .normal) upDownButtonUp.setImage(UIImage(named: "up-active"), for: .selected) upDownButtonUp.tag = i + 1 upDownButtonUp.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside) let upDownButtonDown = UIButton(frame: CGRect(x: 130, y: upDownButtonY, width: 25, height: 25)) upDownButtonDown.setImage(UIImage(named: "down"), for: .normal) upDownButtonDown.setImage(UIImage(named: "down-active"), for: .selected) upDownButtonDown.tag = -(i + 1) upDownButtonDown.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside) upDownButtonUnit.append(upDownButtonUp) upDownButtonUnit.append(upDownButtonDown) self.view.addSubview(upDownButtonUp) self.view.addSubview(upDownButtonDown) upDownButton.append(upDownButtonUnit) upDownButtonY = upDownButtonY - distanceY } upDownButton[0][1].isEnabled = false upDownButton[19][0].isEnabled = false } func buttonTapped(sender: UIButton) { sender.isSelected = !sender.isSelected if sender.isSelected { liftRequestQueue.enqueue(sender.tag) naiveDispatch() for i in 0..<liftCount { if liftInAnimation[i] == 0 { liftAnimation(liftIndex: i) } } } } } class LiftButtonViewCell: UICollectionViewCell { var liftButton: UIButton? override init(frame: CGRect) { super.init(frame: frame) initView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initView() { liftButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) liftButton?.titleLabel?.font = UIFont(name: "Elevator Buttons", size: 50) self.addSubview(liftButton!) } } extension Character { var asciiValue: Int { get { let unicodeString = String(self).unicodeScalars return Int(unicodeString[unicodeString.startIndex].value) } } } public extension UIDevice { var modelName: String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } switch identifier { case "iPad6,7", "iPad6,8": return "iPad Pro 12.9" case "i386", "x86_64": return "Simulator" default: return identifier } } }
mit
0a257b6644a40bb54a669687174c5cfb
38.505219
171
0.685568
4.108337
false
false
false
false
cabarique/TheProposalGame
MyProposalGame/Entities/ProjectileEntity.swift
1
3076
// // ProjectileEntity.swift // MyProposalGame // // Created by Luis Cabarique on 9/18/16. // Copyright © 2016 Luis Cabarique. All rights reserved. // import SpriteKit import GameplayKit class ProjectileEntity: SGEntity { var spriteComponent: SpriteComponent! var animationComponent: AnimationComponent! var physicsComponent: PhysicsComponent! var gameScene:GamePlayMode! private var projectileOrientation: CGFloat = 1.0 init(position: CGPoint, size: CGSize, orientation: CGFloat, texture: SKTexture, scene:GamePlayMode) { super.init() gameScene = scene projectileOrientation = orientation //Initialize components spriteComponent = SpriteComponent(entity: self, texture: texture, size: size, position:position) spriteComponent.node.xScale = projectileOrientation spriteComponent.node.anchorPoint.y = 0 addComponent(spriteComponent) physicsComponent = PhysicsComponent(entity: self, bodySize: CGSize(width: spriteComponent.node.size.width * 0.8, height: spriteComponent.node.size.height * 0.8), bodyShape: .squareOffset, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Projectile.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Wall.rawValue | ColliderType.Destroyable.rawValue) physicsComponent.setPhysicsContacts(ColliderType.Enemy.rawValue | ColliderType.Destroyable.rawValue | ColliderType.Enemy.rawValue) addComponent(physicsComponent) //Final setup of components physicsComponent.physicsBody.affectedByGravity = false spriteComponent.node.physicsBody = physicsComponent.physicsBody spriteComponent.node.name = "projectileNode" name = "projectileEntity" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateWithDeltaTime(seconds: NSTimeInterval) { super.updateWithDeltaTime(seconds) let allContactedBodies = spriteComponent.node.physicsBody?.allContactedBodies() let projectileSpeed = CGPoint(x: 400.0 * projectileOrientation, y: 0.0) spriteComponent.node.position += (projectileSpeed * CGFloat(seconds)) if allContactedBodies?.count > 0 { for body in allContactedBodies! { if body.node is SGSpriteNode { projectileMiss() if body.node?.name == "crateNode" { body.node?.removeFromParent() } } } } if !gameScene.camera!.containsNode(spriteComponent.node) { projectileMiss() } } override func contactWith(entity:SGEntity) { if entity.name == "zombieEntity" { print("") } } func projectileMiss() { spriteComponent.node.removeFromParent() } }
mit
34c99b2a529bd69cb54e6e51f486f2ef
33.943182
212
0.646179
4.850158
false
false
false
false
uias/Tabman
Sources/Tabman/Bar/Generic/EdgeFadedView.swift
1
2087
// // EdgeFadedView.swift // Tabman // // Created by Merrick Sapsford on 03/08/2018. // Copyright © 2022 UI At Six. All rights reserved. // import UIKit internal final class EdgeFadedView: UIView { private struct Defaults { static let leadingStartLocation: CGFloat = 0.02 static let leadingEndLocation: CGFloat = 0.05 static let trailingEndLocation: CGFloat = 0.95 static let trailingStartLocation: CGFloat = 0.98 } private let gradientLayer: CAGradientLayer = { let gradientLayer = CAGradientLayer() gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor] gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) return gradientLayer }() var showFade: Bool = false { didSet { updateFadeRatios() layer.mask = showFade ? gradientLayer : nil } } var leadingFade: CGFloat = 1.0 { didSet { updateFadeRatios() } } var trailingFade: CGFloat = 1.0 { didSet { updateFadeRatios() } } // MARK: Lifecycle override func layoutSubviews() { super.layoutSubviews() superview?.layoutIfNeeded() gradientLayer.frame = self.bounds } // MARK: Updates private func updateFadeRatios() { let leadingStartLocation = NSNumber(value: Float(Defaults.leadingStartLocation * leadingFade)) let leadingEndLocation = NSNumber(value: Float(Defaults.leadingEndLocation * leadingFade)) let trailingEndLocation = NSNumber(value: Float(1.0 - ((1.0 - Defaults.trailingEndLocation) * trailingFade))) let trailingStartLocation = NSNumber(value: Float(1.0 - ((1.0 - Defaults.trailingStartLocation) * trailingFade))) gradientLayer.locations = [leadingStartLocation, leadingEndLocation, trailingEndLocation, trailingStartLocation] } }
mit
f164a6fb7e8438f02b068bb5981b9a05
30.606061
123
0.627996
4.65625
false
false
false
false
ymazdy/YazdanSwiftSocket
YazdanSwiftSocket/Sources/UDPClient.swift
1
6428
// Copyright (c) <2017>, http://yazdan.xyz // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by http://yazdan.xyz. // 4. Neither the name of the http://yazdan.xyz nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY http://yazdan.xyz ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL http://yazdan.xyz BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation @_silgen_name("yudpsocket_server") func c_yudpsocket_server(_ host:UnsafePointer<Int8>,port:Int32) -> Int32 @_silgen_name("yudpsocket_recive") func c_yudpsocket_recive(_ fd:Int32,buff:UnsafePointer<Byte>,len:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32 @_silgen_name("yudpsocket_close") func c_yudpsocket_close(_ fd:Int32) -> Int32 @_silgen_name("yudpsocket_client") func c_yudpsocket_client() -> Int32 @_silgen_name("yudpsocket_get_server_ip") func c_yudpsocket_get_server_ip(_ host:UnsafePointer<Int8>,ip:UnsafePointer<Int8>) -> Int32 @_silgen_name("yudpsocket_sentto") func c_yudpsocket_sentto(_ fd:Int32,buff:UnsafePointer<Byte>,len:Int32,ip:UnsafePointer<Int8>,port:Int32) -> Int32 @_silgen_name("enable_broadcast") func c_enable_broadcast(_ fd:Int32) open class UDPClient: Socket { public override init(address: String, port: Int32) { let remoteipbuff: [Int8] = [Int8](repeating: 0x0,count: 16) let ret = c_yudpsocket_get_server_ip(address, ip: remoteipbuff) guard let ip = String(cString: remoteipbuff, encoding: String.Encoding.utf8), ret == 0 else { super.init(address: "", port: 0) //TODO: change to init? return } super.init(address: ip, port: port) let fd: Int32 = c_yudpsocket_client() if fd > 0 { self.fd = fd } } /* * send data * return success or fail with message */ open func send(data: [Byte]) -> Result { guard let fd = self.fd else { return .failure(SocketError.connectionClosed) } let sendsize: Int32 = c_yudpsocket_sentto(fd, buff: data, len: Int32(data.count), ip: self.address, port: Int32(self.port)) if Int(sendsize) == data.count { return .success } else { return .failure(SocketError.unknownError) } } /* * send string * return success or fail with message */ open func send(string: String) -> Result { guard let fd = self.fd else { return .failure(SocketError.connectionClosed) } let sendsize = c_yudpsocket_sentto(fd, buff: string, len: Int32(strlen(string)), ip: address, port: port) if sendsize == Int32(strlen(string)) { return .success } else { return .failure(SocketError.unknownError) } } /* * enableBroadcast */ open func enableBroadcast() { guard let fd: Int32 = self.fd else { return } c_enable_broadcast(fd) } /* * * send nsdata */ open func send(data: Data) -> Result { guard let fd = self.fd else { return .failure(SocketError.connectionClosed) } var buff = [Byte](repeating: 0x0,count: data.count) (data as NSData).getBytes(&buff, length: data.count) let sendsize = c_yudpsocket_sentto(fd, buff: buff, len: Int32(data.count), ip: address, port: port) if sendsize == Int32(data.count) { return .success } else { return .failure(SocketError.unknownError) } } open func close() { guard let fd = self.fd else { return } _ = c_yudpsocket_close(fd) self.fd = nil } //TODO add multycast and boardcast } open class UDPServer: Socket { public override init(address: String, port: Int32) { super.init(address: address, port: port) let fd = c_yudpsocket_server(address, port: port) if fd > 0 { self.fd = fd } } //TODO add multycast and boardcast open func recv(_ expectlen: Int) -> ([Byte]?, String, Int) { if let fd = self.fd { var buff: [Byte] = [Byte](repeating: 0x0,count: expectlen) var remoteipbuff: [Int8] = [Int8](repeating: 0x0,count: 16) var remoteport: Int32 = 0 let readLen: Int32 = c_yudpsocket_recive(fd, buff: buff, len: Int32(expectlen), ip: &remoteipbuff, port: &remoteport) let port: Int = Int(remoteport) var address = "" if let ip = String(cString: remoteipbuff, encoding: String.Encoding.utf8) { address = ip } if readLen <= 0 { return (nil, address, port) } let rs = buff[0...Int(readLen-1)] let data: [Byte] = Array(rs) return (data, address, port) } return (nil, "no ip", 0) } open func close() { guard let fd = self.fd else { return } _ = c_yudpsocket_close(fd) self.fd = nil } }
bsd-3-clause
8ad4d4029c96bbcac787c5d313a6e93e
38.195122
164
0.625544
3.960567
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceKit/Sources/EurofurenceKit/Entities/KnowledgeEntry.swift
1
4153
import CoreData import EurofurenceWebAPI @objc(KnowledgeEntry) public class KnowledgeEntry: Entity { @nonobjc class func fetchRequest() -> NSFetchRequest<KnowledgeEntry> { return NSFetchRequest<KnowledgeEntry>(entityName: "KnowledgeEntry") } @NSManaged public var order: Int16 @NSManaged public var text: String @NSManaged public var title: String @NSManaged public var group: KnowledgeGroup @NSManaged var links: NSOrderedSet @NSManaged var images: NSOrderedSet public var orderedImages: [KnowledgeEntryImage] { images.array(of: KnowledgeEntryImage.self) } public var orderedLinks: [KnowledgeLink] { links.array(of: KnowledgeLink.self) } } // MARK: - KnowledgeEntry + Comparable extension KnowledgeEntry: Comparable { public static func < (lhs: KnowledgeEntry, rhs: KnowledgeEntry) -> Bool { // If the orders are the same, disambiguiate by name. if lhs.order == rhs.order { return lhs.title < rhs.title } else { return lhs.order < rhs.order } } } // MARK: - KnowledgeEntry + ConsumesRemoteResponse extension KnowledgeEntry: ConsumesRemoteResponse { typealias RemoteObject = EurofurenceWebAPI.KnowledgeEntry func update(context: RemoteResponseConsumingContext<RemoteObject>) throws { identifier = context.remoteObject.id lastEdited = context.remoteObject.lastChangeDateTimeUtc title = context.remoteObject.title text = context.remoteObject.text order = Int16(context.remoteObject.order) group = try context.managedObjectContext.entity(withIdentifier: context.remoteObject.knowledgeGroupIdentifier) updateImages(context) updateLinks(context) } private func updateImages(_ context: RemoteResponseConsumingContext<RemoteObject>) { for imageID in context.remoteObject.imageIdentifiers { if let remoteImage = context.image(identifiedBy: imageID) { let image = KnowledgeEntryImage.identifiedBy(identifier: imageID, in: context.managedObjectContext) image.update(from: remoteImage) addToImages(image) } } } private func updateLinks(_ context: RemoteResponseConsumingContext<RemoteObject>) { removeAllLinks(context) // Insert links alphabetically let sortedLinks = context.remoteObject.links.sorted { first, second in guard let firstName = first.name, let secondName = second.name else { return false } return firstName < secondName } for link in sortedLinks { let knowledgeLink = KnowledgeLink(context: context.managedObjectContext) knowledgeLink.fragmentType = link.fragmentType knowledgeLink.name = link.name knowledgeLink.target = link.target addToLinks(knowledgeLink) } } private func removeAllLinks(_ context: RemoteResponseConsumingContext<RemoteObject>) { for link in links.array.compactMap({ $0 as? KnowledgeLink }) { removeFromLinks(link) context.managedObjectContext.delete(link) } } } // MARK: Generated accessors for images extension KnowledgeEntry { @objc(addImagesObject:) @NSManaged func addToImages(_ value: KnowledgeEntryImage) @objc(removeImagesObject:) @NSManaged func removeFromImages(_ value: KnowledgeEntryImage) @objc(addImages:) @NSManaged func addToImages(_ values: Set<KnowledgeEntryImage>) @objc(removeImages:) @NSManaged func removeFromImages(_ values: Set<KnowledgeEntryImage>) } // MARK: Generated accessors for links extension KnowledgeEntry { @objc(addLinksObject:) @NSManaged func addToLinks(_ value: KnowledgeLink) @objc(removeLinksObject:) @NSManaged func removeFromLinks(_ value: KnowledgeLink) @objc(addLinks:) @NSManaged func addToLinks(_ values: Set<KnowledgeLink>) @objc(removeLinks:) @NSManaged func removeFromLinks(_ values: Set<KnowledgeLink>) }
mit
bc987aa6b92a45ccbc540dd012e042a8
30.462121
118
0.678305
4.94994
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/05726-swift-sourcemanager-getmessage.swift
11
2422
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing case c<T : P return ""\("[1)" class struct Q<T : e { func g func i("" { func i: a { struct S<T { struct A { struct S<d where T where g case c<d where g case c, class typealias e : Int -> (f: e { typealias e : BooleanType, A { typealias e { case c<T : a { class b class a<d where T : c, } } } struct S<T : c, typealias e : c { class func g: a { } typealias e : C { func a class a class a<T where T where T : e == { let t: c<T where T : Int -> () -> U) var d = "[1))) func g<T : C { println(" return " func f: BooleanType, A { class a { typealias e : c { protocol P { } } func i: b: c<T where T where T where T : NSObject { } var d where g } struct Q<T : Int -> ("[Void{ func g func a<d = { func a<T>: a { } struct S<d = { { func i() { struct S<d where T where T : e let i() -> () -> () -> U)" typealias e == "\(f: a { func i: NSObject { let t: e : c { class func g<d where T : BooleanType, A { let t: c<d where T { func g: a { let i(f: c<d = { class class func i() -> U)))" class class a { class a { println(f: c { struct S<d = " return ""\(" return "[Void{ class b class protocol A { protocol P { typealias e : NSObject { func f: e func i() { typealias e : e : c { let t: P } class func i() { var d = [Void{ func g protocol A { let f = " } protocol A { protocol A { protocol P { struct Q<T>: a { let i: T>: e class c<d = "[1))"[1)"\(f: e == { typealias e : e : P class c, class protocol A { func a var d = [1))))"" class func a func a } struct Q<T : a { class case c, class func g: NSObject { class return """\() { struct A { protocol A { struct S<T where g: P class c, let t: BooleanType, A : BooleanType, A { func i("[Void{ protocol P { typealias e : e : NSObject { return " let i: NSObject { class a { let t: c { func i() -> U)" let f = { class protocol A { class a return " let f = " var d = [1)"[1) func g<T where T where g<T> let i(f: c, let f = { { let t: c { class c, let i: e : c, { } typealias e : a { struct A { println(" func i(" let t: NSObject { let t: c { let t: b } return " return "\(""\() -> U))" println() { class b: b class protocol A { case c<T : c, protocol A { return " class b return "\("[Void{ class b func f: a { struct Q<T> protocol A : c, typealias e { } func g case c<T: a { { class func g<T : e : T>: NSObject { println(f:
mit
68df64319acb44a2d3f654f781dc3abd
12.91954
87
0.592073
2.530825
false
false
false
false
brave/browser-ios
brave/src/frontend/favorites/FavoritesDataSource.swift
1
4202
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Storage import CoreData import Shared private let log = Logger.browserLogger class FavoritesDataSource: NSObject, UICollectionViewDataSource { var frc: NSFetchedResultsController<Bookmark>? weak var collectionView: UICollectionView? var isEditing: Bool = false { didSet { if isEditing != oldValue { // We need to post notification here to inform all cells to show the edit button. // collectionView.reloadData() can't be used, it stops InteractiveMovementForItem, // requiring user to long press again if he wants to reorder a tile. let name = isEditing ? NotificationThumbnailEditOn : NotificationThumbnailEditOff NotificationCenter.default.post(name: name, object: nil) } } } override init() { super.init() frc = FavoritesHelper.frc() frc?.delegate = self do { try frc?.performFetch() } catch { log.error("Favorites fetch error") } } func refetch() { try? frc?.performFetch() } func favoriteBookmark(at indexPath: IndexPath) -> Bookmark? { // Favorites may be not updated at this point, fetching them again. try? frc?.performFetch() return frc?.object(at: indexPath) as? Bookmark } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return frc?.fetchedObjects?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Thumbnail", for: indexPath) as! ThumbnailCell return configureCell(cell: cell, at: indexPath) } func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { // Using the same reorder logic as in BookmarksPanel Bookmark.reorderBookmarks(frc: frc, sourceIndexPath: sourceIndexPath, destinationIndexPath: destinationIndexPath) } fileprivate func configureCell(cell: ThumbnailCell, at indexPath: IndexPath) -> UICollectionViewCell { guard let fav = frc?.object(at: indexPath) else { return UICollectionViewCell() } cell.textLabel.text = fav.displayTitle ?? fav.url cell.accessibilityLabel = cell.textLabel.text cell.toggleEditButton(isEditing) guard let urlString = fav.url, let url = URL(string: urlString) else { log.error("configureCell url is nil") return UICollectionViewCell() } let ftd = FavoritesTileDecorator(url: url, cell: cell, indexPath: indexPath) ftd.collection = collectionView ftd.decorateTile() return cell } } extension FavoritesDataSource: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .insert: if let indexPath = indexPath { collectionView?.insertItems(at: [indexPath]) } break case .delete: if let indexPath = indexPath { collectionView?.deleteItems(at: [indexPath]) } break case .update: if let indexPath = indexPath, let cell = collectionView?.cellForItem(at: indexPath) as? ThumbnailCell { _ = configureCell(cell: cell, at: indexPath) } if let newIndexPath = newIndexPath, let cell = collectionView?.cellForItem(at: newIndexPath) as? ThumbnailCell { _ = configureCell(cell: cell, at: newIndexPath) } break case .move: break } } }
mpl-2.0
9a4c8acf82be6d5121b0e664258b2f3b
37.2
200
0.646835
5.387179
false
false
false
false
Fiskie/jsrl
jsrl/Playlist.swift
1
1433
// // Playlist.swift // jsrl // import Foundation /** Playlist manages a sequential playlist that loops forever. */ class Playlist { var list: [Track] var cursor = -1 /** Create a new playlist with an array of tracks as the source. - properties: - tracks: A list of tracks. */ init(_ tracks: [Track]) { self.list = tracks } /** Get the previous track in the sequence. If the cursor is < 0, this will just return the first track in the playlist. - returns: The previous track. */ func getPrevious() -> Track { if (cursor > 0) { cursor -= 1 } else { cursor = 0 } let track = list[cursor % list.count] return track } /** Get the next track in the sequence. - returns: The next track. */ func getNext() -> Track { cursor += 1 let track = list[cursor % list.count] return track } /** Shuffles tracks in this playlist and resets the cursor. */ func shuffle() { if (list.count > 0) { for i in 0...(list.count - 1) { let tmp = list[i] let rand = Int(arc4random_uniform(UInt32(list.count))) list[i] = list[rand] list[rand] = tmp } } cursor = -1 } }
gpl-3.0
9fe57e463d362ef77b78d65e22adbcae
20.073529
71
0.488486
4.290419
false
false
false
false
LeeWongSnail/Swift
DesignBox/DesignBox/ArtKit/PhotoBrowser/ArtWorkImageViewModel.swift
1
2930
// // ArtWorkImageViewModel.swift // DesignBox // // Created by LeeWong on 2017/9/5. // Copyright © 2017年 LeeWong. All rights reserved. // import UIKit class ArtWorkImageViewModel: NSObject { var contentVCBlock:((Int) -> UIViewController)? var pageControllers: [String:AnyObject] = [String:AnyObject]() var work:ArtWork? var fileItems:[ArtFileItemProtocol] = [ArtFileItemProtocol]() } extension ArtWorkImageViewModel:ArtImageBrowserProtocol { func setContentViewController(contentVCBlock: @escaping (Int) -> UIViewController) { self.contentVCBlock = contentVCBlock } func indexOfPageController(viewController:UIViewController) -> Int { var categoryID:String? for (key,value) in self.pageControllers { if (value as! UIViewController) == viewController { categoryID = key } } var index:Int = 0 for idx in 0...self.fileItems.count-1 { let obj = self.fileItems[idx] if obj.getImageURL!() == categoryID { index = idx } } return index } func pageControllerAtIndex(index: Int) -> UIViewController? { if index == -1 || index >= self.fileItems.count { return nil } let item = self.fileItems[index] var viewController = self.pageControllers[item.getImageURL!()!] if viewController == nil { if let contentBlock = contentVCBlock { viewController = contentBlock(index) } else { viewController = UIViewController() } } self.pageControllers[item.getImageURL!()!] = viewController return viewController as? UIViewController } func fileItemAtIndex(index: Int) -> ArtFileItemProtocol? { guard index < self.fileItems.count else { return nil } return self.fileItems[index] } func indexOfFile(item: ArtFileItemProtocol) -> Int { var index = 0 for item1 in self.fileItems { if item1.getImageURL!() == item.getImageURL!() { return index } index += 1 } return index } func loadFileItemsCompletion(completion: ([ArtFileItemProtocol], Bool) -> Void) { guard (work?.work?.imgs?.count)! > 0 else { return } var imageItems:[ArtFileItemProtocol] = [ArtFileItemProtocol]() for img in (work?.work?.imgs)! { // let model = ArtImageBrowserModel() model.imageURL = img["imgurl"] as? String imageItems.append(model) } self.fileItems = imageItems completion(imageItems,true) } }
mit
6512c9d55eaa8f3ef8d04bd4b80f10f3
25.853211
88
0.552443
4.902848
false
false
false
false
enstulen/ARKitAnimation
ARAnimation/Settings.swift
1
1994
// // Settings.swift // ARChartsSampleApp // // Created by Boris Emorine on 7/26/17. // Copyright © 2017 Boris Emorine. All rights reserved. // import Foundation import ARCharts struct Settings { var animationType: ARChartPresenter.AnimationType = .grow var longPressAnimationType : ARChartHighlighter.AnimationStyle = .shrink var barOpacity: Float = 1.0 var showLabels = true var numberOfSeries = 10 var numberOfIndices = 10 var graphWidth: Float = 0.6 var graphHeight: Float = 0.6 var graphLength: Float = 0.3 var dataSet: Int = 0 public func index(forEntranceAnimationType animationType: ARChartPresenter.AnimationType?) -> Int { guard let animationType = animationType else { return 0 } switch animationType { case .fade: return 0 case .progressiveFade: return 1 case .grow: return 2 case .progressiveGrow: return 3 } } public func entranceAnimationType(forIndex index: Int) -> ARChartPresenter.AnimationType? { switch index { case 0: return .fade case 1: return .progressiveFade case 2: return .grow case 3: return .progressiveGrow default: return .fade } } public func index(forLongPressAnimationType animationType: ARChartHighlighter.AnimationStyle?) -> Int { guard let animationType = animationType else { return 0 } switch animationType { case .shrink: return 0 case .fade: return 1 } } public func longPressAnimationType(forIndex index: Int) -> ARChartHighlighter.AnimationStyle? { switch index { case 0: return .shrink case 1: return .fade default: return .shrink } } }
mit
11a37872839559bb45d38cbede2c89a5
24.227848
107
0.57702
4.957711
false
false
false
false
Purdue-iOS-Dev-Club/Fall-2015-Tutorials
ServerClient/DiningCourt/DiningCourt/MasterViewController.swift
1
3760
// // MasterViewController.swift // DiningCourt // // Created by George Lo on 10/5/15. // Copyright © 2015 Purdue iOS Dev Club. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() var restaurants = [NSDictionary]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let data = NSData(contentsOfURL: NSURL(string: "http://localhost:3000/api/diningCourts")!)! let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary self.restaurants = dict["Location"]![0] as! [NSDictionary] print(dict["Location"]![0] as! [NSDictionary]) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) }) } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restaurants.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) print(restaurants[indexPath.row]) let name = restaurants[indexPath.row]["Name"] cell.textLabel!.text = name as? String return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
mit
a0ff724bb4088104ec3598d1222b85b9
36.969697
157
0.675712
5.479592
false
false
false
false
riteshhgupta/RGListKit
RGListKit/TableViewController.swift
1
1173
// // TableViewController.swift // RGListKit // // Created by Ritesh Gupta on 16/12/16. // Copyright © 2016 Ritesh Gupta. All rights reserved. // import UIKit import ReactiveSwift import ReactiveCocoa class TableViewController: UIViewController { @IBOutlet public var tableView: UITableView! { didSet { listViewHolder = ReactiveDiffableListViewHolder(listView: tableView) } } let items = MutableProperty<[SectionModel]?>(nil) var listViewHolder: ReactiveDiffableListViewHolder! override func viewDidLoad() { super.viewDidLoad() listViewHolder.reactive.sections <~ items.producer.skipNil() loadCacheData() mockAPIData() } } extension TableViewController { func loadCacheData() { let cells = (0..<10).map { "\($0)" }.map { TableCellModel(title: $0) } let section = SectionModel(id: "one", cells: cells) items.value = [section] } func mockAPIData() { let delay = DispatchTime.now() + 2 DispatchQueue.main.asyncAfter(deadline: delay) { let cells = (0..<10).filter { $0 % 2 == 0 }.map { "\($0)" }.map { TableCellModel(title: $0) } let section = SectionModel(id: "one", cells: cells) self.items.value = [section] } } }
mit
27ba28421ea088d8fb0e91a8606c2537
23.416667
96
0.694539
3.51952
false
false
false
false
Yummypets/YPImagePicker
Source/Filters/Photo/YPFilter.swift
1
5414
// // YPFilter.swift // photoTaking // // Created by Sacha Durand Saint Omer on 21/10/16. // Copyright © 2016 octopepper. All rights reserved. // import UIKit import CoreImage public typealias FilterApplierType = ((_ image: CIImage) -> CIImage?) public struct YPFilter { var name = "" var applier: FilterApplierType? public init(name: String, coreImageFilterName: String) { self.name = name self.applier = YPFilter.coreImageFilter(name: coreImageFilterName) } public init(name: String, applier: FilterApplierType?) { self.name = name self.applier = applier } } extension YPFilter { public static func coreImageFilter(name: String) -> FilterApplierType { return { (image: CIImage) -> CIImage? in let filter = CIFilter(name: name) filter?.setValue(image, forKey: kCIInputImageKey) return filter?.outputImage! } } public static func clarendonFilter(foregroundImage: CIImage) -> CIImage? { let backgroundImage = getColorImage(red: 127, green: 187, blue: 227, alpha: Int(255 * 0.2), rect: foregroundImage.extent) return foregroundImage.applyingFilter("CIOverlayBlendMode", parameters: [ "inputBackgroundImage": backgroundImage ]) .applyingFilter("CIColorControls", parameters: [ "inputSaturation": 1.35, "inputBrightness": 0.05, "inputContrast": 1.1 ]) } public static func nashvilleFilter(foregroundImage: CIImage) -> CIImage? { let backgroundImage = getColorImage(red: 247, green: 176, blue: 153, alpha: Int(255 * 0.56), rect: foregroundImage.extent) let backgroundImage2 = getColorImage(red: 0, green: 70, blue: 150, alpha: Int(255 * 0.4), rect: foregroundImage.extent) return foregroundImage .applyingFilter("CIDarkenBlendMode", parameters: [ "inputBackgroundImage": backgroundImage ]) .applyingFilter("CISepiaTone", parameters: [ "inputIntensity": 0.2 ]) .applyingFilter("CIColorControls", parameters: [ "inputSaturation": 1.2, "inputBrightness": 0.05, "inputContrast": 1.1 ]) .applyingFilter("CILightenBlendMode", parameters: [ "inputBackgroundImage": backgroundImage2 ]) } public static func apply1977Filter(ciImage: CIImage) -> CIImage? { let filterImage = getColorImage(red: 243, green: 106, blue: 188, alpha: Int(255 * 0.1), rect: ciImage.extent) let backgroundImage = ciImage .applyingFilter("CIColorControls", parameters: [ "inputSaturation": 1.3, "inputBrightness": 0.1, "inputContrast": 1.05 ]) .applyingFilter("CIHueAdjust", parameters: [ "inputAngle": 0.3 ]) return filterImage .applyingFilter("CIScreenBlendMode", parameters: [ "inputBackgroundImage": backgroundImage ]) .applyingFilter("CIToneCurve", parameters: [ "inputPoint0": CIVector(x: 0, y: 0), "inputPoint1": CIVector(x: 0.25, y: 0.20), "inputPoint2": CIVector(x: 0.5, y: 0.5), "inputPoint3": CIVector(x: 0.75, y: 0.80), "inputPoint4": CIVector(x: 1, y: 1) ]) } public static func toasterFilter(ciImage: CIImage) -> CIImage? { let width = ciImage.extent.width let height = ciImage.extent.height let centerWidth = width / 2.0 let centerHeight = height / 2.0 let radius0 = min(width / 4.0, height / 4.0) let radius1 = min(width / 1.5, height / 1.5) let color0 = self.getColor(red: 128, green: 78, blue: 15, alpha: 255) let color1 = self.getColor(red: 79, green: 0, blue: 79, alpha: 255) let circle = CIFilter(name: "CIRadialGradient", parameters: [ "inputCenter": CIVector(x: centerWidth, y: centerHeight), "inputRadius0": radius0, "inputRadius1": radius1, "inputColor0": color0, "inputColor1": color1 ])?.outputImage?.cropped(to: ciImage.extent) return ciImage .applyingFilter("CIColorControls", parameters: [ "inputSaturation": 1.0, "inputBrightness": 0.01, "inputContrast": 1.1 ]) .applyingFilter("CIScreenBlendMode", parameters: [ "inputBackgroundImage": circle! ]) } private static func getColor(red: Int, green: Int, blue: Int, alpha: Int = 255) -> CIColor { return CIColor(red: CGFloat(Double(red) / 255.0), green: CGFloat(Double(green) / 255.0), blue: CGFloat(Double(blue) / 255.0), alpha: CGFloat(Double(alpha) / 255.0)) } private static func getColorImage(red: Int, green: Int, blue: Int, alpha: Int = 255, rect: CGRect) -> CIImage { let color = self.getColor(red: red, green: green, blue: blue, alpha: alpha) return CIImage(color: color).cropped(to: rect) } }
mit
bc8911f6bdb8aaae6ed32a9090c1c2f6
38.510949
117
0.564936
4.393669
false
false
false
false
TTVS/NightOut
Clubber/previousCardViewContoller.swift
1
14930
//// //// CardViewController.h //// Clubber //// //// Created by Terra on 9/21/15. //// Copyright (c) 2015 Dino Media Asia. All rights reserved. //// // //#import <PaperKit/PaperKit.h> ////#import "RKCardView.h" //#import <UIKit/UIKit.h> // //@protocol RKCardViewDelegate <NSObject> //@optional //- (void)nameTap; //- (void)coverPhotoTap; //- (void)profilePhotoTap; //- (void)profileDescriptionTap; // //- (void)pokeButtonTap; // //@end // // //@interface CardViewController : PKContentViewController ////<RKCardViewDelegate> // //@property (nonatomic, weak) IBOutlet id<RKCardViewDelegate> delegate; //@property (nonatomic) PKPreviewView *previewView; // //@property (nonatomic)UIImageView *profileImageView; //@property (nonatomic)UIImageView *coverImageView; //@property (nonatomic)UILabel *titleLabel; //@property (nonatomic)UILabel *descriptionLabel; // //@property (nonatomic)UIButton *pokeButton; // //- (void)addBlur; //- (void)removeBlur; //- (void)addShadow; //- (void)removeShadow; // //@end // // // // // // //// //// CardViewController.m //// Clubber //// //// Created by Terra on 9/21/15. //// Copyright (c) 2015 Dino Media Asia. All rights reserved. //// // //#define viewWidth ([UIScreen mainScreen].bounds.size.width) //#define viewHeight ([UIScreen mainScreen].bounds.size.height) // //#import "CardViewController.h" ////#import "RKCardView.h" ////#import "FriendView.h" // // //// Responsive view ratio values //#define CORNER_RATIO 0.015 //#define CP_RATIO 0.38 //#define PP_RATIO 0.247 //#define PP_X_RATIO 0.03 //#define PP_Y_RATIO 0.213 //#define PP_BUFF 1.0 //#define LABEL_Y_RATIO .012 // //@interface CardViewController () // //@end // //@implementation CardViewController //{ // UIVisualEffectView *visualEffectView; //} // //@synthesize delegate; //@synthesize profileImageView; //@synthesize coverImageView; //@synthesize titleLabel; //@synthesize descriptionLabel; // //@synthesize pokeButton; // //- (void)addShadow //{ // self.view.layer.shadowOpacity = 0.15; // } // // - (void)removeShadow // { // self.view.layer.shadowOpacity = 0; //} // //-(void)setupView // { // // // // self.backgroundColor = [UIColor whiteColor]; // self.view.backgroundColor = [UIColor colorWithRed:23.0f/255.0f green:23.0f/255.0f blue:23.0f/255.0f alpha:1.0f]; // self.view.layer.cornerRadius = self.view.frame.size.width * CORNER_RATIO; // self.view.layer.shadowRadius = 3; // self.view.layer.shadowOpacity = 0; // self.view.layer.shadowOffset = CGSizeMake(1, 1); // [self setupPhotos]; //} // //-(void)setupPhotos // { // CGFloat height = self.view.frame.size.height; // CGFloat width = self.view.frame.size.width; // UIView *cp_mask = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width, height * CP_RATIO)]; // UIView *pp_mask = [[UIView alloc]initWithFrame:CGRectMake(width * PP_X_RATIO, height * PP_Y_RATIO, height * PP_RATIO, height *PP_RATIO)]; // UIView *pp_circle = [[UIView alloc]initWithFrame:CGRectMake(pp_mask.frame.origin.x - PP_BUFF, pp_mask.frame.origin.y - PP_BUFF, pp_mask.frame.size.width + 2* PP_BUFF, pp_mask.frame.size.height + 2*PP_BUFF)]; // pp_circle.backgroundColor = [UIColor colorWithRed:90.0/255.0 green:225.0/255.0 blue:200.0/255.0 alpha:1.0]; // // pp_circle.backgroundColor = [UIColor cyanColor]; // // pp_circle.layer.cornerRadius = pp_circle.frame.size.height/2; // pp_mask.layer.cornerRadius = pp_mask.frame.size.height/2; // pp_mask.backgroundColor = [UIColor darkGrayColor]; // cp_mask.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1]; // // CGFloat cornerRadius = self.view.layer.cornerRadius; // UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cp_mask.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(cornerRadius, cornerRadius)]; // CAShapeLayer *maskLayer = [CAShapeLayer layer]; // maskLayer.frame = cp_mask.bounds; // maskLayer.path = maskPath.CGPath; // cp_mask.layer.mask = maskLayer; // // // UIBlurEffect* blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; // visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect]; // // visualEffectView.frame = cp_mask.frame; // visualEffectView.alpha = 0; // // profileImageView = [[UIImageView alloc]init]; // profileImageView.frame = CGRectMake(0, 0, pp_mask.frame.size.width, pp_mask.frame.size.height); // // profileImageView.layer.masksToBounds = YES; // profileImageView.layer.cornerRadius = profileImageView.frame.size.width/2; // profileImageView.clipsToBounds = YES; // // coverImageView = [[UIImageView alloc]init]; // coverImageView.frame = cp_mask.frame; // [coverImageView setContentMode:UIViewContentModeScaleAspectFill]; // // [cp_mask addSubview:coverImageView]; // [pp_mask addSubview:profileImageView]; // cp_mask.clipsToBounds = YES; // pp_mask.clipsToBounds = YES; // // // Setup the label // CGFloat titleLabelX = pp_circle.frame.origin.x + pp_circle.frame.size.width + 10; // titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(titleLabelX, cp_mask.frame.size.height + 8, self.view.frame.size.width - titleLabelX, 26)]; // titleLabel.adjustsFontSizeToFitWidth = NO; // titleLabel.lineBreakMode = NSLineBreakByClipping; // // [titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:20]]; // [titleLabel setFont:[UIFont fontWithName:@"Avenir-Medium" size:20]]; // // // [titleLabel setTextColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8]]; // [titleLabel setTextColor:[UIColor colorWithRed:90.0/255.0 green:225.0/255.0 blue:200.0/255.0 alpha:1.0]]; // // [titleLabel setBackgroundColor:[UIColor colorWithRed:90 green:225 blue:200 alpha:1]]; // titleLabel.text = @"Title Label"; // // // Setup title banner // CGFloat titleBannerX = pp_circle.frame.origin.x + pp_circle.frame.size.width/2; // UIView *titleBanner = [[UIView alloc]initWithFrame:CGRectMake(titleBannerX, cp_mask.frame.size.height, self.view.frame.size.width - titleBannerX, 44)]; // // UIView *titleBanner = [[UIView alloc]initWithFrame:CGRectMake(0, cp_mask.frame.size.height, width, 44)]; // // // titleBanner.backgroundColor = [UIColor darkGrayColor]; // titleBanner.backgroundColor = [UIColor colorWithRed:56.0/255.0 green:56.0/255.0 blue:56.0/255.0 alpha:1.0]; // // // // // Setup description label // CGFloat descriptionLabelY = pp_circle.frame.origin.y + pp_circle.frame.size.height; // descriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, descriptionLabelY + 10, self.view.frame.size.width - 60, 250)]; // descriptionLabel.adjustsFontSizeToFitWidth = NO; // descriptionLabel.lineBreakMode = NSLineBreakByClipping; // descriptionLabel.contentMode = UIViewContentModeTopLeft; // descriptionLabel.numberOfLines = 12; // [descriptionLabel setFont:[UIFont fontWithName:@"Avenir-Light" size:16]]; // // [descriptionLabel setTextColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.8]]; // [descriptionLabel setTextColor:[UIColor whiteColor]]; // descriptionLabel.text = @"Description Label"; // // // Setup poke button // pokeButton = [[UIButton alloc]initWithFrame:CGRectMake(30, height - 70, self.view.frame.size.width - 60, 55)]; // pokeButton.highlighted = YES; // pokeButton.imageView.contentMode = UIViewContentModeScaleAspectFit; // [pokeButton setImage:[UIImage imageNamed:@"pokeButtonActive"] forState: UIControlStateNormal]; // [pokeButton setImage:[UIImage imageNamed:@"pokeButtonInactive"] forState: UIControlStateHighlighted]; // // // Register touch events on the label // titleLabel.userInteractionEnabled = YES; // UITapGestureRecognizer *tapGestureTitle = // [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleLabelTap)]; // [titleLabel addGestureRecognizer:tapGestureTitle]; // // // Register touch events on the cover image // coverImageView.userInteractionEnabled = YES; // UITapGestureRecognizer *tapGestureCover = // [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coverPhotoTap)]; // [coverImageView addGestureRecognizer:tapGestureCover]; // // // Register touch events on the profile image // profileImageView.userInteractionEnabled = YES; // UITapGestureRecognizer *tapGestureProfile = // [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(profilePhotoTap)]; // [profileImageView addGestureRecognizer:tapGestureProfile]; // // // Register touch events on the description label // descriptionLabel.userInteractionEnabled = YES; // UITapGestureRecognizer *tapGestureDescription = // [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(descriptionLabelTap)]; // [titleLabel addGestureRecognizer:tapGestureDescription]; // // // Register touch events on poke button // pokeButton.userInteractionEnabled = YES; // UITapGestureRecognizer *tapGesturePoke = // [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pokeButtonTap)]; // [titleLabel addGestureRecognizer:tapGesturePoke]; // // // // building upp the views // [self.view addSubview:titleBanner]; // // [titleBanner addSubview:titleLabel]; // [self.view addSubview:titleLabel]; // [self.view addSubview:descriptionLabel]; // [self.view addSubview:pokeButton]; // [self.view addSubview:cp_mask]; // [self.view addSubview:pp_circle]; // [self.view addSubview:pp_mask]; // [coverImageView addSubview:visualEffectView]; // // // //} // // //#pragma mark - Optional RKCardViewDelegate methods //-(void)titleLabelTap{ // if (self.delegate != nil && [self.delegate respondsToSelector:@selector(nameTap)]) { // [self.delegate nameTap]; // } //} // //-(void)coverPhotoTap{ // if (self.delegate != nil && [self.delegate respondsToSelector:@selector(coverPhotoTap)]) { // [self.delegate coverPhotoTap]; // } //} // //-(void)profilePhotoTap{ // if (self.delegate != nil && [self.delegate respondsToSelector:@selector(profilePhotoTap)]) { // [self.delegate profilePhotoTap]; // } //} // //-(void)descriptionLabelTap{ // if (self.delegate != nil && [self.delegate respondsToSelector:@selector(profileDescriptionTap)]) { // [self.delegate profileDescriptionTap]; // } //} // //-(void)pokeButtonTap{ // if (self.delegate != nil && [self.delegate respondsToSelector:@selector(pokeButtonTap)]) { // [self.delegate pokeButtonTap]; // } //} // // // //-(void)addBlur // { // visualEffectView.alpha = 1; //} // //-(void)removeBlur // { // visualEffectView.alpha = 0; // } // // // // // // // // - (void)viewDidLoad { // [super viewDidLoad]; // // [self setupView]; // // [self addShadow]; // // [self addBlur]; // // self.coverImageView.image = [UIImage imageNamed:@"demo"]; // self.profileImageView.image = [UIImage imageNamed:@"mainAvatar4"]; // self.titleLabel.text = @"Simone L."; // self.descriptionLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget semper orci, eu tincidunt neque. Morbi vel ultrices justo, ac lobortis felis. Pellentesque a condimentum nulla, quis placerat ipsum. Suspendisse potenti. Proin posuere dictum erat, vitae porta orci."; // // // // self.view.backgroundColor = [UIColor clearColor]; // // RKCardView* cardView= [[RKCardView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; // // // cardView.coverImageView.image = [UIImage imageNamed:@"demo"]; // // cardView.profileImageView.image = [UIImage imageNamed:@"mainAvatar4"]; // // cardView.titleLabel.text = @"Simone L."; // // For iPhone 5 // // cardView.descriptionLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget semper orci, eu tincidunt neque. Morbi vel ultrices justo, ac lobortis felis. Pellentesque a condimentum nulla, quis placerat ipsum. Suspendisse potenti. Proin posuere dictum erat, vitae porta orci."; // // // cardView.descriptionLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget semper orci, eu tincidunt neque. Morbi vel ultrices justo, ac lobortis felis. Pellentesque a condimentum nulla, quis placerat ipsum. Suspendisse potenti. Proin posuere dictum erat, vitae porta orci. Aenean vulputate accumsan mollis. Nunc rutrum sodales ante congue finibus. Nullam iaculis molestie libero quis ultrices. Donec blandit laoreet eros, vitae sollicitudin arcu gravida nec."; // // cardView.delegate = self; // // [cardView addBlur]; // // [cardView addShadow]; // // [self.view addSubview:cardView]; // // // // // // // // FriendView *friendView = [FriendView friendView]; // // [self.view addSubview:friendView]; // // // // // UIView *friendView = [[[NSBundle mainBundle] loadNibNamed:@"FriendView" owner:self options:nil] objectAtIndex:0]; // // [self.view addSubview:friendView]; // // // _previewView = [[PKPreviewView alloc] initWithImage:[UIImage imageNamed:@"pexels-photo-medium"]]; // // //default // // _previewView = [[PKPreviewView alloc] initWithImage:[UIImage imageNamed:@"profileBG"]]; // // [self.view addSubview:_previewView]; // // } // // - (void)didReceiveMemoryWarning { // [super didReceiveMemoryWarning]; // // Dispose of any resources that can be recreated. //} // // // //#pragma mark - PKContentViewController methods // //- (void)viewDidDisplayInFullScreen //{ // [super viewDidDisplayInFullScreen]; // [self.previewView startMotion]; // } // // - (void)viewDidEndDisplayingInFullScreen // { // [super viewDidEndDisplayingInFullScreen]; // [self.previewView stopMotion]; //} // // // // //@end
apache-2.0
5ef136835597956fd036df08d4a846cc
39.242588
508
0.644273
3.964418
false
false
false
false
yujinjcho/movie_recommendations
ios_ui/MovieRec/Classes/Modules/Recommend/View/RecommendViewController.swift
1
3397
// // RecommendationsTableViewController.swift // MovieRec // // Created by Yujin Cho on 5/27/17. // Copyright © 2017 Yujin Cho. All rights reserved. // import os.log import UIKit import SwiftyJSON class RecommendViewController: UITableViewController, RecommendViewInterface { var eventHandler : RecommendModuleInterface? var userId: String? var recommendations = [String]() var numberRows: Int { return recommendations.count } override func viewDidLoad() { super.viewDidLoad() configureView() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberRows } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "MovieTableViewCell" guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MovieTableViewCell else { fatalError("The dequeued cell is not an instance of MovieTableViewCell.") } let title = recommendations[indexPath.row] cell.titleLabel.text = title return cell } func refreshTable(recommendationsToShow: [String]) { recommendations = recommendationsToShow DispatchQueue.main.async { [unowned self] in self.tableView.reloadData() } endLoadingOverlay() } func didTapRefreshButton() { startLoadingOverlay() if let eventHandler = eventHandler { eventHandler.updateView() } } func didTapBackButton() { if let eventHandler = eventHandler, let navigationController = self.navigationController { eventHandler.navigateToRateView(navigationController: navigationController) } } //MARK: Private Methods private func endLoadingOverlay() { dismiss(animated: false, completion: nil) } private func startLoadingOverlay() { let alert = UIAlertController(title: nil, message: "Loading...", preferredStyle: .alert) let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50)) loadingIndicator.hidesWhenStopped = true loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray loadingIndicator.startAnimating(); alert.view.addSubview(loadingIndicator) present(alert, animated: true, completion: nil) } private func configureView() { navigationItem.title = "Recommend List" let navigateToRecommendItem = UIBarButtonItem(title: "Refresh", style: UIBarButtonItemStyle.plain, target: self, action: #selector(RecommendViewController.didTapRefreshButton)) let navigateToRateItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(RecommendViewController.didTapBackButton)) navigationItem.rightBarButtonItem = navigateToRecommendItem navigationItem.leftBarButtonItem = navigateToRateItem if let eventHandler = eventHandler { eventHandler.configureUserInterfaceForPresentation() } } }
mit
99ede318c8a6c84376524214b1204cd9
34.010309
184
0.681684
5.641196
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
source/Core/Classes/RSRedirectStepViewController.swift
1
2376
// // RSRedirectStepViewController.swift // Pods // // Created by James Kizer on 7/29/17. // // import UIKit import ResearchKit open class RSRedirectStepViewController: RSQuestionViewController { open var redirectDelegate: RSRedirectStepDelegate? open var logInSuccessful: Bool? = nil override open func viewDidLoad() { super.viewDidLoad() if let step = self.step as? RSRedirectStep { self.redirectDelegate = step.delegate } self.redirectDelegate?.redirectViewControllerDidLoad(viewController: self) } override open func continueTapped(_ sender: Any) { self.redirectDelegate?.beginRedirect(completion: { (error, errorMessage) in if error == nil { self.logInSuccessful = true DispatchQueue.main.async { self.notifyDelegateAndMoveForward() } } else { self.logInSuccessful = false let message: String = errorMessage ?? "An unknown error occurred" DispatchQueue.main.async { let alertController = UIAlertController(title: "Log in failed", message: message, preferredStyle: UIAlertController.Style.alert) // Replace UIAlertActionStyle.Default by UIAlertActionStyle.default let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { (result : UIAlertAction) -> Void in } alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } } }) } override open var result: ORKStepResult? { guard let result = super.result else { return nil } guard let logInSuccessful = self.logInSuccessful, let step = step else { return result } let boolResult = ORKBooleanQuestionResult(identifier: step.identifier) boolResult.booleanAnswer = NSNumber(booleanLiteral: logInSuccessful) result.results = [boolResult] return result } }
apache-2.0
f5ca9d4955bce7cf23c2689073878168
30.68
148
0.555556
5.866667
false
false
false
false
niekang/WeiBo
WeiBo/Class/View/Home/WBStatusCell/WBStatusCell.swift
1
2885
// // WBStatusCell.swift // WeiBo // // Created by 聂康 on 2017/6/22. // Copyright © 2017年 com.nk. All rights reserved. // import UIKit class WBStatusCell: UITableViewCell { /// 头像 @IBOutlet weak var iconView: UIImageView! /// 姓名 @IBOutlet weak var nameLab: UILabel! /// 会员图标 @IBOutlet weak var memberImageView: UIImageView! /// 时间 @IBOutlet weak var timeLab: UILabel! /// 来源 @IBOutlet weak var sourceLab: UILabel! /// vip图标 @IBOutlet weak var vipImageView: UIImageView! /// 正文 @IBOutlet weak var contentLab: NKLabel! //底部工具条 @IBOutlet weak var statusToolBar: WBStatusTooBar! @IBOutlet weak var statusPicView: WBStatusPictureView! @IBOutlet weak var retweedtedLab: NKLabel? var statusViewModel:WBStatusViewModel? { didSet{ //姓名 nameLab.text = statusViewModel?.status.user?.screen_name //会员图标 memberImageView.image = statusViewModel?.memberIcon //认证图标 vipImageView.image = statusViewModel?.vipIcon //设置头像 iconView.setImage(URLString: statusViewModel?.status.user?.profile_image_url, placeholderImageName: "avatar_default_big", isAvatar: true) //设置底部工具条数据 statusToolBar.statusViewModel = statusViewModel //设置配图 statusPicView.statusViewModel = statusViewModel //正文 contentLab.patterns = ["武汉"] contentLab.attributedText = statusViewModel?.statusAttrText //设置被转发微博文字 retweedtedLab?.attributedText = statusViewModel?.retweetedAttrText // 设置来源 sourceLab.text = statusViewModel?.status.source // 设置时间 timeLab.text = statusViewModel?.status.createdDate?.dateDescription } } override func awakeFromNib() { /// 离屏渲染 layer.drawsAsynchronously = true //栅格化 layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale // 设置微博文本代理 contentLab.delegate = self retweedtedLab?.delegate = self } } extension WBStatusCell: NKLabelDelegate { func labelDidSelectedLinkText(label: NKLabel, text: String) { // 判断是否是 URL if !text.hasPrefix("http://") { return } // 插入 ? 表示如果代理没有实现协议方法,就什么都不做 // 如果使用 !,代理没有实现协议方法,仍然强行执行,会崩溃! // delegate?.statusCellDidSelectedURLString?(cell: self, urlString: text) } }
apache-2.0
3ee8cd5d252ed359049cfdd7af01ee1d
25.530612
149
0.596154
4.642857
false
false
false
false
benlangmuir/swift
test/SourceKit/CursorInfo/cursor_overrides.swift
23
1305
import FooClangModule protocol Prot { func meth() } class Cls : S1, Prot { override func meth() {} } class SubCls : Cls { override func meth() {} } func goo(x: SubCls) { x.meth() } public protocol WithAssocType { /// Some kind of associated type associatedtype AssocType } public protocol WithInheritedAssocType : WithAssocType { associatedtype AssocType = Int } // REQUIRES: objc_interop // RUN: %sourcekitd-test -req=cursor -pos=16:7 %s -- -embed-bitcode -I %S/Inputs/cursor-overrides %s | %FileCheck -check-prefix=CHECK1 %s // CHECK1: source.lang.swift.ref.function.method.instance (12:17-12:23) // CHECK1: c:@M@cursor_overrides@objc(cs)SubCls(im)meth // CHECK1: (SubCls) -> () -> () // CHECK1: OVERRIDES BEGIN // CHECK1-NEXT: c:@M@cursor_overrides@objc(cs)Cls(im)meth // CHECK1-NEXT: s:16cursor_overrides4ProtP4methyyF // CHECK1-NEXT: c:objc(cs)S1(im)meth // CHECK1-NEXT: c:objc(cs)B1(im)meth // CHECK1-NEXT: c:objc(pl)P1(im)meth // CHECK1-NEXT: OVERRIDES END // RUN: %sourcekitd-test -req=cursor -pos=25:20 %s -- -embed-bitcode -I %S/Inputs/cursor-overrides %s | %FileCheck -check-prefix=CHECK2 %s // CHECK2: s:16cursor_overrides22WithInheritedAssocTypeP0eF0 // CHECK2: OVERRIDES BEGIN // CHECK2-NEXT: s:16cursor_overrides13WithAssocTypeP0dE0 // CHECK2-NEXT: OVERRIDES END
apache-2.0
15de605767e241100a922c5a44a013fe
28
138
0.71341
2.868132
false
false
false
false
davelyon/CheatCodes
CheatCodes/Classes/CheatCodes.swift
1
7379
import UIKit fileprivate typealias Cheat = Selector fileprivate extension Cheat { static let tint = #selector(UIKeyCommand.toggleTintAdjustmentMode) static let userDefaults = #selector(UIKeyCommand.dumpUserDefaults) static let autolayoutTrace = #selector(UIKeyCommand.autolayoutTrace) static let docsDirectory = #selector(UIKeyCommand.showDocumentsPath) static let help = #selector(UIKeyCommand.showHelp) static let traitCollection = #selector(UIKeyCommand.showCurrentTraitCollection) static let dumpDetails = #selector(UIKeyCommand.showDeviceDetails) static let enableInteraction = #selector(UIKeyCommand.enableUserInteraction) static let saveApplicationState = #selector(UIKeyCommand.forceStatePreservation) } // MARK: - Cheat Codes Public Infterface /// CheatCodes additions extension UIKeyCommand { #if CHEATS_Release /// :nodoc: @nonobjc public static let cheatCodes: [UIKeyCommand] = [] #else /// Installed CheatCodeCommands @nonobjc public static var cheatCodes: [UIKeyCommand] { return cheatCodeCommands.map { $0.toKeyCommand() } } #endif /** Add a cheat code to the list of known cheat codes. This will enable the code to be shown in the `help` output, and will make it globally available - parameter command: A new instance of `CheatCodeCommand` to register for availability throughout your app */ @nonobjc public static func addCheatCode(_ command: CheatCodeCommand) { cheatCodeCommands.append(command) } public typealias FormatterContentsBlock = ((inout FormattedKeyValuePrinter) -> Void) /** Create and use a print formatter that prints out a table of Key/Value pairs - parameter title: The title of the data set - parameter contents: A block that yields a `FormattedKeyValuePrinter` you may call `addKey(_: String, value: String)` on to add items to the formatted output */ @nonobjc public func tableFormatted(title: String, contents: FormatterContentsBlock) { var formatter = FormattedKeyValuePrinter(title: title) contents(&formatter) formatter.printContents() } } // MARK: - Cheat Codes Private Interface internal extension UIKeyCommand { #if CHEATS_Release // Don't include cheat code commands for `release` builds #else @nonobjc static var cheatCodeCommands = [ CheatCodeCommand(input: "h", action: .help, discoverabilityTitle: "Print the list of available commands"), CheatCodeCommand(input: "t", action: .tint, discoverabilityTitle: "Cycle tintAdjustmentMode"), CheatCodeCommand(input: "u", action: .userDefaults, discoverabilityTitle: "Print user defaults"), CheatCodeCommand(input: "l", action: .autolayoutTrace, discoverabilityTitle: "Print autolayout backtrace"), CheatCodeCommand(input: "d", action: .docsDirectory, discoverabilityTitle: "Print documents directory path"), CheatCodeCommand(input: "o", action: .traitCollection, discoverabilityTitle: "Print the current trait collection (for the main window)"), CheatCodeCommand(input: "i", action: .dumpDetails, discoverabilityTitle: "Print general device info"), CheatCodeCommand(input: "e", action: .enableInteraction, discoverabilityTitle: "Re-enable user interaction"), CheatCodeCommand(input: UIKeyInputDownArrow, modifierFlags: [.control, .shift, .command], action: .saveApplicationState, discoverabilityTitle: "Trigger restorable state preservation"), ] func showHelp() { tableFormatted(title: "Available Cheat Codes:") { formatter in UIKeyCommand.cheatCodeCommands.sorted(by: { (c1, c2) -> Bool in c1.input <= c2.input }).forEach { formatter.addKey(" \($0.keyCombo)", value: $0.discoverabilityTitle) } } } /// Toggles the tint adjustment mode between `automatic` and `dimmed` on the key window func toggleTintAdjustmentMode() { guard let window = UIApplication.shared.keyWindow else { return } switch window.tintAdjustmentMode { case .dimmed: print("Switching tint adjustment mode: .automatic") window.tintAdjustmentMode = .automatic case .automatic, .normal: print("Switching tint adjustment mode: .dimmed") window.tintAdjustmentMode = .dimmed } } /// Dumps the contents of `NSUserDefaults` to the console func dumpUserDefaults() { print(UserDefaults.standard.dictionaryRepresentation() as NSDictionary) } /// Dumps an autolayout backtrace to the console func autolayoutTrace() { print(UIApplication.shared.keyWindow?.perform(Selector(("_autolayoutTrace")))) } /// Force user interaction to be enabled again func enableUserInteraction() { UIApplication.shared.endIgnoringInteractionEvents() } /// Show the path to the documents directory func showDocumentsPath() { if let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { print("Documents Directory: <#\(url)#"+">") } } /// Print the current trait collection details for the main window func showCurrentTraitCollection() { guard let window = UIApplication.shared.keyWindow else { return } let allTraits = window.traitCollection.debugDescription .components(separatedBy: ";")[1] .components(separatedBy: ",") let kvs: [[String]] = allTraits.map { traitString in traitString .replacingOccurrences(of: " _UITraitName", with: "") .components(separatedBy: " = ") } tableFormatted(title: "Current Trait Collection") { formatter in kvs.forEach { formatter.addKey($0[0], value: $0[1]) } } } /// Print generic device details func showDeviceDetails() { let device = UIDevice.current tableFormatted(title: "Device Details") { formatter in formatter.addKey("Name", value: device.name) formatter.addKey("Model", value: device.model) formatter.addKey("System Name", value: device.systemName) formatter.addKey("System Version", value: String(device.systemVersion)) formatter.addKey("Vendor ID", value: device.identifierForVendor?.description ?? "") } } /// Force application state preservation func forceStatePreservation() { let app = UIApplication.shared let shouldSave = #selector(UIApplicationDelegate.application(_:shouldSaveApplicationState:)) let shouldRestore = #selector(UIApplicationDelegate.application(_:shouldRestoreApplicationState:)) guard let delegate = app.delegate, delegate.responds(to: shouldSave), delegate.responds(to: shouldRestore) else { print("Cannot force state preservation. AppDelegate must implement: \n\t-\(shouldSave) \n\t-\(shouldRestore)") return } print("Attempting to force application state preservation") app.perform(Selector(("_saveApplicationPreservationStateIfSupported"))) } #endif }
mit
f6a916efd77ca1ab4d53ddbee36d79b1
39.543956
192
0.669061
4.870627
false
false
false
false
ppoh71/motoRoutes
motoRoutes/ExploreMotoRoutes.swift
1
25989
// // exploreMotoRoutes.swift // motoRoutes // // Created by Peter Pohlmann on 21.09.16. // Copyright © 2016 Peter Pohlmann. All rights reserved. // import UIKit import Mapbox import Firebase import CoreLocation import Foundation import RealmSwift class ExploreMotoRoutes: UIViewController { @IBOutlet weak var mapView: MGLMapView! @IBOutlet weak var collection: UICollectionView! @IBOutlet weak var menuLabel: UIButton! //MARK: my routes vars var myMotoRoutesRealm: Results<Route>! var myRoutesMaster = [RouteMaster]() var markerViewResueIdentifier = "" var lastIndex = IndexPath(item: 0, section: 0) var activeIndex = IndexPath(item: 0, section: 0) var activeRouteCell: RouteCell? var zoomOnSelect = true var timer = Timer() var timeIntervalMarker = 0.06 var markerCount = 0 //MARK: explore routes vars var firebaseRouteMasters = [RouteMaster]() var activeFirebaseRoute = RouteMaster() var selectedMarkerView = [MGLAnnotation]() var activeAnnotationView: MarkerView? var activeDotView = [MGLAnnotation]() var activeRouteMaster = RouteMaster() var myRouteMarker = [MGLAnnotation]() var routeLine = MGLPolyline() var speedMarker = [MGLAnnotation]() var markerGap = 1 var imageCellCache = [Int:UIImage]() //MARK: vars var funcType = FuncTypes() var countReuse = 0 var firbaseUser = "" //MARK: overrides override func viewDidLoad() { super.viewDidLoad() collection.delegate = self collection.dataSource = self collection.allowsSelection = true updateMyRouteMaster() self.view.backgroundColor = UIColor.black let motoMenu = MotoMenuInit(frame: CGRect(x: self.view.frame.width-80, y: 50, width: 70, height: 70)) self.view.addSubview(motoMenu) let menuButtons = MotoMenu(frame: CGRect(x: self.view.frame.width, y: 120, width: 130, height: 300)) self.view.addSubview(menuButtons) setRouteMarkers(myRoutesMaster, markerTitle: "myMarker", funcType: .PrintMyRouteMarker) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) collection.reloadData() // [2] } override func viewDidAppear(_ animated: Bool) { if((FIRAuth.auth()?.currentUser?.uid) != nil){ firbaseUser = (FIRAuth.auth()?.currentUser?.uid)! } //Listen from FlyoverRoutes if Markers are set NotificationCenter.default.addObserver(self, selector: #selector(ExploreMotoRoutes.gotRoutesfromFirbase), name: NSNotification.Name(rawValue: firbaseGetRoutesNotificationKey), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ExploreMotoRoutes.gotLocationsFromFirbase), name: NSNotification.Name(rawValue: firbaseGetLocationsNotificationKey), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ExploreMotoRoutes.actionMenuConfirm), name: NSNotification.Name(rawValue: actionConfirmNotificationKey), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ExploreMotoRoutes.geoCode), name: NSNotification.Name(rawValue: googleGeoCodeNotificationKey), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ExploreMotoRoutes.menuAction), name: NSNotification.Name(rawValue: motoMenuActionNotificationKey), object: nil) //FirebaseData.dataService.getRoutesFromFIR() //print("---------active routemaster \(activeRouteMaster._MotoRoute.id)") } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self) } func geoCode(_ notification: Notification){ let notifyObj = notification.object as! [AnyObject] if let geoCode = notifyObj[0] as? String { print("got sddress from googe:\(geoCode)") } } @IBAction func menuLabelPressed(_ sender: UIButton) { print("menuLabel pressed") centerMap() } func centerMap(){ var myRoutesLocationsBounds = [LocationMaster]() for item in myRoutesMaster { let locationMaster = LocationMaster(latitude: item._MotoRoute.startLatitude, longitude: item._MotoRoute.startLongitude, altitude: 0, speed: 0, course: 0, timestamp: Date(), accuracy: 0, marker: false, distance: 0) myRoutesLocationsBounds.append(locationMaster) } let RouteList = myRoutesLocationsBounds let Bounds = MapUtils.getBoundCoords(RouteList) let coordArray = Bounds.coordboundArray // let distanceDiagonal = Bounds.distance // let distanceFactor = Bounds.distanceFactor if(coordArray.count > 0){ // let edges = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50) //mapView.setVisibleCoordinateBounds(Bounds.coordbound, edgePadding: edges, animated: true) mapView.setZoomLevel(2, animated: true) // mapView.setVisibleCoordinateBounds(Bounds.coordbound, animated: false) //let centerPoint = MapUtils.getCenterFromBoundig(coordArray) //let loca = CLLocationCoordinate2D(latitude: centerPoint.latitude, longitude: centerPoint.longitude) // mapView.setCenter(loca, animated: true) // let camera = MapUtils.cameraDestination(centerPoint.latitude, longitude:centerPoint.longitude, fromDistance:10, pitch: 0, heading: 0) // mapView.setCamera(camera, withDuration: globalCamDuration.gCamDuration, animationTimingFunction: CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)) { // } } } func updateMyRouteMaster(){ let realm = try! Realm() myMotoRoutesRealm = realm.objects(Route.self).sorted(byProperty: "timestamp", ascending: false) myRoutesMaster = RouteMaster.realmResultToMasterArray(myMotoRoutesRealm) setRouteMarkers(myRoutesMaster, markerTitle: "myMarker", funcType: .PrintMarkerIcon) } func menuAction(_ notification: Notification){ let notifyObj = notification.object as! [AnyObject] if let menuType = notifyObj[0] as? MenuButtonType { print("##### ACTION BUTTON PRESSED \(menuType)") switch(menuType){ case .MenuMyRoutes: print("my") updateMyRouteMaster() collection.reloadData() globalActiveMenuButton.activeMenuButton = menuType case .MenuRecord: print("reord") performSegue(withIdentifier: "recordSegue", sender: nil) case .MenuCloud: print("cloud") FirebaseData.dataService.getRoutesFromFIR() globalActiveMenuButton.activeMenuButton = menuType case .MenuSettings: print("settings") performSegue(withIdentifier: "settingsSegue", sender: nil) default: print("default") } } } func actionMenuConfirm(_ notification: Notification){//marker view notification //print("###ActionButton NotifY Explore") let notifyObj = notification.object as! [AnyObject] if let actionType = notifyObj[0] as? ActionButtonType { switch(actionType) { case .Details: //print("NOTFY: Clicked Details") gotoShowRoute(activeRouteMaster) case .ConfirmDelete: //print("NOTFY: Confirm Delete") deleteRoute() case .ConfirmDeleteFIR: //print("NOTFY: Confirm Delete FIR") FirebaseData.dataService.deleteFIRRouteData(id: self.activeRouteMaster._MotoRoute.id) case .ConfirmShare: //print("NOTFY: Confirm Share") FirebaseData.dataService.addRouteToFIR(self.activeRouteMaster, keychain: self.firbaseUser) case .ConfirmDownload: //print("NOTFY: Confirm Download") addRoutetoRealm(routeMaster: activeRouteMaster) case .CloseMarkerView: //print("Closer MarkerView \(activeRouteMaster)") deleteMarkers(&selectedMarkerView) default: break //print("default click") } } } func gotRoutesfromFirbase(_ notification: Notification){ if let notifyObj = notification.object as? [RouteMaster] { firebaseRouteMasters = notifyObj setRouteMarkers(firebaseRouteMasters, markerTitle: "firebaseMarker", funcType: .PrintCloudMarker) } } func gotLocationsFromFirbase(_ notification: Notification){ if let notifyObj = notification.object as? [RouteMaster] { activeAnnotationView?.setupAll(notifyObj[0], menuType: MarkerViewType.FirRoute) } } func startMarkerTimer(){ timer.invalidate() deleteMarkers(&speedMarker) markerCount = 0 timer = Timer.scheduledTimer(timeInterval: TimeInterval(timeIntervalMarker), target: self, selector: #selector(ExploreMotoRoutes.printSpeeMarker), userInfo: nil, repeats: true) } func printSpeeMarker(){ markerCount = markerCount+markerGap funcType = .PrintCircles DispatchQueue.global(qos: .background).async { if(self.markerCount<self.activeRouteMaster._RouteList.count && self.activeRouteMaster._RouteList.count>0){ let location = self.activeRouteMaster._RouteList[self.markerCount] MapUtils.newSingleMarker(self.mapView, location: location, speedMarker: &self.speedMarker) } else { self.timer.invalidate() } } DispatchQueue.main.async { /*nothing in main queue */} } func printAllMarker(_ funcSwitch: FuncTypes, _RouteMaster: RouteMaster){ self.funcType = funcSwitch self.deletRouteLine(routeLine) markerGap = MapUtils.calcMarkerGap(activeRouteMaster._RouteList, route: activeRouteMaster) self.startMarkerTimer() DispatchQueue.global(qos: .userInteractive).async { DispatchQueue.main.async { self.routeLine = MapUtils.printRouteOneColor(_RouteMaster._RouteList, mapView: self.mapView ) self.deleteMarkers(&self.activeDotView) let endMarker = MapUtils.getEndMarker(_RouteMaster._RouteList) self.mapView.addAnnotation(endMarker) self.activeDotView.append(endMarker) } } } func setRouteMarkers(_ routes: [RouteMaster], markerTitle: String, funcType: FuncTypes){ //deleteMarkers(&myRouteMarker) deleteAllMarker() self.funcType = funcType for item in routes { setMarker(item, markerTitle: markerTitle) } } func setMarker(_ routeMaster: RouteMaster, markerTitle: String){ let newMarker = MapUtils.makeMarker(routeMaster, markerTitle: markerTitle) mapView.addAnnotation(newMarker) routeMaster._marker = newMarker if(markerTitle=="myMarker"){ myRouteMarker.append(newMarker) } } func setViewMarker(_ routeMaster: RouteMaster, markerTitle: String){ deleteMarkers(&selectedMarkerView) let newMarker = MapUtils.makeMarker(routeMaster, markerTitle: markerTitle) mapView.addAnnotation(newMarker) selectedMarkerView.append(newMarker) } func deleteMarkers(_ markers:inout [MGLAnnotation]){ for marker in markers{ mapView.deselectAnnotation(marker, animated: true) mapView.removeAnnotation(marker) } markers = [MGLAnnotation]() } func deleteAllMarker(){ guard (mapView.annotations != nil) else { return } self.mapView.removeAnnotations(mapView.annotations!) } func deletRouteLine(_ routeLine: MGLPolyline){ self.mapView.removeAnnotation(routeLine) } func gotoShowRoute(_ routeMaster: RouteMaster){ if let showRouteController = self.storyboard?.instantiateViewController(withIdentifier: "showRouteVC") as? showRouteController { //print("got it") showRouteController.motoRoute = routeMaster._MotoRoute self.present(showRouteController, animated: true, completion: nil) } } func addRoutetoRealm(routeMaster: RouteMaster){ //print("active id \(routeMaster._MotoRoute.id)") removeAnnotation(routeMaster) RealmUtils.saveRouteFromFIR(routeMaster) NotificationCenter.default.post(name: Notification.Name(rawValue: motoMenuNotificationKey), object: []) reloadData() } func deleteRoute(){ let realm = try! Realm() try! realm.write { removeAnnotation(activeRouteMaster) //print("try delete \(activeRouteMaster._MotoRoute.id) ") realm.delete(activeRouteMaster._MotoRoute) self.reloadData() activeRouteMaster = RouteMaster() deleteMarkers(&self.activeDotView) deleteMarkers(&speedMarker) deletRouteLine(routeLine) NotificationCenter.default.post(name: Notification.Name(rawValue: progressDoneNotificationKey), object: [ProgressDoneType.ProgressDoneDelete]) } } func removeAnnotation(_ routeMaster: RouteMaster){ mapView.deselectAnnotation(routeMaster._marker, animated: false) mapView.removeAnnotation(routeMaster._marker) } func reloadData() { updateMyRouteMaster() collection.reloadData() } @IBAction func closeToExplore(_ segue:UIStoryboardSegue) { //print("close mc \(segue.source)") segue.source.removeFromParentViewController() if segue.source is motoRoutes.showRouteController { collection.reloadData() } } } //MARK: CollectionView Delegate Extension extension ExploreMotoRoutes: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return myRoutesMaster.count } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let latitude = myRoutesMaster[(indexPath as NSIndexPath).item].startLat let longitude = myRoutesMaster[(indexPath as NSIndexPath).item].startLong let routeMaster = myRoutesMaster[(indexPath as NSIndexPath).item] routeMaster.associateRouteListOnly() activeRouteMaster = routeMaster //print("####selected marker \(activeRouteMaster._marker)") if(zoomOnSelect==true){ let bounds = MapUtils.getBoundCoords(activeRouteMaster._RouteList) let distance = bounds.distance*7 //print("Bounds: \(bounds)") MapUtils.flyToLoactionSimple(latitude, longitude: longitude, mapView: mapView, distance: distance, pitch: 0) } if let cell = collectionView.cellForItem(at: indexPath) as? RouteCell { cell.isSelected = true cell.toggleSelected() activeIndex = IndexPath(item: indexPath.item, section: 0) } collection.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally) setViewMarker(routeMaster, markerTitle: "MyRouteMarkerViewSelected") printAllMarker(.PrintCircles, _RouteMaster: routeMaster) zoomOnSelect = true // set back, false from mapview delegate select } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? RouteCell { // print("### did really deselect \(indexPath)") cell.isSelected = false cell.toggleSelected() } collection.reloadData() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RouteCell", for: indexPath) as? RouteCell { //print("ROUTE CELL INIT deque") cell.delegate = self let route = myRoutesMaster[indexPath.row] var image = UIImage() let routeId:String = route._MotoRoute.id let imgName = route._MotoRoute.image let label = route._MotoRoute.locationStart if((imageCellCache[indexPath.row]) != nil && imgName.characters.count > 0){ print("image xxx \(imageCellCache[indexPath.row])") image = (imageCellCache[indexPath.row])! } else{ let imgPath = Utils.getDocumentsDirectory().appendingPathComponent(imgName) image = ImageUtils.loadImageFromPath(imgPath as NSString)! //image = ImageUtils.resizeImage(image, newWidth: 156) imageCellCache[indexPath.row] = image print("image load \(image)") } //print("###label: \(imageCellCache)") cell.configureCell(label: label, datetime: route.routeDate, id: routeId, route: route, image: image, index: indexPath.item) cell.toggleSelected() return cell } else{ return UICollectionViewCell() } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 170, height: 135) } } // MARK: - MKMapViewDelegate extension ExploreMotoRoutes: MGLMapViewDelegate { func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? { var reuseIdentifier = "" var markerImage: UIImage? guard (annotation.subtitle) != nil else { print("guard no tile") return nil } guard annotation.title != nil else { print("gurad mapviw image no title") return nil } switch(self.funcType) { case .PrintMarker: reuseIdentifier = "MarkerSpeed\(Utils.getSpeed(globalSpeed.gSpeed))-1" case .PrintCircles: reuseIdentifier = "MarkerCircle\(Utils.getSpeed(globalSpeed.gSpeed))-5" case .PrintStartEnd: reuseIdentifier = "StartEndMarker" case .PrintMyRouteMarker: reuseIdentifier = "MyRoutemarker" case .PrintCloudMarker: reuseIdentifier = "CloudMarker" default: reuseIdentifier = "Marker-\(annotation.title))" break } var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: reuseIdentifier) if annotationImage == nil { switch(self.funcType) { case .PrintMyRouteMarker: markerImage = ImageUtils.dotColorMarker(12, height: 12, color: UIColor.yellow, style: .CircleFullLine) case .PrintCloudMarker: markerImage = ImageUtils.dotColorMarker(12, height: 12, color: UIColor.cyan, style: .CircleFullLine) case .PrintCircles: let color = ColorUtils.getColorSpeedGlobal() markerImage = ImageUtils.dotColorMarker(5, height: 5, color: color, style: .Circle) case .PrintMarkerIcon: markerImage = UIImage(named: "marker4") default: markerImage = ImageUtils.dotColorMarker(15, height: 15, color: UIColor.cyan, style: .Circle) } annotationImage = MGLAnnotationImage(image: markerImage!, reuseIdentifier: reuseIdentifier) } return annotationImage } func mapView(_ mapView: MGLMapView, didAdd annotationViews: [MGLAnnotationView]) { //print("annotationViews") } func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? { //print("mgl view annotation") guard annotation is MGLPointAnnotation else { return nil } guard let markerTitle = annotation.title else { return nil } guard (markerTitle == "MyRouteMarkerViewSelected") || (markerTitle == "FirebaseMarkerViewSelected") || (markerTitle == "DotMarkerView") else { return nil } guard let reuseIdentifier = annotation.subtitle else { return nil } //print("Markertile: \(markerTitle)") var viewType = MarkerViewType() switch markerTitle! { case "MyRouteMarkerViewSelected": viewType = .MyRoute case "FirebaseMarkerViewSelected": viewType = .FirRoute case "DotMarkerView": viewType = .DotView default: viewType = .MyRoute } //print("resuse Identifier: \(markerViewResueIdentifier)") let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier!) if annotationView == nil { if viewType == .DotView{ let dotMarkerView = MarkerViewDot(reuseIdentifier: reuseIdentifier!, color: UIColor.cyan) return dotMarkerView } else { let markerView = MarkerView(reuseIdentifier: reuseIdentifier!, routeMaster: activeRouteMaster, type: viewType) markerView.isEnabled = false activeAnnotationView = markerView return markerView } } else { return annotationView } } func mapView(_ mapView: MGLMapView, didDeselect annotation: MGLAnnotation) { //print("didDeselect") } func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) { //print("test 1") print(annotation) guard let titleID = annotation.subtitle else { print("guard exploreMotoRoutes didSelect") return } //print("test 2") //print("##did select marker \(annotation) \(activeRouteMaster._MotoRoute.id)") if(annotation.title! == "firebaseMarker" && annotation.subtitle! != activeRouteMaster._MotoRoute.id){ //print("test 3") let routeMaster = RouteMaster.findRouteInRouteMasters(firebaseRouteMasters, key: titleID!).0 if (!routeMaster._MotoRoute.id.isEmpty) { //print("test 4") activeRouteMaster = routeMaster setViewMarker(routeMaster, markerTitle: "FirebaseMarkerViewSelected") //print("test 5") //get locationsList for this Route from firebase if(routeMaster._MotoRoute.locationsList.count<1){ FirebaseData.dataService.geLocationsRouteFIR(routeMaster) } else{ activeAnnotationView?.setupAll(routeMaster, menuType: MarkerViewType.FirRoute) } } } if(annotation.title! != "firebaseMarker" && annotation.subtitle! != activeRouteMaster._MotoRoute.id){ //print("do if else") //print("test 10") let index = RouteMaster.findRouteInRouteMasters(myRoutesMaster, key: titleID!).1 if(index <= myRoutesMaster.count) { collection.delegate?.collectionView!(collection, didDeselectItemAt: activeIndex) collection.selectItem(at: IndexPath(item: index, section: 0) , animated: true, scrollPosition: .centeredHorizontally) zoomOnSelect = false collection.delegate?.collectionView!(collection, didSelectItemAt: IndexPath(item: index, section: 0)) activeIndex = IndexPath(item: index, section: 0) } } } func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool) { // print("regionDidChangeAnimated") } func mapView(_ mapView: MGLMapView, tapOnCalloutFor annotation: MGLAnnotation) { //print("tapOnCalloutFor") } func mapView(_ mapView: MGLMapView, didSelect annotationView: MGLAnnotationView) { //print("did select ANNOTATION VIEW") } func mapViewRegionIsChanging(_ mapView: MGLMapView) { // print("region is chanhing") } func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool { //print("annotationCanShowCallout") return false } func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat { return 2.0 } func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> UIColor { return blue0 } } extension ExploreMotoRoutes: RouteCellDelegate{ func pressedDetails(id: String, index: Int) { //print("pressed Details id: \(id)") gotoShowRoute(activeRouteMaster) } }
apache-2.0
0277ec8dae67e7c2e814f4e310c6c520
39.60625
225
0.625404
5.008287
false
false
false
false
bumpersfm/handy
Components/NotificationWindow.swift
1
5014
// // Created by Dani Postigo on 11/24/16. // import Foundation import UIKit @objc public protocol NotificationWindowDelegate: class { optional func notificationTapped(notification: NotificationWindow) optional func notificationWillPresent(notification: NotificationWindow) optional func notificationPresented(notification: NotificationWindow) optional func notificationWillAnimate(notification: NotificationWindow) optional func notificationDismissed(notification: NotificationWindow) } public class NotificationWindow: UIWindow { public var presented: Bool = false public var dismissOnTap: Bool = false public weak var delegate: NotificationWindowDelegate? = nil public private(set) var contentView: UIView = UIView() { didSet { self.update(contentView: oldValue) } } private(set) var size: CGSize = CGSize.zero private var constraint: NSLayoutConstraint? // MARK: Init required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public init(frame: CGRect) { super.init(frame: frame) Swift.print("NotificationWindow.\(#function)") self.windowLevel = App.keyWindow?.windowLevel ?? UIWindowLevelNormal self.addGesture(UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))) } // MARK: Show / hide public func show(inView window: UIView, animated: Bool = false, completion: Block? = nil, options: AnimationOptions) { self.add(toView: window) self.show(animated: animated, options: options, completion: completion) } public func show(inViewController vc: UIViewController, animated: Bool = false, completion: Block? = nil, options: AnimationOptions) { self.add(toViewController: vc) self.show(animated: animated, options: options, completion: completion) } public func show(animated animated: Bool = false, completion: Block? = nil) { self.show(animated: animated, options: AnimationOptions(duration: 0.4, options: .CurveEaseInOut), completion: completion) } public func show(animated animated: Bool = false, options: AnimationOptions, completion: Block? = nil) { guard self.superview != nil else { return } self.constraint?.constant = self.size.height guard animated else { self.presented(completion: completion); return } UIView.animateWithOptions(options, animations: { self.superview?.layoutIfNeeded() }, completion: { _ in self.presented(completion: completion) }) } public func hide(animated animated: Bool = false, completion: Block? = nil) { self.delegate?.notificationWillAnimate?(self) guard animated else { self.dismissed(completion: completion); return } UIView.transitionWithView(self, duration: 0.45, options: .CurveEaseInOut, animations: { self.hidden = true }, completion: { _ in self.dismissed(completion: completion) }) } // MARK: Actions public func tapped(sender: AnyObject? = nil) { self.delegate?.notificationTapped?(self) guard self.dismissOnTap else { return } self.hide(animated: true) } // MARK: Event handlers private func presented(completion completion: Block? = nil) { self.presented = true self.delegate?.notificationPresented?(self); completion?() } private func dismissed(completion completion: Block? = nil) { self.presented = false self.hidden = true self.delegate?.notificationDismissed?(self); completion?() } // MARK: Convenience private func add(toViewController vc: UIViewController) { self.add(toView: vc.view, topAnchor: vc.topLayoutGuide.topAnchor) } private func add(toView window: UIView) { self.add(toView: window, topAnchor: window.topAnchor) } private func add(toView window: UIView, topAnchor: NSLayoutAnchor) { self.frame.size.width = window.bounds.size.width window.addView(self) self.delegate?.notificationWillPresent?(self) self.leadingAnchor.constraintEqualToAnchor(window.leadingAnchor).active = true self.trailingAnchor.constraintEqualToAnchor(window.trailingAnchor).active = true self.constraint = self.bottomAnchor.constraintEqualToAnchor(topAnchor) self.constraint?.active = true self.superview?.layoutIfNeeded() self.delegate?.notificationWillAnimate?(self) } // MARK: Private methods private func update(contentView oldValue: UIView) { oldValue.removeFromSuperview() self.size = self.contentView.frame.size self.embed(self.contentView) } // MARK: Convenience convenience public init(withView contentView: UIView) { self.init(frame: contentView.bounds) Swift.print("NotificationWindow.\(#function)") ({ self.contentView = contentView })() } }
mit
385945fef96f3e98044a6bfb4a9c2566
36.140741
138
0.686079
4.816523
false
false
false
false
softermii/ASSwiftContactBook
Pods/Extensions/Extensions.swift
2
1595
// // Extensions.swift // ASContacts // // Created by Anton Stremovskiy on 6/26/17. // Copyright © 2017 áSoft. All rights reserved. // import Foundation import UIKit public extension String { func index(from: Int) -> Index { return self.index(startIndex, offsetBy: from) } func substring(from: Int) -> String { let fromIndex = index(from: from) return substring(from: fromIndex) } func substring(to: Int) -> String { let toIndex = index(from: to) return substring(to: toIndex) } func substring(with r: Range<Int>) -> String { let startIndex = index(from: r.lowerBound) let endIndex = index(from: r.upperBound) return substring(with: startIndex..<endIndex) } var digits: String { return components(separatedBy: CharacterSet.decimalDigits.inverted) .joined() } } public extension UIViewController { class func loadFromNib<T: UIViewController>() -> T { return T(nibName: String(describing: self), bundle: nil) } } public extension NSObject { var className: String { return NSStringFromClass(self as! AnyClass).components(separatedBy: ".").last ?? "" } public class var className: String { return NSStringFromClass(self).components(separatedBy: ".").last ?? "" } } public extension Date { func dateToStringFullMonth() -> String { let formatter = DateFormatter() formatter.dateFormat = "MMMM dd, YYYY" return formatter.string(from: self) } }
mit
f49f655117c8450ebdca792576fc18ac
22.776119
91
0.620841
4.364384
false
false
false
false
Schatzjason/cs212
Networking/FavoriteMovie/MovieList/TheMovieDB/TMDBURLs.swift
1
3720
// // TheMovieDB.swift // TheMovieDB // // Created by Jason Schatz on 1/10/16. // import Foundation struct TMDBURLs { // MARK: - URL Helper static let IDPlaceholder: String = "{id}" static func popular() -> URL { return URLForResource(TMDB.Resources.MoviePopular) } static func nowPlaying() -> URL { return URLForResource(TMDB.Resources.MovieTheatres) } static func URLForResource(_ r: String, parameters p: [String : Any] = [:]) -> URL { return URLForResource(r, withId: nil, parameters: p) } static func URLForResource( _ r: String, withId id: Int?, parameters p: [String : Any] = [:] ) -> URL { // make mutable copies of the resource and parameters var resource = r var parameters = p // Add in the API Key parameters["api_key"] = TMDB.Constants.ApiKey as AnyObject? // If this is a resource that requires an id, we will take care of that here if let id = id { // rewrite the resource with the {id} replaced with the id resource = resource.replacingOccurrences(of: "{id}", with: "\(id)") } // turn the remaining parameters into a string let paramString = parameterString(parameters) // Assemble the URL String let urlString = TMDB.Constants.BaseURL + resource + "?" + paramString // Create a URL let url = URL(string: urlString)! return url } // The methods for poster image URL's is almost exactly like the method for people's profile image // URL's. The only diference is the value for the defalut value of the "size" parameter. // // TMDB has different constants for images sizes. You can find the arrays of size values in the TMDB struct static func URLForPosterWithPath(_ filePath: String, size: String? = TMDB.Images.PosterSizes[1]) -> URL { let baseURL = URL(string: TMDB.Constants.BaseImageURL)! return baseURL.appendingPathComponent(size!).appendingPathComponent(filePath) } static func URLForProfileWithPath(_ filePath: String, size: String? = TMDB.Images.ProfileSizes[1]) -> URL { let baseURL = URL(string: TMDB.Constants.BaseImageURL)! return baseURL.appendingPathComponent(size!).appendingPathComponent(filePath) } /** * Translate a dictionary of key-values into a URL encoded parameter string * * For example, ["name" : "Kim", "id" : "22"] becomes "name=Kim&id=22" */ fileprivate static func parameterString(_ parameters: [String : Any]) -> String { if parameters.isEmpty { return "" } // And array of strings. Each element will have the format "key=value" var urlKeyValuePairs = [String]() for (key, value) in parameters { // make sure that it is a string value let stringValue = "\(value)" // Escape it let escapedValue = stringValue.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) // Append it if let escapedValue = escapedValue { let keyValuePair = "\(key)=\(escapedValue)" urlKeyValuePairs.append(keyValuePair) } else { print("Warning: trouble escaping string \"\(stringValue)\"") } } // Create a single string, separated with &'s return urlKeyValuePairs.joined(separator: "&") } }
mit
d580b474811a58912ebe4af046c97508
31.631579
117
0.581989
4.97992
false
false
false
false
mightydeveloper/swift
validation-test/stdlib/GameplayKit.swift
9
2556
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import GameplayKit // GameplayKit is only available on iOS 9.0 and above, OS X 10.11 and above, and // tvOS 9.0 and above. var GamePlayKitTests = TestSuite("GameplayKit") if #available(OSX 10.11, iOS 9.0, tvOS 9.0, *) { class TestComponent : GKComponent {} class OtherTestComponent : GKComponent {} class TestState1 : GKState {} class TestState2 : GKState {} GamePlayKitTests.test("GKEntity.componentForClass()") { let entity = GKEntity() entity.addComponent(TestComponent()) if true { var componentForTestComponent = entity.componentForClass(TestComponent.self) var componentForOtherTestComponent_nil = entity.componentForClass(OtherTestComponent.self) expectNotEmpty(componentForTestComponent) expectType(Optional<TestComponent>.self, &componentForTestComponent) expectEmpty(componentForOtherTestComponent_nil) } entity.removeComponentForClass(TestComponent.self) entity.addComponent(OtherTestComponent()) if true { var componentForOtherTestComponent = entity.componentForClass(OtherTestComponent.self) var componentForTestComponent_nil = entity.componentForClass(TestComponent.self) expectNotEmpty(componentForOtherTestComponent) expectType(Optional<OtherTestComponent>.self, &componentForOtherTestComponent) expectEmpty(componentForTestComponent_nil) } } GamePlayKitTests.test("GKStateMachine.stateForClass()") { if true { // Construct a state machine with a custom subclass as the only state. let stateMachine = GKStateMachine( states: [TestState1()]) var stateForTestState1 = stateMachine.stateForClass(TestState1.self) var stateForTestState2_nil = stateMachine.stateForClass(TestState2.self) expectNotEmpty(stateForTestState1) expectType(Optional<TestState1>.self, &stateForTestState1) expectEmpty(stateForTestState2_nil) } if true { // Construct a state machine with a custom subclass as the only state. let stateMachine = GKStateMachine( states: [TestState2()]) var stateForTestState2 = stateMachine.stateForClass(TestState2.self) var stateForTestState1_nil = stateMachine.stateForClass(TestState1.self) expectNotEmpty(stateForTestState2) expectType(Optional<TestState2>.self, &stateForTestState2) expectEmpty(stateForTestState1_nil) } } } // if #available(OSX 10.11, iOS 9.0, tvOS 9.0, *) runAllTests()
apache-2.0
fbe243eaecfc21d3c173e4c0590fb513
26.782609
82
0.752347
4.0896
false
true
false
false
nielubowicz/Particle-SDK
ParticleSDK/ParticleSDK/ParticleDevice.swift
1
8602
// // ParticleDevice.swift // Particle-SDK // // Created by Chris Nielubowicz on 11/17/15. // Copyright © 2015 Mobiquity, Inc. All rights reserved. // import Foundation import Alamofire enum DeviceParameterNames : String { case id case name case last_app case connected case last_ip_address case last_heard } public class ParticleDevice : NSObject { public var id : String = "" public var deviceName : String = "" public var last_app: String = "" public var connected: Bool = false public var last_ip_address: String = "" public var last_heard: String = "" public var date_last_heard: NSDate? init(deviceJSON: Dictionary<String,AnyObject>) { if let id = deviceJSON[DeviceParameterNames.id.rawValue] as? String { self.id = id } if let deviceName = deviceJSON[DeviceParameterNames.name.rawValue] as? String { self.deviceName = deviceName } if let last_app = deviceJSON[DeviceParameterNames.last_app.rawValue] as? String { self.last_app = last_app } if let connected = deviceJSON[DeviceParameterNames.connected.rawValue] as? NSNumber { self.connected = connected.boolValue } if let last_ip_address = deviceJSON[DeviceParameterNames.last_ip_address.rawValue] as? String { self.last_ip_address = last_ip_address } if let last_heard = deviceJSON[DeviceParameterNames.last_heard.rawValue] as? String { self.last_heard = last_heard date_last_heard = Particle.dateFormatter.dateFromString(last_heard) } } override public var description : String { return "(\(id)): \(deviceName)" } } // MARK: Variable / Function Access extension ParticleDevice { func getVariable(withName: String, completion:( (AnyObject?, NSError?) -> Void)) { guard Particle.sharedInstance.OAuthToken != nil else { return } let variableURL = url(ParticleEndpoints.Variable(deviceName: deviceName, authToken: Particle.sharedInstance.OAuthToken!, variableName: withName)) Alamofire.request(.GET, variableURL) .responseJSON { response in if (response.result.error != nil) { completion(nil, response.result.error) return; } if let JSON = response.result.value as? Dictionary<String, AnyObject> { completion(JSON[ResponseParameterNames.result.rawValue], nil) } else { let particleError = ParticleErrors.VariableResponse(deviceName: self.deviceName, variableName: withName) completion(nil, particleError.error) } } } func callFunction(named: String, arguments: Array<AnyObject>?, completion:( (NSNumber?, NSError?) -> Void)) { guard Particle.sharedInstance.OAuthToken != nil else { return } var arguments: Dictionary<String,AnyObject>? if let args = arguments { let argsValue = args.map({ "\($0)"}).joinWithSeparator(",") if argsValue.characters.count > 63 { let particleError = ParticleErrors.MaximumArgLengthExceeded() completion(nil, particleError.error) return } arguments = ["args": argsValue] } let variableURL = url(ParticleEndpoints.Function(deviceName: deviceName, authToken: Particle.sharedInstance.OAuthToken!, functionName: named)) Alamofire.request(.POST, variableURL, parameters: arguments) .authenticate(user: Particle.sharedInstance.OAuthToken!, password: "") .responseJSON { response in if (response.result.error != nil) { completion(nil, response.result.error) return } if let JSON = response.result.value as? Dictionary<String, AnyObject> { if let connected = JSON[ResponseParameterNames.connected.rawValue] as? NSNumber { if (connected == false) { let particleError = ParticleErrors.DeviceNotConnected(deviceName: self.deviceName) completion(nil, particleError.error) return } } completion(JSON[ResponseParameterNames.return_value.rawValue] as? NSNumber, nil) } else { let particleError = ParticleErrors.FunctionResponse(deviceName: self.deviceName, functionName: named) completion(nil, particleError.error) } } } } // MARK: Housekeeping extension ParticleDevice { func refresh(completion:( (NSError?) -> Void)) { Particle.sharedInstance.getDevice(self.id) { (device, error) -> Void in if let error = error { completion(error) } guard let device = device else { completion(ParticleErrors.DeviceFailedToRefresh(deviceName: self.deviceName).error) return } var propertyNames = Set<NSString>() var outCount: UInt32 = 0 let properties = class_copyPropertyList(NSClassFromString("Particle-SDK.ParticleDevice"), &outCount) for i in 0...Int(outCount) { let property = properties[i] if let propertyName = NSString(CString: property_getName(property), encoding:NSStringEncodingConversionOptions.AllowLossy.rawValue) { propertyNames.insert(propertyName) } } free(properties) for property in propertyNames { let p = String(property) let value = device.valueForKey(p) self.setValue(value, forKey: p) } } } // // /** // * Remove device from current logged in user account // * // * @param completion Completion block called when function completes with NSError object in case of an error or nil if success. // */ // -(void)unclaim:(void(^)(NSError* error))completion; // // // /** // * Rename device // * // * @param newName New device name // * @param completion Completion block called when function completes with NSError object in case of an error or nil if success. // */ // -(void)rename:(NSString *)newName completion:(void(^)(NSError* error))completion; // } // MARK: Event Handling // /* // -(void)addEventHandler:(NSString *)eventName handler:(void(^)(void))handler; // -(void)removeEventHandler:(NSString *)eventName; // */ // // // MARK: Compilation / Flashing // /** // * Flash files to device // * // * @param filesDict files dictionary in the following format: @{@"filename.bin" : <NSData>, ...} - that is a NSString filename as key and NSData blob as value. More than one file can be flashed. Data is alway binary. // * @param completion Completion block called when function completes with NSError object in case of an error or nil if success. NSError.localized descripion will contain a detailed error report in case of a // */ // -(void)flashFiles:(NSDictionary *)filesDict completion:(void(^)(NSError* error))completion; //@{@"<filename>" : NSData, ...} // /* // -(void)compileAndFlash:(NSString *)sourceCode completion:(void(^)(NSError* error))completion; // -(void)flash:(NSData *)binary completion:(void(^)(NSError* error))completion; // */ // // /** // * Flash known firmware images to device // * // * @param knownAppName NSString of known app name. Currently @"tinker" is supported. // * @param completion Completion block called when function completes with NSError object in case of an error or nil if success. NSError.localized descripion will contain a detailed error report in case of a // */ // -(void)flashKnownApp:(NSString *)knownAppName completion:(void (^)(NSError *))completion; // knownAppName = @"tinker", @"blinky", ... see http://docs. // // //-(void)compileAndFlashFiles:(NSDictionary *)filesDict completion:(void(^)(NSError* error))completion; //@{@"<filename>" : @"<file contents>"} // //-(void)complileFiles:(NSDictionary *)filesDict completion:(void(^)(NSData *resultBinary, NSError* error))completion; //@{@"<filename>" : @"<file contents>"} //
mit
bac2f87c37c3bfcece800b0a5bab87e4
40.757282
225
0.604697
4.592098
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Fitting/Drones/FittingEditorShipDrones.swift
2
4817
// // FittingEditorShipDrones.swift // Neocom // // Created by Artem Shimanski on 3/4/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp struct FittingEditorShipDrones: View { @ObservedObject var ship: DGMShip @Environment(\.self) private var environment @Environment(\.managedObjectContext) private var managedObjectContext @Environment(\.typePicker) private var typePicker @EnvironmentObject private var sharedState: SharedState @State private var isTypePickerPresented = false private struct GroupingKey: Hashable { var squadron: DGMDrone.Squadron var squadronTag: Int var typeID: DGMTypeID var isActive: Bool var target: DGMShip? } private func typePicker(_ group: SDEDgmppItemGroup) -> some View { typePicker.get(group, environment: environment, sharedState: sharedState) { self.isTypePickerPresented = false guard let type = $0 else {return} DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { do { let tag = (self.ship.drones.compactMap({$0.squadron == .none ? $0.squadronTag : nil}).max() ?? -2) + 1 let drone = try DGMDrone(typeID: DGMTypeID(type.typeID)) try self.ship.add(drone) for _ in 1..<drone.squadronSize { try self.ship.add(DGMDrone(typeID: DGMTypeID(type.typeID)), squadronTag: tag) } } catch { } } } } private func section(squadron: DGMDrone.Squadron, drones: [(key: GroupingKey, value: DGMDroneGroup)]) -> some View { let used = ship.usedDroneSquadron(squadron) let total = ship.totalDroneSquadron(squadron) let drones = ForEach(drones, id: \.key) { i in // Button(action: {self.selection = .drone(i.value)}) { FittingDroneCell(drone: i.value) // }.buttonStyle(PlainButtonStyle()) } let title = squadron != .none ? Text("\(squadron.title.uppercased()) \(used)/\(total)") : nil return Section(header: title) { drones } } private var group: SDEDgmppItemGroup? { let isStructure = ship is DGMStructure if ship.totalFighterLaunchTubes > 0 { return try? self.managedObjectContext.fetch(SDEDgmppItemGroup.rootGroup(categoryID: isStructure ? .structureFighter : .fighter)).first } else { return try? self.managedObjectContext.fetch(SDEDgmppItemGroup.rootGroup(categoryID: .drone)).first } } var body: some View { let seq = ship.drones // .filter{$0.squadron == .none} .map { (GroupingKey(squadron: $0.squadron, squadronTag: $0.squadronTag, typeID: $0.typeID, isActive: $0.isActive, target: $0.target), $0) } let isStructure = ship is DGMStructure var sections = Dictionary(grouping: seq){$0.0.squadron}.mapValues { values in Dictionary(grouping: values) { $0.0 }//.values .mapValues{DGMDroneGroup($0.map{$0.1})} .sorted {$0.key.squadronTag < $1.key.squadronTag} } if ship.totalFighterLaunchTubes > 0 { let squadrons: Set<DGMDrone.Squadron> = Set(isStructure ? [.standupHeavy, .standupLight, .standupSupport] : [.heavy, .light, .support]) .subtracting(sections.keys) squadrons.forEach{sections[$0] = []} } return VStack(spacing: 0) { FittingEditorShipDronesHeader(ship: ship).padding(8) Divider() List { ForEach(sections.sorted {$0.key.rawValue < $1.key.rawValue}, id: \.key) { section in self.section(squadron: section.key, drones: section.value) } Section { Button(ship.totalFighterLaunchTubes > 0 ? "Add Fighter" : "Add Drone") { self.isTypePickerPresented = true } .frame(maxWidth: .infinity, alignment: .center) .adaptivePopover(isPresented: $isTypePickerPresented, arrowEdge: .leading) { self.group.map{self.typePicker($0)} } } }.listStyle(GroupedListStyle()) } } } #if DEBUG struct FittingEditorShipDrones_Previews: PreviewProvider { static var previews: some View { FittingEditorShipDrones(ship: DGMShip.testNyx()) .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
9af95422dff2629496bd1834b52db48e
36.625
146
0.568729
4.350497
false
false
false
false
dsay/POPDataSource
DataSources/Example/ViewControllers/TextFieldViewController.swift
1
1603
import UIKit import ReactiveCocoa import ReactiveSwift import POPDataSource class TextFieldViewController: UITableViewController { private var name = NameDataSource() private var surname = SurnameDataSource() private var email = EmailDataSource() private var password = PasswordDataSource() private var shim: TableViewDataSourceShim? = nil { didSet { tableView.dataSource = shim tableView.delegate = shim } } override func viewDidLoad() { super.viewDidLoad() tableView.register(cell: TextFieldTableViewCell.self) tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 140 setupDataSource() } private func setupDataSource() { name.on(.custom(TextFieldDataSource.Actions.end)) { cell, _, _ in print("Name end editing: " + (cell.textField?.text ?? "")) } surname.on(.custom(TextFieldDataSource.Actions.end)) { cell, _, _ in print("Surname end editing: " + (cell.textField?.text ?? "")) } email.on(.custom(TextFieldDataSource.Actions.end)) { cell, _, _ in print("Email end editing: " + (cell.textField?.text ?? "")) } password.on(.custom(TextFieldDataSource.Actions.end)) { cell, _, _ in print("Password end editing: " + (cell.textField?.text ?? "")) } let compossed = ComposedDataSource([name, surname, email, password]) shim = TableViewDataSourceShim(compossed) } }
mit
69e1b7fee85b183f334b887e4d1eb395
29.245283
77
0.609482
4.993769
false
false
false
false
CalebeEmerick/Checkout
Source/Checkout/User.swift
1
1092
// // User.swift // Checkout // // Created by Calebe Emerick on 29/11/16. // Copyright © 2016 CalebeEmerick. All rights reserved. // import Foundation struct User { let id: String let token: String let tokenType: String let refreshToken: String let name: String let username: String let customerKey: String } extension User : JSONDecodable { init?(json: JSON) { guard let id = json["userId"] as? String, let token = json["accessToken"] as? String, let tokenType = json["tokenType"] as? String, let refreshToken = json["refreshToken"] as? String, let name = json["name"] as? String, let username = json["username"] as? String, let customerKey = json["customerKey"] as? String else { return nil } self.id = id self.token = token self.tokenType = tokenType self.refreshToken = refreshToken self.name = name self.username = username self.customerKey = customerKey } }
mit
a91b06e4a2fe18af208c378419f79164
23.795455
63
0.580202
4.399194
false
false
false
false
manderson-productions/RompAround
RompAround/LevelScene.swift
1
14210
// // LevelScene.swift // RompAround // // Created by Mark Anderson on 10/10/15. // Copyright © 2015 manderson-productions. All rights reserved. // import SpriteKit import GameplayKit import GameController class LevelScene: SKScene { // MARK: Category Bitmasks static let playerCategory: UInt32 = 0x1 << 0 static let lootCategory: UInt32 = 0x1 << 1 let debug = false var gridGraph: GKGridGraph = GKGridGraph() var levelData: LevelData! var layers = [SKNode]() let defaultPlayer = Player() enum WorldLayer : Int { case BelowCharacter = 0, Character, AboveCharacter, Debug var cgFloat: CGFloat { return CGFloat(self.rawValue) } static func count() -> Int { return WorldLayer.Debug.rawValue + 1 } static func layerFromMapSquare(mapSquare: MapSquare) -> WorldLayer { switch mapSquare { case .Ground: return .BelowCharacter case .Wall: return .BelowCharacter case .Destructable: return .BelowCharacter case .Enemy: return .Character case .Player: return .Character case .Loot: return .Character case .Empty: return .BelowCharacter } } } init(levelData: LevelData, size: CGSize) { self.levelData = levelData self.gridGraph = GKGridGraph(fromGridStartingAt: int2(0,0), width: Int32(levelData.gridWidth), height: Int32(levelData.gridHeight), diagonalsAllowed: false) super.init(size: size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToView(view: SKView) { super.didMoveToView(view) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(UInt64(4.0) * NSEC_PER_SEC)), dispatch_get_main_queue(), { self.configureGameControllers() }) let swipeRight = UISwipeGestureRecognizer(target: self, action: "swiped:") swipeRight.direction = .Right self.view?.addGestureRecognizer(swipeRight) let swipeLeft = UISwipeGestureRecognizer(target: self, action: "swiped:") swipeLeft.direction = .Left self.view?.addGestureRecognizer(swipeLeft) let swipeUp = UISwipeGestureRecognizer(target: self, action: "swiped:") swipeUp.direction = .Up self.view?.addGestureRecognizer(swipeUp) let swipeDown = UISwipeGestureRecognizer(target: self, action: "swiped:") swipeDown.direction = .Down self.view?.addGestureRecognizer(swipeDown) begin() } func addNode(node: SKNode, atWorldLayer layer: WorldLayer) { let layerNode = layers[layer.rawValue] layerNode.addChild(node) } func childNode(nodeName: String, atWorldLayer layer: WorldLayer) -> SKNode? { let layerNode = layers[layer.rawValue] return layerNode.childNodeWithName(nodeName) } func enemyNodesInLevel() -> [EnemySprite] { let enemies = layers[WorldLayer.Character.rawValue].children.filter({ $0.name == MapSquare.Enemy.name }) as! [EnemySprite] return enemies } func lootNodesInLevel() -> [LootSprite] { let loot = layers[WorldLayer.Character.rawValue].children.filter({ $0.name == MapSquare.Loot.name }) as! [LootSprite] return loot } func processTilesWithBlock(block:(levelData:LevelData, tile:MapSquare, gridX:Int, gridY:Int) -> Void){ for gridY in 0..<levelData.gridHeight { for gridX in 0..<levelData.gridWidth { block(levelData: levelData, tile: levelData[gridX,gridY], gridX: gridX, gridY: gridY) } } } func addLevelTiles() { processTilesWithBlock { [weak self](levelData, tile, gridX, gridY) -> Void in //Create a sprite for the square if let sprite = tile.spriteForSquare(inLevel: levelData, atGridX:gridX, gridY:gridY) { if let layerNode = self?.layers[WorldLayer.layerFromMapSquare(tile).rawValue] { if tile == .Player { // assign the default player to the player if let strongself = self { strongself.defaultPlayer.hero = sprite.childNodeWithName("\(MapSquare.Player)") as! PlayerSprite strongself.defaultPlayer.diceHud.hud.position = CGPoint(x: strongself.size.width - 200, y: 0.0) strongself.addNode(strongself.defaultPlayer.diceHud.hud, atWorldLayer: LevelScene.WorldLayer.AboveCharacter) print("Hero Added: \(strongself.defaultPlayer.hero)") } } for child in sprite.children { child.removeFromParent() child.position = sprite.position layerNode.addChild(child) } layerNode.addChild(sprite) } } switch tile { case .Wall, .Empty: let nodeToRemove = self?.gridGraph.nodeAtGridPosition(int2(gridX.int32, gridY.int32)) self?.gridGraph.removeNodes([nodeToRemove!]) default: break } } } func addWorldNode() -> SKNode { let world = SKNode() world.name = "World" world.position = CGPoint(x: levelData.squareSize / 2, y: levelData.squareSize / 2) addChild(world) return world } func addWorldLayerNodes(parentNode: SKNode) { for i in 0..<WorldLayer.count() { let layerEnum = WorldLayer(rawValue: i)! let layerNode = SKNode() layerNode.name = "\(layerEnum)" layerNode.zPosition = layerEnum.cgFloat layers.append(layerNode) parentNode.addChild(layerNode) } } func replaceEnemyTileWithLootAtPosition(enemyPosition: int2) { var tile = levelData![enemyPosition.x.int, enemyPosition.y.int] tile = MapSquare.Loot if let sprite = tile.spriteForSquare(inLevel: self.levelData, atGridX: enemyPosition.x.int, gridY: enemyPosition.y.int) { let layerNode = layers[WorldLayer.layerFromMapSquare(tile).rawValue] for child in sprite.children { child.removeFromParent() child.position = sprite.position layerNode.addChild(child) } layerNode.addChild(sprite) } } // func addPlayer() { // processTilesWithBlock { [weak self] (levelData, tile, gridX, gridY) -> Void in // if tile == .Player { // let playerNode = PlayerSprite(color: tile.color, size: CGSize(width: levelData.squareSize, height: levelData.squareSize)) // self?.addNode(playerNode, atWorldLayer: .Character) // } // } // } // func addLoot() { // var validTilesForLoot = [int2]() // processTilesWithBlock { (levelData, tile, gridX, gridY) -> Void in // if tile == .Ground { // validTilesForLoot.append(int2(x: gridX.int32, y: gridY.int32)) // } // } // // let map = levelData.level.mapJSON() // if let powerupsArray = map["powerups"] as? [[String: AnyObject]] { // for powerup in powerupsArray { // // let powerupNode: SKSpriteNode // // let randomValidTile: int2 = validTilesForLoot[Int(arc4random_uniform(UInt32(validTilesForLoot.count)))] // // let powerupType = PowerupType(rawValue: powerup["type"] as! String)! // switch powerupType { // case .Card: // powerupNode = CardSprite(attack: powerup["attack"] as! Int, health: powerup["health"] as! Int, info: powerup["info"] as! String, size: CGSize(width: levelData.squareSize, height: levelData.squareSize)) // } // // addNode(powerupNode, atWorldLayer: .Character) // } // } // } private func begin() { removeAllChildren() let worldNode = addWorldNode() addWorldLayerNodes(worldNode) addLevelTiles() } override func update(currentTime: NSTimeInterval) { for layer in layers { layer.enumerateChildNodesWithName("//*", usingBlock: { (child, stop) -> Void in if let updateable = child as? UpdateableLevelEntity { updateable.update(currentTime, inLevel: self) } }) } } // MARK: Controller Stuff func configureGameControllers() { let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: "gameControllerDidConnect:", name: GCControllerDidConnectNotification, object: nil) notificationCenter.addObserver(self, selector: "gameControllerDidDisconnect:", name: GCControllerDidDisconnectNotification, object: nil) configureConnectedGameControllers() GCController.startWirelessControllerDiscoveryWithCompletionHandler(nil) } func configureConnectedGameControllers() { // TODO: Horrendous fucking bug with the Extended Gamepad showing up because of the simulator let gameControllers = GCController.controllers().filter { $0.vendorName == "Remote" } print("game controllers: \(gameControllers)") for controller in gameControllers { let playerIndex = controller.playerIndex if playerIndex == GCControllerPlayerIndex.IndexUnset { continue } assignPresetController(controller, toIndex: playerIndex.rawValue) } for controller in gameControllers { let playerIndex = controller.playerIndex if playerIndex != GCControllerPlayerIndex.IndexUnset { continue } assignUnknownController(controller) } } func gameControllerDidConnect(notification: NSNotification) { let controller = notification.object as! GCController let playerIndex = controller.playerIndex if playerIndex == GCControllerPlayerIndex.IndexUnset { assignUnknownController(controller) } else { assignPresetController(controller, toIndex: playerIndex.rawValue) } } func gameControllerDidDisconnect(notification: NSNotification) { let controller = notification.object as! GCController if defaultPlayer.controller == controller { defaultPlayer.controller = nil } } func assignUnknownController(controller: GCController) { if defaultPlayer.controller == nil { controller.playerIndex = GCControllerPlayerIndex(rawValue: 0)! configureController(controller, forPlayer: defaultPlayer) } } func assignPresetController(controller: GCController, toIndex index: Int) { if defaultPlayer.controller != nil && defaultPlayer.controller != controller { assignUnknownController(controller) return } configureController(controller, forPlayer: defaultPlayer) } func configureController(controller: GCController, forPlayer player: Player) { // let directionPadMoveHandler: GCControllerDirectionPadValueChangedHandler = { dpad, x, y in // let length = hypotf(x, y) // if length > 0.0 { // print("\(trunc(dpad.up.value)) \(trunc(dpad.down.value)) \(trunc(dpad.left.value)) \(trunc(dpad.right.value))") // // move the character //// player.hero.move(Direction.directionFromSwipe(dpad.up.value, down: dpad.down.value, left: dpad.left.value, right: dpad.right.value), inLevel: self) // } // } player.controller = controller let fireButtonHandler: GCControllerButtonValueChangedHandler = { [weak self] button, value, pressed in if let strongself = self { if pressed { // we can still roll the dice if there are attacks/magic, the player will just forfeit his turn if !strongself.defaultPlayer.hasMoves() { strongself.defaultPlayer.diceHud.rollDice() } else { // player has moves left, this toggles the attacks/magic strongself.defaultPlayer.diceHud.toggleAttackType() } print("Action Button Pressed") } else { print("Action Button UNPRESSED") } } } print("GAMEPAD: \(controller.description)") controller.microGamepad?.buttonA.valueChangedHandler = fireButtonHandler controller.microGamepad?.buttonX.valueChangedHandler = fireButtonHandler } func swiped(gesture: UISwipeGestureRecognizer) { let moveOrAttackDirection: Direction switch gesture.direction { case UISwipeGestureRecognizerDirection.Up: moveOrAttackDirection = Direction(x: 0, y: 1) case UISwipeGestureRecognizerDirection.Down: moveOrAttackDirection = Direction(x: 0, y: -1) case UISwipeGestureRecognizerDirection.Left: moveOrAttackDirection = Direction(x: -1, y: 0) case UISwipeGestureRecognizerDirection.Right: moveOrAttackDirection = Direction(x: 1, y: 0) default: moveOrAttackDirection = Direction(x: 0, y: 0) print("BLAHAHAHAH") } defaultPlayer.moveOrAttack(moveOrAttackDirection, inLevel: self) } }
apache-2.0
defa314ced122e0c6862ebc225549e9e
38.91573
223
0.591949
4.756947
false
false
false
false
wangchauyan/iOS_365
NotificationCenter/UpNotificationCenter-Swift/UpNotificationCenter-Swift/UpObserver.swift
1
622
// // UpObserver.swift // UpNotificationCenter-Swift // // Created by Chauyan Wang on 10/14/16. // Copyright © 2016 upshotech. All rights reserved. // import UIKit class UpObserver: NSObject { open var obsever:Any? = nil open var userObject:Any? = nil open var selector:Selector? = nil open var notificationName:NSString? = nil open func initObserver(_ observer:Any, selector:Selector, notificationName:NSString?, object:Any?) { self.obsever = observer self.selector = selector self.notificationName = notificationName self.userObject = object } }
mit
94dc035ec8ef24ae55b8462cdf848e20
23.84
104
0.674718
4.032468
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Settings.swift
1
7335
// // Settings.swift // Inbbbox // // Created by Peter Bruz on 04/01/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import Foundation import SwiftyUserDefaults /// Provides interface for application settings kept in user defaults. class Settings { /// Manages settings related to streams' sources. struct StreamSource { /// Indicates if streams' sources are initially set. static var IsSet: Bool { get { return Settings.boolForKey(.streamSourceIsSet) } set { Settings.setValue(newValue as AnyObject?, forKey: .streamSourceIsSet) } } /// Indicates if stream's source for Following is on. static var Following: Bool { get { return Settings.boolForKey(.followingStreamSourceOn) } set { Settings.setValue(newValue as AnyObject?, forKey: .followingStreamSourceOn) Settings.StreamSource.SelectedStreamSource = .mySet } } /// Indicates if stream's source for NewToday is on. static var NewToday: Bool { get { return Settings.boolForKey(.newTodayStreamSourceOn) } set { Settings.setValue(newValue as AnyObject?, forKey: .newTodayStreamSourceOn) Settings.StreamSource.SelectedStreamSource = .mySet } } /// Indicates if stream's source for PopularToday is on. static var PopularToday: Bool { get { return Settings.boolForKey(.popularTodayStreamSourceOn) } set { Settings.setValue(newValue as AnyObject?, forKey: .popularTodayStreamSourceOn) Settings.StreamSource.SelectedStreamSource = .mySet } } /// Indicates if stream's source for Debuts is on. static var Debuts: Bool { get { return Settings.boolForKey(.debutsStreamSourceOn) } set { Settings.setValue(newValue as AnyObject?, forKey: .debutsStreamSourceOn) Settings.StreamSource.SelectedStreamSource = .mySet } } /// Indicates which one stream source is selected static var SelectedStreamSource: ShotsSource { get { return Settings.streamForKey(.selectedStreamSource) } set { Settings.setValue(newValue.rawValue as AnyObject?, forKey: .selectedStreamSource) } } } /// Manages settings related to reminder. struct Reminder { /// Indicates if reminder is enabled. static var Enabled: Bool { get { return Settings.boolForKey(.ReminderOn) } set { Settings.setValue(newValue as AnyObject?, forKey: .ReminderOn) } } /// Indicates date that reminder should appear. static var Date: Date? { get { return Settings.dateForKey(.ReminderDate) } set { Settings.setValue(newValue as AnyObject?, forKey: .ReminderDate) } } /// Indicates if settings for local notifications are provided. static var LocalNotificationSettingsProvided: Bool { get { return Settings.boolForKey(.LocalNotificationSettingsProvided) } set { Settings.setValue(newValue as AnyObject?, forKey: .LocalNotificationSettingsProvided) } } } /// Manages settings related to customization. struct Customization { /// Indicates if "showing author on homescreen" is enabled. static var ShowAuthor: Bool { get { return Settings.boolForKey(.showAuthorOnHomeScreen) } set { Settings.setValue(newValue as AnyObject?, forKey: .showAuthorOnHomeScreen) } } /// Indicates what language is currently set. static var AppLanguage: Language { get { return Language(rawValue: Settings.stringForKey(.language)) ?? .deviceDefault } set { Settings.setValue(newValue.rawValue as AnyObject?, forKey: .language) } } /// Indicates if "showing author on homescreen" is enabled. static var NightMode: Bool { get { return Settings.boolForKey(.nightMode) } set { Settings.setValue(newValue as AnyObject?, forKey: .nightMode) } } /// Indicates if "showing author on homescreen" is enabled. static var AutoNightMode: Bool { get { return Settings.boolForKey(.autoNightMode) } set { Settings.setValue(newValue as AnyObject?, forKey: .autoNightMode) } } /// Indicates what color mode is currently set. /// - SeeAlso: `ColorMode` static var CurrentColorMode: ColorMode { get { let savedSetting = Settings.stringForKey(.colorMode) let colorMode = ColorMode(rawValue: savedSetting) return colorMode != nil ? colorMode! : .dayMode } set { Settings.setValue(newValue.rawValue as AnyObject?, forKey: .colorMode) } } } } private extension Settings { // MARK: NotificationKey static func boolForKey(_ key: NotificationKey) -> Bool { return boolForKey(key.rawValue) } static func dateForKey(_ key: NotificationKey) -> Date? { return Defaults[key.rawValue].date } static func setValue(_ value: AnyObject?, forKey key: NotificationKey) { Defaults[key.rawValue] = value NotificationCenter.default.post( name: Notification.Name(rawValue: InbbboxNotificationKey.UserDidChangeNotificationsSettings.rawValue), object: self) } // MARK: StreamSourceKey static func boolForKey(_ key: StreamSourceKey) -> Bool { return boolForKey(key.rawValue) } static func setValue(_ value: AnyObject?, forKey key: StreamSourceKey) { Defaults[key.rawValue] = value NotificationCenter.default.post( name: Notification.Name(rawValue: InbbboxNotificationKey.UserDidChangeStreamSourceSettings.rawValue), object: self) } // MARK: CusotmizationKey static func boolForKey(_ key: CustomizationKey) -> Bool { return boolForKey(key.rawValue) } static func stringForKey(_ key: CustomizationKey) -> String { return stringForKey(key.rawValue) } static func streamForKey(_ key: CustomizationKey) -> ShotsSource { return streamForKey(key.rawValue) } static func setValue(_ value: AnyObject?, forKey key: CustomizationKey) { Defaults[key.rawValue] = value } // MARK: General static func boolForKey(_ key: String) -> Bool { return Defaults[key].bool ?? false } static func stringForKey(_ key: String) -> String { return Defaults[key].string ?? "" } static func streamForKey(_ key: String) -> ShotsSource { if let streamSourceType = Defaults[key].string { return ShotsSource(rawValue: streamSourceType) ?? .mySet } return .mySet } } extension Settings { /** Returns information if all stream sources are turned off in Settings */ static func areAllStreamSourcesOff() -> Bool { return (!Settings.StreamSource.Following && !Settings.StreamSource.NewToday && !Settings.StreamSource.PopularToday && !Settings.StreamSource.Debuts) } }
gpl-3.0
5b8d93aced866e65918555ad3af39dd4
34.429952
124
0.629534
4.962111
false
false
false
false
baquiax/BasicImageProcessor
Filterer/ImageProcessor/Filters/Contrast.swift
1
1197
import Foundation public class Contrast : Filter { private var factor : Double = 0; public init (factor const: Double) { self.factor = (const == 0) ? 1 : const } func limitAndCastNumber(number:Double) -> UInt8 { return UInt8(max(0,min(number, 255))) } func calculateContrast (value: UInt8) -> UInt8 { return limitAndCastNumber((((( Double(value) / 255.0) - 0.5) * self.factor) + 0.5) * 255.0) } public func apply(image: RGBAImage) -> RGBAImage { for r in 0...image.height - 1 { for c in 0...image.width - 1 { let index = r * image.width + c var pixel = image.pixels[index] pixel = image.pixels[index] pixel.red = calculateContrast(pixel.red) pixel.green = calculateContrast(pixel.green) pixel.blue = calculateContrast(pixel.blue) image.pixels[index] = pixel; } } return image } public func changeIntensity(newValue: Double) { self.factor = newValue; } public func getIntensity() -> Double { return self.factor } }
mit
58ea342e98dfe36d528b8f65bd3a8322
28.219512
99
0.543024
4.099315
false
false
false
false
nakau1/Formations
Formations/Sources/Models/Enums.swift
1
2074
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import UIKit /// ポジション enum Position: String { case goalKeeper = "GK" case defender = "DF" case midfielder = "MF" case forward = "FW" var backgroundColor: UIColor { switch self { case .goalKeeper: return #colorLiteral(red: 0.8431372549, green: 0.6392156863, blue: 0.0862745098, alpha: 1) // D7A316 case .defender: return #colorLiteral(red: 0.1921568627, green: 0.4, blue: 0.8588235294, alpha: 1) // 3166DB case .midfielder: return #colorLiteral(red: 0.3803921569, green: 0.6431372549, blue: 0.2823529412, alpha: 1) // 61A448 case .forward: return #colorLiteral(red: 0.6823529412, green: 0.0862745098, blue: 0.1921568627, alpha: 1) // AE1631 } } static var items: [Position] { return [.goalKeeper, .defender, .midfielder, .forward] } static var texts: [String] { return items.map { $0.rawValue } } } // for Formation-Template-Edit extension Position { init?(at index: Int) { switch index { case 0: self.init(rawValue: Position.defender.rawValue) case 1: self.init(rawValue: Position.midfielder.rawValue) case 2: self.init(rawValue: Position.forward.rawValue) default: return nil } } var positionIndex: Int { switch self { case .goalKeeper: return -1 // not-use case .defender: return 0 case .midfielder: return 1 case .forward: return 2 } } static var formationComponents: [Position] { return [.defender, .midfielder, .forward] } } /// 背番号 class UniformNumber { static var texts: [String] { var ret = (1...99).map { "\($0)" } ret.append("0") ret.append("00") ret.append("-") return ret } }
apache-2.0
8422d1a219b8c95674684cda87551598
29.264706
126
0.54519
3.797048
false
false
false
false
alloyapple/GooseGtk
Sources/Calculator/CalcViewController.swift
1
8087
// // Created by color on 17-11-23. // import Foundation import CGTK import Goose import Dispatch import GooseGtk //class CalcViewController: GTKViewController { //// private var numberString: [String] = ["", ""] //// private var numberIndex: Int = 0 //// private var op: String = "" //// private var displayLabel: GTKLabel? = nil //// //// public override func viewDidLoad() { //// let grid = GTKGrid() //// grid.columnHomogeneous = true //// //// //// let outputLabel = GTKLabel("") //// grid.attach(subView: outputLabel, left: 0, top: 0, width: 4, height: 1) //// outputLabel.name = "calresult" //// outputLabel.halign = GTK_ALIGN_END //// self.displayLabel = outputLabel //// //// let path = OS.getcwd() ?? "" //// let backimage = GTKImage(.File(path + "/Resource/erjinav_bg.png")) //// grid.attach(subView: backimage, left: 0, top: 0, width: 4, height: 1) //// //// let acButton = GTKButton(label: "AC") //// acButton.click = self.clear //// acButton.boderWidth = 0; //// grid.attach(subView: acButton, left: 0, top: 1, width: 1, height: 1) //// //// let minisButton = GTKButton(label: "+/-") //// grid.attach(subView: minisButton, left: 1, top: 1, width: 1, height: 1) //// //minisButton.click = self.testclick //// //// let percentButton = GTKButton(label: "%") //// grid.attach(subView: percentButton, left: 2, top: 1, width: 1, height: 1) //// //// let chuButton = GTKButton(label: "/") //// grid.attach(subView: chuButton, left: 3, top: 1, width: 1, height: 1) //// chuButton.click = self.opAction //// //// let sevenButton = GTKButton(label: "7") //// grid.attach(subView: sevenButton, left: 0, top: 2, width: 1, height: 1) //// sevenButton.click = self.addtext //// //// let eightButton = GTKButton(label: "8") //// grid.attach(subView: eightButton, left: 1, top: 2, width: 1, height: 1) //// eightButton.click = self.addtext //// //// let nineButton = GTKButton(label: "9") //// grid.attach(subView: nineButton, left: 2, top: 2, width: 1, height: 1) //// nineButton.click = self.addtext //// //// let chengButton = GTKButton(label: "*") //// grid.attach(subView: chengButton, left: 3, top: 2, width: 1, height: 1) //// chengButton.click = self.opAction //// //// //// let fourButton = GTKButton(label: "4") //// grid.attach(subView: fourButton, left: 0, top: 3, width: 1, height: 1) //// fourButton.click = self.addtext //// //// let fivButton = GTKButton(label: "5") //// grid.attach(subView: fivButton, left: 1, top: 3, width: 1, height: 1) //// fivButton.click = self.addtext //// //// let sixButton = GTKButton(label: "6") //// grid.attach(subView: sixButton, left: 2, top: 3, width: 1, height: 1) //// sixButton.click = self.addtext //// //// let subButton = GTKButton(label: "-") //// grid.attach(subView: subButton, left: 3, top: 3, width: 1, height: 1) //// subButton.click = self.opAction //// //// let oneButton = GTKButton(label: "1") //// grid.attach(subView: oneButton, left: 0, top: 4, width: 1, height: 1) //// oneButton.click = self.addtext //// //// let twoButton = GTKButton(label: "2") //// grid.attach(subView: twoButton, left: 1, top: 4, width: 1, height: 1) //// twoButton.click = self.addtext //// //// let threeButton = GTKButton(label: "3") //// grid.attach(subView: threeButton, left: 2, top: 4, width: 1, height: 1) //// threeButton.click = self.addtext //// //// let plusButton = GTKButton(label: "+") //// grid.attach(subView: plusButton, left: 3, top: 4, width: 1, height: 1) //// plusButton.click = self.opAction //// //// let zeroButton = GTKButton(label: "0") //// grid.attach(subView: zeroButton, left: 0, top: 5, width: 2, height: 1) //// zeroButton.click = self.addtext //// //// let dotButton = GTKButton(label: ".") //// grid.attach(subView: dotButton, left: 2, top: 5, width: 1, height: 1) //// dotButton.click = self.addtext //// //// let equalButton = GTKButton(label: "=") //// equalButton.click = self.cal //// grid.attach(subView: equalButton, left: 3, top: 5, width: 1, height: 1) //// //// self.view.addSubView(grid) //// } //// //// private func addtext(_ button: GTKButton) { //// let text = numberString[self.numberIndex] //// numberString[self.numberIndex] = text + button.label //// self.displayLabel?.text = numberString[self.numberIndex] //// } //// //// private func cal(_ button: GTKButton) { //// guard numberString[0] != "", numberString[1] != "" else { //// return //// } //// //// //// //// switch (numberString[0].contain("."), numberString[1].contain(".")) { //// case (true, _): //// fallthrough //// case (_, true): //// let num1 = numberString[0].doubleValue //// let num2 = numberString[1].doubleValue //// //// switch self.op { //// case "+": //// self.displayLabel?.text = "\(num1 + num2)" //// case "-": //// self.displayLabel?.text = "\(num1 - num2)" //// case "*": //// self.displayLabel?.text = "\(num1 * num2)" //// case "/": //// self.displayLabel?.text = "\(num1 / num2)" //// default: //// return //// //// } //// //// self.displayLabel?.text = "\(num1 + num2)" //// default: //// let num1 = numberString[0].intValue //// let num2 = numberString[1].intValue //// switch self.op { //// case "+": //// self.displayLabel?.text = "\(num1 + num2)" //// case "-": //// self.displayLabel?.text = "\(num1 - num2)" //// case "*": //// self.displayLabel?.text = "\(num1 * num2)" //// case "/": //// self.displayLabel?.text = "\(num1 / num2)" //// default: //// return //// //// } //// } //// //// //// self.numberIndex = 0 //// numberString = ["", ""] //// } //// //// private func opAction(_ button: GTKButton) { //// self.op = button.label //// self.numberIndex = 1 //// self.displayLabel?.text = "" //// //// } //// //// private func clear(_ button: GTKButton) { //// self.displayLabel?.text = "" //// numberString = ["", ""] //// self.numberIndex = 0 //// //// } //} class CalcViewController: GTKViewController { private var button: GTKButton? public override func loadView() -> GTKWidget? { let grid = GTKGrid() grid.columnHomogeneous = true let outputLabel = GTKLabel("test") grid.attach(widget: outputLabel, left: 0, top: 0, width: 4, height: 1) outputLabel.name = "calresult" //outputLabel.halign = GTK_ALIGN_END //self.displayLabel = outputLabel //self.button = acButton let minisButton = GTKButton(label: "+/-") grid.attach(widget: minisButton, left: 1, top: 1, width: 1, height: 1) //minisButton.click = self.testclick let percentButton = GTKButton(label: "%") grid.attach(widget: percentButton, left: 2, top: 1, width: 1, height: 1) let chuButton = GTKButton(label: "/") grid.attach(widget: chuButton, left: 3, top: 1, width: 1, height: 1) chuButton.tooltip = "除法" chuButton.click = self.opAction return grid } func updateUI(i: Int) { self.button?.label = "\(i)" } func opAction(widget: GTKWidget) { DispatchQueue.global().async { for i in 1...2000 { GtkASync(self.updateUI, i) sleep(1) } } } }
apache-2.0
bc7edf3907aead18e65d9551fa05fdb7
33.25
85
0.522207
3.563933
false
false
false
false
prolificinteractive/simcoe
SimcoeTests/Mocks/SuperPropertyTrackingFake.swift
1
722
// // SuperPropertyTrackingFake.swift // Simcoe // // Created by Yoseob Lee on 2/27/17. // Copyright © 2017 Prolific Interactive. All rights reserved. // @testable import Simcoe internal final class SuperPropertyTrackingFake: SuperPropertyTracking { let name = "Super Property Tracking [Fake]" var superPropertyEventCount = 0 func set(superProperties: Properties) -> TrackingResult { superPropertyEventCount += 1 return .success } func unset(superProperty: String) -> TrackingResult { superPropertyEventCount += 1 return .success } func clearSuperProperties() -> TrackingResult { superPropertyEventCount += 1 return .success } }
mit
87bfd3ffb8248b347a875cfef5d58bc3
21.53125
71
0.679612
4.450617
false
false
false
false
gouyz/GYZBaking
baking/Classes/Tool/3rdLib/ScrollPageView/ScrollPageView.swift
1
5733
// // ScrollPageView.swift // ScrollViewController // // Created by jasnig on 16/4/6. // Copyright © 2016年 ZeroJ. All rights reserved. // github: https://github.com/jasnig // 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit open class ScrollPageView: UIView { static let cellId = "cellId" fileprivate var segmentStyle = SegmentStyle() /// 附加按钮点击响应 open var extraBtnOnClick: ((_ extraBtn: UIButton) -> Void)? { didSet { segView.extraBtnOnClick = extraBtnOnClick } } fileprivate(set) var segView: ScrollSegmentView! fileprivate(set) var contentView: ContentView! /// 标题 fileprivate var titlesArray: [String] = [] /// 角标 fileprivate var badgeValusArray: [String] = [] /// 所有的子控制器 fileprivate var childVcs: [UIViewController] = [] // 这里使用weak避免循环引用 fileprivate weak var parentViewController: UIViewController? public init(frame:CGRect, segmentStyle: SegmentStyle, titles: [String], childVcs:[UIViewController], parentViewController: UIViewController) { self.parentViewController = parentViewController self.childVcs = childVcs self.titlesArray = titles self.segmentStyle = segmentStyle assert(childVcs.count == titles.count, "标题的个数必须和子控制器的个数相同") super.init(frame: frame) commonInit() } public init(frame:CGRect, segmentStyle: SegmentStyle, titles: [String], childVcs:[UIViewController], badgeValus : [String], parentViewController: UIViewController) { self.parentViewController = parentViewController self.childVcs = childVcs self.titlesArray = titles self.segmentStyle = segmentStyle self.badgeValusArray = badgeValus assert(childVcs.count == titles.count, "标题的个数必须和子控制器的个数相同") super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func commonInit() { backgroundColor = UIColor.white if badgeValusArray.count > 0 { segView = ScrollSegmentView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: 44), segmentStyle: segmentStyle, titles: titlesArray,badges:badgeValusArray) }else{ segView = ScrollSegmentView(frame: CGRect(x: 0, y: 0, width: bounds.size.width, height: 44), segmentStyle: segmentStyle, titles: titlesArray) } guard let parentVc = parentViewController else { return } contentView = ContentView(frame: CGRect(x: 0, y: segView.frame.maxY, width: bounds.size.width, height: bounds.size.height - 44), childVcs: childVcs, parentViewController: parentVc) contentView.delegate = self addSubview(segView) addSubview(contentView) // 避免循环引用 segView.titleBtnOnClick = {[unowned self] (label: UILabel, index: Int) in // 切换内容显示(update content) self.contentView.setContentOffSet(CGPoint(x: self.contentView.bounds.size.width * CGFloat(index), y: 0), animated: self.segmentStyle.changeContentAnimated) } } deinit { parentViewController = nil print("\(self.debugDescription) --- 销毁") } } //MARK: - public helper extension ScrollPageView { /// 给外界设置选中的下标的方法(public method to set currentIndex) public func selectedIndex(_ selectedIndex: Int, animated: Bool) { // 移动滑块的位置 segView.selectedIndex(selectedIndex, animated: animated) } /// 给外界重新设置视图内容的标题的方法,添加新的childViewControllers /// (public method to reset childVcs) /// - parameter titles: newTitles /// - parameter newChildVcs: newChildVcs public func reloadChildVcsWithNewTitles(_ titles: [String], andNewChildVcs newChildVcs: [UIViewController]) { self.childVcs = newChildVcs self.titlesArray = titles segView.reloadTitlesWithNewTitles(titlesArray) contentView.reloadAllViewsWithNewChildVcs(childVcs) } ///给外界重新设置角标的方法 public func reloadBadges(badges: [String]){ self.badgeValusArray = badges segView.reloadBadge(badges: badgeValusArray) } } extension ScrollPageView: ContentViewDelegate { public var segmentView: ScrollSegmentView { return segView } }
mit
004b7298ebc0b281d52446784a97c3c0
36.438356
188
0.686608
4.436688
false
false
false
false
abertelrud/swift-package-manager
Sources/SPMTestSupport/MockPackage.swift
2
3942
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2021 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 // //===----------------------------------------------------------------------===// import Foundation import PackageModel import TSCBasic public struct MockPackage { public let name: String public let platforms: [PlatformDescription] public let location: Location public let targets: [MockTarget] public let products: [MockProduct] public let dependencies: [MockDependency] public let versions: [String?] /// Provides revision identifier for the given version. A random identifier might be assigned if this is nil. public let revisionProvider: ((String) -> String)? // FIXME: This should be per-version. public let toolsVersion: ToolsVersion? public init( name: String, platforms: [PlatformDescription] = [], path: String? = nil, targets: [MockTarget], products: [MockProduct] = [], dependencies: [MockDependency] = [], versions: [String?] = [], revisionProvider: ((String) -> String)? = nil, toolsVersion: ToolsVersion? = nil ) { self.name = name self.platforms = platforms self.location = .fileSystem(path: RelativePath(path ?? name)) self.targets = targets self.products = products self.dependencies = dependencies self.versions = versions self.revisionProvider = revisionProvider self.toolsVersion = toolsVersion } public init( name: String, platforms: [PlatformDescription] = [], url: String, targets: [MockTarget], products: [MockProduct], dependencies: [MockDependency] = [], versions: [String?] = [], revisionProvider: ((String) -> String)? = nil, toolsVersion: ToolsVersion? = nil ) { self.name = name self.platforms = platforms self.location = .sourceControl(url: URL(string: url)!) self.targets = targets self.products = products self.dependencies = dependencies self.versions = versions self.revisionProvider = revisionProvider self.toolsVersion = toolsVersion } public init( name: String, platforms: [PlatformDescription] = [], identity: String, alternativeURLs: [String]? = .none, targets: [MockTarget], products: [MockProduct], dependencies: [MockDependency] = [], versions: [String?] = [], revisionProvider: ((String) -> String)? = nil, toolsVersion: ToolsVersion? = nil ) { self.name = name self.platforms = platforms self.location = .registry(identity: .plain(identity), alternativeURLs: alternativeURLs?.compactMap{ URL(string: $0) }) self.targets = targets self.products = products self.dependencies = dependencies self.versions = versions self.revisionProvider = revisionProvider self.toolsVersion = toolsVersion } public static func genericPackage1(named name: String) throws -> MockPackage { return MockPackage( name: name, targets: [ try MockTarget(name: name), ], products: [ MockProduct(name: name, targets: [name]), ], versions: ["1.0.0"] ) } public enum Location { case fileSystem(path: RelativePath) case sourceControl(url: URL) case registry(identity: PackageIdentity, alternativeURLs: [URL]?) } }
apache-2.0
f9ff19438242e9df3966dc0d2da851ae
33.278261
126
0.592085
4.946048
false
false
false
false
ZamzamInc/ZamzamKit
Sources/ZamzamCore/Utilities/SCNetworkReachability.swift
1
1461
// // SCNetworkReachability.swift // ZamzamCore // // Created by Basem Emara on 5/10/16. // Copyright © 2016 Zamzam Inc. All rights reserved. // #if canImport(SystemConfiguration) import SystemConfiguration public extension SCNetworkReachability { /// Determines if the device is connected to the network. /// /// A remote host is considered reachable when a data packet, sent by /// an application into the network stack, can leave the local device. /// Reachability does not guarantee that the data packet will actually /// be received by the host. static var isOnline: Bool { // http://stackoverflow.com/a/25623647 var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags: SCNetworkReachabilityFlags = [] guard SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) else { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return isReachable && !needsConnection } } #endif
mit
1779792d9ee4cca63b0524b55d67cb74
31.444444
84
0.664384
4.965986
false
false
false
false
ioswpf/CalendarKit
CalendarKit/CalendarKit.swift
1
11952
// // CalendarKit.swift // demo // // Created by wpf on 2017/3/20. // Copyright © 2017年 wpf. All rights reserved. // import UIKit import Foundation import ObjectiveC // MARK: - CalendarKit - class CalendarKit { } /// 农历每日的数据 struct ChineseDayModel: CustomDebugStringConvertible { var year: String = "" var month: String = "" var day: String = "" init(components: DateComponents) { let (y,m,d) = model(from: components) self.year = y self.month = m self.day = d } private func model(from components: DateComponents) -> (String,String,String){ guard let y = components.year, var m = components.month, let d = components.day else { return ("","","") } // 2057-9-28 农历会显示14-9-0 应该为14-8-30 if d == 0 { m = m-1 } // Heavenly Stems and Earthy Branches 天干地支 let hs = (y % 10 == 0) ? 10 : y % 10 let eb = (y % 12 == 0) ? 12 : y % 12 let yStr = "\(self.year(from: hs, eb: eb))年" let mStr = "\(((components.isLeapMonth == true) ? "闰" : ""))\(self.month(from: m))月" let dStr = self.day(from: d) return (yStr, mStr, dStr) } // 天干汉字 阳干不配阴支,阴干不配阳支,所以是60年轮回 private static let hss: [String] = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"] private static let ebs: [String] = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"] private func year(from hs: Int, eb: Int) -> String { guard hs <= ChineseDayModel.hss.count, eb <= ChineseDayModel.ebs.count else { return "甲子" } return "\(ChineseDayModel.hss[hs-1])\(ChineseDayModel.ebs[eb-1])" } private static let months: [String] = ["正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "腊"] private func month(from i: Int) -> String { guard i <= ChineseDayModel.months.count else { return "正" } return ChineseDayModel.months[i-1] } private static let days: [String] = ["初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十",] private func day(from i: Int) -> String { guard i <= ChineseDayModel.days.count else { return "初一" } if i == 0 { return ChineseDayModel.days.last! } return ChineseDayModel.days[i-1] } var debugDescription: String { return "\(year)-\(month)-\(day)" } } /// 每天的数据 struct CKDayModel: CustomDebugStringConvertible { /// 数据是否在当前月 enum CKDayInMonthType { case pre case current case sub } /// 提供给components计算的值 fileprivate static let cs: Set<Calendar.Component> = [.day,.month,.year,.weekday,.weekdayOrdinal,.weekOfMonth,.weekOfYear] fileprivate static let chineseCS: Set<Calendar.Component> = [.day,.month,.year] /// 是否在当月 var type: CKDayInMonthType /// 日期 var date: Date /// 当天的值 包含cs中提供的 var components: DateComponents? /// 农历当天的值 包含chineseCS中提供的 var chineseComponents: DateComponents? /// 农历 var chineseDay: ChineseDayModel? /// 在周内的名字 var weekdayName: String = "" init(type: CKDayInMonthType, date: Date) { self.type = type self.date = date self.components = self.dateComponentsCalculate(date: date) self.chineseComponents = self.chineseDateComponentsCalculate(date: date) self.chineseDay = ChineseDayModel(components: self.chineseComponents!) self.weekdayName = date.weekdayName() } fileprivate func dateComponentsCalculate(date: Date) -> DateComponents { return Calendar.ckGregorian.dateComponents(CKDayModel.cs, from: date) } fileprivate func chineseDateComponentsCalculate(date: Date) -> DateComponents { return Calendar.ckChinese.dateComponents(CKDayModel.chineseCS, from: date) } var debugDescription: String { guard let year = self.components?.year, let month = self.components?.month, let day = self.components?.day, let cYear = self.chineseComponents?.year, let cMonth = self.chineseComponents?.month, let cDay = self.chineseComponents?.day else { return "type = \(self.type)" } return "type = \(self.type), components = \(year)-\(month)-\(day), chinese = \(cYear)-\(cMonth)-\(cDay), day = \(self.chineseDay!.year)\(self.chineseDay!.month)\(self.chineseDay!.day) weedayName = \(self.weekdayName)\n" } } // MARK: - CalendarKit Extension - /// 自定义格里高利历(或称公历)和农历 /// - Kit计算过程中只使用一下两个历法。公历为主要计算历法,农历是计算农历相关的日期与节日 extension Calendar { /// CalendarKit Day时间戳 static let dayInterval: Double = 86400 // 24 * 60 * 60 fileprivate static var _ckGregorian: Calendar = Calendar(identifier: .gregorian) /// CalendarKit 格里高利历 static var ckGregorian: Calendar { get{ return _ckGregorian } } fileprivate static var _ckChinese: Calendar = Calendar(identifier: .chinese) /// CalendarKit 农历 static var ckChinese: Calendar { get{ return _ckChinese } } /// 周第一天 enum FirstWeekDayType: Int { case sun = 1, mon, tue, wed, thr, fri, sat } // 以下根据周第一天设置名字数组 private static let wdnames = [Bundle.ckLocalizeString(key: "Day1") ?? "Sun", Bundle.ckLocalizeString(key: "Day2") ?? "Mon", Bundle.ckLocalizeString(key: "Day3") ?? "Tue", Bundle.ckLocalizeString(key: "Day4") ?? "Wed", Bundle.ckLocalizeString(key: "Day5") ?? "Thu", Bundle.ckLocalizeString(key: "Day6") ?? "Fri", Bundle.ckLocalizeString(key: "Day7") ?? "Sat"] static var ckWeekdayNames: [String] = [] /// cCalendarKit 第一个工作日 static var ckFirstWeekday: FirstWeekDayType { get { return Calendar.FirstWeekDayType(rawValue: Calendar.ckGregorian.firstWeekday)! } set { _ckGregorian.firstWeekday = newValue.rawValue _ckChinese.firstWeekday = newValue.rawValue var names: [String] = [] var k: Int = newValue.rawValue - 1 for _ in 0 ..< 7 { names.append(self.wdnames[k]) k = k+1 if k == 7 { k = 0 } } self.ckWeekdayNames = names } } /// CalendarKit 时区 static var ckTimeZone: TimeZone { get { return _ckGregorian.timeZone } } } /// Date计算相关的方法 /// - 以下方法全部都进行百万次计算,选择时间最优的方法或者自定义方法 extension Date { /// 获取当前日所在月的天数 /// /// - Returns: 当前月天数 func daysInMonth() -> Int { guard let di = Calendar.ckGregorian.dateInterval(of: .month, for: self) else { return 0 } return Int(di.duration / Calendar.dayInterval) } /// 获取距离当前月数的日期 /// /// - Parameter: interval 月数间隔 /// - Returns: 日期 func dayByInterval(months interval: Int) -> Date { guard let date = Calendar.ckGregorian.date(byAdding: .month, value: interval, to: self, wrappingComponents: false) else { return self } return date } /// 获取距离当前周数的日期 /// /// - Parameter: interval 周数间隔 /// - Returns: 日期 func dayByInterval(weeks interval: Double) -> Date { return self.dayByInterval(days: interval * 7) } /// 获取距离当前天数的日期 /// /// - Parameter: interval 天数间隔 /// - Returns: 日期 func dayByInterval(days interval: Double) -> Date { return self.addingTimeInterval(TimeInterval(Calendar.dayInterval * interval)) } /// 获取当前日所在月的 每一天的数据 /// /// - Returns: 当月的每一天的数据 func modelInMonth() -> [CKDayModel] { // di.start 本月1号0点 di.end下月1号0点 guard let di = Calendar.ckGregorian.dateInterval(of: .month, for: self), let startInWeek = Calendar.ckGregorian.ordinality(of: .day, in: .weekOfMonth, for: di.start), let endInWeek = Calendar.ckGregorian.ordinality(of: .day, in: .weekOfMonth, for: di.end) else { return [] } var result: [CKDayModel] = [] // 计算当前月第一周包含上月的数据,如果第一天是FirstWeekday就不再计算 print(startInWeek) if startInWeek >= 2 { for i in 1 ... startInWeek - 1 { let model: CKDayModel = CKDayModel(type: .pre, date: di.start.dayByInterval(days: Double(-1 * i))) result.insert(model, at: 0) } } // 计算当前月 的数据 for i in 0 ..< Int(di.duration / Calendar.dayInterval) { let model: CKDayModel = CKDayModel(type: .current, date: di.start.dayByInterval(days: Double(i))) result.append(model) } // 计算当前月最后一周包含下月的数据,如果是下个月第一天是FirstWeekday就不算在最后一周。 if endInWeek > 1 { for i in 0 ..< 7 + 1 - endInWeek { let model: CKDayModel = CKDayModel(type: .sub, date: di.end.dayByInterval(days: Double(i))) result.append(model) } } return result } /// 周名称 func weekdayName() -> String { guard let index = Calendar.ckGregorian.ordinality(of: .day, in: .weekOfMonth, for: self) else { return "error name" } guard Calendar.ckWeekdayNames.count == 7 else { return "\(index)" } return Calendar.ckWeekdayNames[index-1] } fileprivate static let _ckFromatter = DateFormatter() /// Date to String /// /// - Parameters: /// - date: 日期 /// - format: 格式 (yyyy-MM-dd) /// - timezome: 时区 (TimeZone.current) /// - Returns: 对应字符串 func string(from date: Date, format: String = "yyyy-MM-dd", timezome: TimeZone = TimeZone.current) -> String{ Date._ckFromatter.dateFormat = format Date._ckFromatter.timeZone = timezome return Date._ckFromatter.string(from: date) } /// String to Date /// /// - Parameters: /// - string: 字符串 /// - format: 格式 (yyyy-MM-dd) /// - timezome: 时区 (TimeZone.current) /// - Returns: 对应日期 func date(from string: String, format: String = "yyyy-MM-dd", timezome: TimeZone = TimeZone.current) -> Date? { Date._ckFromatter.dateFormat = format Date._ckFromatter.timeZone = timezome return Date._ckFromatter.date(from: string) } }
mit
b41d9641bf206e154564926533e35241
29.765537
227
0.548343
3.644913
false
false
false
false
mightydeveloper/swift
validation-test/compiler_crashers_fixed/2254-swift-type-walk.swift
13
586
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d { protocol A { class c : l : f { } class n : AnyObject) { } let v) -> { } class func c<T : f : d : Int = F extension String { } protocol A { struct S { } typealias R = .f l<T: () -> A { var f { self..substringWithRange((self..a<D> k where d: e(T, i == " } protocol d where f: P { func s p : P { protocol g == { func d.e : e, e } f : e} } protocol f : a { let a: c
apache-2.0
23ae11c7699fb3112555b365a9c8c6c1
17.3125
87
0.619454
2.84466
false
true
false
false
xuzhenguo/LayoutComposer
Example/LayoutComposer/VBoxExampleViewController.swift
1
10051
// // VBoxExampleViewController.swift // LayoutComposer // // Created by Yusuke Kawakami on 2015/08/22. // Copyright (c) 2015年 CocoaPods. All rights reserved. // import UIKit import LayoutComposer enum VBoxExampleType: Int { case Basic case Margin case DefaultMargin case Flex case AlignStart case AlignEnd case AlignCenter case AlignStretch case AlignEachComponent case PackStart case PackEnd case PackCenter case PackFit } class VBoxExampleViewController: ExampleViewController { let exampleType: VBoxExampleType init(exampleType: VBoxExampleType, headerTitle: String) { self.exampleType = exampleType super.init(headerTitle: headerTitle) } required init(coder aDecoder: NSCoder) { fatalError("not supported") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func loadView() { super.loadView() switch exampleType { case .Basic: layoutExampleBasic() case .Margin: layoutExampleMargin() case .DefaultMargin: layoutExampleDefaultMargin() case .Flex: layoutExampleFlex() case .AlignStart: layoutExampleAlignStart() case .AlignEnd: layoutExampleAlignEnd() case .AlignCenter: layoutExampleAlignCenter() case .AlignStretch: layoutExampleAlignStretch() case .AlignEachComponent: layoutExampleAlignEachComponent() case .PackStart: layoutExamplePackStart() case .PackEnd: layoutExamplePackEnd() case .PackCenter: layoutExamplePackCenter() case .PackFit: layoutExamplePackFit() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func layoutExampleBasic() { let view1 = makeItemView(title: "view1 height: 50", color: UIColor.redColor()) let view2 = makeItemView(title: "view2 height: 100", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3 flex: 1", color: UIColor.blueColor()) let view4 = makeItemView(title: "view4 flex: 2", color: UIColor.yellowColor()) contentView.applyLayout(VBox(), items: [ $(view1, height: 50), $(view2, height: 100), $(view3, flex: 1), $(view4, flex: 2) ]) } private func layoutExampleMargin() { let view1 = makeItemView(title: "view1 marginTop: 10", color: UIColor.redColor()) let view2 = makeItemView(title: "view2 marginTop: 10, marginLeft: 20, marginRight: 30", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3 margins: (10, 30, 0, 20)", color: UIColor.blueColor()) contentView.applyLayout(VBox(), items: [ $(view1, height: 50, marginTop: 10), $(view2, height: 100, marginTop: 10, marginLeft: 20, marginRight: 30), $(view3, height: 75, margins: (10, 30, 0, 20)) ]) } private func layoutExampleDefaultMargin() { let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3", color: UIColor.blueColor()) contentView.applyLayout(VBox(defaultMargins: (10, 20, 0, 20)), items: [ $(view1, height: 50), $(view2, height: 100), $(view3, height: 75) ]) } private func layoutExampleFlex() { let view1 = makeItemView(title: "view1 height: 50", color: UIColor.redColor()) let view2 = makeItemView(title: "view2 flex: 1", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3 flex: 3", color: UIColor.blueColor()) let view4 = makeItemView(title: "view3 flex: 2", color: UIColor.yellowColor()) contentView.applyLayout(VBox(defaultMargins: (10, 20, 0, 20)), items: [ $(view1, height: 50), $(view2, flex: 1), $(view3, flex: 3), $(view4, flex: 2) ]) } private func layoutExampleAlignStart() { let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3", color: UIColor.blueColor()) contentView.applyLayout(VBox(defaultMargins: (10, 0, 0, 0), align: .Start), items: [ $(view1, width: 50, height: 50), $(view2, width: 100, height: 50), $(view3, width: 200, height: 100) ]) } private func layoutExampleAlignEnd() { let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3", color: UIColor.blueColor()) contentView.applyLayout(VBox(defaultMargins: (10, 0, 0, 0), align: .End), items: [ $(view1, width: 50, height: 50), $(view2, width: 100, height: 50), $(view3, width: 200, height: 100) ]) } private func layoutExampleAlignCenter() { let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3", color: UIColor.blueColor()) contentView.applyLayout(VBox(defaultMargins: (10, 0, 0, 0), align: .Center), items: [ $(view1, width: 50, height: 50), $(view2, width: 100, height: 50), $(view3, width: 200, height: 100) ]) } private func layoutExampleAlignStretch() { let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3 (if width is set align centered)", color: UIColor.blueColor()) contentView.applyLayout(VBox(defaultMargins: (10, 0, 0, 0), align: .Stretch), items: [ $(view1, height: 50), $(view2, height: 50), $(view3, width: 250, height: 100) ]) } private func layoutExampleAlignEachComponent() { let view1 = makeItemView(title: "view1 align: .Start", color: UIColor.redColor()) let view2 = makeItemView(title: "view2 align: .Center", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3 align: .End", color: UIColor.blueColor()) let view4 = makeItemView(title: "view4 (Default if width is set)", color: UIColor.yellowColor()) let view5 = makeItemView(title: "view5 (Default if width is not set)", color: UIColor.magentaColor()) contentView.applyLayout(VBox(defaultMargins: (10, 0, 0, 0)), items: [ $(view1, width: 200, flex: 1, align: .Start), $(view2, width: 200, flex: 1, align: .Center), $(view3, width: 200, flex: 1, align: .End), $(view4, width: 200, flex: 1), $(view5, flex: 1), ]) } private func layoutExamplePackStart() { let container = UIView() container.backgroundColor = UIColor.lightGrayColor() let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3", color: UIColor.blueColor()) contentView.applyLayout(VBox(), item: $(container, height: 400, layout: VBox(defaultMargins: (10, 0, 0, 0), pack: .Start), items: [ $(view1, height: 50), $(view2, height: 50), $(view3, height: 100) ]) ) } private func layoutExamplePackCenter() { let container = UIView() container.backgroundColor = UIColor.lightGrayColor() let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3", color: UIColor.blueColor()) contentView.applyLayout(VBox(), item: $(container, height: 400, layout: VBox(defaultMargins: (10, 0, 0, 0), pack: .Center), items: [ $(view1, height: 50), $(view2, height: 50), $(view3, height: 100) ]) ) } private func layoutExamplePackEnd() { let container = UIView() container.backgroundColor = UIColor.lightGrayColor() let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3", color: UIColor.blueColor()) contentView.applyLayout(VBox(), item: $(container, height: 400, layout: VBox(defaultMargins: (10, 0, 0, 0), pack: .End), items: [ $(view1, height: 50), $(view2, height: 50), $(view3, height: 100) ]) ) } private func layoutExamplePackFit() { let container = UIView() container.backgroundColor = UIColor.lightGrayColor() let view1 = makeItemView(title: "view1", color: UIColor.redColor()) let view2 = makeItemView(title: "view2", color: UIColor.greenColor()) let view3 = makeItemView(title: "view3", color: UIColor.blueColor()) contentView.applyLayout(VBox(), item: $(container, layout: VBox(defaultMargins: (10, 0, 0, 0), pack: .Fit), items: [ // container height is adjusted to fit items. $(view1, height: 50), $(view2, height: 50), $(view3, height: 100) ]) ) } }
mit
7f483fea563489fb13590adb7b60fe8b
36.920755
136
0.593492
4.174907
false
false
false
false