repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringlengths
1
3
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
piv199/LocalisysChat
LocalisysChat/Sources/Modules/Common/Chat/Components/LocalisysChatToolbarView.swift
1
2699
// // ToolbarView.swift // LocalisysChat // // Created by Olexii Pyvovarov on 6/26/17. // Copyright © 2017 Olexii Pyvovarov. All rights reserved. // import UIKit final class LocalisysChatToolbarView: UIView { // MARK: - UI internal lazy var textArea: AutoTextView = ChatTextInputArea() internal var actionButtons: [ChatActionButton] = [] internal lazy var sendButton: ChatSendButton = ChatSendButton() // MARK: - Properties fileprivate var isInWriteMode: Bool { return !textArea.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } // MARK: - Lifecycle override init(frame: CGRect = .zero) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } fileprivate func setupUI() { backgroundColor = .clear [[textArea, sendButton], actionButtons].flatten().forEach(addSubview) } // MARK: - Actions // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() [[sendButton], actionButtons].flatten().forEach { (view: UIView) in view.sizeToFit() } var currentMaxX = bounds.width - 24.0 let minHeight: CGFloat = 44.0 if isInWriteMode || actionButtons.count == 0 { currentMaxX -= sendButton.bounds.width sendButton.frame = CGRect(origin: .init(x: bounds.width - 24.0 - sendButton.bounds.width, y: (bounds.height - minHeight) + (minHeight - sendButton.bounds.height) / 2.0), size: sendButton.bounds.size) actionButtons.forEach { $0.isHidden = true } sendButton.isHidden = false currentMaxX -= 12.0 // sendButton.isEnabled = isInWriteMode } else { for additionButton in actionButtons { currentMaxX -= additionButton.bounds.width additionButton.frame = CGRect(x: currentMaxX, y: (bounds.height - minHeight) + (minHeight - additionButton.bounds.height) / 2.0, width: additionButton.bounds.width, height: additionButton.bounds.height) currentMaxX -= 12.0 } sendButton.isHidden = true actionButtons.forEach { $0.isHidden = false } } let textAreaWidth = currentMaxX - 24.0 let textAreaHeight = textArea.expectedHeight textArea.frame = CGRect(x: 24.0, y: (bounds.height - textAreaHeight) / 2.0, width: textAreaWidth, height: textAreaHeight) } override func sizeThatFits(_ size: CGSize) -> CGSize { return .init(width: size.width, height: max(min(textArea.expectedHeight, size.height), 44.0)) } }
unlicense
e6647ee55de3a5dd1b2fffc48704bf90
30.741176
125
0.63195
4.474295
false
false
false
false
cplaverty/KeitaiWaniKani
WaniKaniKit/Database/Table/KanjiTable.swift
1
1231
// // KanjiTable.swift // WaniKaniKit // // Copyright © 2017 Chris Laverty. All rights reserved. // final class KanjiTable: Table, SubjectTable { let id = Column(name: "id", type: .int, nullable: false, primaryKey: true) let createdAt = Column(name: "created_at", type: .float, nullable: false) let level = Column(name: "level", type: .int, nullable: false) let slug = Column(name: "slug", type: .text, nullable: false) let hiddenAt = Column(name: "hidden_at", type: .float) let documentURL = Column(name: "document_url", type: .text, nullable: false) let characters = Column(name: "characters", type: .text, nullable: false) let meaningMnemonic = Column(name: "meaning_mnemonic", type: .text, nullable: false) let meaningHint = Column(name: "meaning_hint", type: .text, nullable: true) let readingMnemonic = Column(name: "reading_mnemonic", type: .text, nullable: false) let readingHint = Column(name: "reading_hint", type: .text, nullable: true) let lessonPosition = Column(name: "lesson_position", type: .int, nullable: false) init() { super.init(name: "kanji", indexes: [TableIndex(name: "idx_kanji_by_level", columns: [level])]) } }
mit
0e51a4ff07a4520341b0b0347d08041e
46.307692
88
0.65935
3.596491
false
false
false
false
hedjirog/QiitaFeed
Pods/ReactiveCocoa/ReactiveCocoa/Swift/Atomic.swift
1
1653
// // Atomic.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-06-10. // Copyright (c) 2014 GitHub. All rights reserved. // /// An atomic variable. internal final class Atomic<T> { private var spinlock = OS_SPINLOCK_INIT private var _value: T /// Atomically gets or sets the value of the variable. var value: T { get { lock() let v = _value unlock() return v } set(newValue) { lock() _value = newValue unlock() } } /// Initializes the variable with the given initial value. init(_ value: T) { _value = value } private func lock() { withUnsafeMutablePointer(&spinlock, OSSpinLockLock) } private func unlock() { withUnsafeMutablePointer(&spinlock, OSSpinLockUnlock) } /// Atomically replaces the contents of the variable. /// /// Returns the old value. func swap(newValue: T) -> T { return modify { _ in newValue } } /// Atomically modifies the variable. /// /// Returns the old value. func modify(action: T -> T) -> T { let (oldValue, _) = modify { oldValue in (action(oldValue), 0) } return oldValue } /// Atomically modifies the variable. /// /// Returns the old value, plus arbitrary user-defined data. func modify<U>(action: T -> (T, U)) -> (T, U) { lock() let oldValue: T = _value let (newValue, data) = action(_value) _value = newValue unlock() return (oldValue, data) } /// Atomically performs an arbitrary action using the current value of the /// variable. /// /// Returns the result of the action. func withValue<U>(action: T -> U) -> U { lock() let result = action(_value) unlock() return result } }
mit
d82e03574c68acb5fd8b80db94c326d6
18.678571
75
0.638234
3.292829
false
false
false
false
hacktoolkit/htk-ios-Twitter
Twitter/AppDelegate.swift
1
3058
// // AppDelegate.swift // Twitter // // Created by Jonathan Tsai on 9/26/14. // Copyright (c) 2014 Hacktoolkit. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var storyboard = UIStoryboard(name: "Main", bundle: nil) func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. NSNotificationCenter.defaultCenter().addObserver(self, selector: "userDidLogout", name: TWITTER_USER_DID_LOGOUT_NOTIFICATION, object: nil) if TwitterUser.currentUser != nil { // Go to the logged in screen NSLog("Current user detected: \(TwitterUser.currentUser?.name)") var vc = storyboard.instantiateViewControllerWithIdentifier("TwitterNavigationController") as UIViewController window?.rootViewController = vc } return true } func userDidLogout() { var vc = storyboard.instantiateInitialViewController() as UIViewController window?.rootViewController = vc } 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:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String, annotation: AnyObject?) -> Bool { TwitterClient.sharedInstance.openURL(url) return true } }
mit
a4a1a5e7d7ce26fef20d32eaf47aa27b
46.046154
285
0.736102
5.56
false
false
false
false
srn214/Floral
Floral/Pods/CLImagePickerTool/CLImagePickerTool/CLImagePickerTool/AnotherPickView/CLImagePickerAnotherViewController.swift
2
7276
// // CLImagePickerAnotherViewController.swift // CLImagePickerTool // // Created by darren on 2017/11/17. // Copyright © 2017年 陈亮陈亮. All rights reserved. // import UIKit import Photos class CLImagePickerAnotherViewController: UIViewController { @IBOutlet weak var sureBtn: UIButton! @IBOutlet weak var cancelBtn: UIButton! @IBOutlet weak var resetBtn: UIButton! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var bottomHYS: NSLayoutConstraint! @objc let imageCellID = "imagecellID" // 是否隐藏视频文件,默认不隐藏 @objc public var isHiddenVideo: Bool = false // 是否隐藏图片文件,显示视频文件,默认不隐藏 @objc public var isHiddenImage: Bool = false // 视频和照片只能选择一种,不能同时选择,默认可以同时选择 @objc var onlyChooseImageOrVideo: Bool = false @objc var photoArr: [CLImagePickerPhotoModel]? var MaxImagesCount: Int = 0 @objc var singleChooseImageCompleteClouse: CLImagePickerSingleChooseImageCompleteClouse? override func viewDidLoad() { super.viewDidLoad() self.initView() self.bottomHYS.constant = UIDevice.current.isX() == true ? 50 + 34:50 CLNotificationCenter.addObserver(self, selector: #selector(CLImagePickerAnotherViewController.PreviewForSelectOrNotSelectedNoticFunc), name: NSNotification.Name(rawValue:PreviewForSelectOrNotSelectedNotic), object: nil) } deinit { CLNotificationCenter.removeObserver(self) } @objc func PreviewForSelectOrNotSelectedNoticFunc(notic:Notification) { let modelPreView = notic.object as! PreviewModel for model in (self.photoArr ?? []) { if model.phAsset == modelPreView.phAsset { model.isSelect = modelPreView.isCheck } } if CLPickersTools.instence.getSavePictureCount() > 0 { let title = "\(sureStr)(\(CLPickersTools.instence.getSavePictureCount()))" self.sureBtn.setTitle(title, for: .normal) self.sureBtn.isEnabled = true self.resetBtn.isEnabled = true } else { self.sureBtn.isEnabled = false self.resetBtn.isEnabled = false } self.collectionView.reloadData() } func initView() { // 存储用户设置的最多图片数量 UserDefaults.standard.set(MaxImagesCount, forKey: CLImagePickerMaxImagesCount) UserDefaults.standard.synchronize() CLPickersTools.instence.isHiddenVideo = isHiddenVideo // 是否隐藏视频文件赋值 CLPickersTools.instence.isHiddenImage = isHiddenImage // 清除保存的数据 CLPickersTools.instence.clearPicture() // 如果用户之前设置的是onlyChooseImageOrVideo类型,记得将这个类型刚开始就置空 UserDefaults.standard.set(0, forKey: UserChooserType) UserDefaults.standard.synchronize() self.resetBtn.setTitle(resetStr, for: .normal) self.sureBtn.setTitle(sureStr, for: .normal) self.cancelBtn.setTitle(cancelStr, for: .normal) if CLPickersTools.instence.getSavePictureCount() > 0 { let title = "\(sureStr)(\(CLPickersTools.instence.getSavePictureCount()))" self.sureBtn.setTitle(title, for: .normal) self.sureBtn.isEnabled = true self.resetBtn.isEnabled = true } else { self.sureBtn.isEnabled = false self.resetBtn.isEnabled = false } let flowout = UICollectionViewFlowLayout.init() self.collectionView.collectionViewLayout = flowout flowout.scrollDirection = .horizontal flowout.minimumInteritemSpacing = 10 self.collectionView.register(UINib.init(nibName: "ImagePickerChooseImageCellV2", bundle: BundleUtil.getCurrentBundle()), forCellWithReuseIdentifier: imageCellID) self.photoArr = CLPickersTools.instence.loadPhotoForAll().first?.values.first?.reversed() self.collectionView.reloadData() } @IBAction func clickSureBtn(_ sender: Any) { self.dismiss(animated: true) { if self.singleChooseImageCompleteClouse != nil { self.singleChooseImageCompleteClouse!(CLPickersTools.instence.getChoosePictureArray(),nil) } } } @IBAction func clickResetBtn(_ sender: Any) { if self.photoArr != nil { for model in self.photoArr! { model.isSelect = false } } CLPickersTools.instence.clearPicture() self.resetBtn.isEnabled = false self.sureBtn.isEnabled = false self.sureBtn.setTitle(sureStr, for: .normal) if self.onlyChooseImageOrVideo { for model in (self.photoArr ?? []) { model.onlyChooseImageOrVideo = false } // 重置选择的类型 UserDefaults.standard.set(0, forKey: UserChooserType) UserDefaults.standard.synchronize() } self.collectionView.reloadData() } @IBAction func clickCancelBtn(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func clickEditorBtn(_ sender: Any) { } @IBAction func clickPhotoBtn(_ sender: Any) { } } extension CLImagePickerAnotherViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.photoArr?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let model = self.photoArr?[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imageCellID, for: indexPath) as! ImagePickerChooseImageCellV2 cell.onlyChooseImageOrVideo = self.onlyChooseImageOrVideo cell.model = model cell.imagePickerChooseImage = {[weak self] () in let chooseCount = CLPickersTools.instence.getSavePictureCount() if chooseCount == 0 { self?.sureBtn.setTitle(sureStr, for: .normal) self?.sureBtn.isEnabled = false self?.resetBtn.isEnabled = false } else { self?.sureBtn.setTitle("\(sureStr)(\(chooseCount))", for: .normal) self?.sureBtn.isEnabled = true self?.resetBtn.isEnabled = true } } return cell } func collectionView(_ collectionView: UICollectionView, layout:UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let model = self.photoArr![indexPath.row] var W: CGFloat = (CGFloat(model.phAsset?.pixelWidth ?? 0)) let H: CGFloat = CGFloat(model.phAsset?.pixelHeight ?? 0) if W / H < 1 { W = KScreenWidth/3.2 } else { W = KScreenWidth/1.2 } return CGSize(width: W, height: 230) } }
mit
58fd23e3047ce8a88308d6b8c7b508fa
35.546875
227
0.640587
5.140659
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureRecognizer/Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/BinaryDelimited.swift
4
8486
// Sources/SwiftProtobuf/BinaryDelimited.swift - Delimited support // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Helpers to read/write message with a length prefix. /// // ----------------------------------------------------------------------------- import Foundation /// Helper methods for reading/writing messages with a length prefix. public enum BinaryDelimited { /// Additional errors for delimited message handing. public enum Error: Swift.Error { /// If a read/write to the stream fails, but the stream's `streamError` is nil, /// this error will be throw instead since the stream didn't provide anything /// more specific. A common cause for this can be failing to open the stream /// before trying to read/write to it. case unknownStreamError /// While reading/writing to the stream, less than the expected bytes was /// read/written. case truncated } /// Serialize a single size-delimited message from the given stream. Delimited /// format allows a single file or stream to contain multiple messages, /// whereas normally writing multiple non-delimited messages to the same /// stream would cause them to be merged. A delimited message is a varint /// encoding the message size followed by a message of exactly that size. /// /// - Parameters: /// - message: The message to be written. /// - to: The `OutputStream` to write the message to. The stream is /// is assumed to be ready to be written to. /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - Throws: `BinaryEncodingError` if encoding fails, throws /// `BinaryDelimited.Error` for some writing errors, or the /// underlying `OutputStream.streamError` for a stream error. public static func serialize( message: Message, to stream: OutputStream, partial: Bool = false ) throws { // TODO: Revisit to avoid the extra buffering when encoding is streamed in general. let serialized = try message.serializedData(partial: partial) let totalSize = Varint.encodedSize(of: UInt64(serialized.count)) + serialized.count var data = Data(count: totalSize) data.withUnsafeMutableBytes { (pointer: UnsafeMutablePointer<UInt8>) in var encoder = BinaryEncoder(forWritingInto: pointer) encoder.putBytesValue(value: serialized) } var written: Int = 0 data.withUnsafeBytes { (pointer: UnsafePointer<UInt8>) in written = stream.write(pointer, maxLength: totalSize) } if written != totalSize { if written == -1 { if let streamError = stream.streamError { throw streamError } throw BinaryDelimited.Error.unknownStreamError } throw BinaryDelimited.Error.truncated } } /// Reads a single size-delimited message from the given stream. Delimited /// format allows a single file or stream to contain multiple messages, /// whereas normally parsing consumes the entire input. A delimited message /// is a varint encoding the message size followed by a message of exactly /// exactly that size. /// /// - Parameters: /// - messageType: The type of message to read. /// - from: The `InputStream` to read the data from. The stream is assumed /// to be ready to read from. /// - extensions: An `ExtensionMap` used to look up and decode any /// extensions in this message or messages nested within this message's /// fields. /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - options: The BinaryDecodingOptions to use. /// - Returns: The message read. /// - Throws: `BinaryDecodingError` if decoding fails, throws /// `BinaryDelimited.Error` for some reading errors, and the /// underlying InputStream.streamError for a stream error. public static func parse<M: Message>( messageType: M.Type, from stream: InputStream, extensions: ExtensionMap? = nil, partial: Bool = false, options: BinaryDecodingOptions = BinaryDecodingOptions() ) throws -> M { var message = M() try merge(into: &message, from: stream, extensions: extensions, partial: partial, options: options) return message } /// Updates the message by reading a single size-delimited message from /// the given stream. Delimited format allows a single file or stream to /// contain multiple messages, whereas normally parsing consumes the entire /// input. A delimited message is a varint encoding the message size /// followed by a message of exactly that size. /// /// - Note: If this method throws an error, the message may still have been /// partially mutated by the binary data that was decoded before the error /// occurred. /// /// - Parameters: /// - mergingTo: The message to merge the data into. /// - from: The `InputStream` to read the data from. The stream is assumed /// to be ready to read from. /// - extensions: An `ExtensionMap` used to look up and decode any /// extensions in this message or messages nested within this message's /// fields. /// - partial: If `false` (the default), this method will check /// `Message.isInitialized` before encoding to verify that all required /// fields are present. If any are missing, this method throws /// `BinaryEncodingError.missingRequiredFields`. /// - options: The BinaryDecodingOptions to use. /// - Throws: `BinaryDecodingError` if decoding fails, throws /// `BinaryDelimited.Error` for some reading errors, and the /// underlying InputStream.streamError for a stream error. public static func merge<M: Message>( into message: inout M, from stream: InputStream, extensions: ExtensionMap? = nil, partial: Bool = false, options: BinaryDecodingOptions = BinaryDecodingOptions() ) throws { let length = try Int(decodeVarint(stream)) if length == 0 { // The message was all defaults, nothing to actually read. return } var data = Data(count: length) var bytesRead: Int = 0 data.withUnsafeMutableBytes { (pointer: UnsafeMutablePointer<UInt8>) in bytesRead = stream.read(pointer, maxLength: length) } if bytesRead != length { if bytesRead == -1 { if let streamError = stream.streamError { throw streamError } throw BinaryDelimited.Error.unknownStreamError } throw BinaryDelimited.Error.truncated } try message.merge(serializedData: data, extensions: extensions, partial: partial, options: options) } } // TODO: This should go away when encoding/decoding are more stream based // as that should provide a more direct way to do this. This is basically // a rewrite of BinaryDecoder.decodeVarint(). internal func decodeVarint(_ stream: InputStream) throws -> UInt64 { // Buffer to reuse within nextByte. var readBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 1) defer { readBuffer.deallocate(capacity: 1) } func nextByte() throws -> UInt8 { let bytesRead = stream.read(readBuffer, maxLength: 1) if bytesRead != 1 { if bytesRead == -1 { if let streamError = stream.streamError { throw streamError } throw BinaryDelimited.Error.unknownStreamError } throw BinaryDelimited.Error.truncated } return readBuffer[0] } var value: UInt64 = 0 var shift: UInt64 = 0 while true { let c = try nextByte() value |= UInt64(c & 0x7f) << shift if c & 0x80 == 0 { return value } shift += 7 if shift > 63 { throw BinaryDecodingError.malformedProtobuf } } }
mit
ada5634ae741882f81311a4acf01c939
38.654206
87
0.660382
4.727577
false
false
false
false
VaclavLustek/VLFramework
Pod/Classes/View/Table/Cells/VLBaseCell.swift
1
2283
// // VLBaseCell.swift // Pods // // Created by Václav Luštěk. // // // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Import import UIKit // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Settings // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Constants // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Class public class VLBaseCell: UITableViewCell { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Properties @IBOutlet private weak var titleLabel: UILabel! public var titleText: String? = nil { didSet { self.titleLabel.text = titleText } } @IBOutlet private weak var subtitleLabel: UILabel! public var subtitleText: String? = nil { didSet { self.subtitleLabel.text = subtitleText } } @IBOutlet private weak var mainIV: UIImageView! public var mainImage: UIImage? = nil { didSet { self.mainIV.image = mainImage; } } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Layout public override var bounds: CGRect { didSet { self.contentView.bounds = bounds } } public override func layoutSubviews() { super.layoutSubviews() self.contentView.setNeedsUpdateConstraints() self.contentView.updateConstraintsIfNeeded() self.contentView.setNeedsLayout() self.contentView.layoutIfNeeded() if let titleLabel: UILabel = self.titleLabel { titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(titleLabel.bounds) } if let subtitleLabel: UILabel = self.subtitleLabel { subtitleLabel.preferredMaxLayoutWidth = CGRectGetWidth(subtitleLabel.bounds) } } }
mit
3939d10e629510368a616f1d27bb29e7
20.923077
114
0.404825
4.710744
false
false
false
false
svdo/swift-SecurityExtensions
SecurityExtensionsTests/SecKey+KeychainTests.swift
1
1060
// Copyright (c) 2016 Stefan van den Oord. All rights reserved. import Quick import Nimble import SecurityExtensions class SecKey_KeychainTests: QuickSpec { override func spec() { it("can return the keychain tag of a key") { let keys = testKeyPair() expect(keys.privateKey.keychainTag) != "" expect(keys.publicKey.keychainTag) != "" } it("can retrieve a key by tag") { let keys = testKeyPair() let privTag = keys.privateKey.keychainTag let pubTag = keys.publicKey.keychainTag expect(privTag).toNot(beNil()) expect(pubTag).toNot(beNil()) if let privTag = privTag, let pubTag = pubTag { let retrievedPrivKey = SecKey.loadFromKeychain(tag: privTag) let retrievedPubKey = SecKey.loadFromKeychain(tag: pubTag) expect(retrievedPrivKey?.keyData) == keys.privateKey.keyData expect(retrievedPubKey?.keyData) == keys.publicKey.keyData } } } }
mit
0c9a837382c329e41529a7ee00e8abc1
35.551724
76
0.601887
4.549356
false
true
false
false
kickstarter/ios-oss
Library/ViewModels/ManagePledgeViewModel.swift
1
21169
import KsApi import Prelude import ReactiveExtensions import ReactiveSwift public typealias ManagePledgeViewParamConfigData = ( projectParam: Param, backingParam: Param? ) public enum ManagePledgeAlertAction: CaseIterable { case updatePledge case changePaymentMethod case chooseAnotherReward case contactCreator case cancelPledge case viewRewards } public protocol ManagePledgeViewModelInputs { func beginRefresh() func configureWith(_ params: ManagePledgeViewParamConfigData) func cancelPledgeDidFinish(with message: String) func fixButtonTapped() func menuButtonTapped() func menuOptionSelected(with action: ManagePledgeAlertAction) func pledgeViewControllerDidUpdatePledgeWithMessage(_ message: String) func viewDidLoad() } public protocol ManagePledgeViewModelOutputs { var configurePaymentMethodView: Signal<ManagePledgePaymentMethodViewData, Never> { get } var configurePledgeSummaryView: Signal<ManagePledgeSummaryViewData, Never> { get } var configureRewardReceivedWithData: Signal<ManageViewPledgeRewardReceivedViewData, Never> { get } var endRefreshing: Signal<Void, Never> { get } var goToCancelPledge: Signal<CancelPledgeViewData, Never> { get } var goToChangePaymentMethod: Signal<PledgeViewData, Never> { get } var goToContactCreator: Signal<(MessageSubject, KSRAnalytics.MessageDialogContext), Never> { get } var goToFixPaymentMethod: Signal<PledgeViewData, Never> { get } var goToRewards: Signal<Project, Never> { get } var goToUpdatePledge: Signal<PledgeViewData, Never> { get } var loadProjectAndRewardsIntoDataSource: Signal<(Project, [Reward]), Never> { get } var loadPullToRefreshHeaderView: Signal<(), Never> { get } var notifyDelegateManagePledgeViewControllerFinishedWithMessage: Signal<String?, Never> { get } var paymentMethodViewHidden: Signal<Bool, Never> { get } var pledgeDetailsSectionLabelText: Signal<String, Never> { get } var pledgeDisclaimerViewHidden: Signal<Bool, Never> { get } var rewardReceivedViewControllerViewIsHidden: Signal<Bool, Never> { get } var rightBarButtonItemHidden: Signal<Bool, Never> { get } var showActionSheetMenuWithOptions: Signal<[ManagePledgeAlertAction], Never> { get } var showErrorBannerWithMessage: Signal<String, Never> { get } var showSuccessBannerWithMessage: Signal<String, Never> { get } var startRefreshing: Signal<(), Never> { get } var title: Signal<String, Never> { get } } public protocol ManagePledgeViewModelType { var inputs: ManagePledgeViewModelInputs { get } var outputs: ManagePledgeViewModelOutputs { get } } public final class ManagePledgeViewModel: ManagePledgeViewModelType, ManagePledgeViewModelInputs, ManagePledgeViewModelOutputs { public init() { let params = Signal.combineLatest( self.configureWithProjectOrParamSignal, self.viewDidLoadSignal ) .map(first) let projectParam = params.map(first) let shouldBeginRefresh = Signal.merge( self.pledgeViewControllerDidUpdatePledgeWithMessageSignal.ignoreValues(), self.beginRefreshSignal ) // Keep track of whether the project has successfully loaded at least once. let projectLoaded = MutableProperty<Bool>(false) let shouldFetchProjectWithParam = Signal.merge( projectParam, projectParam.takeWhen(shouldBeginRefresh) ) let fetchProjectEvent = shouldFetchProjectWithParam // Only fetch the project if it hasn't yet succeeded, to avoid this call occurring with each refresh. .filter { [projectLoaded] _ in projectLoaded.value == false } .switchMap { param in AppEnvironment.current.apiService.fetchProject(param: param) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .switchMap { project in fetchProjectRewards(project: project) } .materialize() } let initialProject = fetchProjectEvent.values() // Once we know we have a project value, keep track of that. .on(value: { [projectLoaded] _ in projectLoaded.value = true }) let backingParamFromConfigData = params.map(second) .skipNil() let backingParamFromProject = initialProject.map { $0.personalization.backing?.id } .skipNil() .map(Param.id) let backingParam = Signal.merge( backingParamFromConfigData, backingParamFromProject .take(until: backingParamFromConfigData.ignoreValues()) ) let shouldFetchGraphBackingWithParam = Signal.merge( backingParam, backingParam.takeWhen(shouldBeginRefresh) ) let graphBackingEvent = shouldFetchGraphBackingWithParam .map { param in param.id } .skipNil() .switchMap { backingId in AppEnvironment.current.apiService .fetchBacking(id: backingId, withStoredCards: false) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .materialize() } let graphBackingProject = graphBackingEvent.values() .map { $0.project } let graphBackingEnvelope = graphBackingEvent.values() let backing = graphBackingEnvelope .map { $0.backing } let endRefreshingWhenProjectFailed = fetchProjectEvent.errors() .ignoreValues() let endRefreshingWhenBackingCompleted = graphBackingEvent .filter { $0.isTerminating } .ksr_delay(.milliseconds(300), on: AppEnvironment.current.scheduler) .ignoreValues() self.endRefreshing = Signal.merge( endRefreshingWhenProjectFailed, endRefreshingWhenBackingCompleted ) .ignoreValues() let project = initialProject.combineLatest(with: backing) .map { project, backing -> Project in /** Here we are updating the `Project`'s `Backing` with an updated one from GraphQL. This is because, at the time of writing, v1 does not return add-ons or bonus amount but GraphQL does. */ let p = (project |> Project.lens.personalization.backing .~ backing) return p } let userIsCreatorOfProject = project.map { project in currentUserIsCreator(of: project) } let projectAndReward = Signal.combineLatest(project, backing) .compactMap { project, backing -> (Project, Reward)? in guard let reward = backing.reward else { return (project, .noReward) } return (project, reward) } self.title = graphBackingProject.combineLatest(with: userIsCreatorOfProject) .map(navigationBarTitle(with:userIsCreatorOfProject:)) self.configurePaymentMethodView = backing.map(managePledgePaymentMethodViewData) self.configurePledgeSummaryView = Signal.combineLatest(projectAndReward, backing) .map(unpack) .compactMap(managePledgeSummaryViewData) let projectOrBackingFailedToLoad = Signal.merge( fetchProjectEvent.map { $0.error as Error? }, graphBackingEvent.map { $0.error as Error? } ) .filter(isNotNil) self.loadPullToRefreshHeaderView = projectOrBackingFailedToLoad .take(until: backing.ignoreValues()) .ignoreValues() self.paymentMethodViewHidden = Signal.combineLatest( userIsCreatorOfProject, backing.map { backing in backing.paymentSource } ) .map { userIsCreatorOfProject, creditCard in userIsCreatorOfProject || creditCard == nil } .skipRepeats() self.loadProjectAndRewardsIntoDataSource = projectAndReward.combineLatest(with: backing) .map(unpack) .map { project, reward, backing -> (Project, [Reward]) in (project, distinctRewards([reward] + (backing.addOns ?? []))) } self.rightBarButtonItemHidden = Signal.merge( params.mapConst(true), self.loadPullToRefreshHeaderView.mapConst(true), self.loadProjectAndRewardsIntoDataSource.mapConst(false) ) .skipRepeats() self.pledgeDisclaimerViewHidden = Signal.combineLatest( self.loadProjectAndRewardsIntoDataSource, userIsCreatorOfProject ) .map(unpack) .map { _, rewards, userIsCreatorOfProject in rewards.map { $0.estimatedDeliveryOn }.allSatisfy(isNil) || userIsCreatorOfProject } self.pledgeDetailsSectionLabelText = userIsCreatorOfProject.map { $0 ? Strings.Pledge_details() : Strings.Your_pledge_details() } self.startRefreshing = Signal.merge( params.ignoreValues(), shouldBeginRefresh.ignoreValues() ) let latestRewardDeliveryDate = self.loadProjectAndRewardsIntoDataSource.map { _, rewards in rewards .compactMap { $0.estimatedDeliveryOn } .reduce(0) { accum, value in max(accum, value) } } self.configureRewardReceivedWithData = Signal.combineLatest(project, backing, latestRewardDeliveryDate) .map { project, backing, latestRewardDeliveryDate in ManageViewPledgeRewardReceivedViewData( project: project, backerCompleted: backing.backerCompleted ?? false, estimatedDeliveryOn: latestRewardDeliveryDate, backingState: backing.status ) } let menuOptions = Signal.combineLatest(project, backing, userIsCreatorOfProject) .map(actionSheetMenuOptionsFor(project:backing:userIsCreatorOfProject:)) self.showActionSheetMenuWithOptions = menuOptions .takeWhen(self.menuButtonTappedSignal) let backedRewards = self.loadProjectAndRewardsIntoDataSource.map(second) self.goToUpdatePledge = Signal.combineLatest(project, backing, backedRewards) .takeWhen(self.menuOptionSelectedSignal.filter { $0 == .updatePledge }) .map { project, backing, rewards in (project, backing, rewards, .update) } .map(pledgeViewData) self.goToRewards = project .takeWhen(self.menuOptionSelectedSignal.filter { $0 == .chooseAnotherReward || $0 == .viewRewards }) let cancelPledgeSelected = self.menuOptionSelectedSignal .filter { $0 == .cancelPledge } .ignoreValues() self.goToCancelPledge = Signal.combineLatest(project, backing) .takeWhen(cancelPledgeSelected) .filter { _, backing in backing.cancelable } .map(cancelPledgeViewData(with:backing:)) self.goToContactCreator = project .takeWhen(self.menuOptionSelectedSignal.filter { $0 == .contactCreator }) .map { project in (MessageSubject.project(project), .backerModal) } self.goToChangePaymentMethod = Signal.combineLatest(project, backing, backedRewards) .takeWhen(self.menuOptionSelectedSignal.filter { $0 == .changePaymentMethod }) .map { project, backing, rewards in (project, backing, rewards, .changePaymentMethod) } .map(pledgeViewData) self.goToFixPaymentMethod = Signal.combineLatest(project, backing, backedRewards) .takeWhen(self.fixButtonTappedSignal) .map { project, backing, rewards in (project, backing, rewards, .fixPaymentMethod) } .map(pledgeViewData) self.notifyDelegateManagePledgeViewControllerFinishedWithMessage = Signal.merge( self.cancelPledgeDidFinishWithMessageProperty.signal, backing.skip(first: 1).mapConst(nil) ) self.rewardReceivedViewControllerViewIsHidden = latestRewardDeliveryDate.map { $0 == 0 } self.showSuccessBannerWithMessage = self.pledgeViewControllerDidUpdatePledgeWithMessageSignal let cancelBackingDisallowed = backing .map { $0.cancelable } .filter(isFalse) let attemptedDisallowedCancelBackingMessage = cancelBackingDisallowed .takeWhen(cancelPledgeSelected) .map { _ in // swiftformat:disable wrap Strings.We_dont_allow_cancelations_that_will_cause_a_project_to_fall_short_of_its_goal_within_the_last_24_hours() // swiftformat:enable wrap } let networkErrorMessage = Signal.merge( fetchProjectEvent.errors().ignoreValues(), graphBackingEvent.errors().ignoreValues() ) .map { _ in Strings.Something_went_wrong_please_try_again() } self.showErrorBannerWithMessage = Signal.merge( attemptedDisallowedCancelBackingMessage, networkErrorMessage ) // Tracking Signal.zip(self.loadProjectAndRewardsIntoDataSource, backing) .map(unpack) .observeValues { project, rewards, backing in guard let reward = backing.reward else { return } let checkoutData = checkoutProperties( from: project, baseReward: reward, addOnRewards: rewards, selectedQuantities: selectedRewardQuantities(in: backing), additionalPledgeAmount: backing.bonusAmount, pledgeTotal: backing.amount, shippingTotal: Double(backing.shippingAmount ?? 0), isApplePay: backing.paymentSource?.paymentType == .applePay ) AppEnvironment.current.ksrAnalytics.trackManagePledgePageViewed( project: project, reward: reward, checkoutData: checkoutData ) } } private let (beginRefreshSignal, beginRefreshObserver) = Signal<Void, Never>.pipe() public func beginRefresh() { self.beginRefreshObserver.send(value: ()) } private let (configureWithProjectOrParamSignal, configureWithProjectOrParamObserver) = Signal<ManagePledgeViewParamConfigData, Never>.pipe() public func configureWith(_ params: ManagePledgeViewParamConfigData) { self.configureWithProjectOrParamObserver.send(value: params) } private let cancelPledgeDidFinishWithMessageProperty = MutableProperty<String?>(nil) public func cancelPledgeDidFinish(with message: String) { self.cancelPledgeDidFinishWithMessageProperty.value = message } private let (fixButtonTappedSignal, fixButtonTappedObserver) = Signal<Void, Never>.pipe() public func fixButtonTapped() { self.fixButtonTappedObserver.send(value: ()) } private let (menuButtonTappedSignal, menuButtonTappedObserver) = Signal<Void, Never>.pipe() public func menuButtonTapped() { self.menuButtonTappedObserver.send(value: ()) } private let (menuOptionSelectedSignal, menuOptionSelectedObserver) = Signal<ManagePledgeAlertAction, Never> .pipe() public func menuOptionSelected(with action: ManagePledgeAlertAction) { self.menuOptionSelectedObserver.send(value: action) } private let ( pledgeViewControllerDidUpdatePledgeWithMessageSignal, pledgeViewControllerDidUpdatePledgeWithMessageObserver ) = Signal<String, Never>.pipe() public func pledgeViewControllerDidUpdatePledgeWithMessage(_ message: String) { self.pledgeViewControllerDidUpdatePledgeWithMessageObserver.send(value: message) } private let (viewDidLoadSignal, viewDidLoadObserver) = Signal<(), Never>.pipe() public func viewDidLoad() { self.viewDidLoadObserver.send(value: ()) } public let configurePaymentMethodView: Signal<ManagePledgePaymentMethodViewData, Never> public let configurePledgeSummaryView: Signal<ManagePledgeSummaryViewData, Never> public let configureRewardReceivedWithData: Signal<ManageViewPledgeRewardReceivedViewData, Never> public let endRefreshing: Signal<Void, Never> public let goToCancelPledge: Signal<CancelPledgeViewData, Never> public let goToChangePaymentMethod: Signal<PledgeViewData, Never> public let goToContactCreator: Signal<(MessageSubject, KSRAnalytics.MessageDialogContext), Never> public let goToFixPaymentMethod: Signal<PledgeViewData, Never> public let goToRewards: Signal<Project, Never> public let goToUpdatePledge: Signal<PledgeViewData, Never> public let loadProjectAndRewardsIntoDataSource: Signal<(Project, [Reward]), Never> public let loadPullToRefreshHeaderView: Signal<(), Never> public let paymentMethodViewHidden: Signal<Bool, Never> public let pledgeDetailsSectionLabelText: Signal<String, Never> public let pledgeDisclaimerViewHidden: Signal<Bool, Never> public let notifyDelegateManagePledgeViewControllerFinishedWithMessage: Signal<String?, Never> public let rewardReceivedViewControllerViewIsHidden: Signal<Bool, Never> public let rightBarButtonItemHidden: Signal<Bool, Never> public let showActionSheetMenuWithOptions: Signal<[ManagePledgeAlertAction], Never> public let showSuccessBannerWithMessage: Signal<String, Never> public let showErrorBannerWithMessage: Signal<String, Never> public let startRefreshing: Signal<(), Never> public let title: Signal<String, Never> public var inputs: ManagePledgeViewModelInputs { return self } public var outputs: ManagePledgeViewModelOutputs { return self } } // MARK: - Functions private func fetchProjectRewards(project: Project) -> SignalProducer<Project, ErrorEnvelope> { return AppEnvironment.current.apiService .fetchProjectRewards(projectId: project.id) .ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler) .switchMap { projectRewards -> SignalProducer<Project, ErrorEnvelope> in var allRewards = projectRewards if let noRewardReward = project.rewardData.rewards.first { allRewards.insert(noRewardReward, at: 0) } let projectWithBackingAndRewards = project |> Project.lens.rewardData.rewards .~ allRewards return SignalProducer(value: projectWithBackingAndRewards) } } private func pledgeViewData( project: Project, backing: Backing, rewards: [Reward], context: PledgeViewContext ) -> PledgeViewData { return PledgeViewData( project: project, rewards: rewards, selectedQuantities: selectedRewardQuantities(in: backing), selectedLocationId: backing.locationId, refTag: nil, context: context ) } private func actionSheetMenuOptionsFor( project: Project, backing: Backing, userIsCreatorOfProject: Bool ) -> [ManagePledgeAlertAction] { if userIsCreatorOfProject { return [.viewRewards] } guard project.state == .live else { return [.viewRewards, .contactCreator] } if backing.status == .preauth { return [.contactCreator] } return ManagePledgeAlertAction.allCases.filter { $0 != .viewRewards } } private func navigationBarTitle( with project: Project, userIsCreatorOfProject: Bool ) -> String { if userIsCreatorOfProject { return Strings.Pledge_details() } return project.state == .live ? Strings.Manage_your_pledge() : Strings.Your_pledge() } private func managePledgeMenuCTAType(for managePledgeAlertAction: ManagePledgeAlertAction) -> KSRAnalytics.ManagePledgeMenuCTAType { switch managePledgeAlertAction { case .cancelPledge: return .cancelPledge case .changePaymentMethod: return .changePaymentMethod case .chooseAnotherReward: return .chooseAnotherReward case .contactCreator: return .contactCreator case .updatePledge: return .updatePledge case .viewRewards: return .viewRewards } } private func cancelPledgeViewData( with project: Project, backing: Backing ) -> CancelPledgeViewData { return .init( project: project, projectName: project.name, omitUSCurrencyCode: project.stats.omitUSCurrencyCode, backingId: backing.graphID, pledgeAmount: backing.amount ) } private func managePledgePaymentMethodViewData( with backing: Backing ) -> ManagePledgePaymentMethodViewData { ManagePledgePaymentMethodViewData( backingState: backing.status, expirationDate: backing.paymentSource?.expirationDate, lastFour: backing.paymentSource?.lastFour, creditCardType: backing.paymentSource?.type, paymentType: backing.paymentSource?.paymentType ) } private func managePledgeSummaryViewData( with project: Project, backedReward: Reward, backing: Backing ) -> ManagePledgeSummaryViewData? { guard let backer = backing.backer else { return nil } let isRewardLocalPickup = isRewardLocalPickup(backing.reward) let projectCurrencyCountry = projectCountry(forCurrency: project.stats.currency) ?? project.country return ManagePledgeSummaryViewData( backerId: backer.id, backerName: backer.name, backerSequence: backing.sequence, backingState: backing.status, bonusAmount: backing.bonusAmount, currentUserIsCreatorOfProject: currentUserIsCreator(of: project), isNoReward: backedReward.id == Reward.noReward.id, locationName: backing.locationName, needsConversion: project.stats.needsConversion, omitUSCurrencyCode: project.stats.omitUSCurrencyCode, pledgeAmount: backing.amount, pledgedOn: backing.pledgedAt, projectCurrencyCountry: projectCurrencyCountry, projectDeadline: project.dates.deadline, projectState: project.state, rewardMinimum: allRewardsTotal(for: backing), shippingAmount: backing.shippingAmount.flatMap(Double.init), shippingAmountHidden: backing.reward?.shipping.enabled == false, rewardIsLocalPickup: isRewardLocalPickup ) } private func allRewardsTotal(for backing: Backing) -> Double { let baseRewardAmount = backing.reward?.minimum ?? 0 guard let addOns = backing.addOns else { return baseRewardAmount } return baseRewardAmount + addOns.reduce(0.0) { total, addOn in total.addingCurrency(addOn.minimum) } } private func distinctRewards(_ rewards: [Reward]) -> [Reward] { var rewardIds: Set<Int> = [] return rewards.filter { reward in defer { rewardIds.insert(reward.id) } return !rewardIds.contains(reward.id) } }
apache-2.0
d1600e14863d1ed4e630548e5ab14b19
36.008741
121
0.742973
4.866437
false
false
false
false
apple/swift-nio
Sources/NIOCore/FileDescriptor.swift
1
1278
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// public protocol FileDescriptor { /// Will be called with the file descriptor if still open, if not it will /// throw an `IOError`. /// /// The ownership of the file descriptor must not escape the `body` as it's completely managed by the /// implementation of the `FileDescriptor` protocol. /// /// - parameters: /// - body: The closure to execute if the `FileDescriptor` is still open. /// - throws: If either the `FileDescriptor` was closed before or the closure throws by itself. func withUnsafeFileDescriptor<T>(_ body: (CInt) throws -> T) throws -> T /// `true` if this `FileDescriptor` is open (which means it was not closed yet). var isOpen: Bool { get } /// Close this `FileDescriptor`. func close() throws }
apache-2.0
daa74d696b7d2f16c7d406b9d4d2c797
36.588235
105
0.595462
4.877863
false
false
false
false
kvedula/WWDC2015
Kamesh Vedula/TimelineView.swift
1
12750
// // TimelineView.swift // Kamesh Vedula // // Created by Kamesh Vedula on 4/25/15. // Copyright (c) Kamesh Vedula. All rights reserved. // import UIKit /** Represents an instance in the Timeline. A Timeline is built using one or more of these TimeFrames. */ public struct TimeFrame{ /** A description of the event. */ let text: String /** The date that the event occured. */ let date: String /** An optional image to show with the text and the date in the timeline. */ let image: UIImage? } /** The shape of a bullet that appears next to each event in the Timeline. */ public enum BulletType{ /** Bullet shaped as a diamond with no fill. */ case Diamond } /** View that shows the given events in bullet form. */ public class TimelineView: UIView { //MARK: Public Properties /** The events shown in the Timeline */ public var timeFrames: [TimeFrame]{ didSet{ setupContent() } } /** The color of the bullets and the lines connecting them. */ public var lineColor: UIColor = UIColor.lightGrayColor(){ didSet{ setupContent() } } /** Color of the larger Date title label in each event. */ public var titleLabelColor: UIColor = UIColor(red: 0/255, green: 131/255, blue: 122/255, alpha: 1){ didSet{ setupContent() } } /** Color of the smaller Text detail label in each event. */ public var detailLabelColor: UIColor = UIColor(red: 110/255, green: 110/255, blue: 110/255, alpha: 1){ didSet{ setupContent() } } /** The type of bullet shown next to each element. */ public var bulletType: BulletType = BulletType.Diamond{ didSet{ setupContent() } } //MARK: Private Properties private var imageViewer: JTSImageViewController? //MARK: Public Methods /** Note that the timeFrames cannot be set by this method. Further setup is required once this initalization occurs. May require more work to allow this to work with restoration. @param coder An unarchiver object. */ required public init(coder aDecoder: NSCoder) { timeFrames = [] super.init(coder: aDecoder) } /** Initializes the timeline with all information needed for a complete setup. @param bulletType The type of bullet shown next to each element. @param timeFrames The events shown in the Timeline */ public init(bulletType: BulletType, timeFrames: [TimeFrame]){ self.timeFrames = timeFrames self.bulletType = bulletType super.init(frame: CGRect.zeroRect) setTranslatesAutoresizingMaskIntoConstraints(false) setupContent() } //MARK: Private Methods private func setupContent(){ for v in subviews{ v.removeFromSuperview() } let guideView = UIView() guideView.setTranslatesAutoresizingMaskIntoConstraints(false) addSubview(guideView) addConstraints([ NSLayoutConstraint(item: guideView, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 24), NSLayoutConstraint(item: guideView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: guideView, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: guideView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 0) ]) var i = 0 var viewFromAbove = guideView for element in timeFrames{ let v = blockForTimeFrame(element, imageTag: i) addSubview(v) addConstraints([ NSLayoutConstraint(item: v, attribute: .Top, relatedBy: .Equal, toItem: viewFromAbove, attribute: .Bottom, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: v, attribute: .Left, relatedBy: .Equal, toItem: viewFromAbove, attribute: .Left, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: v, attribute: .Width, relatedBy: .Equal, toItem: viewFromAbove, attribute: .Width, multiplier: 1.0, constant: 0), ]) viewFromAbove = v i++ } let extraSpace: CGFloat = 200 let line = UIView() line.setTranslatesAutoresizingMaskIntoConstraints(false) line.backgroundColor = lineColor addSubview(line) sendSubviewToBack(line) addConstraints([ NSLayoutConstraint(item: line, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 20.5), NSLayoutConstraint(item: line, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 1), NSLayoutConstraint(item: line, attribute: .Top, relatedBy: .Equal, toItem: viewFromAbove, attribute: .Bottom, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: line, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: extraSpace) ]) addConstraint(NSLayoutConstraint(item: viewFromAbove, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0)) } private func bulletView(size: CGSize, bulletType: BulletType) -> UIView { var path: UIBezierPath switch bulletType { case .Diamond: path = UIBezierPath(diamondOfSize: size) } let shapeLayer = CAShapeLayer() shapeLayer.fillColor = UIColor.clearColor().CGColor shapeLayer.strokeColor = lineColor.CGColor shapeLayer.path = path.CGPath let v = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.width)) v.setTranslatesAutoresizingMaskIntoConstraints(false) v.layer.addSublayer(shapeLayer) return v } private func blockForTimeFrame(element: TimeFrame, imageTag: Int) -> UIView{ let v = UIView() v.setTranslatesAutoresizingMaskIntoConstraints(false) //bullet let s = CGSize(width: 14, height: 14) var bullet: UIView = bulletView(s, bulletType: bulletType) v.addSubview(bullet) v.addConstraints([ NSLayoutConstraint(item: bullet, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 14), NSLayoutConstraint(item: bullet, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: 0) ]) //image if let image = element.image{ let backgroundViewForImage = UIView() backgroundViewForImage.setTranslatesAutoresizingMaskIntoConstraints(false) backgroundViewForImage.backgroundColor = UIColor.blackColor() backgroundViewForImage.layer.cornerRadius = 10 v.addSubview(backgroundViewForImage) v.addConstraints([ NSLayoutConstraint(item: backgroundViewForImage, attribute: .Width, relatedBy: .Equal, toItem: v, attribute: .Width, multiplier: 1.0, constant: -60), NSLayoutConstraint(item: backgroundViewForImage, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 130), NSLayoutConstraint(item: backgroundViewForImage, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 40), NSLayoutConstraint(item: backgroundViewForImage, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: 0) ]) let imageView = UIImageView(image: image) imageView.layer.cornerRadius = 10 imageView.setTranslatesAutoresizingMaskIntoConstraints(false) imageView.contentMode = UIViewContentMode.ScaleAspectFit v.addSubview(imageView) imageView.tag = imageTag v.addConstraints([ NSLayoutConstraint(item: imageView, attribute: .Left, relatedBy: .Equal, toItem: backgroundViewForImage, attribute: .Left, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: imageView, attribute: .Right, relatedBy: .Equal, toItem: backgroundViewForImage, attribute: .Right, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: imageView, attribute: .Top, relatedBy: .Equal, toItem: backgroundViewForImage, attribute: .Top, multiplier: 1.0, constant: 0), NSLayoutConstraint(item: imageView, attribute: .Bottom, relatedBy: .Equal, toItem: backgroundViewForImage, attribute: .Bottom, multiplier: 1.0, constant: 0) ]) let button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton button.setTranslatesAutoresizingMaskIntoConstraints(false) button.backgroundColor = UIColor.clearColor() button.tag = imageTag button.addTarget(self, action: "tapImage:", forControlEvents: UIControlEvents.TouchUpInside) v.addSubview(button) v.addConstraints([ NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: v, attribute: .Width, multiplier: 1.0, constant: -60), NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 130), NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 40), NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: 0) ]) } let y = element.image == nil ? 0 as CGFloat : 145.0 as CGFloat let titleLabel = UILabel() titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false) titleLabel.font = UIFont(name: "ArialMT", size: 20) titleLabel.textColor = titleLabelColor titleLabel.text = element.date titleLabel.numberOfLines = 0 titleLabel.layer.masksToBounds = false v.addSubview(titleLabel) v.addConstraints([ NSLayoutConstraint(item: titleLabel, attribute: .Width, relatedBy: .Equal, toItem: v, attribute: .Width, multiplier: 1.0, constant: -40), NSLayoutConstraint(item: titleLabel, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 40), NSLayoutConstraint(item: titleLabel, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: y - 5) ]) let textLabel = UILabel() textLabel.setTranslatesAutoresizingMaskIntoConstraints(false) textLabel.font = UIFont(name: "ArialMT", size: 16) textLabel.text = element.text textLabel.textColor = detailLabelColor textLabel.numberOfLines = 0 textLabel.layer.masksToBounds = false v.addSubview(textLabel) v.addConstraints([ NSLayoutConstraint(item: textLabel, attribute: .Width, relatedBy: .Equal, toItem: v, attribute: .Width, multiplier: 1.0, constant: -47), NSLayoutConstraint(item: textLabel, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 40), NSLayoutConstraint(item: textLabel, attribute: .Top, relatedBy: .Equal, toItem: titleLabel, attribute: .Bottom, multiplier: 1.0, constant: 5), NSLayoutConstraint(item: textLabel, attribute: .Bottom, relatedBy: .Equal, toItem: v, attribute: .Bottom, multiplier: 1.0, constant: -10) ]) //draw the line between the bullets let line = UIView() line.setTranslatesAutoresizingMaskIntoConstraints(false) line.backgroundColor = lineColor v.addSubview(line) sendSubviewToBack(line) v.addConstraints([ NSLayoutConstraint(item: line, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 1), NSLayoutConstraint(item: line, attribute: .Left, relatedBy: .Equal, toItem: v, attribute: .Left, multiplier: 1.0, constant: 20.5), NSLayoutConstraint(item: line, attribute: .Top, relatedBy: .Equal, toItem: v, attribute: .Top, multiplier: 1.0, constant: 14), NSLayoutConstraint(item: line, attribute: .Height, relatedBy: .Equal, toItem: v, attribute: .Height, multiplier: 1.0, constant: -14) ]) return v } func tapImage(button: UIButton){ var imageView: UIImageView? = nil for v in subviews{ for w in v.subviews{ if w.tag == button.tag && w is UIImageView{ imageView = (w as? UIImageView) } } } if let i = imageView{ let imageInfo = JTSImageInfo() imageInfo.image = i.image imageInfo.referenceRect = convertRect(i.frame, fromView: i.superview) imageInfo.referenceView = self imageViewer = JTSImageViewController(imageInfo: imageInfo, mode: JTSImageViewControllerMode.Image, backgroundStyle: JTSImageViewControllerBackgroundStyle._ScaledDimmedBlurred) imageViewer!.showFromViewController(UIApplication.sharedApplication().keyWindow?.rootViewController, transition: JTSImageViewControllerTransition._FromOriginalPosition) } } } extension UIBezierPath { convenience init(diamondOfSize size: CGSize) { self.init() moveToPoint(CGPoint(x: size.width / 2, y: 0)) addLineToPoint(CGPoint(x: size.width, y: size.height / 2)) addLineToPoint(CGPoint(x: size.width / 2, y: size.height)) addLineToPoint(CGPoint(x: 0, y: size.width / 2)) closePath() } }
mit
279978ff28f5e6b0c3c1cf0107557c07
37.636364
178
0.718745
3.957169
false
false
false
false
SanjoDeundiak/Wardrobe
Sources/App/Models/Colors.swift
1
726
// // Colors.swift // Hello // // Created by Oleksandr Deundiak on 6/15/17. // // import Foundation enum ColorName: String { case red = "red" case green = "green" case blue = "blue" case yellow = "yellow" case black = "black" case white = "white" } enum Color { case colorName(ColorName) case hex(String) init?(rawValue: String) { if let colorName = ColorName(rawValue: rawValue) { self = .colorName(colorName) } else { self = .hex(rawValue) } } var rawValue: String { switch self { case .colorName(let color): return color.rawValue case .hex(let value): return value } } }
mit
a457149e481e9384cc60cbc95cad3248
17.615385
58
0.549587
3.84127
false
false
false
false
fe9lix/Protium
iOS/Protium/src/gifdetails/GifDetailsUI.swift
1
2606
import UIKit import RxSwift import RxCocoa final class GifDetailsUI: InteractableUI<GifDetailsInteractor> { @IBOutlet weak var copyEmbedLinkButton: UIButton! @IBOutlet weak var openGiphyButton: UIButton! let disposeBag = DisposeBag() private var playerViewController: GifPlayerViewController? // MARK: - Lifecycle class func create(interactorFactory: @escaping (GifDetailsUI) -> GifDetailsInteractor) -> GifDetailsUI { return create( storyboard: UIStoryboard(name: "GifDetails", bundle: Bundle(for: GifDetailsUI.self)), interactorFactory: downcast(interactorFactory) ) as! GifDetailsUI } deinit { log(self) } // The Gif Player is shown using a container view in the storyboard and an embed segue. // Use the "prepare" call to store a reference to GifPlayerViewController that // starts playback when the Gif-Observable triggers. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) guard let identifier = segue.identifier else { return } if case .gifPlayer? = Segue(rawValue: identifier) { playerViewController = segue.destination as? GifPlayerViewController } } override func viewDidLoad() { copyEmbedLinkButton.setTitle("GifDetails.CopyEmbedLink".localized, for: .normal) openGiphyButton.setTitle("GifDetails.OpenGiphy".localized, for: .normal) super.viewDidLoad() } // MARK: - Bindings override func bindInteractor(interactor: GifDetailsInteractor) { interactor.gif.drive(onNext: { gif in self.playVideo(url: gif.videoURL) }).addDisposableTo(disposeBag) interactor.gif .map { $0.embedURL == nil } .drive(self.copyEmbedLinkButton.rx.isHidden) .addDisposableTo(disposeBag) } // MARK: - Video Playback private func playVideo(url: URL?) { guard let url = url, let playerViewController = playerViewController else { return } playerViewController.play(url: url) } } extension GifDetailsUI { struct Actions { let copyEmbedLink: Driver<Void> let openGiphy: Driver<Void> } var actions: Actions { return Actions( copyEmbedLink: copyEmbedLinkButton.rx.tap.asDriver(), openGiphy: openGiphyButton.rx.tap.asDriver() ) } } extension GifDetailsUI { enum Segue: String { case gifPlayer } }
mit
93aba12cd89ea900da39b95d52cfab9e
30.02381
108
0.646201
5.011538
false
false
false
false
SteveRohrlack/CitySimCore
Tests/RessourceTypeTests.swift
1
2101
// // RessourceTypeTests.swift // CitySimCore // // Created by Steve Rohrlack on 08.06.16. // Copyright © 2016 Steve Rohrlack. All rights reserved. // import XCTest #if os(iOS) @testable import CitySimCoreiOS #endif #if os(OSX) @testable import CitySimCoreMacOS #endif class RessourceTypeTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testValue() { let ressourceType: RessourceType = .Electricity(10) XCTAssertEqual(10, ressourceType.value()) } func testOperatorGreaterEqual() { let ressourceType1: RessourceType = .Electricity(10) let ressourceType2: RessourceType = .Electricity(20) let ressourceTypeNil: RessourceType = .Electricity(nil) XCTAssertEqual(true, ressourceType1 <= ressourceType2) XCTAssertEqual(false, ressourceType1 <= ressourceTypeNil) } func testOperatorLesserEqual() { let ressourceType1: RessourceType = .Electricity(10) let ressourceType2: RessourceType = .Electricity(20) let ressourceTypeNil: RessourceType = .Electricity(nil) XCTAssertEqual(true, ressourceType1 <= ressourceType2) XCTAssertEqual(false, ressourceType1 <= ressourceTypeNil) } func testOperatorEqual() { let ressourceType1: RessourceType = .Electricity(10) let ressourceType2: RessourceType = .Electricity(10) let ressourceTypeNil: RessourceType = .Electricity(nil) XCTAssertEqual(true, ressourceType1 == ressourceType2) XCTAssertEqual(false, ressourceType1 == ressourceTypeNil) XCTAssertEqual(false, ressourceType1 != ressourceType2) } func testConsumerConsumes() { let ressourceConsumer = RessourceConsumerTestDouble(ressources: [.Electricity(1)]) XCTAssertEqual(true, ressourceConsumer.consumes(ressource: .Electricity(nil))) XCTAssertEqual(false, ressourceConsumer.consumes(ressource: .Water(nil))) } }
mit
a9748402e76051bd04debc7adf99687a
29.014286
90
0.67
5.084746
false
true
false
false
skedgo/tripkit-ios
Sources/TripKitUI/cards/TKUIRoutingResultsMapManager.swift
1
7263
// // TKUIRoutingResultsMapManager.swift // TripKit // // Created by Adrian Schoenig on 13/4/17. // Copyright © 2017 SkedGo Pty Ltd. All rights reserved. // import Foundation import MapKit import RxSwift import RxCocoa import TGCardViewController import TripKit /// An item to be displayed on the map public struct TKUIRoutingResultsMapRouteItem { let trip: Trip public let polyline: TKRoutePolyline public let selectionIdentifier: String init?(_ trip: Trip) { self.trip = trip self.selectionIdentifier = trip.objectID.uriRepresentation().absoluteString let displayableShapes = trip.segments .compactMap { $0.shapes.isEmpty ? nil : $0.shapes } // Only include those with shapes .flatMap { $0.filter { $0.routeIsTravelled } } // Flat list of travelled shapes let route = displayableShapes .reduce(into: TKColoredRoute(path: [], identifier: selectionIdentifier)) { $0.append($1.sortedCoordinates ?? []) } guard let polyline = TKRoutePolyline(route: route) else { return nil } self.polyline = polyline } } public protocol TKUIRoutingResultsMapManagerType: TGCompatibleMapManager { @MainActor var droppedPin: Signal<CLLocationCoordinate2D> { get } @MainActor var selectedMapRoute: Signal<TKUIRoutingResultsMapRouteItem> { get } } class TKUIRoutingResultsMapManager: TKUIMapManager, TKUIRoutingResultsMapManagerType { weak var viewModel: TKUIRoutingResultsViewModel? private let zoomToDestination: Bool init(destination: MKAnnotation? = nil, zoomToDestination: Bool) { self.zoomToDestination = zoomToDestination super.init() self.destinationAnnotation = destination self.preferredZoomLevel = .road self.showOverlayPolygon = true } private var dropPinRecognizer = UILongPressGestureRecognizer() private var droppedPinPublisher = PublishSubject<CLLocationCoordinate2D>() var droppedPin: Signal<CLLocationCoordinate2D> { return droppedPinPublisher.asSignal(onErrorSignalWith: .empty()) } private var tapRecognizer = UITapGestureRecognizer() private var selectedRoutePublisher = PublishSubject<TKUIRoutingResultsMapRouteItem>() var selectedMapRoute: Signal<TKUIRoutingResultsMapRouteItem> { return selectedRoutePublisher.asSignal(onErrorSignalWith: .empty()) } private var disposeBag = DisposeBag() private var originAnnotation: MKAnnotation? { didSet { if let old = oldValue { mapView?.removeAnnotation(old) } if let new = originAnnotation { mapView?.addAnnotation(new) } } } private var destinationAnnotation: MKAnnotation? { didSet { guard let mapView = mapView else { return } if let old = oldValue { mapView.removeAnnotation(old) } if let new = destinationAnnotation { mapView.addAnnotation(new) } } } fileprivate var selectedRoute: TKUIRoutingResultsMapRouteItem? { didSet { selectionIdentifier = selectedRoute?.selectionIdentifier } } private var allRoutes: [TKUIRoutingResultsMapRouteItem] = [] { didSet { guard let mapView = mapView else { return } let oldPolylines = oldValue.map { $0.polyline } mapView.removeOverlays(oldPolylines) let newPolylines = allRoutes.map { $0.polyline } mapView.addOverlays(newPolylines) if oldPolylines.isEmpty && !newPolylines.isEmpty { // Zoom to the new polylines plus 20% padding around them let boundingRect = newPolylines.boundingMapRect let zoomToRect = boundingRect.insetBy(dx: boundingRect.size.width * -0.2, dy: boundingRect.size.height * -0.2) zoom(to: zoomToRect, animated: true) } } } override func takeCharge(of mapView: MKMapView, animated: Bool) { super.takeCharge(of: mapView, animated: animated) guard let viewModel = viewModel else { assertionFailure(); return } let zoomTo = [originAnnotation, destinationAnnotation].compactMap { $0 } if zoomToDestination, !zoomTo.isEmpty { self.zoom(to: zoomTo, animated: true) } viewModel.originAnnotation .drive(onNext: { [weak self] in self?.originAnnotation = $0 }) .disposed(by: disposeBag) viewModel.destinationAnnotation .drive(onNext: { [weak self] in self?.destinationAnnotation = $0 }) .disposed(by: disposeBag) viewModel.mapRoutes .drive(onNext: { [weak self] in self?.selectedRoute = $1 self?.allRoutes = $0 }) .disposed(by: disposeBag) // Interaction mapView.addGestureRecognizer(dropPinRecognizer) dropPinRecognizer.rx.event .filter { $0.state == .began } .map { [unowned mapView] in let point = $0.location(in: mapView) return mapView.convert(point, toCoordinateFrom: mapView) } .bind(to: droppedPinPublisher) .disposed(by: disposeBag) mapView.addGestureRecognizer(tapRecognizer) tapRecognizer.rx.event .filter { $0.state == .ended } .filter { [unowned self] _ in !self.allRoutes.isEmpty } .map { [unowned mapView] in let point = $0.location(in: mapView) return mapView.convert(point, toCoordinateFrom: mapView) } .map { [unowned self] in self.closestRoute(to: $0) } .filter { $0 != nil } .map { $0! } .bind(to: selectedRoutePublisher) .disposed(by: disposeBag) } override func cleanUp(_ mapView: MKMapView, animated: Bool) { disposeBag = DisposeBag() // clean up map annotations and overlays originAnnotation = nil destinationAnnotation = nil selectedRoute = nil allRoutes = [] mapView.removeGestureRecognizer(dropPinRecognizer) mapView.removeGestureRecognizer(tapRecognizer) super.cleanUp(mapView, animated: animated) } private func closestRoute(to coordinate: CLLocationCoordinate2D) -> TKUIRoutingResultsMapRouteItem? { let mapPoint = MKMapPoint(coordinate) return allRoutes .filter { $0 != selectedRoute } .min { $0.distance(to: mapPoint) < $1.distance(to: mapPoint) } } } extension TKUIRoutingResultsMapRouteItem { fileprivate func distance(to mapPoint: MKMapPoint) -> CLLocationDistance { return polyline.closestPoint(to: mapPoint).distance } } // MARK: - MKMapViewDelegate extension TKUIRoutingResultsMapManager { override func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation === mapView.userLocation { return nil // Use the default MKUserLocation annotation } // for whatever reason reuse breaks callouts when remove and re-adding views to change their colours, so we just always create a new one. let view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: nil) if annotation === originAnnotation { view.pinTintColor = .green } else if annotation === destinationAnnotation { view.pinTintColor = .red } else { view.pinTintColor = .purple } view.animatesDrop = true view.isDraggable = true view.annotation = annotation view.alpha = 1 view.canShowCallout = true return view } }
apache-2.0
62b002b5d2efc3b329ce3ea43d346d38
28.884774
141
0.686725
4.737117
false
false
false
false
shirokova/CustomAlert
CustomAlert/Classes/CustomAlert.swift
1
1410
// // UIViewController+CustomAlert.swift // Pods // // Created by Anna Shirokova on 11/09/2017. // // import UIKit public protocol CustomAlertDelegate: class { func dismissAlert(animated: Bool) func dismissAlert(animated: Bool, completion: @escaping () -> Void) } open class CustomAlertView: UIView { public weak var delegate: CustomAlertDelegate? } public class CustomAlert { let config: CustomAlertConfig let builder: () -> UIView static var globalPresentationWindow: UIWindow? private var alertController: CustomAlertController! var alertView: UIView! public var isPresented: Bool { return alertController?.presentingViewController != nil } func createAlertController() -> CustomAlertController { alertController = CustomAlertController() alertController!.config = config alertView = builder() alertController!.addAlertView(alertView) (alertView as? CustomAlertView)?.delegate = alertController return alertController! } public init(config: CustomAlertConfig = .default, builder: @escaping () -> UIView) { self.config = config self.builder = builder } public func dismiss(animated: Bool = true) { alertController.dismissAlert(animated: animated) { [weak self] in self?.alertController = nil self?.alertView = nil } } }
mit
f70309154a2904993f4e6cf4e20fa787
26.115385
88
0.678014
4.862069
false
true
false
false
duming91/Hear-You
Hear You/Extensions/CGRect+Extension.swift
1
2217
// // CGRect+Hello.swift // Hello // // Created by snow on 16/3/23. // Copyright © 2016年 snow. All rights reserved. // import UIKit extension CGRect { var x: CGFloat { get { return self.origin.x } set { self = CGRectMake(newValue, self.y, self.width, self.height) } } var y: CGFloat { get { return self.origin.y } set { self = CGRectMake(self.x, newValue, self.width, self.height) } } var width: CGFloat { get { return self.size.width } set { self = CGRectMake(self.x, self.y, newValue, self.height) } } var height: CGFloat { get { return self.size.height } set { self = CGRectMake(self.x, self.y, self.width, newValue) } } var top: CGFloat { get { return self.origin.y } set { y = newValue } } var bottom: CGFloat { get { return self.origin.y + self.size.height } set { self = CGRectMake(x, newValue - height, width, height) } } var left: CGFloat { get { return self.origin.x } set { self.x = newValue } } var right: CGFloat { get { return x + width } set { self = CGRectMake(newValue - width, y, width, height) } } var midX: CGFloat { get { return self.x + self.width / 2 } set { self = CGRectMake(newValue - width / 2, y, width, height) } } var midY: CGFloat { get { return self.y + self.height / 2 } set { self = CGRectMake(x, newValue - height / 2, width, height) } } var center: CGPoint { get { return CGPointMake(self.midX, self.midY) } set { self = CGRectMake(newValue.x - width / 2, newValue.y - height / 2, width, height) } } }
gpl-3.0
c82d33953c696535b02cfbf489e22290
18.421053
93
0.434508
4.241379
false
false
false
false
Rep2/SimplerNews
Sources/App/Google.swift
1
2971
import Vapor import HTTP import Foundation import Dispatch final class Google { let serverKey = "AIzaSyCBRqxdYBflBz764vRu6kjlBTx66VlROMM" func login(request: Request) throws -> ResponseRepresentable { guard let idToken = request.data["id_token"]?.string else { throw Abort.custom(status: .badRequest, message: "Parameter id_token:string is required") } let (userId, email) = try verifyUser(idToken: idToken) let accessToken = UUID().uuidString DispatchQueue.global(qos: .utility).async { do { var user = self.fetchUser(email: email, accessToken: accessToken) let userProfile = try self.fetchUserProfile(userId: userId, user: user) user.googleJSON = userProfile try user.save() try SendUser.sendUser(user: user) } catch { print("Fetch details faield") } } return accessToken } func user(request: Request) throws -> ResponseRepresentable { guard let email = request.data["email"]?.string else { throw Abort.custom(status: .badRequest, message: "Parameter email:string is required") } let accessToken = UUID().uuidString return fetchUser(email: email, accessToken: accessToken) } func verifyUser(idToken: String) throws -> (String, String) { let response = try drop.client.get("https://www.googleapis.com/oauth2/v3/tokeninfo?" + "id_token=\(idToken)") guard let bytes = response.body.bytes, let body = try? JSONSerialization.jsonObject(with: Data(bytes: bytes), options: []) else { throw Abort.custom(status: .badRequest, message: "Failed to parse Google verification response") } if let body = body as? [String : String], let userId = body["sub"], let email = body["email"] { return (userId, email) } else { throw Abort.custom(status: .badRequest, message: "Failed to get Google user id") } } func fetchUser(email: String, accessToken: String) -> User { var user: User if let users = try? User.query().filter("email", email).run(), let oldUser = users.first { user = oldUser user.accessToken = accessToken } else { user = User(email: email, accessToken: accessToken) } return user } func fetchUserProfile(userId: String, user: User) throws -> JSON { let response = try drop.client.get("https://content.googleapis.com/plus/v1/people/" + "\(userId)?" + "key=\(serverKey)") guard let bytes = response.body.bytes, let _ = try? JSONSerialization.jsonObject(with: Data(bytes: bytes), options: []) else { throw Abort.custom(status: .badRequest, message: "Failed to parse Google user response") } return try JSON(bytes: bytes) } }
mit
6cfe78a2bd75694c85cfff02f8b8f901
33.546512
137
0.60653
4.460961
false
false
false
false
lulee007/GankMeizi
GankMeizi/Search/SearchModel.swift
1
1651
// // SearchModel.swift // GankMeizi // // Created by 卢小辉 on 16/5/26. // Copyright © 2016年 lulee007. All rights reserved. // import Foundation import RxSwift import CocoaLumberjack import Kanna import ObjectMapper class SearchModel: BaseModel { static let sharedInstance = SearchModel() var searchText: String var items: [ArticleEntity] override init() { self.searchText = "" items = [] super.init() } func search(text: String?,category: String = "all",count: Int = 20,page: Int = 1) -> Observable<[ArticleEntity]> { self.offset = count if page != 1{ self.page = page } if text != nil { self.searchText = text! items.removeAll() self.page = 1 } return provider.request(GankIOService.Search(text: self.searchText,category: category,count: self.offset,page: self.page)) .observeOn(backgroundWorkScheduler) .filterStatusCodes(200...201) .observeOn(backgroundWorkScheduler) .map { (response) -> [ArticleEntity] in let jsonStr = String(data: response.data,encoding: NSUTF8StringEncoding) let result = Mapper<BaseEntity<ArticleEntity>>().map(jsonStr!) if ((result?.results) != nil){ self.page = self.page + 1 self.items += (result?.results!)! } return self.items } } func reset() { self.page = 1 self.items.removeAll() } }
mit
45ac2500223711abc2a7d50e21bc01a4
25.483871
130
0.543849
4.523416
false
false
false
false
lyimin/EyepetizerApp
EyepetizerApp/EyepetizerApp/Controllers/ChoiceController/EYEChoiceController.swift
1
8566
// // EYEChoiceController.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/10. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit import Alamofire class EYEChoiceController: EYEBaseViewController, LoadingPresenter, MenuPresenter { //MARK: --------------------------- LifeCycle -------------------------- override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(collectionView) // 设置loadview setupLoaderView() // 获取数据 getData(EYEAPIHeaper.API_Choice, params: ["date" : NSDate.getCurrentTimeStamp(), "num" : "7"]) setLoaderViewHidden(false) // 初始化菜单按钮 setupMenuBtn() // 下拉刷新 collectionView.headerViewPullToRefresh { [unowned self] in self.getData(EYEAPIHeaper.API_Choice, params: ["date": NSDate.getCurrentTimeStamp(), "num": "7"]) } // 上拉加载更多 collectionView.footerViewPullToRefresh {[unowned self] in if let url = self.nextPageUrl { self.getData(url) } } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } //MARK: --------------------------- Network -------------------------- private func getData(api: String, params: [String : AnyObject]? = nil) { Alamofire.request(.GET, api, parameters: params).responseSwiftyJSON ({[unowned self](request, Response, json, error) -> Void in print("\(EYEAPIHeaper.API_Choice)- \(params)") if json != .null && error == nil{ // 转模型 let dict = json.rawValue as! NSDictionary // 获取下一个url self.nextPageUrl = dict["nextPageUrl"] as? String // 内容数组 let issueArray = dict["issueList"] as! [NSDictionary] let list = issueArray.map({ (dict) -> IssueModel in return IssueModel(dict: dict) }) // 这里判断下拉刷新还是上拉加载更多,如果是上拉加载更多,拼接model。如果是下拉刷新,直接复制 if let _ = params { // 如果params有值就是下拉刷新 self.issueList = list self.collectionView.headerViewEndRefresh() } else { self.issueList.appendContentsOf(list) self.collectionView.footerViewEndRefresh() } // 隐藏loaderview self.setLoaderViewHidden(true) // 刷新 self.collectionView.reloadData() } }) } //MARK: --------------------------- Event or Action -------------------------- func menuBtnDidClick() { let menuController = EYEMenuViewController() menuController.modalPresentationStyle = .Custom menuController.transitioningDelegate = self // 设置刀砍式动画属性 if menuController is GuillotineAnimationDelegate { presentationAnimator.animationDelegate = menuController as? GuillotineAnimationDelegate } presentationAnimator.supportView = self.navigationController?.navigationBar presentationAnimator.presentButton = menuBtn presentationAnimator.duration = 0.15 self.presentViewController(menuController, animated: true, completion: nil) } //MARK: --------------------------- Getter or Setter ------------------------- /// 模型数据 var issueList: [IssueModel] = [IssueModel]() /// 下一个page的地址 var nextPageUrl: String? /// 加载控件 var loaderView: EYELoaderView! /// 菜单按钮 var menuBtn: EYEMenuBtn! /// collectionView private lazy var collectionView : EYECollectionView = { var collectionView : EYECollectionView = EYECollectionView(frame: self.view.bounds, collectionViewLayout:EYECollectionLayout()) // 注册header collectionView.registerClass(EYEChoiceHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: EYEChoiceHeaderView.reuseIdentifier) collectionView.delegate = self collectionView.dataSource = self return collectionView }() // 点击菜单动画 private lazy var presentationAnimator = GuillotineTransitionAnimation() } //MARK: --------------------------- UICollectionViewDelegate, UICollectionViewDataSource -------------------------- extension EYEChoiceController : UICollectionViewDelegate, UICollectionViewDataSource { // return section count func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return issueList.count } // return section row count func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let issueModel : IssueModel = issueList[section] let itemList = issueModel.itemList return itemList.count } // 传递模型 func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { let cell = cell as! EYEChoiceCell let issueModel = issueList[indexPath.section] cell.model = issueModel.itemList[indexPath.row] } // 显示view func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell : EYEChoiceCell = collectionView.dequeueReusableCellWithReuseIdentifier(EYEChoiceCell.reuseIdentifier, forIndexPath: indexPath) as! EYEChoiceCell return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { self.selectCell = collectionView.cellForItemAtIndexPath(indexPath) as! EYEChoiceCell let issueModel = issueList[indexPath.section] let model: ItemModel = issueModel.itemList[indexPath.row] // 如果播放地址为空就返回 if model.playUrl.isEmpty { APESuperHUD.showOrUpdateHUD(.SadFace, message: "没有播放地址", duration: 0.3, presentingView: self.view, completion: nil) return } self.navigationController?.pushViewController(EYEVideoDetailController(model: model), animated: true) } /** * section HeaderView */ func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { // if kind == UICollectionElementKindSectionHeader { let headerView : EYEChoiceHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: EYEChoiceHeaderView.reuseIdentifier, forIndexPath: indexPath) as! EYEChoiceHeaderView let issueModel = issueList[indexPath.section] if let image = issueModel.headerImage { headerView.image = image } else { headerView.title = issueModel.headerTitle } return headerView // } } // return section headerview height func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { // 获取cell的类型 let issueModel = issueList[section] if issueModel.isHaveSectionView { return CGSize(width: UIConstant.SCREEN_WIDTH, height: 50) } else { return CGSizeZero } } } // 这个是点击菜单的动画代理。 extension EYEChoiceController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { presentationAnimator.mode = .Presentation return presentationAnimator } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { presentationAnimator.mode = .Dismissal return presentationAnimator } }
mit
b247e922981c9134322b7bb1895b3dae
40.326633
249
0.636872
5.937184
false
false
false
false
skyfe79/RxPlayground
RxSectionedTableView/RxSectionedTableView/NumberSection.swift
1
1412
// // NumberSection.swift // RxSectionedTableView // // Created by burt.k(Sungcheol Kim) on 2016. 1. 20.. // Copyright © 2016년 burt. All rights reserved. // import Foundation import RxDataSources // MARK: Data struct NumberSection { var header: String var numbers: [IntItem] var updated: NSDate init(header: String, numbers: [IntItem], updated: NSDate) { self.header = header self.numbers = numbers self.updated = updated } } struct IntItem { let number: Int let date: NSDate } // MARK: Just extensions to say how to determine identity and how to determine is entity updated extension NumberSection : AnimatableSectionModelType { typealias Item = IntItem typealias Identity = String var identity: String { return header } var items: [IntItem] { return numbers } init(original: NumberSection, items: [Item]) { self = original self.numbers = items } } extension IntItem : IdentifiableType, Equatable { typealias Identity = Int var identity: Int { return number } } func == (lhs: IntItem, rhs: IntItem) -> Bool { return lhs.number == rhs.number && lhs.date.isEqualToDate(rhs.date) } extension IntItem : CustomDebugStringConvertible { var debugDescription: String { return "IntItem(number: \(number), data: date)" } }
mit
00c34903e574c88e0326377904986e86
19.434783
96
0.643009
4.308869
false
false
false
false
nathawes/swift
test/Driver/bad_tmpdir.swift
2
840
// Check a handful of failures in the driver when TMPDIR can't be accessed. // // These particular error messages are kind of finicky to hit because they // depend on what commands the driver needs to execute on each platform, so the // test is somewhat artificially limited to macOS. // // REQUIRES: OS=macosx // SR-12362: This test is failing on master-next. // XFAIL: * // RUN: env TMP="%t/fake/" TMPDIR="%t/fake/" not %target-build-swift -c -driver-filelist-threshold=0 %s 2>&1 | %FileCheck -check-prefix=CHECK-SOURCES %s // CHECK-SOURCES: - unable to create list of input sources // RUN: echo > %t.o // RUN: env TMP="%t/fake/" TMPDIR="%t/fake/" not %target-build-swift -driver-filelist-threshold=0 %t.o 2>&1 | %FileCheck -check-prefix=CHECK-FILELIST %s // CHECK-FILELIST: - unable to create temporary file for inputs.LinkFileList
apache-2.0
622a58e09bc57582ba11f09bedada0e7
43.210526
152
0.716667
3.346614
false
true
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Library/JLToast/JLToast.swift
2
4140
/* * JLToast.swift * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * Version 2, December 2004 * * Copyright (C) 2013-2015 Su Yeol Jeon * * Everyone is permitted to copy and distribute verbatim or modified * copies of this license document, and changing it is allowed as long * as the name is changed. * * DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE * TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION * * 0. You just DO WHAT THE FUCK YOU WANT TO. * */ import UIKit public struct JLToastDelay { public static let ShortDelay: NSTimeInterval = 2.0 public static let LongDelay: NSTimeInterval = 3.5 } @objc public class JLToast: NSOperation { public var view: JLToastView = JLToastView() public var text: String? { get { return self.view.textLabel.text } set { self.view.textLabel.text = newValue } } public var delay: NSTimeInterval = 0 public var duration: NSTimeInterval = JLToastDelay.ShortDelay private var _executing = false override public var executing: Bool { get { return self._executing } set { self.willChangeValueForKey("isExecuting") self._executing = newValue self.didChangeValueForKey("isExecuting") } } private var _finished = false override public var finished: Bool { get { return self._finished } set { self.willChangeValueForKey("isFinished") self._finished = newValue self.didChangeValueForKey("isFinished") } } internal var window: UIWindow { let windows = UIApplication.sharedApplication().windows for window in windows.reverse() { let className = NSStringFromClass(window.dynamicType) if className == "UIRemoteKeyboardWindow" || className == "UITextEffectsWindow" { return window } } return windows.first! } public class func makeText(text: String) -> JLToast { return JLToast.makeText(text, delay: 0, duration: JLToastDelay.ShortDelay) } public class func makeText(text: String, duration: NSTimeInterval) -> JLToast { return JLToast.makeText(text, delay: 0, duration: duration) } public class func makeText(text: String, delay: NSTimeInterval, duration: NSTimeInterval) -> JLToast { let toast = JLToast() toast.text = text toast.delay = delay toast.duration = duration return toast } public func show() { JLToastCenter.defaultCenter().addToast(self) } override public func start() { if !NSThread.isMainThread() { dispatch_async(dispatch_get_main_queue(), { self.start() }) } else { super.start() } } override public func main() { self.executing = true dispatch_async(dispatch_get_main_queue(), { self.view.updateView() self.view.alpha = 0 self.window.addSubview(self.view) UIView.animateWithDuration( 0.5, delay: self.delay, options: .BeginFromCurrentState, animations: { self.view.alpha = 1 }, completion: { completed in UIView.animateWithDuration( self.duration, animations: { self.view.alpha = 1.0001 }, completion: { completed in self.finish() UIView.animateWithDuration(0.5, animations: { self.view.alpha = 0 }) } ) } ) }) } public func finish() { self.executing = false self.finished = true } }
apache-2.0
2df6e147382bbe1e8d4971cff876f9be
27.363014
106
0.536957
5.240506
false
false
false
false
practicalswift/swift
stdlib/public/core/Availability.swift
9
1711
//===----------------------------------------------------------------------===// // // 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 SwiftShims /// Returns 1 if the running OS version is greater than or equal to /// major.minor.patchVersion and 0 otherwise. /// /// This is a magic entry point known to the compiler. It is called in /// generated code for API availability checking. @_semantics("availability.osversion") @inlinable public func _stdlib_isOSVersionAtLeast( _ major: Builtin.Word, _ minor: Builtin.Word, _ patch: Builtin.Word ) -> Builtin.Int1 { #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) if Int(major) == 9999 { return true._value } // The call to _swift_stdlib_operatingSystemVersion is used as an indicator // that this function was called by a compiler optimization pass. If it is // replaced that pass needs to be updated. let runningVersion = _swift_stdlib_operatingSystemVersion() let result = (runningVersion.majorVersion,runningVersion.minorVersion,runningVersion.patchVersion) >= (Int(major),Int(minor),Int(patch)) return result._value #else // FIXME: As yet, there is no obvious versioning standard for platforms other // than Darwin-based OSes, so we just assume false for now. // rdar://problem/18881232 return false._value #endif }
apache-2.0
a484277f879ebc7fa2c7d604076f74cf
35.404255
89
0.658679
4.409794
false
false
false
false
proxpero/Placeholder
Placeholder/UserProfileViewController.swift
1
2277
import UIKit import CoreLocation import MapKit final class UserProfileViewController: UIViewController { // MARK: IB Outlets & Actions. @IBOutlet var nameLabel: UILabel! @IBOutlet var usernameLabel: UILabel! @IBOutlet var emailLabel: UILabel! @IBOutlet var streetLabel: UILabel! @IBOutlet var suiteLabel: UILabel! @IBOutlet var cityLabel: UILabel! @IBOutlet var zipcodeLabel: UILabel! @IBOutlet var mapView: MKMapView! @IBAction func didTapDone(_ sender: Any) { dismiss() } // MARK: Stored Properties. /// The `User` to be displayed. var user: User? { didSet { refresh() } } /// Action to dismiss the ViewController. var dismiss: () -> () = {} // MARK: Lifecycle private func refresh() { if let nameLabel = nameLabel, let usernameLabel = usernameLabel, let emailLabel = emailLabel, let streetLabel = streetLabel, let suiteLabel = suiteLabel, let cityLabel = cityLabel, let zipcodeLabel = zipcodeLabel, let mapView = mapView { nameLabel.text = user?.name usernameLabel.text = user?.username emailLabel.text = user?.email streetLabel.text = user?.address.street suiteLabel.text = user?.address.suite cityLabel.text = user?.address.city zipcodeLabel.text = user?.address.zipcode if let location = user?.address.geo.location { // Some of these coordinates are in the middle of the ocean, so make the region large. let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 30_000, 30_000) mapView.setRegion(region, animated: true) } } } // Refresh the UI in case the models are set before the views exist. override func viewDidLoad() { super.viewDidLoad() refresh() } } extension User.Address.Geo { /// The CLLocation of the address of the user's address var location: CLLocation? { guard let lat = Double(lat), let lng = Double(lng) else { return nil } return CLLocation(latitude: lat, longitude: lng) } }
mit
fcb0bfe97278aa559bf20a62f1f96c48
27.4625
102
0.604304
4.875803
false
false
false
false
ObjectAlchemist/OOUIKit
Sources/View/Positioning/ViewStackVertical.swift
1
2526
// // ViewStackVertical.swift // OOSwift // // Created by Karsten Litsche on 01.09.17. // // import UIKit public let VerticalStretched: Float = -1 /** A view container that presents it's contents in a vertical top based stack. Note: Last view ignores it's height and stretches to end (use VerticalStretched to tell)! Add a VrSpace at end if you don't like it. Visual: --- <content1> <content2> ^ content3 (height=VerticalStretched) v --- */ public final class ViewStackVertical: OOView { // MARK: init public init(content childs: [(height: Float, view: OOView)]) { guard childs.count != 0 else { fatalError("A container without childs doesn't make any sense!") } guard childs.filter( { $0.height == VerticalStretched }).count == 1 else { fatalError("A stack must contain exactly one child with height=VerticalStretched!") } self.childs = childs } // MARK: protocol OOView private var _ui: UIView? public var ui: UIView { if _ui == nil { _ui = createView() } return _ui! } public func setNeedsRefresh() { childs.forEach { $0.view.setNeedsRefresh() } } // MARK: private private let childs: [(height: Float, view: OOView)] private func createView() -> UIView { let view = PointInsideCheckingView() view.backgroundColor = UIColor.clear addChilds(toView: view) return view } private func addChilds(toView parentView: UIView) { let last = childs.last!.view var previousChild: UIView? childs.forEach { (height: Float, view: OOView) in let childView = view.ui childView.translatesAutoresizingMaskIntoConstraints = false parentView.addSubview(childView) childView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true childView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true childView.topAnchor.constraint(equalTo: previousChild==nil ? parentView.topAnchor : previousChild!.bottomAnchor).isActive = true if last === view { childView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true } if height != VerticalStretched { childView.heightAnchor.constraint(equalToConstant: CGFloat(height)).isActive = true } previousChild = childView } } }
mit
f7155d332d6581de0b20106931efb6a8
30.185185
168
0.634204
4.703911
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Private/Model/Assets/Asset.swift
1
564
// // Asset.swift // lottie-swift // // Created by Brandon Withrow on 1/9/19. // import Foundation public class Asset: Codable { /// The ID of the asset let id: String private enum CodingKeys : String, CodingKey { case id = "id" } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Asset.CodingKeys.self) if let id = try? container.decode(String.self, forKey: .id) { self.id = id } else { self.id = String(try container.decode(Int.self, forKey: .id)) } } }
mit
e66f383d6d3444186b2cd0f5e2757263
19.888889
73
0.634752
3.503106
false
false
false
false
Fitbit/RxBluetoothKit
ExampleApp/ExampleApp/Screens/CentralSpecific/CentralSpecificView.swift
2
1835
import UIKit class CentralSpecificView: UIView { init() { super.init(frame: .zero) backgroundColor = .systemBackground setupLayout() } required init?(coder: NSCoder) { nil } // MARK: - Subviews let serviceUuidTextField: UITextField = { let textField = UITextField() textField.placeholder = Labels.serviceUuidPlaceholder return textField }() let characteristicUuidTextField: UITextField = { let textField = UITextField() textField.placeholder = Labels.characteristicUuidPlaceholder return textField }() let connectButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Connect", for: .normal) button.setImage(UIImage(systemName: "bolt.horizontal"), for: .normal) return button }() let readValueLabel: UILabel = { let label = UILabel() label.text = "Read value: --" label.font = UIFont.systemFont(ofSize: 20.0) label.textColor = .green return label }() let stackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.spacing = 20.0 return stackView }() // MARK: - Private private func setupLayout() { stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) [serviceUuidTextField, characteristicUuidTextField, connectButton, readValueLabel].forEach(stackView.addArrangedSubview) NSLayoutConstraint.activate([ stackView.centerXAnchor.constraint(equalTo: centerXAnchor), stackView.centerYAnchor.constraint(equalTo: centerYAnchor), stackView.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -32) ]) } }
apache-2.0
e29716a97156acc15903c5724a89ba03
27.671875
91
0.643052
5.288184
false
false
false
false
Makosa/BubbleControl-Swift
BubbleControl-Swift/ViewController.swift
1
14060
// // ViewController.swift // BubbleControl-Swift // // Created by Cem Olcay on 11/12/14. // Copyright (c) 2014 Cem Olcay. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupBubble() } // MARK: Bubble var bubble: BubbleControl! func setupBubble () { let win = APPDELEGATE.window! bubble = BubbleControl (size: CGSizeMake(80, 80)) bubble.image = UIImage (named: "basket.png") bubble.didNavigationBarButtonPressed = { println("pressed in nav bar") self.bubble!.popFromNavBar() } bubble.setOpenAnimation = { content, background in self.bubble.contentView!.bottom = win.bottom if (self.bubble.center.x > win.center.x) { self.bubble.contentView!.left = win.right self.bubble.contentView!.spring({ () -> Void in self.bubble.contentView!.right = win.right }, completion: nil) } else { self.bubble.contentView!.right = win.left self.bubble.contentView!.spring({ () -> Void in self.bubble.contentView!.left = win.left }, completion: nil) } } let min: CGFloat = 50 let max: CGFloat = win.h - 250 let randH = min + CGFloat(random()%Int(max-min)) let v = UIView (frame: CGRect (x: 0, y: 0, width: win.w, height: max)) v.backgroundColor = UIColor.grayColor() let label = UILabel (frame: CGRect (x: 10, y: 10, width: v.w, height: 20)) label.text = "test text" v.addSubview(label) bubble.contentView = v win.addSubview(bubble) } // MARK: Animation var animateIcon: Bool = false { didSet { if animateIcon { bubble.didToggle = { on in if let shapeLayer = self.bubble.imageView?.layer.sublayers?[0] as? CAShapeLayer { self.animateBubbleIcon(on) } else { self.bubble.imageView?.image = nil let shapeLayer = CAShapeLayer () shapeLayer.lineWidth = 0.25 shapeLayer.strokeColor = UIColor.blackColor().CGColor shapeLayer.fillMode = kCAFillModeForwards self.bubble.imageView?.layer.addSublayer(shapeLayer) self.animateBubbleIcon(on) } } } else { bubble.didToggle = nil bubble.imageView?.layer.sublayers = nil bubble.imageView?.image = bubble.image! } } } func animateBubbleIcon (on: Bool) { let shapeLayer = self.bubble.imageView!.layer.sublayers![0] as! CAShapeLayer let from = on ? self.basketBezier().CGPath: self.arrowBezier().CGPath let to = on ? self.arrowBezier().CGPath: self.basketBezier().CGPath let anim = CABasicAnimation (keyPath: "path") anim.fromValue = from anim.toValue = to anim.duration = 0.5 anim.fillMode = kCAFillModeForwards anim.removedOnCompletion = false shapeLayer.addAnimation (anim, forKey:"bezier") } func arrowBezier () -> UIBezierPath { //// PaintCode Trial Version //// www.paintcodeapp.com let color0 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) var bezier2Path = UIBezierPath() bezier2Path.moveToPoint(CGPointMake(21.22, 2.89)) bezier2Path.addCurveToPoint(CGPointMake(19.87, 6.72), controlPoint1: CGPointMake(21.22, 6.12), controlPoint2: CGPointMake(20.99, 6.72)) bezier2Path.addCurveToPoint(CGPointMake(14.54, 7.92), controlPoint1: CGPointMake(19.12, 6.72), controlPoint2: CGPointMake(16.72, 7.24)) bezier2Path.addCurveToPoint(CGPointMake(0.44, 25.84), controlPoint1: CGPointMake(7.27, 10.09), controlPoint2: CGPointMake(1.64, 17.14)) bezier2Path.addCurveToPoint(CGPointMake(2.39, 26.97), controlPoint1: CGPointMake(-0.08, 29.74), controlPoint2: CGPointMake(1.12, 30.49)) bezier2Path.addCurveToPoint(CGPointMake(17.62, 16.09), controlPoint1: CGPointMake(4.34, 21.19), controlPoint2: CGPointMake(10.12, 17.14)) bezier2Path.addLineToPoint(CGPointMake(21.14, 15.64)) bezier2Path.addLineToPoint(CGPointMake(21.37, 19.47)) bezier2Path.addLineToPoint(CGPointMake(21.59, 23.29)) bezier2Path.addLineToPoint(CGPointMake(29.09, 17.52)) bezier2Path.addCurveToPoint(CGPointMake(36.59, 11.22), controlPoint1: CGPointMake(33.22, 14.37), controlPoint2: CGPointMake(36.59, 11.52)) bezier2Path.addCurveToPoint(CGPointMake(22.12, -0.33), controlPoint1: CGPointMake(36.59, 10.69), controlPoint2: CGPointMake(24.89, 1.39)) bezier2Path.addCurveToPoint(CGPointMake(21.22, 2.89), controlPoint1: CGPointMake(21.44, -0.71), controlPoint2: CGPointMake(21.22, 0.19)) bezier2Path.closePath() bezier2Path.moveToPoint(CGPointMake(31.87, 8.82)) bezier2Path.addCurveToPoint(CGPointMake(34.64, 11.22), controlPoint1: CGPointMake(33.44, 9.94), controlPoint2: CGPointMake(34.72, 10.99)) bezier2Path.addCurveToPoint(CGPointMake(28.87, 15.87), controlPoint1: CGPointMake(34.64, 11.44), controlPoint2: CGPointMake(32.09, 13.54)) bezier2Path.addLineToPoint(CGPointMake(23.09, 20.14)) bezier2Path.addLineToPoint(CGPointMake(22.87, 17.07)) bezier2Path.addLineToPoint(CGPointMake(22.64, 13.99)) bezier2Path.addLineToPoint(CGPointMake(18.97, 14.44)) bezier2Path.addCurveToPoint(CGPointMake(6.22, 19.24), controlPoint1: CGPointMake(13.04, 15.12), controlPoint2: CGPointMake(9.44, 16.54)) bezier2Path.addCurveToPoint(CGPointMake(5.09, 16.84), controlPoint1: CGPointMake(2.77, 22.24), controlPoint2: CGPointMake(2.39, 21.49)) bezier2Path.addCurveToPoint(CGPointMake(20.69, 8.22), controlPoint1: CGPointMake(8.09, 11.82), controlPoint2: CGPointMake(14.54, 8.22)) bezier2Path.addCurveToPoint(CGPointMake(22.72, 5.14), controlPoint1: CGPointMake(22.57, 8.22), controlPoint2: CGPointMake(22.72, 7.99)) bezier2Path.addLineToPoint(CGPointMake(22.72, 2.07)) bezier2Path.addLineToPoint(CGPointMake(25.94, 4.47)) bezier2Path.addCurveToPoint(CGPointMake(31.87, 8.82), controlPoint1: CGPointMake(27.67, 5.74), controlPoint2: CGPointMake(30.37, 7.77)) bezier2Path.closePath() bezier2Path.miterLimit = 4; color0.setFill() bezier2Path.fill() return bezier2Path } func basketBezier () -> UIBezierPath { //// PaintCode Trial Version //// www.paintcodeapp.com let color0 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) var bezier2Path = UIBezierPath() bezier2Path.moveToPoint(CGPointMake(0.86, 0.36)) bezier2Path.addCurveToPoint(CGPointMake(3.41, 6.21), controlPoint1: CGPointMake(-0.27, 1.41), controlPoint2: CGPointMake(0.48, 2.98)) bezier2Path.addLineToPoint(CGPointMake(6.41, 9.51)) bezier2Path.addLineToPoint(CGPointMake(3.18, 9.73)) bezier2Path.addCurveToPoint(CGPointMake(-0.27, 12.96), controlPoint1: CGPointMake(0.03, 9.96), controlPoint2: CGPointMake(-0.04, 10.03)) bezier2Path.addCurveToPoint(CGPointMake(0.48, 16.71), controlPoint1: CGPointMake(-0.42, 14.83), controlPoint2: CGPointMake(-0.12, 16.18)) bezier2Path.addCurveToPoint(CGPointMake(3.26, 23.46), controlPoint1: CGPointMake(1.08, 17.08), controlPoint2: CGPointMake(2.28, 20.16)) bezier2Path.addCurveToPoint(CGPointMake(18.33, 32.08), controlPoint1: CGPointMake(6.03, 32.91), controlPoint2: CGPointMake(4.61, 32.08)) bezier2Path.addCurveToPoint(CGPointMake(33.41, 23.46), controlPoint1: CGPointMake(32.06, 32.08), controlPoint2: CGPointMake(30.63, 32.91)) bezier2Path.addCurveToPoint(CGPointMake(36.18, 16.71), controlPoint1: CGPointMake(34.38, 20.16), controlPoint2: CGPointMake(35.58, 17.08)) bezier2Path.addCurveToPoint(CGPointMake(36.93, 12.96), controlPoint1: CGPointMake(36.78, 16.18), controlPoint2: CGPointMake(37.08, 14.83)) bezier2Path.addCurveToPoint(CGPointMake(33.48, 9.73), controlPoint1: CGPointMake(36.71, 10.03), controlPoint2: CGPointMake(36.63, 9.96)) bezier2Path.addLineToPoint(CGPointMake(30.26, 9.51)) bezier2Path.addLineToPoint(CGPointMake(33.33, 6.13)) bezier2Path.addCurveToPoint(CGPointMake(36.18, 1.48), controlPoint1: CGPointMake(35.06, 4.26), controlPoint2: CGPointMake(36.33, 2.16)) bezier2Path.addCurveToPoint(CGPointMake(28.23, 4.63), controlPoint1: CGPointMake(35.66, -1.22), controlPoint2: CGPointMake(33.26, -0.24)) bezier2Path.addLineToPoint(CGPointMake(23.06, 9.58)) bezier2Path.addLineToPoint(CGPointMake(18.33, 9.58)) bezier2Path.addLineToPoint(CGPointMake(13.61, 9.58)) bezier2Path.addLineToPoint(CGPointMake(8.51, 4.71)) bezier2Path.addCurveToPoint(CGPointMake(0.86, 0.36), controlPoint1: CGPointMake(3.78, 0.13), controlPoint2: CGPointMake(2.06, -0.84)) bezier2Path.closePath() bezier2Path.moveToPoint(CGPointMake(10.08, 12.66)) bezier2Path.addCurveToPoint(CGPointMake(14.58, 12.21), controlPoint1: CGPointMake(12.33, 14.38), controlPoint2: CGPointMake(14.58, 14.16)) bezier2Path.addCurveToPoint(CGPointMake(18.33, 11.08), controlPoint1: CGPointMake(14.58, 11.38), controlPoint2: CGPointMake(15.48, 11.08)) bezier2Path.addCurveToPoint(CGPointMake(22.08, 12.21), controlPoint1: CGPointMake(21.18, 11.08), controlPoint2: CGPointMake(22.08, 11.38)) bezier2Path.addCurveToPoint(CGPointMake(26.58, 12.66), controlPoint1: CGPointMake(22.08, 14.16), controlPoint2: CGPointMake(24.33, 14.38)) bezier2Path.addCurveToPoint(CGPointMake(32.21, 11.08), controlPoint1: CGPointMake(28.08, 11.61), controlPoint2: CGPointMake(29.88, 11.08)) bezier2Path.addCurveToPoint(CGPointMake(35.58, 13.33), controlPoint1: CGPointMake(35.43, 11.08), controlPoint2: CGPointMake(35.58, 11.16)) bezier2Path.addLineToPoint(CGPointMake(35.58, 15.58)) bezier2Path.addLineToPoint(CGPointMake(18.33, 15.58)) bezier2Path.addLineToPoint(CGPointMake(1.08, 15.58)) bezier2Path.addLineToPoint(CGPointMake(1.08, 13.33)) bezier2Path.addCurveToPoint(CGPointMake(4.46, 11.08), controlPoint1: CGPointMake(1.08, 11.16), controlPoint2: CGPointMake(1.23, 11.08)) bezier2Path.addCurveToPoint(CGPointMake(10.08, 12.66), controlPoint1: CGPointMake(6.78, 11.08), controlPoint2: CGPointMake(8.58, 11.61)) bezier2Path.closePath() bezier2Path.moveToPoint(CGPointMake(11.21, 22.86)) bezier2Path.addCurveToPoint(CGPointMake(12.71, 28.71), controlPoint1: CGPointMake(11.21, 28.18), controlPoint2: CGPointMake(11.36, 28.71)) bezier2Path.addCurveToPoint(CGPointMake(14.43, 22.86), controlPoint1: CGPointMake(14.06, 28.71), controlPoint2: CGPointMake(14.21, 28.11)) bezier2Path.addCurveToPoint(CGPointMake(15.56, 17.08), controlPoint1: CGPointMake(14.58, 18.96), controlPoint2: CGPointMake(14.96, 17.08)) bezier2Path.addCurveToPoint(CGPointMake(16.23, 21.21), controlPoint1: CGPointMake(16.16, 17.08), controlPoint2: CGPointMake(16.38, 18.36)) bezier2Path.addCurveToPoint(CGPointMake(18.56, 28.93), controlPoint1: CGPointMake(15.86, 27.13), controlPoint2: CGPointMake(16.46, 29.23)) bezier2Path.addCurveToPoint(CGPointMake(20.21, 22.86), controlPoint1: CGPointMake(20.13, 28.71), controlPoint2: CGPointMake(20.21, 28.33)) bezier2Path.addCurveToPoint(CGPointMake(21.11, 17.08), controlPoint1: CGPointMake(20.21, 18.88), controlPoint2: CGPointMake(20.51, 17.08)) bezier2Path.addCurveToPoint(CGPointMake(22.23, 22.86), controlPoint1: CGPointMake(21.71, 17.08), controlPoint2: CGPointMake(22.08, 18.96)) bezier2Path.addCurveToPoint(CGPointMake(23.96, 28.71), controlPoint1: CGPointMake(22.46, 28.11), controlPoint2: CGPointMake(22.61, 28.71)) bezier2Path.addCurveToPoint(CGPointMake(25.46, 22.86), controlPoint1: CGPointMake(25.31, 28.71), controlPoint2: CGPointMake(25.46, 28.18)) bezier2Path.addLineToPoint(CGPointMake(25.46, 17.08)) bezier2Path.addLineToPoint(CGPointMake(29.43, 17.08)) bezier2Path.addCurveToPoint(CGPointMake(31.53, 24.58), controlPoint1: CGPointMake(33.93, 17.08), controlPoint2: CGPointMake(33.86, 16.78)) bezier2Path.addLineToPoint(CGPointMake(29.88, 30.21)) bezier2Path.addLineToPoint(CGPointMake(18.33, 30.21)) bezier2Path.addLineToPoint(CGPointMake(6.78, 30.21)) bezier2Path.addLineToPoint(CGPointMake(5.13, 24.58)) bezier2Path.addCurveToPoint(CGPointMake(7.31, 17.08), controlPoint1: CGPointMake(2.81, 16.78), controlPoint2: CGPointMake(2.73, 17.08)) bezier2Path.addLineToPoint(CGPointMake(11.21, 17.08)) bezier2Path.addLineToPoint(CGPointMake(11.21, 22.86)) bezier2Path.closePath() bezier2Path.miterLimit = 4; color0.setFill() bezier2Path.fill() return bezier2Path } // MARK: IBActions @IBAction func postionValueChanged(sender: UISwitch) { bubble.movesBottom = sender.on } @IBAction func animateIconValueChanged(sender: UISwitch) { animateIcon = sender.on } @IBAction func snapInsideChanged(sender: UISwitch) { bubble.snapsInside = sender.on } @IBAction func addPressed(sender: AnyObject) { bubble.badgeCount++ } @IBAction func removePressed(sender: AnyObject) { bubble.badgeCount-- } }
mit
bb3dccb3c173fa92f9a5b33331193542
54.354331
146
0.657681
3.84258
false
false
false
false
Vostro162/VaporTelegram
Sources/App/Contact+Extensions.swift
1
892
// // Contact+Extensions.swift // VaporTelegram // // Created by Marius Hartig on 11.05.17. // // import Foundation import Vapor // MARK: - JSON extension Contact: JSONInitializable { public init(json: JSON) throws { guard let phoneNumber = json["phone_number"]?.string, let firstName = json["first_name"]?.string else { throw VaporTelegramError.parsing } self.phoneNumber = phoneNumber self.firstName = firstName /* * * Optionals * */ if let lastName = json["last_name"]?.string { self.lastName = lastName } else { self.lastName = nil } if let userId = json["user_id"]?.int { self.userId = userId } else { self.userId = nil } } }
mit
24c7d77c7603b2389c7f7b83b7933fd6
18.822222
59
0.498879
4.645833
false
false
false
false
russelhampton05/MenMew
App Prototypes/Menu_Server_App_Prototype_001/Menu_Server_App_Prototype_001/RestaurantTableViewController.swift
1
4421
// // RestaurantTableViewController.swift // Menu_Server_App_Prototype_001 // // Created by Jon Calanio on 10/3/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit var currentTicket: Ticket? class RestaurantTableViewController: UITableViewController, SWRevealViewControllerDelegate { //IBOutlets @IBOutlet weak var menuButton: UIBarButtonItem! //Variables var restaurantArray: [Restaurant] = [] var segueIndex: Int? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = false tableView.sectionHeaderHeight = 70 tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension navigationItem.hidesBackButton = true menuButton.target = self.revealViewController() self.revealViewController().delegate = self menuButton.action = #selector(SWRevealViewController.revealToggle(_:)) //Load the assigned restaurants loadRestaurants() loadTheme() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { loadTheme() tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restaurantArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantCell", for: indexPath) cell.textLabel!.text = restaurantArray[(indexPath as NSIndexPath).row].title cell.detailTextLabel!.text = restaurantArray[(indexPath as NSIndexPath).row].location cell.backgroundColor = currentTheme!.primary! cell.textLabel!.textColor = currentTheme!.highlight! cell.detailTextLabel!.textColor = currentTheme!.highlight! //Interaction let bgView = UIView() bgView.backgroundColor = currentTheme!.highlight! cell.selectedBackgroundView = bgView cell.textLabel?.highlightedTextColor = currentTheme!.primary! cell.detailTextLabel?.highlightedTextColor = currentTheme!.primary! return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { segueIndex = (indexPath as NSIndexPath).row performSegue(withIdentifier: "TableListSegue", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "TableListSegue" { let tableVC = segue.destination as! RTableTableViewController let backItem = UIBarButtonItem() backItem.title = "" navigationItem.backBarButtonItem = backItem tableVC.restaurant = restaurantArray[segueIndex!] } } func loadRestaurants() { //For now, load all restaurants var restaurantList: [String] = [] for item in currentServer!.restaurants! { restaurantList.append(item) } RestaurantManager.GetRestaurant(ids: restaurantList) { restaurants in self.restaurantArray = restaurants DispatchQueue.main.async { self.tableView.reloadData() } } } func loadTheme() { //Background and Tint self.view.backgroundColor = currentTheme!.primary! self.view.tintColor = currentTheme!.highlight! //Navigation UINavigationBar.appearance().backgroundColor = currentTheme!.primary! UINavigationBar.appearance().tintColor = currentTheme!.highlight! self.navigationController?.navigationBar.barTintColor = currentTheme!.primary! self.navigationController?.navigationBar.tintColor = currentTheme!.highlight! self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: currentTheme!.highlight!, NSFontAttributeName: UIFont.systemFont(ofSize: 20, weight: UIFontWeightLight)] } }
mit
79ec9c3a3fb92763bf00c434f7eced1e
32.740458
208
0.66267
5.917001
false
false
false
false
lstanii-magnet/ChatKitSample-iOS
ChatMessenger/Pods/ChatKit/ChatKit/source/Views/ContactsCell.swift
1
1751
/* * Copyright (c) 2016 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import MagnetMax protocol ContactsCellDelegate : class { func didSelectContactsCellAvatar(cell : ContactsCell) } public class ContactsCell: UITableViewCell { //MARK: Public Properties @IBOutlet public private(set) var avatar : UIImageView? @IBOutlet public private(set)var userName : UILabel? public internal(set) var user : MMUser? //MARK: Internal properties weak var delegate : ContactsCellDelegate? //MARK: Actions func didSelectAvatar() { self.delegate?.didSelectContactsCellAvatar(self) } override public func awakeFromNib() { super.awakeFromNib() let tap = UITapGestureRecognizer(target: self, action: "didSelectAvatar") tap.cancelsTouchesInView = true tap.delaysTouchesBegan = true self.avatar?.userInteractionEnabled = true self.avatar?.addGestureRecognizer(tap) if let avatar = self.avatar { avatar.layer.cornerRadius = avatar.frame.size.width / 2.0 avatar.clipsToBounds = true } } }
apache-2.0
08bbf347deef00c82dfc86b53b3e78d9
26.359375
81
0.679041
4.745257
false
false
false
false
AliSoftware/Dip
Sources/Register.swift
2
3421
// // Dip // // Copyright (c) 2015 Olivier Halligon <olivier@halligon.net> // // 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. // extension DependencyContainer { /** Registers definition for passed type. If instance created by factory of definition, passed as a first parameter, does not implement type passed in a `type` parameter, container will throw `DipError.DefinitionNotFound` error when trying to resolve that type. - parameters: - definition: Definition to register - type: Type to register definition for - tag: Optional tag to associate definition with. Default is `nil`. - returns: New definition registered for passed type. */ @discardableResult public func register<T, U, F>(_ definition: Definition<T, U>, type: F.Type, tag: DependencyTagConvertible? = nil) -> Definition<F, U> { return _register(definition: definition, type: type, tag: tag) } /** Register definiton in the container and associate it with an optional tag. Will override already registered definition for the same type and factory, associated with the same tag. - parameters: - tag: The arbitrary tag to associate this definition with. Pass `nil` to associate with any tag. Default value is `nil`. - definition: The definition to register in the container. */ public func register<T, U>(_ definition: Definition<T, U>, tag: DependencyTagConvertible? = nil) { _register(definition: definition, tag: tag) } } extension DependencyContainer { func _register<T, U>(definition aDefinition: Definition<T, U>, tag: DependencyTagConvertible? = nil) { precondition(!bootstrapped, "You can not modify container's definitions after it was bootstrapped.") let definition = aDefinition threadSafe { let key = DefinitionKey(type: T.self, typeOfArguments: U.self, tag: tag?.dependencyTag) if let _ = definitions[key] { _remove(definitionForKey: key) } definition.container = self definitions[key] = definition resolvedInstances.singletons[key] = nil resolvedInstances.weakSingletons[key] = nil resolvedInstances.sharedSingletons[key] = nil resolvedInstances.sharedWeakSingletons[key] = nil if .eagerSingleton == definition.scope { bootstrapQueue.append({ _ = try self.resolve(tag: tag) as T }) } } } }
mit
41456ea92ab1c09650aae77026f71634
39.72619
156
0.71558
4.513193
false
false
false
false
RocketChat/Rocket.Chat.iOS
Pods/DifferenceKit/Sources/Extensions/UIKitExtension.swift
1
8731
#if os(iOS) || os(tvOS) import UIKit public extension UITableView { /// Applies multiple animated updates in stages using `StagedChangeset`. /// /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. /// /// - Parameters: /// - stagedChangeset: A staged set of changes. /// - animation: An option to animate the updates. /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated /// updates should be stopped and performed reloadData. Default is nil. /// - setData: A closure that takes the collection as a parameter. /// The collection should be set to data-source of UITableView. func reload<C>( using stagedChangeset: StagedChangeset<C>, with animation: @autoclosure () -> RowAnimation, interrupt: ((Changeset<C>) -> Bool)? = nil, setData: (C) -> Void ) { reload( using: stagedChangeset, deleteSectionsAnimation: animation(), insertSectionsAnimation: animation(), reloadSectionsAnimation: animation(), deleteRowsAnimation: animation(), insertRowsAnimation: animation(), reloadRowsAnimation: animation(), interrupt: interrupt, setData: setData ) } /// Applies multiple animated updates in stages using `StagedChangeset`. /// /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. /// /// - Parameters: /// - stagedChangeset: A staged set of changes. /// - deleteSectionsAnimation: An option to animate the section deletion. /// - insertSectionsAnimation: An option to animate the section insertion. /// - reloadSectionsAnimation: An option to animate the section reload. /// - deleteRowsAnimation: An option to animate the row deletion. /// - insertRowsAnimation: An option to animate the row insertion. /// - reloadRowsAnimation: An option to animate the row reload. /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated /// updates should be stopped and performed reloadData. Default is nil. /// - setData: A closure that takes the collection as a parameter. /// The collection should be set to data-source of UITableView. func reload<C>( using stagedChangeset: StagedChangeset<C>, deleteSectionsAnimation: @autoclosure () -> RowAnimation, insertSectionsAnimation: @autoclosure () -> RowAnimation, reloadSectionsAnimation: @autoclosure () -> RowAnimation, deleteRowsAnimation: @autoclosure () -> RowAnimation, insertRowsAnimation: @autoclosure () -> RowAnimation, reloadRowsAnimation: @autoclosure () -> RowAnimation, interrupt: ((Changeset<C>) -> Bool)? = nil, setData: (C) -> Void ) { if case .none = window, let data = stagedChangeset.last?.data { setData(data) return reloadData() } for changeset in stagedChangeset { if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data { setData(data) return reloadData() } _performBatchUpdates { setData(changeset.data) if !changeset.sectionDeleted.isEmpty { deleteSections(IndexSet(changeset.sectionDeleted), with: deleteSectionsAnimation()) } if !changeset.sectionInserted.isEmpty { insertSections(IndexSet(changeset.sectionInserted), with: insertSectionsAnimation()) } if !changeset.sectionUpdated.isEmpty { reloadSections(IndexSet(changeset.sectionUpdated), with: reloadSectionsAnimation()) } for (source, target) in changeset.sectionMoved { moveSection(source, toSection: target) } if !changeset.elementDeleted.isEmpty { deleteRows(at: changeset.elementDeleted.map { IndexPath(row: $0.element, section: $0.section) }, with: deleteRowsAnimation()) } if !changeset.elementInserted.isEmpty { insertRows(at: changeset.elementInserted.map { IndexPath(row: $0.element, section: $0.section) }, with: insertRowsAnimation()) } if !changeset.elementUpdated.isEmpty { reloadRows(at: changeset.elementUpdated.map { IndexPath(row: $0.element, section: $0.section) }, with: reloadRowsAnimation()) } for (source, target) in changeset.elementMoved { moveRow(at: IndexPath(row: source.element, section: source.section), to: IndexPath(row: target.element, section: target.section)) } } } } private func _performBatchUpdates(_ updates: () -> Void) { if #available(iOS 11.0, tvOS 11.0, *) { performBatchUpdates(updates) } else { beginUpdates() updates() endUpdates() } } } public extension UICollectionView { /// Applies multiple animated updates in stages using `StagedChangeset`. /// /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. /// /// - Parameters: /// - stagedChangeset: A staged set of changes. /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated /// updates should be stopped and performed reloadData. Default is nil. /// - setData: A closure that takes the collection as a parameter. /// The collection should be set to data-source of UICollectionView. func reload<C>( using stagedChangeset: StagedChangeset<C>, interrupt: ((Changeset<C>) -> Bool)? = nil, setData: (C) -> Void ) { if case .none = window, let data = stagedChangeset.last?.data { setData(data) return reloadData() } for changeset in stagedChangeset { if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data { setData(data) return reloadData() } performBatchUpdates({ setData(changeset.data) if !changeset.sectionDeleted.isEmpty { deleteSections(IndexSet(changeset.sectionDeleted)) } if !changeset.sectionInserted.isEmpty { insertSections(IndexSet(changeset.sectionInserted)) } if !changeset.sectionUpdated.isEmpty { reloadSections(IndexSet(changeset.sectionUpdated)) } for (source, target) in changeset.sectionMoved { moveSection(source, toSection: target) } if !changeset.elementDeleted.isEmpty { deleteItems(at: changeset.elementDeleted.map { IndexPath(item: $0.element, section: $0.section) }) } if !changeset.elementInserted.isEmpty { insertItems(at: changeset.elementInserted.map { IndexPath(item: $0.element, section: $0.section) }) } if !changeset.elementUpdated.isEmpty { reloadItems(at: changeset.elementUpdated.map { IndexPath(item: $0.element, section: $0.section) }) } for (source, target) in changeset.elementMoved { moveItem(at: IndexPath(item: source.element, section: source.section), to: IndexPath(item: target.element, section: target.section)) } }) } } } #endif
mit
4cde7e264bd7bcd8bac8802d6413c95e
44.005155
152
0.599473
5.406192
false
false
false
false
everald/JetPack
Sources/UI/z_ImageView+PHAssetSource.swift
1
3436
// File name prefixed with z_ to avoid compiler crash related to type extensions, nested types and order of Swift source files. // TODO // - allow passing PHImageRequestOptions, copy it and set .synchronous to false // - allow using a custom PHImageManager, e.g. PHCachingImageManager import Photos import UIKit public extension ImageView { public struct PHAssetSource: Source, Equatable { public var asset: PHAsset public init(asset: PHAsset) { self.asset = asset } public func createSession() -> Session? { return PHAssetSourceSession(source: self) } } } public func == (a: ImageView.PHAssetSource, b: ImageView.PHAssetSource) -> Bool { return a.asset == b.asset } private final class PHAssetSourceSession: ImageView.Session { fileprivate var lastRequestedContentMode: PHImageContentMode? fileprivate var lastRequestedSize = CGSize() fileprivate var listener: ImageView.SessionListener? fileprivate var requestId: PHImageRequestID? fileprivate let source: ImageView.PHAssetSource fileprivate init(source: ImageView.PHAssetSource) { self.source = source } fileprivate func imageViewDidChangeConfiguration(_ imageView: ImageView) { startOrRestartRequestForImageView(imageView) } fileprivate func startOrRestartRequestForImageView(_ imageView: ImageView) { let optimalSize = imageView.optimalImageSize.scaleBy(imageView.optimalImageScale) var size = self.lastRequestedSize size.width = max(size.width, optimalSize.width) size.height = max(size.height, optimalSize.height) let contentMode: PHImageContentMode switch imageView.scaling { case .fitInside, .none: contentMode = .aspectFit case .fitHorizontally, .fitHorizontallyIgnoringAspectRatio, .fitIgnoringAspectRatio, .fitOutside, .fitVertically, .fitVerticallyIgnoringAspectRatio: contentMode = .aspectFill } guard contentMode != lastRequestedContentMode || size != lastRequestedSize else { return } stopRequest() startRequestWithSize(size, contentMode: contentMode) } fileprivate func startRequestWithSize(_ size: CGSize, contentMode: PHImageContentMode) { precondition(self.requestId == nil) self.lastRequestedContentMode = contentMode self.lastRequestedSize = size let manager = PHImageManager.default() let options = PHImageRequestOptions() options.deliveryMode = .opportunistic options.isNetworkAccessAllowed = true options.resizeMode = .exact options.isSynchronous = false options.version = .current requestId = manager.requestImage(for: source.asset, targetSize: size, contentMode: contentMode, options: options) { image, _ in guard let image = image else { return } let imageSize = image.size.scaleBy(image.scale) self.lastRequestedSize.width = max(self.lastRequestedSize.width, imageSize.width) self.lastRequestedSize.height = max(self.lastRequestedSize.height, imageSize.height) self.listener?.sessionDidRetrieveImage(image) } } fileprivate func startRetrievingImageForImageView(_ imageView: ImageView, listener: ImageView.SessionListener) { precondition(self.listener == nil) self.listener = listener self.startOrRestartRequestForImageView(imageView) } fileprivate func stopRetrievingImage() { listener = nil stopRequest() } fileprivate func stopRequest() { guard let requestId = requestId else { return } PHImageManager.default().cancelImageRequest(requestId) self.requestId = nil } }
mit
f163fee6f19856f92e16de99e6cdf197
25.030303
150
0.768335
4.268323
false
false
false
false
stendahls/AsyncTask
Tests/ThrowableTask.swift
1
3229
// // ThrowableTask.swift // AsyncTest // // Created by Thomas Sempf on 2017-03-06. // Copyright © 2017 Stendahls. 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 XCTest @testable import AsyncTask class ThrowableTaskTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testTaskThrows() { enum TaskError: Error { case notFound } let load = {(path: String) -> ThrowableTask<Data> in ThrowableTask { Thread.sleep(forTimeInterval: 0.05) switch path { case "profile.png": return Data() case "index.html": return Data() default: throw TaskError.notFound } } } XCTAssertNotNil(try? load("profile.png").await()) XCTAssertNotNil(try? load("index.html").await()) XCTAssertNotNil(try? [load("profile.png"), load("index.html")].awaitAll()) XCTAssertThrowsError(try load("random.txt").await()) XCTAssertThrowsError(try [load("profile.png"), load("index.html"), load("random.txt")].awaitAll()) } func testThatAwaitResultReturnsFailureAfterTimeout() { let echo = ThrowableTask { () -> String in Thread.sleep(forTimeInterval: 0.5) return "Hello" } let result = echo.awaitResult(.background, timeout: 0.05) if case .success = result { XCTFail() } } func testThatAwaitThrowsAfterTimeout() { let echo = ThrowableTask { () -> String in Thread.sleep(forTimeInterval: 0.5) return "Hello" } XCTAssertThrowsError(try echo.await(.background, timeout: 0.05)) } }
mit
79a75717c2be85ea066538e62e28b23a
34.086957
111
0.619269
4.75405
false
true
false
false
githubxiangdong/DouYuZB
DouYuZB/DouYuZB/Classes/Home/Controller/RecommendViewController.swift
1
3510
// // RecommendViewController.swift // DouYuZB // // Created by new on 2017/4/25. // Copyright © 2017年 9-kylins. All rights reserved. // import UIKit private let kAdViewH = kScreenW * 3/8 // 广告栏的高度 private let kGameH :CGFloat = 90 // 游戏推荐的高度 class RecommendViewController: BaseAnchorViewController { // MARK:- 懒加载属性 fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel() fileprivate lazy var adView : RecommendAdv = { let adView = RecommendAdv.recommendAdv() adView.frame = CGRect(x: 0, y: -(kAdViewH + kGameH), width: kScreenW, height: kAdViewH) return adView }() fileprivate lazy var gameView : GameRecommendView = { let gameView = GameRecommendView.gameRecommendView() gameView.frame = CGRect(x: 0, y: -kGameH, width: kScreenW, height: kGameH) return gameView }() } // MARK:- 设置Ui界面 extension RecommendViewController { override func setupUI() { // 1,先调用super super.setupUI() // 2, 将adView添加到collectioView上 collectionView.addSubview(adView) // 3, 将game添加到collectionView collectionView.addSubview(gameView) // 4, 设置collectionView的内边距 collectionView.contentInset = UIEdgeInsetsMake(kAdViewH + kGameH, 0, 0, 0) } } // MARK:- 请求数据 extension RecommendViewController { override func loadData() { // 0, 给父类的viewModel赋值 baseVM = recommendVM // 1, 请求推荐数据 recommendVM.requestData { // 1, 展示推荐数据 self.collectionView.reloadData() // 2, 将数据传给gameView var groups = self.recommendVM.anchorGroups // 2.1, 移除前两组数据 groups.removeFirst() groups.removeFirst() // 2.2, 添加个更多组的图标 let moreModel = AnchorGroupModel() moreModel.tag_name = "更多" groups.append(moreModel) self.gameView.groupModels = groups // 3, 请求数据完成 self.loadDataFinished() } // 2, 请求广告栏数据 recommendVM.requestAds { self.adView.adsModels = self.recommendVM.adsModels } } } extension RecommendViewController : UICollectionViewDelegateFlowLayout { // 重写父类的返回cell的方法 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { // 1, 取出niceCell let niceCell = collectionView.dequeueReusableCell(withReuseIdentifier: kNiceCellID, for: indexPath) as! NiceCollectionViewCell // 2, 设置数据 niceCell.model = recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item] return niceCell } else { return super.collectionView(collectionView, cellForItemAt: indexPath) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kNiceItemH) } return CGSize(width: kItemW, height: kItemH) } }
mit
ef38823c0a9154cd2e3289d860a20183
29.082569
160
0.619396
4.953172
false
false
false
false
exponent/exponent
packages/expo-modules-core/ios/Swift/Arguments/Types/EnumArgumentType.swift
2
2834
// Copyright 2021-present 650 Industries. All rights reserved. /** An argument type representing an enum that conforms to `EnumArgument`. */ internal struct EnumArgumentType: AnyArgumentType { let innerType: EnumArgument.Type func cast<ArgType>(_ value: ArgType) throws -> Any { return try innerType.create(fromRawValue: value) } var description: String { "Enum<\(innerType)>" } } /** A protocol that allows converting raw values to enum cases. */ public protocol EnumArgument: AnyArgument { /** Tries to create an enum case using given raw value. May throw errors, e.g. when the raw value doesn't match any case. */ static func create<ArgType>(fromRawValue rawValue: ArgType) throws -> Self /** Returns an array of all raw values available in the enum. */ static var allRawValues: [Any] { get } /** Type-erased enum's raw value. */ var anyRawValue: Any { get } } /** Extension for `EnumArgument` that also conforms to `RawRepresentable`. This constraint allows us to reference the associated `RawValue` type. */ public extension EnumArgument where Self: RawRepresentable, Self: Hashable { static func create<ArgType>(fromRawValue rawValue: ArgType) throws -> Self { guard let rawValue = rawValue as? RawValue else { throw EnumCastingException((type: RawValue.self, value: rawValue)) } guard let enumCase = Self.init(rawValue: rawValue) else { throw EnumNoSuchValueException((type: Self.self, value: rawValue)) } return enumCase } var anyRawValue: Any { rawValue } static var allRawValues: [Any] { // Be careful — it operates on unsafe pointers! let sequence = AnySequence { () -> AnyIterator<RawValue> in var raw = 0 return AnyIterator { let current: Self? = withUnsafePointer(to: &raw) { ptr in ptr.withMemoryRebound(to: Self.self, capacity: 1) { $0.pointee } } guard let value = current?.rawValue else { return nil } raw += 1 return value } } return Array(sequence) } } /** An error that is thrown when the value cannot be cast to associated `RawValue`. */ internal class EnumCastingException: GenericException<(type: Any.Type, value: Any)> { override var reason: String { "Unable to cast '\(param.value)' to expected type \(param.type)" } } /** An error that is thrown when the value doesn't match any available case. */ internal class EnumNoSuchValueException: GenericException<(type: EnumArgument.Type, value: Any)> { var allRawValuesFormatted: String { return param.type.allRawValues .map { "'\($0)'" } .joined(separator: ", ") } override var reason: String { "'\(param.value)' is not present in \(param.type) enum, it must be one of: \(allRawValuesFormatted)" } }
bsd-3-clause
2dd27817bfc0d25e2c54ef48fce969da
27.606061
104
0.674082
4.183161
false
false
false
false
drewag/Swiftlier
Sources/Swiftlier/Model/Types/Price.swift
1
1189
// // Price.swift // web // // Created by Andrew J Wagner on 4/23/17. // // import Foundation public struct Price: CustomStringConvertible { private static let currencyFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.currencySymbol = "" return formatter }() enum Value { case pennies(Int) case dollars(Double) } private let value: Value public init(pennies: Int) { self.value = .pennies(pennies) } public init(dollars: Double) { self.value = .dollars(dollars) } public var pennies: Int { switch self.value { case .pennies(let pennies): return pennies case .dollars(let dollars): return Int(round(dollars * 100)) } } public var dollars: Double { switch self.value { case .pennies(let pennies): return Double(pennies) / 100 case .dollars(let dollars): return dollars } } public var description: String { return Price.currencyFormatter.string(for: self.dollars) ?? "NA" } }
mit
a1cab81b99a052fcd0be7c70d7f09778
19.859649
72
0.581161
4.436567
false
false
false
false
box/box-ios-sdk
Sources/Responses/RetentionPolicyEntry.swift
1
1147
// // RetentionPolicyEntry.swift // BoxSDK-iOS // // Created by Martina Stremeňová on 9/2/19. // Copyright © 2019 box. All rights reserved. // import Foundation /// Retention policy entry public class RetentionPolicyEntry: BoxModel { private static var resourceType: String = "retention_policy" public private(set) var rawData: [String: Any] /// Box item type public var type: String /// Identifier public let id: String /// The name of the retention policy. public let name: String? public required init(json: [String: Any]) throws { guard let itemType = json["type"] as? String else { throw BoxCodingError(message: .typeMismatch(key: "type")) } guard itemType == RetentionPolicyEntry.resourceType else { throw BoxCodingError(message: .valueMismatch(key: "type", value: itemType, acceptedValues: [RetentionPolicyEntry.resourceType])) } rawData = json type = itemType id = try BoxJSONDecoder.decode(json: json, forKey: "id") name = try BoxJSONDecoder.optionalDecode(json: json, forKey: "policy_name") } }
apache-2.0
3da1e2651129f257bfc5497f03e04f12
29.105263
140
0.660839
4.129964
false
false
false
false
Viddi/ios-process-button
ProcessButton/ProcessButton/FlatButton.swift
1
2884
// // FlatButton.swift // ProcessButton // // Created by Vidar Ottosson on 2/7/15. // Copyright (c) 2015 Vidar Ottosson. All rights reserved. // import UIKit protocol FlatButtonDelegate { func showSuccess() func showError() } class FlatButton: UIButton { enum Colors { static let Success = UIColor(red: 153 / 255.0, green: 204 / 255.0, blue: 0 / 255.0, alpha: 1.0) static let Error = UIColor(red: 255 / 255.0, green: 68 / 255.0, blue: 68 / 255.0, alpha: 1.0) } var delegate: FlatButtonDelegate? override init(frame: CGRect) { super.init(frame: frame) prepareView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareView() } private func prepareView() { titleLabel?.font = UIFont.boldSystemFontOfSize(36.0) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted) setTitleColor(UIColor.whiteColor(), forState: UIControlState.Disabled) } private func showSuccess(text: String, seconds: Double) { delegate?.showSuccess() enabled = false var tempBackground = backgroundColor backgroundColor = Colors.Success var tempText = titleLabel?.text setTitle(text, forState: UIControlState.Normal) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.backgroundColor = tempBackground self.setTitle(tempText, forState: UIControlState.Normal) self.enabled = true } } private func showError(text: String, seconds: Double) { delegate?.showError() enabled = false var tempBackground = backgroundColor backgroundColor = Colors.Error var tempText = titleLabel?.text setTitle(text, forState: UIControlState.Normal) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { self.backgroundColor = tempBackground self.setTitle(tempText, forState: UIControlState.Normal) self.enabled = true } } func showSuccessText(text: String, seconds: Double) { showSuccess(text, seconds: seconds) } func showSuccessText(text: String) { showSuccess(text, seconds: ProcessButtonUtil.Length.Short) } func showErrorText(text: String, seconds: Double) { showError(text, seconds: seconds) } func showErrorText(text: String) { showError(text, seconds: ProcessButtonUtil.Length.Long) } func setBackgroundColor(normalState: UIColor, highlightedState: UIColor) { backgroundColor = normalState setBackgroundImage(ProcessButtonUtil.imageWithColor(highlightedState), forState: UIControlState.Highlighted) } }
mit
79b5b3ef63b55b40d84d6501f2c1c74d
28.428571
112
0.712552
4.241176
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Lint/WeakDelegateRule.swift
1
5629
import SwiftSyntax struct WeakDelegateRule: OptInRule, SwiftSyntaxRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "weak_delegate", name: "Weak Delegate", description: "Delegates should be weak to avoid reference cycles.", kind: .lint, nonTriggeringExamples: [ Example("class Foo {\n weak var delegate: SomeProtocol?\n}\n"), Example("class Foo {\n weak var someDelegate: SomeDelegateProtocol?\n}\n"), Example("class Foo {\n weak var delegateScroll: ScrollDelegate?\n}\n"), // We only consider properties to be a delegate if it has "delegate" in its name Example("class Foo {\n var scrollHandler: ScrollDelegate?\n}\n"), // Only trigger on instance variables, not local variables Example("func foo() {\n var delegate: SomeDelegate\n}\n"), // Only trigger when variable has the suffix "-delegate" to avoid false positives Example("class Foo {\n var delegateNotified: Bool?\n}\n"), // There's no way to declare a property weak in a protocol Example("protocol P {\n var delegate: AnyObject? { get set }\n}\n"), Example("class Foo {\n protocol P {\n var delegate: AnyObject? { get set }\n}\n}\n"), Example("class Foo {\n var computedDelegate: ComputedDelegate {\n return bar() \n} \n}"), Example(""" class Foo { var computedDelegate: ComputedDelegate { get { return bar() } } """), Example("struct Foo {\n @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate \n}"), Example("struct Foo {\n @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate \n}"), Example("struct Foo {\n @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var extensionDelegate \n}"), Example(""" class Foo { func makeDelegate() -> SomeDelegate { let delegate = SomeDelegate() return delegate } } """), Example(""" class Foo { var bar: Bool { let appDelegate = AppDelegate.bar return appDelegate.bar } } """, excludeFromDocumentation: true), Example("private var appDelegate: String?", excludeFromDocumentation: true) ], triggeringExamples: [ Example("class Foo {\n ↓var delegate: SomeProtocol?\n}\n"), Example("class Foo {\n ↓var scrollDelegate: ScrollDelegate?\n}\n"), Example(""" class Foo { ↓var delegate: SomeProtocol? { didSet { print("Updated delegate") } } """) ] ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } } private extension WeakDelegateRule { final class Visitor: ViolationsSyntaxVisitor { override var skippableDeclarations: [DeclSyntaxProtocol.Type] { [ ProtocolDeclSyntax.self ] } override func visitPost(_ node: VariableDeclSyntax) { guard node.hasDelegateSuffix, node.weakOrUnownedModifier == nil, !node.hasComputedBody, !node.containsIgnoredAttribute, let parent = node.parent, Syntax(parent).enclosingClass() != nil else { return } violations.append(node.letOrVarKeyword.positionAfterSkippingLeadingTrivia) } } } private extension Syntax { func enclosingClass() -> ClassDeclSyntax? { if let classExpr = self.as(ClassDeclSyntax.self) { return classExpr } else if self.as(DeclSyntax.self) != nil { return nil } return parent?.enclosingClass() } } private extension VariableDeclSyntax { var hasDelegateSuffix: Bool { bindings.allSatisfy { binding in guard let pattern = binding.pattern.as(IdentifierPatternSyntax.self) else { return false } return pattern.identifier.withoutTrivia().text.lowercased().hasSuffix("delegate") } } var hasComputedBody: Bool { bindings.allSatisfy { binding in guard let accessor = binding.accessor else { return false } if accessor.is(CodeBlockSyntax.self) { return true } else if accessor.as(AccessorBlockSyntax.self)?.getAccessor != nil { return true } return false } } var containsIgnoredAttribute: Bool { let ignoredAttributes: Set = [ "UIApplicationDelegateAdaptor", "NSApplicationDelegateAdaptor", "WKExtensionDelegateAdaptor" ] return attributes?.contains { attr in guard let customAttr = attr.as(CustomAttributeSyntax.self), let typeIdentifier = customAttr.attributeName.as(SimpleTypeIdentifierSyntax.self) else { return false } return ignoredAttributes.contains(typeIdentifier.name.withoutTrivia().text) } ?? false } }
mit
72740c87d9633f2f9b0235fb40d31312
35.751634
116
0.560377
5.453928
false
false
false
false
zakkhoyt/ColorPicKit
ColorPicKit/Classes/HSLASlider.swift
1
1430
// // HSLASlider.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/28/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit class HSLASlider: Slider { private var _saturation: CGFloat = 0.5 @IBInspectable public var saturation: CGFloat { get { return _saturation } set { if _saturation != newValue { _saturation = newValue hslaView.saturation = newValue updateKnobColor() } } } private var _lightness: CGFloat = 0.5 public var lightness: CGFloat { get { return _lightness } set { if _lightness != newValue { _lightness = newValue hslaView.lightness = newValue updateKnobColor() } } } fileprivate var hslaView = HSLASliderView() override func configureBackgroundView() { hslaView.borderColor = borderColor hslaView.borderWidth = borderWidth hslaView.roundedCorners = roundedCorners addSubview(hslaView) self.sliderView = hslaView } override func colorFrom(value: CGFloat) -> UIColor { let hue = value let hsla = HSLA(hue: hue, saturation: saturation, lightness: lightness) let color = hsla.color() return color } }
mit
0031abed7deb89f9bfb8ce8afa729730
22.816667
79
0.551435
5.253676
false
false
false
false
h-n-y/UICollectionView-TheCompleteGuide
chapter-6/ImprovedCoverFlow/CoverFlow/CoverFlowFlowLayout.swift
1
9520
// // CoverFlowFlowLayout.swift // CoverFlow // // Created by Hans Yelek on 5/1/16. // Copyright © 2016 Hans Yelek. All rights reserved. // import UIKit class CoverFlowFlowLayout: UICollectionViewFlowLayout { override class func layoutAttributesClass() -> AnyClass { return CollectionViewLayoutAttributes.self } override init() { super.init() setDefaultPropertyValues() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setDefaultPropertyValues() } private func setDefaultPropertyValues() { scrollDirection = .Horizontal itemSize = CGSize(width: 180, height: 180) // Get items up close to one another minimumLineSpacing = -60 // Makes sure we only have one row of items in portrait mode minimumInteritemSpacing = 200 } override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { // Very important - need to re-layout the cells when scrolling return true } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let layoutAttributesArray = super.layoutAttributesForElementsInRect(rect) else { return nil } guard let collectionView = self.collectionView else { return layoutAttributesArray } // Calculate the rect of the collection view visible to the user let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.width, height: collectionView.bounds.height) for attributes in layoutAttributesArray { // Only modify attributes whose frames intersect the visible portion of the collection view if CGRectIntersectsRect(attributes.frame, rect) { applyLayoutAttributes(attributes, forVisibleRect: visibleRect) } } return layoutAttributesArray } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { guard let attributes = super.layoutAttributesForItemAtIndexPath(indexPath) else { return nil } guard let collectionView = self.collectionView else { return attributes } // Calculate the rect of the collection view visible to the user let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.width, height: collectionView.bounds.height) applyLayoutAttributes(attributes, forVisibleRect: visibleRect) return attributes } // Forces collection view to center a cell once scrolling has stopped. override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = self.collectionView else { return super.targetContentOffsetForProposedContentOffset(proposedContentOffset, withScrollingVelocity: velocity) } var offsetAdjustment = MAXFLOAT let horizontalCenter: CGFloat = proposedContentOffset.x + collectionView.bounds.width / 2.0 // Use the center to find the proposed visible rect. let proposedRect = CGRect(x: 0, y: 0, width: collectionView.bounds.width, height: collectionView.bounds.height) // Get the attributes for the cells in that rect. guard let layoutAttributes = layoutAttributesForElementsInRect(proposedRect) else { return super.targetContentOffsetForProposedContentOffset(proposedContentOffset, withScrollingVelocity: velocity) } // This loop will find the closest cell to proposed center // of the collection view for attributes in layoutAttributes { // Skip supplementary views if attributes.representedElementCategory != .Cell { continue } // Determine if this layout attribute's cell is closer than the closest // we have so far. let itemHorizontalCenter: CGFloat = attributes.center.x if fabs(itemHorizontalCenter - horizontalCenter) < CGFloat(fabs(offsetAdjustment)) { offsetAdjustment = Float(itemHorizontalCenter - horizontalCenter) } } return CGPoint(x: proposedContentOffset.x + CGFloat(offsetAdjustment), y: proposedContentOffset.y) } // Applies the cover flow effect to the given layout attributes private func applyLayoutAttributes(attributes: UICollectionViewLayoutAttributes, forVisibleRect visibleRect: CGRect) { // Ignore supplementary views. guard attributes.representedElementKind == nil else { return } guard let attributes = attributes as? CollectionViewLayoutAttributes else { return } let ACTIVE_DISTANCE: CGFloat = 100.0 let TRANSLATE_DISTANCE: CGFloat = 100.0 let ZOOM_FACTOR: CGFloat = 0.2 let FLOW_OFFSET: CGFloat = 40.0 let INACTIVE_GRAY_VALUE: CGFloat = 0.6 // Calculate the distance from the center of the visible rect to the center // of the attributes. Then normalize the distance so we can compare them all. // This way, all items further away than the active get the same transform. let distanceFromVisibleRectToItem: CGFloat = CGRectGetMidX(visibleRect) - attributes.center.x let normalizedDistance: CGFloat = distanceFromVisibleRectToItem / ACTIVE_DISTANCE let isLeft = distanceFromVisibleRectToItem > 0 // Default values var transform = CATransform3DIdentity var maskAlpha: CGFloat = 0.0 if fabs(distanceFromVisibleRectToItem) < ACTIVE_DISTANCE { // We're close enough to apply the transform in relation to // how far away from the center we are transform = CATransform3DTranslate(CATransform3DIdentity, (isLeft ? -FLOW_OFFSET: FLOW_OFFSET) * abs(distanceFromVisibleRectToItem / TRANSLATE_DISTANCE ), 0, (1 - fabs(normalizedDistance)) * 40_000.0 + (isLeft ? 200.0 : 0.0)) // Set the perspective of the transform transform.m34 = -1.0 / (4.6777 * itemSize.width) // Set the rotation of the transform transform = CATransform3DRotate(transform, (isLeft ? 1 : -1) * fabs(normalizedDistance) * CGFloat(45).radians(), 0, 1, 0) // Set the zoom factor let zoom: CGFloat = 1 + ZOOM_FACTOR * ( 1 - abs(normalizedDistance) ) transform = CATransform3DScale(transform, zoom, zoom, 1) attributes.zIndex = 1 let ratioToCenter = ( ACTIVE_DISTANCE - fabs(distanceFromVisibleRectToItem)) / ACTIVE_DISTANCE // Interpolate between 0.0 and INACTIVE_GRAY_VALUE maskAlpha = INACTIVE_GRAY_VALUE + ratioToCenter * (-INACTIVE_GRAY_VALUE) } else { // We're too far away; just apply a standard perpective transform transform.m34 = -1 / ( 4.6777 * itemSize.width ) transform = CATransform3DTranslate(transform, isLeft ? -FLOW_OFFSET : FLOW_OFFSET, 0, 0) transform = CATransform3DRotate(transform, ( isLeft ? 1 : -1 ) * CGFloat(45).radians(), 0, 1, 0) attributes.zIndex = 0 maskAlpha = INACTIVE_GRAY_VALUE } attributes.transform3D = transform // Rasterize the cells for smoother edges attributes.shouldRasterize = true attributes.maskingValue = maskAlpha } } extension CoverFlowFlowLayout { func indexPathIsCentered(indexPath: NSIndexPath) -> Bool { guard let collectionView = self.collectionView else { return false } guard let attributes = layoutAttributesForItemAtIndexPath(indexPath) else { return false } let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.width, height: collectionView.bounds.height) let distanceFromVisibleRectToItem: CGFloat = CGRectGetMidX(visibleRect) - attributes.center.x return fabs(distanceFromVisibleRectToItem) < 1 } } extension CGFloat { /// Assumes that `self`'s current value is in terms of *degrees* and returns /// the *radian* equivalent. func radians() -> CGFloat { return self * CGFloat(M_PI / 180.0) } }
mit
6958073cd6bec71966685279a1dc8a73
44.113744
147
0.60437
5.945659
false
false
false
false
aestusLabs/ASChatApp
Colours.swift
1
5538
// // Colours.swift // ChatAppOrigionalFiles // // Created by Ian Kohlert on 2017-07-19. // Copyright © 2017 aestusLabs. All rights reserved. // import Foundation import UIKit enum ColourTheme { case light, dark } struct Colours { func getMainAppColour() -> UIColor{ return appInfo.appColourMain } let appColourLeft = UIColor(red: 1.0, green: 0.325490196, blue: 0.541176471, alpha: 1.0) let appColourRight = UIColor(red: 1.0, green: 0.494117647, blue: 0.435294118, alpha: 1.0) private let lightBackground = UIColor(red: 0.960784314, green: 0.960784314, blue: 0.960784314, alpha: 1.0) private let darkBackground = UIColor.black private let lightHelperBarBackground = UIColor.white private let darkHelperBarBackground = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightTextColour = UIColor.black private let darkTextColour = UIColor.white private let lightEmptyHelperCircle = UIColor(red: 0.290196078, green: 0.290196078, blue: 0.290196078, alpha: 1.0) private let darkEmptyHelperCircle = UIColor.white //UIColor(red: 0.901960784, green: 0.901960784, blue: 0.901960784, alpha: 1.0) private let lightHelperSuggestionColour = UIColor.white private let darkHelperSuggestionColour = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightSliderColour = UIColor.black private let darkSliderColour = UIColor.white private let appGradientLeft = UIColor(red: 1.0, green: 0.325490196, blue: 0.541176471, alpha: 1.0) private let appGradientRight = UIColor(red: 1.0, green: 0.494117647, blue: 0.435294118, alpha: 1.0) private let lightOnboardBehindTextField = UIColor.white private let darktOnboardBehindTextField = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightWhite = UIColor.white private let darkGrey = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightMask = UIColor.white private let darkMask = UIColor(red: 0.231372549, green: 0.231372549, blue: 0.231372549, alpha: 1.0) private let lightHelperSuggestionExpandedBackground = UIColor(red: 0.956862745, green: 0.956862745, blue: 0.956862745, alpha: 1.0) private let lightBehindHelperTextHomeBackground = UIColor(red: 0.988235294, green: 0.988235294, blue: 0.988235294, alpha: 1.0) private let lightCardBackgroundColour = UIColor.white private let darkCardBackgroundColour = UIColor.lightGray private let lightSessionWidgetHighlightColour = UIColor(red: 0.980392157, green: 0.980392157, blue: 0.980392157, alpha: 1.0) private let darkSessionWidgetHighlightColour = UIColor(red: 0.094117647, green: 0.094117647, blue: 0.094117647, alpha: 1.0) func getBackgroundColour() -> UIColor { if ASUser.colourTheme == .light { return lightBackground } else { return darkBackground } } func getHelperBarBackgroundColour() -> UIColor { if ASUser.colourTheme == .light { return lightHelperBarBackground } else { return darkHelperBarBackground } } func getTextColour() -> UIColor { if ASUser.colourTheme == .light { return lightTextColour } else { return darkTextColour } } func getEmptyHelperColour() -> UIColor { if ASUser.colourTheme == .light { return lightEmptyHelperCircle } else { return darkEmptyHelperCircle } } func getHelperSuggestionColour() -> UIColor { if ASUser.colourTheme == .light { return lightHelperSuggestionColour } else { return darkHelperSuggestionColour } } func getSliderColour() -> UIColor { if ASUser.colourTheme == .light { return lightSliderColour } else { return darkSliderColour } } func getGradientColours() -> (UIColor, UIColor) { return (appGradientLeft, appGradientRight) } func getOnboardBehindTextFieldColours() -> UIColor { if ASUser.colourTheme == .light { return lightOnboardBehindTextField } else { return darktOnboardBehindTextField } } func getLineBackground() -> UIColor { if ASUser.colourTheme == .light { return lightWhite } else { return darkGrey } } func getMaskColour() -> UIColor { if ASUser.colourTheme == .light { return lightMask } else { return darkMask } } func getHelperExpandedSuggestionBackground() -> UIColor { return lightHelperSuggestionExpandedBackground } func getBehindHelperTextHomeBackground() -> UIColor { return lightBehindHelperTextHomeBackground } func getCardBackgroundColour() -> UIColor { if ASUser.colourTheme == .light { return lightCardBackgroundColour } else { return darkCardBackgroundColour } } func getContentSessionWidgetHightlightColout () -> UIColor { if ASUser.colourTheme == .light { return lightSessionWidgetHighlightColour } else { return darkSessionWidgetHighlightColour } } } let appColours = Colours()
mit
984da541379ca1f83b38a5879c66b6bc
32.762195
134
0.649269
4.433147
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/Analytics/EditorAnalytics/PostEditorAnalyticsSessionTests.swift
1
7033
import Foundation import XCTest @testable import WordPress class PostEditorAnalyticsSessionTests: CoreDataTestCase { enum PostContent { static let classic = """ Text <strong>bold</strong> <em>italic</em> """ static let gutenberg = """ <!-- wp:image {"id":-181231834} --> <figure class="wp-block-image"><img src="file://tmp/EC856C66-7B79-4631-9503-2FB9FF0E6C66.jpg" alt="" class="wp-image--181231834"/></figure> <!-- /wp:image --> """ } override func setUp() { TestAnalyticsTracker.setup() } override func tearDown() { TestAnalyticsTracker.tearDown() } func testStartGutenbergSessionWithoutContentAndTitle() { startSession(editor: .gutenberg) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) XCTAssertEqual(tracked?.value(for: "content_type"), PostEditorAnalyticsSession.ContentType.new.rawValue) XCTAssertEqual(tracked?.value(for: "editor"), PostEditorAnalyticsSession.Editor.gutenberg.rawValue) } func testStartGutenbergSessionWithTitleButNoContent() { startSession(editor: .gutenberg, postTitle: "Title") XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) XCTAssertEqual(tracked?.value(for: "content_type"), PostEditorAnalyticsSession.ContentType.new.rawValue) XCTAssertEqual(tracked?.value(for: "editor"), PostEditorAnalyticsSession.Editor.gutenberg.rawValue) } func testStartGutenbergSessionWithTitleAndContent() { startSession(editor: .gutenberg, postTitle: "Title", postContent: PostContent.gutenberg) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) XCTAssertEqual(tracked?.value(for: "content_type"), PostEditorAnalyticsSession.ContentType.gutenberg.rawValue) XCTAssertEqual(tracked?.value(for: "editor"), PostEditorAnalyticsSession.Editor.gutenberg.rawValue) } func testTrackUnsupportedBlocksOnStart() { let unsupportedBlocks = ["unsupported"] startSession(editor: .gutenberg, unsupportedBlocks: unsupportedBlocks) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) let serializedArray = String(data: try! JSONSerialization.data(withJSONObject: unsupportedBlocks, options: .fragmentsAllowed), encoding: .utf8) XCTAssertEqual(tracked?.value(for: "unsupported_blocks"), serializedArray) XCTAssertEqual(tracked?.value(for: "has_unsupported_blocks"), "1") } func testTrackUnsupportedBlocksOnStartWithEmptyList() { let unsupportedBlocks = [String]() startSession(editor: .gutenberg, unsupportedBlocks: unsupportedBlocks) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) let serializedArray = String(data: try! JSONSerialization.data(withJSONObject: unsupportedBlocks, options: .fragmentsAllowed), encoding: .utf8) XCTAssertEqual(tracked?.value(for: "unsupported_blocks"), serializedArray) XCTAssertEqual(tracked?.value(for: "has_unsupported_blocks"), "0") } func testTrackUnsupportedBlocksOnSwitch() { let unsupportedBlocks = ["unsupported"] var session = startSession(editor: .gutenberg, unsupportedBlocks: unsupportedBlocks) session.switch(editor: .gutenberg) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 2) let tracked = TestAnalyticsTracker.tracked.last XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionSwitchEditor) XCTAssertEqual(tracked?.value(for: "has_unsupported_blocks"), "1") let trackedUnsupportedBlocks: [String]? = tracked?.value(for: "unsupported_blocks") XCTAssertNil(trackedUnsupportedBlocks) } func testTrackUnsupportedBlocksOnEnd() { let unsupportedBlocks = ["unsupported"] let session = startSession(editor: .gutenberg, unsupportedBlocks: unsupportedBlocks) session.end(outcome: .publish) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 2) let tracked = TestAnalyticsTracker.tracked.last XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionEnd) XCTAssertEqual(tracked?.value(for: "has_unsupported_blocks"), "1") let trackedUnsupportedBlocks: [String]? = tracked?.value(for: "unsupported_blocks") XCTAssertNil(trackedUnsupportedBlocks) } func testTrackBlogIdOnStart() { startSession(editor: .gutenberg, blogID: 123) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 1) let tracked = TestAnalyticsTracker.tracked.first XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionStart) XCTAssertEqual(tracked?.value(for: "blog_id"), "123") } func testTrackBlogIdOnSwitch() { var session = startSession(editor: .gutenberg, blogID: 456) session.switch(editor: .gutenberg) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 2) let tracked = TestAnalyticsTracker.tracked.last XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionSwitchEditor) XCTAssertEqual(tracked?.value(for: "blog_id"), "456") } func testTrackBlogIdOnEnd() { let session = startSession(editor: .gutenberg, blogID: 789) session.end(outcome: .publish) XCTAssertEqual(TestAnalyticsTracker.tracked.count, 2) let tracked = TestAnalyticsTracker.tracked.last XCTAssertEqual(tracked?.stat, WPAnalyticsStat.editorSessionEnd) XCTAssertEqual(tracked?.value(for: "blog_id"), "789") } } extension PostEditorAnalyticsSessionTests { func createPost(title: String? = nil, body: String? = nil, blogID: NSNumber? = nil) -> AbstractPost { let post = AbstractPost(context: mainContext) post.postTitle = title post.content = body post.blog = Blog(context: mainContext) post.blog.dotComID = blogID return post } @discardableResult func startSession(editor: PostEditorAnalyticsSession.Editor, postTitle: String? = nil, postContent: String? = nil, unsupportedBlocks: [String] = [], blogID: NSNumber? = nil) -> PostEditorAnalyticsSession { let post = createPost(title: postTitle, body: postContent, blogID: blogID) var session = PostEditorAnalyticsSession(editor: .gutenberg, post: post) session.start(unsupportedBlocks: unsupportedBlocks) return session } }
gpl-2.0
d39ca954239d59e26134d793120d71b0
39.653179
209
0.711503
5.126093
false
true
false
false
NobodyNada/SwiftStack
Sources/SwiftStack/Post.swift
1
5883
// // Post.swift // SwiftStack // // Created by FelixSFD on 06.12.16. // // import Foundation // - MARK: The type of the post /** Defines the type of a post. Either a question or an answer - author: FelixSFD */ public enum PostType: String, StringRepresentable { case answer = "answer" case question = "question" } // - MARK: Post /** The base class of `Question`s and `Answer`s - author: FelixSFD - seealso: [StackExchange API](https://api.stackexchange.com/docs/types/post) */ public class Post: Content { // - MARK: Post.Notice /** Represents a notice on a post. - author: FelixSFD */ public struct Notice: JsonConvertible { public init?(jsonString json: String) { do { guard let dictionary = try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments) as? [String: Any] else { return nil } self.init(dictionary: dictionary) } catch { return nil } } public init(dictionary: [String: Any]) { self.body = dictionary["body"] as? String if let timestamp = dictionary["creation_date"] as? Int { self.creation_date = Date(timeIntervalSince1970: Double(timestamp)) } self.owner_user_id = dictionary["owner_user_id"] as? Int } public var dictionary: [String: Any] { var dict = [String: Any]() dict["body"] = body dict["creation_date"] = creation_date dict["owner_user_id"] = owner_user_id return dict } public var jsonString: String? { return (try? JsonHelper.jsonString(from: self)) ?? nil } public var body: String? public var creation_date: Date? public var owner_user_id: Int? } // - MARK: Initializers /** Basic initializer without default values */ public override init() { super.init() } /** Initializes the object from a JSON string. - parameter json: The JSON string returned by the API - author: FelixSFD */ public required convenience init?(jsonString json: String) { do { guard let dictionary = try JSONSerialization.jsonObject(with: json.data(using: String.Encoding.utf8)!, options: .allowFragments) as? [String: Any] else { return nil } self.init(dictionary: dictionary) } catch { return nil } } public required init(dictionary: [String: Any]) { super.init(dictionary: dictionary) //only initialize the properties that are not part of the superclass self.comment_count = dictionary["comment_count"] as? Int if let commentsArray = dictionary["comments"] as? [[String: Any]] { var commentsTmp = [Comment]() for commentDictionary in commentsArray { let commentTmp = Comment(dictionary: commentDictionary) commentsTmp.append(commentTmp) } } self.down_vote_count = dictionary["down_vote_count"] as? Int self.downvoted = dictionary["downvoted"] as? Bool if let timestamp = dictionary["creation_date"] as? Int { self.creation_date = Date(timeIntervalSince1970: Double(timestamp)) } if let timestamp = dictionary["last_activity_date"] as? Int { self.last_activity_date = Date(timeIntervalSince1970: Double(timestamp)) } if let timestamp = dictionary["last_edit_date"] as? Int { self.last_edit_date = Date(timeIntervalSince1970: Double(timestamp)) } if let user = dictionary["last_editor"] as? [String: Any] { self.last_editor = User(dictionary: user) } if let urlString = dictionary["share_link"] as? String { self.share_link = URL(string: urlString) } self.title = (dictionary["title"] as? String)?.stringByDecodingHTMLEntities self.up_vote_count = dictionary["up_vote_count"] as? Int } // - MARK: JsonConvertible public override var dictionary: [String: Any] { var dict = super.dictionary dict["creation_date"] = creation_date dict["comment_count"] = comment_count if comments != nil && (comments?.count)! > 0 { var tmpComments = [[String: Any]]() for comment in comments! { tmpComments.append(comment.dictionary) } dict["comments"] = tmpComments } dict["down_vote_count"] = down_vote_count dict["downvoted"] = downvoted dict["last_activity_date"] = last_activity_date dict["last_edit_date"] = last_edit_date dict["last_editor"] = last_editor?.dictionary dict["share_link"] = share_link dict["title"] = title dict["up_vote_count"] = up_vote_count return dict } // - MARK: Fields public var creation_date: Date? public var comment_count: Int? public var comments: [Comment]? public var down_vote_count: Int? public var downvoted: Bool? public var last_activity_date: Date? public var last_edit_date: Date? public var last_editor: User? public var share_link: URL? public var title: String? public var up_vote_count: Int? }
mit
8920704b374567708dcc689d2707399a
26.75
169
0.54479
4.661648
false
false
false
false
mgiraldo/watchOS-animations-test
watchSample/FrameLoader.swift
1
1100
// // FrameLoader.swift // watchSample // // Created by Mauricio Giraldo on 2/5/16. // import Foundation class FrameLoader { static func loadFrames()-> Array<NSData> { let frame1 = FrameLoader.getFile("1") let frame2 = FrameLoader.getFile("2") let frame3 = FrameLoader.getFile("3") let frame4 = FrameLoader.getFile("4") let frame5 = FrameLoader.getFile("5") let frame6 = FrameLoader.getFile("6") var frames = [NSData]() frames.append(frame1) frames.append(frame2) frames.append(frame3) frames.append(frame4) frames.append(frame5) frames.append(frame6) return frames } static func getFile(name:String)-> NSData { let bundles = NSBundle.allBundles() var file : NSData? for bundle in bundles { if let resourcePath = (bundle).pathForResource(name, ofType: "png") { file = NSData(contentsOfFile: resourcePath) return file! } } return file! } }
mit
044fb9c0cc25a4c0a9b2c4d7d0a320ba
24.604651
81
0.565455
4.38247
false
false
false
false
sol/aeson
tests/JSONTestSuite/parsers/test_PMJSON_1_1_0/Encoder.swift
6
6183
// // Encoder.swift // PMJSON // // Created by Kevin Ballard on 2/1/16. // Copyright © 2016 Postmates. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // extension JSON { /// Encodes a `JSON` to a `String`. /// - Parameter json: The `JSON` to encode. /// - Parameter pretty: If `true`, include extra whitespace for formatting. Default is `false`. /// - Returns: A `String` with the JSON representation of *json*. public static func encodeAsString(_ json: JSON, pretty: Bool = false) -> String { var s = "" encode(json, toStream: &s, pretty: pretty) return s } /// Encodes a `JSON` to an output stream. /// - Parameter json: The `JSON` to encode. /// - Parameter stream: The output stream to write the encoded JSON to. /// - Parameter pretty: If `true`, include extra whitespace for formatting. Default is `false`. public static func encode<Target: TextOutputStream>(_ json: JSON, toStream stream: inout Target, pretty: Bool = false) { encode(json, toStream: &stream, indent: pretty ? 0 : nil) } private static func encode<Target: TextOutputStream>(_ json: JSON, toStream stream: inout Target, indent: Int?) { switch json { case .null: encodeNull(&stream) case .bool(let b): encodeBool(b, toStream: &stream) case .int64(let i): encodeInt64(i, toStream: &stream) case .double(let d): encodeDouble(d, toStream: &stream) case .string(let s): encodeString(s, toStream: &stream) case .object(let obj): encodeObject(obj, toStream: &stream, indent: indent) case .array(let ary): encodeArray(ary, toStream: &stream, indent: indent) } } private static func encodeNull<Target: TextOutputStream>(_ stream: inout Target) { stream.write("null") } private static func encodeBool<Target: TextOutputStream>(_ value: Bool, toStream stream: inout Target) { stream.write(value ? "true" : "false") } private static func encodeInt64<Target: TextOutputStream>(_ value: Int64, toStream stream: inout Target) { stream.write(String(value)) } private static func encodeDouble<Target: TextOutputStream>(_ value: Double, toStream stream: inout Target) { stream.write(String(value)) } private static func encodeString<Target: TextOutputStream>(_ value: String, toStream stream: inout Target) { stream.write("\"") let scalars = value.unicodeScalars var start = scalars.startIndex let end = scalars.endIndex var idx = start while idx < scalars.endIndex { let s: String let c = scalars[idx] switch c { case "\\": s = "\\\\" case "\"": s = "\\\"" case "\n": s = "\\n" case "\r": s = "\\r" case "\t": s = "\\t" case "\u{8}": s = "\\b" case "\u{C}": s = "\\f" case "\0"..<"\u{10}": s = "\\u000\(String(c.value, radix: 16, uppercase: true))" case "\u{10}"..<" ": s = "\\u00\(String(c.value, radix: 16, uppercase: true))" default: idx = scalars.index(after: idx) continue } if idx != start { stream.write(String(scalars[start..<idx])) } stream.write(s) idx = scalars.index(after: idx) start = idx } if start != end { String(scalars[start..<end]).write(to: &stream) } stream.write("\"") } private static func encodeObject<Target: TextOutputStream>(_ object: JSONObject, toStream stream: inout Target, indent: Int?) { let indented = indent.map({$0+1}) if let indent = indented { stream.write("{\n") writeIndent(indent, toStream: &stream) } else { stream.write("{") } var first = true for (key, value) in object { if first { first = false } else if let indent = indented { stream.write(",\n") writeIndent(indent, toStream: &stream) } else { stream.write(",") } encodeString(key, toStream: &stream) stream.write(indented != nil ? ": " : ":") encode(value, toStream: &stream, indent: indented) } if let indent = indent { stream.write("\n") writeIndent(indent, toStream: &stream) } stream.write("}") } private static func encodeArray<Target: TextOutputStream>(_ array: JSONArray, toStream stream: inout Target, indent: Int?) { let indented = indent.map({$0+1}) if let indent = indented { stream.write("[\n") writeIndent(indent, toStream: &stream) } else { stream.write("[") } var first = true for elt in array { if first { first = false } else if let indent = indented { stream.write(",\n") writeIndent(indent, toStream: &stream) } else { stream.write(",") } encode(elt, toStream: &stream, indent: indented) } if let indent = indent { stream.write("\n") writeIndent(indent, toStream: &stream) } stream.write("]") } private static func writeIndent<Target: TextOutputStream>(_ indent: Int, toStream stream: inout Target) { for _ in stride(from: 4, through: indent, by: 4) { stream.write(" ") } switch indent % 4 { case 1: stream.write(" ") case 2: stream.write(" ") case 3: stream.write(" ") default: break } } }
bsd-3-clause
54b4f507d81da446a3fd042feb5f48b3
36.017964
131
0.540925
4.314027
false
false
false
false
LittoCats/coffee-mobile
CoffeeMobile/Base/Utils/UIKitExtension/CMNSAttributedStringExtension.swift
1
8954
// // CMNSAttributedStringExtension.swift // CoffeeMobile // // Created by 程巍巍 on 5/25/15. // Copyright (c) 2015 Littocats. All rights reserved. // import Foundation import UIKit import XMLNode extension NSAttributedString { /** MARK: 由自定义的 xml 字符串生成 attributedString 支持的 属性参照 NSAttributedString.XMLParser.ExpressionMap */ convenience init(xml: String){ self.init(xml:xml, defaultAttribute: [String: AnyObject]()) } convenience init(xml: String, defaultAttribute: [String: AnyObject]){ self.init(attributedString: XMLParser(xml: xml,defaultAttribute: defaultAttribute).start().maString) } private class XMLParser: NSObject, NSXMLParserDelegate { private var maString = NSMutableAttributedString() private var xml: String! private var attrStack = [[String: AnyObject]]() init(xml: String, defaultAttribute: [String: AnyObject]){ super.init() attrStack.append(defaultAttribute) self.xml = "<xml>\(xml)</xml>" } func start()-> XMLParser { let parser = NSXMLParser(data: xml.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) parser.delegate = self var flag = parser.parse() return self } //MARK: 解析标签 @objc func parserDidStartDocument(parser: NSXMLParser){ if attrStack.isEmpty { attrStack.append([String: AnyObject]()) } } @objc func parserDidEndDocument(parser: NSXMLParser){ } @objc func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]){ var attr = attrStack.last! for (key, value) in attributeDict { if let name = (key as? String)?.lowercaseString { if let closure = XMLParser.ExpressionMap[(key as! String).lowercaseString] { for (k,v) in closure(key: name, value: value as! String){ attr[k] = v } } } } attrStack.append(attr) } @objc func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){ attrStack.removeLast() } @objc func parser(parser: NSXMLParser, foundCharacters string: String?){ if let str = string { buildString(str) } } @objc func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError){ println(parseError) } //MARK: 解析文本 private func buildString(str: String) { var string = str if var at = attrStack.last{ // font var font: UIFont? var family = at[CMTextFontFamilyAttributeName] as? String var size = at[CMTextFontSizeAttributeName] as? Float if size == nil {size = 17} if family == nil { font = UIFont.systemFontOfSize(CGFloat(size!)) }else{ font = UIFont(name: family!, size: CGFloat(size!)) } if font != nil { at[NSFontAttributeName] = font! } at.removeValueForKey(CMTextFontFamilyAttributeName) at.removeValueForKey(CMTextFontSizeAttributeName) // paragraph var para = NSMutableParagraphStyle() if let align = at[CMTextAlignmentAttributeName] as? Int { para.alignment = NSTextAlignment(rawValue: align)! at.removeValueForKey(CMTextAlignmentAttributeName) } if let firstLineHeadIndent = at[CMTextFirstLineHeadIndentAttributeName] as? Float { para.firstLineHeadIndent = CGFloat(firstLineHeadIndent) at.removeValueForKey(CMTextFirstLineHeadIndentAttributeName) } if let headIndent = at[CMTextHeadIndentAttributeName] as? Float { para.headIndent = CGFloat(headIndent) at.removeValueForKey(CMTextHeadIndentAttributeName) } if let tailIndent = at[CMTextTailIndentAttributeName] as? Float { para.tailIndent = CGFloat(tailIndent) at.removeValueForKey(CMTextTailIndentAttributeName) } if let lineSpace = at[CMTextLineSpaceAttributeName] as? Float { para.lineSpacing = CGFloat(lineSpace) at.removeValueForKey(CMTextLineSpaceAttributeName) } at[NSParagraphStyleAttributeName] = para // append maString.appendAttributedString(NSAttributedString(string: str, attributes: at)) }else{ maString.appendAttributedString(NSAttributedString(string: str)) } } } } private let CMTextFontFamilyAttributeName = "CMTextFontFamilyAttributeName" private let CMTextFontSizeAttributeName = "CMTextFontSizeAttributeName" private let CMTextAlignmentAttributeName = "NSTextAlignmentAttributeName" private let CMTextFirstLineHeadIndentAttributeName = "CMTextFirstLineHeadIndentAttributeName" private let CMTextHeadIndentAttributeName = "CMTextHeadIndentAttributeName" private let CMTextTailIndentAttributeName = "CMTextTailIndentAttributeName" private let CMTextLineSpaceAttributeName = "CMTextLineSpaceAttributeName" private func FloatValue(str: String)->Float { var float = (str as NSString).floatValue return float } extension NSAttributedString.XMLParser { typealias EXP = (key: String, value: String)->[String: AnyObject] static var ExpressionMap: [String: EXP] = [ // foreground/background color "color": {EXP in [NSForegroundColorAttributeName: UIColor(script: EXP.1)]}, "bgcolor": {EXP in [NSBackgroundColorAttributeName: UIColor(script: EXP.1)]}, // font "font": {EXP in [CMTextFontFamilyAttributeName: EXP.1]}, "size": {EXP in [CMTextFontSizeAttributeName: FloatValue(EXP.1)]}, // under line "underline": {EXP in [NSUnderlineStyleAttributeName: FloatValue(EXP.1)]}, "ul": {EXP in if EXP.0 == EXP.1 { return [NSUnderlineStyleAttributeName: 1] } return [NSUnderlineStyleAttributeName: FloatValue(EXP.1)] }, "underlinecolor": {EXP in [NSUnderlineColorAttributeName: UIColor(script: EXP.1)]}, "ulcolor": {EXP in [NSUnderlineColorAttributeName: UIColor(script: EXP.1)]}, // strike though "strikethrough": {EXP in [NSStrikethroughStyleAttributeName: FloatValue(EXP.1)]}, "st": {EXP in if EXP.0 == EXP.1 { return [NSStrikethroughStyleAttributeName: 1] } return [NSStrikethroughStyleAttributeName: FloatValue(EXP.1)] }, "strikethroughcolor": {EXP in [NSStrikethroughColorAttributeName: UIColor(script: EXP.1)]}, "stcolor": {EXP in [NSStrikethroughColorAttributeName: UIColor(script: EXP.1)]}, // stroke 可以间接实现 字体加粗效果 "strokecolor": {EXP in [NSStrikethroughColorAttributeName: UIColor(script: EXP.1)]}, "stroke": {EXP in [NSStrokeWidthAttributeName: FloatValue(EXP.1)]}, // paragraph // text align "algin": { EXP in switch EXP.1 { case "-|","right": return [CMTextAlignmentAttributeName: NSTextAlignment.Right.rawValue] case "||","center": return [CMTextAlignmentAttributeName: NSTextAlignment.Center.rawValue] default: return [CMTextAlignmentAttributeName: NSTextAlignment.Left.rawValue] } }, // 缩紧 "firstlineindent": {EXP in [CMTextFirstLineHeadIndentAttributeName: FloatValue(EXP.1)]}, "flindent": {EXP in [CMTextFirstLineHeadIndentAttributeName: FloatValue(EXP.1)]}, "headindent": {EXP in [CMTextHeadIndentAttributeName: FloatValue(EXP.1)]}, "hindent": {EXP in [CMTextHeadIndentAttributeName: FloatValue(EXP.1)]}, "trailindent": {EXP in [CMTextTailIndentAttributeName: FloatValue(EXP.1)]}, "tindent": {EXP in [CMTextTailIndentAttributeName: FloatValue(EXP.1)]}, "linespace": {EXP in [CMTextLineSpaceAttributeName: FloatValue(EXP.1)]}, ] }
apache-2.0
204cc6e05d106bf6cd4eb453ad9f534e
40.260465
187
0.597632
5.56811
false
false
false
false
michael-lehew/swift-corelibs-foundation
Foundation/NSError.swift
1
57255
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import CoreFoundation public typealias NSErrorDomain = NSString /// Predefined domain for errors from most Foundation APIs. public let NSCocoaErrorDomain: String = "NSCocoaErrorDomain" // Other predefined domains; value of "code" will correspond to preexisting values in these domains. public let NSPOSIXErrorDomain: String = "NSPOSIXErrorDomain" public let NSOSStatusErrorDomain: String = "NSOSStatusErrorDomain" public let NSMachErrorDomain: String = "NSMachErrorDomain" // Key in userInfo. A recommended standard way to embed NSErrors from underlying calls. The value of this key should be an NSError. public let NSUnderlyingErrorKey: String = "NSUnderlyingError" // Keys in userInfo, for subsystems wishing to provide their error messages up-front. Note that NSError will also consult the userInfoValueProvider for the domain when these values are not present in the userInfo dictionary. public let NSLocalizedDescriptionKey: String = "NSLocalizedDescription" public let NSLocalizedFailureReasonErrorKey: String = "NSLocalizedFailureReason" public let NSLocalizedRecoverySuggestionErrorKey: String = "NSLocalizedRecoverySuggestion" public let NSLocalizedRecoveryOptionsErrorKey: String = "NSLocalizedRecoveryOptions" public let NSRecoveryAttempterErrorKey: String = "NSRecoveryAttempter" public let NSHelpAnchorErrorKey: String = "NSHelpAnchor" // Other standard keys in userInfo, for various error codes public let NSStringEncodingErrorKey: String = "NSStringEncodingErrorKey" public let NSURLErrorKey: String = "NSURL" public let NSFilePathErrorKey: String = "NSFilePathErrorKey" open class NSError : NSObject, NSCopying, NSSecureCoding, NSCoding { typealias CFType = CFError internal var _cfObject: CFType { return CFErrorCreate(kCFAllocatorSystemDefault, domain._cfObject, code, nil) } // ErrorType forbids this being internal open var _domain: String open var _code: Int /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. private var _userInfo: [String : Any]? /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. public init(domain: String, code: Int, userInfo dict: [String : Any]? = nil) { _domain = domain _code = code _userInfo = dict } public required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } _code = aDecoder.decodeInteger(forKey: "NSCode") _domain = aDecoder.decodeObject(of: NSString.self, forKey: "NSDomain")!._swiftObject if let info = aDecoder.decodeObject(of: [NSSet.self, NSDictionary.self, NSArray.self, NSString.self, NSNumber.self, NSData.self, NSURL.self], forKey: "NSUserInfo") as? NSDictionary { var filteredUserInfo = [String : Any]() // user info must be filtered so that the keys are all strings info.enumerateKeysAndObjects(options: []) { if let key = $0.0 as? NSString { filteredUserInfo[key._swiftObject] = $0.1 } } _userInfo = filteredUserInfo } } public static var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(_domain._bridgeToObjectiveC(), forKey: "NSDomain") aCoder.encode(Int32(_code), forKey: "NSCode") aCoder.encode(_userInfo?._bridgeToObjectiveC(), forKey: "NSUserInfo") } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open var domain: String { return _domain } open var code: Int { return _code } /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types. open var userInfo: [String : Any] { if let info = _userInfo { return info } else { return Dictionary<String, Any>() } } open var localizedDescription: String { let desc = userInfo[NSLocalizedDescriptionKey] as? String return desc ?? "The operation could not be completed" } open var localizedFailureReason: String? { return userInfo[NSLocalizedFailureReasonErrorKey] as? String } open var localizedRecoverySuggestion: String? { return userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String } open var localizedRecoveryOptions: [String]? { return userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String] } open var recoveryAttempter: Any? { return userInfo[NSRecoveryAttempterErrorKey] } open var helpAnchor: String? { return userInfo[NSHelpAnchorErrorKey] as? String } internal typealias NSErrorProvider = (_ error: NSError, _ key: String) -> AnyObject? internal static var userInfoProviders = [String: NSErrorProvider]() open class func setUserInfoValueProvider(forDomain errorDomain: String, provider: (/* @escaping */ (NSError, String) -> AnyObject?)?) { NSError.userInfoProviders[errorDomain] = provider } open class func userInfoValueProvider(forDomain errorDomain: String) -> ((NSError, String) -> AnyObject?)? { return NSError.userInfoProviders[errorDomain] } override open var description: String { return localizedDescription } // -- NSObject Overrides -- // The compiler has special paths for attempting to do some bridging on NSError (and equivalent Error instances) -- in particular, in the lookup of NSError objects' superclass. // On platforms where we don't have bridging (i.e. Linux), this causes a silgen failure. We can avoid the issue by overriding methods inherited by NSObject ourselves. override open var hashValue: Int { // CFHash does the appropriate casting/bridging on platforms where we support it. return Int(bitPattern: CFHash(self)) } override open func isEqual(_ object: Any?) -> Bool { // Pulled from NSObject itself; this works on all platforms. if let obj = object as? NSError { return obj === self } return false } } extension NSError : Swift.Error { } extension NSError : _CFBridgeable { } extension CFError : _NSBridgeable { typealias NSType = NSError internal var _nsObject: NSType { let userInfo = CFErrorCopyUserInfo(self)._swiftObject var newUserInfo: [String: Any] = [:] for (key, value) in userInfo { if let key = key as? String { newUserInfo[key] = value } } return NSError(domain: CFErrorGetDomain(self)._swiftObject, code: CFErrorGetCode(self), userInfo: newUserInfo) } } /// Describes an error that provides localized messages describing why /// an error occurred and provides more information about the error. public protocol LocalizedError : Error { /// A localized message describing what error occurred. var errorDescription: String? { get } /// A localized message describing the reason for the failure. var failureReason: String? { get } /// A localized message describing how one might recover from the failure. var recoverySuggestion: String? { get } /// A localized message providing "help" text if the user requests help. var helpAnchor: String? { get } } public extension LocalizedError { var errorDescription: String? { return nil } var failureReason: String? { return nil } var recoverySuggestion: String? { return nil } var helpAnchor: String? { return nil } } /// Class that implements the informal protocol /// NSErrorRecoveryAttempting, which is used by NSError when it /// attempts recovery from an error. class _NSErrorRecoveryAttempter { func attemptRecovery(fromError nsError: NSError, optionIndex recoveryOptionIndex: Int) -> Bool { let error = nsError as Error as! RecoverableError return error.attemptRecovery(optionIndex: recoveryOptionIndex) } } /// Describes an error that may be recoverable by presenting several /// potential recovery options to the user. public protocol RecoverableError : Error { /// Provides a set of possible recovery options to present to the user. var recoveryOptions: [String] { get } /// Attempt to recover from this error when the user selected the /// option at the given index. This routine must call handler and /// indicate whether recovery was successful (or not). /// /// This entry point is used for recovery of errors handled at a /// "document" granularity, that do not affect the entire /// application. func attemptRecovery(optionIndex recoveryOptionIndex: Int, resultHandler handler: (_ recovered: Bool) -> Void) /// Attempt to recover from this error when the user selected the /// option at the given index. Returns true to indicate /// successful recovery, and false otherwise. /// /// This entry point is used for recovery of errors handled at /// the "application" granularity, where nothing else in the /// application can proceed until the attempted error recovery /// completes. func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool } public extension RecoverableError { /// Default implementation that uses the application-model recovery /// mechanism (``attemptRecovery(optionIndex:)``) to implement /// document-modal recovery. func attemptRecovery(optionIndex recoveryOptionIndex: Int, resultHandler handler: (_ recovered: Bool) -> Void) { handler(attemptRecovery(optionIndex: recoveryOptionIndex)) } } /// Describes an error type that specifically provides a domain, code, /// and user-info dictionary. public protocol CustomNSError : Error { /// The domain of the error. static var errorDomain: String { get } /// The error code within the given domain. var errorCode: Int { get } /// The user-info dictionary. var errorUserInfo: [String : Any] { get } } public extension Error where Self : CustomNSError { /// Default implementation for customized NSErrors. var _domain: String { return Self.errorDomain } /// Default implementation for customized NSErrors. var _code: Int { return self.errorCode } } public extension Error { /// Retrieve the localized description for this error. var localizedDescription: String { return NSError(domain: _domain, code: _code, userInfo: nil).localizedDescription } } /// Retrieve the default userInfo dictionary for a given error. public func _swift_Foundation_getErrorDefaultUserInfo(_ error: Error) -> Any? { // TODO: Implement info value providers and return the code that was deleted here. let hasUserInfoValueProvider = false // Populate the user-info dictionary var result: [String : Any] // Initialize with custom user-info. if let customNSError = error as? CustomNSError { result = customNSError.errorUserInfo } else { result = [:] } // Handle localized errors. If we registered a user-info value // provider, these will computed lazily. if !hasUserInfoValueProvider, let localizedError = error as? LocalizedError { if let description = localizedError.errorDescription { result[NSLocalizedDescriptionKey] = description } if let reason = localizedError.failureReason { result[NSLocalizedFailureReasonErrorKey] = reason } if let suggestion = localizedError.recoverySuggestion { result[NSLocalizedRecoverySuggestionErrorKey] = suggestion } if let helpAnchor = localizedError.helpAnchor { result[NSHelpAnchorErrorKey] = helpAnchor } } // Handle recoverable errors. If we registered a user-info value // provider, these will computed lazily. if !hasUserInfoValueProvider, let recoverableError = error as? RecoverableError { result[NSLocalizedRecoveryOptionsErrorKey] = recoverableError.recoveryOptions result[NSRecoveryAttempterErrorKey] = _NSErrorRecoveryAttempter() } return result } // NSError and CFError conform to the standard Error protocol. Compiler // magic allows this to be done as a "toll-free" conversion when an NSError // or CFError is used as an Error existential. extension CFError : Error { public var _domain: String { return CFErrorGetDomain(self)._swiftObject } public var _code: Int { return CFErrorGetCode(self) } public var _userInfo: Any? { return CFErrorCopyUserInfo(self) as Any } } /// An internal protocol to represent Swift error enums that map to standard /// Cocoa NSError domains. public protocol _ObjectTypeBridgeableError : Error { /// Produce a value of the error type corresponding to the given NSError, /// or return nil if it cannot be bridged. init?(_bridgedNSError: NSError) } /// Helper protocol for _BridgedNSError, which used to provide /// default implementations. public protocol __BridgedNSError : Error { static var _nsErrorDomain: String { get } } // Allow two bridged NSError types to be compared. extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.rawValue.toIntMax() == rhs.rawValue.toIntMax() } } public extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: SignedInteger { public final var _domain: String { return Self._nsErrorDomain } public final var _code: Int { return Int(rawValue.toIntMax()) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(IntMax(_bridgedNSError.code))) } public final var hashValue: Int { return _code } } // Allow two bridged NSError types to be compared. extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.rawValue.toUIntMax() == rhs.rawValue.toUIntMax() } } public extension __BridgedNSError where Self: RawRepresentable, Self.RawValue: UnsignedInteger { public final var _domain: String { return Self._nsErrorDomain } public final var _code: Int { return Int(bitPattern: UInt(rawValue.toUIntMax())) } public init?(rawValue: RawValue) { self = unsafeBitCast(rawValue, to: Self.self) } public init?(_bridgedNSError: NSError) { if _bridgedNSError.domain != Self._nsErrorDomain { return nil } self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code)))) } public final var hashValue: Int { return _code } } /// Describes a raw representable type that is bridged to a particular /// NSError domain. /// /// This protocol is used primarily to generate the conformance to /// _ObjectTypeBridgeableError for such an enum. public protocol _BridgedNSError : __BridgedNSError, RawRepresentable, _ObjectTypeBridgeableError, Hashable { /// The NSError domain to which this type is bridged. static var _nsErrorDomain: String { get } } /// Describes a bridged error that stores the underlying NSError, so /// it can be queried. public protocol _BridgedStoredNSError : __BridgedNSError, _ObjectTypeBridgeableError, CustomNSError, Hashable { /// The type of an error code. associatedtype Code: _ErrorCodeProtocol /// The error code for the given error. var code: Code { get } //// Retrieves the embedded NSError. var _nsError: NSError { get } /// Create a new instance of the error type with the given embedded /// NSError. /// /// The \c error must have the appropriate domain for this error /// type. init(_nsError error: NSError) } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: SignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: Self._nsErrorDomain, code: numericCast(code.rawValue), userInfo: userInfo)) } /// The user-info dictionary for an error that was bridged from /// NSError. var userInfo: [String : Any] { return errorUserInfo } } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: UnsignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: Self._nsErrorDomain, code: numericCast(code.rawValue), userInfo: userInfo)) } } /// Implementation of __BridgedNSError for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { /// Default implementation of ``init(_bridgedNSError)`` to provide /// bridging from NSError. public init?(_bridgedNSError error: NSError) { if error.domain != Self._nsErrorDomain { return nil } self.init(_nsError: error) } } /// Implementation of CustomNSError for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { static var errorDomain: String { return _nsErrorDomain } var errorCode: Int { return _nsError.code } var errorUserInfo: [String : Any] { return _nsError.userInfo } } /// Implementation of Hashable for all _BridgedStoredNSErrors. public extension _BridgedStoredNSError { var hashValue: Int { return _nsError.hashValue } } /// Describes the code of an error. public protocol _ErrorCodeProtocol : Equatable { /// The corresponding error code. associatedtype _ErrorType // FIXME: We want _ErrorType to be _BridgedStoredNSError and have its // Code match Self, but we cannot express those requirements yet. } extension _ErrorCodeProtocol where Self._ErrorType: _BridgedStoredNSError { /// Allow one to match an error code against an arbitrary error. public static func ~=(match: Self, error: Error) -> Bool { guard let specificError = error as? Self._ErrorType else { return false } // FIXME: Work around IRGen crash when we set Code == Code._ErrorType.Code. let specificCode = specificError.code as! Self return match == specificCode } } extension _BridgedStoredNSError { public static func == (lhs: Self, rhs: Self) -> Bool { return lhs._nsError.isEqual(rhs._nsError) } } /// Describes errors within the Cocoa error domain. public struct CocoaError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSCocoaErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSCocoaErrorDomain } /// The error code itself. public struct Code : RawRepresentable, _ErrorCodeProtocol { public typealias _ErrorType = CocoaError public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static var fileNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 4) } public static var fileLocking: CocoaError.Code { return CocoaError.Code(rawValue: 255) } public static var fileReadUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 256) } public static var fileReadNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 257) } public static var fileReadInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 258) } public static var fileReadCorruptFile: CocoaError.Code { return CocoaError.Code(rawValue: 259) } public static var fileReadNoSuchFile: CocoaError.Code { return CocoaError.Code(rawValue: 260) } public static var fileReadInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 261) } public static var fileReadUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 262) } public static var fileReadTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 263) } public static var fileReadUnknownStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 264) } public static var fileWriteUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 512) } public static var fileWriteNoPermission: CocoaError.Code { return CocoaError.Code(rawValue: 513) } public static var fileWriteInvalidFileName: CocoaError.Code { return CocoaError.Code(rawValue: 514) } public static var fileWriteFileExists: CocoaError.Code { return CocoaError.Code(rawValue: 516) } public static var fileWriteInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code(rawValue: 517) } public static var fileWriteUnsupportedScheme: CocoaError.Code { return CocoaError.Code(rawValue: 518) } public static var fileWriteOutOfSpace: CocoaError.Code { return CocoaError.Code(rawValue: 640) } public static var fileWriteVolumeReadOnly: CocoaError.Code { return CocoaError.Code(rawValue: 642) } public static var fileManagerUnmountUnknown: CocoaError.Code { return CocoaError.Code(rawValue: 768) } public static var fileManagerUnmountBusy: CocoaError.Code { return CocoaError.Code(rawValue: 769) } public static var keyValueValidation: CocoaError.Code { return CocoaError.Code(rawValue: 1024) } public static var formatting: CocoaError.Code { return CocoaError.Code(rawValue: 2048) } public static var userCancelled: CocoaError.Code { return CocoaError.Code(rawValue: 3072) } public static var featureUnsupported: CocoaError.Code { return CocoaError.Code(rawValue: 3328) } public static var executableNotLoadable: CocoaError.Code { return CocoaError.Code(rawValue: 3584) } public static var executableArchitectureMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3585) } public static var executableRuntimeMismatch: CocoaError.Code { return CocoaError.Code(rawValue: 3586) } public static var executableLoad: CocoaError.Code { return CocoaError.Code(rawValue: 3587) } public static var executableLink: CocoaError.Code { return CocoaError.Code(rawValue: 3588) } public static var propertyListReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 3840) } public static var propertyListReadUnknownVersion: CocoaError.Code { return CocoaError.Code(rawValue: 3841) } public static var propertyListReadStream: CocoaError.Code { return CocoaError.Code(rawValue: 3842) } public static var propertyListWriteStream: CocoaError.Code { return CocoaError.Code(rawValue: 3851) } public static var propertyListWriteInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 3852) } public static var xpcConnectionInterrupted: CocoaError.Code { return CocoaError.Code(rawValue: 4097) } public static var xpcConnectionInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4099) } public static var xpcConnectionReplyInvalid: CocoaError.Code { return CocoaError.Code(rawValue: 4101) } public static var ubiquitousFileUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4353) } public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code { return CocoaError.Code(rawValue: 4354) } public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code { return CocoaError.Code(rawValue: 4355) } public static var userActivityHandoffFailed: CocoaError.Code { return CocoaError.Code(rawValue: 4608) } public static var userActivityConnectionUnavailable: CocoaError.Code { return CocoaError.Code(rawValue: 4609) } public static var userActivityRemoteApplicationTimedOut: CocoaError.Code { return CocoaError.Code(rawValue: 4610) } public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code { return CocoaError.Code(rawValue: 4611) } public static var coderReadCorrupt: CocoaError.Code { return CocoaError.Code(rawValue: 4864) } public static var coderValueNotFound: CocoaError.Code { return CocoaError.Code(rawValue: 4865) } } } public extension CocoaError { private var _nsUserInfo: [AnyHashable : Any] { return NSError(domain: _domain, code: _code, userInfo: nil).userInfo } /// The file path associated with the error, if any. var filePath: String? { return _nsUserInfo[NSFilePathErrorKey._bridgeToObjectiveC()] as? String } /// The string encoding associated with this error, if any. var stringEncoding: String.Encoding? { return (_nsUserInfo[NSStringEncodingErrorKey._bridgeToObjectiveC()] as? NSNumber) .map { String.Encoding(rawValue: $0.uintValue) } } /// The underlying error behind this error, if any. var underlying: Error? { return _nsUserInfo[NSUnderlyingErrorKey._bridgeToObjectiveC()] as? Error } /// The URL associated with this error, if any. var url: URL? { return _nsUserInfo[NSURLErrorKey._bridgeToObjectiveC()] as? URL } } extension CocoaError.Code { } extension CocoaError { public static var fileNoSuchFile: CocoaError.Code { return CocoaError.Code.fileNoSuchFile } public static var fileLocking: CocoaError.Code { return CocoaError.Code.fileLocking } public static var fileReadUnknown: CocoaError.Code { return CocoaError.Code.fileReadUnknown } public static var fileReadNoPermission: CocoaError.Code { return CocoaError.Code.fileReadNoPermission } public static var fileReadInvalidFileName: CocoaError.Code { return CocoaError.Code.fileReadInvalidFileName } public static var fileReadCorruptFile: CocoaError.Code { return CocoaError.Code.fileReadCorruptFile } public static var fileReadNoSuchFile: CocoaError.Code { return CocoaError.Code.fileReadNoSuchFile } public static var fileReadInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code.fileReadInapplicableStringEncoding } public static var fileReadUnsupportedScheme: CocoaError.Code { return CocoaError.Code.fileReadUnsupportedScheme } public static var fileReadTooLarge: CocoaError.Code { return CocoaError.Code.fileReadTooLarge } public static var fileReadUnknownStringEncoding: CocoaError.Code { return CocoaError.Code.fileReadUnknownStringEncoding } public static var fileWriteUnknown: CocoaError.Code { return CocoaError.Code.fileWriteUnknown } public static var fileWriteNoPermission: CocoaError.Code { return CocoaError.Code.fileWriteNoPermission } public static var fileWriteInvalidFileName: CocoaError.Code { return CocoaError.Code.fileWriteInvalidFileName } public static var fileWriteFileExists: CocoaError.Code { return CocoaError.Code.fileWriteFileExists } public static var fileWriteInapplicableStringEncoding: CocoaError.Code { return CocoaError.Code.fileWriteInapplicableStringEncoding } public static var fileWriteUnsupportedScheme: CocoaError.Code { return CocoaError.Code.fileWriteUnsupportedScheme } public static var fileWriteOutOfSpace: CocoaError.Code { return CocoaError.Code.fileWriteOutOfSpace } public static var fileWriteVolumeReadOnly: CocoaError.Code { return CocoaError.Code.fileWriteVolumeReadOnly } public static var fileManagerUnmountUnknown: CocoaError.Code { return CocoaError.Code.fileManagerUnmountUnknown } public static var fileManagerUnmountBusy: CocoaError.Code { return CocoaError.Code.fileManagerUnmountBusy } public static var keyValueValidation: CocoaError.Code { return CocoaError.Code.keyValueValidation } public static var formatting: CocoaError.Code { return CocoaError.Code.formatting } public static var userCancelled: CocoaError.Code { return CocoaError.Code.userCancelled } public static var featureUnsupported: CocoaError.Code { return CocoaError.Code.featureUnsupported } public static var executableNotLoadable: CocoaError.Code { return CocoaError.Code.executableNotLoadable } public static var executableArchitectureMismatch: CocoaError.Code { return CocoaError.Code.executableArchitectureMismatch } public static var executableRuntimeMismatch: CocoaError.Code { return CocoaError.Code.executableRuntimeMismatch } public static var executableLoad: CocoaError.Code { return CocoaError.Code.executableLoad } public static var executableLink: CocoaError.Code { return CocoaError.Code.executableLink } public static var propertyListReadCorrupt: CocoaError.Code { return CocoaError.Code.propertyListReadCorrupt } public static var propertyListReadUnknownVersion: CocoaError.Code { return CocoaError.Code.propertyListReadUnknownVersion } public static var propertyListReadStream: CocoaError.Code { return CocoaError.Code.propertyListReadStream } public static var propertyListWriteStream: CocoaError.Code { return CocoaError.Code.propertyListWriteStream } public static var propertyListWriteInvalid: CocoaError.Code { return CocoaError.Code.propertyListWriteInvalid } public static var xpcConnectionInterrupted: CocoaError.Code { return CocoaError.Code.xpcConnectionInterrupted } public static var xpcConnectionInvalid: CocoaError.Code { return CocoaError.Code.xpcConnectionInvalid } public static var xpcConnectionReplyInvalid: CocoaError.Code { return CocoaError.Code.xpcConnectionReplyInvalid } public static var ubiquitousFileUnavailable: CocoaError.Code { return CocoaError.Code.ubiquitousFileUnavailable } public static var ubiquitousFileNotUploadedDueToQuota: CocoaError.Code { return CocoaError.Code.ubiquitousFileNotUploadedDueToQuota } public static var ubiquitousFileUbiquityServerNotAvailable: CocoaError.Code { return CocoaError.Code.ubiquitousFileUbiquityServerNotAvailable } public static var userActivityHandoffFailed: CocoaError.Code { return CocoaError.Code.userActivityHandoffFailed } public static var userActivityConnectionUnavailable: CocoaError.Code { return CocoaError.Code.userActivityConnectionUnavailable } public static var userActivityRemoteApplicationTimedOut: CocoaError.Code { return CocoaError.Code.userActivityRemoteApplicationTimedOut } public static var userActivityHandoffUserInfoTooLarge: CocoaError.Code { return CocoaError.Code.userActivityHandoffUserInfoTooLarge } public static var coderReadCorrupt: CocoaError.Code { return CocoaError.Code.coderReadCorrupt } public static var coderValueNotFound: CocoaError.Code { return CocoaError.Code.coderValueNotFound } } extension CocoaError { public var isCoderError: Bool { return code.rawValue >= 4864 && code.rawValue <= 4991 } public var isExecutableError: Bool { return code.rawValue >= 3584 && code.rawValue <= 3839 } public var isFileError: Bool { return code.rawValue >= 0 && code.rawValue <= 1023 } public var isFormattingError: Bool { return code.rawValue >= 2048 && code.rawValue <= 2559 } public var isPropertyListError: Bool { return code.rawValue >= 3840 && code.rawValue <= 4095 } public var isUbiquitousFileError: Bool { return code.rawValue >= 4352 && code.rawValue <= 4607 } public var isUserActivityError: Bool { return code.rawValue >= 4608 && code.rawValue <= 4863 } public var isValidationError: Bool { return code.rawValue >= 1024 && code.rawValue <= 2047 } public var isXPCConnectionError: Bool { return code.rawValue >= 4096 && code.rawValue <= 4224 } } /// Describes errors in the URL error domain. public struct URLError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSURLErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSURLErrorDomain } public enum Code : Int, _ErrorCodeProtocol { public typealias _ErrorType = URLError case unknown = -1 case cancelled = -999 case badURL = -1000 case timedOut = -1001 case unsupportedURL = -1002 case cannotFindHost = -1003 case cannotConnectToHost = -1004 case networkConnectionLost = -1005 case dnsLookupFailed = -1006 case httpTooManyRedirects = -1007 case resourceUnavailable = -1008 case notConnectedToInternet = -1009 case redirectToNonExistentLocation = -1010 case badServerResponse = -1011 case userCancelledAuthentication = -1012 case userAuthenticationRequired = -1013 case zeroByteResource = -1014 case cannotDecodeRawData = -1015 case cannotDecodeContentData = -1016 case cannotParseResponse = -1017 case fileDoesNotExist = -1100 case fileIsDirectory = -1101 case noPermissionsToReadFile = -1102 case secureConnectionFailed = -1200 case serverCertificateHasBadDate = -1201 case serverCertificateUntrusted = -1202 case serverCertificateHasUnknownRoot = -1203 case serverCertificateNotYetValid = -1204 case clientCertificateRejected = -1205 case clientCertificateRequired = -1206 case cannotLoadFromNetwork = -2000 case cannotCreateFile = -3000 case cannotOpenFile = -3001 case cannotCloseFile = -3002 case cannotWriteToFile = -3003 case cannotRemoveFile = -3004 case cannotMoveFile = -3005 case downloadDecodingFailedMidStream = -3006 case downloadDecodingFailedToComplete = -3007 case internationalRoamingOff = -1018 case callIsActive = -1019 case dataNotAllowed = -1020 case requestBodyStreamExhausted = -1021 case backgroundSessionRequiresSharedContainer = -995 case backgroundSessionInUseByAnotherProcess = -996 case backgroundSessionWasDisconnected = -997 } } public extension URLError { private var _nsUserInfo: [AnyHashable : Any] { return NSError(domain: _domain, code: _code, userInfo: nil).userInfo } /// The URL which caused a load to fail. public var failingURL: URL? { return _nsUserInfo[NSURLErrorFailingURLErrorKey._bridgeToObjectiveC()] as? URL } /// The string for the URL which caused a load to fail. public var failureURLString: String? { return _nsUserInfo[NSURLErrorFailingURLStringErrorKey._bridgeToObjectiveC()] as? String } } public extension URLError { public static var unknown: URLError.Code { return .unknown } public static var cancelled: URLError.Code { return .cancelled } public static var badURL: URLError.Code { return .badURL } public static var timedOut: URLError.Code { return .timedOut } public static var unsupportedURL: URLError.Code { return .unsupportedURL } public static var cannotFindHost: URLError.Code { return .cannotFindHost } public static var cannotConnectToHost: URLError.Code { return .cannotConnectToHost } public static var networkConnectionLost: URLError.Code { return .networkConnectionLost } public static var dnsLookupFailed: URLError.Code { return .dnsLookupFailed } public static var httpTooManyRedirects: URLError.Code { return .httpTooManyRedirects } public static var resourceUnavailable: URLError.Code { return .resourceUnavailable } public static var notConnectedToInternet: URLError.Code { return .notConnectedToInternet } public static var redirectToNonExistentLocation: URLError.Code { return .redirectToNonExistentLocation } public static var badServerResponse: URLError.Code { return .badServerResponse } public static var userCancelledAuthentication: URLError.Code { return .userCancelledAuthentication } public static var userAuthenticationRequired: URLError.Code { return .userAuthenticationRequired } public static var zeroByteResource: URLError.Code { return .zeroByteResource } public static var cannotDecodeRawData: URLError.Code { return .cannotDecodeRawData } public static var cannotDecodeContentData: URLError.Code { return .cannotDecodeContentData } public static var cannotParseResponse: URLError.Code { return .cannotParseResponse } public static var fileDoesNotExist: URLError.Code { return .fileDoesNotExist } public static var fileIsDirectory: URLError.Code { return .fileIsDirectory } public static var noPermissionsToReadFile: URLError.Code { return .noPermissionsToReadFile } public static var secureConnectionFailed: URLError.Code { return .secureConnectionFailed } public static var serverCertificateHasBadDate: URLError.Code { return .serverCertificateHasBadDate } public static var serverCertificateUntrusted: URLError.Code { return .serverCertificateUntrusted } public static var serverCertificateHasUnknownRoot: URLError.Code { return .serverCertificateHasUnknownRoot } public static var serverCertificateNotYetValid: URLError.Code { return .serverCertificateNotYetValid } public static var clientCertificateRejected: URLError.Code { return .clientCertificateRejected } public static var clientCertificateRequired: URLError.Code { return .clientCertificateRequired } public static var cannotLoadFromNetwork: URLError.Code { return .cannotLoadFromNetwork } public static var cannotCreateFile: URLError.Code { return .cannotCreateFile } public static var cannotOpenFile: URLError.Code { return .cannotOpenFile } public static var cannotCloseFile: URLError.Code { return .cannotCloseFile } public static var cannotWriteToFile: URLError.Code { return .cannotWriteToFile } public static var cannotRemoveFile: URLError.Code { return .cannotRemoveFile } public static var cannotMoveFile: URLError.Code { return .cannotMoveFile } public static var downloadDecodingFailedMidStream: URLError.Code { return .downloadDecodingFailedMidStream } public static var downloadDecodingFailedToComplete: URLError.Code { return .downloadDecodingFailedToComplete } public static var internationalRoamingOff: URLError.Code { return .internationalRoamingOff } public static var callIsActive: URLError.Code { return .callIsActive } public static var dataNotAllowed: URLError.Code { return .dataNotAllowed } public static var requestBodyStreamExhausted: URLError.Code { return .requestBodyStreamExhausted } public static var backgroundSessionRequiresSharedContainer: URLError.Code { return .backgroundSessionRequiresSharedContainer } public static var backgroundSessionInUseByAnotherProcess: URLError.Code { return .backgroundSessionInUseByAnotherProcess } public static var backgroundSessionWasDisconnected: URLError.Code { return .backgroundSessionWasDisconnected } } /// Describes an error in the POSIX error domain. public struct POSIXError : _BridgedStoredNSError { public let _nsError: NSError public init(_nsError error: NSError) { precondition(error.domain == NSPOSIXErrorDomain) self._nsError = error } public static var _nsErrorDomain: String { return NSPOSIXErrorDomain } public enum Code : Int, _ErrorCodeProtocol { public typealias _ErrorType = POSIXError case EPERM case ENOENT case ESRCH case EINTR case EIO case ENXIO case E2BIG case ENOEXEC case EBADF case ECHILD case EDEADLK case ENOMEM case EACCES case EFAULT case ENOTBLK case EBUSY case EEXIST case EXDEV case ENODEV case ENOTDIR case EISDIR case EINVAL case ENFILE case EMFILE case ENOTTY case ETXTBSY case EFBIG case ENOSPC case ESPIPE case EROFS case EMLINK case EPIPE case EDOM case ERANGE case EAGAIN case EWOULDBLOCK case EINPROGRESS case EALREADY case ENOTSOCK case EDESTADDRREQ case EMSGSIZE case EPROTOTYPE case ENOPROTOOPT case EPROTONOSUPPORT case ESOCKTNOSUPPORT case ENOTSUP case EPFNOSUPPORT case EAFNOSUPPORT case EADDRINUSE case EADDRNOTAVAIL case ENETDOWN case ENETUNREACH case ENETRESET case ECONNABORTED case ECONNRESET case ENOBUFS case EISCONN case ENOTCONN case ESHUTDOWN case ETOOMANYREFS case ETIMEDOUT case ECONNREFUSED case ELOOP case ENAMETOOLONG case EHOSTDOWN case EHOSTUNREACH case ENOTEMPTY case EPROCLIM case EUSERS case EDQUOT case ESTALE case EREMOTE case EBADRPC case ERPCMISMATCH case EPROGUNAVAIL case EPROGMISMATCH case EPROCUNAVAIL case ENOLCK case ENOSYS case EFTYPE case EAUTH case ENEEDAUTH case EPWROFF case EDEVERR case EOVERFLOW case EBADEXEC case EBADARCH case ESHLIBVERS case EBADMACHO case ECANCELED case EIDRM case ENOMSG case EILSEQ case ENOATTR case EBADMSG case EMULTIHOP case ENODATA case ENOLINK case ENOSR case ENOSTR case EPROTO case ETIME case ENOPOLICY case ENOTRECOVERABLE case EOWNERDEAD case EQFULL } } extension POSIXError { /// Operation not permitted. public static var EPERM: POSIXError.Code { return .EPERM } /// No such file or directory. public static var ENOENT: POSIXError.Code { return .ENOENT } /// No such process. public static var ESRCH: POSIXError.Code { return .ESRCH } /// Interrupted system call. public static var EINTR: POSIXError.Code { return .EINTR } /// Input/output error. public static var EIO: POSIXError.Code { return .EIO } /// Device not configured. public static var ENXIO: POSIXError.Code { return .ENXIO } /// Argument list too long. public static var E2BIG: POSIXError.Code { return .E2BIG } /// Exec format error. public static var ENOEXEC: POSIXError.Code { return .ENOEXEC } /// Bad file descriptor. public static var EBADF: POSIXError.Code { return .EBADF } /// No child processes. public static var ECHILD: POSIXError.Code { return .ECHILD } /// Resource deadlock avoided. public static var EDEADLK: POSIXError.Code { return .EDEADLK } /// Cannot allocate memory. public static var ENOMEM: POSIXError.Code { return .ENOMEM } /// Permission denied. public static var EACCES: POSIXError.Code { return .EACCES } /// Bad address. public static var EFAULT: POSIXError.Code { return .EFAULT } /// Block device required. public static var ENOTBLK: POSIXError.Code { return .ENOTBLK } /// Device / Resource busy. public static var EBUSY: POSIXError.Code { return .EBUSY } /// File exists. public static var EEXIST: POSIXError.Code { return .EEXIST } /// Cross-device link. public static var EXDEV: POSIXError.Code { return .EXDEV } /// Operation not supported by device. public static var ENODEV: POSIXError.Code { return .ENODEV } /// Not a directory. public static var ENOTDIR: POSIXError.Code { return .ENOTDIR } /// Is a directory. public static var EISDIR: POSIXError.Code { return .EISDIR } /// Invalid argument. public static var EINVAL: POSIXError.Code { return .EINVAL } /// Too many open files in system. public static var ENFILE: POSIXError.Code { return .ENFILE } /// Too many open files. public static var EMFILE: POSIXError.Code { return .EMFILE } /// Inappropriate ioctl for device. public static var ENOTTY: POSIXError.Code { return .ENOTTY } /// Text file busy. public static var ETXTBSY: POSIXError.Code { return .ETXTBSY } /// File too large. public static var EFBIG: POSIXError.Code { return .EFBIG } /// No space left on device. public static var ENOSPC: POSIXError.Code { return .ENOSPC } /// Illegal seek. public static var ESPIPE: POSIXError.Code { return .ESPIPE } /// Read-only file system. public static var EROFS: POSIXError.Code { return .EROFS } /// Too many links. public static var EMLINK: POSIXError.Code { return .EMLINK } /// Broken pipe. public static var EPIPE: POSIXError.Code { return .EPIPE } /// Math Software /// Numerical argument out of domain. public static var EDOM: POSIXError.Code { return .EDOM } /// Result too large. public static var ERANGE: POSIXError.Code { return .ERANGE } /// Non-blocking and interrupt I/O. /// Resource temporarily unavailable. public static var EAGAIN: POSIXError.Code { return .EAGAIN } /// Operation would block. public static var EWOULDBLOCK: POSIXError.Code { return .EWOULDBLOCK } /// Operation now in progress. public static var EINPROGRESS: POSIXError.Code { return .EINPROGRESS } /// Operation already in progress. public static var EALREADY: POSIXError.Code { return .EALREADY } /// IPC/Network software -- argument errors. /// Socket operation on non-socket. public static var ENOTSOCK: POSIXError.Code { return .ENOTSOCK } /// Destination address required. public static var EDESTADDRREQ: POSIXError.Code { return .EDESTADDRREQ } /// Message too long. public static var EMSGSIZE: POSIXError.Code { return .EMSGSIZE } /// Protocol wrong type for socket. public static var EPROTOTYPE: POSIXError.Code { return .EPROTOTYPE } /// Protocol not available. public static var ENOPROTOOPT: POSIXError.Code { return .ENOPROTOOPT } /// Protocol not supported. public static var EPROTONOSUPPORT: POSIXError.Code { return .EPROTONOSUPPORT } /// Socket type not supported. public static var ESOCKTNOSUPPORT: POSIXError.Code { return .ESOCKTNOSUPPORT } /// Operation not supported. public static var ENOTSUP: POSIXError.Code { return .ENOTSUP } /// Protocol family not supported. public static var EPFNOSUPPORT: POSIXError.Code { return .EPFNOSUPPORT } /// Address family not supported by protocol family. public static var EAFNOSUPPORT: POSIXError.Code { return .EAFNOSUPPORT } /// Address already in use. public static var EADDRINUSE: POSIXError.Code { return .EADDRINUSE } /// Can't assign requested address. public static var EADDRNOTAVAIL: POSIXError.Code { return .EADDRNOTAVAIL } /// IPC/Network software -- operational errors /// Network is down. public static var ENETDOWN: POSIXError.Code { return .ENETDOWN } /// Network is unreachable. public static var ENETUNREACH: POSIXError.Code { return .ENETUNREACH } /// Network dropped connection on reset. public static var ENETRESET: POSIXError.Code { return .ENETRESET } /// Software caused connection abort. public static var ECONNABORTED: POSIXError.Code { return .ECONNABORTED } /// Connection reset by peer. public static var ECONNRESET: POSIXError.Code { return .ECONNRESET } /// No buffer space available. public static var ENOBUFS: POSIXError.Code { return .ENOBUFS } /// Socket is already connected. public static var EISCONN: POSIXError.Code { return .EISCONN } /// Socket is not connected. public static var ENOTCONN: POSIXError.Code { return .ENOTCONN } /// Can't send after socket shutdown. public static var ESHUTDOWN: POSIXError.Code { return .ESHUTDOWN } /// Too many references: can't splice. public static var ETOOMANYREFS: POSIXError.Code { return .ETOOMANYREFS } /// Operation timed out. public static var ETIMEDOUT: POSIXError.Code { return .ETIMEDOUT } /// Connection refused. public static var ECONNREFUSED: POSIXError.Code { return .ECONNREFUSED } /// Too many levels of symbolic links. public static var ELOOP: POSIXError.Code { return .ELOOP } /// File name too long. public static var ENAMETOOLONG: POSIXError.Code { return .ENAMETOOLONG } /// Host is down. public static var EHOSTDOWN: POSIXError.Code { return .EHOSTDOWN } /// No route to host. public static var EHOSTUNREACH: POSIXError.Code { return .EHOSTUNREACH } /// Directory not empty. public static var ENOTEMPTY: POSIXError.Code { return .ENOTEMPTY } /// Quotas /// Too many processes. public static var EPROCLIM: POSIXError.Code { return .EPROCLIM } /// Too many users. public static var EUSERS: POSIXError.Code { return .EUSERS } /// Disk quota exceeded. public static var EDQUOT: POSIXError.Code { return .EDQUOT } /// Network File System /// Stale NFS file handle. public static var ESTALE: POSIXError.Code { return .ESTALE } /// Too many levels of remote in path. public static var EREMOTE: POSIXError.Code { return .EREMOTE } /// RPC struct is bad. public static var EBADRPC: POSIXError.Code { return .EBADRPC } /// RPC version wrong. public static var ERPCMISMATCH: POSIXError.Code { return .ERPCMISMATCH } /// RPC prog. not avail. public static var EPROGUNAVAIL: POSIXError.Code { return .EPROGUNAVAIL } /// Program version wrong. public static var EPROGMISMATCH: POSIXError.Code { return .EPROGMISMATCH } /// Bad procedure for program. public static var EPROCUNAVAIL: POSIXError.Code { return .EPROCUNAVAIL } /// No locks available. public static var ENOLCK: POSIXError.Code { return .ENOLCK } /// Function not implemented. public static var ENOSYS: POSIXError.Code { return .ENOSYS } /// Inappropriate file type or format. public static var EFTYPE: POSIXError.Code { return .EFTYPE } /// Authentication error. public static var EAUTH: POSIXError.Code { return .EAUTH } /// Need authenticator. public static var ENEEDAUTH: POSIXError.Code { return .ENEEDAUTH } /// Intelligent device errors. /// Device power is off. public static var EPWROFF: POSIXError.Code { return .EPWROFF } /// Device error, e.g. paper out. public static var EDEVERR: POSIXError.Code { return .EDEVERR } /// Value too large to be stored in data type. public static var EOVERFLOW: POSIXError.Code { return .EOVERFLOW } /// Program loading errors. /// Bad executable. public static var EBADEXEC: POSIXError.Code { return .EBADEXEC } /// Bad CPU type in executable. public static var EBADARCH: POSIXError.Code { return .EBADARCH } /// Shared library version mismatch. public static var ESHLIBVERS: POSIXError.Code { return .ESHLIBVERS } /// Malformed Macho file. public static var EBADMACHO: POSIXError.Code { return .EBADMACHO } /// Operation canceled. public static var ECANCELED: POSIXError.Code { return .ECANCELED } /// Identifier removed. public static var EIDRM: POSIXError.Code { return .EIDRM } /// No message of desired type. public static var ENOMSG: POSIXError.Code { return .ENOMSG } /// Illegal byte sequence. public static var EILSEQ: POSIXError.Code { return .EILSEQ } /// Attribute not found. public static var ENOATTR: POSIXError.Code { return .ENOATTR } /// Bad message. public static var EBADMSG: POSIXError.Code { return .EBADMSG } /// Reserved. public static var EMULTIHOP: POSIXError.Code { return .EMULTIHOP } /// No message available on STREAM. public static var ENODATA: POSIXError.Code { return .ENODATA } /// Reserved. public static var ENOLINK: POSIXError.Code { return .ENOLINK } /// No STREAM resources. public static var ENOSR: POSIXError.Code { return .ENOSR } /// Not a STREAM. public static var ENOSTR: POSIXError.Code { return .ENOSTR } /// Protocol error. public static var EPROTO: POSIXError.Code { return .EPROTO } /// STREAM ioctl timeout. public static var ETIME: POSIXError.Code { return .ETIME } /// No such policy registered. public static var ENOPOLICY: POSIXError.Code { return .ENOPOLICY } /// State not recoverable. public static var ENOTRECOVERABLE: POSIXError.Code { return .ENOTRECOVERABLE } /// Previous owner died. public static var EOWNERDEAD: POSIXError.Code { return .EOWNERDEAD } /// Interface output queue is full. public static var EQFULL: POSIXError.Code { return .EQFULL } }
apache-2.0
91ce4c238f6863f88db61047c6df61a8
42.211321
224
0.676203
5.29159
false
false
false
false
ahoppen/swift
stdlib/public/core/UnicodeData.swift
10
6756
//===----------------------------------------------------------------------===// // // 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 SwiftShims internal typealias ScalarAndNormData = ( scalar: Unicode.Scalar, normData: Unicode._NormData ) extension Unicode { // A wrapper type over the normalization data value we receive when we // lookup a scalar's normalization information. The layout of the underlying // 16 bit value we receive is as follows: // // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // └───┬───┘ └──── CCC ────┘ └─┘ │ // │ │ └── NFD_QC // │ └── NFC_QC // └── Unused // // NFD_QC: This is a simple Yes/No on whether the scalar has canonical // decomposition. Note: Yes is indicated via 0 instead of 1. // // NFC_QC: This is either Yes/No/Maybe on whether the scalar is NFC quick // check. Yes, represented as 0, means the scalar can NEVER compose // with another scalar previous to it. No, represented as 1, means the // scalar can NEVER appear within a well formed NFC string. Maybe, // represented as 2, means the scalar could appear with an NFC string, // but further information is required to determine if that is the // case. At the moment, we really only care about Yes/No. // // CCC: This is the canonical combining class property of a scalar that is // used when sorting scalars of a normalization segment after NFD // computation. A scalar with a CCC value of 128 can NEVER appear before // a scalar with a CCC value of 100, unless there are normalization // boundaries between them. // internal struct _NormData { var rawValue: UInt16 var ccc: UInt8 { UInt8(truncatingIfNeeded: rawValue >> 3) } var isNFCQC: Bool { rawValue & 0x6 == 0 } var isNFDQC: Bool { rawValue & 0x1 == 0 } init(_ scalar: Unicode.Scalar, fastUpperbound: UInt32 = 0xC0) { if _fastPath(scalar.value < fastUpperbound) { // CCC = 0, NFC_QC = Yes, NFD_QC = Yes rawValue = 0 } else { rawValue = _swift_stdlib_getNormData(scalar.value) // Because we don't store precomposed hangul in our NFD_QC data, these // will return true for NFD_QC when in fact they are not. if (0xAC00 ... 0xD7A3).contains(scalar.value) { // NFD_QC = false rawValue |= 0x1 } } } init(rawValue: UInt16) { self.rawValue = rawValue } } } extension Unicode { // A wrapper type for normalization buffers in the NFC and NFD iterators. // This helps remove some of the buffer logic like removal and sorting out of // the iterators and into this type. internal struct _NormDataBuffer { var storage: [ScalarAndNormData] = [] // This is simply a marker denoting that we've built up our storage, and // now everything within it needs to be emitted. We reverse the buffer and // pop elements from the back as a way to remove them. var isReversed = false var isEmpty: Bool { storage.isEmpty } var last: ScalarAndNormData? { storage.last } mutating func append(_ scalarAndNormData: ScalarAndNormData) { _internalInvariant(!isReversed) storage.append(scalarAndNormData) } // Removes the first element from the buffer. Note: it is not safe to append // to the buffer after this function has been called. We reverse the storage // internally for everything to be emitted out, so appending would insert // into the storage at the wrong location. One must continue to call this // function until a 'nil' return value has been received before appending. mutating func next() -> ScalarAndNormData? { guard !storage.isEmpty else { isReversed = false return nil } // If our storage hasn't been reversed yet, do so now. if !isReversed { storage.reverse() isReversed = true } return storage.removeLast() } // Sort the entire buffer based on the canonical combining class. mutating func sort() { storage._insertionSort(within: storage.indices) { $0.normData.ccc < $1.normData.ccc } } } } extension Unicode { // A wrapper type over the decomposition entry value we receive when we // lookup a scalar's canonical decomposition. The layout of the underlying // 32 bit value we receive is as follows: // // Top 14 bits Bottom 18 bits // // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // └───────── Index ─────────┘ └───────── Hashed Scalar ─────────┘ // // Index: This is the direct index into '_swift_stdlib_nfd_decompositions' // that points to a size byte indicating the overall size of the // UTF-8 decomposition string. Following the size byte is said string. // // Hashed Scalar: Because perfect hashing doesn't know the original set of // keys it was hashed with, we store the original scalar in the // decomposition entry so that we can guard against scalars // who happen to hash to the same index. // internal struct _DecompositionEntry { let rawValue: UInt32 // Our original scalar is stored in the first 18 bits of this entry. var hashedScalar: Unicode.Scalar { Unicode.Scalar(_value: (rawValue << 14) >> 14) } // The index into the decomposition array is stored in the top 14 bits. var index: Int { Int(truncatingIfNeeded: rawValue >> 18) } // A buffer pointer to the UTF8 decomposition string. var utf8: UnsafeBufferPointer<UInt8> { let decompPtr = _swift_stdlib_nfd_decompositions._unsafelyUnwrappedUnchecked // This size is the utf8 length of the decomposition. let size = Int(truncatingIfNeeded: decompPtr[index]) return UnsafeBufferPointer( // We add 1 here to skip the size byte. start: decompPtr + index + 1, count: size ) } init(_ scalar: Unicode.Scalar) { rawValue = _swift_stdlib_getDecompositionEntry(scalar.value) } } }
apache-2.0
bdae1f42f567d0c6b7d06526ce480c2d
33.952381
82
0.621405
4.380637
false
false
false
false
Johennes/firefox-ios
StorageTests/TestLogins.swift
2
31154
/* 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 Shared @testable import Storage import XCGLogger import XCTest private let log = XCGLogger.defaultInstance() class TestSQLiteLogins: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! let formSubmitURL = "http://submit.me" let login = Login.createWithHostname("hostname1", username: "username1", password: "password1", formSubmitURL: "http://submit.me") override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsqlitelogins.db", files: files) self.logins = SQLiteLogins(db: self.db) let expectation = self.expectationWithDescription("Remove all logins.") self.removeAllLogins().upon({ res in expectation.fulfill() }) waitForExpectationsWithTimeout(10.0, handler: nil) } func testAddLogin() { log.debug("Created \(self.login)") let expectation = self.expectationWithDescription("Add login") addLogin(login) >>> getLoginsFor(login.protectionSpace, expected: [login]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testGetOrder() { let expectation = self.expectationWithDescription("Add login") // Different GUID. let login2 = Login.createWithHostname("hostname1", username: "username2", password: "password2") login2.formSubmitURL = "http://submit.me" addLogin(login) >>> { self.addLogin(login2) } >>> getLoginsFor(login.protectionSpace, expected: [login2, login]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testRemoveLogin() { let expectation = self.expectationWithDescription("Remove login") addLogin(login) >>> removeLogin(login) >>> getLoginsFor(login.protectionSpace, expected: []) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testRemoveLogins() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1", formSubmitURL: formSubmitURL) let loginB = Login.createWithHostname("alpha.com", username: "username2", password: "password2", formSubmitURL: formSubmitURL) let loginC = Login.createWithHostname("berry.com", username: "username3", password: "password3", formSubmitURL: formSubmitURL) let loginD = Login.createWithHostname("candle.com", username: "username4", password: "password4", formSubmitURL: formSubmitURL) func addLogins() -> Success { addLogin(loginA).value addLogin(loginB).value addLogin(loginC).value addLogin(loginD).value return succeed() } addLogins().value let guids = [loginA.guid, loginB.guid] logins.removeLoginsWithGUIDs(guids).value let result = logins.getAllLogins().value.successValue! XCTAssertEqual(result.count, 2) } func testRemoveManyLogins() { log.debug("Remove a large number of logins at once") var guids: [GUID] = [] for i in 0..<2000 { let login = Login.createWithHostname("mozilla.org", username: "Fire", password: "fox", formSubmitURL: formSubmitURL) if i <= 1000 { guids += [login.guid] } addLogin(login).value } logins.removeLoginsWithGUIDs(guids).value let result = logins.getAllLogins().value.successValue! XCTAssertEqual(result.count, 999) } func testUpdateLogin() { let expectation = self.expectationWithDescription("Update login") let updated = Login.createWithHostname("hostname1", username: "username1", password: "password3", formSubmitURL: formSubmitURL) updated.guid = self.login.guid addLogin(login) >>> updateLogin(updated) >>> getLoginsFor(login.protectionSpace, expected: [updated]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testAddInvalidLogin() { let emptyPasswordLogin = Login.createWithHostname("hostname1", username: "username1", password: "", formSubmitURL: formSubmitURL) var result = logins.addLogin(emptyPasswordLogin).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty password.") let emptyHostnameLogin = Login.createWithHostname("", username: "username1", password: "password", formSubmitURL: formSubmitURL) result = logins.addLogin(emptyHostnameLogin).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty hostname.") let credential = NSURLCredential(user: "username", password: "password", persistence: .ForSession) let protectionSpace = NSURLProtectionSpace(host: "https://website.com", port: 443, protocol: "https", realm: "Basic Auth", authenticationMethod: "Basic Auth") let bothFormSubmitURLAndRealm = Login.createWithCredential(credential, protectionSpace: protectionSpace) bothFormSubmitURLAndRealm.formSubmitURL = "http://submit.me" result = logins.addLogin(bothFormSubmitURLAndRealm).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with both a httpRealm and formSubmitURL.") let noFormSubmitURLOrRealm = Login.createWithHostname("host", username: "username1", password: "password", formSubmitURL: nil) result = logins.addLogin(noFormSubmitURLOrRealm).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login without a httpRealm or formSubmitURL.") } func testUpdateInvalidLogin() { let updated = Login.createWithHostname("hostname1", username: "username1", password: "", formSubmitURL: formSubmitURL) updated.guid = self.login.guid addLogin(login).value var result = logins.updateLoginByGUID(login.guid, new: updated, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty password.") let emptyHostnameLogin = Login.createWithHostname("", username: "username1", password: "", formSubmitURL: formSubmitURL) emptyHostnameLogin.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: emptyHostnameLogin, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with an empty hostname.") let credential = NSURLCredential(user: "username", password: "password", persistence: .ForSession) let protectionSpace = NSURLProtectionSpace(host: "https://website.com", port: 443, protocol: "https", realm: "Basic Auth", authenticationMethod: "Basic Auth") let bothFormSubmitURLAndRealm = Login.createWithCredential(credential, protectionSpace: protectionSpace) bothFormSubmitURLAndRealm.formSubmitURL = "http://submit.me" bothFormSubmitURLAndRealm.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: bothFormSubmitURLAndRealm, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login with both a httpRealm and formSubmitURL.") let noFormSubmitURLOrRealm = Login.createWithHostname("host", username: "username1", password: "password", formSubmitURL: nil) noFormSubmitURLOrRealm.guid = self.login.guid result = logins.updateLoginByGUID(login.guid, new: noFormSubmitURLOrRealm, significant: true).value XCTAssertNil(result.successValue) XCTAssertNotNil(result.failureValue) XCTAssertEqual(result.failureValue?.description, "Can't add a login without a httpRealm or formSubmitURL.") } func testSearchLogins() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1", formSubmitURL: formSubmitURL) let loginB = Login.createWithHostname("alpha.com", username: "username2", password: "password2", formSubmitURL: formSubmitURL) let loginC = Login.createWithHostname("berry.com", username: "username3", password: "password3", formSubmitURL: formSubmitURL) let loginD = Login.createWithHostname("candle.com", username: "username4", password: "password4", formSubmitURL: formSubmitURL) func addLogins() -> Success { addLogin(loginA).value addLogin(loginB).value addLogin(loginC).value addLogin(loginD).value return succeed() } func checkAllLogins() -> Success { return logins.getAllLogins() >>== { results in XCTAssertEqual(results.count, 4) return succeed() } } func checkSearchHostnames() -> Success { return logins.searchLoginsWithQuery("pha") >>== { results in XCTAssertEqual(results.count, 2) XCTAssertEqual(results[0]!.hostname, "http://alpha.com") XCTAssertEqual(results[1]!.hostname, "http://alphabet.com") return succeed() } } func checkSearchUsernames() -> Success { return logins.searchLoginsWithQuery("username") >>== { results in XCTAssertEqual(results.count, 4) XCTAssertEqual(results[0]!.username, "username2") XCTAssertEqual(results[1]!.username, "username1") XCTAssertEqual(results[2]!.username, "username3") XCTAssertEqual(results[3]!.username, "username4") return succeed() } } func checkSearchPasswords() -> Success { return logins.searchLoginsWithQuery("pass") >>== { results in XCTAssertEqual(results.count, 4) XCTAssertEqual(results[0]!.password, "password2") XCTAssertEqual(results[1]!.password, "password1") XCTAssertEqual(results[2]!.password, "password3") XCTAssertEqual(results[3]!.password, "password4") return succeed() } } XCTAssertTrue(addLogins().value.isSuccess) XCTAssertTrue(checkAllLogins().value.isSuccess) XCTAssertTrue(checkSearchHostnames().value.isSuccess) XCTAssertTrue(checkSearchUsernames().value.isSuccess) XCTAssertTrue(checkSearchPasswords().value.isSuccess) XCTAssertTrue(removeAllLogins().value.isSuccess) } /* func testAddUseOfLogin() { let expectation = self.expectationWithDescription("Add visit") if var usageData = login as? LoginUsageData { usageData.timeCreated = NSDate.nowMicroseconds() } addLogin(login) >>> addUseDelayed(login, time: 1) >>> getLoginDetailsFor(login, expected: login as! LoginUsageData) >>> done(login.protectionSpace, expectation: expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } */ func done(expectation: XCTestExpectation)() -> Success { return removeAllLogins() >>> getLoginsFor(login.protectionSpace, expected: []) >>> { expectation.fulfill() return succeed() } } // Note: These functions are all curried so that we pass arguments, but still chain them below func addLogin(login: LoginData) -> Success { log.debug("Add \(login)") return logins.addLogin(login) } func updateLogin(login: LoginData)() -> Success { log.debug("Update \(login)") return logins.updateLoginByGUID(login.guid, new: login, significant: true) } func addUseDelayed(login: Login, time: UInt32)() -> Success { sleep(time) login.timeLastUsed = NSDate.nowMicroseconds() let res = logins.addUseOfLoginByGUID(login.guid) sleep(time) return res } func getLoginsFor(protectionSpace: NSURLProtectionSpace, expected: [LoginData]) -> (() -> Success) { return { log.debug("Get logins for \(protectionSpace)") return self.logins.getLoginsForProtectionSpace(protectionSpace) >>== { results in XCTAssertEqual(expected.count, results.count) for (index, login) in expected.enumerate() { XCTAssertEqual(results[index]!.username!, login.username!) XCTAssertEqual(results[index]!.hostname, login.hostname) XCTAssertEqual(results[index]!.password, login.password) } return succeed() } } } /* func getLoginDetailsFor(login: LoginData, expected: LoginUsageData) -> (() -> Success) { return { log.debug("Get details for \(login)") let deferred = self.logins.getUsageDataForLogin(login) log.debug("Final result \(deferred)") return deferred >>== { l in log.debug("Got cursor") XCTAssertLessThan(expected.timePasswordChanged - l.timePasswordChanged, 10) XCTAssertLessThan(expected.timeLastUsed - l.timeLastUsed, 10) XCTAssertLessThan(expected.timeCreated - l.timeCreated, 10) return succeed() } } } */ func removeLogin(login: LoginData)() -> Success { log.debug("Remove \(login)") return logins.removeLoginByGUID(login.guid) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM \(TableLoginsMirror)") >>> { self.db.run("DELETE FROM \(TableLoginsLocal)") } } } class TestSQLiteLoginsPerf: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsqlitelogins.db", files: files) self.logins = SQLiteLogins(db: self.db) } func testLoginsSearchMatchOnePerf() { populateTestLogins() // Measure time to find one entry amongst the 1000 of them self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { self.logins.searchLoginsWithQuery("username500").value } self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func testLoginsSearchMatchAllPerf() { populateTestLogins() // Measure time to find all matching results self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { self.logins.searchLoginsWithQuery("username").value } self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func testLoginsGetAllPerf() { populateTestLogins() // Measure time to find all matching results self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { self.logins.getAllLogins().value } self.stopMeasuring() } XCTAssertTrue(removeAllLogins().value.isSuccess) } func populateTestLogins() { for i in 0..<1000 { let login = Login.createWithHostname("website\(i).com", username: "username\(i)", password: "password\(i)") addLogin(login).value } } func addLogin(login: LoginData) -> Success { return logins.addLogin(login) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM \(TableLoginsMirror)") >>> { self.db.run("DELETE FROM \(TableLoginsLocal)") } } } class TestSyncableLogins: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsyncablelogins.db", files: files) self.logins = SQLiteLogins(db: self.db) let expectation = self.expectationWithDescription("Remove all logins.") self.removeAllLogins().upon({ res in expectation.fulfill() }) waitForExpectationsWithTimeout(10.0, handler: nil) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM \(TableLoginsMirror)") >>> { self.db.run("DELETE FROM \(TableLoginsLocal)") } } func testDiffers() { let guid = "abcdabcdabcd" let host = "http://example.com" let user = "username" let loginA1 = Login(guid: guid, hostname: host, username: user, password: "password1") loginA1.formSubmitURL = "\(host)/form1/" loginA1.usernameField = "afield" let loginA2 = Login(guid: guid, hostname: host, username: user, password: "password1") loginA2.formSubmitURL = "\(host)/form1/" loginA2.usernameField = "somefield" let loginB = Login(guid: guid, hostname: host, username: user, password: "password2") loginB.formSubmitURL = "\(host)/form1/" let loginC = Login(guid: guid, hostname: host, username: user, password: "password") loginC.formSubmitURL = "\(host)/form2/" XCTAssert(loginA1.isSignificantlyDifferentFrom(loginB)) XCTAssert(loginA1.isSignificantlyDifferentFrom(loginC)) XCTAssert(loginA2.isSignificantlyDifferentFrom(loginB)) XCTAssert(loginA2.isSignificantlyDifferentFrom(loginC)) XCTAssert(!loginA1.isSignificantlyDifferentFrom(loginA2)) } func testLocalNewStaysNewAndIsRemoved() { let guidA = "abcdabcdabcd" let loginA1 = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "password") loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 1 XCTAssertTrue((self.logins as BrowserLogins).addLogin(loginA1).value.isSuccess) let local1 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! XCTAssertNotNil(local1) XCTAssertEqual(local1!.guid, guidA) XCTAssertEqual(local1!.syncStatus, SyncStatus.New) XCTAssertEqual(local1!.timesUsed, 1) XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess) // It's still new. let local2 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! XCTAssertNotNil(local2) XCTAssertEqual(local2!.guid, guidA) XCTAssertEqual(local2!.syncStatus, SyncStatus.New) XCTAssertEqual(local2!.timesUsed, 2) // It's removed immediately, because it was never synced. XCTAssertTrue((self.logins as BrowserLogins).removeLoginByGUID(guidA).value.isSuccess) XCTAssertNil(self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!) } func testApplyLogin() { let guidA = "abcdabcdabcd" let loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234) loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 3 XCTAssertTrue(self.logins.applyChangedLogin(loginA1).value.isSuccess) let local = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirror = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertTrue(nil == local) XCTAssertTrue(nil != mirror) XCTAssertEqual(mirror!.guid, guidA) XCTAssertFalse(mirror!.isOverridden) XCTAssertEqual(mirror!.serverModified, Timestamp(1234), "Timestamp matches.") XCTAssertEqual(mirror!.timesUsed, 3) XCTAssertTrue(nil == mirror!.httpRealm) XCTAssertTrue(nil == mirror!.passwordField) XCTAssertTrue(nil == mirror!.usernameField) XCTAssertEqual(mirror!.formSubmitURL!, "http://example.com/form/") XCTAssertEqual(mirror!.hostname, "http://example.com") XCTAssertEqual(mirror!.username!, "username") XCTAssertEqual(mirror!.password, "password") // Change it. let loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "newpassword", modified: 2234) loginA2.formSubmitURL = "http://example.com/form/" loginA2.timesUsed = 4 XCTAssertTrue(self.logins.applyChangedLogin(loginA2).value.isSuccess) let changed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertTrue(nil != changed) XCTAssertFalse(changed!.isOverridden) XCTAssertEqual(changed!.serverModified, Timestamp(2234), "Timestamp is new.") XCTAssertEqual(changed!.username!, "username") XCTAssertEqual(changed!.password, "newpassword") XCTAssertEqual(changed!.timesUsed, 4) // Change it locally. let preUse = NSDate.now() XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess) let localUsed = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirrorUsed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertNotNil(localUsed) XCTAssertNotNil(mirrorUsed) XCTAssertEqual(mirrorUsed!.guid, guidA) XCTAssertEqual(localUsed!.guid, guidA) XCTAssertEqual(mirrorUsed!.password, "newpassword") XCTAssertEqual(localUsed!.password, "newpassword") XCTAssertTrue(mirrorUsed!.isOverridden) // It's now overridden. XCTAssertEqual(mirrorUsed!.serverModified, Timestamp(2234), "Timestamp is new.") XCTAssertTrue(localUsed!.localModified >= preUse) // Local record is modified. XCTAssertEqual(localUsed!.syncStatus, SyncStatus.Synced) // Uses aren't enough to warrant upload. // Uses are local until reconciled. XCTAssertEqual(localUsed!.timesUsed, 5) XCTAssertEqual(mirrorUsed!.timesUsed, 4) // Change the password and form URL locally. let newLocalPassword = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "yupyup") newLocalPassword.formSubmitURL = "http://example.com/form2/" let preUpdate = NSDate.now() // Updates always bump our usages, too. XCTAssertTrue(self.logins.updateLoginByGUID(guidA, new: newLocalPassword, significant: true).value.isSuccess) let localAltered = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirrorAltered = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(mirrorUsed!)) // The mirror is unchanged. XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(localUsed!)) XCTAssertTrue(mirrorAltered!.isOverridden) // It's still overridden. XCTAssertTrue(localAltered!.isSignificantlyDifferentFrom(localUsed!)) XCTAssertEqual(localAltered!.password, "yupyup") XCTAssertEqual(localAltered!.formSubmitURL!, "http://example.com/form2/") XCTAssertTrue(localAltered!.localModified >= preUpdate) XCTAssertEqual(localAltered!.syncStatus, SyncStatus.Changed) // Changes are enough to warrant upload. XCTAssertEqual(localAltered!.timesUsed, 6) XCTAssertEqual(mirrorAltered!.timesUsed, 4) } func testDeltas() { // Shared. let guidA = "abcdabcdabcd" let loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234) loginA1.timeCreated = 1200 loginA1.timeLastUsed = 1234 loginA1.timePasswordChanged = 1200 loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 3 let a1a1 = loginA1.deltas(from: loginA1) XCTAssertEqual(0, a1a1.nonCommutative.count) XCTAssertEqual(0, a1a1.nonConflicting.count) XCTAssertEqual(0, a1a1.commutative.count) let loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1235) loginA2.timeCreated = 1200 loginA2.timeLastUsed = 1235 loginA2.timePasswordChanged = 1200 loginA2.timesUsed = 4 let a1a2 = loginA2.deltas(from: loginA1) XCTAssertEqual(2, a1a2.nonCommutative.count) XCTAssertEqual(0, a1a2.nonConflicting.count) XCTAssertEqual(1, a1a2.commutative.count) switch a1a2.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(increment, 1) break } switch a1a2.nonCommutative[0] { case let .FormSubmitURL(to): XCTAssertNil(to) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a2.nonCommutative[1] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1235) break default: XCTFail("Unexpected non-commutative login field.") } let loginA3 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "something else", modified: 1280) loginA3.timeCreated = 1200 loginA3.timeLastUsed = 1250 loginA3.timePasswordChanged = 1250 loginA3.formSubmitURL = "http://example.com/form/" loginA3.timesUsed = 5 let a1a3 = loginA3.deltas(from: loginA1) XCTAssertEqual(3, a1a3.nonCommutative.count) XCTAssertEqual(0, a1a3.nonConflicting.count) XCTAssertEqual(1, a1a3.commutative.count) switch a1a3.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(increment, 2) break } switch a1a3.nonCommutative[0] { case let .Password(to): XCTAssertEqual("something else", to) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a3.nonCommutative[1] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a3.nonCommutative[2] { case let .TimePasswordChanged(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } // Now apply the deltas to the original record and check that they match! XCTAssertFalse(loginA1.applyDeltas(a1a2).isSignificantlyDifferentFrom(loginA2)) XCTAssertFalse(loginA1.applyDeltas(a1a3).isSignificantlyDifferentFrom(loginA3)) let merged = Login.mergeDeltas(a: (loginA2.serverModified, a1a2), b: (loginA3.serverModified, a1a3)) let mCCount = merged.commutative.count let a2CCount = a1a2.commutative.count let a3CCount = a1a3.commutative.count XCTAssertEqual(mCCount, a2CCount + a3CCount) let mNCount = merged.nonCommutative.count let a2NCount = a1a2.nonCommutative.count let a3NCount = a1a3.nonCommutative.count XCTAssertLessThanOrEqual(mNCount, a2NCount + a3NCount) XCTAssertGreaterThanOrEqual(mNCount, max(a2NCount, a3NCount)) let mFCount = merged.nonConflicting.count let a2FCount = a1a2.nonConflicting.count let a3FCount = a1a3.nonConflicting.count XCTAssertLessThanOrEqual(mFCount, a2FCount + a3FCount) XCTAssertGreaterThanOrEqual(mFCount, max(a2FCount, a3FCount)) switch merged.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(1, increment) } switch merged.commutative[1] { case let .TimesUsed(increment): XCTAssertEqual(2, increment) } switch merged.nonCommutative[0] { case let .Password(to): XCTAssertEqual("something else", to) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[1] { case let .FormSubmitURL(to): XCTAssertNil(to) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[2] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[3] { case let .TimePasswordChanged(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } // Applying the merged deltas gives us the expected login. let expected = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "something else") expected.timeCreated = 1200 expected.timeLastUsed = 1250 expected.timePasswordChanged = 1250 expected.formSubmitURL = nil expected.timesUsed = 6 let applied = loginA1.applyDeltas(merged) XCTAssertFalse(applied.isSignificantlyDifferentFrom(expected)) XCTAssertFalse(expected.isSignificantlyDifferentFrom(applied)) } func testLoginsIsSynced() { let loginA = Login.createWithHostname("alphabet.com", username: "username1", password: "password1") let serverLoginA = ServerLogin(guid: loginA.guid, hostname: "alpha.com", username: "username1", password: "password1", modified: NSDate.now()) XCTAssertFalse(logins.hasSyncedLogins().value.successValue ?? true) logins.addLogin(loginA).value XCTAssertFalse(logins.hasSyncedLogins().value.successValue ?? false) logins.applyChangedLogin(serverLoginA).value XCTAssertTrue(logins.hasSyncedLogins().value.successValue ?? false) } }
mpl-2.0
20dfb46a469017385f587edab8880264
41.1
166
0.653784
4.95767
false
false
false
false
IMcD23/Proton
Source/Core/View/View+Size.swift
1
1230
// // View+Size.swift // Proton // // Created by McDowell, Ian J [ITACD] on 4/5/16. // Copyright © 2016 Ian McDowell. All rights reserved. // public extension View { public func size(width width: Percent, height: Percent) -> Self { self.size = LayoutSize(type: .Percent, width: width.value, height: height.value) return self } public func size(width width: CGFloat, height: CGFloat) -> Self { return self.size(size: CGSizeMake(width, height)) } public func size(size size: CGSize) -> Self { self.size = LayoutSize(type: .Fixed, width: size.width, height: size.height) return self } public func width(width: CGFloat) -> Self { self.size.type = .Fixed self.size.width = width return self } public func height(height: CGFloat) -> Self { self.size.type = .Fixed self.size.height = height return self } public func width(width: Percent) -> Self { self.size.type = .Percent self.size.width = width.value return self } public func height(height: Percent) -> Self { self.size.type = .Percent self.size.height = height.value return self } }
mit
5d00ad5f523c326a3605e202f4182cdd
28.97561
88
0.603743
3.840625
false
false
false
false
huonw/swift
stdlib/public/core/WriteBackMutableSlice.swift
12
1730
//===--- WriteBackMutableSlice.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 // //===----------------------------------------------------------------------===// @inlinable internal func _writeBackMutableSlice<C, Slice_>( _ self_: inout C, bounds: Range<C.Index>, slice: Slice_ ) where C : MutableCollection, Slice_ : Collection, C.Element == Slice_.Element, C.Index == Slice_.Index { self_._failEarlyRangeCheck(bounds, bounds: self_.startIndex..<self_.endIndex) // FIXME(performance): can we use // _withUnsafeMutableBufferPointerIfSupported? Would that create inout // aliasing violations if the newValue points to the same buffer? var selfElementIndex = bounds.lowerBound let selfElementsEndIndex = bounds.upperBound var newElementIndex = slice.startIndex let newElementsEndIndex = slice.endIndex while selfElementIndex != selfElementsEndIndex && newElementIndex != newElementsEndIndex { self_[selfElementIndex] = slice[newElementIndex] self_.formIndex(after: &selfElementIndex) slice.formIndex(after: &newElementIndex) } _precondition( selfElementIndex == selfElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a smaller size") _precondition( newElementIndex == newElementsEndIndex, "Cannot replace a slice of a MutableCollection with a slice of a larger size") }
apache-2.0
49dac0392f5b6bd4388137819dd19257
35.041667
83
0.689595
4.818942
false
false
false
false
AlesTsurko/AudioKit
Tests/Tests/AKBalance.swift
2
1253
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/21/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: Float = 4.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let amplitude = AKOscillator() amplitude.frequency = 1.ak let oscillator = AKOscillator() oscillator.amplitude = amplitude auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:oscillator) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let synth = AKFMOscillator() let balanced = AKBalance(input: synth, comparatorAudioSource: audioSource) setAudioOutput(balanced) resetParameter(audioSource) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) processor.play() instrument.play() let manager = AKManager.sharedManager() while(manager.isRunning) {} //do nothing println("Test complete!")
lgpl-3.0
4dc1fa9ca3a4ee08b6d933138260f811
20.982456
82
0.703113
4.675373
false
true
false
false
Yvent/YVImagePickerController
YVImagePickerController/YVImagePickerCell.swift
2
2425
// // YVImagePickerCell.swift // Demo // // Created by 周逸文 on 2017/10/12. // Copyright © 2017年 YV. All rights reserved. // import UIKit class YVImagePickerCell: UICollectionViewCell { var closeBtnColor: UIColor = UIColor(red: 88/255.0, green: 197/255.0, blue: 141/255.0, alpha: 1) var imageV: UIImageView! var closeBtn: UIButton! var timeLab: UILabel! override init(frame: CGRect) { super.init(frame: frame) initUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initUI() { contentView.backgroundColor = UIColor.white let imagevFrame: CGRect = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) imageV = UIImageView(frame: imagevFrame) let closeBtnFrame: CGRect = CGRect(x: self.frame.width-3-24, y: 3, width: 24, height: 24) closeBtn = UIButton(frame: closeBtnFrame) let bundle = Bundle(for: YVImagePickerController.self) let path = bundle.path(forResource: "YVImagePickerController", ofType: "bundle") let imageBundle = Bundle(path: path!) let nolImage = UIImage(contentsOfFile: (imageBundle?.path(forResource: "yvCloseBtn_nol", ofType: "png"))!) let selImage = UIImage(contentsOfFile: (imageBundle?.path(forResource: "yvCloseBtn_sel", ofType: "png"))!) closeBtn.setImage(nolImage, for: .normal) closeBtn.setImage(selImage, for: .selected) closeBtn.isUserInteractionEnabled = false let timeLabFrame: CGRect = CGRect(x: 5, y: self.frame.height-20, width: self.frame.width-10, height: 20) timeLab = UILabel(frame: timeLabFrame) timeLab.textAlignment = .right timeLab.textColor = UIColor.white timeLab.font = UIFont.systemFont(ofSize: 12) self.contentView.addSubview(imageV) self.contentView.addSubview(closeBtn) self.contentView.addSubview(timeLab) } func createImageWithColor(clolr: UIColor,rect: CGRect) -> UIImage{ UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(clolr.cgColor) context!.fill(rect) let theImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return theImage! } }
mit
e03edf8e0d2bb8590e0944797fe3cbba
36.75
114
0.656871
4.268551
false
false
false
false
linhaosunny/yeehaiyake
椰海雅客微博/椰海雅客微博/Classes/Main/LSXVisitorView.swift
1
4660
// // LSXVisitorView.swift // 椰海雅客微博 // // Created by 李莎鑫 on 2017/4/3. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit class LSXVisitorView: UIView { //MARK: 懒加载 //: 转盘 lazy var rotationView:UIImageView = { () -> UIImageView in let imageView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_image_smallicon")) return imageView }() //: 转盘遮盖 lazy var rotationCoverView:UIImageView = { () -> UIImageView in let coverView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_mask_smallicon")) return coverView }() //: 图片 lazy var imageView:UIImageView = { () -> UIImageView in let iconView = UIImageView(image: #imageLiteral(resourceName: "visitordiscover_feed_image_house")) return iconView }() //: 标题 lazy var titleLable:UILabel = { () -> UILabel in let label = UILabel() label.textColor = UIColor.gray label.numberOfLines = 0; label.text = "新特性,抢先试玩,注册就能体验新的生活方式" return label }() //: 注册 lazy var registerButton:UIButton = { () -> UIButton in let button = UIButton() button.setTitleColor(SystemTintColor, for: .normal) button.setTitleColor(UIColor.white, for: .highlighted) button.setTitle("注册", for: .normal) button.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .normal) return button }() //: 登录 lazy var loginButton:UIButton = { () -> UIButton in let button = UIButton() button.setTitleColor(UIColor.gray, for: .normal) button.setTitleColor(UIColor.white, for: .highlighted) button.setTitle("登录", for: .normal) button.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .normal) return button }() //MARK: 构造方法 class func visitorView() -> LSXVisitorView { let view = self.init() view.addSubview(view.rotationView) view.addSubview(view.rotationCoverView) view.addSubview(view.imageView) view.addSubview(view.titleLable) view.addSubview(view.registerButton) view.addSubview(view.loginButton) return view } //MARK: 私有方法 //: 使用自动布局工具snapkit override func layoutSubviews() { super.layoutSubviews() rotationView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().offset(-100) } rotationCoverView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().offset(-100) } imageView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview().offset(-100) } titleLable.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.width.equalTo(240) make.top.equalTo(imageView.snp.bottom).offset(40) } registerButton.snp.makeConstraints { (make) in make.left.equalTo(titleLable.snp.left) make.top.equalTo(titleLable.snp.bottom).offset(20) make.width.equalTo(100) make.height.equalTo(40) } loginButton.snp.makeConstraints { (make) in make.right.equalTo(titleLable.snp.right) make.top.width.height.equalTo(registerButton) } } func startAnimation() { let animation = CABasicAnimation(keyPath: "transform.rotation") //: 设置动画属性 animation.toValue = 2 * M_PI animation.duration = 10.0 animation.repeatCount = MAXFLOAT // 注意: 默认情况下只要视图消失, 系统就会自动移除动画 // 只要设置removedOnCompletion为false, 系统就不会移除动画 animation.isRemovedOnCompletion = false rotationView.layer.add(animation, forKey: "transform.rotation") } //MARK: 外部调用方法 func setupVisitorInfo(imageName: String? ,title: String){ titleLable.text = title guard let name = imageName else { startAnimation() return } rotationView.isHidden = true imageView.image = UIImage(named: name) } }
mit
7bb906e32d8b5d26e485cb74c667e75b
31.255474
111
0.606246
4.636936
false
false
false
false
austinzheng/swift
test/decl/protocol/req/associated_type_ambiguity.swift
27
1748
// RUN: %target-typecheck-verify-swift // Reference to associated type from 'where' clause should not be // ambiguous when there's a typealias with the same name in another // protocol. // // FIXME: The semantics here are still really iffy. There's also a // case to be made that type aliases in protocol extensions should // only act as defaults and not as same-type constraints. However, // if we decide to go down that route, it's important that *both* // the unqualified (T) and qualified (Self.T) lookups behave the // same. protocol P1 { typealias T = Int // expected-note {{found this candidate}} } protocol P2 { associatedtype T // expected-note {{found this candidate}} } // FIXME: This extension's generic signature is still minimized differently from // the next one. We need to decide if 'T == Int' is a redundant requirement or // not. extension P1 where Self : P2, T == Int { func takeT1(_: T) {} func takeT2(_: Self.T) {} } extension P1 where Self : P2 { // FIXME: This doesn't make sense -- either both should // succeed, or both should be ambiguous. func takeT1(_: T) {} // expected-error {{'T' is ambiguous for type lookup in this context}} func takeT2(_: Self.T) {} } // Same as above, but now we have two visible associated types with the same // name. protocol P3 { associatedtype T } // FIXME: This extension's generic signature is still minimized differently from // the next one. We need to decide if 'T == Int' is a redundant requirement or // not. extension P2 where Self : P3, T == Int { func takeT1(_: T) {} func takeT2(_: Self.T) {} } extension P2 where Self : P3 { func takeT1(_: T) {} func takeT2(_: Self.T) {} } protocol P4 : P2, P3 { func takeT1(_: T) func takeT2(_: Self.T) }
apache-2.0
ff1fc00c93228258ae0d4ec6aea5bfb3
29.137931
93
0.685927
3.61157
false
false
false
false
iabudiab/gdg-devfestka-2015-swift
Swift Intro.playground/Pages/Variables & Constants.xcplaygroundpage/Contents.swift
1
292
var answerToTheQuestionOfLife = 42 // Type is inferred answerToTheQuestionOfLife = 9001 // answerToTheQuestionOfLife = 3.14 // Compile error ~> Int var numberOfTalks: Int = 1 let language = "Swift" let pi: Double = 3.141592 // pi = 3.1415927 // Compile error ~> constant //: [Next](@next)
mit
95fc97b5b9e53ed6da24d1eaf738f5d5
25.545455
59
0.712329
3.518072
false
false
false
false
WLChopSticks/weibo-swift-
weibo(swift)/weibo(swift)/Classes/Tools/Extention/UILabel+Extention.swift
2
684
// // UILabel+Extention.swift // weibo(swift) // // Created by 王 on 15/12/16. // Copyright © 2015年 王. All rights reserved. // import UIKit //构造便利函数,扩展label的方法 extension UILabel { convenience init(title: String, color: UIColor, fontSize: CGFloat, margin: CGFloat = 0) { self.init() text = title numberOfLines = 0 textColor = color textAlignment = .Center font = UIFont.systemFontOfSize(fontSize) //针对参数设置label的宽度 if margin != 0 { preferredMaxLayoutWidth = screenWidth - 2 * margin textAlignment = .Left } } }
mit
b1c3e014ae7e853aa35e53d5fc6e3d5c
20.266667
93
0.580848
4.218543
false
false
false
false
Ruenzuo/fansabisu
FanSabisu/Sources/MediaViewController.swift
1
10542
import UIKit import Photos import FanSabisuKit class MediaViewController: GAITrackedViewController { @IBOutlet var collectionView: UICollectionView? var itemsPerRow: CGFloat? var dataSource: [PHAsset] = [] var activityIndicatorView: UIActivityIndicatorView? override func viewDidLoad() { super.viewDidLoad() self.title = String.localizedString(for: "MEDIA") self.screenName = "Media" setupItemsPerRow(with: self.view.frame.size) automaticallyAdjustsScrollViewInsets = false setupNavigationItems() PHPhotoLibrary.requestAuthorization { (status) in if status != .authorized { DispatchQueue.main.async { self.presentAuthorizationError() } } else { self.loadAssets() } } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { if hasUserInterfaceIdiomPadTrait() { self.collectionView?.reloadSections(IndexSet(integer: 0)) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) setupItemsPerRow(with: size) self.collectionView?.collectionViewLayout.invalidateLayout() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "MediaDetail" { let controller = segue.destination as! MediaDetailViewController let indexPath = collectionView?.indexPath(for: sender as! UICollectionViewCell) let asset = dataSource[indexPath!.row] controller.asset = asset } } func checkPasteboard() { if PHPhotoLibrary.authorizationStatus() != .authorized { DispatchQueue.main.async { self.presentAuthorizationError() } } else { processPasteboard() } } func setupItemsPerRow(with viewSize: CGSize) { let landscape = viewSize.width > viewSize.height if hasUserInterfaceIdiomPadTrait() { if landscape { itemsPerRow = 7 } else { itemsPerRow = 5 } } else { if landscape { itemsPerRow = 7 } else { itemsPerRow = 4 } } } func presentAuthorizationError() { self.activityIndicatorView?.stopAnimating() self.presentMessage(title: String.localizedString(for: "AUTHORIZATION_NOT_GRANTED"), message: String.localizedString(for: "USAGE_DESCRIPTION"), actionHandler: { let url = URL(string: UIApplicationOpenSettingsURLString)! UIApplication.shared.openURL(url) }) } func setupNavigationItems() { activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicatorView?.startAnimating() navigationItem.setLeftBarButton(UIBarButtonItem(customView: activityIndicatorView!), animated: true) let refreshBarButonItem = UIBarButtonItem(image: UIImage(named: "Refresh"), style: .plain, target: self, action: #selector(loadAssets)) let pasteboardBarButonItem = UIBarButtonItem(image: UIImage(named: "Clipboard"), style: .plain, target: self, action: #selector(checkPasteboard)) navigationItem.setRightBarButtonItems([refreshBarButonItem, pasteboardBarButonItem], animated: true) } func processPasteboard() { guard let pasteboard = UIPasteboard.general.string else { presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "PASTEBOARD_NOT_FOUND"), actionHandler: nil) return } guard let url = URL(string: pasteboard) else { presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "CONTENTS_NOT_SUITABLE"), actionHandler: nil) return } if !url.isValidURL { let message = String(format: String.localizedString(for: "INVALID_URL"), url.absoluteString) presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: message, actionHandler: nil) return } let message = String(format: String.localizedString(for: "URL_FOUND"), url.absoluteString) let controller = UIAlertController(title: String.localizedString(for: "PASTEBOARD_FOUND"), message: message, preferredStyle: .alert) controller.addAction(UIAlertAction(title: String.localizedString(for: "CANCEL"), style: .cancel, handler: nil)) controller.addAction(UIAlertAction(title: String.localizedString(for: "DOWNLOAD"), style: .default, handler: { (action) in self.activityIndicatorView?.startAnimating() let mediaDownloader = MediaDownloader(session: Session.shared) mediaDownloader.downloadMedia(with: url, completionHandler: { (result) in do { let videoUrl = try result.resolve() let videoProcessor = VideoProcessor() videoProcessor.processVideo(with: videoUrl, completionHandler: { (result) in guard let url = try? result.resolve() else { self.activityIndicatorView?.stopAnimating() return self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "PROCESS_VIDEO_ERROR"), actionHandler: nil) } let manager = FileManager.default try? manager.removeItem(at: url) self.activityIndicatorView?.stopAnimating() self.presentMessage(title: String.localizedString(for: "FINISHED"), message: String.localizedString(for: "GIF_STORED"), actionHandler: nil) self.loadAssets() }) } catch MediaDownloaderError.tooManyRequests { self.activityIndicatorView?.stopAnimating() return self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "TOO_MANY_REQUESTS"), actionHandler: nil) } catch MediaDownloaderError.forbidden { self.activityIndicatorView?.stopAnimating() return self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "FORBIDDEN"), actionHandler: nil) } catch { return self.presentMessage(title: String.localizedString(for: "ERROR_TITLE"), message: String.localizedString(for: "DOWNLOAD_VIDEO_ERROR"), actionHandler: nil) } }) })) present(controller, animated: true, completion: nil) } func loadAssets() { dataSource.removeAll() let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)] options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) let fetchResult = PHAsset.fetchAssets(with: options) fetchResult.enumerateObjects({ (asset, index, _) in let resources = PHAssetResource.assetResources(for: asset) for (_, resource) in resources.enumerated() { if resource.uniformTypeIdentifier == "com.compuserve.gif" { self.dataSource.append(asset) break } } }) DispatchQueue.main.async { self.activityIndicatorView?.stopAnimating() self.collectionView?.reloadSections(IndexSet(integer: 0)) } } @IBAction func unwindToMedia(sender: UIStoryboardSegue) { self.activityIndicatorView?.startAnimating() self.loadAssets() } } extension MediaViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AssetCell", for: indexPath) as! MediaCell cell.asset = dataSource[indexPath.row] if hasCompactHorizontalTrait() { cell.imageView?.contentMode = .scaleAspectFill } else { cell.imageView?.contentMode = .scaleAspectFit } return cell } } extension MediaViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { performSegue(withIdentifier: "MediaDetail", sender: collectionView.cellForItem(at: indexPath)) } } extension MediaViewController: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let interItemSpace: CGFloat if hasCompactHorizontalTrait() { interItemSpace = 1 } else { if hasUserInterfaceIdiomPadTrait() { interItemSpace = 20 } else { interItemSpace = 1 } } let paddingSpace = interItemSpace * (itemsPerRow! + 1) let availableWidth = view.frame.width - paddingSpace let widthPerItem = availableWidth / itemsPerRow! return CGSize(width: widthPerItem, height: widthPerItem) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { if hasCompactHorizontalTrait() { return .zero } else { return UIEdgeInsets.init(top: 16, left: 16, bottom: 16, right: 16) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { if hasCompactHorizontalTrait() { return 1 } else { return 10 } } }
mit
9183d513b57f393252bea1d56cc44ed3
42.742739
186
0.642573
5.530955
false
false
false
false
vary-llc/SugarRecord
spec/CoreData/DefaultCDStackTests.swift
10
6513
// // DefaultCDStackTests.swift // SugarRecord // // Created by Pedro Piñera Buendía on 27/09/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import UIKit import XCTest import CoreData class DefaultCDStackTests: XCTestCase { var stack: DefaultCDStack? = nil override func setUp() { super.setUp() let bundle: NSBundle = NSBundle(forClass: CoreDataObjectTests.classForCoder()) let modelPath: NSString = bundle.pathForResource("TestsDataModel", ofType: "momd")! let model: NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: NSURL(fileURLWithPath: modelPath)!)! stack = DefaultCDStack(databaseName: "TestDB.sqlite", model: model, automigrating: true) SugarRecord.addStack(stack!) } override func tearDown() { SugarRecord.cleanup() SugarRecord.removeAllStacks() SugarRecord.removeDatabase() super.tearDown() } func testThatTheRootSavingContextIsSavedInApplicationWillTerminate() { class MockCDStack: DefaultCDStack { var savedChangesInRootSavingContext: Bool = false override func saveChanges() { savedChangesInRootSavingContext = true } } let context: MockCDStack = MockCDStack(databaseName: "test", automigrating: false) context.applicationWillTerminate() XCTAssertTrue(context.savedChangesInRootSavingContext, "Root saving context should be saved when application will terminate") context.removeDatabase() } func testThatTheRootSavingContextIsSavedInApplicationWillResignActive() { class MockCDStack: DefaultCDStack { var savedChangesInRootSavingContext: Bool = false override func saveChanges() { savedChangesInRootSavingContext = true } } let context: MockCDStack = MockCDStack(databaseName: "test", automigrating: false) context.applicationWillResignActive() XCTAssertTrue(context.savedChangesInRootSavingContext, "Root saving context should be saved when application will resign active") context.removeDatabase() } func testInitializeOfComponents() { class MockCDStack: DefaultCDStack { var pscCreated: Bool = false var databaseAdded: Bool = false var rootSavingContextCreated: Bool = false var mainContextAdded: Bool = false override func createPersistentStoreCoordinator() -> NSPersistentStoreCoordinator { pscCreated = true return NSPersistentStoreCoordinator() } override func addDatabase(completionClosure: CompletionClosure) { databaseAdded = true completionClosure(error: nil) } override func createRootSavingContext(persistentStoreCoordinator: NSPersistentStoreCoordinator?) -> NSManagedObjectContext { rootSavingContextCreated = true return NSManagedObjectContext() } override func createMainContext(parentContext: NSManagedObjectContext?) -> NSManagedObjectContext { mainContextAdded = true return NSManagedObjectContext() } } let stack: MockCDStack = MockCDStack(databaseName: "test", automigrating: false) stack.initialize() XCTAssertTrue(stack.pscCreated, "Should initialize the persistent store coordinator") XCTAssertTrue(stack.databaseAdded, "Should add the database") XCTAssertTrue(stack.rootSavingContextCreated, "Should create the root saving context") XCTAssertTrue(stack.mainContextAdded, "Should add a main context") XCTAssertTrue(stack.stackInitialized, "Stack should be set as initialized") stack.removeDatabase() } func testBackgroundContextShouldHaveTheRootSavingContextAsParent() { XCTAssertEqual((stack!.backgroundContext() as SugarRecordCDContext).contextCD.parentContext!, stack!.rootSavingContext!, "The private context should have the root saving context as parent") } func testMainContextShouldHaveTheRootSavingContextAsParent() { XCTAssertEqual(stack!.mainContext!.parentContext!, stack!.rootSavingContext!, "Main saving context should have the root saving context as parent") } func testRootSavingContextShouldHaveThePersistentStoreCoordinatorAsParent() { XCTAssertEqual(stack!.rootSavingContext!.persistentStoreCoordinator!, stack!.persistentStoreCoordinator!, "Root saving context should have the PSC as parent") } func testBackgroundContextConcurrencyType() { XCTAssertEqual(stack!.rootSavingContext!.concurrencyType, NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType, "The concurrency type should be PrivateQueueConcurrencyType") } func testMainContextConcurrencyType() { XCTAssertEqual(stack!.mainContext!.concurrencyType, NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType, "The concurrency type should be MainQueueConcurrencyType") } func testRootSavingContextConcurrencyType() { XCTAssertEqual((stack!.backgroundContext() as SugarRecordCDContext).contextCD.concurrencyType, NSManagedObjectContextConcurrencyType.ConfinementConcurrencyType, "The concurrency type should be MainQueueConcurrencyType") } func testIfTheAutoSavingClosureIsCalledDependingOnTheAutoSavingProperty() { class MockDefaultStack: DefaultCDStack { var autoSavingClosureCalled: Bool = true override func autoSavingClosure() -> () -> () { return { [weak self] (notification) -> Void in self!.autoSavingClosureCalled = true } } } let mockStack: MockDefaultStack = MockDefaultStack(databaseName: "test", automigrating: false) mockStack.initialize() mockStack.autoSaving = true XCTAssertTrue(mockStack.autoSavingClosureCalled, "The AutoSavingClosure should be called if the autosaving is enabled") mockStack.autoSavingClosureCalled = false mockStack.autoSaving = false XCTAssertFalse(mockStack.autoSavingClosureCalled, "The AutoSavingClosure shouldn't be called if the autosaving is disabled") } }
mit
30ba7ad8f47cd0e01437e62b009e15d4
41.006452
227
0.686377
6.296905
false
true
false
false
lorentey/swift
test/Constraints/patterns.swift
1
10741
// RUN: %target-typecheck-verify-swift // Leaf expression patterns are matched to corresponding pieces of a switch // subject (TODO: or ~= expression) using ~= overload resolution. switch (1, 2.5, "three") { case (1, _, _): () // Double is ExpressibleByIntegerLiteral case (_, 2, _), (_, 2.5, _), (_, _, "three"): () // ~= overloaded for (Range<Int>, Int) case (0..<10, _, _), (0..<10, 2.5, "three"), (0...9, _, _), (0...9, 2.5, "three"): () default: () } switch (1, 2) { case (var a, a): // expected-error {{use of unresolved identifier 'a'}} () } // 'is' patterns can perform the same checks that 'is' expressions do. protocol P { func p() } class B : P { init() {} func p() {} func b() {} } class D : B { override init() { super.init() } func d() {} } class E { init() {} func e() {} } struct S : P { func p() {} func s() {} } // Existential-to-concrete. var bp : P = B() switch bp { case is B, is D, is S: () case is E: () default: () } switch bp { case let b as B: b.b() case let d as D: d.b() d.d() case let s as S: s.s() case let e as E: e.e() default: () } // Super-to-subclass. var db : B = D() switch db { case is D: () case is E: // expected-warning {{always fails}} () default: () } // Raise an error if pattern productions are used in expressions. var b = var x // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // TODO: Bad recovery in these cases. Although patterns are never valid // expr-unary productions, it would be good to parse them anyway for recovery. //var e = 2 + var y //var e = var y + 2 // 'E.Case' can be used in a dynamic type context as an equivalent to // '.Case as E'. protocol HairType {} enum MacbookHair: HairType { case HairSupply(S) } enum iPadHair<T>: HairType { case HairForceOne } enum Watch { case Sport, Watch, Edition } let hair: HairType = MacbookHair.HairSupply(S()) switch hair { case MacbookHair.HairSupply(let s): s.s() case iPadHair<S>.HairForceOne: () case iPadHair<E>.HairForceOne: () case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}} () case Watch.Edition: // expected-warning {{cast from 'HairType' to unrelated type 'Watch' always fails}} () case .HairForceOne: // expected-error{{type 'HairType' has no member 'HairForceOne'}} () default: break } // <rdar://problem/19382878> Introduce new x? pattern switch Optional(42) { case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} case nil: break } func SR2066(x: Int?) { // nil literals should still work when wrapped in parentheses switch x { case (nil): break case _?: break } switch x { case ((nil)): break case _?: break } switch (x, x) { case ((nil), _): break case (_?, _): break } } // Test x???? patterns. switch (nil as Int???) { case let x???: print(x, terminator: "") case let x??: print(x as Any, terminator: "") case let x?: print(x as Any, terminator: "") case 4???: break case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}} case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}} default: break } switch ("foo" as String?) { case "what": break default: break } // Test some value patterns. let x : Int? extension Int { func method() -> Int { return 42 } } func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool { return lhs == rhs } switch 4 as Int? { case x?.method(): break // match value default: break } switch 4 { case x ?? 42: break // match value default: break } for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}} for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}} var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} // Crash when re-typechecking EnumElementPattern. // FIXME: This should actually type-check -- the diagnostics are bogus. But // at least we don't crash anymore. protocol PP { associatedtype E } struct A<T> : PP { typealias E = T } extension PP { func map<T>(_ f: (Self.E) -> T) -> T {} // expected-note@-1 2 {{in call to function 'map'}} } enum EE { case A case B } func good(_ a: A<EE>) -> Int { return a.map { switch $0 { case .A: return 1 default: return 2 } } } func bad(_ a: A<EE>) { a.map { // expected-error {{generic parameter 'T' could not be inferred}} let _: EE = $0 return 1 } } func ugly(_ a: A<EE>) { a.map { // expected-error {{generic parameter 'T' could not be inferred}} switch $0 { case .A: return 1 default: return 2 } } } // SR-2057 enum SR2057 { case foo } let sr2057: SR2057? if case .foo = sr2057 { } // Ok // Invalid 'is' pattern class SomeClass {} if case let doesNotExist as SomeClass:AlsoDoesNotExist {} // expected-error@-1 {{use of undeclared type 'AlsoDoesNotExist'}} // expected-error@-2 {{variable binding in a condition requires an initializer}} // `.foo` and `.bar(...)` pattern syntax should also be able to match // static members as expr patterns struct StaticMembers: Equatable { init() {} init(_: Int) {} init?(opt: Int) {} static var prop = StaticMembers() static var optProp: Optional = StaticMembers() static func method(_: Int) -> StaticMembers { return prop } // expected-note@-1 {{found candidate with type '(Int) -> StaticMembers'}} static func method(withLabel: Int) -> StaticMembers { return prop } // expected-note@-1 {{found candidate with type '(Int) -> StaticMembers'}} static func optMethod(_: Int) -> StaticMembers? { return optProp } static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true } } let staticMembers = StaticMembers() let optStaticMembers: Optional = StaticMembers() switch staticMembers { case .init: break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(opt:): break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}} case .init(): break case .init(0): break case .init(_): break // expected-error{{'_' can only appear in a pattern}} case .init(let x): break // expected-error{{cannot appear in an expression}} case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}} // expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} // expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} case .prop: break // TODO: repeated error message case .optProp: break // expected-error* {{not unwrapped}} case .method: break // expected-error{{no exact matches in call to static method 'method'}} case .method(0): break case .method(_): break // expected-error{{'_' can only appear in a pattern}} case .method(let x): break // expected-error{{cannot appear in an expression}} case .method(withLabel:): break // expected-error{{member 'method(withLabel:)' expects argument of type 'Int'}} case .method(withLabel: 0): break case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}} case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}} case .optMethod: break // expected-error{{member 'optMethod' expects argument of type 'Int'}} case .optMethod(0): break // expected-error@-1 {{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}} // expected-note@-2 {{coalesce}} // expected-note@-3 {{force-unwrap}} } _ = 0 // rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining struct S_32241441 { enum E_32241441 { case foo case bar } var type: E_32241441 = E_32241441.foo } func rdar32241441() { let s: S_32241441? = S_32241441() switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}} case .foo: // Ok break; case .bar: // Ok break; } } // SR-6100 struct One<Two> { public enum E: Error { // if you remove associated value, everything works case SomeError(String) } } func testOne() { do { } catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}} if case One.E.SomeError = error {} // expected-error{{generic enum type 'One.E' is ambiguous without explicit generic parameters when matching value of type 'Error'}} } } // SR-8347 // constrain initializer expressions of optional some pattern bindings to be optional func test8347() -> String { struct C { subscript (s: String) -> String? { return "" } subscript (s: String) -> [String] { return [""] } func f() -> String? { return "" } func f() -> Int { return 3 } func g() -> String { return "" } func h() -> String { return "" } func h() -> Double { return 3.0 } func h() -> Int? { //expected-note{{found this candidate}} return 2 } func h() -> Float? { //expected-note{{found this candidate}} return nil } } let c = C() if let s = c[""] { return s } if let s = c.f() { return s } if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}} return s } if let s = c.h() { //expected-error{{ambiguous use of 'h()'}} return s } } enum SR_7799 { case baz case bar } let sr7799: SR_7799? = .bar switch sr7799 { case .bar?: break // Ok case .baz: break // Ok default: break } let sr7799_1: SR_7799?? = .baz switch sr7799_1 { case .bar?: break // Ok case .baz: break // Ok default: break } if case .baz = sr7799_1 {} // Ok if case .bar? = sr7799_1 {} // Ok
apache-2.0
760c14d5987d88d881dd677c4497290a
23.635321
208
0.633926
3.583917
false
false
false
false
lorentey/swift
test/SILGen/dynamically_replaceable.swift
3
19328
// RUN: %target-swift-emit-silgen -swift-version 5 %s | %FileCheck %s // RUN: %target-swift-emit-silgen -swift-version 5 %s -enable-implicit-dynamic | %FileCheck %s --check-prefix=IMPLICIT // RUN: %target-swift-emit-silgen -swift-version 5 %s -disable-previous-implementation-calls-in-dynamic-replacements | %FileCheck %s --check-prefix=NOPREVIOUS // CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable014maybe_dynamic_B0yyF : $@convention(thin) () -> () { // IMPLICIT-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable014maybe_dynamic_B0yyF : $@convention(thin) () -> () { func maybe_dynamic_replaceable() { } // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable08dynamic_B0yyF : $@convention(thin) () -> () { dynamic func dynamic_replaceable() { } // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV1xACSi_tcfC : $@convention(method) (Int, @thin Strukt.Type) -> Strukt // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B0yyF : $@convention(method) (Strukt) -> () { // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B4_varSivg // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV08dynamic_B4_varSivs // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktVyS2icig : $@convention(method) (Int, Strukt) -> Int // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktVyS2icis : $@convention(method) (Int, Int, @inout Strukt) -> () // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV22property_with_observerSivW // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable6StruktV22property_with_observerSivw struct Strukt { dynamic init(x: Int) { } dynamic func dynamic_replaceable() { } dynamic var dynamic_replaceable_var : Int { get { return 10 } set { } } dynamic subscript(x : Int) -> Int { get { return 10 } set { } } dynamic var property_with_observer : Int { didSet { } willSet { } } } // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC1xACSi_tcfc : $@convention(method) (Int, @owned Klass) -> @owned Klass // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B0yyF : $@convention(method) (@guaranteed Klass) -> () { // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassCyS2icig : $@convention(method) (Int, @guaranteed Klass) -> Int // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassCyS2icis : $@convention(method) (Int, Int, @guaranteed Klass) -> () // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC22property_with_observerSivW // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable5KlassC22property_with_observerSivw class Klass { dynamic init(x: Int) { } dynamic convenience init(c: Int) { self.init(x: c) } dynamic convenience init(a: Int, b: Int) { } dynamic func dynamic_replaceable() { } dynamic func dynamic_replaceable2() { } dynamic var dynamic_replaceable_var : Int { get { return 10 } set { } } dynamic subscript(x : Int) -> Int { get { return 10 } set { } } dynamic var property_with_observer : Int { didSet { } willSet { } } } class SubKlass : Klass { // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable8SubKlassC1xACSi_tcfc // CHECK: // dynamic_function_ref Klass.init(x:) // CHECK: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1xACSi_tcfc // CHECK: apply [[FUN]] dynamic override init(x: Int) { super.init(x: x) } } // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable6globalSivg : $@convention(thin) () -> Int { dynamic var global : Int { return 1 } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable11replacementyyF : $@convention(thin) () -> () { @_dynamicReplacement(for: dynamic_replaceable()) func replacement() { } extension Klass { // Calls to the replaced function inside the replacing function should be // statically dispatched. // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable5KlassC11replacementyyF : $@convention(method) (@guaranteed Klass) -> () { // CHECK: [[FN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC11replacementyyF // CHECK: apply [[FN]](%0) : $@convention(method) (@guaranteed Klass) -> () // CHECK: [[METHOD:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable2!1 // CHECK: = apply [[METHOD]](%0) : $@convention(method) (@guaranteed Klass) -> () // CHECK: return // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable5KlassC11replacementyyF : $@convention(method) (@guaranteed Klass) -> () { // NOPREVIOUS: [[FN:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable // NOPREVIOUS: apply [[FN]](%0) : $@convention(method) (@guaranteed Klass) -> () // NOPREVIOUS: [[METHOD:%.*]] = class_method %0 : $Klass, #Klass.dynamic_replaceable2!1 // NOPREVIOUS: = apply [[METHOD]](%0) : $@convention(method) (@guaranteed Klass) -> () // NOPREVIOUS: return @_dynamicReplacement(for: dynamic_replaceable()) func replacement() { dynamic_replaceable() dynamic_replaceable2() } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1cACSi_tcfC"] [ossa] @$s23dynamically_replaceable5KlassC2crACSi_tcfC : $@convention(method) (Int, @thick Klass.Type) -> @owned Klass { // CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC2crACSi_tcfC // CHECK: apply [[FUN]]({{.*}}, %1) // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1cACSi_tcfC"] [ossa] @$s23dynamically_replaceable5KlassC2crACSi_tcfC : $@convention(method) (Int, @thick Klass.Type) -> @owned Klass { // NOPREVIOUS: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC // NOPREVIOUS: apply [[FUN]]({{.*}}, %1) @_dynamicReplacement(for: init(c:)) convenience init(cr: Int) { self.init(c: cr + 1) } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1a1bACSi_SitcfC"] [ossa] @$s23dynamically_replaceable5KlassC2ar2brACSi_SitcfC // CHECK: // dynamic_function_ref Klass.__allocating_init(c:) // CHECK: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC // CHECK: apply [[FUN]]({{.*}}, %2) // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC1a1bACSi_SitcfC"] [ossa] @$s23dynamically_replaceable5KlassC2ar2brACSi_SitcfC // NOPREVIOUS: // dynamic_function_ref Klass.__allocating_init(c:) // NOPREVIOUS: [[FUN:%.*]] = dynamic_function_ref @$s23dynamically_replaceable5KlassC1cACSi_tcfC // NOPREVIOUS: apply [[FUN]]({{.*}}, %2) @_dynamicReplacement(for: init(a: b:)) convenience init(ar: Int, br: Int) { self.init(c: ar + br) } @_dynamicReplacement(for: init(x:)) init(xr: Int) { } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable5KlassC1rSivg : $@convention(method) (@guaranteed Klass) -> Int { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Klass): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1rSivg // CHECK: apply [[ORIG]]([[ARG]]) : $@convention(method) (@guaranteed Klass) -> Int // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable5KlassC1rSivg : $@convention(method) (@guaranteed Klass) -> Int { // NOPREVIOUS: bb0([[ARG:%.*]] : @guaranteed $Klass): // NOPREVIOUS: [[ORIG:%.*]] = class_method [[ARG]] : $Klass, #Klass.dynamic_replaceable_var!getter.1 // NOPREVIOUS: apply [[ORIG]]([[ARG]]) : $@convention(method) (@guaranteed Klass) -> Int // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable5KlassC1rSivs : $@convention(method) (Int, @guaranteed Klass) -> () { // CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1rSivs // CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) // NOPREVIOUS-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassC08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable5KlassC1rSivs : $@convention(method) (Int, @guaranteed Klass) -> () { // NOPREVIOUS: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass): // NOPREVIOUS: [[ORIG:%.*]] = class_method [[SELF]] : $Klass, #Klass.dynamic_replaceable_var!setter // NOPREVIOUS: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) @_dynamicReplacement(for: dynamic_replaceable_var) var r : Int { get { return dynamic_replaceable_var + 1 } set { dynamic_replaceable_var = newValue + 1 } } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassCyS2icig"] [ossa] @$s23dynamically_replaceable5KlassC1xS2i_tcig // CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1xS2i_tcig // CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) (Int, @guaranteed Klass) -> Int // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable5KlassCyS2icis"] [ossa] @$s23dynamically_replaceable5KlassC1xS2i_tcis // CHECK: bb0({{.*}} : $Int, {{.*}} : $Int, [[SELF:%.*]] : @guaranteed $Klass): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable5KlassC1xS2i_tcis // CHECK: apply [[ORIG]]({{.*}}, {{.*}}, [[SELF]]) : $@convention(method) (Int, Int, @guaranteed Klass) -> () @_dynamicReplacement(for: subscript(_:)) subscript(x y: Int) -> Int { get { return self[y] } set { self[y] = newValue } } } extension Strukt { // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable6StruktV11replacementyyF : $@convention(method) (Strukt) -> () { // CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV11replacementyyF // CHECK: apply [[FUN]](%0) : $@convention(method) (Strukt) -> () @_dynamicReplacement(for: dynamic_replaceable()) func replacement() { dynamic_replaceable() } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV1xACSi_tcfC"] [ossa] @$s23dynamically_replaceable6StruktV1yACSi_tcfC : $@convention(method) (Int, @thin Strukt.Type) -> Strukt { // CHECK: [[FUN:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1yACSi_tcfC // CHECK: apply [[FUN]]({{.*}}, %1) @_dynamicReplacement(for: init(x:)) init(y: Int) { self.init(x: y + 1) } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable6StruktV1rSivg // CHECK: bb0([[ARG:%.*]] : $Strukt): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1rSivg // CHECK: apply [[ORIG]]([[ARG]]) : $@convention(method) (Strukt) -> Int // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktV08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable6StruktV1rSivs // CHECK: bb0({{.*}} : $Int, [[ARG:%.*]] : $*Strukt): // CHECK: [[BA:%.*]] = begin_access [modify] [unknown] [[ARG]] : $*Strukt // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1rSivs // CHECK: apply [[ORIG]]({{.*}}, [[BA]]) : $@convention(method) (Int, @inout Strukt) -> () // CHECK: end_access [[BA]] : $*Strukt @_dynamicReplacement(for: dynamic_replaceable_var) var r : Int { get { return dynamic_replaceable_var + 1 } set { dynamic_replaceable_var = newValue + 1 } } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktVyS2icig"] [ossa] @$s23dynamically_replaceable6StruktV1xS2i_tcig // CHECK: bb0({{.*}} : $Int, [[SELF:%.*]] : $Strukt): // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1xS2i_tcig // CHECK: apply [[ORIG]]({{.*}}, [[SELF]]) : $@convention(method) (Int, Strukt) -> Int // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable6StruktVyS2icis"] [ossa] @$s23dynamically_replaceable6StruktV1xS2i_tcis // CHECK: bb0({{.*}} : $Int, {{.*}} : $Int, [[SELF:%.*]] : $*Strukt): // CHECK: [[BA:%.*]] = begin_access [modify] [unknown] [[SELF]] : $*Strukt // CHECK: [[ORIG:%.*]] = prev_dynamic_function_ref @$s23dynamically_replaceable6StruktV1xS2i_tcis // CHECK: apply [[ORIG]]({{.*}}, {{.*}}, [[BA]]) : $@convention(method) (Int, Int, @inout Strukt) -> () // CHECK: end_access [[BA]] : $*Strukt @_dynamicReplacement(for: subscript(_:)) subscript(x y: Int) -> Int { get { return self[y] } set { self[y] = newValue } } } struct GenericS<T> { dynamic init(x: Int) { } dynamic func dynamic_replaceable() { } dynamic var dynamic_replaceable_var : Int { get { return 10 } set { } } dynamic subscript(x : Int) -> Int { get { return 10 } set { } } // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable8GenericSV22property_with_observerSivW // CHECK-LABEL: sil private [dynamically_replacable] [ossa] @$s23dynamically_replaceable8GenericSV22property_with_observerSivw dynamic var property_with_observer : Int { didSet { } willSet { } } } extension GenericS { // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B0yyF"] [ossa] @$s23dynamically_replaceable8GenericSV11replacementyyF // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV11replacementyyF @_dynamicReplacement(for: dynamic_replaceable()) func replacement() { dynamic_replaceable() } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV1xACyxGSi_tcfC"] [ossa] @$s23dynamically_replaceable8GenericSV1yACyxGSi_tcfC // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1yACyxGSi_tcfC @_dynamicReplacement(for: init(x:)) init(y: Int) { self.init(x: y + 1) } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B4_varSivg"] [ossa] @$s23dynamically_replaceable8GenericSV1rSivg // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1rSivg // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV08dynamic_B4_varSivs"] [ossa] @$s23dynamically_replaceable8GenericSV1rSivs // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1rSivs @_dynamicReplacement(for: dynamic_replaceable_var) var r : Int { get { return dynamic_replaceable_var + 1 } set { dynamic_replaceable_var = newValue + 1 } } // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSVyS2icig"] [ossa] @$s23dynamically_replaceable8GenericSV1xS2i_tcig // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1xS2i_tcig // CHECK-LABEL: sil hidden [dynamic_replacement_for "$s23dynamically_replaceable8GenericSVyS2icis"] [ossa] @$s23dynamically_replaceable8GenericSV1xS2i_tcis // CHECK: prev_dynamic_function_ref @$s23dynamically_replaceable8GenericSV1xS2i_tcis @_dynamicReplacement(for: subscript(_:)) subscript(x y: Int) -> Int { get { return self[y] } set { self[y] = newValue } } // CHECK-LABEL: sil private [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV22property_with_observerSivW"] [ossa] @$s23dynamically_replaceable8GenericSV34replacement_property_with_observerSivW // CHECK-LABEL: sil private [dynamic_replacement_for "$s23dynamically_replaceable8GenericSV22property_with_observerSivw"] [ossa] @$s23dynamically_replaceable8GenericSV34replacement_property_with_observerSivw @_dynamicReplacement(for: property_with_observer) var replacement_property_with_observer : Int { didSet { } willSet { } } } dynamic var globalX = 0 // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable7globalXSivg : $@convention(thin) () -> Int // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable7globalXSivs : $@convention(thin) (Int) -> () // CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable7getsetXyS2iF // CHECK: dynamic_function_ref @$s23dynamically_replaceable7globalXSivs // CHECK: dynamic_function_ref @$s23dynamically_replaceable7globalXSivg func getsetX(_ x: Int) -> Int { globalX = x return globalX } // CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable18funcWithDefaultArgyySSFfA_ // CHECK-LABEL: sil hidden [dynamically_replacable] [ossa] @$s23dynamically_replaceable18funcWithDefaultArgyySSF dynamic func funcWithDefaultArg(_ arg : String = String("hello")) { print("hello") } // IMPLICIT-LABEL: sil hidden [thunk] [ossa] @barfoo @_cdecl("barfoo") func foobar() { } // IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable6$deferL_yyF var x = 10 defer { let y = x } // IMPLICIT-LABEL: sil [dynamically_replacable] [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF // IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF05localF0L_yyF // IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyF05localF0L_yyF0geF0L_yyF // IMPLICIT-LABEL: sil private [ossa] @$s23dynamically_replaceable16testWithLocalFunyyFyycfU_ public func testWithLocalFun() { func localFun() { func localLocalFun() { print("bar") } print("foo") localLocalFun() } localFun() let unamedClosure = { print("foo") } unamedClosure() } @propertyWrapper struct WrapperWithInitialValue<T> { var wrappedValue: T init(wrappedValue initialValue: T) { self.wrappedValue = initialValue } } // CHECK-LABEL: sil hidden [ossa] @$s23dynamically_replaceable10SomeStructV1tSbvpfP public struct SomeStruct { @WrapperWithInitialValue var t = false }
apache-2.0
1c6c390cc428d48c7046e4d620076421
45.019048
228
0.703435
3.646792
false
false
false
false
wircho/D3Workshop
HelloWorld/HelloWorld/MontrealViewController.swift
1
1471
// // MontrealViewController.swift // HelloWorld // // Created by Adolfo Rodriguez on 2015-08-01. // Copyright (c) 2015 Relevant. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import BrightFutures class MontrealViewController: UIViewController { @IBOutlet weak var contentLabel: UILabel! @IBAction func touchRefresh(sender: AnyObject) { let url = "http://api.whatthetrend.com/api/v2/trends.json?woeid=3534" request(.GET, url).responseJSON { (_, _, object, _) -> Void in Queue.main.async { if let obj:AnyObject = object { let json = JSON(obj) self.contentLabel.text = "\n".join(json["trends"].arrayValue.map{$0["name"].stringValue}) }else { self.contentLabel.text = "ERROR" } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.touchRefresh(self) } }
mit
b9427680b55364c2101d1a6813b580ab
23.114754
109
0.532291
5.072414
false
false
false
false
178inaba/SwiftCollatz
SwiftCollatz/ViewController.swift
1
1621
// // ViewController.swift // SwiftCollatz // // Created by 178inaba on 2015/10/18. // Copyright © 2015年 178inaba. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var targetNumField: UITextField! @IBOutlet weak var resultView: UITableView! // collatz results var results: [UInt64] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. targetNumField.keyboardType = .NumberPad resultView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tapCalc(sender: UIButton) { targetNumField.resignFirstResponder() results = [] calcCollatz(UInt64(targetNumField.text!)!) resultView.reloadData() } func calcCollatz(num: UInt64) { results.append(num) print(num) if num % 2 == 1 && num > 1 { calcCollatz(3 * num + 1) } else if num % 2 == 0 { calcCollatz(num / 2) } } // cell rows func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.count } // change cell value func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel!.text = String(results[indexPath.row]) return cell } }
mit
598775d952be80900a2da835dcc0d8f6
24.68254
109
0.634734
4.689855
false
false
false
false
aerogear/aerogear-ios-http
AeroGearHttp/MultiPartData.swift
2
2141
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual contributors * * 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 /** Represents a multipart object containing a file plus metadata to be processed during upload. */ open class MultiPartData { /// The 'name' to be used on the request. open var name: String /// The 'filename' to be used on the request. open var filename: String /// The 'MIME type' to be used on the request. open var mimeType: String /// The actual data to be sent. open var data: Data /** Initialize a multipart object using an NSURL and a corresponding MIME type. :param: url the url of the local file. :param: mimeType the MIME type. :returns: the newly created multipart data. */ public init(url: URL, mimeType: String) { self.name = url.lastPathComponent self.filename = url.lastPathComponent self.mimeType = mimeType; self.data = try! Data(contentsOf: url) } /** Initialize a multipart object using an NSData plus metadata. :param: data the actual data to be uploaded. :param: name the 'name' to be used on the request. :param: filename the 'filename' to be used on the request. :param: mimeType the 'MIME type' to be used on the request. :returns: the newly created multipart data. */ public init(data: Data, name: String, filename: String, mimeType: String) { self.data = data; self.name = name; self.filename = filename; self.mimeType = mimeType; } }
apache-2.0
3d695bba85391401ce83206760549273
31.439394
92
0.674451
4.299197
false
false
false
false
noppoMan/Hexaville
Sources/HexavilleCore/Process/Proc.swift
1
1269
// // Proc.swift // Hexaville // // Created by Yuki Takei on 2017/05/16. // // import Foundation extension Process { public static func exec(_ cmd: String, _ args: [String], environment: [String: String] = ProcessInfo.processInfo.environment) -> Proc { var args = args args.insert(cmd, at: 0) return Proc.init("/usr/bin/env", args, environment: environment) } } public struct Proc { public let terminationStatus: Int32 public let stdout: Any? public let stderr: Any? public let pid: Int32? public init(_ exetutablePath: String, _ arguments: [String] = [], environment: [String: String] = ProcessInfo.processInfo.environment) { let process = Process() process.launchPath = exetutablePath process.arguments = arguments process.environment = environment process.launch() // handle SIGINT SignalEventEmitter.shared.once { sig in assert(sig == .int) process.interrupt() } process.waitUntilExit() terminationStatus = process.terminationStatus stdout = process.standardOutput stderr = process.standardError pid = process.processIdentifier } }
mit
b124817928ecffe7feef31fb17798a7a
25.4375
140
0.617021
4.614545
false
false
false
false
AceWangLei/BYWeiBo
BYWeiBo/BYUserAccountViewModel.swift
1
3995
// // BYUserAccountViewModel.swift // BYWeiBo // // Created by wanglei on 16/1/25. // Copyright © 2016年 lit. All rights reserved. // import UIKit class BYUserAccountViewModel: NSObject { /** BYUserAccount 视图模型引用的Model */ var account: BYUserAccount? /** string accessToken */ var accessToken: String? { return account?.access_token } /** bool 以后,外界只需要调用这个属性就知道是否登陆 */ var isLogon: Bool { // account 不能为 nil && accessToken 不能过期 if account != nil && isExpiresIn == false { // 代表当前用户登陆 return true } return false } /** bool 代表当前账户是否过期, 为 true 代表过期 */ var isExpiresIn: Bool { // 当前时间比过期时间小,也就是还没有到过期时间,也就是没有过期 if NSDate().compare(account!.expiresDate!) == .OrderedAscending { return false } return true } /** BYUserAccountViewModel 全局访问对象 */ static let sharedViewModel:BYUserAccountViewModel = { let viewModel = BYUserAccountViewModel() // 会在第一次使用当前类的时候去归档文件里面读取当前用户的信息 viewModel.account = viewModel.userAccount() return viewModel }() /** string 归档&解档的路径 */ private var archivePath: String { return (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive") } /** 加载 accessToken - parameter code: code - parameter finished: 是否加载成功 */ func loadAccessToken(code: String, finished:(isSuccess: Bool)->()) { BYNetworkTools.sharedTools.loadAccessToken(code) { (response, error) -> () in if error != nil { finished(isSuccess: false) return } // 判断返回数据是否是字典 guard let dict = response as? [String: AnyObject] else { finished(isSuccess: false) return } // 字典转模型 let account = BYUserAccount(dict: dict) // 加载个人信息 self.loadUserInfo(account, finished: finished) } } /** 加载个人信息 - parameter account: BYUserAccount - parameter finished: 是否加载成功 */ private func loadUserInfo(account: BYUserAccount, finished: (isSuccess: Bool)->()) { BYNetworkTools.sharedTools.loadUserInfo(account.access_token!, uid: account.uid!) { (response, error) -> () in if error != nil { finished(isSuccess: false) return } guard let dict = response as? [String: AnyObject] else { finished(isSuccess: false) return } account.avatar_large = dict["avatar_large"] as? String account.screen_name = dict["screen_name"] as? String // 归档保存 self.saveUserAccount(account) // 给当前类的 account 赋值 self.account = account // 回调登陆成功 finished(isSuccess: true) } } } extension BYUserAccountViewModel { private func saveUserAccount(account: BYUserAccount) { // 1. 获取归档路径 print(archivePath) // 2. NSKeyedArchive NSKeyedArchiver.archiveRootObject(account, toFile: archivePath) } // 解档数据 func userAccount() -> BYUserAccount? { return NSKeyedUnarchiver.unarchiveObjectWithFile(archivePath) as? BYUserAccount } }
apache-2.0
898ab1a6d79020380280c7ba362b7355
27.736
206
0.565145
5.009763
false
false
false
false
AngryLi/note
iOS/Demos/Assignments_swift/assignment-1-calculator/Calculator_assignment/Calculator/StringExtension.swift
3
2148
// // StringExtension.swift // Calculator // // Created by 李亚洲 on 15/4/29. // Copyright (c) 2015年 liyazhou. All rights reserved. // import Foundation extension String{ //分割字符 func split(s:String)->[String]{ if s.isEmpty{ var x=[String]() for y in self{ x.append(String(y)) } return x } return self.componentsSeparatedByString(s) } //去掉左右空格 func trim()->String{ return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } //是否包含字符串 func has(s:String)->Bool{ if (self.rangeOfString(s) != nil) { return true }else{ return false } } //是否包含前缀 func hasBegin(s:String)->Bool{ if self.hasPrefix(s) { return true }else{ return false } } //是否包含后缀 func hasEnd(s:String)->Bool{ if self.hasSuffix(s) { return true }else{ return false } } //统计长度 func length()->Int{ return count(self) } //统计长度(别名) func size()->Int{ return count(self) } //截取字符串 func substringFromIndex(#startIndex: Int) -> String { return self.substringFromIndex(advance(self.startIndex, startIndex)) } func substringToIndex(#endIndex: Int) -> String { return self.substringToIndex(advance(self.startIndex, endIndex)) } func substringWithRange(#startIndex:Int, endIndex:Int) -> String { return self.substringWithRange(Range(start: advance(self.startIndex, startIndex), end: advance(self.startIndex, endIndex))) } //重复字符串 func repeat(#times: Int) -> String{ var result = "" for i in 0..<times { result += self } return result } //反转 func reverse()-> String{ var s=self.split("").reverse() var x="" for y in s{ x+=y } return x } }
mit
6cb96c4caeec98d5ac70c665bd28b988
22.170455
131
0.533857
4.254697
false
false
false
false
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/Mixpanel.swift
2
6803
// // Mixpanel.swift // Mixpanel // // Created by Yarden Eitan on 6/1/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation #if !os(OSX) import UIKit #endif // os(OSX) /// The primary class for integrating Mixpanel with your app. open class Mixpanel { #if !os(OSX) /** Initializes an instance of the API with the given project token. Returns a new Mixpanel instance API object. This allows you to create more than one instance of the API object, which is convenient if you'd like to send data to more than one Mixpanel project from a single app. - parameter token: your project token - parameter launchOptions: Optional. App delegate launchOptions - parameter flushInterval: Optional. Interval to run background flushing - parameter instanceName: Optional. The name you want to call this instance - important: If you have more than one Mixpanel instance, it is beneficial to initialize the instances with an instanceName. Then they can be reached by calling getInstance with name. - returns: returns a mixpanel instance if needed to keep throughout the project. You can always get the instance by calling getInstance(name) */ @discardableResult open class func initialize(token apiToken: String, launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil, flushInterval: Double = 60, instanceName: String = UUID().uuidString) -> MixpanelInstance { return MixpanelManager.sharedInstance.initialize(token: apiToken, launchOptions: launchOptions, flushInterval: flushInterval, instanceName: instanceName) } #else /** Initializes an instance of the API with the given project token (MAC OS ONLY). Returns a new Mixpanel instance API object. This allows you to create more than one instance of the API object, which is convenient if you'd like to send data to more than one Mixpanel project from a single app. - parameter token: your project token - parameter flushInterval: Optional. Interval to run background flushing - parameter instanceName: Optional. The name you want to call this instance - important: If you have more than one Mixpanel instance, it is beneficial to initialize the instances with an instanceName. Then they can be reached by calling getInstance with name. - returns: returns a mixpanel instance if needed to keep throughout the project. You can always get the instance by calling getInstance(name) */ @discardableResult open class func initialize(token apiToken: String, flushInterval: Double = 60, instanceName: String = UUID().uuidString) -> MixpanelInstance { return MixpanelManager.sharedInstance.initialize(token: apiToken, flushInterval: flushInterval, instanceName: instanceName) } #endif // os(OSX) /** Gets the mixpanel instance with the given name - parameter name: the instance name - returns: returns the mixpanel instance */ open class func getInstance(name: String) -> MixpanelInstance? { return MixpanelManager.sharedInstance.getInstance(name: name) } /** Returns the main instance that was initialized. If not specified explicitly, the main instance is always the last instance added - returns: returns the main Mixpanel instance */ open class func mainInstance() -> MixpanelInstance { let instance = MixpanelManager.sharedInstance.getMainInstance() if instance == nil { fatalError("You have to call initialize(token:) before calling the main instance, " + "or define a new main instance if removing the main one") } return instance! } /** Sets the main instance based on the instance name - parameter name: the instance name */ open class func setMainInstance(name: String) { MixpanelManager.sharedInstance.setMainInstance(name: name) } /** Removes an unneeded Mixpanel instance based on its name - parameter name: the instance name */ open class func removeInstance(name: String) { MixpanelManager.sharedInstance.removeInstance(name: name) } } class MixpanelManager { static let sharedInstance = MixpanelManager() private var instances: [String: MixpanelInstance] private var mainInstance: MixpanelInstance? init() { instances = [String: MixpanelInstance]() Logger.addLogging(PrintLogging()) } #if !os(OSX) func initialize(token apiToken: String, launchOptions: [UIApplicationLaunchOptionsKey : Any]?, flushInterval: Double, instanceName: String) -> MixpanelInstance { let instance = MixpanelInstance(apiToken: apiToken, launchOptions: launchOptions, flushInterval: flushInterval, name: instanceName) mainInstance = instance instances[instanceName] = instance return instance } #else func initialize(token apiToken: String, flushInterval: Double, instanceName: String) -> MixpanelInstance { let instance = MixpanelInstance(apiToken: apiToken, flushInterval: flushInterval, name: instanceName) mainInstance = instance instances[instanceName] = instance return instance } #endif // os(OSX) func getInstance(name instanceName: String) -> MixpanelInstance? { guard let instance = instances[instanceName] else { Logger.warn(message: "no such instance: \(instanceName)") return nil } return instance } func getMainInstance() -> MixpanelInstance? { return mainInstance } func setMainInstance(name instanceName: String) { guard let instance = instances[instanceName] else { return } mainInstance = instance } func removeInstance(name instanceName: String) { if instances[instanceName] === mainInstance { mainInstance = nil } instances[instanceName] = nil } }
mit
dd418ae7cfb5dc5aa27c2b3414966658
35.180851
99
0.617171
5.779099
false
false
false
false
crazypoo/PTools
Pods/CollectionViewPagingLayout/Lib/SwiftUI/PagingCollectionViewControllerBuilder.swift
1
2298
// // PagingCollectionViewControllerBuilder.swift // CollectionViewPagingLayout // // Created by Amir on 28/03/2021. // Copyright © 2021 Amir Khorsandi. All rights reserved. // import SwiftUI public class PagingCollectionViewControllerBuilder<ValueType: Identifiable, PageContent: View> { public typealias ViewController = PagingCollectionViewController<ValueType, PageContent> // MARK: Properties let data: [ValueType] let pageViewBuilder: (ValueType, CGFloat) -> PageContent let selection: Binding<ValueType.ID?>? var modifierData: PagingCollectionViewModifierData = .init() weak var viewController: ViewController? // MARK: Lifecycle public init( data: [ValueType], pageViewBuilder: @escaping (ValueType, CGFloat) -> PageContent, selection: Binding<ValueType.ID?>? ) { self.data = data self.pageViewBuilder = pageViewBuilder self.selection = selection } public init( data: [ValueType], pageViewBuilder: @escaping (ValueType) -> PageContent, selection: Binding<ValueType.ID?>? ) { self.data = data self.pageViewBuilder = { value, _ in pageViewBuilder(value) } self.selection = selection } // MARK: Public functions func make() -> ViewController { let viewController = ViewController() viewController.pageViewBuilder = pageViewBuilder viewController.modifierData = modifierData viewController.update(list: data, currentIndex: nil) setupOnCurrentPageChanged(viewController) return viewController } func update(viewController: ViewController) { let selectedIndex = data.enumerated().first { $0.element.id == selection?.wrappedValue }?.offset viewController.modifierData = modifierData viewController.update(list: data, currentIndex: selectedIndex) setupOnCurrentPageChanged(viewController) } // MARK: Private functions private func setupOnCurrentPageChanged(_ viewController: ViewController) { viewController.onCurrentPageChanged = { [data, selection] in guard $0 >= 0 && $0 < data.count else { return } selection?.wrappedValue = data[$0].id } } }
mit
b8ff4fe57bfa9f5ce7a4c5468bbc933e
28.448718
96
0.670004
5.115813
false
false
false
false
IngmarStein/swift
stdlib/public/SDK/CoreGraphics/Private.swift
4
11354
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Redeclarations of all SwiftPrivate symbols with appropriate markup, // so that tools can help with migration // @available(*, unavailable, renamed:"DispatchQueue.init(label:attributes:target:)") @available(*, unavailable, message:"Use == instead") public func CGAffineTransformEqualToTransform(_ t1: CGAffineTransform, _ t2: CGAffineTransform) -> Bool { fatalError() } @available(*, unavailable, message:"Use class var white/black/clear instead") public func CGColorGetConstantColor(_ colorName: CFString?) -> CGColor? { fatalError() } @available(*, unavailable, message:"Use == instead") public func CGColorEqualToColor(_ color1: CGColor?, _ color2: CGColor?) -> Bool { fatalError() } @available(*, unavailable, renamed:"getter:CGColor.components(self:)") public func CGColorGetComponents(_ color: CGColor?) -> UnsafePointer<CGFloat> { fatalError() } @available(*, unavailable, message:"Use colorTable.count instead") public func CGColorSpaceGetColorTableCount(_ space: CGColorSpace?) -> Int { fatalError() } @available(*, unavailable, renamed:"CGColorSpace.colorTable(self:_:)") public func CGColorSpaceGetColorTable(_ space: CGColorSpace?, _ table: UnsafeMutablePointer<UInt8>) { fatalError() } @available(*, unavailable, message:"Use setLineDash(self:phase:lengths:)") public func CGContextSetLineDash(_ c: CGContext?, _ phase: CGFloat, _ lengths: UnsafePointer<CGFloat>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use move(to:) instead") public func CGContextMoveToPoint(_ c: CGContext?, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addLine(to:) instead") public func CGContextAddLineToPoint(_ c: CGContext?, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addCurve(to:control1:control2:) instead") public func CGContextAddCurveToPoint(_ c: CGContext?, _ cp1x: CGFloat, _ cp1y: CGFloat, _ cp2x: CGFloat, _ cp2y: CGFloat, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addQuadCurve(to:control:)") public func CGContextAddQuadCurveToPoint(_ c: CGContext?, _ cpx: CGFloat, _ cpy: CGFloat, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addRects(_:)") public func CGContextAddRects(_ c: CGContext?, _ rects: UnsafePointer<CGRect>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use addLines(between:)") public func CGContextAddLines(_ c: CGContext?, _ points: UnsafePointer<CGPoint>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use addArc(center:radius:startAngle:endAngle:clockwise:)") public func CGContextAddArc(_ c: CGContext?, _ x: CGFloat, _ y: CGFloat, _ radius: CGFloat, _ startAngle: CGFloat, _ endAngle: CGFloat, _ clockwise: Int32) { fatalError() } @available(*, unavailable, message:"Use addArc(self:x1:y1:x2:y2:radius:)") public func CGContextAddArcToPoint(_ c: CGContext?, _ x1: CGFloat, _ y1: CGFloat, _ x2: CGFloat, _ y2: CGFloat, _ radius: CGFloat) { fatalError() } @available(*, unavailable, message:"Use fill(self:_:count:)") public func CGContextFillRects(_ c: CGContext?, _ rects: UnsafePointer<CGRect>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use strokeLineSegments(self:between:count:)") public func CGContextStrokeLineSegments(_ c: CGContext?, _ points: UnsafePointer<CGPoint>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use clip(to:)") public func CGContextClipToRects(_ c: CGContext?, _ rects: UnsafePointer<CGRect>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use draw(_:in:)") public func CGContextDrawImage(_ c: CGContext?, _ rect: CGRect, _ image: CGImage?) { fatalError() } @available(*, unavailable, message:"Use draw(_:in:byTiling:)") public func CGContextDrawTiledImage(_ c: CGContext?, _ rect: CGRect, _ image: CGImage?) { fatalError() } @available(*, unavailable, renamed:"getter:CGContext.textPosition(self:)") public func CGContextGetTextPosition(_ c: CGContext?) -> CGPoint { fatalError() } @available(*, unavailable, message:"Use var textPosition") public func CGContextSetTextPosition(_ c: CGContext?, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use showGlyphs(_:at:)") public func CGContextShowGlyphsAtPositions(_ c: CGContext?, _ glyphs: UnsafePointer<CGGlyph>, _ Lpositions: UnsafePointer<CGPoint>, _ count: Int) { fatalError() } @available(*, unavailable, renamed:"CGContext.fillPath(self:)") public func CGContextFillPath(_ c: CGContext?) { fatalError() } @available(*, unavailable, message:"Use fillPath(using:)") public func CGContextEOFillPath(_ c: CGContext?) { fatalError() } @available(*, unavailable, renamed:"CGContext.clip(self:)") public func CGContextClip(_ c: CGContext?) { fatalError() } @available(*, unavailable, message:"Use clip(using:)") public func CGContextEOClip(_ c: CGContext?) { fatalError() } @available(*, unavailable, renamed:"CGGetLastMouseDelta") // different type public func CGGetLastMouseDelta(_ deltaX: UnsafeMutablePointer<Int32>?, _ deltaY: UnsafeMutablePointer<Int32>?) { fatalError() } @available(*, unavailable, message:"Use divided(atDistance:from:)") public func CGRectDivide(_ rect: CGRect, _ slice: UnsafeMutablePointer<CGRect>, _ remainder: UnsafeMutablePointer<CGRect>, _ amount: CGFloat, _ edge: CGRectEdge) { fatalError() } @available(*, unavailable, message:"Use CGPoint.init(dictionaryRepresentation:)") public func CGPointMakeWithDictionaryRepresentation(_ dict: CFDictionary?, _ point: UnsafeMutablePointer<CGPoint>) -> Bool { fatalError() } @available(*, unavailable, message:"Use CGSize.init(dictionaryRepresentation:)") public func CGSizeMakeWithDictionaryRepresentation(_ dict: CFDictionary?, _ size: UnsafeMutablePointer<CGSize>) -> Bool { fatalError() } @available(*, unavailable, message:"Use CGRect.init(dictionaryRepresentation:)") public func CGRectMakeWithDictionaryRepresentation(_ dict: CFDictionary?, _ rect: UnsafeMutablePointer<CGRect>) -> Bool { fatalError() } @available(*, unavailable, renamed:"CGImage.copy(self:maskingColorComponents:)") public func CGImageCreateWithMaskingColors(_ image: CGImage?, _ components: UnsafePointer<CGFloat>) -> CGImage? { fatalError() } @available(*, unavailable, message:"Use draw(_:in:)") public func CGContextDrawLayerInRect(_ context: CGContext?, _ rect: CGRect, _ layer: CGLayer?) { fatalError() } @available(*, unavailable, message:"Use draw(_:at:)") public func CGContextDrawLayerAtPoint(_ context: CGContext?, _ point: CGPoint, _ layer: CGLayer?) { fatalError() } @available(*, unavailable, message:"Use copy(byDashingWithPhase:lengths:transform:)") public func CGPathCreateCopyByDashingPath(_ path: CGPath?, _ transform: UnsafePointer<CGAffineTransform>, _ phase: CGFloat, _ lengths: UnsafePointer<CGFloat>, _ count: Int) -> CGPath? { fatalError() } @available(*, unavailable, message:"Use copy(byStroking:lineWidth:lineCap:lineJoin:miterLimit:transform:)") public func CGPathCreateCopyByStrokingPath(_ path: CGPath?, _ transform: UnsafePointer<CGAffineTransform>, _ lineWidth: CGFloat, _ lineCap: CGLineCap, _ lineJoin: CGLineJoin, _ miterLimit: CGFloat) -> CGPath? { fatalError() } @available(*, unavailable, message:"Use == instead") public func CGPathEqualToPath(_ path1: CGPath?, _ path2: CGPath?) -> Bool { fatalError() } @available(*, unavailable, message:"Use move(to:transform:)") public func CGPathMoveToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addLine(to:transform:)") public func CGPathAddLineToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addCurve(to:control1:control2:transform:)") public func CGPathAddCurveToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ cp1x: CGFloat, _ cp1y: CGFloat, _ cp2x: CGFloat, _ cp2y: CGFloat, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addQuadCurve(to:control:transform:)") public func CGPathAddQuadCurveToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ cpx: CGFloat, _ cpy: CGFloat, _ x: CGFloat, _ y: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addRect(_:transform:)") public func CGPathAddRect(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ rect: CGRect) { fatalError() } @available(*, unavailable, message:"Use addRects(_:transform:)") public func CGPathAddRects(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ rects: UnsafePointer<CGRect>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use addLines(between:transform:)") public func CGPathAddLines(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ points: UnsafePointer<CGPoint>, _ count: Int) { fatalError() } @available(*, unavailable, message:"Use addEllipse(rect:transform:)") public func CGPathAddEllipseInRect(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ rect: CGRect) { fatalError() } @available(*, unavailable, message:"Use addRelativeArc(center:radius:startAngle:delta:transform:)") public func CGPathAddRelativeArc(_ path: CGMutablePath?, _ matrix: UnsafePointer<CGAffineTransform>, _ x: CGFloat, _ y: CGFloat, _ radius: CGFloat, _ startAngle: CGFloat, _ delta: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addArc(center:radius:startAngle:endAngle:clockwise:transform:)") public func CGPathAddArc(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ x: CGFloat, _ y: CGFloat, _ radius: CGFloat, _ startAngle: CGFloat, _ endAngle: CGFloat, _ clockwise: Bool) { fatalError() } @available(*, unavailable, message:"Use addArc(tangent1End:tangent2End:radius:transform:)") public func CGPathAddArcToPoint(_ path: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ x1: CGFloat, _ y1: CGFloat, _ x2: CGFloat, _ y2: CGFloat, _ radius: CGFloat) { fatalError() } @available(*, unavailable, message:"Use addPath(_:transform:)") public func CGPathAddPath(_ path1: CGMutablePath?, _ m: UnsafePointer<CGAffineTransform>, _ path2: CGPath?) { fatalError() } @available(*, unavailable, message:"Use CGColor.white") // retyped public var kCGColorWhite: CFString { fatalError() } @available(*, unavailable, message:"Use CGColor.black") // retyped public var kCGColorBlack: CFString { fatalError() } @available(*, unavailable, message:"Use CGColor.clear") // retyped public var kCGColorClear: CFString { fatalError() } // TODO: also add migration support from previous Swift3 betas?
apache-2.0
303cb249baa138736bc7255fcefd39b8
48.580786
209
0.717897
4.370285
false
false
false
false
iossocket/DBDemo
DBDemo/DetailViewController.swift
1
1125
// // DetailViewController.swift // DBDemo // // Created by Jianing Zheng on 12/27/16. // Copyright © 2016 ThoughtWorks. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! let bookDataService: BookDataService = RealmBookDataService(transform: RealmBookToBookTransform()) var bookDetailViewModel: BookDetailViewModel! override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { title = "Book Detail" nameLabel.text = bookDetailViewModel.name() authorLabel.text = bookDetailViewModel.author() statusLabel.text = bookDetailViewModel.status() } @IBAction func changeStatus(_ sender: Any) { bookDataService.changeBookStatus(bookDetailViewModel.bookID()) { [weak self] book in if let strongSelf = self { strongSelf.statusLabel.text = book.displayedStatus } } } }
mit
98c5b89323623b9da3a298abaf3ab9a3
25.761905
102
0.651246
4.865801
false
false
false
false
krevis/MIDIApps
Frameworks/SnoizeMIDI/VirtualInputStream.swift
1
3911
/* Copyright (c) 2001-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Foundation public class VirtualInputStream: InputStream { public override init(midiContext: MIDIContext) { virtualEndpointName = midiContext.name uniqueID = 0 // Let CoreMIDI assign a unique ID to the virtual endpoint when it is created singleSource = SingleInputStreamSource(name: virtualEndpointName) super.init(midiContext: midiContext) } deinit { isActive = false } public var uniqueID: MIDIUniqueID { didSet { if uniqueID != oldValue, let endpoint = endpoint { endpoint.uniqueID = uniqueID // that may or may not have worked uniqueID = endpoint.uniqueID } } } public var virtualEndpointName: String { didSet { if virtualEndpointName != oldValue { endpoint?.name = virtualEndpointName } } } public func setInputSourceName(_ name: String) { singleSource.name = name } public private(set) var endpoint: Destination? // MARK: InputStream subclass public override var parsers: [MessageParser] { if let parser = parser { return [parser] } else { return [] } } public override func parser(sourceConnectionRefCon refCon: UnsafeMutableRawPointer?) -> MessageParser? { // refCon is ignored, since it only applies to connections created with MIDIPortConnectSource() parser } public override func streamSource(parser: MessageParser) -> InputStreamSource? { singleSource.asInputStreamSource } public override var inputSources: [InputStreamSource] { [singleSource.asInputStreamSource] } public override var selectedInputSources: Set<InputStreamSource> { get { isActive ? [singleSource.asInputStreamSource] : [] } set { isActive = newValue.contains(singleSource.asInputStreamSource) } } // MARK: InputStream overrides public override var persistentSettings: Any? { isActive ? ["uniqueID": uniqueID] : nil } public override func takePersistentSettings(_ settings: Any) -> [String] { if let settings = settings as? [String: Any], let settingsUniqueID = settings["uniqueID"] as? MIDIUniqueID { uniqueID = settingsUniqueID isActive = true } else { isActive = false } return [] } // MARK: Private private let singleSource: SingleInputStreamSource private var parser: MessageParser? private var isActive: Bool { get { endpoint != nil } set { if newValue && endpoint == nil { createEndpoint() } else if !newValue && endpoint != nil { disposeEndpoint() } } } private func createEndpoint() { endpoint = midiContext.createVirtualDestination(name: virtualEndpointName, uniqueID: uniqueID, midiReadBlock: midiReadBlock) if let endpoint = endpoint { if parser == nil { parser = createParser(originatingEndpoint: endpoint) } else { parser!.originatingEndpoint = endpoint } // We requested a specific uniqueID, but we might not have gotten it. // Update our copy of it from the actual value in CoreMIDI. uniqueID = endpoint.uniqueID } } private func disposeEndpoint() { endpoint?.remove() endpoint = nil parser?.originatingEndpoint = nil } }
bsd-3-clause
0e3cc0f70e89b669fd64dc8f28cd8ac1
26.34965
132
0.595756
5.401934
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Models/CoreData/Game Rows/GameMaps.swift
1
7403
// // GameMaps.swift // MEGameTracker // // Created by Emily Ivie on 9/22/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import Foundation import CoreData extension Map: GameRowStorable { /// (CodableCoreDataStorable Protocol) /// Type of the core data entity. public typealias EntityType = GameMaps /// (GameRowStorable Protocol) /// Corresponding data entity for this game entity. public typealias DataRowType = DataMap /// (CodableCoreDataStorable Protocol) /// Sets core data values to match struct values (specific). public func setAdditionalColumnsOnSave( coreItem: EntityType ) { // only save searchable columns setDateModifiableColumnsOnSave(coreItem: coreItem) //TODO coreItem.id = id coreItem.gameSequenceUuid = gameSequenceUuid?.uuidString coreItem.isExplored = Map.gameValuesForIsExplored(isExploredPerGameVersion: isExploredPerGameVersion) coreItem.isSavedToCloud = isSavedToCloud ? 1 : 0 coreItem.dataParent = generalData.entity(context: coreItem.managedObjectContext) } /// (GameRowStorable X Eventsable Protocol) /// Create a new game entity value for the game uuid given using the data value given. public static func create( using data: DataRowType, with manager: CodableCoreDataManageable? ) -> Map { var item = Map(id: data.id, generalData: data) item.events = item.getEvents(gameSequenceUuid: item.gameSequenceUuid, with: manager) return item } /// (GameRowStorable Protocol) public mutating func migrateId(id newId: String) { id = newId generalData.migrateId(id: newId) } } extension Map { /// The closure type for editing fetch requests. /// (Duplicate these per file or use Whole Module Optimization, which is slow in dev) public typealias AlterFetchRequest<T: NSManagedObject> = ((NSFetchRequest<T>) -> Void) /// (OVERRIDE) /// Return all matching game values made from the data values. public static func getAllFromData( gameSequenceUuid: UUID?, with manager: CodableCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<DataRowType.EntityType> ) -> [Map] { let manager = manager ?? defaultManager let dataItems = DataRowType.getAll(gameVersion: nil, with: manager, alterFetchRequest: alterFetchRequest) let some: [Map] = dataItems.map { (dataItem: DataRowType) -> Map? in Map.getOrCreate(using: dataItem, gameSequenceUuid: gameSequenceUuid, with: manager) }.filter({ $0 != nil }).map({ $0! }) return some } // MARK: Methods customized with GameVersion /// Get a map by id and set it to specified game version. public static func get( id: String, gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> Map? { return getFromData(gameVersion: gameVersion, with: manager) { fetchRequest in fetchRequest.predicate = NSPredicate( format: "(%K == %@)", "id", id ) } } /// Get a map and set it to specified game version. public static func getFromData( gameVersion: GameVersion?, with manager: CodableCoreDataManageable? = nil, alterFetchRequest: @escaping AlterFetchRequest<DataRowType.EntityType> ) -> Map? { return getAllFromData(gameVersion: gameVersion, with: manager, alterFetchRequest: alterFetchRequest).first } /// Get a set of maps with the specified ids and set them to specified game version. public static func getAll( ids: [String], gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> [Map] { return getAllFromData(gameVersion: gameVersion, with: manager) { fetchRequest in fetchRequest.predicate = NSPredicate( format: "(%K in %@)", "id", ids ) } } /// Get a set of maps and set them to specified game version. public static func getAllFromData( gameVersion: GameVersion?, with manager: CodableCoreDataManageable? = nil, alterFetchRequest: @escaping AlterFetchRequest<DataRowType.EntityType> ) -> [Map] { let manager = manager ?? defaultManager let dataItems = DataRowType.getAll(gameVersion: gameVersion, with: manager, alterFetchRequest: alterFetchRequest) let some: [Map] = dataItems.map { (dataItem: DataRowType) -> Map? in Map.getOrCreate(using: dataItem, with: manager) }.filter({ $0 != nil }).map({ $0! }) return some } // MARK: Additional Convenience Methods /// Get all maps from the specified game version. public static func getAll( gameVersion: GameVersion, with manager: CodableCoreDataManageable? = nil ) -> [Map] { return getAllFromData(gameVersion: gameVersion, with: manager) { _ in } } /// Get all child maps of the specified map. public static func getAll( inMapId mapId: String, gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> [Map] { return getAllFromData(gameVersion: gameVersion, with: manager) { fetchRequest in fetchRequest.predicate = NSPredicate( format: "(%K == %@)", #keyPath(DataMaps.inMapId), mapId ) } } /// Get all main maps. public static func getAllMain( gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> [Map] { return getAllFromData(gameVersion: gameVersion, with: manager) { fetchRequest in fetchRequest.predicate = NSPredicate( format: "(%K == true)", #keyPath(DataMaps.isMain) ) } } /// Get all recently viewed maps. public static func getAllRecent( gameVersion: GameVersion? = nil, with manager: CodableCoreDataManageable? = nil ) -> [Map] { var maps: [Map] = [] App.current.recentlyViewedMaps.contents.forEach { if var map = Map.get(id: $0.id, gameVersion: gameVersion, with: manager) { map.modifiedDate = $0.date // hijack for date - won't be saved anyway maps.append(map) } } return maps } /// Copy all the matching game values to a new GameSequence UUID. public static func copyAll( in gameVersions: [GameVersion], sourceUuid: UUID, destinationUuid: UUID, with manager: CodableCoreDataManageable? ) -> Bool { return copyAll(with: manager, alterFetchRequest: { fetchRequest in fetchRequest.predicate = NSPredicate( format: "gameSequenceUuid == %@", sourceUuid.uuidString) }, setChangedValues: { coreItem in coreItem.setValue(destinationUuid.uuidString, forKey: "gameSequenceUuid") var isExploredPerGameVersion = Map.gameValuesFromIsExplored(gameValues: coreItem.isExplored ?? "") for (gameVersion, _) in isExploredPerGameVersion { if !gameVersions.contains(gameVersion) { isExploredPerGameVersion[gameVersion] = false } } coreItem.isExplored = Map.gameValuesForIsExplored(isExploredPerGameVersion: isExploredPerGameVersion) if let data = coreItem.value(forKey: Map.serializedDataKey) as? Data, var json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { json["isExplored"] = coreItem.isExplored json["gameSequenceUuid"] = coreItem.gameSequenceUuid if let data2 = try? JSONSerialization.data(withJSONObject: json) { coreItem.setValue(data2, forKey: serializedDataKey) } } }) } }
mit
12dfa6fbcb8b4ba3b92195c28d763d24
34.247619
115
0.686841
4.351558
false
false
false
false
6ag/BaoKanIOS
BaoKanIOS/Classes/Module/News/Model/JFShareItemModel.swift
1
2228
// // JFShareItemModel.swift // WindSpeedVPN // // Created by zhoujianfeng on 2016/11/30. // Copyright © 2016年 zhoujianfeng. All rights reserved. // import UIKit enum JFShareType: Int { case qqFriend = 0 // qq好友 case qqQzone = 1 // qq空间 case weixinFriend = 2 // 微信好友 case friendCircle = 3 // 朋友圈 } class JFShareItemModel: NSObject { /// 名称 var title: String? /// 图标 var icon: String? /// 类型 var type: JFShareType = .qqFriend init(dict: [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} /// 加载分享item class func loadShareItems() -> [JFShareItemModel] { var shareItems = [JFShareItemModel]() // QQ if QQApiInterface.isQQInstalled() && QQApiInterface.isQQSupportApi() { let shareItemQQFriend = JFShareItemModel(dict: [ "title" : "QQ", "icon" : "share_qq" ]) shareItemQQFriend.type = JFShareType.qqFriend shareItems.append(shareItemQQFriend) let shareItemQQQzone = JFShareItemModel(dict: [ "title" : "QQ空间", "icon" : "share_qqkj" ]) shareItemQQFriend.type = JFShareType.qqQzone shareItems.append(shareItemQQQzone) } // 微信 if WXApi.isWXAppInstalled() && WXApi.isWXAppSupport() { let shareItemWeixinFriend = JFShareItemModel(dict: [ "title" : "微信好友", "icon" : "share_wechat" ]) shareItemWeixinFriend.type = JFShareType.weixinFriend shareItems.append(shareItemWeixinFriend) let shareItemFriendCircle = JFShareItemModel(dict: [ "title" : "朋友圈", "icon" : "share_friend" ]) shareItemFriendCircle.type = JFShareType.friendCircle shareItems.append(shareItemFriendCircle) } return shareItems } }
apache-2.0
9135b228249b4ef21446d70b40022e69
26.705128
78
0.536326
4.597872
false
false
false
false
tonystone/geofeatures2
Sources/GeoFeatures/Precision.swift
1
1681
/// /// Precision.swift /// /// Copyright (c) 2016 Tony Stone /// /// 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. /// /// Created by Tony Stone on 2/11/2016. /// import Swift /// /// The precision model used for all `Geometry` types. /// public protocol Precision { /// /// Convert a double into `self` precision. /// /// - Returns: A double converted to `self` precision. /// func convert(_ value: Double) -> Double /// /// Convert an optional double into `self` precision. /// /// - Returns: A double converted to `self` precision if a value was passed, or nil otherwise. /// func convert(_ value: Double?) -> Double? /// /// Convert a Coordinate into `self` precision. /// /// - Returns: A Coordinate converted to `self` precision. /// func convert(_ coordinate: Coordinate) -> Coordinate } /// /// Compares to precision types for equality when both are Hashable. /// public func == <T1: Precision & Hashable, T2: Precision & Hashable>(lhs: T1, rhs: T2) -> Bool { if type(of: lhs) == type(of: rhs) { return lhs.hashValue == rhs.hashValue } return false }
apache-2.0
b504cd321607b631bbca99859b314bf5
28.491228
98
0.644259
3.992874
false
false
false
false
jigneshsheth/Datastructures
DataStructure/DataStructure/LongestSubstring.swift
1
1414
// // LongestSubstring.swift // DataStructure // // Created by Jigs Sheth on 11/2/21. // Copyright © 2021 jigneshsheth.com. All rights reserved. // /** Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: s = "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. Example 4: Input: s = "" Output: 0 Constraints: 0 <= s.length <= 5 * 104 s consists of English letters, digits, symbols and spaces. **/ import Foundation class LongestSubstring { public static func lengthOfLongestSubstring(_ s: String) -> Int { var start = 0 var end = start+1 var counter = 0 var dict = [Character:Bool]() let charArray = Array(s) while start < charArray.count { dict[charArray[start]] = true while end < charArray.count { if dict[charArray[end]] != nil { break }else { dict[charArray[end]] = true end += 1 } } counter = max(dict.count,counter) dict.removeAll() start = start + 1 end = start + 1 } return counter } }
mit
88384ca7338ccd03d54887d39ad5aa9f
16.6625
89
0.630573
3.446341
false
false
false
false
jarocht/iOS-AlarmDJ
AlarmDJ/AlarmDJ/SettingsTableViewController.swift
1
4091
// // SettingsTableViewController.swift // AlarmDJ // // Created by X Code User on 7/22/15. // Copyright (c) 2015 Tim Jaroch, Morgan Heyboer, Andreas Plüss (TEAM E). All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var snoozeTimeTextField: UITextField! @IBOutlet weak var zipcodeTextField: UITextField! @IBOutlet weak var twentyFourHourSwitch: UISwitch! @IBOutlet weak var newsQueryTextField: UITextField! @IBOutlet weak var musicGenreDataPicker: UIPickerView! let ldm = LocalDataManager() var settings = SettingsContainer() var genres: [String] = ["Alternative","Blues","Country","Dance","Electronic","Hip-Hop/Rap","Jazz","Klassik","Pop","Rock", "Soundtracks"] override func viewDidLoad() { super.viewDidLoad() snoozeTimeTextField.delegate = self snoozeTimeTextField.tag = 0 zipcodeTextField.delegate = self zipcodeTextField.tag = 1 newsQueryTextField.delegate = self newsQueryTextField.tag = 2 musicGenreDataPicker.dataSource = self musicGenreDataPicker.delegate = self } override func viewWillAppear(animated: Bool) { settings = ldm.loadSettings() snoozeTimeTextField.text! = "\(settings.snoozeInterval)" zipcodeTextField.text! = settings.weatherZip twentyFourHourSwitch.on = settings.twentyFourHour newsQueryTextField.text! = settings.newsQuery var index = 0 for var i = 0; i < genres.count; i++ { if genres[i] == settings.musicGenre{ index = i } } musicGenreDataPicker.selectRow(index, inComponent: 0, animated: true) } override func viewWillDisappear(animated: Bool) { if count(zipcodeTextField.text!) == 5 { settings.weatherZip = zipcodeTextField.text! } if count(snoozeTimeTextField.text!) > 0 { var timeVal: Int = (snoozeTimeTextField.text!).toInt()! if timeVal > 0 { settings.snoozeInterval = timeVal //ldm.saveSettings(settingsContainer: settings) } } if count (newsQueryTextField.text!) > 0 { settings.newsQuery = newsQueryTextField.text! } ldm.saveSettings(settingsContainer: settings) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func twentyFourHourSwitchClicked(sender: AnyObject) { settings.twentyFourHour = twentyFourHourSwitch.on } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if textField.tag < 2 { if count(textField.text!) + count(string) <= 5 { return true; } return false } else { if count(textField.text!) + count(string) <= 25 { return true; } return false } } func textFieldDidBeginEditing(textField: UITextField) { } func textFieldShouldEndEditing(textField: UITextField) -> Bool { return true } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return genres.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return genres[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { settings.musicGenre = genres[row] } }
mit
d207e8ac6ca5ea9328b8425b5d580525
32.809917
140
0.632274
5.099751
false
false
false
false
johnsextro/cycschedule
cycschedule/SelectionViewController.swift
1
2664
import Foundation import UIKit class SelectionViewController: UITableViewController { var TableData:Array< String > = Array < String >() var lastSelectedIndexPath: NSIndexPath? override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return TableData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell cell.accessoryType = .None cell.textLabel?.text = TableData[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.row != lastSelectedIndexPath?.row { if let lastSelectedIndexPath = lastSelectedIndexPath{ let oldCell = tableView.cellForRowAtIndexPath(lastSelectedIndexPath) oldCell?.accessoryType = .None } let newCell = tableView.cellForRowAtIndexPath(indexPath) newCell?.accessoryType = .Checkmark lastSelectedIndexPath = indexPath self.navigationItem.rightBarButtonItem?.enabled = true } } func extract_json(data:NSString) { var parseError: NSError? let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)! let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &parseError) if (parseError == nil) { if let seasons_obj = json as? NSDictionary { if let seasons = seasons_obj["seasons"] as? NSArray { for (var i = 0; i < seasons.count ; i++ ) { if let season_obj = seasons[i] as? NSDictionary { if let season = season_obj["season"] as? String { TableData.append(season) } } } } } } do_table_refresh(); } func do_table_refresh() { dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() return }) } }
gpl-2.0
820bebedde2a77c42667172415433a45
34.052632
118
0.567568
6.068337
false
false
false
false
toggl/superday
teferi/UI/Modules/Daily Summary/SummaryPageViewModel.swift
1
1910
import Foundation import RxSwift class SummaryPageViewModel { private var selectedDate = Variable<Date>(Date()) var currentlySelectedDate : Date { get { return self.selectedDate.value.ignoreTimeComponents() } set(value) { self.selectedDate.value = value self.canMoveForwardSubject.onNext(canScroll(toDate: selectedDate.value.add(days: 1))) self.canMoveBackwardSubject.onNext(canScroll(toDate: selectedDate.value.add(days: -1))) } } private let canMoveForwardSubject = PublishSubject<Bool>() private(set) lazy var canMoveForwardObservable : Observable<Bool> = { return self.canMoveForwardSubject.asObservable() }() private let canMoveBackwardSubject = PublishSubject<Bool>() private(set) lazy var canMoveBackwardObservable : Observable<Bool> = { return self.canMoveBackwardSubject.asObservable() }() private let settingsService: SettingsService private let timeService: TimeService var dateObservable : Observable<String> { return selectedDate .asObservable() .map { let dateformater = DateFormatter() dateformater.dateFormat = "EEE, dd MMM" return dateformater.string(from: $0) } } init(date: Date, timeService: TimeService, settingsService: SettingsService) { selectedDate.value = date self.settingsService = settingsService self.timeService = timeService } func canScroll(toDate date: Date) -> Bool { let minDate = settingsService.installDate!.ignoreTimeComponents() let maxDate = timeService.now.ignoreTimeComponents() let dateWithNoTime = date.ignoreTimeComponents() return dateWithNoTime >= minDate && dateWithNoTime <= maxDate } }
bsd-3-clause
a6d0f91c46c1888be9314eb1c6893a3d
30.833333
99
0.646073
5.134409
false
false
false
false
crescentflare/ViewletCreator
ViewletCreatorIOS/Example/ViewletCreator/Viewlets/UITextFieldViewlet.swift
1
2257
// // UITextFieldViewlet.swift // Viewlet creator example // // Create a simple text input field // import UIKit import ViewletCreator class UITextFieldViewlet: Viewlet { func create() -> UIView { return UITextField() } func update(view: UIView, attributes: [String: Any], parent: UIView?, binder: ViewletBinder?) -> Bool { if let textField = view as? UITextField { // Prefilled text and placeholder textField.text = ViewletConvUtil.asString(value: attributes["text"]) textField.placeholder = NSLocalizedString(ViewletConvUtil.asString(value: attributes["placeholder"]) ?? "", comment: "") // Set keyboard mode textField.keyboardType = .default textField.autocapitalizationType = .sentences if let keyboardType = ViewletConvUtil.asString(value: attributes["keyboardType"]) { if keyboardType == "email" { textField.keyboardType = .emailAddress textField.autocapitalizationType = .none } else if keyboardType == "url" { textField.keyboardType = .URL textField.autocapitalizationType = .none } } // Text style let fontSize = ViewletConvUtil.asDimension(value: attributes["textSize"]) ?? 17 if let font = ViewletConvUtil.asString(value: attributes["font"]) { if font == "bold" { textField.font = UIFont.boldSystemFont(ofSize: fontSize) } else if font == "italics" { textField.font = UIFont.italicSystemFont(ofSize: fontSize) } else { textField.font = UIFont(name: font, size: fontSize) } } else { textField.font = UIFont.systemFont(ofSize: fontSize) } // Standard view attributes UIViewViewlet.applyDefaultAttributes(view: view, attributes: attributes) return true } return false } func canRecycle(view: UIView, attributes: [String : Any]) -> Bool { return view is UITextField } }
mit
a13e8366f8e236cfd43597ed7aea14ea
36
132
0.564023
5.425481
false
false
false
false
devpunk/cartesian
cartesian/Model/DrawProject/Menu/Text/MDrawProjectMenuTextItemSize.swift
1
1393
import UIKit class MDrawProjectMenuTextItemSize:MDrawProjectMenuTextItem, MDrawProjectFontSizeDelegate { private weak var controller:CDrawProject? init() { let title:String = NSLocalizedString("MDrawProjectMenuTextItemSize_title", comment:"") super.init( title:title, image:#imageLiteral(resourceName: "assetGenericFontSize")) } override func selected(controller:CDrawProject) { self.controller = controller controller.modelState.stateStand(controller:controller) controller.viewProject.viewMenu.viewBar.modeNormal() controller.viewProject.showFontSize(delegate:self) } //MARK: fontSize delegate func fontSizeSelected(size:Int16) { let modelLabel:DLabel? = controller?.editingView?.viewSpatial.model as? DLabel controller?.endText() modelLabel?.fontSize = size modelLabel?.updateGenerated() DManager.sharedInstance?.save() modelLabel?.notifyDraw() } func fontCurrentSize() -> Int16? { guard let modelLabel:DLabel = controller?.editingView?.viewSpatial.model as? DLabel else { return nil } let currentSize:Int16 = modelLabel.fontSize return currentSize } }
mit
f091e7041f8f9f8fbe3b35edada6ade7
25.283019
94
0.620962
5.178439
false
false
false
false
xeo-it/poggy
Pods/Eureka/Source/Core/HeaderFooterView.swift
2
5324
// HeaderFooterView.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** Enumeration used to generate views for the header and footer of a section. - Class: Will generate a view of the specified class. - Callback->ViewType: Will generate the view as a result of the given closure. - NibFile: Will load the view from a nib file. */ public enum HeaderFooterProvider<ViewType: UIView> { /** * Will generate a view of the specified class. */ case Class /** * Will generate the view as a result of the given closure. */ case Callback(()->ViewType) /** * Will load the view from a nib file. */ case NibFile(name: String, bundle: NSBundle?) internal func createView() -> ViewType { switch self { case .Class: return ViewType() case .Callback(let builder): return builder() case .NibFile(let nibName, let bundle): return (bundle ?? NSBundle(forClass: ViewType.self)).loadNibNamed(nibName, owner: nil, options: nil)![0] as! ViewType } } } /** * Represents headers and footers of sections */ public enum HeaderFooterType { case Header, Footer } /** * Struct used to generate headers and footers either from a view or a String. */ public struct HeaderFooterView<ViewType: UIView> : StringLiteralConvertible, HeaderFooterViewRepresentable { /// Holds the title of the view if it was set up with a String. public var title: String? /// Generates the view. public var viewProvider: HeaderFooterProvider<ViewType>? /// Closure called when the view is created. Useful to customize its appearance. public var onSetupView: ((view: ViewType, section: Section) -> ())? /// A closure that returns the height for the header or footer view. public var height: (()->CGFloat)? /** This method can be called to get the view corresponding to the header or footer of a section in a specific controller. - parameter section: The section from which to get the view. - parameter type: Either header or footer. - parameter controller: The controller from which to get that view. - returns: The header or footer of the specified section. */ public func viewForSection(section: Section, type: HeaderFooterType) -> UIView? { var view: ViewType? if type == .Header { view = section.headerView as? ViewType ?? { let result = viewProvider?.createView() section.headerView = result return result }() } else { view = section.footerView as? ViewType ?? { let result = viewProvider?.createView() section.footerView = result return result }() } guard let v = view else { return nil } onSetupView?(view: v, section: section) return v } /** Initiates the view with a String as title */ public init?(title: String?){ guard let t = title else { return nil } self.init(stringLiteral: t) } /** Initiates the view with a view provider, ideal for customized headers or footers */ public init(_ provider: HeaderFooterProvider<ViewType>){ viewProvider = provider } /** Initiates the view with a String as title */ public init(unicodeScalarLiteral value: String) { self.title = value } /** Initiates the view with a String as title */ public init(extendedGraphemeClusterLiteral value: String) { self.title = value } /** Initiates the view with a String as title */ public init(stringLiteral value: String) { self.title = value } } extension UIView { func eurekaInvalidate() { setNeedsUpdateConstraints() updateConstraintsIfNeeded() setNeedsLayout() } }
apache-2.0
f512d174deb6e7016081a02a0b6ce7cc
31.463415
129
0.628663
4.966418
false
false
false
false
zenangst/Faker
Source/Data/Parser.swift
1
2753
import SwiftyJSON public class Parser { public var locale: String { didSet { if locale != oldValue { loadData() } } } var data: JSON = [] var provider: Provider public init(locale: String = Config.defaultLocale) { self.provider = Provider() self.locale = locale loadData() } // MARK: - Parsing public func fetch(key: String) -> String { var parsed: String = "" var parts = split(key) {$0 == "."} if parts.count > 0 { var keyData = data[locale]["faker"] let subject = parts[0] for part in parts { keyData = keyData[part] } if let value = keyData.string { parsed = value } else if let array = keyData.arrayObject { let count = UInt32(array.count) if let item = array[Int(arc4random_uniform(count))] as? String { parsed = item } } if parsed.rangeOfString("#{") != nil { parsed = parse(parsed, forSubject: subject) } } return parsed } func parse(template: String, forSubject subject: String) -> String { var text = "" let string = template as NSString let regex = NSRegularExpression(pattern: "(\\(?)#\\{([A-Za-z]+\\.)?([^\\}]+)\\}([^#]+)?", options: nil, error: nil)! let matches = regex.matchesInString(string as String, options: nil, range: NSMakeRange(0, string.length)) as! [NSTextCheckingResult] if matches.count > 0 { for match in matches { if match.numberOfRanges < 4 { continue } let prefixRange = match.rangeAtIndex(1) let subjectRange = match.rangeAtIndex(2) let methodRange = match.rangeAtIndex(3) let otherRange = match.rangeAtIndex(4) if prefixRange.length > 0 { text += string.substringWithRange(prefixRange) } var subjectWithDot = subject + "." if subjectRange.length > 0 { subjectWithDot = string.substringWithRange(subjectRange) } if methodRange.length > 0 { let key = subjectWithDot.lowercaseString + string.substringWithRange(methodRange) text += fetch(key) } if otherRange.length > 0 { text += string.substringWithRange(otherRange) } } } else { text = template } return text } // MARK: - Data loading func loadData() { if let localeData = provider.dataForLocale(locale) { data = JSON(data: localeData, options: NSJSONReadingOptions.AllowFragments, error: nil) } else if locale != Config.defaultLocale { locale = Config.defaultLocale } else { fatalError("JSON file for '\(locale)' locale was not found.") } } }
mit
4ffb418454ba2c9d198f802b7ac1d067
23.362832
93
0.579368
4.376789
false
false
false
false
mrlegowatch/JSON-to-Swift-Converter
JSON to Swift Converter/ViewController.swift
1
7441
// // ViewController.swift // JSON to Swift Converter // // Created by Brian Arnold on 2/20/17. // Copyright © 2018 Brian Arnold. All rights reserved. // import Cocoa extension NSButton { var isChecked: Bool { return self.state == .on } } extension String { /// Returns an attributed string with the specified color. func attributed(with color: NSColor) -> NSAttributedString { let attributes: [NSAttributedStringKey: Any] = [.foregroundColor: color] return NSMutableAttributedString(string: self, attributes: attributes) } /// Returns an attributed string with the Swift "keyword" color. var attributedKeywordColor: NSAttributedString { return self.attributed(with: NSColor(calibratedRed: 0.72, green: 0.2, blue: 0.66, alpha: 1.0)) } /// Returns an attributed string with the Swift "type" color. var attributedTypeColor: NSAttributedString { return self.attributed(with: NSColor(calibratedRed: 0.44, green: 0.26, blue: 0.66, alpha: 1.0)) } /// Returns an attributed string with the Swift "string literal" color. var attributedStringColor: NSAttributedString { return self.attributed(with: NSColor(calibratedRed: 0.84, green: 0.19, blue: 0.14, alpha: 1.0)) } /// Returns an attributed string with the Swift "int literal" color. var attributedIntColor: NSAttributedString { return self.attributed(with: NSColor(calibratedRed: 0.16, green: 0.20, blue: 0.83, alpha: 1.0)) } /// Returns self as an attributed string, for contatenation with other attributed strings. var attributed: NSAttributedString { return NSAttributedString(string: self) } } class ViewController: NSViewController { @IBOutlet weak var declarationLet: NSButton! @IBOutlet weak var declarationVar: NSButton! @IBOutlet weak var typeExplicit: NSButton! @IBOutlet weak var typeOptional: NSButton! @IBOutlet weak var typeRequired: NSButton! @IBOutlet weak var addDefaultValue: NSButton! @IBOutlet weak var supportCodable: NSButton! @IBOutlet weak var version: NSTextField! { didSet { version.stringValue = "Version \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String)" } } @IBOutlet weak var output: NSTextField! var appSettings = AppSettings() override func viewDidLoad() { super.viewDidLoad() updateControls() updateOutput() } /// Update the controls to match the user defaults settings func updateControls() { let isDeclarationLet = appSettings.declaration == .useLet declarationLet.state = isDeclarationLet ? .on : .off declarationVar.state = isDeclarationLet ? .off : .on let typeUnwrapping = appSettings.typeUnwrapping typeExplicit.state = typeUnwrapping == .explicit ? .on : .off typeOptional.state = typeUnwrapping == .optional ? .on : .off typeRequired.state = typeUnwrapping == .required ? .on : .off addDefaultValue.state = appSettings.addDefaultValue ? .on : .off supportCodable.state = appSettings.supportCodable ? .on : .off } /// Update the output text view to reflect the current settings func updateOutput() { let declaration = appSettings.declaration == .useLet ? "let" : "var" let typeUnwrapping = appSettings.typeUnwrapping == .optional ? "?" : appSettings.typeUnwrapping == .required ? "!" : "" let outputData = [["user name", "String", "\"\""], ["age", "Int", "0"]] let outputString = NSMutableAttributedString(string: "") outputString.beginEditing() let lineIndent = LineIndent(useTabs: false, indentationWidth: 4, level: 1) // Add the coding keys (required for example because swiftName doesn't match JSON name) outputString.append("private enum".attributedKeywordColor) outputString.append(" CodingKeys: ".attributed) outputString.append("String".attributedKeywordColor) outputString.append(", ".attributed) outputString.append("CodingKey".attributedKeywordColor) outputString.append(" {\n".attributed) for item in outputData { outputString.append("\(lineIndent)".attributed) outputString.append("case ".attributedKeywordColor) outputString.append(" \(item[0].swiftName)".attributed) if item[0] != item[0].swiftName { outputString.append(" = ".attributed) outputString.append("\"\(item[0])\"".attributedStringColor) } outputString.append("\n".attributed) } outputString.append("}\n\n".attributed) // Add the declarations for item in outputData { outputString.append("\(declaration)".attributedKeywordColor) outputString.append(" \(item[0].swiftName): ".attributed) outputString.append(": \(item[1])".attributedTypeColor) outputString.append("\(typeUnwrapping)".attributed) if appSettings.addDefaultValue { outputString.append(" = ".attributed) let value = item[2] == "0" ? "\(item[2])".attributedIntColor : "\(item[2])".attributedStringColor outputString.append(value) } outputString.append("\n".attributed) } outputString.append("\n".attributed) if appSettings.supportCodable { // Add the init method. do {//if appSettings.addInit { outputString.append("init".attributedKeywordColor) outputString.append("(from decoder: ".attributed) outputString.append("Decoder".attributedKeywordColor) outputString.append(") ".attributed) outputString.append("throws".attributedKeywordColor) outputString.append(" { ... }\n".attributed) } // Add the dictionary variable. do {//if appSettings.addDictionary { outputString.append("func encode".attributedKeywordColor) outputString.append("(to encoder: ".attributed) outputString.append("Encoder".attributedKeywordColor) outputString.append(") ".attributed) outputString.append("throws".attributedKeywordColor) outputString.append(" { ... }".attributed) } } outputString.endEditing() output.attributedStringValue = outputString } @IBAction func changeDeclaration(_ sender: NSButton) { let selectedTag = sender.selectedTag() appSettings.declaration = AppSettings.Declaration(rawValue: selectedTag)! updateOutput() } @IBAction func changeTypeUnwrapping(_ sender: NSButton) { let selectedTag = sender.selectedTag() appSettings.typeUnwrapping = AppSettings.TypeUnwrapping(rawValue: selectedTag)! updateOutput() } @IBAction func changeDefaultValue(_ sender: NSButton) { appSettings.addDefaultValue = sender.isChecked updateOutput() } @IBAction func changeSupportCodable(_ sender: NSButton) { appSettings.supportCodable = sender.isChecked updateOutput() } }
mit
e63a10a147256eecbd2132f53d1bca5d
37.75
128
0.633333
5.232068
false
false
false
false
flowsprenger/RxLifx-Swift
RxLifxApi/RxLifxApi/Light.swift
1
10987
/* Copyright 2017 Florian Sprenger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import LifxDomain import RxSwift public protocol LightSource { var tick: Observable<Int> { get } var source: UInt32 { get } var ioScheduler: SchedulerType { get } var mainScheduler: SchedulerType { get } func extensionOf<E>() -> E? where E: LightServiceExtension var messages: Observable<SourcedMessage> { get } func sendMessage(light: Light?, data: Data) -> Bool } public protocol LightsChangeDispatcher { func notifyChange(light: Light, property: LightPropertyName, oldValue: Any?, newValue: Any?) func lightAdded(light: Light) } public enum LightPropertyName { case color case zones case power case label case hostFirmware case wifiFirmware case version case group case location case infraredBrightness case reachable } public class Light: Equatable { private var disposeBag: CompositeDisposable = CompositeDisposable() public let lightSource: LightSource public let lightChangeDispatcher: LightsChangeDispatcher public let target: UInt64 public let id: String public var addr: sockaddr? public var sequence: UInt8 = 0 public static let refreshMutablePropertiesTickModulo = 20 public static let productsSupportingMultiZone = [0, 31, 32, 38] public static let productsSupportingInfrared = [0, 29, 30, 45, 46] public static let productsSupportingTile = [55] public lazy var color: LightProperty<HSBK> = { LightProperty<HSBK>(light: self, name: .color) }() public lazy var zones: LightProperty<MultiZones> = { LightProperty<MultiZones>(light: self, name: .zones) }() public lazy var power: LightProperty<UInt16> = { LightProperty<UInt16>(light: self, name: .power) }() public lazy var label: LightProperty<String> = { LightProperty<String>(light: self, name: .label) }() public lazy var hostFirmware: LightProperty<FirmwareVersion> = { LightProperty<FirmwareVersion>(light: self, name: .hostFirmware) }() public lazy var wifiFirmware: LightProperty<FirmwareVersion> = { LightProperty<FirmwareVersion>(light: self, name: .wifiFirmware) }() public lazy var version: LightProperty<LightVersion> = { LightProperty<LightVersion>(light: self, name: .version) }() public lazy var group: LightProperty<LightGroup> = { LightProperty<LightGroup>(light: self, name: .group, defaultValue: LightGroup.defaultGroup) }() public lazy var location: LightProperty<LightLocation> = { LightProperty<LightLocation>(light: self, name: .location, defaultValue: LightLocation.defaultLocation) }() public lazy var infraredBrightness: LightProperty<UInt16> = { LightProperty<UInt16>(light: self, name: .infraredBrightness) }() public lazy var reachable: LightProperty<Bool> = { LightProperty<Bool>(light: self, name: .reachable, defaultValue: false) }() public var lastSeenAt: Date = Date.distantPast public var powerState: Bool { get { return power.value ?? 0 == 0 ? false : true } } public var supportsMultiZone: Bool { get { return Light.productsSupportingMultiZone.contains(Int(version.value?.product ?? 0)) } } public var supportsInfrared: Bool { get { return Light.productsSupportingInfrared.contains(Int(version.value?.product ?? 0)) } } public var supportsTile: Bool { get { return Light.productsSupportingTile.contains(Int(version.value?.product ?? 0)) } } public init(id: UInt64, lightSource: LightSource, lightChangeDispatcher: LightsChangeDispatcher) { self.lightSource = lightSource self.lightChangeDispatcher = lightChangeDispatcher self.target = id self.id = id.toLightId() } public func dispose() { disposeBag.dispose() } public func getNextSequence() -> UInt8 { sequence = sequence &+ 1 return sequence } public func updateReachability() { reachable.updateFromClient(value: lastSeenAt.timeIntervalSinceNow > -11) } public func attach(observable: GroupedObservable<UInt64, SourcedMessage>) -> Light { dispose() disposeBag = CompositeDisposable() _ = disposeBag.insert(observable.subscribe(onNext: { (message: SourcedMessage) in self.addr = message.sourceAddress self.lastSeenAt = Date() self.updateReachability() LightMessageHandler.handleMessage(light: self, message: message.message) })) _ = disposeBag.insert(lightSource.tick.subscribe(onNext: { c in self.pollState() self.updateReachability() if (c % Light.refreshMutablePropertiesTickModulo == 0) { self.pollMutableProperties() } return })) pollProperties() pollState() return self } private func pollState() { LightGetCommand.create(light: self).fireAndForget() if (supportsMultiZone) { MultiZoneGetColorZonesCommand.create(light: self, startIndex: UInt8.min, endIndex: UInt8.max).fireAndForget() } if (supportsInfrared) { LightGetInfraredCommand.create(light: self).fireAndForget() } } private func pollProperties() { DeviceGetHostFirmwareCommand.create(light: self).fireAndForget() DeviceGetWifiFirmwareCommand.create(light: self).fireAndForget() DeviceGetVersionCommand.create(light: self).fireAndForget() pollMutableProperties() } private func pollMutableProperties() { DeviceGetGroupCommand.create(light: self).fireAndForget() DeviceGetLocationCommand.create(light: self).fireAndForget() } public static func ==(lhs: Light, rhs: Light) -> Bool { return lhs.target == rhs.target } } public class LightProperty<T: Equatable> { private var _value: T? = nil public var value: T? { get { return _value } } private let light: Light private let name: LightPropertyName private var updatedFromClientAt: Date = Date.distantPast private let localValueValidityWindow: TimeInterval = -2 init(light: Light, name: LightPropertyName, defaultValue: T? = nil) { self.light = light self.name = name self._value = defaultValue } public func updateFromClient(value: T?) { if (_value != value) { let oldValue = _value _value = value updatedFromClientAt = Date() light.lightChangeDispatcher.notifyChange(light: light, property: name, oldValue: oldValue, newValue: value) } } public func updateFromDevice(value: T?) { if (_value != value && !hasRecentlyUpdatedFromClient()) { let oldValue = _value _value = value light.lightChangeDispatcher.notifyChange(light: light, property: name, oldValue: oldValue, newValue: value) } } public func hasRecentlyUpdatedFromClient() -> Bool { return updatedFromClientAt.timeIntervalSinceNow > localValueValidityWindow } } public class FirmwareVersion: Equatable { public let build: UInt64 public let version: UInt32 init(build: UInt64, version: UInt32) { self.build = build self.version = version } public static func ==(lhs: FirmwareVersion, rhs: FirmwareVersion) -> Bool { return lhs.build == rhs.build && lhs.version == rhs.version } } public class LightVersion: Equatable { public let vendor: UInt32 public let product: UInt32 public let version: UInt32 init(vendor: UInt32, product: UInt32, version: UInt32) { self.vendor = vendor self.product = product self.version = version } public static func ==(lhs: LightVersion, rhs: LightVersion) -> Bool { return lhs.vendor == rhs.vendor && lhs.product == rhs.product && lhs.version == rhs.version } } public class LightLocation: Equatable { static let defaultLocation = LightLocation(id: Array(repeating: 48, count: 8), label: "", updatedAt: Date(timeIntervalSince1970: 0)) public let id: [UInt8] public let label: String public let updatedAt: Date public lazy var identifier: String = String(describing: id.map({ UnicodeScalar($0) })) init(id: [UInt8], label: String, updatedAt: Date) { self.id = id self.label = label self.updatedAt = updatedAt } public static func ==(lhs: LightLocation, rhs: LightLocation) -> Bool { return lhs.id == rhs.id && lhs.label == rhs.label && lhs.updatedAt == rhs.updatedAt } } public class LightGroup: Equatable { static let defaultGroup = LightGroup(id: Array(repeating: 48, count: 8), label: "", updatedAt: Date(timeIntervalSince1970: 0)) public let id: [UInt8] public let label: String public let updatedAt: Date public lazy var identifier: String = String(describing: id.map({ UnicodeScalar($0) })) init(id: [UInt8], label: String, updatedAt: Date) { self.id = id self.label = label self.updatedAt = updatedAt } public static func ==(lhs: LightGroup, rhs: LightGroup) -> Bool { return lhs.id == rhs.id && lhs.label == rhs.label && lhs.updatedAt == rhs.updatedAt } } public class MultiZones: Equatable { public var colors: [HSBK] = [] public static func ==(lhs: MultiZones, rhs: MultiZones) -> Bool { return false } func dimTo(_ count: Int) { while (colors.count < count) { colors.append(HSBK(hue: 0, saturation: 0, brightness: 0, kelvin: 0)) } while (colors.count > count) { colors.removeLast() } } }
mit
76713a7a9a84d5ad0ae8abe8f8ef8f7f
30.665706
136
0.66069
4.534461
false
false
false
false
vojto/NiceKit
NiceKit/EditableTableRowView.swift
1
1239
// // CustomTableRowView.swift // FocusPlan // // Created by Vojtech Rinik on 5/11/17. // Copyright © 2017 Median. All rights reserved. // import Foundation import AppKit open class EditableTableRowView: NSTableRowView { open var isEditing = false } open class CustomTableRowView: EditableTableRowView { static var selectionColor = NSColor(hexString: "ECEEFA")! override open var isSelected: Bool { didSet { needsDisplay = true } } override open var isEditing: Bool { didSet { needsDisplay = true } } override open func drawBackground(in dirtyRect: NSRect) { let rect = bounds.insetBy(dx: 4, dy: 4) let path = NSBezierPath(roundedRect: rect, cornerRadius: 3) let blue = CustomTableRowView.selectionColor if isEditing { NSColor.white.set() bounds.fill() blue.setStroke() path.stroke() } else if isSelected { NSColor.white.set() bounds.fill() blue.setFill() path.fill() } else { NSColor.white.set() bounds.fill() } } }
mit
ca3708e9f0a25e820261b0a1b0ef34c1
22.358491
67
0.555735
4.779923
false
false
false
false
saraford/AttemptOne
AttemptOne/ViewController.swift
1
10986
// // ViewController.swift // AttemptOne // // Created by Sara Ford on 8/29/15. // Copyright (c) 2015 Sara Ford. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { var gameScenes = [GameScene]() var gameEngine:GameEngine! // var validCommands:ValidCommands! var allCommands = [Command]() var currentScene:Int = 0 @IBOutlet weak var responseText: UITextView! @IBOutlet weak var userInput: UITextField! @IBOutlet weak var gameText: UITextView! @IBOutlet var sceneView: UIView! @IBOutlet weak var sceneTextView: UITextView! @IBOutlet weak var responseTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() // needed for the keyboard self.userInput.delegate = self // show keyboard userInput.becomeFirstResponder() gameText.scrollRangeToVisible(NSRange(location:0, length:0)) gameEngine = GameEngine(viewController: self) createGameScenes() updateInitScene() // validCommands = ValidCommands() // println("commands: \(validCommands.verbs)") } func updateInitScene() { currentScene = 0 gameText.text = gameScenes[currentScene].sceneText responseText.text = gameScenes[currentScene].hintText gameText.textColor = UIColor.whiteColor() sceneView.backgroundColor = UIColor.blackColor() sceneTextView.backgroundColor = UIColor.blackColor() responseTextView.backgroundColor = UIColor.blackColor() } func updateScene(newScene: Int, lastCommand: String) { currentScene = newScene var currentGameScene = gameScenes[currentScene] gameText.text = lastCommand + "\n\n" + currentGameScene.sceneText // update new scene with hint text, if any responseText.text = currentGameScene.hintText } func updateDeathScene(deathText: String) { gameText.text = deathText.uppercaseString responseText.text = gameScenes[0].hintText sceneView.backgroundColor = UIColor.redColor() sceneTextView.backgroundColor = UIColor.redColor() responseTextView.backgroundColor = UIColor.redColor() responseText.text = "hint \"try again\"" } func updateResponse(error: String) { responseText.text = error } func createGameScenes() { var commandFeelAround = Command(verb: "feel", object: "around") allCommands.append(commandFeelAround) var commandWalkForwards = Command(verb:"walk", object:"forwards") allCommands.append(commandWalkForwards) var commandWalkBackwards = Command(verb:"walk", object:"backwards") allCommands.append(commandWalkBackwards) var commandHelp = Command(verb:"help", object:"") allCommands.append(commandHelp) var commandTakeShoes = Command(verb:"take", object:"shoes") allCommands.append(commandTakeShoes) var commandOpenDoor = Command(verb: "open", object: "door") allCommands.append(commandOpenDoor) var commandDoNothing = Command(verb: "do", object: "nothing") allCommands.append(commandDoNothing) var commandWalkLeft = Command(verb: "walk", object: "left") allCommands.append(commandWalkLeft) var commandWalkRight = Command(verb: "walk", object: "right") allCommands.append(commandWalkRight) var commandSayHello = Command(verb: "say", object: "hello") allCommands.append(commandSayHello) var commandTryAgain = Command(verb: "try", object: "again") allCommands.append(commandTryAgain) var state0 = GameScene() state0.sceneText = "You open your eyes, but the world remains dark." state0.hintText = "hint: \"feel around\"" state0.addValidCommand(commandFeelAround, text: "You feel around", goToScene: 1) state0.addNothingCommand(commandDoNothing) gameScenes.append(state0) var state1 = GameScene() state1.sceneText = "You are in a small room. The room rocks gently back and forth. There's a loud rumbling noise in the distance." state1.hintText = "" state1.addValidCommand(commandFeelAround, text: "You feel around", goToScene: 2) state1.addValidCommand(commandOpenDoor, text: "You open the door and walk through", goToScene: 3) state1.addUnableToCommand(commandWalkForwards, error: "You walk directly into something") gameScenes.append(state1) var state2 = GameScene() state2.sceneText = "You find a closed door blocking your path. The room rocks gently back and forth." state2.hintText = "" state2.addValidCommand(commandOpenDoor, text: "You open the door", goToScene: 3) state2.addUnableToCommand(commandWalkForwards, error: "You walk directly into something") gameScenes.append(state2) var state3 = GameScene() state3.sceneText = "You see the bow of a boat. The roar and darkness of an approaching storm frightens you." state3.addValidCommand(commandWalkForwards, text: "You walk forwards", goToScene: 4) state3.hintText = "" gameScenes.append(state3) var state4 = GameScene() state4.sceneText = "You jump off the boat. You are on a pier. The shore is on right. The pier continues on left" state4.hintText = "hint: \"walk left or walk right\"" state4.addValidCommand(commandWalkRight, text: "You walk right", goToScene: 5) state4.addDeathCommand(commandWalkLeft, deathText: "A water spout appears. The wind is too fearce to run away. You fall into the bay and drown.") gameScenes.append(state4) var state5 = GameScene() state5.sceneText = "You arrive at the entrance of the Yacht Club. It starts to downpour. A waterspout appears heading right for you." state5.hintText = "" state5.addValidCommand(commandOpenDoor, text: "You open the door", goToScene: 6) state5.addDeathCommand(commandFeelAround, deathText: "You took too long getting inside. A wooden board from the pier hits you in the head.") gameScenes.append(state5) var state6 = GameScene() state6.sceneText = "You take shelter with others inside." state6.hintText = "hint \"Say hello\"" state6.addValidCommand(commandSayHello, text: "You say hello", goToScene: 7) gameScenes.append(state6) var state7 = GameScene() state7.sceneText = "No one remembers how they got here. The sky becomes pitch black. A dragon appears over the small bay, looking for you." state7.addValidCommand(commandWalkForwards, text: "You leave the yacht club", goToScene: 8) gameScenes.append(state7) var state8 = GameScene() state8.sceneText = "You get out just in time. You are in a parking lot." state8.hintText = "Congrats you won becuase this is as far as I've gotten." gameScenes.append(state8) } // for handling the return key when it is clicked from the keyboard // requires UITextFieldDelegate and setting the delegate!! func textFieldShouldReturn(textField: UITextField) -> Bool { processInput() // textField.resignFirstResponder() return true; } // if the user taps outside the keyboard to add the item override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if (userInput.text == "") { // just ignore in case user accidentally tapped outside the textbox without any info return } // self.view.endEditing(true) } func processInput() { var input = userInput.text.lowercaseString println(input) var command:Command! // check if input is valid input from user before even continuing if (validateInput(input)) { // got a valid command var command = createCommand(input) // update the scene gameEngine.executeCommand(gameScenes[currentScene], command: command) } userInput.text = "" } func createCommand(input: String) -> Command { var words = findWords(input) // add an 's' to forward and backward objects if (words.count > 1) { if (words[1] == "forward") { words[1] = "forwards" } else if (words[1] == "backward") { words[1] = "backward" } } if (words.count == 1) { return Command(verb: words[0], object: "") } else { return Command(verb: words[0], object: words[1]) } } func validateInput(input: String) -> Bool { if (input.isEmpty || input == "") { displayError("Are you giving me the slience treatment?") return false } // remove any trailing whitespace var trimmedInput = input.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) if (trimmedInput.isEmpty || trimmedInput == "") { displayError("Are you giving me the slience treatment?") return false } var words = findWords(trimmedInput) if (words.count > 2) { displayError("I only respond to 1 or 2 word commands") return false } // verify first word is in list of known words for cmd in allCommands { if (cmd.verb == words[0]) { return true } } displayError("Sorry, I don't know what \(words[0]) means ") return false } func displayError(error:String) { updateResponse("Um... \(error)") } func findWords(s: String) -> [String] { var words = s.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) var legitWords = [String]() for word in words { if (word != "") { legitWords.append(word) } } return legitWords } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
84bf4baf9bd6f0b149c05acd984d9496
31.40708
153
0.597215
4.991368
false
false
false
false
andrewferrier/imbk
imbk/AppDelegate.swift
1
3247
// // AppDelegate.swift // imbk // // Created by Andrew Ferrier on 10/05/2016. // Copyright © 2016 Andrew Ferrier. All rights reserved. // import UIKit import HockeySDK @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. NSLog("About to authenticate with HockeyApp services") BITHockeyManager.sharedHockeyManager().configureWithIdentifier("a15ddd8537b64652afe2e1aca26887c9") BITHockeyManager.sharedHockeyManager().startManager() BITHockeyManager.sharedHockeyManager().authenticator.authenticateInstallation() NSLog("About to ask for permission for notifications.") application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge], categories: nil)) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. let notification = UILocalNotification() notification.timeZone = NSTimeZone.defaultTimeZone() let dateTime = NSDate(timeIntervalSinceNow: 60 * 60 * 24 * 3) // 3 days notification.fireDate = dateTime notification.alertBody = "Time to backup your photos with imbk!" notification.applicationIconBadgeNumber = 1 UIApplication.sharedApplication().scheduleLocalNotification(notification) NSLog("Local notification scheduled.") } 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
c163fc0f68f5a2f532adb1e896de0d40
50.52381
285
0.753851
5.775801
false
false
false
false
pine613/SwiftyPopover
Example/Tests/Tests.swift
1
1180
// https://github.com/Quick/Quick import Quick import Nimble import SwiftyPopover 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
b22885e1aeec1ca7901dc88b0098394f
22.48
63
0.365417
5.485981
false
false
false
false
iluuu1994/2048
2048/Classes/GameOverScene.swift
1
2291
// // GameOverScene.swift // 2048 // // Created by Ilija Tovilo on 31/07/14. // Copyright (c) 2014 Ilija Tovilo. All rights reserved. // import Foundation @objc(TFGameOverScene) class GameOverScene: CCScene { // MARK: Instanc Variables private let _score: Int lazy private var _backgroundNode: CCNodeColor = { CCNodeColor(color: CCColor(red: 0.98, green: 0.97, blue: 0.94)) }() lazy var _gameOverLabel: CCLabelTTF = { let l = CCLabelTTF(string: "Game Over!", fontName: "ClearSans-Bold", fontSize: 40) l.position = CGPoint(x: 0.5, y: 0.55) l.positionType = CCPositionType( xUnit: .Normalized, yUnit: .Normalized, corner: .BottomLeft ) l.fontColor = CCColor(red: 0.47, green: 0.43, blue: 0.4) return l }() lazy var _scoreLabel: CCLabelTTF = { let l = CCLabelTTF(string: "Score: \(self._score)", fontName: "ClearSans-Bold", fontSize: 28) l.position = CGPoint(x: 0.5, y: 0.45) l.positionType = CCPositionType( xUnit: .Normalized, yUnit: .Normalized, corner: .BottomLeft ) l.fontColor = CCColor(red: 0.67, green: 0.63, blue: 0.6) return l }() lazy var _tryAgainButton: CCButton = { let l = Button(title: "TRY AGAIN", fontName: "ClearSans-Bold", fontSize: 28) l.position = CGPoint(x: 0.5, y: 0.3) l.positionType = CCPositionType( xUnit: .Normalized, yUnit: .Normalized, corner: .BottomLeft ) l.setTarget(self, selector: "restartGame") return l }() // MARK: Init class func scene(#score: Int) -> GameOverScene { return GameOverScene(score: score) } init(score: Int) { _score = score super.init() initSubnodes() } func initSubnodes() { addChild(_backgroundNode) addChild(_gameOverLabel) addChild(_scoreLabel) addChild(_tryAgainButton) } // MARK: Target Actions func restartGame() { CCDirector.sharedDirector().replaceScene(GameScene.scene()) } }
bsd-3-clause
05f42f060d69b0031ea11a56eab2b83f
23.634409
101
0.54474
4.005245
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Core/Matrix4.swift
1
56037
// // Matrix4.swift // CesiumKit // // Created by Ryan Walklin on 13/07/14. // Copyright (c) 2014 Test Toast. All rights reserved. // import Foundation import simd /** * A 4x4 matrix, indexable as a column-major order array. * Constructor parameters are in row-major order for code readability. * @alias Matrix4 * @constructor * * @param {Number} [column0Row0=0.0] The value for column 0, row 0. * @param {Number} [column1Row0=0.0] The value for column 1, row 0. * @param {Number} [column2Row0=0.0] The value for column 2, row 0. * @param {Number} [column3Row0=0.0] The value for column 3, row 0. * @param {Number} [column0Row1=0.0] The value for column 0, row 1. * @param {Number} [column1Row1=0.0] The value for column 1, row 1. * @param {Number} [column2Row1=0.0] The value for column 2, row 1. * @param {Number} [column3Row1=0.0] The value for column 3, row 1. * @param {Number} [column0Row2=0.0] The value for column 0, row 2. * @param {Number} [column1Row2=0.0] The value for column 1, row 2. * @param {Number} [column2Row2=0.0] The value for column 2, row 2. * @param {Number} [column3Row2=0.0] The value for column 3, row 2. * @param {Number} [column0Row3=0.0] The value for column 0, row 3. * @param {Number} [column1Row3=0.0] The value for column 1, row 3. * @param {Number} [column2Row3=0.0] The value for column 2, row 3. * @param {Number} [column3Row3=0.0] The value for column 3, row 3. * * @see Matrix4.fromColumnMajorArray * @see Matrix4.fromRowMajorArray * @see Matrix4.fromRotationTranslation * @see Matrix4.fromTranslationQuaternionRotationScale * @see Matrix4.fromTranslation * @see Matrix4.fromScale * @see Matrix4.fromUniformScale * @see Matrix4.fromCamera * @see Matrix4.computePerspectiveFieldOfView * @see Matrix4.computeOrthographicOffCenter * @see Matrix4.computePerspectiveOffCenter * @see Matrix4.computeInfinitePerspectiveOffCenter * @see Matrix4.computeViewportTransformation * @see Matrix2 * @see Matrix3 * @see Packable */ public struct Matrix4 { fileprivate (set) internal var simdType: double4x4 var floatRepresentation: float4x4 { return float4x4([ simd_float(simdType[0]), simd_float(simdType[1]), simd_float(simdType[2]), simd_float(simdType[3]) ]) } public init( _ column0Row0: Double, _ column1Row0: Double, _ column2Row0: Double, _ column3Row0: Double, _ column0Row1: Double, _ column1Row1: Double, _ column2Row1: Double, _ column3Row1: Double, _ column0Row2: Double, _ column1Row2: Double, _ column2Row2: Double, _ column3Row2: Double, _ column0Row3: Double, _ column1Row3: Double, _ column2Row3: Double, _ column3Row3: Double) { simdType = double4x4(rows: [ double4(column0Row0, column1Row0, column2Row0, column3Row0), double4(column0Row1, column1Row1, column2Row1, column3Row1), double4(column0Row2, column1Row2, column2Row2, column3Row2), double4(column0Row3, column1Row3, column2Row3, column3Row3) ]) } public init(grid: [Double]) { assert(grid.count >= Matrix4.packedLength(), "invalid grid length") self.init( grid[0], grid[1], grid[2], grid[3], grid[4], grid[5], grid[6], grid[7], grid[8], grid[9], grid[10], grid[11], grid[12], grid[13], grid[14], grid[15] ) } public init (simd: double4x4) { simdType = simd } public init (_ scalar: Double = 0.0) { simdType = double4x4(scalar) } public init (diagonal: double4) { simdType = double4x4(diagonal: diagonal) } /* /** * Creates a Matrix4 from 16 consecutive elements in an array. * @function * * @param {Number[]} array The array whose 16 consecutive elements correspond to the positions of the matrix. Assumes column-major order. * @param {Number} [startingIndex=0] The offset into the array of the first element, which corresponds to first column first row position in the matrix. * @param {Matrix4} [result] The object onto which to store the result. * @returns {Matrix4} The modified result parameter or a new Matrix4 instance if one was not provided. * * @example * // Create the Matrix4: * // [1.0, 2.0, 3.0, 4.0] * // [1.0, 2.0, 3.0, 4.0] * // [1.0, 2.0, 3.0, 4.0] * // [1.0, 2.0, 3.0, 4.0] * * var v = [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0]; * var m = Cesium.Matrix4.fromArray(v); * * // Create same Matrix4 with using an offset into an array * var v2 = [0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0]; * var m2 = Cesium.Matrix4.fromArray(v2, 2); */ Matrix4.fromArray = Matrix4.unpack; /** * Computes a Matrix4 instance from a column-major order array. * * @param {Number[]} values The column-major order array. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created. * @returns The modified result parameter, or a new Matrix4 instance if one was not provided. */ Matrix4.fromColumnMajorArray = function(values, result) { //>>includeStart('debug', pragmas.debug); if (!defined(values)) { throw new DeveloperError('values is required'); } //>>includeEnd('debug'); assert(grid.count == 16, "Invalid source array") self.init(rows: [ double4(grid[0], grid[1], grid[2], grid[3]), double4(grid[4], grid[5], grid[6], grid[7]), double4(grid[8], grid[9], grid[10], grid[11]), double4(grid[12], grid[13], grid[14], grid[15]) ]) }}; */ /** * Computes a Matrix4 instance from a row-major order array. * The resulting matrix will be in column-major order. * * @param {Number[]} values The row-major order array. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created. * @returns The modified result parameter, or a new Matrix4 instance if one was not provided. */ init(rowMajorArray grid: [Double]) { self.init(grid: grid) } /** * Computes a Matrix4 instance from a Matrix3 representing the rotation * and a Cartesian3 representing the translation. * * @param {Matrix3} rotation The upper left portion of the matrix representing the rotation. * @param {Cartesian3} [translation=Cartesian3.ZERO] The upper right portion of the matrix representing the translation. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created. * @returns The modified result parameter, or a new Matrix4 instance if one was not provided. */ init (rotation: Matrix3, translation: Cartesian3 = Cartesian3.zero) { self.init( rotation[0,0], rotation[1,0], rotation[2,0], translation.x, rotation[0,1], rotation[1,1], rotation[2,1], translation.y, rotation[0,2], rotation[1,2], rotation[2,2], translation.z, 0.0, 0.0, 0.0, 1.0 ) } /* var scratchTrsRotation = new Matrix3(); /** * Computes a Matrix4 instance from a translation, rotation, and scale (TRS) * representation with the rotation represented as a quaternion. * * @param {Cartesian3} translation The translation transformation. * @param {Quaternion} rotation The rotation transformation. * @param {Cartesian3} scale The non-uniform scale transformation. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created. * @returns The modified result parameter, or a new Matrix4 instance if one was not provided. * * @example * result = Cesium.Matrix4.fromTranslationQuaternionRotationScale( * new Cesium.Cartesian3(1.0, 2.0, 3.0), // translation * Cesium.Quaternion.IDENTITY, // rotation * new Cesium.Cartesian3(7.0, 8.0, 9.0), // scale * result); */ Matrix4.fromTranslationQuaternionRotationScale = function(translation, rotation, scale, result) { //>>includeStart('debug', pragmas.debug); if (!defined(translation)) { throw new DeveloperError('translation is required.'); } if (!defined(rotation)) { throw new DeveloperError('rotation is required.'); } if (!defined(scale)) { throw new DeveloperError('scale is required.'); } //>>includeEnd('debug'); if (!defined(result)) { result = new Matrix4(); } var scaleX = scale.x; var scaleY = scale.y; var scaleZ = scale.z; var x2 = rotation.x * rotation.x; var xy = rotation.x * rotation.y; var xz = rotation.x * rotation.z; var xw = rotation.x * rotation.w; var y2 = rotation.y * rotation.y; var yz = rotation.y * rotation.z; var yw = rotation.y * rotation.w; var z2 = rotation.z * rotation.z; var zw = rotation.z * rotation.w; var w2 = rotation.w * rotation.w; var m00 = x2 - y2 - z2 + w2; var m01 = 2.0 * (xy - zw); var m02 = 2.0 * (xz + yw); var m10 = 2.0 * (xy + zw); var m11 = -x2 + y2 - z2 + w2; var m12 = 2.0 * (yz - xw); var m20 = 2.0 * (xz - yw); var m21 = 2.0 * (yz + xw); var m22 = -x2 - y2 + z2 + w2; result[0] = m00 * scaleX; result[1] = m10 * scaleX; result[2] = m20 * scaleX; result[3] = 0.0; result[4] = m01 * scaleY; result[5] = m11 * scaleY; result[6] = m21 * scaleY; result[7] = 0.0; result[8] = m02 * scaleZ; result[9] = m12 * scaleZ; result[10] = m22 * scaleZ; result[11] = 0.0; result[12] = translation.x; result[13] = translation.y; result[14] = translation.z; result[15] = 1.0; return result; }; */ /** * Creates a Matrix4 instance from a Cartesian3 representing the translation. * * @param {Cartesian3} translation The upper right portion of the matrix representing the translation. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created. * @returns The modified result parameter, or a new Matrix4 instance if one was not provided. * * @see Matrix4.multiplyByTranslation */ init (translation: Cartesian3) { self.init(rotation: Matrix3.identity, translation: translation) } /** * Computes a Matrix4 instance representing a non-uniform scale. * * @param {Cartesian3} scale The x, y, and z scale factors. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created. * @returns The modified result parameter, or a new Matrix4 instance if one was not provided. * * @example * // Creates * // [7.0, 0.0, 0.0, 0.0] * // [0.0, 8.0, 0.0, 0.0] * // [0.0, 0.0, 9.0, 0.0] * // [0.0, 0.0, 0.0, 1.0] * var m = Cesium.Matrix4.fromScale(new Cartesian3(7.0, 8.0, 9.0)); */ init (scale: Cartesian3) { let diagonal = double4([scale.simdType.x, scale.simdType.y, scale.simdType.z, 1.0]) self.simdType = double4x4(diagonal: diagonal) /*Matrix4( scale.x, 0.0, 0.0, 0.0, 0.0, scale.y, 0.0, 0.0, 0.0, 0.0, scale.z, 0.0, 0.0, 0.0, 0.0, 1.0);*/ } /* /** * Computes a Matrix4 instance representing a uniform scale. * * @param {Number} scale The uniform scale factor. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created. * @returns The modified result parameter, or a new Matrix4 instance if one was not provided. * * @example * // Creates * // [2.0, 0.0, 0.0, 0.0] * // [0.0, 2.0, 0.0, 0.0] * // [0.0, 0.0, 2.0, 0.0] * // [0.0, 0.0, 0.0, 1.0] * var m = Cesium.Matrix4.fromScale(2.0); */ Matrix4.fromUniformScale = function(scale, result) { //>>includeStart('debug', pragmas.debug); if (typeof scale !== 'number') { throw new DeveloperError('scale is required.'); } //>>includeEnd('debug'); if (!defined(result)) { return new Matrix4(scale, 0.0, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, 0.0, scale, 0.0, 0.0, 0.0, 0.0, 1.0); } result[0] = scale; result[1] = 0.0; result[2] = 0.0; result[3] = 0.0; result[4] = 0.0; result[5] = scale; result[6] = 0.0; result[7] = 0.0; result[8] = 0.0; result[9] = 0.0; result[10] = scale; result[11] = 0.0; result[12] = 0.0; result[13] = 0.0; result[14] = 0.0; result[15] = 1.0; return result; }; var fromCameraF = new Cartesian3(); var fromCameraS = new Cartesian3(); var fromCameraU = new Cartesian3(); /** * Computes a Matrix4 instance from a Camera. * * @param {Camera} camera The camera to use. * @param {Matrix4} [result] The object in which the result will be stored, if undefined a new instance will be created. * @returns The modified result parameter, or a new Matrix4 instance if one was not provided. */ Matrix4.fromCamera = function(camera, result) { //>>includeStart('debug', pragmas.debug); if (!defined(camera)) { throw new DeveloperError('camera is required.'); } //>>includeEnd('debug'); var eye = camera.eye; var target = camera.target; var up = camera.up; //>>includeStart('debug', pragmas.debug); if (!defined(eye)) { throw new DeveloperError('camera.eye is required.'); } if (!defined(target)) { throw new DeveloperError('camera.target is required.'); } if (!defined(up)) { throw new DeveloperError('camera.up is required.'); } //>>includeEnd('debug'); Cartesian3.normalize(Cartesian3.subtract(target, eye, fromCameraF), fromCameraF); Cartesian3.normalize(Cartesian3.cross(fromCameraF, up, fromCameraS), fromCameraS); Cartesian3.normalize(Cartesian3.cross(fromCameraS, fromCameraF, fromCameraU), fromCameraU); var sX = fromCameraS.x; var sY = fromCameraS.y; var sZ = fromCameraS.z; var fX = fromCameraF.x; var fY = fromCameraF.y; var fZ = fromCameraF.z; var uX = fromCameraU.x; var uY = fromCameraU.y; var uZ = fromCameraU.z; var eyeX = eye.x; var eyeY = eye.y; var eyeZ = eye.z; var t0 = sX * -eyeX + sY * -eyeY+ sZ * -eyeZ; var t1 = uX * -eyeX + uY * -eyeY+ uZ * -eyeZ; var t2 = fX * eyeX + fY * eyeY + fZ * eyeZ; //The code below this comment is an optimized //version of the commented lines. //Rather that create two matrices and then multiply, //we just bake in the multiplcation as part of creation. //var rotation = new Matrix4( // sX, sY, sZ, 0.0, // uX, uY, uZ, 0.0, // -fX, -fY, -fZ, 0.0, // 0.0, 0.0, 0.0, 1.0); //var translation = new Matrix4( // 1.0, 0.0, 0.0, -eye.x, // 0.0, 1.0, 0.0, -eye.y, // 0.0, 0.0, 1.0, -eye.z, // 0.0, 0.0, 0.0, 1.0); //return rotation.multiply(translation); if (!defined(result)) { return new Matrix4( sX, sY, sZ, t0, uX, uY, uZ, t1, -fX, -fY, -fZ, t2, 0.0, 0.0, 0.0, 1.0); } result[0] = sX; result[1] = uX; result[2] = -fX; result[3] = 0.0; result[4] = sY; result[5] = uY; result[6] = -fY; result[7] = 0.0; result[8] = sZ; result[9] = uZ; result[10] = -fZ; result[11] = 0.0; result[12] = t0; result[13] = t1; result[14] = t2; result[15] = 1.0; return result; }; */ public subscript (column: Int) -> Cartesian4 { return Cartesian4(simd: simdType[column]) } /// Access to individual elements. public subscript (column: Int, row: Int) -> Double { return simdType[column][row] } /* /** * Computes a Matrix4 instance representing a perspective transformation matrix. * * @param {Number} fovY The field of view along the Y axis in radians. * @param {Number} aspectRatio The aspect ratio. * @param {Number} near The distance to the near plane in meters. * @param {Number} far The distance to the far plane in meters. * @param {Matrix4} result The object in which the result will be stored. * @returns The modified result parameter. * * @exception {DeveloperError} fovY must be in [0, PI). * @exception {DeveloperError} aspectRatio must be greater than zero. * @exception {DeveloperError} near must be greater than zero. * @exception {DeveloperError} far must be greater than zero. */ Matrix4.computePerspectiveFieldOfView = function(fovY, aspectRatio, near, far, result) { //>>includeStart('debug', pragmas.debug); if (fovY <= 0.0 || fovY > Math.PI) { throw new DeveloperError('fovY must be in [0, PI).'); } if (aspectRatio <= 0.0) { throw new DeveloperError('aspectRatio must be greater than zero.'); } if (near <= 0.0) { throw new DeveloperError('near must be greater than zero.'); } if (far <= 0.0) { throw new DeveloperError('far must be greater than zero.'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); var bottom = Math.tan(fovY * 0.5); var column1Row1 = 1.0 / bottom; var column0Row0 = column1Row1 / aspectRatio; var column2Row2 = (far + near) / (near - far); var column3Row2 = (2.0 * far * near) / (near - far); result[0] = column0Row0; result[1] = 0.0; result[2] = 0.0; result[3] = 0.0; result[4] = 0.0; result[5] = column1Row1; result[6] = 0.0; result[7] = 0.0; result[8] = 0.0; result[9] = 0.0; result[10] = column2Row2; result[11] = -1.0; result[12] = 0.0; result[13] = 0.0; result[14] = column3Row2; result[15] = 0.0; return result; }; */ /** * Computes a Matrix4 instance representing an orthographic transformation matrix. * * @param {Number} left The number of meters to the left of the camera that will be in view. * @param {Number} right The number of meters to the right of the camera that will be in view. * @param {Number} bottom The number of meters below of the camera that will be in view. * @param {Number} top The number of meters above of the camera that will be in view. * @param {Number} near The distance to the near plane in meters. * @param {Number} far The distance to the far plane in meters. * @param {Matrix4} result The object in which the result will be stored. * @returns The modified result parameter. */ static func computeOrthographicOffCenter (left: Double, right: Double, bottom: Double, top: Double, near: Double = 0.0, far: Double = 1.0) -> Matrix4 { // Converted to Metal NDC coordinates - z: [0-1] // https://msdn.microsoft.com/en-us/library/windows/desktop/bb205348(v=vs.85).aspx let a = 2.0 / (right - left) let b = 2.0 / (top - bottom) let c = 1.0 / (far - near) let tx = (right + left) / (left - right) let ty = (top + bottom) / (bottom - top) let tz = near / (far - near) return Matrix4( a, 0.0, 0.0, tx, 0.0, b, 0.0, ty, 0.0, 0.0, c, tz, 0.0, 0.0, 0.0, 1.0) } /** * Computes a Matrix4 instance representing an off center perspective transformation. * * @param {Number} left The number of meters to the left of the camera that will be in view. * @param {Number} right The number of meters to the right of the camera that will be in view. * @param {Number} bottom The number of meters below of the camera that will be in view. * @param {Number} top The number of meters above of the camera that will be in view. * @param {Number} near The distance to the near plane in meters. * @param {Number} far The distance to the far plane in meters. * @param {Matrix4} result The object in which the result will be stored. * @returns The modified result parameter. */ static func computePerspectiveOffCenter (left: Double, right: Double, bottom: Double, top: Double, near: Double, far: Double) -> Matrix4 { // Converted to Metal NDC coordinates - z: [0-1] // https://msdn.microsoft.com/en-us/library/windows/desktop/bb205354(v=vs.85).aspx let column0Row0 = 2.0 * near / (right - left) // w let column1Row1 = 2.0 * near / (top - bottom) // h let column2Row0 = (left + right) / (right - left) let column2Row1 = (top + bottom) / (top - bottom) let column2Row2 = far / (near - far) // Q let column3Row2 = near * far / (near - far) return Matrix4( column0Row0, 0.0, column2Row0, 0.0, 0.0, column1Row1, column2Row1, 0.0, 0.0, 0.0, column2Row2, column3Row2, 0.0, 0.0, -1.0, 0.0) } /** * Computes a Matrix4 instance representing an infinite off center perspective transformation. * * @param {Number} left The number of meters to the left of the camera that will be in view. * @param {Number} right The number of meters to the right of the camera that will be in view. * @param {Number} bottom The number of meters below of the camera that will be in view. * @param {Number} top The number of meters above of the camera that will be in view. * @param {Number} near The distance to the near plane in meters. * @param {Matrix4} result The object in which the result will be stored. * @returns The modified result parameter. */ static func computeInfinitePerspectiveOffCenter (left: Double, right: Double, bottom: Double, top: Double, near: Double) -> Matrix4 { //assertionFailure("not updated for metal NDC") let column0Row0 = 2.0 * near / (right - left) let column1Row1 = 2.0 * near / (top - bottom) let column2Row0 = (right + left) / (right - left) let column2Row1 = (top + bottom) / (top - bottom) let column2Row2 = -1.0 let column2Row3 = -1.0 let column3Row2 = -2.0 * near return Matrix4( column0Row0, 0.0, column2Row0, 0.0, 0.0, column1Row1, column2Row1, 0.0, 0.0, 0.0, column2Row2, column3Row2, 0.0, 0.0, column2Row3, 0.0) } /** * Computes a Matrix4 instance that transforms from normalized device coordinates to window coordinates. * * @param {Object}[viewport = { x : 0.0, y : 0.0, width : 0.0, height : 0.0 }] The viewport's corners as shown in Example 1. * @param {Number}[nearDepthRange=0.0] The near plane distance in window coordinates. * @param {Number}[farDepthRange=1.0] The far plane distance in window coordinates. * @param {Matrix4} result The object in which the result will be stored. * @returns The modified result parameter. * * @example * // Example 1. Create viewport transformation using an explicit viewport and depth range. * var m = Cesium.Matrix4.computeViewportTransformation({ * x : 0.0, * y : 0.0, * width : 1024.0, * height : 768.0 * }, 0.0, 1.0); * * @example * // Example 2. Create viewport transformation using the context's viewport. * var m = Cesium.Matrix4.computeViewportTransformation(context.getViewport()); */ internal static func computeViewportTransformation (_ viewport: Cartesian4, nearDepthRange: Double = 0.0, farDepthRange: Double = 1.0) -> Matrix4 { let x = viewport.x let y = viewport.y let width = viewport.width let height = viewport.height let halfWidth = width * 0.5 let halfHeight = height * 0.5 let halfDepth = (farDepthRange - nearDepthRange) * 0.5 let column0Row0 = halfWidth let column1Row1 = halfHeight let column2Row2 = halfDepth let column3Row0 = x + halfWidth let column3Row1 = y + halfHeight let column3Row2 = nearDepthRange + halfDepth let column3Row3 = 1.0 return Matrix4( column0Row0, 0.0, 0.0, column3Row0, 0.0, column1Row1, 0.0, column3Row1, 0.0, 0.0, column2Row2, column3Row2, 0.0, 0.0, 0.0, column3Row3 ) } /* /** * Computes the array index of the element at the provided row and column. * * @param {Number} row The zero-based index of the row. * @param {Number} column The zero-based index of the column. * @returns {Number} The index of the element at the provided row and column. * * @exception {DeveloperError} row must be 0, 1, 2, or 3. * @exception {DeveloperError} column must be 0, 1, 2, or 3. * * @example * var myMatrix = new Cesium.Matrix4(); * var column1Row0Index = Cesium.Matrix4.getElementIndex(1, 0); * var column1Row0 = myMatrix[column1Row0Index] * myMatrix[column1Row0Index] = 10.0; */ Matrix4.getElementIndex = function(column, row) { //>>includeStart('debug', pragmas.debug); if (typeof row !== 'number' || row < 0 || row > 3) { throw new DeveloperError('row must be 0, 1, 2, or 3.'); } if (typeof column !== 'number' || column < 0 || column > 3) { throw new DeveloperError('column must be 0, 1, 2, or 3.'); } //>>includeEnd('debug'); return column * 4 + row; }; */ /** * Retrieves a copy of the matrix column at the provided index as a Cartesian4 instance. * * @param {Matrix4} matrix The matrix to use. * @param {Number} index The zero-based index of the column to retrieve. * @param {Cartesian4} result The object onto which to store the result. * @returns {Cartesian4} The modified result parameter. * * @exception {DeveloperError} index must be 0, 1, 2, or 3. * * @example * //returns a Cartesian4 instance with values from the specified column * // m = [10.0, 11.0, 12.0, 13.0] * // [14.0, 15.0, 16.0, 17.0] * // [18.0, 19.0, 20.0, 21.0] * // [22.0, 23.0, 24.0, 25.0] * * //Example 1: Creates an instance of Cartesian * var a = Cesium.Matrix4.getColumn(m, 2); * * @example * //Example 2: Sets values for Cartesian instance * var a = new Cesium.Cartesian4(); * Cesium.Matrix4.getColumn(m, 2, a); * * // a.x = 12.0; a.y = 16.0; a.z = 20.0; a.w = 24.0; */ func getColumn (_ index: Int) -> Cartesian4 { assert(index >= 0 && index <= 3, "index must be 0, 1, 2, or 3.") return Cartesian4(simd: simdType[index]) } /** * Computes a new matrix that replaces the specified column in the provided matrix with the provided Cartesian4 instance. * * @param {Matrix4} matrix The matrix to use. * @param {Number} index The zero-based index of the column to set. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified column. * @returns {Matrix4} The modified result parameter. * * @exception {DeveloperError} index must be 0, 1, 2, or 3. * * @example * //creates a new Matrix4 instance with new column values from the Cartesian4 instance * // m = [10.0, 11.0, 12.0, 13.0] * // [14.0, 15.0, 16.0, 17.0] * // [18.0, 19.0, 20.0, 21.0] * // [22.0, 23.0, 24.0, 25.0] * * var a = Cesium.Matrix4.setColumn(m, 2, new Cartesian4(99.0, 98.0, 97.0, 96.0)); * * // m remains the same * // a = [10.0, 11.0, 99.0, 13.0] * // [14.0, 15.0, 98.0, 17.0] * // [18.0, 19.0, 97.0, 21.0] * // [22.0, 23.0, 96.0, 25.0] */ func setColumn (_ index: Int, cartesian: Cartesian4) -> Matrix4 { assert(index >= 0 && index <= 3, "index must be 0, 1, 2, or 3.") var result = simdType result[index] = double4(cartesian.x, cartesian.y, cartesian.z, cartesian.w) return Matrix4(simd: result) } /** * Computes a new matrix that replaces the translation in the rightmost column of the provided * matrix with the provided translation. This assumes the matrix is an affine transformation * * @param {Matrix4} matrix The matrix to use. * @param {Cartesian3} translation The translation that replaces the translation of the provided matrix. * @param {Cartesian4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. */ func setTranslation (_ translation: Cartesian3) -> Matrix4 { var result = simdType result[3] = double4(translation.x, translation.y, translation.z, simdType[3].w) return Matrix4(simd: result) } /** * Retrieves a copy of the matrix row at the provided index as a Cartesian4 instance. * * @param {Matrix4} matrix The matrix to use. * @param {Number} index The zero-based index of the row to retrieve. * @param {Cartesian4} result The object onto which to store the result. * @returns {Cartesian4} The modified result parameter. * * @exception {DeveloperError} index must be 0, 1, 2, or 3. * * @example * //returns a Cartesian4 instance with values from the specified column * // m = [10.0, 11.0, 12.0, 13.0] * // [14.0, 15.0, 16.0, 17.0] * // [18.0, 19.0, 20.0, 21.0] * // [22.0, 23.0, 24.0, 25.0] * * //Example 1: Returns an instance of Cartesian * var a = Cesium.Matrix4.getRow(m, 2); * * @example * //Example 2: Sets values for a Cartesian instance * var a = new Cesium.Cartesian4(); * Cesium.Matrix4.getRow(m, 2, a); * * // a.x = 18.0; a.y = 19.0; a.z = 20.0; a.w = 21.0; */ func row (_ index: Int) -> Cartesian4 { assert(index >= 0 && index <= 3, "index must be 0, 1, 2, or 3.") return Cartesian4( x: self[0, index], y: self[1, index], z: self[2, index], w: self[3, index] ) } /** * Computes the product of two matrices. * * @param {MatrixType} self The first matrix. * @param {MatrixType} other The second matrix. * @returns {MatrixType} The modified result parameter. */ func multiply(_ other: Matrix4) -> Matrix4 { return Matrix4(simd: simdType * other.simdType) } func negate() -> Matrix4 { return Matrix4(simd: -simdType) } func transpose () -> Matrix4 { return Matrix4(simd: simdType.transpose) } /** * Compares this matrix to the provided matrix componentwise and returns * <code>true</code> if they are equal, <code>false</code> otherwise. * * @param {MatrixType} [right] The right hand side matrix. * @returns {Boolean} <code>true</code> if they are equal, <code>false</code> otherwise. */ func equals(_ other: Matrix4) -> Bool { return simd_equal(simdType, other.simdType) } /** * Compares the provided matrices componentwise and returns * <code>true</code> if they are within the provided epsilon, * <code>false</code> otherwise. * * @param {MatrixType} [left] The first matrix. * @param {MatrixType} [right] The second matrix. * @param {Number} epsilon The epsilon to use for equality testing. * @returns {Boolean} <code>true</code> if left and right are within the provided epsilon, <code>false</code> otherwise. */ func equalsEpsilon(_ other: Matrix4, epsilon: Double) -> Bool { return simd_almost_equal_elements(self.simdType, other.simdType, epsilon) } /* /** * Computes a new matrix that replaces the specified row in the provided matrix with the provided Cartesian4 instance. * * @param {Matrix4} matrix The matrix to use. * @param {Number} index The zero-based index of the row to set. * @param {Cartesian4} cartesian The Cartesian whose values will be assigned to the specified row. * @param {Cartesian4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. * * @exception {DeveloperError} index must be 0, 1, 2, or 3. * * @example * //create a new Matrix4 instance with new row values from the Cartesian4 instance * // m = [10.0, 11.0, 12.0, 13.0] * // [14.0, 15.0, 16.0, 17.0] * // [18.0, 19.0, 20.0, 21.0] * // [22.0, 23.0, 24.0, 25.0] * * var a = Cesium.Matrix4.setRow(m, 2, new Cartesian4(99.0, 98.0, 97.0, 96.0)); * * // m remains the same * // a = [10.0, 11.0, 12.0, 13.0] * // [14.0, 15.0, 16.0, 17.0] * // [99.0, 98.0, 97.0, 96.0] * // [22.0, 23.0, 24.0, 25.0] */ Matrix4.setRow = function(matrix, index, cartesian, result) { //>>includeStart('debug', pragmas.debug); if (!defined(matrix)) { throw new DeveloperError('matrix is required'); } if (!defined(cartesian)) { throw new DeveloperError('cartesian is required'); } if (typeof index !== 'number' || index < 0 || index > 3) { throw new DeveloperError('index must be 0, 1, 2, or 3.'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); result = Matrix4.clone(matrix, result); result[index] = cartesian.x; result[index + 4] = cartesian.y; result[index + 8] = cartesian.z; result[index + 12] = cartesian.w; return result; }; var scratchColumn = new Cartesian3(); /** * Extracts the non-uniform scale assuming the matrix is an affine transformation. * * @param {Matrix4} matrix The matrix. * @param {Cartesian3} result The object onto which to store the result. * @returns {Cartesian3} The modified result parameter */ Matrix4.getScale = function(matrix, result) { //>>includeStart('debug', pragmas.debug); if (!defined(matrix)) { throw new DeveloperError('matrix is required.'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); result.x = Cartesian3.magnitude(Cartesian3.fromElements(matrix[0], matrix[1], matrix[2], scratchColumn)); result.y = Cartesian3.magnitude(Cartesian3.fromElements(matrix[4], matrix[5], matrix[6], scratchColumn)); result.z = Cartesian3.magnitude(Cartesian3.fromElements(matrix[8], matrix[9], matrix[10], scratchColumn)); return result; }; var scratchScale = new Cartesian3(); /** * Computes the maximum scale assuming the matrix is an affine transformation. * The maximum scale is the maximum length of the column vectors in the upper-left * 3x3 matrix. * * @param {Matrix4} matrix The matrix. * @returns {Number} The maximum scale. */ Matrix4.getMaximumScale = function(matrix) { Matrix4.getScale(matrix, scratchScale); return Cartesian3.maximumComponent(scratchScale); }; */ /** * Computes the product of two matrices assuming the matrices are * affine transformation matrices, where the upper left 3x3 elements * are a rotation matrix, and the upper three elements in the fourth * column are the translation. The bottom row is assumed to be [0, 0, 0, 1]. * The matrix is not verified to be in the proper form. * This method is faster than computing the product for general 4x4 * matrices using {@link Matrix4.multiply}. * * @param {Matrix4} left The first matrix. * @param {Matrix4} right The second matrix. * @param {Matrix4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. * * @example * var m1 = new Cesium.Matrix4(1.0, 6.0, 7.0, 0.0, 2.0, 5.0, 8.0, 0.0, 3.0, 4.0, 9.0, 0.0, 0.0, 0.0, 0.0, 1.0]; * var m2 = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3(1.0, 1.0, 1.0)); * var m3 = Cesium.Matrix4.multiplyTransformation(m1, m2); */ /*func multiplyTransformation (other: Matrix4) -> Matrix4 { let this0 = _grid[0] let this1 = _grid[1] let this2 = _grid[2] let this4 = _grid[4] let this5 = _grid[5] let this6 = _grid[6] let this8 = _grid[8] let this9 = _grid[9] let this10 = _grid[10] let this12 = _grid[12] let this13 = _grid[13] let this14 = _grid[14] let other0 = other[0] let other1 = other[1] let other2 = other[2] let other4 = other[4] let other5 = other[5] let other6 = other[6] let other8 = other[8] let other9 = other[9] let other10 = other[10] let other12 = other[12] let other13 = other[13] let other14 = other[14] let column0Row0 = this0 * other0 + this4 * other1 + this8 * other2 let column0Row1 = this1 * other0 + this5 * other1 + this9 * other2 let column0Row2 = this2 * other0 + this6 * other1 + this10 * other2 let column1Row0 = this0 * other4 + this4 * other5 + this8 * other6 let column1Row1 = this1 * other4 + this5 * other5 + this9 * other6 let column1Row2 = this2 * other4 + this6 * other5 + this10 * other6 let column2Row0 = this0 * other8 + this4 * other9 + this8 * other10 let column2Row1 = this1 * other8 + this5 * other9 + this9 * other10 let column2Row2 = this2 * other8 + this6 * other9 + this10 * other10 let column3Row0 = this0 * other12 + this4 * other13 + this8 * other14 + this12 let column3Row1 = this1 * other12 + this5 * other13 + this9 * other14 + this13 let column3Row2 = this2 * other12 + this6 * other13 + this10 * other14 + this14 return Matrix4( column0Row0, column1Row0, column2Row0, column3Row0, column0Row1, column1Row1, column2Row1, column3Row1, column0Row2, column1Row2, column2Row2, column3Row2, 0.0, 0.0, 0.0, 1.0 ) }*/ /* /** * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>) * by a 3x3 rotation matrix. This is an optimization * for <code>Matrix4.multiply(m, Matrix4.fromRotationTranslation(rotation), m);</code> with less allocations and arithmetic operations. * * @param {Matrix4} matrix The matrix on the left-hand side. * @param {Matrix3} rotation The 3x3 rotation matrix on the right-hand side. * @param {Matrix4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. * * @example * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromRotationTranslation(rotation), m); * Cesium.Matrix4.multiplyByMatrix3(m, rotation, m); */ Matrix4.multiplyByMatrix3 = function(matrix, rotation, result) { //>>includeStart('debug', pragmas.debug); if (!defined(matrix)) { throw new DeveloperError('matrix is required'); } if (!defined(rotation)) { throw new DeveloperError('rotation is required'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); var left0 = matrix[0]; var left1 = matrix[1]; var left2 = matrix[2]; var left4 = matrix[4]; var left5 = matrix[5]; var left6 = matrix[6]; var left8 = matrix[8]; var left9 = matrix[9]; var left10 = matrix[10]; var right0 = rotation[0]; var right1 = rotation[1]; var right2 = rotation[2]; var right4 = rotation[3]; var right5 = rotation[4]; var right6 = rotation[5]; var right8 = rotation[6]; var right9 = rotation[7]; var right10 = rotation[8]; var column0Row0 = left0 * right0 + left4 * right1 + left8 * right2; var column0Row1 = left1 * right0 + left5 * right1 + left9 * right2; var column0Row2 = left2 * right0 + left6 * right1 + left10 * right2; var column1Row0 = left0 * right4 + left4 * right5 + left8 * right6; var column1Row1 = left1 * right4 + left5 * right5 + left9 * right6; var column1Row2 = left2 * right4 + left6 * right5 + left10 * right6; var column2Row0 = left0 * right8 + left4 * right9 + left8 * right10; var column2Row1 = left1 * right8 + left5 * right9 + left9 * right10; var column2Row2 = left2 * right8 + left6 * right9 + left10 * right10; result[0] = column0Row0; result[1] = column0Row1; result[2] = column0Row2; result[3] = 0.0; result[4] = column1Row0; result[5] = column1Row1; result[6] = column1Row2; result[7] = 0.0; result[8] = column2Row0; result[9] = column2Row1; result[10] = column2Row2; result[11] = 0.0; result[12] = matrix[12]; result[13] = matrix[13]; result[14] = matrix[14]; result[15] = matrix[15]; return result; }; /** * Multiplies an affine transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>) * by an implicit non-uniform scale matrix. This is an optimization * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code>, where * <code>m</code> must be an affine matrix. * This function performs fewer allocations and arithmetic operations. * * @param {Matrix4} matrix The matrix on the left-hand side. * @param {Cartesian3} translation The translation on the right-hand side. * @param {Matrix4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. * * @example * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromTranslation(position), m); * Cesium.Matrix4.multiplyByTranslation(m, position, m); */ Matrix4.multiplyByTranslation = function(matrix, translation, result) { //>>includeStart('debug', pragmas.debug); if (!defined(matrix)) { throw new DeveloperError('matrix is required'); } if (!defined(translation)) { throw new DeveloperError('translation is required'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); var x = translation.x; var y = translation.y; var z = translation.z; var tx = (x * matrix[0]) + (y * matrix[4]) + (z * matrix[8]) + matrix[12]; var ty = (x * matrix[1]) + (y * matrix[5]) + (z * matrix[9]) + matrix[13]; var tz = (x * matrix[2]) + (y * matrix[6]) + (z * matrix[10]) + matrix[14]; result[0] = matrix[0]; result[1] = matrix[1]; result[2] = matrix[2]; result[3] = matrix[3]; result[4] = matrix[4]; result[5] = matrix[5]; result[6] = matrix[6]; result[7] = matrix[7]; result[8] = matrix[8]; result[9] = matrix[9]; result[10] = matrix[10]; result[11] = matrix[11]; result[12] = tx; result[13] = ty; result[14] = tz; result[15] = matrix[15]; return result; }; var uniformScaleScratch = new Cartesian3(); /** * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>) * by an implicit uniform scale matrix. This is an optimization * for <code>Matrix4.multiply(m, Matrix4.fromUniformScale(scale), m);</code> with less allocations and arithmetic operations. * * @param {Matrix4} matrix The matrix on the left-hand side. * @param {Number} scale The uniform scale on the right-hand side. * @param {Matrix4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. * * @see Matrix4.fromUniformScale * @see Matrix4.multiplyByScale * * @example * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromUniformScale(scale), m); * Cesium.Matrix4.multiplyByUniformScale(m, scale, m); */ Matrix4.multiplyByUniformScale = function(matrix, scale, result) { //>>includeStart('debug', pragmas.debug); if (!defined(matrix)) { throw new DeveloperError('matrix is required'); } if (typeof scale !== 'number') { throw new DeveloperError('scale is required'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); uniformScaleScratch.x = scale; uniformScaleScratch.y = scale; uniformScaleScratch.z = scale; return Matrix4.multiplyByScale(matrix, uniformScaleScratch, result); }; /** * Multiplies a transformation matrix (with a bottom row of <code>[0.0, 0.0, 0.0, 1.0]</code>) * by an implicit non-uniform scale matrix. This is an optimization * for <code>Matrix4.multiply(m, Matrix4.fromScale(scale), m);</code> with less allocations and arithmetic operations. * * @param {Matrix4} matrix The matrix on the left-hand side. * @param {Cartesian3} scale The non-uniform scale on the right-hand side. * @param {Matrix4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. * * @see Matrix4.fromScale * @see Matrix4.multiplyByUniformScale * * @example * // Instead of Cesium.Matrix4.multiply(m, Cesium.Matrix4.fromScale(scale), m); * Cesium.Matrix4.multiplyByUniformScale(m, scale, m); */ Matrix4.multiplyByScale = function(matrix, scale, result) { //>>includeStart('debug', pragmas.debug); if (!defined(matrix)) { throw new DeveloperError('matrix is required'); } if (!defined(scale)) { throw new DeveloperError('scale is required'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); var scaleX = scale.x; var scaleY = scale.y; var scaleZ = scale.z; // Faster than Cartesian3.equals if ((scaleX === 1.0) && (scaleY === 1.0) && (scaleZ === 1.0)) { return Matrix4.clone(matrix, result); } result[0] = scaleX * matrix[0]; result[1] = scaleX * matrix[1]; result[2] = scaleX * matrix[2]; result[3] = 0.0; result[4] = scaleY * matrix[4]; result[5] = scaleY * matrix[5]; result[6] = scaleY * matrix[6]; result[7] = 0.0; result[8] = scaleZ * matrix[8]; result[9] = scaleZ * matrix[9]; result[10] = scaleZ * matrix[10]; result[11] = 0.0; result[12] = matrix[12]; result[13] = matrix[13]; result[14] = matrix[14]; result[15] = 1.0; return result; }; */ /** * Computes the product of a matrix and a column vector. * * @param {Matrix4} matrix The matrix. * @param {Cartesian4} cartesian The vector. * @param {Cartesian4} result The object onto which to store the result. * @returns {Cartesian4} The modified result parameter. */ func multiplyByVector(_ cartesian: Cartesian4) -> Cartesian4 { return Cartesian4(simd: self.simdType * cartesian.simdType) } /** * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector} * with a {@link Cartesian4} with a <code>w</code> component of zero. * * @param {Matrix4} matrix The matrix. * @param {Cartesian3} cartesian The point. * @param {Cartesian3} result The object onto which to store the result. * @returns {Cartesian3} The modified result parameter. * * @example * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0); * Cesium.Matrix4.multiplyByPointAsVector(matrix, p, result); * // A shortcut for * // Cartesian3 p = ... * // Cesium.Matrix4.multiplyByVector(matrix, new Cesium.Cartesian4(p.x, p.y, p.z, 0.0), result); */ func multiplyByPointAsVector (_ cartesian: Cartesian3) -> Cartesian3 { let vector = simdType * double4(cartesian.x, cartesian.y, cartesian.z, 0.0) return Cartesian3(x: vector.x, y: vector.y, z: vector.z) } /** * Computes the product of a matrix and a {@link Cartesian3}. This is equivalent to calling {@link Matrix4.multiplyByVector} * with a {@link Cartesian4} with a <code>w</code> component of 1, but returns a {@link Cartesian3} instead of a {@link Cartesian4}. * * @param {Matrix4} matrix The matrix. * @param {Cartesian3} cartesian The point. * @param {Cartesian3} result The object onto which to store the result. * @returns {Cartesian3} The modified result parameter. * * @example * var p = new Cesium.Cartesian3(1.0, 2.0, 3.0); * Cesium.Matrix4.multiplyByPoint(matrix, p, result); */ func multiplyByPoint (_ cartesian: Cartesian3) -> Cartesian3 { let vector = simdType * double4(cartesian.x, cartesian.y, cartesian.z, 1.0) return Cartesian3(x: vector.x, y: vector.y, z: vector.z) } /* /** * Computes the product of a matrix and a scalar. * * @param {Matrix4} matrix The matrix. * @param {Number} scalar The number to multiply by. * @param {Matrix4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. * * @example * //create a Matrix4 instance which is a scaled version of the supplied Matrix4 * // m = [10.0, 11.0, 12.0, 13.0] * // [14.0, 15.0, 16.0, 17.0] * // [18.0, 19.0, 20.0, 21.0] * // [22.0, 23.0, 24.0, 25.0] * * var a = Cesium.Matrix4.multiplyBy(scalar: m, -2); * * // m remains the same * // a = [-20.0, -22.0, -24.0, -26.0] * // [-28.0, -30.0, -32.0, -34.0] * // [-36.0, -38.0, -40.0, -42.0] * // [-44.0, -46.0, -48.0, -50.0] */ Matrix4.multiplyByScalar = function(matrix, scalar, result) { //>>includeStart('debug', pragmas.debug); if (!defined(matrix)) { throw new DeveloperError('matrix is required'); } if (typeof scalar !== 'number') { throw new DeveloperError('scalar must be a number'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); result[0] = matrix[0] * scalar; result[1] = matrix[1] * scalar; result[2] = matrix[2] * scalar; result[3] = matrix[3] * scalar; result[4] = matrix[4] * scalar; result[5] = matrix[5] * scalar; result[6] = matrix[6] * scalar; result[7] = matrix[7] * scalar; result[8] = matrix[8] * scalar; result[9] = matrix[9] * scalar; result[10] = matrix[10] * scalar; result[11] = matrix[11] * scalar; result[12] = matrix[12] * scalar; result[13] = matrix[13] * scalar; result[14] = matrix[14] * scalar; result[15] = matrix[15] * scalar; return result; }; /** * Computes a matrix, which contains the absolute (unsigned) values of the provided matrix's elements. * * @param {Matrix4} matrix The matrix with signed elements. * @param {Matrix4} result The object onto which to store the result. * @returns {Matrix4} The modified result parameter. */ Matrix4.abs = function(matrix, result) { //>>includeStart('debug', pragmas.debug); if (!defined(matrix)) { throw new DeveloperError('matrix is required'); } if (!defined(result)) { throw new DeveloperError('result is required,'); } //>>includeEnd('debug'); result[0] = Math.abs(matrix[0]); result[1] = Math.abs(matrix[1]); result[2] = Math.abs(matrix[2]); result[3] = Math.abs(matrix[3]); result[4] = Math.abs(matrix[4]); result[5] = Math.abs(matrix[5]); result[6] = Math.abs(matrix[6]); result[7] = Math.abs(matrix[7]); result[8] = Math.abs(matrix[8]); result[9] = Math.abs(matrix[9]); result[10] = Math.abs(matrix[10]); result[11] = Math.abs(matrix[11]); result[12] = Math.abs(matrix[12]); result[13] = Math.abs(matrix[13]); result[14] = Math.abs(matrix[14]); result[15] = Math.abs(matrix[15]); return result; }; */ /** * Gets the translation portion of the provided matrix, assuming the matrix is a affine transformation matrix. * * @param {Matrix4} matrix The matrix to use. * @param {Cartesian3} result The object onto which to store the result. * @returns {Cartesian3} The modified result parameter. */ var translation: Cartesian3 { let column3 = simdType[3] return Cartesian3(x: column3.x, y: column3.y, z: column3.z) } /** * Gets the upper left 3x3 rotation matrix of the provided matrix, assuming the matrix is a affine transformation matrix. * * @param {Matrix4} matrix The matrix to use. * @param {Matrix3} result The object onto which to store the result. * @returns {Matrix3} The modified result parameter. * * @example * // returns a Matrix3 instance from a Matrix4 instance * * // m = [10.0, 14.0, 18.0, 22.0] * // [11.0, 15.0, 19.0, 23.0] * // [12.0, 16.0, 20.0, 24.0] * // [13.0, 17.0, 21.0, 25.0] * * var b = new Cesium.Matrix3(); * Cesium.Matrix4.getRotation(m,b); * * // b = [10.0, 14.0, 18.0] * // [11.0, 15.0, 19.0] * // [12.0, 16.0, 20.0] */ var rotation: Matrix3 { let column0 = simdType[0] let column1 = simdType[1] let column2 = simdType[2] return Matrix3( column0.x, column1.x, column2.x, column0.y, column1.y, column2.y, column0.z, column1.z, column2.z) } var inverse: Matrix4 { // Special case for a zero scale matrix that can occur, for example, // when a model's node has a [0, 0, 0] scale. if rotation.equalsEpsilon(Matrix3.zero, epsilon: Math.Epsilon7) && self[3] == Cartesian4.unitW { return Matrix4(simd: double4x4([ double4(), double4(), double4(), double4(self[3,0], self[3,1], self[3,2], 1.0)]) ) /*result[0] = 0.0; result[1] = 0.0; result[2] = 0.0; result[3] = 0.0; result[4] = 0.0; result[5] = 0.0; result[6] = 0.0; result[7] = 0.0; result[8] = 0.0; result[9] = 0.0; result[10] = 0.0; result[11] = 0.0; result[12] = -matrix[12]; result[13] = -matrix[13]; result[14] = -matrix[14]; result[15] = 1.0; return result;*/ } return Matrix4(simd: simdType.inverse) } /** * An immutable Matrix4 instance initialized to the identity matrix. * * @type {Matrix4} * @constant */ public static let identity = Matrix4(1.0) public static let zero = Matrix4() /** * @private */ func equalsArray (_ array: [Float], offset: Int) -> Bool { let other = Matrix4.unpack(array, startingIndex: offset) return self == other } } extension Matrix4: Packable { var length: Int { return Matrix4.packedLength() } static func packedLength () -> Int { return 16 } init(array: [Double], startingIndex: Int = 0) { self.init() assert(checkPackedArrayLength(array, startingIndex: startingIndex), "Invalid packed array length") _ = array.withUnsafeBufferPointer { (pointer: UnsafeBufferPointer<Double>) in memcpy(&self, pointer.baseAddress, Matrix4.packedLength() * MemoryLayout<Double>.stride) } } } extension Matrix4: Equatable {} /** * Compares the provided matrices componentwise and returns * <code>true</code> if they are equal, <code>false</code> otherwise. * * @param {Matrix4} [left] The first matrix. * @param {Matrix4} [right] The second matrix. * @returns {Boolean} <code>true</code> if left and right are equal, <code>false</code> otherwise. * * @example * //compares two Matrix4 instances * * // a = [10.0, 14.0, 18.0, 22.0] * // [11.0, 15.0, 19.0, 23.0] * // [12.0, 16.0, 20.0, 24.0] * // [13.0, 17.0, 21.0, 25.0] * * // b = [10.0, 14.0, 18.0, 22.0] * // [11.0, 15.0, 19.0, 23.0] * // [12.0, 16.0, 20.0, 24.0] * // [13.0, 17.0, 21.0, 25.0] * * if(Cesium.Matrix4.equals(a,b)) { * console.log("Both matrices are equal"); * } else { * console.log("They are not equal"); * } * * //Prints "Both matrices are equal" on the console */ public func == (left: Matrix4, right: Matrix4) -> Bool { return left.equals(right) }
apache-2.0
1506adab272c841727ab5c4c14eee1f1
35.506189
155
0.609704
3.364373
false
false
false
false
v-andr/LakestoneCore
Source/PersistentPropertyList.swift
1
12465
// // PersistentPropertyList.swift // LakestoneCore // // Created by Taras Vozniuk on 6/13/16. // Copyright © 2016 GeoThings. All rights reserved. // // -------------------------------------------------------- // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #if COOPER import android.content import android.preference #else import Foundation #endif public class PersistentPropertyList { #if COOPER fileprivate let sharedPreference: SharedPreferences fileprivate let sharedPreferenceEditor: SharedPreferences.Editor public init(applicationContext: Context, preferenceFileKey: String? = nil){ if let passedPreferenceKey = preferenceFileKey { self.sharedPreference = applicationContext.getSharedPreferences(preferenceFileKey, Context.MODE_PRIVATE) } else { self.sharedPreference = PreferenceManager.getDefaultSharedPreferences(applicationContext) } self.sharedPreferenceEditor = self.sharedPreference.edit() } #else fileprivate let userDefaults: UserDefaults public init(){ self.userDefaults = UserDefaults.standard } #endif public func set(_ value: Bool, forKey key: String){ #if COOPER self.sharedPreferenceEditor.putBoolean(key, value) #else self.userDefaults.set(value, forKey: key) #endif } public func set(_ value: Int, forKey key: String){ #if COOPER self.sharedPreferenceEditor.putLong(key, value) #else self.userDefaults.set(value, forKey: key) #endif } public func set(_ value: Float, forKey key: String){ #if COOPER self.sharedPreferenceEditor.putFloat(key, value) #else self.userDefaults.set(value, forKey: key) #endif } public func set(_ value: Double, forKey key: String){ #if COOPER //android sharedPreference for some reason doesn't have double support, store as string then instead self.sharedPreferenceEditor.putString(key, value.toString()) #else self.userDefaults.set(value, forKey: key) #endif } public func set(_ value: String, forKey key: String){ #if COOPER self.sharedPreferenceEditor.putString(key, value) #else self.userDefaults.set(value, forKey: key) #endif } public func set(_ value: Set<String>, forKey key: String){ #if COOPER var javaSet = java.util.HashSet<String>(value) self.sharedPreferenceEditor.putStringSet(key, javaSet) #else self.userDefaults.set([String](value), forKey: key) #endif } public func bool(forKey key: String) -> Bool? { #if COOPER return (self.sharedPreference.contains(key)) ? self.sharedPreference.getBoolean(key, false) : nil #else return (self.userDefaults.object(forKey: key) != nil) ? self.userDefaults.bool(forKey: key) : nil #endif } public func integer(forKey key: String) -> Int? { #if COOPER return (self.sharedPreference.contains(key)) ? self.sharedPreference.getLong(key, 0) : nil #else return (self.userDefaults.object(forKey: key) != nil) ? self.userDefaults.integer(forKey: key) : nil #endif } public func float(forKey key: String) -> Float? { #if COOPER return (self.sharedPreference.contains(key)) ? self.sharedPreference.getFloat(key, 0.0) : nil #else return (self.userDefaults.object(forKey: key) != nil) ? self.userDefaults.float(forKey: key) : nil #endif } public func double(forKey key: String) -> Double? { #if COOPER //android sharedPreference for some reason doesn't have double support, it is stored as string instead return (self.sharedPreference.contains(key)) ? Double.parseDouble(self.sharedPreference.getString(key, "0.0")) : nil #else return (self.userDefaults.object(forKey: key) != nil) ? self.userDefaults.double(forKey: key) : nil #endif } public func string(forKey key: String) -> String? { #if COOPER return (self.sharedPreference.contains(key)) ? self.sharedPreference.getString(key, "") : nil #else return self.userDefaults.string(forKey: key) #endif } public func stringSet(forKey key: String) -> Set<String>? { #if COOPER if (self.sharedPreference.contains(key)){ let javaStringSet = java.util.HashSet<String>(self.sharedPreference.getStringSet(key, java.util.HashSet<String>())) let returnSet = Set<String>() for entity in javaStringSet { returnSet.insert(entity) } return returnSet } else { return nil } #else guard let stringArray = self.userDefaults.stringArray(forKey: key) else { return nil } return Set<String>(stringArray) #endif } public func removeObject(forKey key: String){ #if COOPER self.sharedPreferenceEditor.remove(key) #else self.userDefaults.removeObject(forKey: key) #endif } public func synchronize(){ #if COOPER self.sharedPreferenceEditor.apply() #else _ = self.userDefaults.synchronize() #endif } public func contains(key: String) -> Bool { #if COOPER return self.sharedPreference.contains(key) #else return self.userDefaults.object(forKey: key) != nil #endif } #if COOPER public var allKeys: Set<String> { let javaStringSet = self.sharedPreference.getAll().keySet() let returnSet = Set<String>() for entity in javaStringSet { returnSet.insert(entity) } return returnSet } #elseif !os(Linux) public var allKeys: Set<String> { return Set<String>(self.userDefaults.dictionaryRepresentation().keys) } #endif } // Array, Dictionary, Date, String, URL, UUID extension PersistentPropertyList { /// -remark: Overloading with '_ value:' will result in dex failure in Silver public func set(array: [Any], forKey key: String) { #if COOPER guard let jsonString = try? JSONSerialization.string(withJSONObject: array) else { return } self.set(jsonString, forKey: key) #else self.userDefaults.set(array, forKey: key) #endif } public func set(set: Set<AnyHashable>, forKey key: String){ self.set(array: [AnyHashable](set), forKey: key) } public func set(_ value: [String: Any], forKey key: String) { #if COOPER guard let jsonString = try? JSONSerialization.string(withJSONObject: value) else { return } self.set(jsonString, forKey: key) #else self.userDefaults.set(value, forKey: key) #endif } public func set(_ value: Date, forKey key: String) { #if COOPER let timeInterval = value.timeIntervalSince1970 self.set(timeInterval, forKey: key) #else self.userDefaults.set(value, forKey: key) #endif } public func set(_ value: URL, forKey key: String) { #if COOPER let absoluteString = value.absoluteString self.set(absoluteString, forKey: key) #else self.userDefaults.set(value, forKey: key) #endif } public func set(_ uuid: UUID, forKey key: String){ self.set(uuid.uuidString, forKey: key) } public func array(forKey key: String) -> [Any]? { #if COOPER guard let jsonString = self.string(forKey: key), let jsonData = Data.with(utf8EncodedString: jsonString) else { return nil } guard let jsonObject = try? JSONSerialization.jsonObject(with: jsonData) else { return nil } return jsonObject as? [Any] #else return self.userDefaults.array(forKey: key) #endif } public func set(forKey key: String) -> Set<AnyHashable>? { guard let array = self.array(forKey: key) as? [AnyHashable] else { return nil } return Set<AnyHashable>(array) } public func dictionary(forKey key: String) -> [String: Any]? { #if COOPER guard let jsonString = self.string(forKey: key), let jsonData = Data.with(utf8EncodedString: jsonString) else { return nil } guard let jsonObject = try? JSONSerialization.jsonObject(with: jsonData) else { return nil } return jsonObject as? [String: Any] #else return self.userDefaults.dictionary(forKey: key) #endif } public func date(forKey key: String) -> Date? { #if COOPER guard let timeInterval = self.double(forKey: key) else { return nil } return Date(timeIntervalSince1970: timeInterval) #else return self.userDefaults.object(forKey: key) as? Date #endif } public func url(forKey key: String) -> URL? { #if COOPER guard let absoluteString = self.string(forKey: key) else { return nil } return URL(string: absoluteString) #else return self.userDefaults.url(forKey: key) #endif } public func uuid(forKey key: String) -> UUID? { guard let uuidString = self.string(forKey: key) else { return nil } return UUID(uuidString: uuidString) } } // CustomSerializable support extension PersistentPropertyList { public func setCustomSerializable(_ customSerializable: CustomSerializable, forKey key: String) throws { let serializedDict = try CustomSerialization.dictionary(from: customSerializable) #if COOPER let jsonString = try JSONSerialization.string(withJSONObject: serializedDict) self.set(jsonString, forKey: key) #else self.userDefaults.set(serializedDict, forKey: key) #endif } public func set(customSerializableArray: [CustomSerializable], forKey key: String) throws { let serializedArray = try CustomSerialization.array(from: customSerializableArray) #if COOPER let jsonString = try JSONSerialization.string(withJSONObject: serializedArray) self.set(jsonString, forKey: key) #else self.userDefaults.set(serializedArray, forKey: key) #endif } #if COOPER // if using generics with Class<T> in Silver, the return type of T? will be interpretted as? '? extends CustomSerializable' // while in Swift you can have strong typing with // public func customSerializable<T: CustomSerializable>(forKey key: String, ofDesiredType: T.Type, withTotalCustomTypes: [CustomSerializableType]) -> T? // using the CustomSerializable return type for the sake of matching declarations for now private func _performCustomSerializationToUnderlyingParsedJSONEntity(forKey key: String, withCustomTypes: [CustomSerializableType]) -> Any? { guard let jsonString = self.string(forKey: key), let jsonData = Data.with(utf8EncodedString: jsonString), let jsonObject = try? JSONSerialization.jsonObject(with: jsonData), let targetEntity = try? CustomSerialization.applyCustomSerialization(ofCustomTypes: withCustomTypes, to: jsonObject) else { return nil } return targetEntity } public func customSerializable(forKey key: String, withCustomTypes: [CustomSerializableType]) -> CustomSerializable? { return _performCustomSerializationToUnderlyingParsedJSONEntity(forKey: key, withCustomTypes: withCustomTypes) as? CustomSerializable } public func customSerializableArray(forKey key: String, withCustomTypes: [CustomSerializableType]) -> [CustomSerializable]? { return _performCustomSerializationToUnderlyingParsedJSONEntity(forKey: key, withCustomTypes: withCustomTypes) as? [CustomSerializable] } #else public func customSerializable(forKey key: String, withCustomTypes: [CustomSerializableType]) -> CustomSerializable? { guard let storedDictionary = self.userDefaults.dictionary(forKey: key), let customSerializable = try? CustomSerialization.applyCustomSerialization(ofCustomTypes: withCustomTypes, to: storedDictionary) else { return nil } return customSerializable as? CustomSerializable } public func customSerializableArray(forKey key: String, withCustomTypes: [CustomSerializableType]) -> [CustomSerializable]? { guard let storedDictionary = self.userDefaults.array(forKey: key), let customSerializableArray = try? CustomSerialization.applyCustomSerialization(ofCustomTypes: withCustomTypes, to: storedDictionary) else { return nil } return customSerializableArray as? [CustomSerializable] } #endif }
apache-2.0
e265df8c8c2c5201aeccdb1f30b2211d
24.175758
154
0.703097
3.917636
false
false
false
false
cristiannomartins/Tree-Sets
Tree Sets/PopulateDB.swift
1
28037
// // PopulateDB.swift // Tree Sets // // Created by Cristianno Vieira on 29/12/16. // Copyright © 2016 Cristianno Vieira. All rights reserved. // import Foundation import CoreData import UIKit class PopulateDB { // MARK: -- Local variables declarations static let encoding: String.Encoding = String.Encoding.utf8 // managedObjectContext: interface to access the data model //static let CDWrapper = CoreDataWrapper() static let CDWrapper = (UIApplication.shared.delegate as! AppDelegate).CDWrapper // static let managedObjectContext: NSManagedObjectContext = // (UIApplication.shared.delegate // //as! AppDelegate).persistentContainer.viewContext // as! AppDelegate).managedObjectContext //static fileprivate var basePokemon: [String:Pokemon] = [:] static fileprivate var basePkms = [Pokemon]() // references of pkms that were added to the data source static fileprivate var types = [Type]() // references of types that were added to the data source static fileprivate var stats = [Stats]() // references of stats that were added to the data source static fileprivate var abilities = [Ability]() // references of abilities that were added to the data source static fileprivate var items = [Item]() // references of items that were added to the data source static fileprivate var moves = [Move]() // references of moves that were added to the data source static fileprivate var tclasses = [TrainerClass]() // references of Trainer Classes that were added to the data source static fileprivate var dexes = [(id: Int, dex: Dex)]() // references of Dexes that were added to the data source static fileprivate var pkmSets = [PokemonSet]() // references of PkmSets that were added to the data source static var processingQueue = DispatchQueue(label: "com.Tree_Sets.heavyProcessing", attributes: []) // MARK: -- Auxiliary enums //Lookup | ID | Ndex | Species | Forme | Type1 | Type2 | Ability1 | Ability2 | AbilityH | HP | Attack | Defense | SpAttack | SpDefense | Speed | Total | Weight | Height | Dex1 | Dex2 | Class | %Male | %Female | Pre-Evolution | Egg Group 1 | Egg Group 2 | Type Concat | Ability Concat enum PkmTSV: Int { case species = 0 case id = 1 case nid //case species case primaryType = 5 case secondaryType case ability1 case ability2 case abilityH case baseHP case baseAtk case baseDef case baseSpa case baseSpd case baseSpe } enum DexCSV: Int { // first line of a dex //case id = 0 //case trainers // other dex lines (max of 5 repetitions) case species = 0 case set1 case set2 case set3 case set4 } // just a shortcut to organize the stats ids enum StatID: Int16 { case HP = 0 case Atk case Def case Spa case Spd case Spe } enum ItemCSV: Int { // Name;Mega Stone;ID;Effect case name = 0 case ID = 2 } enum PkmImagesCSV: Int { // Lookup;ID;subid;Ndex case species = 0 case ID } // Pokemon | Nature | Item | [Moves 1 - 4] | [EV Placement HP-Spe] enum PkmSetCSV: Int { case species = 0 case isMega case nature case heldItem case move1 case move2 case move3 case move4 case hpEV case atkEV case defEV case spaEV case spdEV case speEV } // Name | dex | Category | possible sex | sex | Start | End enum TrainerCSV: Int { case name = 0 case dexID case category case sex = 4 case start case end } // Trainer Category | Possible Sex | Characteristic enum TrainerClassCSV: Int { case name = 0 case possibleSex case characteristic } // MARK: -- Auxiliary getOrCreate functions static fileprivate func createPokemonSet() -> PokemonSet { return NSEntityDescription.insertNewObject(forEntityName: "PokemonSet", into: CDWrapper.managedObjectContext) as! PokemonSet } static fileprivate func createImage() -> Image { return NSEntityDescription.insertNewObject(forEntityName: "Image", into: CDWrapper.managedObjectContext) as! Image } static fileprivate func getOrCreateMove(_ name: String) -> Move { let result = moves.filter() { $0.name == name } if result.count > 1 { // there is more than one pokemon with the same species: something went wrong! abort() } if result.count == 1 { return result.first! } // TODO: Implement the rest of the moves fields let newMove = NSEntityDescription.insertNewObject(forEntityName: "Move", into: CDWrapper.managedObjectContext) as! Move newMove.name = name moves.append(newMove) return newMove } static var PkmnID = [String:Int]() static fileprivate func getID(forPkmn name: String) -> Int { if PkmnID.count > 0 { return PkmnID[name]! } if let contentsOfURL = Bundle.main.url(forResource: "pkmn_images-Table 1-1", withExtension: "csv") { do { let content = try String(contentsOf: contentsOfURL, encoding: encoding) var lines:[String] = content.components(separatedBy: "\r\n") as [String] lines.remove(at: 0) // gets rid of the header line for line in lines { let values = line.components(separatedBy: ";") PkmnID[values[PkmImagesCSV.species.rawValue]] = Int(values[PkmImagesCSV.ID.rawValue]) } } catch { print(error) } } return getID(forPkmn: name) } static var ItemID = [String:Int]() static fileprivate func getID(forItem name: String) -> Int { if ItemID.count > 0 { return ItemID[name]! } if let contentsOfURL = Bundle.main.url(forResource: "items_images-Table 1-1", withExtension: "csv") { do { let content = try String(contentsOf: contentsOfURL, encoding: encoding) var lines:[String] = content.components(separatedBy: "\r\n") as [String] lines.remove(at: 0) // gets rid of the header line for line in lines { let values = line.components(separatedBy: ";") ItemID[values[ItemCSV.name.rawValue]] = Int(values[ItemCSV.ID.rawValue]) } } catch { print(error) } } return getID(forItem: name) } static fileprivate func getOrCreateItem(_ name: String) -> Item { let result = items.filter() { $0.name == name } if result.count > 1 { // there is more than one pokemon with the same species: something went wrong! abort() } if result.count == 1 { return result.first! } // TODO: Implement the image from the items let newItem = NSEntityDescription.insertNewObject(forEntityName: "Item", into: CDWrapper.managedObjectContext) as! Item newItem.name = name let itemID = getID(forItem: name) let itemImage = createImage() itemImage.x = NSNumber.init(value: itemID / Image.ImageColumns) itemImage.y = NSNumber.init(value: itemID % Image.ImageColumns) newItem.image = itemImage items.append(newItem) return newItem } static fileprivate func getOrCreateAbility(_ name: String) -> Ability { let result = abilities.filter() { $0.name == name } if result.count > 1 { // there is more than one pokemon with the same species: something went wrong! abort() } if result.count == 1 { return result.first! } let newAbility = NSEntityDescription.insertNewObject(forEntityName: "Ability", into: CDWrapper.managedObjectContext) as! Ability newAbility.name = name abilities.append(newAbility) return newAbility } static fileprivate func getOrCreateType(_ name: String) -> Type { let result = types.filter() { $0.name == name } if result.count > 1 { // there is more than one pokemon with the same species: something went wrong! abort() } if result.count == 1 { return result.first! } let newType = NSEntityDescription.insertNewObject(forEntityName: "Type", into: CDWrapper.managedObjectContext) as! Type newType.name = name types.append(newType) return newType } static fileprivate func getOrCreateStat(id: Int16, value: Int16) -> Stats { let result = stats.filter() { $0.id == id && $0.value == value } if result.count > 1 { // there is more than one pokemon with the same species: something went wrong! abort() } if result.count == 1 { return result.first! } let newStat = NSEntityDescription.insertNewObject(forEntityName: "Stat", into: CDWrapper.managedObjectContext) as! Stats newStat.id = id newStat.value = value stats.append(newStat) return newStat } static fileprivate func getOrCreatePokemon(ofSpecies species: String) -> Pokemon { let result = basePkms.filter() { $0.species == species } if result.count > 1 { print("there is more than one pokemon with the same species: something went wrong!\n") abort() } if result.count == 1 { // found the mon return result.first! } // need to create a new mon let tuples = pkmBaseData.filter() { $0.key == species } if tuples.count != 1 { print("there is more/less than one pokemon with the same species: something went wrong!\n") abort() } let monData = tuples.first! let newMon = NSEntityDescription.insertNewObject(forEntityName: "Pokemon", into: CDWrapper.managedObjectContext) as! Pokemon newMon.species = monData.key // TODO: What should I do on these cases? if monData.value.count > 1 { print("More than one found for species \(monData.key):\n") for value in monData.value { print("\t\(value)\n") } } let values = monData.value.first!.components(separatedBy: "\t") newMon.id = Int32(values[PkmTSV.id.rawValue])! newMon.firstAbility = getOrCreateAbility(values[PkmTSV.ability1.rawValue]) newMon.secondAbility = getOrCreateAbility(values[PkmTSV.ability2.rawValue]) newMon.hiddenAbility = getOrCreateAbility(values[PkmTSV.abilityH.rawValue]) newMon.type1 = getOrCreateType(values[PkmTSV.primaryType.rawValue]) newMon.type2 = getOrCreateType(values[PkmTSV.secondaryType.rawValue]) var baseStats = [Stats]() baseStats.append(getOrCreateStat(id: StatID.HP.rawValue, value: Int16(values[PkmTSV.baseHP.rawValue])!)) baseStats.append(getOrCreateStat(id: StatID.Atk.rawValue, value: Int16(values[PkmTSV.baseAtk.rawValue])!)) baseStats.append(getOrCreateStat(id: StatID.Def.rawValue, value: Int16(values[PkmTSV.baseDef.rawValue])!)) baseStats.append(getOrCreateStat(id: StatID.Spa.rawValue, value: Int16(values[PkmTSV.baseSpa.rawValue])!)) baseStats.append(getOrCreateStat(id: StatID.Spd.rawValue, value: Int16(values[PkmTSV.baseSpd.rawValue])!)) baseStats.append(getOrCreateStat(id: StatID.Spe.rawValue, value: Int16(values[PkmTSV.baseSpe.rawValue])!)) //print("1\n") newMon.baseStats = NSSet(array: baseStats) //print("2\n") basePkms.append(newMon) return newMon } // MARK: -- Other functions /** * Returns a dictionary that contains an array representing the different forms * a given pokemon can have. A string containing the pokemon species is the key. */ static fileprivate func getPokemonBasicData() -> [String:[String]] { var pokemons = [String:[String]]() if let contentsOfURL = Bundle.main.url(forResource: "Battle Tree Lookup - Pokedex", withExtension: "tsv") { do { let content = try String(contentsOf: contentsOfURL, encoding: encoding) var lines:[String] = content.components(separatedBy: "\r\n") as [String] lines.remove(at: 0) // gets rid of the header line for line in lines { let values = line.components(separatedBy: "\t") if pokemons[values[PkmTSV.species.rawValue]] == nil { pokemons[values[PkmTSV.species.rawValue]] = [] } pokemons[values[PkmTSV.species.rawValue]]!.append(line) } } catch { print(error) } } return pokemons } static fileprivate func getRecalcStats(stats precalcStats: [Stats], forItem item: Item) -> NSSet { // TODO: Implement this function to recalculate the stats based on the item var newStats = [Stats]() for stat in precalcStats { switch PokemonSet.PkmnStats(rawValue: stat.id)! { case .hp: newStats.append(stat) case .atk: if item.name == "Choice Band" { newStats.append(getOrCreateStat(id: PokemonSet.PkmnStats.atk.rawValue, value: Int16(Double(stat.value)*1.5))) } else { newStats.append(stat) } case .def: newStats.append(stat) case .spa: if item.name == "Choice Specs" { newStats.append(getOrCreateStat(id: PokemonSet.PkmnStats.spa.rawValue, value: Int16(Double(stat.value)*1.5))) } else { newStats.append(stat) } case .spd: newStats.append(stat) case .spe: if item.name == "Choice Scarf" { newStats.append(getOrCreateStat(id: PokemonSet.PkmnStats.spe.rawValue, value: Int16(Double(stat.value)*1.5))) } else { newStats.append(stat) } } } return NSSet(array: newStats) } static fileprivate func createImage(forPokemon id: Int) -> Image { let img = NSEntityDescription.insertNewObject(forEntityName: "Image", into: CDWrapper.managedObjectContext) as! Image img.x = NSNumber(value: id / Image.PkmColumns) img.y = NSNumber(value: id % Image.PkmColumns) return img } static fileprivate let pkmBaseData = getPokemonBasicData() // raw data of all pkm species //static fileprivate var altForms = [[String]]() // species of alternate forms static fileprivate func parsePkms() { if let contentsOfURL = Bundle.main.url(forResource: "Pokemon-Table 1", withExtension: "csv") { do { let content = try String(contentsOf: contentsOfURL, encoding: encoding) var lines:[String] = content.components(separatedBy: "\r\n") as [String] lines.remove(at: 0) // gets rid of the header line var index = 0 while index < lines.count { var species = "" var bckspecies = "" var basePkm: Pokemon! for i in 0...3 { var values = lines[index + i].components(separatedBy: ";") if i == 0 { species = values[0] } bckspecies = species // creates a new line with the same species but a different form if values[PkmSetCSV.isMega.rawValue] == "Mega" { // Megas species = "\(species) (Mega \(species))" } basePkm = getOrCreatePokemon(ofSpecies: species) // empty line of alternative sets if values[PkmSetCSV.heldItem.rawValue] == "" { //species = bckspecies continue } let newPkmSet = createPokemonSet() newPkmSet.species = basePkm newPkmSet.setID = (i + 1) as NSNumber? newPkmSet.nature = values[PkmSetCSV.nature.rawValue] newPkmSet.holding = getOrCreateItem(values[PkmSetCSV.heldItem.rawValue]) var evs = [Stats]() var divisor = 0 for c in PkmSetCSV.hpEV.rawValue...PkmSetCSV.speEV.rawValue { if values[c] != "" { divisor += 1 } } let investment = divisor == 2 ? 252 : 164 evs.append(getOrCreateStat(id: StatID.HP.rawValue, value: Int16(values[PkmSetCSV.hpEV.rawValue] == "" ? 0 : investment) )) evs.append(getOrCreateStat(id: StatID.Atk.rawValue, value: Int16(values[PkmSetCSV.atkEV.rawValue] == "" ? 0 : investment) )) evs.append(getOrCreateStat(id: StatID.Def.rawValue, value: Int16(values[PkmSetCSV.defEV.rawValue] == "" ? 0 : investment) )) evs.append(getOrCreateStat(id: StatID.Spa.rawValue, value: Int16(values[PkmSetCSV.spaEV.rawValue] == "" ? 0 : investment) )) evs.append(getOrCreateStat(id: StatID.Spd.rawValue, value: Int16(values[PkmSetCSV.spdEV.rawValue] == "" ? 0 : investment) )) evs.append(getOrCreateStat(id: StatID.Spe.rawValue, value: Int16(values[PkmSetCSV.speEV.rawValue] == "" ? 0 : investment) )) newPkmSet.evs = NSSet(array: evs) var precalcStats = [Stats]() precalcStats.append(getOrCreateStat(id: StatID.HP.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.hp)))) precalcStats.append(getOrCreateStat(id: StatID.Atk.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.atk)))) precalcStats.append(getOrCreateStat(id: StatID.Def.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.def)))) precalcStats.append(getOrCreateStat(id: StatID.Spa.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.spa)))) precalcStats.append(getOrCreateStat(id: StatID.Spd.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.spd)))) precalcStats.append(getOrCreateStat(id: StatID.Spe.rawValue, value: Int16(newPkmSet.getStatValue(PokemonSet.PkmnStats.spe)))) newPkmSet.preCalcStatsNoItem = NSSet(array: precalcStats) newPkmSet.preCalcStats = getRecalcStats(stats: precalcStats, forItem: newPkmSet.holding!) var moveSet = [Move]() moveSet.append(getOrCreateMove(values[PkmSetCSV.move1.rawValue])) moveSet.append(getOrCreateMove(values[PkmSetCSV.move2.rawValue])) moveSet.append(getOrCreateMove(values[PkmSetCSV.move3.rawValue])) moveSet.append(getOrCreateMove(values[PkmSetCSV.move4.rawValue])) newPkmSet.moveSet = NSSet(array: moveSet) newPkmSet.image = createImage(forPokemon: getID(forPkmn:newPkmSet.species!.species!)) //try? newPkmSet.managedObjectContext?.save() pkmSets.append(newPkmSet) //print("\(species), set \(i): OK") species = bckspecies } index += 4 } //CDWrapper.saveContext() } catch { print(error) } } } static fileprivate func getTrainerClassPossibleSex(_ name: String) -> String { if let contentsOfURL = Bundle.main.url(forResource: "Trainer Category-Table 1", withExtension: "csv") { do { let content = try String(contentsOf: contentsOfURL, encoding: encoding) var lines:[String] = content.components(separatedBy: "\r\n") as [String] lines.remove(at: 0) // gets rid of the header line for line in lines { let values = line.components(separatedBy: ";") if values[TrainerClassCSV.name.rawValue] == name { return values[TrainerClassCSV.possibleSex.rawValue] } } } catch { print(error) } } //print("Could not find trainer class named \(name) on Trainer Category Table.") //abort() return "?" // undiscovered trainer class } static fileprivate func getPkmSet(pkmNamed species: String, id setID: Int) -> PokemonSet { if let result = findPkmSet(pkmNamed: species, id: setID) { // regular form return result } else if let result = findPkmSet(pkmNamed: "\(species) (Mega \(species))", id: setID) { // mega return result } else { abort() } } static fileprivate func findPkmSet(pkmNamed species: String, id setID: Int) -> PokemonSet? { let result = pkmSets.filter() { $0.species?.species == species } if result.count == 0 { // there is no pokemon from that species on the db abort() } for res in result { if Int(res.setID!) == setID { return res } } // // // Could not find a pkmSet with the same id as requested // abort() return nil } static fileprivate func parseDexes() { if let contentsOfURL = Bundle.main.url(forResource: "Dex-Table 1", withExtension: "csv") { do { let content = try String(contentsOf: contentsOfURL, encoding: encoding) let lines:[String] = content.components(separatedBy: "\r\n") as [String] var curr = 0 while (curr < lines.count) { // first line of a dex (only the id matters) let id = Int(lines[curr].components(separatedBy: ";")[0])! curr += 1 var values = lines[curr].components(separatedBy: ";") let newDex = NSEntityDescription.insertNewObject(forEntityName: "Dex", into: CDWrapper.managedObjectContext) as! Dex var pkmSets = [PokemonSet]() while values[0] != "" { for setID in 1...4 { if values[setID] == "\(setID)" { pkmSets.append(getPkmSet(pkmNamed: values[DexCSV.species.rawValue], id: setID)) } } values.removeFirst(5) if values.count == 0 { // this line has ended curr += 1 // there are no more lines available if curr == lines.count { values.append("") continue } values = lines[curr].components(separatedBy: ";") } else if values[0] == "" { // or this line was an incomplete one curr += 1 } } newDex.contains = NSSet(array:pkmSets) dexes.append((id: id, dex: newDex)) curr += 1 } } catch { print(error) } } } static fileprivate func getDex(_ id: Int) -> Dex { if dexes.count == 0 { parseDexes() } let result = dexes.filter() { $0.id == id } if result.count > 1 { // there is more than one dex with the same id: something went wrong! abort() } if result.count == 1 { return result.first!.dex } print("Could not find dex with id \(id).") abort() } static fileprivate func getOrCreateTrainerClass(_ name: String) -> TrainerClass { let result = tclasses.filter() { $0.name == name } if result.count > 1 { // there is more than one pokemon with the same species: something went wrong! abort() } if result.count == 1 { return result.first! } // TODO: Implement the image of Trainer Class let newTClass = NSEntityDescription.insertNewObject(forEntityName: "TrainerClass", into: CDWrapper.managedObjectContext) as! TrainerClass newTClass.name = name newTClass.possibleSex = getTrainerClassPossibleSex(name) tclasses.append(newTClass) return newTClass } static fileprivate func parseTrainers() /*-> [Trainer]*/ { //var trainers = [Trainer]() if let contentsOfURL = Bundle.main.url(forResource: "Trainer-Table 1", withExtension: "csv") { do { let content = try String(contentsOf: contentsOfURL, encoding: encoding) var lines:[String] = content.components(separatedBy: "\r\n") as [String] lines.remove(at: 0) // gets rid of the header line for line in lines { let values = line.components(separatedBy: ";") // TODO: Implement the quotes spoken by the trainers let newTrainer = NSEntityDescription.insertNewObject(forEntityName: "Trainer", into: CDWrapper.managedObjectContext) as! Trainer newTrainer.name = values[TrainerCSV.name.rawValue] newTrainer.sex = values[TrainerCSV.sex.rawValue] newTrainer.start = values[TrainerCSV.start.rawValue] == "" ? nil : values[TrainerCSV.start.rawValue] newTrainer.end = values[TrainerCSV.end.rawValue] == "" ? nil : values[TrainerCSV.end.rawValue] newTrainer.trainerClass = getOrCreateTrainerClass(values[TrainerCSV.category.rawValue]) newTrainer.availableMons = getDex(Int(values[TrainerCSV.dexID.rawValue])!) //try? newTrainer.managedObjectContext?.save() //trainers.append(newTrainer) } //CDWrapper.saveContext() } catch { print(error) } } //return trainers } /** * Remove all content inside the database (for debugging purposes) */ static fileprivate func removeData () { // Remove the existing mons-sets and trainers let fetchMonSets = NSFetchRequest<PokemonSet>(entityName: "PokemonSet") let fetchTrainers = NSFetchRequest<Trainer>(entityName: "Trainer") do { let pkms = try CDWrapper.managedObjectContext.fetch(fetchMonSets) for pkm in pkms { CDWrapper.managedObjectContext.delete(pkm) } let trainers = try CDWrapper.managedObjectContext.fetch(fetchTrainers) for trainer in trainers { CDWrapper.managedObjectContext.delete(trainer) } } catch { print("Failed to retrieve record: \(error)") } // Remove the existing items, moves and pkm let fetchItems = NSFetchRequest<Item>(entityName: "Item") let fetchMoves = NSFetchRequest<Move>(entityName: "Move") let fetchMons = NSFetchRequest<Pokemon>(entityName: "Pokemon") do { let items = try CDWrapper.managedObjectContext.fetch(fetchItems) for item in items { CDWrapper.managedObjectContext.delete(item) } let moves = try CDWrapper.managedObjectContext.fetch(fetchMoves) for move in moves { CDWrapper.managedObjectContext.delete(move) } let pkms = try CDWrapper.managedObjectContext.fetch(fetchMons) for pkm in pkms { CDWrapper.managedObjectContext.delete(pkm) } } catch { print("Failed to retrieve record: \(error)") } // Remove the existing dexes, abilities, types and trainer categories let fetchTrainerCat = NSFetchRequest<TrainerClass>(entityName: "TrainerClass") let fetchDex = NSFetchRequest<Dex>(entityName: "Dex") let fetchAbility = NSFetchRequest<Ability>(entityName: "Ability") let fetchType = NSFetchRequest<Type>(entityName: "Type") do { let cats = try CDWrapper.managedObjectContext.fetch(fetchTrainerCat) for cat in cats { CDWrapper.managedObjectContext.delete(cat) } let dexes = try CDWrapper.managedObjectContext.fetch(fetchDex) for dex in dexes { CDWrapper.managedObjectContext.delete(dex) } let abilities = try CDWrapper.managedObjectContext.fetch(fetchAbility) for ability in abilities { CDWrapper.managedObjectContext.delete(ability) } let types = try CDWrapper.managedObjectContext.fetch(fetchType) for type in types { CDWrapper.managedObjectContext.delete(type) } } catch { print("Failed to retrieve record: \(error)") } } static func preload() { removeData() parsePkms() //parseAlternateForms() parseTrainers() //CDWrapper.saveContext() } }
mit
79007ad15156fa5ff8a0d109111f815f
33.23199
285
0.615601
4.548345
false
false
false
false
DerrickQin2853/SinaWeibo-Swift
SinaWeibo/SinaWeibo/Classes/View/EmoticonKeyboard/View/DQEmoticonToolBar.swift
1
2614
// // DQEmoticonToolBar.swift // SinaWeibo // // Created by admin on 2016/10/8. // Copyright © 2016年 Derrick_Qin. All rights reserved. // import UIKit enum EmoticonType: Int { case RECENT = 0 case DEFAULT case EMOJI case LXH } class DQEmoticonToolBar: UIStackView { override init(frame: CGRect) { super.init(frame: frame) setupUI() axis = .horizontal distribution = .fillEqually tag = 999 } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { addButton(title: "最近", backgroundImageName: "compose_emotion_table_left", type: .RECENT) addButton(title: "默认", backgroundImageName: "compose_emotion_table_mid", type: .DEFAULT) addButton(title: "Emoji", backgroundImageName: "compose_emotion_table_mid", type: .EMOJI) addButton(title: "浪小花", backgroundImageName: "compose_emotion_table_right", type: .LXH) } private func addButton(title: String, backgroundImageName: String, type: EmoticonType) { let button = UIButton() button.tag = type.rawValue button.setBackgroundImage(UIImage(named: backgroundImageName + "_normal"), for: .normal) button.setBackgroundImage(UIImage(named: backgroundImageName + "_selected"), for: .selected) button.setTitle(title, for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.setTitleColor(UIColor.darkGray, for: .selected) button.titleLabel?.font = UIFont.systemFont(ofSize: 14) button.addTarget(self, action: #selector(buttonClick(btn:)), for: .touchUpInside) self.addArrangedSubview(button) if type == .RECENT { button.isSelected = true lastSelectedButton = button } } func setButtonSelected(indexPath: IndexPath) { let btn = self.viewWithTag(indexPath.section) as! UIButton if btn.isSelected { return } lastSelectedButton?.isSelected = false lastSelectedButton = btn btn.isSelected = true } @objc private func buttonClick(btn: UIButton) { if btn.isSelected { return } lastSelectedButton?.isSelected = false lastSelectedButton = btn btn.isSelected = true emoticonTypeSelectClosure?(EmoticonType.init(rawValue: btn.tag)!) } var lastSelectedButton: UIButton? var emoticonTypeSelectClosure: ((EmoticonType) -> ())? }
mit
640456d34272944906a36b093ed4651f
28.850575
100
0.628032
4.654122
false
false
false
false
ios-ximen/DYZB
斗鱼直播/Pods/Kingfisher/Sources/UIButton+Kingfisher.swift
68
19447
// // UIButton+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/13. // // Copyright (c) 2017 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // MARK: - Set Images /** * Set image to use in button from web for a specified state. */ extension Kingfisher where Base: UIButton { /** Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. If `resource` is `nil`, the `placeholder` image will be set and `completionHandler` will be called with both `error` and `image` being `nil`. */ @discardableResult public func setImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.setImage(placeholder, for: state) setWebURL(nil, for: state) completionHandler?(nil, nil, .none, nil) return .empty } let options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo) if !options.keepCurrentImageWhileLoading { base.setImage(placeholder, for: state) } setWebURL(resource.downloadURL, for: state) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL(for: state) else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL(for: state) else { completionHandler?(image, error, cacheType, imageURL) return } self.setImageTask(nil) if image != nil { strongBase.setImage(image, for: state) } completionHandler?(image, error, cacheType, imageURL) } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelImageDownloadTask() { imageTask?.cancel() } /** Set the background image to use for a specified state with a resource, a placeholder image, options progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. If `resource` is `nil`, the `placeholder` image will be set and `completionHandler` will be called with both `error` and `image` being `nil`. */ @discardableResult public func setBackgroundImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.setBackgroundImage(placeholder, for: state) setBackgroundWebURL(nil, for: state) completionHandler?(nil, nil, .none, nil) return .empty } let options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo) if !options.keepCurrentImageWhileLoading { base.setBackgroundImage(placeholder, for: state) } setBackgroundWebURL(resource.downloadURL, for: state) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.backgroundWebURL(for: state) else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: { [weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.backgroundWebURL(for: state) else { completionHandler?(image, error, cacheType, imageURL) return } self.setBackgroundImageTask(nil) if image != nil { strongBase.setBackgroundImage(image, for: state) } completionHandler?(image, error, cacheType, imageURL) } }) setBackgroundImageTask(task) return task } /** Cancel the background image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelBackgroundImageDownloadTask() { backgroundImageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var imageTaskKey: Void? extension Kingfisher where Base: UIButton { /** Get the image URL binded to this button for a specified state. - parameter state: The state that uses the specified image. - returns: Current URL for image. */ public func webURL(for state: UIControlState) -> URL? { return webURLs[NSNumber(value:state.rawValue)] as? URL } fileprivate func setWebURL(_ url: URL?, for state: UIControlState) { webURLs[NSNumber(value:state.rawValue)] = url } fileprivate var webURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(base, &lastURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() setWebURLs(dictionary!) } return dictionary! } fileprivate func setWebURLs(_ URLs: NSMutableDictionary) { objc_setAssociatedObject(base, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var lastBackgroundURLKey: Void? private var backgroundImageTaskKey: Void? extension Kingfisher where Base: UIButton { /** Get the background image URL binded to this button for a specified state. - parameter state: The state that uses the specified background image. - returns: Current URL for background image. */ public func backgroundWebURL(for state: UIControlState) -> URL? { return backgroundWebURLs[NSNumber(value:state.rawValue)] as? URL } fileprivate func setBackgroundWebURL(_ url: URL?, for state: UIControlState) { backgroundWebURLs[NSNumber(value:state.rawValue)] = url } fileprivate var backgroundWebURLs: NSMutableDictionary { var dictionary = objc_getAssociatedObject(base, &lastBackgroundURLKey) as? NSMutableDictionary if dictionary == nil { dictionary = NSMutableDictionary() setBackgroundWebURLs(dictionary!) } return dictionary! } fileprivate func setBackgroundWebURLs(_ URLs: NSMutableDictionary) { objc_setAssociatedObject(base, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var backgroundImageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &backgroundImageTaskKey) as? RetrieveImageTask } fileprivate func setBackgroundImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web for a specified state. Deprecated. Use `kf` namespacing instead. */ extension UIButton { /** Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.setImage` instead.", renamed: "kf.setImage") public func kf_setImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelImageDownloadTask` instead.", renamed: "kf.cancelImageDownloadTask") public func kf_cancelImageDownloadTask() { kf.cancelImageDownloadTask() } /** Set the background image to use for a specified state with a resource, a placeholder image, options progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter state: The state that uses the specified image. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.setBackgroundImage` instead.", renamed: "kf.setBackgroundImage") public func kf_setBackgroundImage(with resource: Resource?, for state: UIControlState, placeholder: UIImage? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setBackgroundImage(with: resource, for: state, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the background image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.cancelBackgroundImageDownloadTask` instead.", renamed: "kf.cancelBackgroundImageDownloadTask") public func kf_cancelBackgroundImageDownloadTask() { kf.cancelBackgroundImageDownloadTask() } /** Get the image URL binded to this button for a specified state. - parameter state: The state that uses the specified image. - returns: Current URL for image. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.webURL` instead.", renamed: "kf.webURL") public func kf_webURL(for state: UIControlState) -> URL? { return kf.webURL(for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL, for state: UIControlState) { kf.setWebURL(url, for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.webURLs") fileprivate var kf_webURLs: NSMutableDictionary { return kf.webURLs } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setWebURLs") fileprivate func kf_setWebURLs(_ URLs: NSMutableDictionary) { kf.setWebURLs(URLs) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) } /** Get the background image URL binded to this button for a specified state. - parameter state: The state that uses the specified background image. - returns: Current URL for background image. */ @available(*, deprecated, message: "Extensions directly on UIButton are deprecated. Use `button.kf.backgroundWebURL` instead.", renamed: "kf.backgroundWebURL") public func kf_backgroundWebURL(for state: UIControlState) -> URL? { return kf.backgroundWebURL(for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURL") fileprivate func kf_setBackgroundWebURL(_ url: URL, for state: UIControlState) { kf.setBackgroundWebURL(url, for: state) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundWebURLs") fileprivate var kf_backgroundWebURLs: NSMutableDictionary { return kf.backgroundWebURLs } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundWebURLs") fileprivate func kf_setBackgroundWebURLs(_ URLs: NSMutableDictionary) { kf.setBackgroundWebURLs(URLs) } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.backgroundImageTask") fileprivate var kf_backgroundImageTask: RetrieveImageTask? { return kf.backgroundImageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setBackgroundImageTask") fileprivate func kf_setBackgroundImageTask(_ task: RetrieveImageTask?) { return kf.setBackgroundImageTask(task) } }
mit
345c14b399878353de9184f65bb06912
45.082938
122
0.6546
5.545195
false
false
false
false
emilstahl/swift
test/SourceKit/CodeFormat/indent-closure.swift
10
1478
func foo() { bar() { var abc = 1 let a: String = { let b = "asdf" return b }() } } class C { private static let durationTimeFormatter: NSDateComponentsFormatter = { return timeFormatter }() } func foo1(a: Int, handler : ()->()) {} func foo2(handler : () ->()) {} func foo3() { foo1(1) { } } // RUN: %sourcekitd-test -req=format -line=3 -length=1 %s >%t.response // RUN: %sourcekitd-test -req=format -line=4 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=5 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=6 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=7 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=8 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=14 -length=1 %s >>%t.response // RUN: %sourcekitd-test -req=format -line=22 -length=1 %s >>%t.response // RUN: FileCheck --strict-whitespace %s <%t.response // CHECK: key.sourcetext: " var abc = 1" // CHECK: key.sourcetext: " let a: String = {" // CHECK: key.sourcetext: " let b = "asdf"" // CHECK: key.sourcetext: " return b" // CHECK: key.sourcetext: " }()" // CHECK: key.sourcetext: " }" // " private static let durationTimeFormatter: NSDateComponentsFormatter = {" // CHECK: key.sourcetext: " }()" // " foo1(1)" // CHECK: key.sourcetext: " {"
apache-2.0
b86739f3fc61ff320269dd599cd53176
31.130435
101
0.570365
3.206074
false
true
false
false