repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
djq993452611/YiYuDaoJia_Swift
YiYuDaoJia/YiYuDaoJia/Classes/Category/Controller/CategoryViewController.swift
1
3065
// // CategoryViewController.swift // YiYuDaoJia // // Created by 蓝海天网Djq on 2017/4/25. // Copyright © 2017年 蓝海天网Djq. All rights reserved. // import UIKit class CategoryViewController: BaseViewController { } extension CategoryViewController{ override func setupUI() { super.setupUI() loadDataFinished() //隐藏左边的返回按钮 navigationItem.leftBarButtonItem = UIBarButtonItem() let textLabel = UILabel(frame: CGRect.init(x: 100, y: 200, width: 200, height: 60)) textLabel.text = "一共7件商品:¥800" textLabel.font = UIFont.systemFont(ofSize: 14) textLabel.textColor = UIColor.ColorHexString(hexStr: "#666666") view.addSubview(textLabel) // 先把string 类型转换成nsstring,再使用OC的分类方法计算出range位置,NSMutableAttributedString根据计算的位置设置字体大小和颜色.(不在位置范围的内容将保留原来label的样式) let labelString = textLabel.text! as NSString let startIndex = labelString.index(of: ":")+1 let length = labelString.length - Int(startIndex) let range = NSRange.init(location: Int(startIndex), length:length ) let attString = NSMutableAttributedString(string: labelString as String) //改变字体样式 attString.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 24),NSForegroundColorAttributeName:UIColor.ColorHexString(hexStr: "0x198cdf")], range: range) textLabel.attributedText = attString //原来的label显示测试 //新的label显示测试 let attLabel = UILabel(frame: CGRect.init(x: 100, y: 300, width: 200, height: 60)) attLabel.textColor = UIColor.brown attLabel.attributedText = attString view.addSubview(attLabel) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //异步线程和返回主线程 DispatchQueue.global().async { var test = "34556" DLog(log: "testGlobal=\(test)") DispatchQueue.main.async { test = "khdkfk" DLog(log: "testMain=\(test)") } } DLog(log: Date.getCurrentTime()) //延迟线程 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(4)) { DLog(log: Date.getCurrentTime()) } view.frame=CGRect(x: 0, y: 64, width: kScreenW, height: kScreenH-64-49) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+DispatchTimeInterval.seconds(1)) { DShowToastBottom(messsge: "window 显示底部内容") DShowToastCenter(message: "window 显示中间内容") } // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(5)) { // self.view.hideToastActivity() // } } }
mit
fd4e47ee69a1f7ea774043ee1ac6c344
31.425287
172
0.610776
4.42163
false
true
false
false
PureSwift/MongoDB
Sources/MongoDB/HostList.swift
1
2959
// // HostList.swift // MongoDB // // Created by Alsey Coleman Miller on 12/25/15. // Copyright © 2015 PureSwift. All rights reserved. // import SwiftFoundation import BinaryJSON import CMongoC import CBSON public extension MongoDB { public struct Host { public let host: String public let hostPort: String public let port: UInt16 internal static func fromHostList(firstHostList: mongoc_host_list_t) -> [Host] { var hostArray = [Host]() var currentHostList: mongoc_host_list_t? = firstHostList // convert and add to array while var hostList = currentHostList { let hostString: String do { let string = withUnsafePointer(&hostList.host) { (unsafeTuplePointer) -> String in let charPointer = unsafeBitCast(unsafeTuplePointer, UnsafePointer<CChar>.self) guard let string = String.fromCString(charPointer) else { fatalError("Could not create string ") } return string } hostString = string } let hostPortString: String do { let string = withUnsafePointer(&hostList.host_and_port) { (unsafeTuplePointer) -> String in let charPointer = unsafeBitCast(unsafeTuplePointer, UnsafePointer<CChar>.self) guard let string = String.fromCString(charPointer) else { fatalError("Could not create string ") } return string } hostPortString = string } // create host and add to array let host = Host(host: hostString, hostPort: hostPortString, port: hostList.port) // make sure first host is not empty if hostArray.isEmpty { guard host.host.isEmpty == false && host.hostPort.isEmpty == false else { return [] } } hostArray.append(host) // set next host in linked list if hostList.next != nil { currentHostList = hostList.next.memory } else { currentHostList = nil } } return hostArray } } }
mit
2889ce030f3a06a0a47cd953dd61c659
31.516484
111
0.431034
6.587973
false
false
false
false
chanhx/Octogit
iGithub/Octicon.swift
2
7287
// // Octicon.swift // iGithub // // Created by Chan Hocheung on 7/20/16. // Copyright © 2016 Hocheung. All rights reserved. // import UIKit enum Octicon : String, CustomStringConvertible { case alert = "\u{f02d}" case arrowDown = "\u{f03f}" case arrowLeft = "\u{f040}" case arrowRight = "\u{f03e}" case arrowSmallDown = "\u{f0a0}" case arrowSmallLeft = "\u{f0a1}" case arrowSmallRight = "\u{f071}" case arrowSmallUp = "\u{f09f}" case arrowUp = "\u{f03d}" case beaker = "\u{f0dd}" case bell = "\u{f0de}" case bold = "\u{f0e2}" case book = "\u{f007}" case bookmark = "\u{f07b}" case briefcase = "\u{f0d3}" case broadcast = "\u{f048}" case browser = "\u{f0c5}" case bug = "\u{f091}" case calendar = "\u{f068}" case check = "\u{f03a}" case checkList = "\u{f076}" case chevronDown = "\u{f0a3}" case chevronLeft = "\u{f0a4}" case chevronRight = "\u{f078}" case chevronUp = "\u{f0a2}" case circleSlash = "\u{f084}" case circuitBoard = "\u{f0d6}" case clippy = "\u{f035}" case clock = "\u{f046}" case cloudDownload = "\u{f00b}" case cloudUpload = "\u{f00c}" case code = "\u{f05f}" case commentDiscussion = "\u{f04f}" case comment = "\u{f02b}" case creditCard = "\u{f045}" case dash = "\u{f0ca}" case dashboard = "\u{f07d}" case database = "\u{f096}" case desktopDownload = "\u{f0dc}" case deviceCameraVideo = "\u{f057}" case deviceCamera = "\u{f056}" case deviceDesktop = "\u{f27c}" case deviceMobile = "\u{f038}" case diffAdded = "\u{f06b}" case diffIgnored = "\u{f099}" case diffModified = "\u{f06d}" case diffRemoved = "\u{f06c}" case diffRenamed = "\u{f06e}" case diff = "\u{f04d}" case ellipsis = "\u{f09a}" case eye = "\u{f04e}" case fileBinary = "\u{f094}" case fileCode = "\u{f010}" case fileDirectory = "\u{f016}" case fileMedia = "\u{f012}" case filePDF = "\u{f014}" case fileSubmodule = "\u{f017}" case fileSymlinkDirectory = "\u{f0b1}" case fileSymlinkFile = "\u{f0b0}" case fileText = "\u{f011}" case fileZip = "\u{f013}" case flame = "\u{f0d2}" case fold = "\u{f0cc}" case gear = "\u{f02f}" case gift = "\u{f042}" case gistSecret = "\u{f08c}" case gist = "\u{f00e}" case gitBranch = "\u{f020}" case gitCommit = "\u{f01f}" case gitCompare = "\u{f0ac}" case gitMerge = "\u{f023}" case gitPullrequest = "\u{f009}" case globe = "\u{f0b6}" case graph = "\u{f043}" case heart = "\u{2665}" case history = "\u{f07e}" case home = "\u{f08d}" case horizontalRule = "\u{f070}" case hubot = "\u{f09d}" case inbox = "\u{f0cf}" case info = "\u{f059}" case issueClosed = "\u{f028}" case issueOpened = "\u{f026}" case issueReopened = "\u{f027}" case italic = "\u{f0e4}" case jersey = "\u{f019}" case key = "\u{f049}" case keyboard = "\u{f00d}" case law = "\u{f0d8}" case lightBulb = "\u{f000}" case linkExternal = "\u{f07f}" case link = "\u{f05c}" case listOrdered = "\u{f062}" case listUnordered = "\u{f061}" case location = "\u{f060}" case lock = "\u{f06a}" case logoGist = "\u{f0ad}" case logoGithub = "\u{f092}" case mailRead = "\u{f03c}" case mailReply = "\u{f051}" case mail = "\u{f03b}" case markGithub = "\u{f00a}" case markDown = "\u{f0c9}" case megaphone = "\u{f077}" case mention = "\u{f0be}" case milestone = "\u{f075}" case mirror = "\u{f024}" case mortarBoard = "\u{f0d7}" case mute = "\u{f080}" case noNewline = "\u{f09c}" case octoface = "\u{f008}" case organization = "\u{f037}" case package = "\u{f0c4}" case paintcan = "\u{f0d1}" case pencil = "\u{f058}" case person = "\u{f018}" case pin = "\u{f041}" case plug = "\u{f0d4}" case plus = "\u{f05d}" case primitiveDot = "\u{f052}" case primitiveSquare = "\u{f053}" case pulse = "\u{f085}" case question = "\u{f02c}" case quote = "\u{f063}" case radioTower = "\u{f030}" case repoClone = "\u{f04c}" case repoForcePush = "\u{f04a}" case repoForked = "\u{f002}" case repoPull = "\u{f006}" case repoPush = "\u{f005}" case repo = "\u{f001}" case rocket = "\u{f033}" case rss = "\u{f034}" case ruby = "\u{f047}" case search = "\u{f02e}" case server = "\u{f097}" case settings = "\u{f07c}" case shield = "\u{f0e1}" case signin = "\u{f036}" case signout = "\u{f032}" case smiley = "\u{f0e7}" case squirrel = "\u{f0b2}" case star = "\u{f02a}" case stop = "\u{f08f}" case sync = "\u{f087}" case tag = "\u{f015}" case tasklist = "\u{f0e5}" case telescope = "\u{f088}" case terminal = "\u{f0c8}" case textSize = "\u{f0e3}" case threeBars = "\u{f05e}" case thumbsdown = "\u{f0db}" case thumbsup = "\u{f0da}" case tools = "\u{f031}" case trashcan = "\u{f0d0}" case triangleDown = "\u{f05b}" case triangleLeft = "\u{f044}" case triangleRight = "\u{f05a}" case triangleUp = "\u{f0aa}" case unfold = "\u{f039}" case unmute = "\u{f0ba}" case unverified = "\u{f0e8}" case verified = "\u{f0e6}" case versions = "\u{f064}" case watch = "\u{f0e0}" case x = "\u{f081}" case zap = "\u{26a1}" func iconString(_ text: String, iconSize: CGFloat = 14, iconColor: UIColor? = nil, attributes: [NSAttributedString.Key: AnyObject]? = nil) -> NSMutableAttributedString { var iconAttributes: [NSAttributedString.Key: AnyObject] = [NSAttributedString.Key.font: UIFont.OcticonOfSize(iconSize)] if iconColor != nil { iconAttributes[NSAttributedString.Key.foregroundColor] = iconColor } let iconString = NSMutableAttributedString(string: "\(self)", attributes: iconAttributes) let attributedText = NSMutableAttributedString(string: " \(text)") if let attributes = attributes { attributedText.addAttributes(attributes, range: NSMakeRange(1, text.count)) } iconString.append(attributedText) return iconString } func image(color: UIColor = UIColor(netHex: 0x333333), backgroundColor: UIColor = .clear, iconSize: CGFloat, size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) (rawValue as NSString).draw(in: CGRect(origin: CGPoint.zero, size: size), withAttributes: [ NSAttributedString.Key.font: UIFont.OcticonOfSize(iconSize), NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.backgroundColor: backgroundColor]) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } var description: String { return self.rawValue } } extension UIFont { @inline(__always) class func OcticonOfSize(_ fontSize: CGFloat) -> UIFont { return UIFont(name: "octicons", size: fontSize)! } }
gpl-3.0
83329520ce2a44ee4470853da6ed4cdd
31.526786
173
0.569448
3.215357
false
false
false
false
TheBrewery/Hikes
WorldHeritage/Controllers/WHSortViewController.swift
1
3229
// // WHSortViewController.swift // World Heritage // // Created by James Hildensperger on 5/22/16. // Copyright © 2016 The Brewery. All rights reserved. // import Foundation import RealmSwift import Static class WHSortViewController: TableViewController { let sortProperties: [(title: String, property: String)] = [("Inscription Date", "identifier"), ("Distance", "distance"), ("Site Name", "name"), ("Region", "region"), ("Country", "countries")] var sortDescriptor: SortDescriptor? init(sortDescriptor: SortDescriptor? = nil) { super.init(style: .Plain) self.sortDescriptor = sortDescriptor } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() let footer = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: self.view.frame.width, height: 1.0))) let rows = sortProperties.enumerate().map({ return row($0.index, sortProperty: $0.element) }) dataSource.sections = [ Section(rows: rows, footer: .View(footer)) ] } func row(index: Int, sortProperty: (title: String, property: String)) -> Row { let arrowLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) arrowLabel.textColor = UIColor.blackColor() arrowLabel.font = UIFont.ionicFontOfSize(28) if sortDescriptor?.property == sortProperty.property { arrowLabel.text! = sortDescriptor!.ascending ? Ionic.IosArrowThinDown.rawValue : Ionic.IosArrowThinUp.rawValue } let row = Row(text: sortProperty.title, cellClass: WHTableViewCell.self, accessory: .View(arrowLabel), selection: { [unowned self] in var isAscending = true if self.sortDescriptor?.property == sortProperty.property { isAscending = !self.sortDescriptor!.ascending self.sortDescriptor = SortDescriptor(property: sortProperty.property, ascending: isAscending) } else { self.sortDescriptor = SortDescriptor(property: sortProperty.property) } let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.20 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { [weak self] in guard let _self = self else { return } _self.deselectRows() let label = _self.dataSource.sections[0].rows[index].accessory.view as? UILabel label?.text = isAscending ? Ionic.IosArrowThinUp.rawValue : Ionic.IosArrowThinDown.rawValue } }) return row } func deselectRows() { let selectedRows = self.dataSource.sections[0].rows.filter { guard let label = $0.accessory.view as? UILabel where label.text != nil else { return false } return true } for row in selectedRows { let label = row.accessory.view as? UILabel label?.text = nil } } }
mit
540379165f3b9ca8b5007e9bf28dacab
36.534884
195
0.592007
4.685051
false
false
false
false
srn214/Floral
Floral/Pods/WCDB.swift/swift/source/util/Tagged.swift
1
1183
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 final class Counter { static let counter = Atomic<Int>(0) static func step() -> Int { return ++counter } } final class Tagged<Value>: Equatable { let identifier: Int let value: Value init(_ value: Value) { self.value = value self.identifier = Counter.step() } static func == (lhs: Tagged, rhs: Tagged) -> Bool { return lhs.identifier == rhs.identifier } }
mit
ff2f24daacc42938388656bf509b9389
26.511628
76
0.681319
4.121951
false
false
false
false
ValeryLanin/InstagramFirebase
InstagramFirebase/PhotoSelectorHeader.swift
1
845
// // PhotoSelectorHeader.swift // InstagramFirebase // // Created by Admin on 22.10.17. // Copyright © 2017 Valery Lanin. All rights reserved. // import UIKit class PhotoSelectorHeader: UICollectionViewCell { let photoImageView: UIImageView = { let iv = UIImageView() iv.contentMode = .scaleAspectFill iv.clipsToBounds = true iv.backgroundColor = .cyan return iv }() override init(frame: CGRect) { super.init(frame: frame) addSubview(photoImageView) photoImageView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
a7a7f998ca5df5b21fad7ce7ad3be932
24.575758
192
0.663507
4.395833
false
false
false
false
jarrroo/MarkupKitLint
Tools/Pods/Nimble/Sources/Nimble/Matchers/Contain.swift
33
4060
import Foundation /// A Nimble matcher that succeeds when the actual sequence contains the expected value. public func contain<S: Sequence, T: Equatable>(_ items: T...) -> Predicate<S> where S.Iterator.Element == T { return contain(items) } public func contain<S: Sequence, T: Equatable>(_ items: [T]) -> Predicate<S> where S.Iterator.Element == T { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(arrayAsString(items))>" if let actual = try actualExpression.evaluate() { return items.all { return actual.contains($0) } } return false }.requireNonNil } /// A Nimble matcher that succeeds when the actual string contains the expected substring. public func contain(_ substrings: String...) -> Predicate<String> { return contain(substrings) } public func contain(_ substrings: [String]) -> Predicate<String> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(arrayAsString(substrings))>" if let actual = try actualExpression.evaluate() { return substrings.all { let range = actual.range(of: $0) return range != nil && !range!.isEmpty } } return false }.requireNonNil } /// A Nimble matcher that succeeds when the actual string contains the expected substring. public func contain(_ substrings: NSString...) -> Predicate<NSString> { return contain(substrings) } public func contain(_ substrings: [NSString]) -> Predicate<NSString> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(arrayAsString(substrings))>" if let actual = try actualExpression.evaluate() { return substrings.all { actual.range(of: $0.description).length != 0 } } return false }.requireNonNil } /// A Nimble matcher that succeeds when the actual collection contains the expected object. public func contain(_ items: Any?...) -> Predicate<NMBContainer> { return contain(items) } public func contain(_ items: [Any?]) -> Predicate<NMBContainer> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in failureMessage.postfixMessage = "contain <\(arrayAsString(items))>" guard let actual = try actualExpression.evaluate() else { return false } return items.all { item in return item != nil && actual.contains(item!) } }.requireNonNil } #if _runtime(_ObjC) extension NMBObjCMatcher { public class func containMatcher(_ expected: [NSObject]) -> NMBObjCMatcher { return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in let location = actualExpression.location let actualValue = try! actualExpression.evaluate() if let value = actualValue as? NMBContainer { let expr = Expression(expression: ({ value as NMBContainer }), location: location) // A straightforward cast on the array causes this to crash, so we have to cast the individual items let expectedOptionals: [Any?] = expected.map({ $0 as Any? }) return try! contain(expectedOptionals).matches(expr, failureMessage: failureMessage) } else if let value = actualValue as? NSString { let expr = Expression(expression: ({ value as String }), location: location) return try! contain(expected as! [String]).matches(expr, failureMessage: failureMessage) } else if actualValue != nil { failureMessage.postfixMessage = "contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)" } else { failureMessage.postfixMessage = "contain <\(arrayAsString(expected))>" } return false } } } #endif
mit
d1f8043ae650148a66fb103827c9625c
42.191489
149
0.658374
5.158831
false
false
false
false
lhc70000/iina
iina/PrefUtilsViewController.swift
2
5048
// // PrefUtilsViewController.swift // iina // // Created by Collider LI on 9/7/2018. // Copyright © 2018 lhc. All rights reserved. // import Cocoa class PrefUtilsViewController: PreferenceViewController, PreferenceWindowEmbeddable { override var nibName: NSNib.Name { return NSNib.Name("PrefUtilsViewController") } var preferenceTabTitle: String { return NSLocalizedString("preference.utilities", comment: "Utilities") } var preferenceTabImage: NSImage { return NSImage(named: NSImage.Name("pref_utils"))! } override var sectionViews: [NSView] { return [sectionDefaultAppView, sectionClearCacheView, sectionBrowserExtView] } @IBOutlet var sectionDefaultAppView: NSView! @IBOutlet var sectionClearCacheView: NSView! @IBOutlet var sectionBrowserExtView: NSView! @IBOutlet var setAsDefaultSheet: NSWindow! @IBOutlet weak var setAsDefaultVideoCheckBox: NSButton! @IBOutlet weak var setAsDefaultAudioCheckBox: NSButton! @IBOutlet weak var setAsDefaultPlaylistCheckBox: NSButton! @IBOutlet weak var thumbCacheSizeLabel: NSTextField! @IBOutlet weak var savedPlaybackProgressClearedLabel: NSTextField! @IBOutlet weak var playHistoryClearedLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() DispatchQueue.main.async { self.updateThumbnailCacheStat() } } private func updateThumbnailCacheStat() { thumbCacheSizeLabel.stringValue = "\(FloatingPointByteCountFormatter.string(fromByteCount: CacheManager.shared.getCacheSize(), countStyle: .binary))B" } @IBAction func setIINAAsDefaultAction(_ sender: Any) { view.window!.beginSheet(setAsDefaultSheet) } @IBAction func setAsDefaultOKBtnAction(_ sender: Any) { guard let utiTypes = Bundle.main.infoDictionary?["UTImportedTypeDeclarations"] as? [[String: Any]], let cfBundleID = Bundle.main.bundleIdentifier as CFString? else { return } Logger.log("Set self as default") var successCount = 0 var failedCount = 0 let utiChecked = [ "public.movie": setAsDefaultVideoCheckBox.state == .on, "public.audio": setAsDefaultAudioCheckBox.state == .on, "public.text": setAsDefaultPlaylistCheckBox.state == .on ] for utiType in utiTypes { guard let conformsTo = utiType["UTTypeConformsTo"] as? [String], let tagSpec = utiType["UTTypeTagSpecification"] as? [String: Any], let exts = tagSpec["public.filename-extension"] as? [String] else { return } // make sure that `conformsTo` contains a checked UTI type guard utiChecked.map({ (uti, checked) in checked && conformsTo.contains(uti) }).contains(true) else { continue } for ext in exts { let utiString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext as CFString, nil)!.takeUnretainedValue() let status = LSSetDefaultRoleHandlerForContentType(utiString, .all, cfBundleID) if status == kOSReturnSuccess { successCount += 1 } else { Logger.log("failed for \(ext): return value \(status)", level: .error) failedCount += 1 } } } Utility.showAlert("set_default.success", arguments: [successCount, failedCount], style: .informational, sheetWindow: view.window) view.window!.endSheet(setAsDefaultSheet) } @IBAction func setAsDefaultCancelBtnAction(_ sender: Any) { view.window!.endSheet(setAsDefaultSheet) } @IBAction func clearWatchLaterBtnAction(_ sender: Any) { Utility.quickAskPanel("clear_watch_later", sheetWindow: view.window) { respond in guard respond == .alertFirstButtonReturn else { return } try? FileManager.default.removeItem(atPath: Utility.watchLaterURL.path) Utility.createDirIfNotExist(url: Utility.watchLaterURL) self.savedPlaybackProgressClearedLabel.isHidden = false } } @IBAction func clearHistoryBtnAction(_ sender: Any) { Utility.quickAskPanel("clear_history", sheetWindow: view.window) { respond in guard respond == .alertFirstButtonReturn else { return } try? FileManager.default.removeItem(atPath: Utility.playbackHistoryURL.path) NSDocumentController.shared.clearRecentDocuments(self) Preference.set(nil, for: .iinaLastPlayedFilePath) self.playHistoryClearedLabel.isHidden = false } } @IBAction func clearCacheBtnAction(_ sender: Any) { Utility.quickAskPanel("clear_cache", sheetWindow: view.window) { respond in guard respond == .alertFirstButtonReturn else { return } try? FileManager.default.removeItem(atPath: Utility.thumbnailCacheURL.path) Utility.createDirIfNotExist(url: Utility.thumbnailCacheURL) self.updateThumbnailCacheStat() } } @IBAction func extChromeBtnAction(_ sender: Any) { NSWorkspace.shared.open(URL(string: AppData.chromeExtensionLink)!) } @IBAction func extFirefoxBtnAction(_ sender: Any) { NSWorkspace.shared.open(URL(string: AppData.firefoxExtensionLink)!) } }
gpl-3.0
efb79b77cb44c9355a4e2f065f7a1fbf
34.048611
154
0.715871
4.494212
false
false
false
false
ReactiveX/RxSwift
RxCocoa/iOS/UIPickerView+Rx.swift
1
9329
// // UIPickerView+Rx.swift // RxCocoa // // Created by Segii Shulga on 5/12/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if os(iOS) import RxSwift import UIKit extension Reactive where Base: UIPickerView { /// Reactive wrapper for `delegate`. /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy<UIPickerView, UIPickerViewDelegate> { return RxPickerViewDelegateProxy.proxy(for: base) } /// Installs delegate as forwarding delegate on `delegate`. /// Delegate won't be retained. /// /// It enables using normal delegate mechanism with reactive delegate mechanism. /// /// - parameter delegate: Delegate object. /// - returns: Disposable object that can be used to unbind the delegate. public func setDelegate(_ delegate: UIPickerViewDelegate) -> Disposable { return RxPickerViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) } /** Reactive wrapper for `dataSource`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var dataSource: DelegateProxy<UIPickerView, UIPickerViewDataSource> { return RxPickerViewDataSourceProxy.proxy(for: base) } /** Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`. */ public var itemSelected: ControlEvent<(row: Int, component: Int)> { let source = delegate .methodInvoked(#selector(UIPickerViewDelegate.pickerView(_:didSelectRow:inComponent:))) .map { return (row: try castOrThrow(Int.self, $0[1]), component: try castOrThrow(Int.self, $0[2])) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`. It can be only used when one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods is used to bind observable sequence, or any other data source conforming to a `ViewDataSourceType` protocol. ``` pickerView.rx.modelSelected(MyModel.self) .map { ... ``` - parameter modelType: Type of a Model which bound to the dataSource */ public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<[T]> { let source = itemSelected.flatMap { [weak view = self.base as UIPickerView] _, component -> Observable<[T]> in guard let view = view else { return Observable.empty() } let model: [T] = try (0 ..< view.numberOfComponents).map { component in let row = view.selectedRow(inComponent: component) return try view.rx.model(at: IndexPath(row: row, section: component)) } return Observable.just(model) } return ControlEvent(events: source) } /** Binds sequences of elements to picker view rows. - parameter source: Observable sequence of items. - parameter titleForRow: Transform between sequence elements and row titles. - returns: Disposable object that can be used to unbind. Example: let items = Observable.just([ "First Item", "Second Item", "Third Item" ]) items .bind(to: pickerView.rx.itemTitles) { (row, element) in return element } .disposed(by: disposeBag) */ public func itemTitles<Sequence: Swift.Sequence, Source: ObservableType> (_ source: Source) -> (_ titleForRow: @escaping (Int, Sequence.Element) -> String?) -> Disposable where Source.Element == Sequence { return { titleForRow in let adapter = RxStringPickerViewAdapter<Sequence>(titleForRow: titleForRow) return self.items(adapter: adapter)(source) } } /** Binds sequences of elements to picker view rows. - parameter source: Observable sequence of items. - parameter attributedTitleForRow: Transform between sequence elements and row attributed titles. - returns: Disposable object that can be used to unbind. Example: let items = Observable.just([ "First Item", "Second Item", "Third Item" ]) items .bind(to: pickerView.rx.itemAttributedTitles) { (row, element) in return NSAttributedString(string: element) } .disposed(by: disposeBag) */ public func itemAttributedTitles<Sequence: Swift.Sequence, Source: ObservableType> (_ source: Source) -> (_ attributedTitleForRow: @escaping (Int, Sequence.Element) -> NSAttributedString?) -> Disposable where Source.Element == Sequence { return { attributedTitleForRow in let adapter = RxAttributedStringPickerViewAdapter<Sequence>(attributedTitleForRow: attributedTitleForRow) return self.items(adapter: adapter)(source) } } /** Binds sequences of elements to picker view rows. - parameter source: Observable sequence of items. - parameter viewForRow: Transform between sequence elements and row views. - returns: Disposable object that can be used to unbind. Example: let items = Observable.just([ "First Item", "Second Item", "Third Item" ]) items .bind(to: pickerView.rx.items) { (row, element, view) in guard let myView = view as? MyView else { let view = MyView() view.configure(with: element) return view } myView.configure(with: element) return myView } .disposed(by: disposeBag) */ public func items<Sequence: Swift.Sequence, Source: ObservableType> (_ source: Source) -> (_ viewForRow: @escaping (Int, Sequence.Element, UIView?) -> UIView) -> Disposable where Source.Element == Sequence { return { viewForRow in let adapter = RxPickerViewAdapter<Sequence>(viewForRow: viewForRow) return self.items(adapter: adapter)(source) } } /** Binds sequences of elements to picker view rows using a custom reactive adapter used to perform the transformation. This method will retain the adapter for as long as the subscription isn't disposed (result `Disposable` being disposed). In case `source` observable sequence terminates successfully, the adapter will present latest element until the subscription isn't disposed. - parameter adapter: Adapter used to transform elements to picker components. - parameter source: Observable sequence of items. - returns: Disposable object that can be used to unbind. */ public func items<Source: ObservableType, Adapter: RxPickerViewDataSourceType & UIPickerViewDataSource & UIPickerViewDelegate>(adapter: Adapter) -> (_ source: Source) -> Disposable where Source.Element == Adapter.Element { return { source in let delegateSubscription = self.setDelegate(adapter) let dataSourceSubscription = source.subscribeProxyDataSource(ofObject: self.base, dataSource: adapter, retainDataSource: true, binding: { [weak pickerView = self.base] (_: RxPickerViewDataSourceProxy, event) in guard let pickerView = pickerView else { return } adapter.pickerView(pickerView, observedEvent: event) }) return Disposables.create(delegateSubscription, dataSourceSubscription) } } /** Synchronous helper method for retrieving a model at indexPath through a reactive data source. */ public func model<T>(at indexPath: IndexPath) throws -> T { let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods was used.") return castOrFatalError(try dataSource.model(at: indexPath)) } } #endif
mit
db2da24fee0bfdf6dbbf7a39111da2ee
40.642857
244
0.572041
5.826359
false
false
false
false
weyert/Whisper
Source/Configuration/ColorList.swift
1
606
import UIKit public struct ColorList { public struct Shout { public static var background = UIColor.whiteColor() public static var dragIndicator = UIColor(red:0.90, green:0.90, blue:0.90, alpha:1) public static var title = UIColor.blackColor() public static var subtitle = UIColor.blackColor() } public struct Whistle { public static var background = UIColor.whiteColor() public static var title = UIColor.blackColor() } public struct Disclosure { public static var background = UIColor.whiteColor() public static var title = UIColor.blackColor() } }
mit
8673183ba080be7a72053958f14a301f
26.545455
87
0.707921
4.455882
false
false
false
false
taktamur/BondSample
Pods/Bond/Bond/Core/EventProducer.swift
6
6919
// // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public enum EventProducerLifecycle { case Normal /// Normal lifecycle (alive as long as there exists at least one strong reference to it). case Managed /// Normal + retained by the sink given to the producer whenever there is at least one observer. } /// Enables production of the events and dispatches them to the registered observers. public class EventProducer<Event>: EventProducerType { private var isDispatchInProgress: Bool = false private var observers: [Int64:Event -> Void] = [:] private var nextToken: Int64 = 0 private let lock = NSRecursiveLock(name: "com.swift-bond.Bond.EventProducer") internal private(set) var replayBuffer: Buffer<Event>? = nil /// Type of the sink used by the event producer. public typealias Sink = Event -> Void /// Number of events to replay to each new observer. public var replayLength: Int { return replayBuffer?.size ?? 0 } /// A composite disposable that will be disposed when the event producer is deallocated. public let deinitDisposable = CompositeDisposable() /// Internal buffer for event replaying. /// Used to manage lifecycle of the event producer when lifetime == .Managed. /// Captured by the producer sink. It will hold a strong reference to self /// when there is at least one observer registered. /// /// When all observers are unregistered, the reference will weakify its reference to self. /// That means the event producer will be deallocated if no one else holds a strong reference to it. /// Deallocation will dispose `deinitDisposable` and thus break the connection with the source. private weak var selfReference: Reference<EventProducer<Event>>? = nil /// Consult `EventProducerLifecycle` for more info. public private(set) var lifecycle: EventProducerLifecycle /// Creates a new event producer with the given replay length and the producer that is used /// to generate events that will be dispatched to the registered observers. /// /// Replay length specifies how many previous events should be buffered and then replayed /// to each new observer. Event producer buffers only latest `replayLength` events, discarding old ones. /// /// Producer closure will be executed immediately. It will receive a sink into which /// events can be dispatched. If producer returns a disposable, the observable will store /// it and dispose upon [observable's] deallocation. public init(replayLength: Int = 0, lifecycle: EventProducerLifecycle = .Managed, @noescape producer: Sink -> DisposableType?) { self.lifecycle = lifecycle let tmpSelfReference = Reference(self) tmpSelfReference.release() if replayLength > 0 { replayBuffer = Buffer(size: replayLength) } let disposable = producer { event in tmpSelfReference.object?.next(event) } if let disposable = disposable { deinitDisposable += disposable } self.selfReference = tmpSelfReference } public init(replayLength: Int = 0, lifecycle: EventProducerLifecycle = .Normal) { self.lifecycle = lifecycle if replayLength > 0 { replayBuffer = Buffer(size: replayLength) } } /// Sends an event to the observers public func next(event: Event) { replayBuffer?.push(event) dispatchNext(event) } /// Registers the given observer and returns a disposable that can cancel observing. public func observe(observer: Event -> Void) -> DisposableType { if lifecycle == .Managed { selfReference?.retain() } let eventProducerBaseDisposable = addObserver(observer) replayBuffer?.replayTo(observer) let observerDisposable = BlockDisposable { [weak self] in eventProducerBaseDisposable.dispose() if let unwrappedSelf = self { if unwrappedSelf.observers.count == 0 { unwrappedSelf.selfReference?.release() } } } deinitDisposable += observerDisposable return observerDisposable } private func dispatchNext(event: Event) { guard !isDispatchInProgress else { return } lock.lock() isDispatchInProgress = true for (_, send) in observers { send(event) } isDispatchInProgress = false lock.unlock() } private func addObserver(observer: Event -> Void) -> DisposableType { lock.lock() let token = nextToken nextToken = nextToken + 1 lock.unlock() observers[token] = observer return EventProducerDisposable(eventProducer: self, token: token) } private func removeObserver(disposable: EventProducerDisposable<Event>) { observers.removeValueForKey(disposable.token) } deinit { deinitDisposable.dispose() } } extension EventProducer: BindableType { /// Creates a new sink that can be used to update the receiver. /// Optionally accepts a disposable that will be disposed on receiver's deinit. public func sink(disconnectDisposable: DisposableType?) -> Event -> Void { if let disconnectDisposable = disconnectDisposable { deinitDisposable += disconnectDisposable } return { [weak self] value in self?.next(value) } } } public final class EventProducerDisposable<EventType>: DisposableType { private weak var eventProducer: EventProducer<EventType>! private var token: Int64 public var isDisposed: Bool { return eventProducer == nil } private init(eventProducer: EventProducer<EventType>, token: Int64) { self.eventProducer = eventProducer self.token = token } public func dispose() { if let eventProducer = eventProducer { eventProducer.removeObserver(self) self.eventProducer = nil } } }
bsd-2-clause
cea72a760712197c4595411bfa637350
33.252475
129
0.709351
4.845238
false
false
false
false
chenyunguiMilook/VisualDebugger
Sources/VisualDebugger/extensions/CGRect+Behavior.swift
1
1865
// // CGRect+Behavior.swift // VisualDebugger // // Created by chenyungui on 2018/3/19. // import Foundation import CoreGraphics #if os(iOS) || os(tvOS) import UIKit #else import Cocoa #endif extension CGRect { public static let unit: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1) public var affineRect: AffineRect { return AffineRect(x: origin.x, y: origin.y, width: width, height: height) } internal func fixed() -> CGRect { guard self.width == 0 || self.height == 0 else { return self } let width = self.width == 0 ? min(self.height / 2, 1) : self.width let height = self.height == 0 ? min(self.width / 2, 1) : self.height return CGRect(origin: self.origin, size: CGSize(width: width, height: height)) } public var rectFromOrigin: CGRect { let minX = min(0, self.minX) let minY = min(0, self.minY) let maxX = max(0, self.maxX) let maxY = max(0, self.maxY) return CGRect(x: minX, y: minY, width: maxX-minX, height: maxY-minY) } } extension CGRect : Debuggable { public var bounds: CGRect { return self } public func debug(in coordinate: CoordinateSystem, color: AppColor?) { let rect = self.applying(coordinate.matrix) let color = color ?? coordinate.getNextColor() let path = AppBezierPath.init(rect: rect) let shape = CAShapeLayer.init(path: path.cgPath, strokeColor: color, fillColor: nil, lineWidth: 1) coordinate.addSublayer(shape) } } extension Array where Element == CGRect { public var bounds: CGRect { guard !self.isEmpty else { return .zero } var rect = self[0] for i in 1 ..< self.count { rect = self[i].union(rect) } return rect } }
mit
6be6254df9f7aec5366ffc9ac6c04cd3
27.692308
87
0.591421
3.821721
false
false
false
false
hernanc/swift-1
Pitch Perfect/PlaySoundsViewController.swift
1
2516
// // PlaySoundsViewController.swift // Pitch Perfect // // Created by HernanGCalabrese on 4/11/15. // Copyright (c) 2015 Ouiea. All rights reserved. // import UIKit import AVFoundation class PlaySoundsViewController: UIViewController { var audioPlayer:AVAudioPlayer! var receivedAudio:RecordedAudio! var audioEngine:AVAudioEngine! var audioFile:AVAudioFile! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filePathUrl, error: nil) audioPlayer.enableRate = true audioPlayer.prepareToPlay() audioEngine = AVAudioEngine() audioFile = AVAudioFile(forReading: receivedAudio.filePathUrl, error: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func playAudioWithVariablePitch(pitch: Float){ audioPlayer.stop() audioEngine.stop() audioEngine.reset() var audioPlayerNode = AVAudioPlayerNode() audioEngine.attachNode(audioPlayerNode) var changePitchEffect = AVAudioUnitTimePitch() changePitchEffect.pitch = pitch audioEngine.attachNode(changePitchEffect) audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil) audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil) audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil) audioEngine.startAndReturnError(nil) audioPlayerNode.play() } func playAudio(speed: Float){ audioPlayer.stop() audioEngine.stop() audioEngine.reset() audioPlayer.rate = speed audioPlayer.currentTime = 0 audioPlayer.play() } @IBAction func playSlow(sender: UIButton) { playAudio(0.5) } @IBAction func playFast(sender: UIButton) { playAudio(2.0) } @IBAction func playChipmunkAudio(sender: UIButton) { playAudioWithVariablePitch(1000) } @IBAction func playDarthvaderAudio(sender: UIButton) { playAudioWithVariablePitch(-1000) } @IBAction func stopAudio(sender: UIButton) { audioPlayer.stop() audioEngine.stop() audioEngine.reset() } }
mit
b8cba10ec5b6abb21bd1de8dea239111
26.347826
89
0.646264
5.219917
false
false
false
false
derekli66/Learning-Core-Audio-Swift-SampleCode
CH09_OpenALOrbitLoop-Swift/CH09_OpenALOrbitLoop-Swift/main.swift
1
8147
// // main.swift // CH09_OpenALOrbitLoop-Swift // // Created by LEE CHIEN-MING on 19/08/2017. // Copyright © 2017 derekli66. All rights reserved. // import Foundation import AudioToolbox import OpenAL private let LOOP_PATH = "/Library/Audio/Apple Loops/Apple/iLife Sound Effects/Transportation/Bicycle Coasting.caf" private let ORBIT_SPEED = 1 private let RUN_TIME = 20.0 private extension Int { func toUInt32() -> UInt32 { return UInt32(self) } func toFloat64() -> Float64 { return Float64(self) } func toDouble() -> Double { return Double(self) } } private extension Int64 { func toUInt32() -> UInt32 { return UInt32(self) } func toFloat64() -> Float64 { return Float64(self) } func toDouble() -> Double { return Double(self) } } private extension UInt32 { func toInt() -> Int { return Int(self) } } class MyLoopPlayer { var dataFormat: AudioStreamBasicDescription = AudioStreamBasicDescription() var sampleBuffer: UnsafeMutablePointer<UInt16>? var bufferSizeBytes: UInt32 = 0 var sources: ALuint = 0 } func CheckALError(_ operation: String) -> Void { let alErr = alGetError() if alErr == AL_NO_ERROR { return } var errFormat = "" switch alErr { case AL_INVALID_NAME: errFormat = "OpenAL Error: \(operation) (AL_INVALID_NAME)" case AL_INVALID_VALUE: errFormat = "OpenAL Error: \(operation) (AL_INVALID_VALUE)" case AL_INVALID_ENUM: errFormat = "OpenAL Error: \(operation) (AL_INVALID_ENUM)" case AL_INVALID_OPERATION: errFormat = "OpenAL Error: \(operation) (AL_INVALID_OPERATION)" case AL_OUT_OF_MEMORY: errFormat = "OpenAL Error: \(operation) (AL_OUT_OF_MEMORY)" default: break } debugPrint(errFormat) exit(1) } private func sizeof<T>(_ instance: T) -> Int { return MemoryLayout.size(ofValue: instance) } private func sizeof<T>(_ type: T.Type) -> Int { return MemoryLayout<T>.size } func updateSourceLocation(_ player: MyLoopPlayer) -> Void { let theta: Double = fmod( CFAbsoluteTimeGetCurrent() * ORBIT_SPEED.toDouble() , Double.pi * 2.0) let x: ALfloat = ALfloat( 3 * cos(theta)) let y: ALfloat = ALfloat(0.5 * sin(theta)) let z: ALfloat = ALfloat(1.0 * sin(theta)) debugPrint("x=\(x), y=\(y), z=\(z)") alSource3f(player.sources, AL_POSITION, x, y, z) } func loadLoopIntoBuffer(_ player: MyLoopPlayer) -> OSStatus { let loopFileURL = URL(fileURLWithPath: LOOP_PATH) // describe the client format - AL needs mono player.dataFormat = AudioStreamBasicDescription(mSampleRate: 44100.0, mFormatID: kAudioFormatLinearPCM, mFormatFlags: kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked, mBytesPerPacket: 2, mFramesPerPacket: 1, mBytesPerFrame: 2, mChannelsPerFrame: 1, mBitsPerChannel: 16, mReserved: 0) var extAudioFile: ExtAudioFileRef? CheckError(ExtAudioFileOpenURL(loopFileURL as CFURL, &extAudioFile), "Couldn't open ExtAudioFile for reading") guard let extAudioFileUnwrapped = extAudioFile else { return kAudioFileFileNotFoundError } // tell extAudioFile about our format CheckError(ExtAudioFileSetProperty(extAudioFileUnwrapped, kExtAudioFileProperty_ClientDataFormat, sizeof(AudioStreamBasicDescription.self).toUInt32(), &player.dataFormat), "Couldn't set client format on ExtAudioFile") // figure out how big a buffer we need var fileLengthFrames: Int64 = 0 var propSize: UInt32 = sizeof(fileLengthFrames).toUInt32() CheckError(ExtAudioFileGetProperty(extAudioFileUnwrapped, kExtAudioFileProperty_FileLengthFrames, &propSize, &fileLengthFrames), "Couldn't get file length frames from ExtAudioFile") debugPrint("plan on reading \(fileLengthFrames) frames") player.bufferSizeBytes = fileLengthFrames.toUInt32() * player.dataFormat.mBytesPerFrame let buffersRef: UnsafeMutableAudioBufferListPointer = AudioBufferList.allocate(maximumBuffers: 1) // allocate sample buffer player.sampleBuffer = UnsafeMutablePointer<UInt16>.allocate(capacity: player.bufferSizeBytes.toInt()) buffersRef[0].mNumberChannels = 1 buffersRef[0].mDataByteSize = player.bufferSizeBytes buffersRef[0].mData = UnsafeMutableRawPointer(player.sampleBuffer) debugPrint("Created AudioBufferList") // loop reading into the ABL until buffer is full var totalFramesRead: UInt32 = 0 repeat { var framesRead: UInt32 = fileLengthFrames.toUInt32() - totalFramesRead; guard let sampleBuffer = player.sampleBuffer else { break } buffersRef[0].mData = UnsafeMutableRawPointer(sampleBuffer + Int(totalFramesRead * sizeof(UInt16.self).toUInt32())) CheckError(ExtAudioFileRead(extAudioFileUnwrapped, &framesRead, buffersRef.unsafeMutablePointer), "ExtAudioFileRead failed") totalFramesRead += framesRead debugPrint("Read \(framesRead) frames") } while (totalFramesRead < fileLengthFrames.toUInt32()) free(buffersRef.unsafeMutablePointer) return noErr } typealias ALCdevice = OpaquePointer typealias ALCcontext = OpaquePointer func main() { let player: MyLoopPlayer = MyLoopPlayer() // convert to an OpenAL-friendly format and read into memory CheckError(loadLoopIntoBuffer(player), "Couldn't load loop into buffer") // set up OpenAL buffer let alDevice: ALCdevice = alcOpenDevice(nil) CheckALError("Couldn't open AL device") let alContext: ALCcontext = alcCreateContext(alDevice, nil) CheckALError("Couldn't open AL context") alcMakeContextCurrent(alContext) CheckALError("Couldn't make AL context current") var buffers: Array<ALuint> = [ALuint(0)] // var buffers: ALuint = ALuint(0) alGenBuffers(1, &buffers) CheckALError("Couldn't generate buffers") alBufferData(buffers[0], AL_FORMAT_MONO16, player.sampleBuffer, ALsizei(player.bufferSizeBytes), ALsizei(player.dataFormat.mSampleRate)) // AL copies the samples, so we can free them now free(player.sampleBuffer) // set up OpenAL source alGenSources(1, &player.sources) CheckALError("Couldn't generate sources"); alSourcei(player.sources, AL_LOOPING, AL_TRUE) CheckALError("Couldn't set source looping property") alSourcef(player.sources, AL_GAIN, ALfloat(AL_MAX_GAIN)) CheckALError("Couldn't set source again") updateSourceLocation(player) CheckALError("Couldn't set initial source position") // connect buffer to source alSourcei(player.sources, AL_BUFFER, ALint(buffers[0])) CheckALError("Couldn't connect buffer to source") // set up listener alListener3f(AL_POSITION, 0.0, 0.0, 0.0) // start playing alSourcePlay(player.sources) // and wait print("Playing...") let startTime: time_t = time(nil) repeat { // get next theta updateSourceLocation(player) CheckALError("Couldn't set looping source position") CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 0.1, false) } while (difftime(time(nil), startTime) < RUN_TIME) // cleanup: alSourceStop(player.sources) alDeleteSources(1, &player.sources) alDeleteBuffers(1, &buffers) alcDestroyContext(alContext) alcCloseDevice(alDevice) print("Bottom of main") } main()
mit
937d49b5445be242bc2a36415a89d57b
32.80083
125
0.635281
4.604862
false
false
false
false
rajeejones/SavingPennies
Saving Pennies/LogicController.swift
1
13053
// // LogicController.swift // Saving Pennies // // Created by Rajee Jones on 2/28/17. // Copyright © 2017 Rajee Jones. All rights reserved. // import Foundation class LogicController { var lvl:Level! fileprivate var comboMultiplier = 0 init(withLevel lvel:Level) { lvl = lvel } func coinAtColumn(_ column: Int, row: Int) -> Coin? { assert(column >= 0 && column < NumColumns) assert(row >= 0 && row < NumRows) return lvl.coins[column, row] } func shuffle() -> Set<Coin> { var set: Set<Coin> repeat { set = createInitialCoins() detectPossibleSwaps() print("possible swaps: \(lvl.possibleSwaps)") } while lvl.possibleSwaps.count == 0 return set } fileprivate func calculateScores(chains: Set<Chain>) { // 3-chain is 60 pts, 4-chain is 120, 5-chain is 180, and so on for chain in chains { switch chain.firstCoin().cointype { case .penny: chain.score = 40 * (chain.length - 2) * comboMultiplier break case .bag: chain.score = 100 * (chain.length - 2) * comboMultiplier //print("Matched a BAG!") break case .tag: chain.score = -40 * (chain.length - 2) * comboMultiplier //print("Matched a TAG!") break default: chain.score = 60 * (chain.length - 2) * comboMultiplier } comboMultiplier += 1 } } fileprivate func createInitialCoins() -> Set<Coin> { var set = Set<Coin>() // 1 for row in 0..<NumRows { for column in 0..<NumColumns { if lvl.tiles[column, row] != nil { // 2 var coinType: CoinType repeat { coinType = CoinType.random() } while (column >= 2 && lvl.coins[column - 1, row]?.cointype == coinType && lvl.coins[column - 2, row]?.cointype == coinType) || (row >= 2 && lvl.coins[column, row - 1]?.cointype == coinType && lvl.coins[column, row - 2]?.cointype == coinType) // 3 let coin = Coin(column: column, row: row, cointype: coinType) lvl.coins[column, row] = coin // 4 set.insert(coin) } } } return set } func tileAtColumn(_ column: Int, row: Int) -> Tile? { assert(column >= 0 && column < NumColumns) assert(row >= 0 && row < NumRows) return lvl.tiles[column, row] } func performSwap(_ swap: Swap) { let columnA = swap.coinA.column let rowA = swap.coinA.row let columnB = swap.coinB.column let rowB = swap.coinB.row lvl.coins[columnA, rowA] = swap.coinB swap.coinB.column = columnA swap.coinB.row = rowA lvl.coins[columnB, rowB] = swap.coinA swap.coinA.column = columnB swap.coinA.row = rowB } fileprivate func hasChainAtColumn(_ column: Int, row: Int) -> Bool { let coinType = lvl.coins[column, row]?.cointype // Horizontal chain check var horzLength = 1 // Left var i = column - 1 while i >= 0 && lvl.coins[i, row]?.cointype == coinType { i -= 1 horzLength += 1 } // Right i = column + 1 while i < NumColumns && lvl.coins[i, row]?.cointype == coinType { i += 1 horzLength += 1 } if horzLength >= 3 { return true } // Vertical chain check var vertLength = 1 // Down i = row - 1 while i >= 0 && lvl.coins[column, i]?.cointype == coinType { i -= 1 vertLength += 1 } // Up i = row + 1 while i < NumRows && lvl.coins[column, i]?.cointype == coinType { i += 1 vertLength += 1 } return vertLength >= 3 } func detectPossibleSwaps() { var set = Set<Swap>() for row in 0..<NumRows { for column in 0..<NumColumns { if let coin = lvl.coins[column, row] { // Is it possible to swap this coin with the one on the right? if column < NumColumns - 1 { // Have a coin in this spot? If there is no tile, there is no coin. if let other = lvl.coins[column + 1, row] { // Swap them lvl.coins[column, row] = other lvl.coins[column + 1, row] = coin // Is either coin now part of a chain? if hasChainAtColumn(column + 1, row: row) || hasChainAtColumn(column, row: row) { set.insert(Swap(coinA: coin, coinB: other)) } // Swap them back lvl.coins[column, row] = coin lvl.coins[column + 1, row] = other } } if row < NumRows - 1 { if let other = lvl.coins[column, row + 1] { lvl.coins[column, row] = other lvl.coins[column, row + 1] = coin // Is either coin now part of a chain? if hasChainAtColumn(column, row: row + 1) || hasChainAtColumn(column, row: row) { set.insert(Swap(coinA: coin, coinB: other)) } // Swap them back lvl.coins[column, row] = coin lvl.coins[column, row + 1] = other } } } } } lvl.possibleSwaps = set } func isPossibleSwap(_ swap: Swap) -> Bool { return lvl.possibleSwaps.contains(swap) } func removeMatches() -> Set<Chain> { let horizontalChains = detectHorizontalMatches() let verticalChains = detectVerticalMatches() //let lChains = detectLtypeMatches() removeCoins(horizontalChains) removeCoins(verticalChains) //removeCoins(lChains) // print("L type matches: \(lChains)") calculateScores(chains:horizontalChains) calculateScores(chains:verticalChains) //calculateScores(chains:lChains) return horizontalChains.union(verticalChains) } func fillHoles() -> [[Coin]] { var columns = [[Coin]]() // 1 for column in 0..<NumColumns { var array = [Coin]() for row in 0..<NumRows { // 2 if lvl.tiles[column, row] != nil && lvl.coins[column, row] == nil { // 3 for lookup in (row + 1)..<NumRows { if let coin = lvl.coins[column, lookup] { // 4 lvl.coins[column, lookup] = nil lvl.coins[column, row] = coin coin.row = row // 5 array.append(coin) // 6 break } } } } // 7 if !array.isEmpty { columns.append(array) } } return columns } func topUpCoins() -> [[Coin]] { var columns = [[Coin]]() var coinType: CoinType = .unknown for column in 0..<NumColumns { var array = [Coin]() // 1 var row = NumRows - 1 while row >= 0 && lvl.coins[column, row] == nil { // 2 if lvl.tiles[column, row] != nil { // 3 var newCoinType: CoinType repeat { newCoinType = CoinType.random() } while newCoinType == coinType coinType = newCoinType // 4 let coin = Coin(column: column, row: row, cointype: coinType) lvl.coins[column, row] = coin array.append(coin) } row -= 1 } // 5 if !array.isEmpty { columns.append(array) } } return columns } fileprivate func removeCoins(_ chains: Set<Chain>) { for chain in chains { for coin in chain.coins { lvl.coins[coin.column, coin.row] = nil } } } fileprivate func detectHorizontalMatches() -> Set<Chain> { // 1 var set = Set<Chain>() // 2 for row in 0..<NumRows { var column = 0 while column < NumColumns-2 { // 3 if let coin = lvl.coins[column, row] { let matchType = coin.cointype // 4 if lvl.coins[column + 1, row]?.cointype == matchType && lvl.coins[column + 2, row]?.cointype == matchType { // 5 let chain = Chain(chainType: .horizontal) repeat { chain.addCoin(lvl.coins[column, row]!) column += 1 } while column < NumColumns && lvl.coins[column, row]?.cointype == matchType set.insert(chain) continue } } // 6 column += 1 } } return set } fileprivate func detectLtypeMatches() -> Set<Chain> { // 1 var set = Set<Chain>() // 2 for indexRow in 0..<NumRows { var row = indexRow var column = indexRow while column < NumColumns-2 && row < NumRows-2 { // 3 if let coin = lvl.coins[column, row] { let matchType = coin.cointype // 4 if lvl.coins[column + 1, row]?.cointype == matchType && lvl.coins[column, row + 1]?.cointype == matchType { // 5 let chain = Chain(chainType: .ltype) repeat { chain.addCoin(lvl.coins[column, row]!) column += 1 row += 1 } while column < NumColumns && row < NumRows && lvl.coins[column, row]?.cointype == matchType set.insert(chain) continue } } // 6 column += 1 row += 1 } } return set } fileprivate func detectVerticalMatches() -> Set<Chain> { var set = Set<Chain>() for column in 0..<NumColumns { var row = 0 while row < NumRows-2 { if let coin = lvl.coins[column, row] { let matchType = coin.cointype if lvl.coins[column, row + 1]?.cointype == matchType && lvl.coins[column, row + 2]?.cointype == matchType { let chain = Chain(chainType: .vertical) repeat { chain.addCoin(lvl.coins[column, row]!) row += 1 } while row < NumRows && lvl.coins[column, row]?.cointype == matchType set.insert(chain) continue } } row += 1 } } return set } func resetComboMultiplier() { comboMultiplier = 1 } }
gpl-3.0
9bafe1d40fce787fabbb642d5247c690
32.295918
117
0.404382
5.307849
false
false
false
false
bryan1anderson/iMessage-to-Day-One-Importer
Pods/SQLite.swift/Sources/SQLite/Typed/Operators.swift
1
23311
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // // TODO: use `@warn_unused_result` by the time operator functions support it public func +(lhs: Expression<String>, rhs: Expression<String>) -> Expression<String> { return "||".infix(lhs, rhs) } public func +(lhs: Expression<String>, rhs: Expression<String?>) -> Expression<String?> { return "||".infix(lhs, rhs) } public func +(lhs: Expression<String?>, rhs: Expression<String>) -> Expression<String?> { return "||".infix(lhs, rhs) } public func +(lhs: Expression<String?>, rhs: Expression<String?>) -> Expression<String?> { return "||".infix(lhs, rhs) } public func +(lhs: Expression<String>, rhs: String) -> Expression<String> { return "||".infix(lhs, rhs) } public func +(lhs: Expression<String?>, rhs: String) -> Expression<String?> { return "||".infix(lhs, rhs) } public func +(lhs: String, rhs: Expression<String>) -> Expression<String> { return "||".infix(lhs, rhs) } public func +(lhs: String, rhs: Expression<String?>) -> Expression<String?> { return "||".infix(lhs, rhs) } // MARK: - public func +<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func +<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func +<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func +<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func +<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func +<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func +<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func +<V: Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func -<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func -<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func -<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func -<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func -<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func -<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func -<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func -<V: Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func *<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func *<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func *<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func *<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func *<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func *<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func *<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func *<V: Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func /<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func /<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func /<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func /<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func /<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func /<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public func /<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return infix(lhs, rhs) } public func /<V: Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return infix(lhs, rhs) } public prefix func -<V : Value>(rhs: Expression<V>) -> Expression<V> where V.Datatype : Number { return wrap(rhs) } public prefix func -<V : Value>(rhs: Expression<V?>) -> Expression<V?> where V.Datatype : Number { return wrap(rhs) } // MARK: - public func %<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func %<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func %<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func %<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func %<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func %<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func %<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func %<V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func <<<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func <<<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func <<<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func <<<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func <<<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func <<<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func <<<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func <<<V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func >><V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func >><V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func >><V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func >><V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func >><V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func >><V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func >><V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func >><V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func &<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func &<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func &<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func &<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func &<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func &<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func &<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func &<V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func |<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func |<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func |<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func |<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func |<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func |<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func |<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return infix(lhs, rhs) } public func |<V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return infix(lhs, rhs) } public func ^<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return (~(lhs & rhs)) & (lhs | rhs) } public func ^<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return (~(lhs & rhs)) & (lhs | rhs) } public func ^<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<V?> where V.Datatype == Int64 { return (~(lhs & rhs)) & (lhs | rhs) } public func ^<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return (~(lhs & rhs)) & (lhs | rhs) } public func ^<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<V> where V.Datatype == Int64 { return (~(lhs & rhs)) & (lhs | rhs) } public func ^<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<V?> where V.Datatype == Int64 { return (~(lhs & rhs)) & (lhs | rhs) } public func ^<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return (~(lhs & rhs)) & (lhs | rhs) } public func ^<V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return (~(lhs & rhs)) & (lhs | rhs) } public prefix func ~<V : Value>(rhs: Expression<V>) -> Expression<V> where V.Datatype == Int64 { return wrap(rhs) } public prefix func ~<V : Value>(rhs: Expression<V?>) -> Expression<V?> where V.Datatype == Int64 { return wrap(rhs) } // MARK: - public func ==<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Equatable { return "=".infix(lhs, rhs) } public func ==<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Equatable { return "=".infix(lhs, rhs) } public func ==<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<Bool?> where V.Datatype : Equatable { return "=".infix(lhs, rhs) } public func ==<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Equatable { return "=".infix(lhs, rhs) } public func ==<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<Bool> where V.Datatype : Equatable { return "=".infix(lhs, rhs) } public func ==<V : Value>(lhs: Expression<V?>, rhs: V?) -> Expression<Bool?> where V.Datatype : Equatable { guard let rhs = rhs else { return "IS".infix(lhs, Expression<V?>(value: nil)) } return "=".infix(lhs, rhs) } public func ==<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Equatable { return "=".infix(lhs, rhs) } public func ==<V : Value>(lhs: V?, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Equatable { guard let lhs = lhs else { return "IS".infix(Expression<V?>(value: nil), rhs) } return "=".infix(lhs, rhs) } public func !=<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Equatable { return infix(lhs, rhs) } public func !=<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Equatable { return infix(lhs, rhs) } public func !=<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<Bool?> where V.Datatype : Equatable { return infix(lhs, rhs) } public func !=<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Equatable { return infix(lhs, rhs) } public func !=<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<Bool> where V.Datatype : Equatable { return infix(lhs, rhs) } public func !=<V : Value>(lhs: Expression<V?>, rhs: V?) -> Expression<Bool?> where V.Datatype : Equatable { guard let rhs = rhs else { return "IS NOT".infix(lhs, Expression<V?>(value: nil)) } return infix(lhs, rhs) } public func !=<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Equatable { return infix(lhs, rhs) } public func !=<V : Value>(lhs: V?, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Equatable { guard let lhs = lhs else { return "IS NOT".infix(Expression<V?>(value: nil), rhs) } return infix(lhs, rhs) } public func ><V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func ><V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func ><V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func ><V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func ><V : Value>(lhs: Expression<V>, rhs: V) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func ><V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func ><V : Value>(lhs: V, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func ><V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func >=<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func >=<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func >=<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func >=<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func >=<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func >=<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func >=<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func >=<V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <<V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <=<V : Value>(lhs: Expression<V>, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <=<V : Value>(lhs: Expression<V>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <=<V : Value>(lhs: Expression<V?>, rhs: Expression<V>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <=<V : Value>(lhs: Expression<V?>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <=<V : Value>(lhs: Expression<V>, rhs: V) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <=<V : Value>(lhs: Expression<V?>, rhs: V) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <=<V : Value>(lhs: V, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return infix(lhs, rhs) } public func <=<V : Value>(lhs: V, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return infix(lhs, rhs) } public func ~=<V : Value>(lhs: ClosedRange<V>, rhs: Expression<V>) -> Expression<Bool> where V.Datatype : Comparable { return Expression("\(rhs.template) BETWEEN ? AND ?", rhs.bindings + [lhs.lowerBound as? Binding, lhs.upperBound as? Binding]) } public func ~=<V : Value>(lhs: ClosedRange<V>, rhs: Expression<V?>) -> Expression<Bool?> where V.Datatype : Comparable { return Expression("\(rhs.template) BETWEEN ? AND ?", rhs.bindings + [lhs.lowerBound as? Binding, lhs.upperBound as? Binding]) } // MARK: - public func &&(lhs: Expression<Bool>, rhs: Expression<Bool>) -> Expression<Bool> { return "AND".infix(lhs, rhs) } public func &&(lhs: Expression<Bool>, rhs: Expression<Bool?>) -> Expression<Bool?> { return "AND".infix(lhs, rhs) } public func &&(lhs: Expression<Bool?>, rhs: Expression<Bool>) -> Expression<Bool?> { return "AND".infix(lhs, rhs) } public func &&(lhs: Expression<Bool?>, rhs: Expression<Bool?>) -> Expression<Bool?> { return "AND".infix(lhs, rhs) } public func &&(lhs: Expression<Bool>, rhs: Bool) -> Expression<Bool> { return "AND".infix(lhs, rhs) } public func &&(lhs: Expression<Bool?>, rhs: Bool) -> Expression<Bool?> { return "AND".infix(lhs, rhs) } public func &&(lhs: Bool, rhs: Expression<Bool>) -> Expression<Bool> { return "AND".infix(lhs, rhs) } public func &&(lhs: Bool, rhs: Expression<Bool?>) -> Expression<Bool?> { return "AND".infix(lhs, rhs) } public func ||(lhs: Expression<Bool>, rhs: Expression<Bool>) -> Expression<Bool> { return "OR".infix(lhs, rhs) } public func ||(lhs: Expression<Bool>, rhs: Expression<Bool?>) -> Expression<Bool?> { return "OR".infix(lhs, rhs) } public func ||(lhs: Expression<Bool?>, rhs: Expression<Bool>) -> Expression<Bool?> { return "OR".infix(lhs, rhs) } public func ||(lhs: Expression<Bool?>, rhs: Expression<Bool?>) -> Expression<Bool?> { return "OR".infix(lhs, rhs) } public func ||(lhs: Expression<Bool>, rhs: Bool) -> Expression<Bool> { return "OR".infix(lhs, rhs) } public func ||(lhs: Expression<Bool?>, rhs: Bool) -> Expression<Bool?> { return "OR".infix(lhs, rhs) } public func ||(lhs: Bool, rhs: Expression<Bool>) -> Expression<Bool> { return "OR".infix(lhs, rhs) } public func ||(lhs: Bool, rhs: Expression<Bool?>) -> Expression<Bool?> { return "OR".infix(lhs, rhs) } public prefix func !(rhs: Expression<Bool>) -> Expression<Bool> { return "NOT ".wrap(rhs) } public prefix func !(rhs: Expression<Bool?>) -> Expression<Bool?> { return "NOT ".wrap(rhs) }
mit
fc08953c7ddf9d517f6f26d343ed575e
42.086876
129
0.650922
3.37386
false
false
false
false
abeschneider/stem
Sources/Op/CollectionOp.swift
1
6379
// // CollectionOp.swift // stem // // Created by Abraham Schneider on 12/26/16. // // import Foundation import Tensor open class CollectionOp<S:Storage>: Op<S>, Sequence { open var ops:[Op<S>] open var ordering:AnyOrdering<S> open var count:Int { return ops.count } public init<T:Ordering>( ops:[Op<S>], inputs:[Op<S>], outputs:[Op<S>], ordering:T) where T.StorageType==S { self.ordering = AnyOrdering<S>(ordering) self.ops = ops super.init(inputs: ["input"], outputs: ["output"]) if inputs.count > 0 { connect(from: inputs, "output", to: self, "input") } self.outputs["output"] = outputs.map { $0.output } } // required for Copyable public required init(op:Op<S>, shared:Bool) { let cop = op as! CollectionOp<S> ordering = AnyOrdering<S>(cop.ordering) ops = cop.ops.map { copy(op: $0, shared: shared) } super.init(inputs: ["input"], outputs: ["outputs"]) outputs["output"] = [Tensor<S>(op.output.shape)] } open override func apply() { for op in ordering.traversal(ops) { op.apply() } } open func makeIterator() -> AnyIterator<Op<S>> { return ordering.traversal(ops).makeIterator() } open override func reset() { fill(output, value: 0) } open override var description: String { let className = String(describing: Mirror(reflecting: self).subjectType) var inputDescription:String if let inputOps:[Source<S>] = inputs["input"] { inputDescription = inputOps.map { if let op = $0.op { let output:Tensor<S> = $0.output return String(describing: output.shape.dims) } else { return "[]" } }.joined(separator: ", ") } else { inputDescription = "<empty>" } let value = ops.map { String(describing: $0) }.joined(separator: "\n\t") return "<\(className): inputs:\(inputDescription), outputs:\(output.shape.dims)> {\n\t\(value)\n}" } open override func params() -> [Tensor<S>] { return ops.reduce([]) { $0 + $1.params() } } } open class CollectionGradient<S:Storage>: Op<S>, Gradient { public typealias StorageType = S open var ops:[Op<S>] = [] var ordering:AnyOrdering<S> open var _input:Tensor<S> { return inputs[1].output } open var _gradOutput:Tensor<S> { return inputs[2].output } public required init(op:CollectionOp<S>) { ordering = op.ordering super.init(inputs: ["op", "inputs", "gradOutput"], outputs: ["output"]) outputs["output"] = [Tensor<S>()] // start with outputs, and work backwards createBackwardsGraph(op.ops) // output = ops.last!.output setAction("gradOutput", action: self.gradOutputSet) } public init<T:Ordering>( ops:[Op<S>], inputs:[Op<S>], outputs:[Op<S>], ordering:T) where T.StorageType==S { self.ordering = AnyOrdering<S>(ordering) self.ops = ops super.init(inputs: ["op", "input", "gradOutput"], outputs: ["outputs"]) // connect(from: outputs, "output", to: self, "gradOutput") self.outputs["output"] = outputs.map { $0.output } setAction("gradOutput", action: self.gradOutputSet) } required public init(op: Op<S>, shared: Bool) { fatalError("init(op:shared:) has not been implemented") } func createBackwardsGraph(_ ops:[Op<S>]) { // convert all ops -> opGradient var gradOps:[Int:Op<S>] = [:] for op in ops.reversed() { if let diffOp = op as? Differentiable { let gradOp = (diffOp.gradient() as! Op<S>) gradOps[op.id] = gradOp self.ops.append(gradOp) } } // connect all (op1 -> op2) to (op2Gradient -> op1Gradient) for op in ops { if let opInputs:[Source<S>] = op.inputs["input"] { for input in opInputs { if let fromOp = gradOps[op.id], let toOp = gradOps[input.op!.id] { connect(from: fromOp, to: toOp, "gradOutput") } } } } } func gradOutputSet(_ key:String, value:[Source<S>]) { // connect(from: value, "output", to: ops.first!, "gradOutput") setInput(inputLabel: "gradOutput", to: value) let sourceOps:[Op<S>] = value.map { $0.op! } connect(from: sourceOps, "output", to: ops.first!, "gradOutput") // let target = Target<S>(op: op, label: "gradOutput") // connect(from: value, to) // connect(from: value, to: Target<S>(op: [op], label: "gradOutput")) } open subscript(index:Int) -> Op<S> { return ops[index] } open override func apply() { var lastOp:Op<S>? for op in ordering.traversal(ops) { op.apply() lastOp = op } if let op:Op<S> = lastOp { // TODO: make this a function (part of copy?) // Also: is it necessary to copy, or should we // just point? if output.shape != op.output.shape { output.resize(op.output.shape) } copy(from: op.output, to: output) } } open override func reset() { ops.forEach { $0.reset() } fill(output, value: 0) } open override var description: String { let className = String(describing: Mirror(reflecting: self).subjectType) let value = ops.map { String(describing: $0) }.joined(separator: "\n\t") return "<\(className): inputs=?, outputs=\(output.shape.dims)> {\n\t\(value)\n}" } open override func params() -> [Tensor<S>] { return ops.reversed().reduce([]) { $0 + $1.params() } } } extension CollectionOp:Differentiable { public func gradient() -> GradientType { return CollectionGradient<S>(op: self) } }
mit
0a306697673b5776e68a78772cdcbdcd
29.816425
106
0.524063
3.999373
false
false
false
false
tryswift/TryParsec
excludedTests/TryParsec/Specs/PermutationSpec.swift
1
5359
import TryParsec import Runes import Quick import Nimble class PermutationSpec: QuickSpec { override func spec() { describe("Permutation (n=1)") { let perm: Permutation<USV, USV> = { $0 } <^^> string("abc") let p: Parser<USV, USV> = permute(perm) it("succeeds") { let r = parse(p, "abc123")._done expect(r?.input) == "123" expect(r?.output) == "abc" } it("fails (wrong input)") { let r = parse(p, "123")._fail expect(r?.input) == "123" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } it("fails (no input)") { let r = parse(p, "")._fail expect(r?.input) == "" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } } describe("Permutation (n=2)") { let perm: Permutation<USV, USV> = { a in { b in a + "," + b } } <^^> string("abc") <||> string("123") let p: Parser<USV, USV> = permute(perm) it("succeeds") { let r = parse(p, "abc123")._done expect(r?.input) == "" expect(r?.output) == "abc,123" } it("succeeds (reordered)") { let r = parse(p, "123abc")._done expect(r?.input) == "" expect(r?.output) == "abc,123" } it("fails (no input)") { let r = parse(p, "")._fail expect(r?.input) == "" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } } describe("Permutation (n=2, required + optional)") { let perm: Permutation<USV, USV> = { a in { b in a + "," + b } } <^^> string("abc") // `<^^>` or `<||>` as required <|?> ("_", string("123")) // `<^?>` or `<|?>` as optional let p: Parser<USV, USV> = permute(perm) it("succeeds") { let r = parse(p, "abc123")._done expect(r?.input) == "" expect(r?.output) == "abc,123" } it("succeeds (reordered)") { let r = parse(p, "123abc")._done expect(r?.input) == "" expect(r?.output) == "abc,123" } it("succeeds ('123' is optional)") { let r = parse(p, "abc???")._done expect(r?.input) == "???" expect(r?.output) == "abc,_" } it("fails ('abc' is required)") { let r = parse(p, "123")._fail expect(r?.input) == "123" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } it("fails (no input)") { let r = parse(p, "")._fail expect(r?.input) == "" expect(r?.contexts) == [] expect(r?.message) == "satisfy" } } describe("Permutation (n=3, URL-query example)") { /// Extracts "value" from "\(key)=value&...". func valueParser(_ key: USV) -> Parser<USV, USV> { return string(key + "=") *> many1(noneOf("&#")) <* zeroOrOne(char("&")) } let perm: Permutation<USV, (USV, USV, USV)> = { a in { b in { c in (a, b, c) } } } <^?> ("_", valueParser("key1")) <|?> ("_", valueParser("key2")) <|?> ("_", valueParser("key3")) let p: Parser<USV, (USV, USV, USV)> = permute(perm) it("succeeds") { let r = parse(p, "key1=a&key2=b&key3=c#hello")._done expect(r?.input) == "#hello" expect(r?.output.0) == "a" expect(r?.output.1) == "b" expect(r?.output.2) == "c" } it("succeeds (reordered)") { let keyValues: [String] = ["key1=a", "key2=b", "key3=c"] let patterns = permutations(keyValues) for pattern in patterns { /// e.g. "key2=b&key1=a&key3=c" let query: String = pattern.joined(separator: "&") let r = parse(p, query.unicodeScalars)._done expect(r?.input) == "" expect(r?.output.0) == "a" expect(r?.output.1) == "b" expect(r?.output.2) == "c" } } it("succeeds (keyValues are optional)") { let r = parse(p, "key3=c&key2=b#hello")._done expect(r?.input) == "#hello" expect(r?.output.0) == "_" expect(r?.output.1) == "b" expect(r?.output.2) == "c" } it("succeeds (no input)") { let r = parse(p, "")._done expect(r?.input) == "" expect(r?.output.0) == "_" expect(r?.output.1) == "_" expect(r?.output.2) == "_" } } } }
mit
f426c0bdea6e1f05e0ed7bcd12758ab3
30.339181
87
0.376003
4.078387
false
false
false
false
pavankataria/SwiftDataTables
SwiftDataTables/Classes/Models/DataTableValueType.swift
1
2588
// // DataTableDataType.swift // Pods // // Created by Pavan Kataria on 12/03/2017. // // import Foundation //MARK: - TODO: 11 march - TODO: See if you can make the multidimensional array a generic object so that it can accept any value type. //This will probably make sorting easier and could potenntially allow us to get rid of this class public enum DataTableValueType { //MARK: - Properties case string(String) case int(Int) case float(Float) case double(Double) public var stringRepresentation: String { get { switch self { case .string(let value): return String(value) case .int(let value): return String(value) case .float(let value): return String(value) case .double(let value): return String(value) } } } public init(_ value: Any){ //Determine the actual type first switch value { case let value as Int: self = .int(value) case let value as Float: self = .float(value) case let value as Double: self = .double(value) default: let temporaryStringRepresentation = String(describing: value) if let value = Int(temporaryStringRepresentation) { self = .int(value) } else if let value = Float(temporaryStringRepresentation) { self = .float(value) } else if let value = Double(temporaryStringRepresentation) { self = .double(value) } else { self = .string(temporaryStringRepresentation) } } } } extension DataTableValueType: Comparable { public static func == (lhs: DataTableValueType, rhs: DataTableValueType) -> Bool { return lhs.stringRepresentation == rhs.stringRepresentation } public static func < (lhs: DataTableValueType, rhs: DataTableValueType) -> Bool { switch (lhs, rhs) { case (.string(let lhsValue), .string(let rhsValue)): return lhsValue < rhsValue case (.int(let lhsValue), .int(let rhsValue)): return lhsValue < rhsValue case (.float(let lhsValue), .float(let rhsValue)): return lhsValue < rhsValue case (.double(let lhsValue), .double(let rhsValue)): return lhsValue < rhsValue default: return lhs.stringRepresentation < rhs.stringRepresentation } } }
mit
a074fe22391a805f28d73d277b01ad1e
30.560976
134
0.574575
4.920152
false
false
false
false
silt-lang/silt
Sources/SyntaxGen/Node.swift
1
659
/// Node.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. struct Node { enum Kind { case collection(element: String) case node(kind: String, children: [Child]) } let typeName: String let kind: Kind init(_ typeName: String, element: String) { self.typeName = typeName self.kind = .collection(element: element) } init(_ typeName: String, kind: String, children: [Child]) { self.typeName = typeName self.kind = .node(kind: kind == "Syntax" ? "" : kind, children: children) } }
mit
6d860240add9e5bf03a1b0f326d80873
25.36
70
0.635812
3.899408
false
false
false
false
matthew-healy/TableControlling
TableControlling/Model/TableSection.swift
1
1784
/** A view model which represents a section in a `UITableView`. It has an optional `Header` and `Footer`, and a non-optional array of `Cell`s. The `Header`, `Footer` and `Cell` types are `Equatable` in order for us to equate entire `TableSection`s. */ struct TableSection<Header: Equatable, Cell: Equatable, Footer: Equatable>: Equatable { let header: Header? let cells: [Cell] let footer: Footer? /** Creates a `TableSection` with the given parameters. - parameter header: The view model for the section's header. The default argument is `nil`. - parameter cells: An array of view models for the sections' cells. The default argument is an empty array. - parameter footer: The view model for the section's footer. The default argument is `nil`. */ init(header: Header? = nil, cells: [Cell] = [], footer: Footer? = nil) { self.header = header self.cells = cells self.footer = footer } static func ==<Header: Equatable, Cell: Equatable, Footer: Equatable>( lhs: TableSection<Header, Cell, Footer>, rhs: TableSection<Header, Cell, Footer> ) -> Bool { return lhs.header == rhs.header && lhs.cells == rhs.cells && lhs.footer == rhs.footer } /** The number of items in the `TableSection`. */ var numberOfItems: Int { return cells.count } /** Fetches the item at the given row of the `TableSection`. - parameter row: The `Int` row for the requested cell. - returns: The cell's view model, if it exists, or `nil` otherwise. */ func item(atRow row: Int) -> Cell? { guard let cell = cells[safe: row] else { return nil } return cell } }
mit
3c13c62e5c8529b896def06214233614
32.037037
112
0.61435
4.227488
false
false
false
false
ashfurrow/RxSwift
RxSwift/Schedulers/CurrentThreadScheduler.swift
4
4689
// // CurrentThreadScheduler.swift // Rx // // Created by Krunoslav Zaher on 8/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation let CurrentThreadSchedulerKeyInstance = CurrentThreadSchedulerKey() let CurrentThreadSchedulerQueueKeyInstance = CurrentThreadSchedulerQueueKey() class CurrentThreadSchedulerKey : NSObject, NSCopying { override func isEqual(object: AnyObject?) -> Bool { return object === CurrentThreadSchedulerKeyInstance } override var hashValue: Int { return -904739208 } override func copy() -> AnyObject { return CurrentThreadSchedulerKeyInstance } func copyWithZone(zone: NSZone) -> AnyObject { return CurrentThreadSchedulerKeyInstance } } class CurrentThreadSchedulerQueueKey : NSObject, NSCopying { override func isEqual(object: AnyObject?) -> Bool { return object === CurrentThreadSchedulerQueueKeyInstance } override var hashValue: Int { return -904739207 } override func copy() -> AnyObject { return CurrentThreadSchedulerQueueKeyInstance } func copyWithZone(zone: NSZone) -> AnyObject { return CurrentThreadSchedulerQueueKeyInstance } } /** Represents an object that schedules units of work on the current thread. This is the default scheduler for operators that generate elements. This scheduler is also sometimes called `trampoline scheduler`. */ public class CurrentThreadScheduler : ImmediateSchedulerType { typealias ScheduleQueue = RxMutableBox<Queue<ScheduledItemType>> /** The singleton instance of the current thread scheduler. */ public static let instance = CurrentThreadScheduler() static var queue : ScheduleQueue? { get { return NSThread.currentThread().threadDictionary[CurrentThreadSchedulerQueueKeyInstance] as? ScheduleQueue } set { let threadDictionary = NSThread.currentThread().threadDictionary if let newValue = newValue { threadDictionary[CurrentThreadSchedulerQueueKeyInstance] = newValue } else { threadDictionary.removeObjectForKey(CurrentThreadSchedulerQueueKeyInstance) } } } /** Gets a value that indicates whether the caller must call a `schedule` method. */ public static private(set) var isScheduleRequired: Bool { get { return NSThread.currentThread().threadDictionary[CurrentThreadSchedulerKeyInstance] == nil } set(value) { if value { NSThread.currentThread().threadDictionary.removeObjectForKey(CurrentThreadSchedulerKeyInstance) } else { NSThread.currentThread().threadDictionary[CurrentThreadSchedulerKeyInstance] = CurrentThreadSchedulerKeyInstance } } } /** Schedules an action to be executed as soon as possible on current thread. If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be automatically installed and uninstalled after all work is performed. - parameter state: State passed to the action to be executed. - parameter action: Action to be executed. - returns: The disposable object used to cancel the scheduled action (best effort). */ public func schedule<StateType>(state: StateType, action: (StateType) -> Disposable) -> Disposable { if CurrentThreadScheduler.isScheduleRequired { CurrentThreadScheduler.isScheduleRequired = false let disposable = action(state) defer { CurrentThreadScheduler.isScheduleRequired = true CurrentThreadScheduler.queue = nil } guard let queue = CurrentThreadScheduler.queue else { return disposable } while let latest = queue.value.tryDequeue() { if latest.disposed { continue } latest.invoke() } return disposable } let existingQueue = CurrentThreadScheduler.queue let queue: RxMutableBox<Queue<ScheduledItemType>> if let existingQueue = existingQueue { queue = existingQueue } else { queue = RxMutableBox(Queue<ScheduledItemType>(capacity: 1)) CurrentThreadScheduler.queue = queue } let scheduledItem = ScheduledItem(action: action, state: state) queue.value.enqueue(scheduledItem) return scheduledItem } }
mit
5236d4982c124d859907baf2358f7ccf
31.79021
128
0.658916
6.259012
false
false
false
false
matthew-healy/TableControlling
TableControlling/State/DynamicTable.swift
1
3056
import Foundation /** A state model which represents the possible states for a dynamic `Table`. It can either be `ready` to display a `Table`, `loading` one, `displaying` one, or showing an `Error`. It has proxies for the `Table`s data methods - e.g. `numberOfSections` which it passes on to the underlying `Table`, if it exists, or returns sensible default values for otherwise. */ enum DynamicTable< Header: Equatable, SectionHeader: Equatable, Cell: Equatable, SectionFooter: Equatable, Footer: Equatable >: Equatable, TableModelling { /// The table is `ready` to display data. This is the default state of a newly-created table. case ready /// The table is `loading` data to display. This is the appropriate state for which to show an activity indicator. case loading /// The table is currently `displaying` the associated `Table` view model. case displaying( Table<Header, SectionHeader, Cell, SectionFooter, Footer> ) /// The table has `failed` to load. This is the appropriate state for which to show an error. case failed(Error) static func ==< Header: Equatable, SectionHeader: Equatable, Cell: Equatable, SectionFooter: Equatable, Footer: Equatable >( lhs: DynamicTable<Header, SectionHeader, Cell, SectionFooter, Footer>, rhs: DynamicTable<Header, SectionHeader, Cell, SectionFooter, Footer> ) -> Bool { switch (lhs, rhs) { case (.ready, .ready): return true case (.loading, .loading): return true case (.displaying(let lhsTable), .displaying(let rhsTable)): return lhsTable == rhsTable case (.failed(let lhsError as NSError), .failed(let rhsError as NSError)): return lhsError == rhsError default: return false } } /** The number of sections in the underlying `Table`, or `0` if one is not displayed. */ var numberOfSections: Int { guard case .displaying(let table) = self else { return 0 } return table.numberOfSections } /** The number of `Cell`s in the given section of the underlying `Table`. - parameter section: The `Int` index of the requested section. - returns: The `numberOfItems` for that section of the `Table`, or `0` if one is not displayed. */ func numberOfItems(inSection section: Int) -> Int { guard case .displaying(let table) = self else { return 0 } return table.numberOfItems(inSection: section) } /** Fetches the item at the given index path of the underlying `Table`. - parameter indexPath: The `IndexPath` of the requested `Cell`. - returns: The result of calling `item(at:)` on the underlying `Table`, or `nil` if one is not currently displayed. */ func item(at indexPath: IndexPath) -> Cell? { guard case .displaying(let table) = self else { return nil } return table.item(at: indexPath) } }
mit
725bf701f78b5b8b5dcdcf63ccbd7d97
35.380952
118
0.64267
4.554396
false
false
false
false
PekanMmd/Pokemon-XD-Code
enums/XGTrainerClasses.swift
1
2059
// // XGTrainerClasses.swift // XG Tool // // Created by StarsMmd on 31/05/2015. // Copyright (c) 2015 StarsMmd. All rights reserved. // import Foundation enum XGTrainerClasses : Int, Codable, CaseIterable { case none = 0x00 case michael1 = 0x01 case michael2 = 0x02 // Unconfirmed case michael3 = 0x03 // Unconfirmed case grandMaster = 0x04 case mysteryMan = 0x05 case cipherAdmin = 0x06 case thug = 0x07 case recruit = 0x08 case snagemHead = 0x09 case roboGroudon = 0x0A case wanderer = 0x0B case mythTrainer = 0x0C case preGymLeader = 0x0D case kaminkoAide = 0x0E case rogue = 0x0F case spy = 0x10 case cipherPeon = 0x11 case superTrainer = 0x12 case areaLeader = 0x13 case coolTrainer = 0x14 case funOldMan = 0x15 case curdmudgeon = 0x16 case matron = 0x17 case casualGuy = 0x18 case teamSnagem = 0x19 case chaser = 0x1A case hunter = 0x1B case rider = 0x1C case worker = 0x1D case researcher = 0x1E case navigator = 0x1F case sailor = 0x20 case casualDude = 0x21 case beauty = 0x22 case bodyBuilder = 0x23 case trendyGuy = 0x24 case mtBattleMaster = 0x25 case newsCaster = 0x26 case simTrainer = 0x27 case cipherCMDR = 0x28 case cipherRAndD = 0x29 case cipherAdmin2 = 0x2A case spy2 = 0x2B case cipherPeon2 = 0x2C case superTrainer2 = 0x2D case areaLeader2 = 0x2E case coolTrainer2 = 0x2F case chaser2 = 0x30 case bodyBuilder2 = 0x31 case simTrainer2 = 0x32 var data : XGTrainerClass { get { return XGTrainerClass(index: self.rawValue) } } var nameID : Int { get { return data.nameID } } var name : XGString { get { return data.name } } var payout : Int { get { return data.payout } } } extension XGTrainerClasses: XGEnumerable { var enumerableName: String { return name.unformattedString } var enumerableValue: String? { return rawValue.string } static var className: String { return "Trainer Classes" } static var allValues: [XGTrainerClasses] { return allCases } }
gpl-2.0
78f6dfe3f40b35c7a91d33154fdec75a
16.016529
53
0.690141
2.430933
false
false
false
false
Anduil/TKSwitcherCollection
TKSwitcherCollection/TKSimpleSwitch.swift
1
6395
// // TKSimpleSwitch.swift // SwitcherCollection // // Created by Tbxark on 15/10/25. // Copyright © 2015年 TBXark. All rights reserved. // import UIKit // Dedign by Oleg Frolov //https://dribbble.com/shots/1990516-Switcher //https://dribbble.com/shots/2165675-Switcher-V public struct TKSimpleSwitchConfig { public var onColor : UIColor public var offColor : UIColor public var lineColor : UIColor public var circleColor : UIColor public var lineSize: Double public init(onColor : UIColor = UIColor(red:0.341, green:0.914, blue:0.506, alpha:1), offColor : UIColor = UIColor(white: 0.9, alpha: 1), lineColor : UIColor = UIColor(white: 0.9, alpha: 1), circleColor : UIColor = UIColor.white, lineSize : Double = 8) { self.onColor = onColor self.offColor = offColor self.lineColor = lineColor self.circleColor = circleColor self.lineSize = lineSize } } open class TKSimpleSwitch: TKBaseSwitch { public var startValue: Bool = false fileprivate var swichControl = CAShapeLayer() fileprivate var backgroundLayer = CAShapeLayer() // 是否加旋转特效 open var rotateWhenValueChange = false open var config = TKSimpleSwitchConfig() { didSet { setUpView() } } open var lineWidth : CGFloat { return CGFloat(config.lineSize) * sizeScale } // 初始化 View override open func setUpView(state: Bool = false) { super.setUpView(state: state) startValue = state setValue(state: state) self.backgroundColor = UIColor.clear let frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height) let radius = bounds.height/2 - lineWidth let roundedRectPath = UIBezierPath(roundedRect:frame.insetBy(dx: lineWidth, dy: lineWidth) , cornerRadius:radius) backgroundLayer.fillColor = stateToFillColor(state) backgroundLayer.strokeColor = config.lineColor.cgColor backgroundLayer.lineWidth = lineWidth backgroundLayer.path = roundedRectPath.cgPath layer.addSublayer(backgroundLayer) let innerLineWidth = bounds.height - lineWidth*3 + 1 let swichControlPath = UIBezierPath() if state { swichControlPath.move(to: CGPoint(x: bounds.width - 2 * lineWidth - innerLineWidth + 1 , y: 0)) swichControlPath.addLine(to: CGPoint(x: lineWidth, y: 0)) } else { swichControlPath.move(to: CGPoint(x: lineWidth , y: 0)) swichControlPath.addLine(to: CGPoint(x: bounds.width - 2 * lineWidth - innerLineWidth + 1, y: 0)) } var point = backgroundLayer.position point.y += (radius + lineWidth) point.x += (radius) swichControl.position = point swichControl.path = swichControlPath.cgPath swichControl.lineCap = kCALineCapRound swichControl.fillColor = nil swichControl.strokeColor = config.circleColor.cgColor swichControl.lineWidth = innerLineWidth swichControl.strokeEnd = 0.0001 layer.addSublayer(swichControl) } override public func changeValue(_ animate: Bool) { super.changeValue(animate) animate ? changeValueAnimate(isOn,duration: animateDuration) : changeValueAnimate(isOn, duration: 0) } // MARK: - Animate open func changeValueAnimate(_ turnOn:Bool, duration:Double) { let times = [0,0.49,0.51,1] // 线条运动动画 let swichControlStrokeStartAnim = CAKeyframeAnimation(keyPath:"strokeStart") if startValue { swichControlStrokeStartAnim.values = turnOn ? [1,0,0, 0] : [0,0,0,1] } else { swichControlStrokeStartAnim.values = turnOn ? [0,0,0, 1] : [1,0,0,0] } swichControlStrokeStartAnim.keyTimes = times as [NSNumber]? swichControlStrokeStartAnim.duration = duration swichControlStrokeStartAnim.isRemovedOnCompletion = true let swichControlStrokeEndAnim = CAKeyframeAnimation(keyPath:"strokeEnd") if startValue { swichControlStrokeEndAnim.values = turnOn ? [1,1,1,0] : [0,1,1,1] } else { swichControlStrokeEndAnim.values = turnOn ? [0,1,1,1] : [1,1,1,0] } swichControlStrokeEndAnim.keyTimes = times as [NSNumber]? swichControlStrokeEndAnim.duration = duration swichControlStrokeEndAnim.isRemovedOnCompletion = true // 颜色动画 let backgroundFillColorAnim = CAKeyframeAnimation(keyPath:"fillColor") backgroundFillColorAnim.values = [stateToFillColor(!turnOn), stateToFillColor(!turnOn), stateToFillColor(turnOn), stateToFillColor(turnOn)] backgroundFillColorAnim.keyTimes = [0,0.5,0.51,1] backgroundFillColorAnim.duration = duration backgroundFillColorAnim.fillMode = kCAFillModeForwards backgroundFillColorAnim.isRemovedOnCompletion = false // 旋转动画 if rotateWhenValueChange{ UIView.animate(withDuration: duration, animations: { () -> Void in self.transform = self.transform.rotated(by: CGFloat(M_PI)) }) } // 动画组 let swichControlChangeStateAnim : CAAnimationGroup = CAAnimationGroup() swichControlChangeStateAnim.animations = [swichControlStrokeStartAnim,swichControlStrokeEndAnim] swichControlChangeStateAnim.fillMode = kCAFillModeForwards swichControlChangeStateAnim.isRemovedOnCompletion = false swichControlChangeStateAnim.duration = duration let animateKey = turnOn ? "TurnOn" : "TurnOff" swichControl.add(swichControlChangeStateAnim, forKey: animateKey) backgroundLayer.add(backgroundFillColorAnim, forKey: "Color") } fileprivate func stateToFillColor(_ isOn:Bool) -> CGColor { return isOn ? config.onColor.cgColor : config.offColor.cgColor } }
mit
2c4f2d8280143b5df6491f130422aea1
35.011364
121
0.621647
5.11129
false
false
false
false
tiagobarreto/Swifter
SwifterCommon/SwifterFollowers.swift
3
19069
// // SwifterFollowers.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Swifter { /* GET friendships/no_retweets/ids Returns a collection of user_ids that the currently authenticated user does not want to receive retweets from. Use POST friendships/update to set the "no retweets" status for a given user account on behalf of the current user. */ func getFriendshipsNoRetweetsIDsWithStringifyIDs(stringifyIDs: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/no_retweets/ids.json" var parameters = Dictionary<String, AnyObject>() parameters["stringify_ids"] = stringifyIDs! self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET friends/ids Returns Users (*: user IDs for followees) Returns a cursored collection of user IDs for every user the specified user is following (otherwise known as their "friends"). At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 5,000 user IDs and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. This method is especially powerful when used in conjunction with GET users/lookup, a method that allows you to convert user IDs into full user objects in bulk. */ func getFriendsIDsWithID(id: Int, cursor: Int?, stringifyIDs: Bool?, count: Int?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friends/ids.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if cursor { parameters["cursor"] = cursor! } if stringifyIDs { parameters["stringify_ids"] = stringifyIDs! } if count { parameters["count"] = count! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func getFriendsIDsWithScreenName(screenName: String, cursor: Int?, stringifyIDs: Bool?, count: Int?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friends/ids.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if cursor { parameters["cursor"] = cursor! } if stringifyIDs { parameters["stringify_ids"] = stringifyIDs! } if count { parameters["count"] = count! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET followers/ids Returns a cursored collection of user IDs for every user following the specified user. At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 5,000 user IDs and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. This method is especially powerful when used in conjunction with GET users/lookup, a method that allows you to convert user IDs into full user objects in bulk. */ func getFollowersIDsWithID(id: Int, cursor: Int?, stringifyIDs: Bool?, count: Int?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "followers/ids.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if cursor { parameters["cursor"] = cursor! } if stringifyIDs { parameters["stringify_ids"] = stringifyIDs! } if count { parameters["count"] = count! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func getFollowersIDsWithScreenName(screenName: String, cursor: Int?, stringifyIDs: Bool?, count: Int?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "followers/ids.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if cursor { parameters["cursor"] = cursor! } if stringifyIDs { parameters["stringify_ids"] = stringifyIDs! } if count { parameters["count"] = count! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET friendships/incoming Returns a collection of numeric IDs for every user who has a pending request to follow the authenticating user. */ func getFriendshipsIncomingWithCursor(cursor: String?, stringifyIDs: String?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/incoming.json" var parameters = Dictionary<String, AnyObject>() if cursor { parameters["cursor"] = cursor! } if stringifyIDs { parameters["stringify_urls"] = stringifyIDs! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET friendships/outgoing Returns a collection of numeric IDs for every protected user for whom the authenticating user has a pending follow request. */ func getFriendshipsOutgoingWithCursor(cursor: String?, stringifyIDs: String?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/outgoing.json" var parameters = Dictionary<String, AnyObject>() if cursor { parameters["cursor"] = cursor! } if stringifyIDs { parameters["stringify_urls"] = stringifyIDs! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* POST friendships/create Allows the authenticating users to follow the user specified in the ID parameter. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. If you are already friends with the user a HTTP 403 may be returned, though for performance reasons you may get a 200 OK message even if the friendship already exists. Actions taken in this method are asynchronous and changes will be eventually consistent. */ func postCreateFriendshipWithID(id: Int, follow: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/create.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if follow { parameters["follow"] = follow! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func postCreateFriendshipWithScreenName(screenName: String, follow: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/create.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if follow { parameters["follow"] = follow! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* POST friendships/destroy Allows the authenticating user to unfollow the user specified in the ID parameter. Returns the unfollowed user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. Actions taken in this method are asynchronous and changes will be eventually consistent. */ func postDestroyFriendshipWithID(id: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/destroy.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func postDestroyFriendshipWithScreenName(screenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/destroy.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* POST friendships/update Allows one to enable or disable retweets and device notifications from the specified user. */ func postUpdateFriendshipWithID(id: Int, device: Bool?, retweets: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/update.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if device { parameters["device"] = device! } if retweets { parameters["retweets"] = retweets! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func postUpdateFriendshipWithScreenName(screenName: String, device: Bool?, retweets: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/update.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if device { parameters["device"] = device! } if retweets { parameters["retweets"] = retweets! } self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET friendships/show Returns detailed information about the relationship between two arbitrary users. */ func getFriendshipsShowWithSourceID(sourceID: Int?, orSourceScreenName sourceScreenName: String?, targetID: Int?, orTargetScreenName targetScreenName: String?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { assert(sourceID || sourceScreenName, "Either a source screenName or a userID must be provided.") assert(targetID || targetScreenName, "Either a target screenName or a userID must be provided.") let path = "friendships/show.json" var parameters = Dictionary<String, AnyObject>() if sourceID { parameters["source_id"] = sourceID! } else if sourceScreenName { parameters["source_screen_name"] = sourceScreenName! } if targetID { parameters["target_id"] = targetID! } else if targetScreenName { parameters["targetScreenName"] = targetScreenName! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET friends/list Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends"). At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. */ func getFriendsListWithID(id: Int, cursor: Int?, count: Int?, skipStatus: Bool?, includeUserEntities: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/list.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if cursor { parameters["cursor"] = cursor! } if count { parameters["count"] = count! } if skipStatus { parameters["skip_status"] = skipStatus! } if includeUserEntities { parameters["include_user_entities"] = includeUserEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func getFriendsListWithScreenName(screenName: String, cursor: Int?, count: Int?, skipStatus: Bool?, includeUserEntities: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "friendships/list.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if cursor { parameters["cursor"] = cursor! } if count { parameters["count"] = count! } if skipStatus { parameters["skip_status"] = skipStatus! } if includeUserEntities { parameters["include_user_entities"] = includeUserEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET followers/list Returns a cursored collection of user objects for users following the specified user. At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information. */ func getFollowersListWithID(id: Int, cursor: Int?, count: Int?, skipStatus: Bool?, includeUserEntities: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "followers/list.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id if cursor { parameters["cursor"] = cursor! } if count { parameters["count"] = count! } if skipStatus { parameters["skip_status"] = skipStatus! } if includeUserEntities { parameters["include_user_entities"] = includeUserEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func getFollowersListWithScreenName(screenName: String, cursor: Int?, count: Int?, skipStatus: Bool?, includeUserEntities: Bool?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "followers/list.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName if cursor { parameters["cursor"] = cursor! } if count { parameters["count"] = count! } if skipStatus { parameters["skip_status"] = skipStatus! } if includeUserEntities { parameters["include_user_entities"] = includeUserEntities! } self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } /* GET friendships/lookup Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided. Values for connections can be: following, following_requested, followed_by, none. */ func getFriendshipsLookupWithScreenName(screenName: String, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "followers/lookup.json" var parameters = Dictionary<String, AnyObject>() parameters["screen_name"] = screenName self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } func getFriendshipsLookupWithID(id: Int, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let path = "followers/lookup.json" var parameters = Dictionary<String, AnyObject>() parameters["id"] = id self.getJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: success, failure: failure) } }
mit
cfda4bafa76f2f917beff7d7d66bfdd1
43.431235
388
0.683542
5.146058
false
false
false
false
zhenghuadong11/firstGitHub
旅游app_useSwift/旅游app_useSwift/MYMyticketCell.swift
1
5823
// // MYMyticketCell.swift // 旅游app_useSwift // // Created by zhenghuadong on 16/4/23. // Copyright © 2016年 zhenghuadong. All rights reserved. // import Foundation import UIKit class MYMyticketCell:UITableViewCell { weak var _tableViewImageView: UIImageView? weak var _nameLabel: UILabel? weak var _one_wordLabel: UILabel? weak var _needMoneyLabel: UILabel? weak var numPassLabel:UILabel? var _isHaveEvaluationLabel:UILabel = UILabel() var _myTicketModel:MYMyTicketModel{ set{ self._collectModelTmp = newValue self.setUpSubViewWithDiffrentWithAgoModel(newValue) } get { return _collectModelTmp! } } var _collectModelTmp:MYMyTicketModel? func setUpSubViewWithDiffrentWithAgoModel(diffrentWithAgoModel:MYMyTicketModel) -> Void { _tableViewImageView?.image = UIImage(named: (diffrentWithAgoModel.picture!)) _nameLabel?.text = diffrentWithAgoModel.name _one_wordLabel?.text = diffrentWithAgoModel.one_word _needMoneyLabel?.text = diffrentWithAgoModel.date?.description self.numPassLabel?.text = "领票码:"+diffrentWithAgoModel.pass! self.numPassLabel?.textColor = UIColor.orangeColor() } static func firstPageCellWithTableView(tableView:UITableView) -> MYMyticketCell { let cellID="MYMyticketCell" var cell:MYMyticketCell? = tableView.dequeueReusableCellWithIdentifier(cellID) as? MYMyticketCell if cell == nil { cell = MYMyticketCell(style: UITableViewCellStyle.Default , reuseIdentifier: cellID) } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let deleteLabel = UILabel() deleteLabel.backgroundColor = UIColor.redColor() deleteLabel.text = "退票" self.contentView.addSubview(deleteLabel) deleteLabel.snp_makeConstraints { (make) in make.left.equalTo(self.snp_right) make.top.equalTo(self.contentView) make.bottom.equalTo(self.contentView).offset(1) make.width.equalTo(self.contentView) } let tableViewImageView = UIImageView() self.selectionStyle = UITableViewCellSelectionStyle.None self.addSubview(tableViewImageView) _tableViewImageView = tableViewImageView let nameLabel = UILabel() self.addSubview(nameLabel) _nameLabel = nameLabel let one_wordLabel = UILabel() self.addSubview(one_wordLabel) _one_wordLabel = one_wordLabel let needMoneyLabel = UILabel() self.addSubview(needMoneyLabel) _needMoneyLabel = needMoneyLabel let numPass = UILabel() self.numPassLabel = numPass self.addSubview(numPass) self.addSubview(_isHaveEvaluationLabel) _isHaveEvaluationLabel.textColor = UIColor.grayColor() } override func layoutSubviews() { _tableViewImageView?.frame = CGRectMake(10, 10, self.frame.width * 0.25, self.frame.height - 20) _nameLabel?.snp_makeConstraints(closure: { (make) in make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.top.equalTo(self.snp_top).offset(10) make.right.equalTo(self.snp_right).offset(-10) make.height.equalTo(self.snp_height).multipliedBy(0.25) }) _one_wordLabel?.snp_makeConstraints(closure: { (make) in make.top.equalTo(_nameLabel!.snp_bottom).offset(10) make.right.equalTo(self.snp_right).offset(-10) make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.height.equalTo(self.snp_height).multipliedBy(0.25) }) _needMoneyLabel?.snp_makeConstraints(closure: { (make) in make.top.equalTo(_one_wordLabel!.snp_bottom).offset(10) make.right.equalTo(self.snp_right).offset(-10) make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.height.equalTo(self.snp_height).multipliedBy(0.25) }) _isHaveEvaluationLabel.snp_makeConstraints { (make) in make.top.equalTo(self).offset(10) make.right.equalTo(self).offset(-10) make.height.equalTo(30) make.width.equalTo(100) } self.numPassLabel?.snp_makeConstraints(closure: { (make) in make.top.equalTo(self).offset(10) make.right.equalTo(self).offset(-10) make.height.equalTo(30) make.width.equalTo(150) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
f7ac38d8b0ca78aee8cfe379023f97fb
33.152941
109
0.534792
5.395911
false
false
false
false
afarber/ios-newbie
FetchJsonEscapable/FetchJsonEscapable/ViewModels/DownloadingImageViewModel.swift
1
1523
// // TopImageViewModel.swift // FetchJsonEscapable // // Created by Alexander Farber on 13.05.21. // import Foundation import SwiftUI import Combine class DownloadingImageViewModel: ObservableObject { @Published var image: UIImage? = nil @Published var isLoading: Bool = false var cancellables = Set<AnyCancellable>() let manager = CacheManager.instance let urlString: String init(url: String) { urlString = url getImage() } func getImage() { if let savedImage = manager.get(name: urlString) { image = savedImage print("Getting saved image!") } else { downloadImage() print("Downloading image now!") } } func downloadImage() { isLoading = true guard let url = URL(string: urlString) else { isLoading = false return } URLSession.shared.dataTaskPublisher(for: url) .map { UIImage(data: $0.data) } .receive(on: DispatchQueue.main) .sink { [weak self] (_) in self?.isLoading = false } receiveValue: { [weak self] (returnedImage) in guard let self = self, let image = returnedImage else { return } self.image = image self.manager.add(image: image, name: self.urlString) } .store(in: &cancellables) } }
unlicense
20675009b372c28729707c4d7946949c
24.813559
68
0.533815
4.897106
false
false
false
false
sundeepgupta/dependency-injection-example
4-Injection.playground/contents.swift
1
1488
protocol Remixer { func result(list: Array<String>) -> Array<String> } class Repeater : Remixer { func result(list: Array<String>) -> Array<String> { return list.map { item -> String in return item + " " + item } } } class Reverser : Remixer { func result(list: Array<String>) -> Array<String> { return list.reverse() } } class Song { private let lineStart = "This is " private let lineEnd = "." private var phrases = [ "the house that Jack built", "the malt that lay in", "the rat that ate" ] init(remixer: Remixer?) { if remixer != nil { self.phrases = remixer!.result(self.phrases) } } func line(number: Int) -> String { let linePhrases = self.phrases[0...number-1].reverse() let line = " ".join(linePhrases) return self.lineStart + line + self.lineEnd } func recite() -> String { var lines = [String]() for i in 1...self.phrases.count { lines.append(self.line(i)) } return "\n".join(lines) } } let song = Song(remixer: nil) song.line(1) song.line(2) song.line(3) song.recite() let repeatingSong = Song(remixer: Repeater()) repeatingSong.line(1) repeatingSong.line(2) repeatingSong.line(3) repeatingSong.recite() let reversingSong = Song(remixer: Reverser()) reversingSong.line(1) reversingSong.line(2) reversingSong.line(3) reversingSong.recite()
unlicense
de7d0e3ece6910883662f6c2b7ae7939
21.892308
62
0.594086
3.526066
false
false
false
false
Appsaurus/Infinity
Infinity/UIScrollView+Infinity.swift
1
9923
// // UIScrollView+Infinity.swift // InfinitySample // // Created by Danis on 15/12/21. // Copyright © 2015年 danis. All rights reserved. // import UIKit private var associatedPullToRefresherKey: String = "InfinityPullToRefresherKey" private var associatedInfiniteScrollerKey: String = "InfinityInfiniteScrollerKey" private var associatedisPullToRefreshEnabledKey: String = "InfinityisPullToRefreshEnabledKey" private var associatedisInfiniteScrollEnabledKey: String = "InfinityisInfiniteScrollEnabledKey" private var associatedInfinityKey = "Infinity.Associated.Infinity" // MARK: - PullToRefresh extension UIScrollView { public var fty: Infinity { get { if let value = objc_getAssociatedObject(self, &associatedInfinityKey) as? Infinity { return value } else { let newValue = Infinity(scrollView: self) objc_setAssociatedObject(self, &associatedInfinityKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return newValue } } } } public enum InfinityScrollDirection{ case vertical, horizontal } public class Infinity { public let pullToRefresh: PullToRefreshWrapper public let infiniteScroll: InfiniteScrollWrapper let scrollView: UIScrollView init(scrollView: UIScrollView) { self.scrollView = scrollView pullToRefresh = PullToRefreshWrapper(scrollView: scrollView) infiniteScroll = InfiniteScrollWrapper(scrollView: scrollView) } public class PullToRefreshWrapper { let scrollView: UIScrollView init(scrollView: UIScrollView) { self.scrollView = scrollView } public func add(height: CGFloat = 60, direction: InfinityScrollDirection, animator: CustomPullToRefreshAnimator, action: (() -> Void)?) { scrollView.addPullToRefresh(height, direction: direction, animator: animator, action: action) } public func bind(height: CGFloat = 60, direction: InfinityScrollDirection, animator: CustomPullToRefreshAnimator, action: (() -> Void)?) { scrollView.bindPullToRefresh(height, direction: direction, toAnimator: animator, action: action) } public func remove() { scrollView.removePullToRefresh() } public func begin() { scrollView.beginRefreshing() } public func end() { scrollView.endRefreshing() } public var isEnabled: Bool { get { return scrollView.isPullToRefreshEnabled } set { scrollView.isPullToRefreshEnabled = newValue } } public var isScrollingToTopImmediately: Bool { get { return scrollView.isScrollingToTopImmediately } set { scrollView.isScrollingToTopImmediately = newValue } } public var animatorOffset: UIOffset { get { if let offset = scrollView.pullToRefresher?.animatorOffset { return offset } return UIOffset() } set { scrollView.pullToRefresher?.animatorOffset = newValue } } } public class InfiniteScrollWrapper { let scrollView: UIScrollView init(scrollView: UIScrollView) { self.scrollView = scrollView } public func add(height: CGFloat = 60, direction: InfinityScrollDirection, animator: CustomInfiniteScrollAnimator, action: (() -> Void)?) { scrollView.addInfiniteScroll(height, direction: direction, animator: animator, action: action) } public func bind(height: CGFloat = 60, direction: InfinityScrollDirection, animator: CustomInfiniteScrollAnimator, action: (() -> Void)?) { scrollView.bindInfiniteScroll(height, direction: direction, toAnimator: animator, action: action) } public func remove() { scrollView.removeInfiniteScroll() } public func begin() { scrollView.beginInfiniteScrolling() } public func end() { scrollView.endInfiniteScrolling() } public var isEnabled: Bool { get { return scrollView.isInfiniteScrollEnabled } set { scrollView.isInfiniteScrollEnabled = newValue } } public var isStickToContent: Bool { get { return scrollView.isInfiniteStickToContent } set { scrollView.isInfiniteStickToContent = newValue } } } public func clear() { pullToRefresh.remove() infiniteScroll.remove() } } extension UIScrollView { func addPullToRefresh(_ height: CGFloat = 60.0, direction: InfinityScrollDirection, animator: CustomPullToRefreshAnimator, action:(()->Void)?) { bindPullToRefresh(height, direction: direction, toAnimator: animator, action: action) self.pullToRefresher?.scrollbackImmediately = false if let animatorView = animator as? UIView { self.pullToRefresher?.containerView.addSubview(animatorView) } } func bindPullToRefresh(_ height: CGFloat = 60.0, direction: InfinityScrollDirection, toAnimator: CustomPullToRefreshAnimator, action:(()->Void)?) { removePullToRefresh() self.pullToRefresher = PullToRefresher(height: height, direction: direction, animator: toAnimator) self.pullToRefresher?.scrollView = self self.pullToRefresher?.action = action } func removePullToRefresh() { self.pullToRefresher?.scrollView = nil self.pullToRefresher = nil } func beginRefreshing() { self.pullToRefresher?.beginRefreshing() } func endRefreshing() { self.pullToRefresher?.endRefreshing() } //MARK: - Properties var pullToRefresher: PullToRefresher? { get { return objc_getAssociatedObject(self, &associatedPullToRefresherKey) as? PullToRefresher } set { objc_setAssociatedObject(self, &associatedPullToRefresherKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var isPullToRefreshEnabled: Bool { get { return pullToRefresher?.enable ?? false } set { pullToRefresher?.enable = newValue } } var isScrollingToTopImmediately: Bool { get { return pullToRefresher?.scrollbackImmediately ?? false } set { pullToRefresher?.scrollbackImmediately = newValue } } } // MARK: - InfiniteScroll extension UIScrollView { func addInfiniteScroll(_ height: CGFloat = 80.0, direction: InfinityScrollDirection, animator: CustomInfiniteScrollAnimator, action: (() -> Void)?) { bindInfiniteScroll(height, direction: direction,toAnimator: animator, action: action) if let animatorView = animator as? UIView { self.infiniteScroller?.containerView.addSubview(animatorView) } } func bindInfiniteScroll(_ height: CGFloat = 80.0, direction: InfinityScrollDirection, toAnimator: CustomInfiniteScrollAnimator, action: (() -> Void)?) { removeInfiniteScroll() self.infiniteScroller = InfiniteScroller(height: height, direction: direction, animator: toAnimator) self.infiniteScroller?.scrollView = self self.infiniteScroller?.action = action } func removeInfiniteScroll() { self.infiniteScroller?.scrollView = nil self.infiniteScroller = nil } func beginInfiniteScrolling() { self.infiniteScroller?.beginInfiniteScrolling() } func endInfiniteScrolling() { self.infiniteScroller?.endInfiniteScrolling() } //MARK: - Properties var infiniteScroller: InfiniteScroller? { get { return objc_getAssociatedObject(self, &associatedInfiniteScrollerKey) as? InfiniteScroller } set { objc_setAssociatedObject(self, &associatedInfiniteScrollerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // 当并未添加infinityScroll时返回的为nil,表示并不支持这种配置 var isInfiniteStickToContent: Bool { get { return self.infiniteScroller?.stickToContent ?? false } set { self.infiniteScroller?.stickToContent = newValue } } var isInfiniteScrollEnabled: Bool { get { return infiniteScroller?.enable ?? false } set { infiniteScroller?.enable = newValue } } } private var associatedSupportSpringBouncesKey:String = "InfinitySupportSpringBouncesKey" private var associatedLockInsetKey: String = "InfinityLockInsetKey" extension UIScrollView { var lockInset: Bool { get { let locked = objc_getAssociatedObject(self, &associatedLockInsetKey) as? Bool if locked == nil { return false } return locked! } set { objc_setAssociatedObject(self, &associatedLockInsetKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func setContentInset(_ inset: UIEdgeInsets, completion: ((Bool) -> Void)?) { UIView.animate(withDuration: 0.3, delay: 0, options: [.allowUserInteraction, .beginFromCurrentState], animations: { () -> Void in self.lockInset = true self.contentInset = inset self.lockInset = false }, completion: { (finished) -> Void in completion?(finished) }) } }
mit
bcc56a9e1af93bcea78f4648ded5d534
33.538462
156
0.623203
5.580791
false
false
false
false
PureSwift/BinaryJSON
Sources/BinaryJSON/BSON.swift
1
10749
// // BSON.swift // BSON // // Created by Alsey Coleman Miller on 12/13/15. // Copyright © 2015 PureSwift. All rights reserved. // import SwiftFoundation /// [Binary JSON](http://bsonspec.org) public struct BSON { /// BSON Array public typealias Array = [BSON.Value] /// BSON Document public typealias Document = [String: BSON.Value] /// BSON value type. public enum Value: RawRepresentable, Equatable, CustomStringConvertible { case Null case Array(BSON.Array) case Document(BSON.Document) case Number(BSON.Number) case String(StringValue) case Date(DateValue) case Timestamp(BSON.Timestamp) case Binary(BSON.Binary) case Code(BSON.Code) case ObjectID(BSON.ObjectID) case RegularExpression(BSON.RegularExpression) case Key(BSON.Key) // MARK: - Extract Values /// Tries to extract an array value from a ```BSON.Value```. /// /// - Note: Does not convert the individual elements of the array to their raw values. public var arrayValue: BSON.Array? { switch self { case let .Array(value): return value default: return nil } } /// Tries to extract a document value from a ```BSON.Value```. /// /// - Note: Does not convert the values of the document to their raw values. public var documentValue: BSON.Document? { switch self { case let .Document(value): return value default: return nil } } } public enum Number: Equatable { case Boolean(Bool) case Integer32(Int32) case Integer64(Int64) case Double(DoubleValue) } public struct Binary: Equatable { public enum Subtype: Byte { case Generic = 0x00 case Function = 0x01 case Old = 0x02 case UUIDOld = 0x03 case UUID = 0x04 case MD5 = 0x05 case User = 0x80 } public var data: Data public var subtype: Subtype public init(data: Data, subtype: Subtype = .Generic) { self.data = data self.subtype = subtype } } /// Represents a string of Javascript code. public struct Code: Equatable { public var code: String public var scope: BSON.Document? public init(_ code: String, scope: BSON.Document? = nil) { self.code = code self.scope = scope } } /// BSON maximum and minimum representable types. public enum Key { case Minimum case Maximum } public struct Timestamp: Equatable { /// Seconds since the Unix epoch. public var time: UInt32 /// Prdinal for operations within a given second. public var oridinal: UInt32 public init(time: UInt32, oridinal: UInt32) { self.time = time self.oridinal = oridinal } } public struct RegularExpression: Equatable { public var pattern: String public var options: String public init(_ pattern: String, options: String) { self.pattern = pattern self.options = options } } } // MARK: - RawRepresentable public extension BSON.Value { var rawValue: Any { switch self { case .Null: return SwiftFoundation.Null() case let .Array(array): let rawValues = array.map { (value) in return value.rawValue } return rawValues case let .Document(document): var rawObject = [StringValue: Any]() for (key, value) in document { rawObject[key] = value.rawValue } return rawObject case let .Number(number): return number.rawValue case let .Date(date): return date case let .Timestamp(timestamp): return timestamp case let .Binary(binary): return binary case let .String(string): return string case let .Key(key): return key case let .Code(code): return code case let .ObjectID(objectID): return objectID case let .RegularExpression(regularExpression): return regularExpression } } init?(rawValue: Any) { guard (rawValue as? SwiftFoundation.Null) == nil else { self = .Null return } if let key = rawValue as? BSON.Key { self = .Key(key) return } if let string = rawValue as? Swift.String { self = .String(string) return } if let date = rawValue as? SwiftFoundation.Date { self = .Date(date) return } if let timestamp = rawValue as? BSON.Timestamp { self = .Timestamp(timestamp) return } if let binary = rawValue as? BSON.Binary { self = .Binary(binary) return } if let number = BSON.Number(rawValue: rawValue) { self = .Number(number) return } if let rawArray = rawValue as? [Any], let jsonArray: [BSON.Value] = BSON.Value.fromRawValues(rawArray) { self = .Array(jsonArray) return } if let rawDictionary = rawValue as? [Swift.String: Any] { var document = BSON.Document() for (key, rawValue) in rawDictionary { guard let bsonValue = BSON.Value(rawValue: rawValue) else { return nil } document[key] = bsonValue } self = .Document(document) return } if let code = rawValue as? BSON.Code { self = .Code(code) return } if let objectID = rawValue as? BSON.ObjectID { self = .ObjectID(objectID) return } if let regularExpression = rawValue as? BSON.RegularExpression { self = .RegularExpression(regularExpression) return } return nil } } public extension BSON.Number { public var rawValue: Any { switch self { case .Boolean(let value): return value case .Integer32(let value): return value case .Integer64(let value): return value case .Double(let value): return value } } public init?(rawValue: Any) { if let value = rawValue as? Bool { self = .Boolean(value) } if let value = rawValue as? Int32 { self = .Integer32(value) } if let value = rawValue as? Int64 { self = .Integer64(value) } if let value = rawValue as? DoubleValue { self = .Double(value) } return nil } } // MARK: - CustomStringConvertible public extension BSON.Value { public var description: Swift.String { return "\(rawValue)" } } public extension BSON.Number { public var description: Swift.String { return "\(rawValue)" } } // MARK: Equatable public func ==(lhs: BSON.Value, rhs: BSON.Value) -> Bool { switch (lhs, rhs) { case (.Null, .Null): return true case let (.String(leftValue), .String(rightValue)): return leftValue == rightValue case let (.Number(leftValue), .Number(rightValue)): return leftValue == rightValue case let (.Array(leftValue), .Array(rightValue)): return leftValue == rightValue case let (.Document(leftValue), .Document(rightValue)): return leftValue == rightValue case let (.Date(leftValue), .Date(rightValue)): return leftValue == rightValue case let (.Timestamp(leftValue), .Timestamp(rightValue)): return leftValue == rightValue case let (.Binary(leftValue), .Binary(rightValue)): return leftValue == rightValue case let (.Code(leftValue), .Code(rightValue)): return leftValue == rightValue case let (.ObjectID(leftValue), .ObjectID(rightValue)): return leftValue == rightValue case let (.RegularExpression(leftValue), .RegularExpression(rightValue)): return leftValue == rightValue case let (.Key(leftValue), .Key(rightValue)): return leftValue == rightValue default: return false } } public func ==(lhs: BSON.Number, rhs: BSON.Number) -> Bool { switch (lhs, rhs) { case let (.Boolean(leftValue), .Boolean(rightValue)): return leftValue == rightValue case let (.Integer32(leftValue), .Integer32(rightValue)): return leftValue == rightValue case let (.Integer64(leftValue), .Integer64(rightValue)): return leftValue == rightValue case let (.Double(leftValue), .Double(rightValue)): return leftValue == rightValue default: return false } } public func ==(lhs: BSON.Timestamp, rhs: BSON.Timestamp) -> Bool { return lhs.time == rhs.time && lhs.oridinal == rhs.oridinal } public func ==(lhs: BSON.Binary, rhs: BSON.Binary) -> Bool { return lhs.data == rhs.data && lhs.subtype == rhs.subtype } public func ==(lhs: BSON.Code, rhs: BSON.Code) -> Bool { if let leftScope = lhs.scope { guard let rightScope = rhs.scope where rightScope == leftScope else { return false } } return lhs.code == rhs.code } public func ==(lhs: BSON.RegularExpression, rhs: BSON.RegularExpression) -> Bool { return lhs.pattern == rhs.pattern && lhs.options == rhs.options } // MARK: - Typealiases // Due to compiler error public typealias DataValue = Data public typealias DateValue = Date
mit
b50229a24a879a3bb916a362e0c63548
25.278729
112
0.52233
5.177264
false
false
false
false
GraphKit/MaterialKit
Sources/iOS/Icon.swift
2
7042
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public struct Icon { /// An internal reference to the icons bundle. private static var internalBundle: Bundle? /** A public reference to the icons bundle, that aims to detect the correct bundle to use. */ public static var bundle: Bundle { if nil == Icon.internalBundle { Icon.internalBundle = Bundle(for: View.self) let url = Icon.internalBundle!.resourceURL! let b = Bundle(url: url.appendingPathComponent("io.cosmicmind.material.icons.bundle")) if let v = b { Icon.internalBundle = v } } return Icon.internalBundle! } /// Get the icon by the file name. public static func icon(_ name: String) -> UIImage? { return UIImage(named: name, in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) } /// Google icons. public static let add = Icon.icon("ic_add_white") public static let addCircle = Icon.icon("ic_add_circle_white") public static let addCircleOutline = Icon.icon("ic_add_circle_outline_white") public static let arrowBack = Icon.icon("ic_arrow_back_white") public static let arrowDownward = Icon.icon("ic_arrow_downward_white") public static let audio = Icon.icon("ic_audiotrack_white") public static let bell = Icon.icon("cm_bell_white") public static let cameraFront = Icon.icon("ic_camera_front_white") public static let cameraRear = Icon.icon("ic_camera_rear_white") public static let check = Icon.icon("ic_check_white") public static let clear = Icon.icon("ic_close_white") public static let close = Icon.icon("ic_close_white") public static let edit = Icon.icon("ic_edit_white") public static let email = Icon.icon("ic_email_white") public static let favorite = Icon.icon("ic_favorite_white") public static let favoriteBorder = Icon.icon("ic_favorite_border_white") public static let flashAuto = Icon.icon("ic_flash_auto_white") public static let flashOff = Icon.icon("ic_flash_off_white") public static let flashOn = Icon.icon("ic_flash_on_white") public static let history = Icon.icon("ic_history_white") public static let home = Icon.icon("ic_home_white") public static let image = Icon.icon("ic_image_white") public static let menu = Icon.icon("ic_menu_white") public static let moreHorizontal = Icon.icon("ic_more_horiz_white") public static let moreVertical = Icon.icon("ic_more_vert_white") public static let movie = Icon.icon("ic_movie_white") public static let pen = Icon.icon("ic_edit_white") public static let place = Icon.icon("ic_place_white") public static let phone = Icon.icon("ic_phone_white") public static let photoCamera = Icon.icon("ic_photo_camera_white") public static let photoLibrary = Icon.icon("ic_photo_library_white") public static let search = Icon.icon("ic_search_white") public static let settings = Icon.icon("ic_settings_white") public static let share = Icon.icon("ic_share_white") public static let star = Icon.icon("ic_star_white") public static let starBorder = Icon.icon("ic_star_border_white") public static let starHalf = Icon.icon("ic_star_half_white") public static let videocam = Icon.icon("ic_videocam_white") public static let visibility = Icon.icon("ic_visibility_white") public static let work = Icon.icon("ic_work_white") /// CosmicMind icons. public struct cm { public static let add = Icon.icon("cm_add_white") public static let arrowBack = Icon.icon("cm_arrow_back_white") public static let arrowDownward = Icon.icon("cm_arrow_downward_white") public static let audio = Icon.icon("cm_audio_white") public static let audioLibrary = Icon.icon("cm_audio_library_white") public static let bell = Icon.icon("cm_bell_white") public static let check = Icon.icon("cm_check_white") public static let clear = Icon.icon("cm_close_white") public static let close = Icon.icon("cm_close_white") public static let edit = Icon.icon("cm_pen_white") public static let image = Icon.icon("cm_image_white") public static let menu = Icon.icon("cm_menu_white") public static let microphone = Icon.icon("cm_microphone_white") public static let moreHorizontal = Icon.icon("cm_more_horiz_white") public static let moreVertical = Icon.icon("cm_more_vert_white") public static let movie = Icon.icon("cm_movie_white") public static let pause = Icon.icon("cm_pause_white") public static let pen = Icon.icon("cm_pen_white") public static let photoCamera = Icon.icon("cm_photo_camera_white") public static let photoLibrary = Icon.icon("cm_photo_library_white") public static let play = Icon.icon("cm_play_white") public static let search = Icon.icon("cm_search_white") public static let settings = Icon.icon("cm_settings_white") public static let share = Icon.icon("cm_share_white") public static let shuffle = Icon.icon("cm_shuffle_white") public static let skipBackward = Icon.icon("cm_skip_backward_white") public static let skipForward = Icon.icon("cm_skip_forward_white") public static let star = Icon.icon("cm_star_white") public static let videocam = Icon.icon("cm_videocam_white") public static let volumeHigh = Icon.icon("cm_volume_high_white") public static let volumeMedium = Icon.icon("cm_volume_medium_white") public static let volumeOff = Icon.icon("cm_volume_off_white") } }
agpl-3.0
ab2e8688d78cc89d9760060797d569ed
51.162963
104
0.717552
3.825095
false
false
false
false
not4mj/think
Pods/SwiftyUserDefaults/Sources/SwiftyUserDefaults.swift
1
15567
// // SwiftyUserDefaults // // Copyright (c) 2015-2016 Radosław Pietruszewski // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public extension UserDefaults { class Proxy { fileprivate let defaults: UserDefaults fileprivate let key: String fileprivate init(_ defaults: UserDefaults, _ key: String) { self.defaults = defaults self.key = key } // MARK: Getters open var object: Any? { return defaults.object(forKey: key) } open var string: String? { return defaults.string(forKey: key) } open var array: [Any]? { return defaults.array(forKey: key) } open var dictionary: [String: Any]? { return defaults.dictionary(forKey: key) } open var data: Data? { return defaults.data(forKey: key) } open var date: Date? { return object as? Date } open var number: NSNumber? { return defaults.numberForKey(key) } open var int: Int? { return number?.intValue } open var double: Double? { return number?.doubleValue } open var bool: Bool? { return number?.boolValue } // MARK: Non-Optional Getters open var stringValue: String { return string ?? "" } open var arrayValue: [Any] { return array ?? [] } open var dictionaryValue: [String: Any] { return dictionary ?? [:] } open var dataValue: Data { return data ?? Data() } open var numberValue: NSNumber { return number ?? 0 } open var intValue: Int { return int ?? 0 } open var doubleValue: Double { return double ?? 0 } open var boolValue: Bool { return bool ?? false } } /// `NSNumber` representation of a user default func numberForKey(_ key: String) -> NSNumber? { return object(forKey: key) as? NSNumber } /// Returns getter proxy for `key` public subscript(key: String) -> Proxy { return Proxy(self, key) } /// Sets value for `key` public subscript(key: String) -> Any? { get { // return untyped Proxy // (make sure we don't fall into infinite loop) let proxy: Proxy = self[key] return proxy } set { guard let newValue = newValue else { removeObject(forKey: key) return } switch newValue { // @warning This should always be on top of Int because a cast // from Double to Int will always succeed. case let v as Double: self.set(v, forKey: key) case let v as Int: self.set(v, forKey: key) case let v as Bool: self.set(v, forKey: key) case let v as URL: self.set(v, forKey: key) default: self.set(newValue, forKey: key) } } } /// Returns `true` if `key` exists public func hasKey(_ key: String) -> Bool { return object(forKey: key) != nil } /// Removes value for `key` public func remove(_ key: String) { removeObject(forKey: key) } /// Removes all keys and values from user defaults /// Use with caution! /// - Note: This method only removes keys on the receiver `UserDefaults` object. /// System-defined keys will still be present afterwards. public func removeAll() { for (key, _) in dictionaryRepresentation() { removeObject(forKey: key) } } } /// Global shortcut for `UserDefaults.standard` /// /// **Pro-Tip:** If you want to use shared user defaults, just /// redefine this global shortcut in your app target, like so: /// ~~~ /// var Defaults = UserDefaults(suiteName: "com.my.app")! /// ~~~ public let Defaults = UserDefaults.standard // MARK: - Static keys /// Extend this class and add your user defaults keys as static constants /// so you can use the shortcut dot notation (e.g. `Defaults[.yourKey]`) open class DefaultsKeys { fileprivate init() {} } /// Base class for static user defaults keys. Specialize with value type /// and pass key name to the initializer to create a key. open class DefaultsKey<ValueType>: DefaultsKeys { // TODO: Can we use protocols to ensure ValueType is a compatible type? open let _key: String public init(_ key: String) { self._key = key super.init() } } extension UserDefaults { /// This function allows you to create your own custom Defaults subscript. Example: [Int: String] public func set<T>(_ key: DefaultsKey<T>, _ value: Any?) { self[key._key] = value } } extension UserDefaults { /// Returns `true` if `key` exists public func hasKey<T>(_ key: DefaultsKey<T>) -> Bool { return object(forKey: key._key) != nil } /// Removes value for `key` public func remove<T>(_ key: DefaultsKey<T>) { removeObject(forKey: key._key) } } // MARK: Subscripts for specific standard types // TODO: Use generic subscripts when they become available extension UserDefaults { public subscript(key: DefaultsKey<String?>) -> String? { get { return string(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<String>) -> String { get { return string(forKey: key._key) ?? "" } set { set(key, newValue) } } public subscript(key: DefaultsKey<Int?>) -> Int? { get { return numberForKey(key._key)?.intValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Int>) -> Int { get { return numberForKey(key._key)?.intValue ?? 0 } set { set(key, newValue) } } public subscript(key: DefaultsKey<Double?>) -> Double? { get { return numberForKey(key._key)?.doubleValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Double>) -> Double { get { return numberForKey(key._key)?.doubleValue ?? 0.0 } set { set(key, newValue) } } public subscript(key: DefaultsKey<Bool?>) -> Bool? { get { return numberForKey(key._key)?.boolValue } set { set(key, newValue) } } public subscript(key: DefaultsKey<Bool>) -> Bool { get { return numberForKey(key._key)?.boolValue ?? false } set { set(key, newValue) } } public subscript(key: DefaultsKey<Any?>) -> Any? { get { return object(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<Data?>) -> Data? { get { return data(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<Data>) -> Data { get { return data(forKey: key._key) ?? Data() } set { set(key, newValue) } } public subscript(key: DefaultsKey<Date?>) -> Date? { get { return object(forKey: key._key) as? Date } set { set(key, newValue) } } public subscript(key: DefaultsKey<URL?>) -> URL? { get { return url(forKey: key._key) } set { set(key, newValue) } } // TODO: It would probably make sense to have support for statically typed dictionaries (e.g. [String: String]) public subscript(key: DefaultsKey<[String: Any]?>) -> [String: Any]? { get { return dictionary(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[String: Any]>) -> [String: Any] { get { return dictionary(forKey: key._key) ?? [:] } set { set(key, newValue) } } } // MARK: Static subscripts for array types extension UserDefaults { public subscript(key: DefaultsKey<[Any]?>) -> [Any]? { get { return array(forKey: key._key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Any]>) -> [Any] { get { return array(forKey: key._key) ?? [] } set { set(key, newValue) } } } // We need the <T: AnyObject> and <T: _ObjectiveCBridgeable> variants to // suppress compiler warnings about NSArray not being convertible to [T] // AnyObject is for NSData and NSDate, _ObjectiveCBridgeable is for value // types bridge-able to Foundation types (String, Int, ...) extension UserDefaults { public func getArray<T: _ObjectiveCBridgeable>(_ key: DefaultsKey<[T]>) -> [T] { return array(forKey: key._key) as NSArray? as? [T] ?? [] } public func getArray<T: _ObjectiveCBridgeable>(_ key: DefaultsKey<[T]?>) -> [T]? { return array(forKey: key._key) as NSArray? as? [T] } public func getArray<T: Any>(_ key: DefaultsKey<[T]>) -> [T] { return array(forKey: key._key) as NSArray? as? [T] ?? [] } public func getArray<T: Any>(_ key: DefaultsKey<[T]?>) -> [T]? { return array(forKey: key._key) as NSArray? as? [T] } } extension UserDefaults { public subscript(key: DefaultsKey<[String]?>) -> [String]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[String]>) -> [String] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Int]?>) -> [Int]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Int]>) -> [Int] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Double]?>) -> [Double]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Double]>) -> [Double] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Bool]?>) -> [Bool]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Bool]>) -> [Bool] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Data]?>) -> [Data]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Data]>) -> [Data] { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Date]?>) -> [Date]? { get { return getArray(key) } set { set(key, newValue) } } public subscript(key: DefaultsKey<[Date]>) -> [Date] { get { return getArray(key) } set { set(key, newValue) } } } // MARK: - Archiving custom types // MARK: RawRepresentable extension UserDefaults { // TODO: Ensure that T.RawValue is compatible public func archive<T: RawRepresentable>(_ key: DefaultsKey<T>, _ value: T) { set(key, value.rawValue) } public func archive<T: RawRepresentable>(_ key: DefaultsKey<T?>, _ value: T?) { if let value = value { set(key, value.rawValue) } else { remove(key) } } public func unarchive<T: RawRepresentable>(_ key: DefaultsKey<T?>) -> T? { return object(forKey: key._key).flatMap { T(rawValue: $0 as! T.RawValue) } } public func unarchive<T: RawRepresentable>(_ key: DefaultsKey<T>) -> T? { return object(forKey: key._key).flatMap { T(rawValue: $0 as! T.RawValue) } } } // MARK: NSCoding extension UserDefaults { // TODO: Can we simplify this and ensure that T is NSCoding compliant? public func archive<T>(_ key: DefaultsKey<T>, _ value: T) { set(key, NSKeyedArchiver.archivedData(withRootObject: value)) } public func archive<T>(_ key: DefaultsKey<T?>, _ value: T?) { if let value = value { set(key, NSKeyedArchiver.archivedData(withRootObject: value)) } else { remove(key) } } public func unarchive<T>(_ key: DefaultsKey<T>) -> T? { return data(forKey: key._key).flatMap { NSKeyedUnarchiver.unarchiveObject(with: $0) } as? T } public func unarchive<T>(_ key: DefaultsKey<T?>) -> T? { return data(forKey: key._key).flatMap { NSKeyedUnarchiver.unarchiveObject(with: $0) } as? T } } // MARK: - Deprecations infix operator ?= : AssignmentPrecedence /// If key doesn't exist, sets its value to `expr` /// - Deprecation: This will be removed in a future release. /// Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60 /// - Note: This isn't the same as `Defaults.registerDefaults`. This method saves the new value to disk, whereas `registerDefaults` only modifies the defaults in memory. /// - Note: If key already exists, the expression after ?= isn't evaluated @available(*, deprecated:1, message:"Please migrate to static keys and use this gist: https://gist.github.com/radex/68de9340b0da61d43e60") public func ?= (proxy: UserDefaults.Proxy, expr: @autoclosure() -> Any) { if !proxy.defaults.hasKey(proxy.key) { proxy.defaults[proxy.key] = expr() } } /// Adds `b` to the key (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to `b` @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public func += (proxy: UserDefaults.Proxy, b: Int) { let a = proxy.defaults[proxy.key].intValue proxy.defaults[proxy.key] = a + b } @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public func += (proxy: UserDefaults.Proxy, b: Double) { let a = proxy.defaults[proxy.key].doubleValue proxy.defaults[proxy.key] = a + b } /// Icrements key by one (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to 1 @available(*, deprecated:1, message:"Please migrate to static keys to use this.") public postfix func ++ (proxy: UserDefaults.Proxy) { proxy += 1 }
apache-2.0
cf298d46dd33618c26eaafae942ac3ae
29.884921
169
0.584415
4.224152
false
false
false
false
BBRick/wp
wp/Other/AppServerHelper.swift
1
3457
// // AppServerHelper.swift // wp // // Created by 木柳 on 2017/1/18. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit import Fabric import Crashlytics import Alamofire class AppServerHelper: NSObject , WXApiDelegate{ fileprivate static var helper = AppServerHelper() var feedbackKid: YWFeedbackKit? class func instance() -> AppServerHelper{ return helper } func initServer() { initFeedback() initFabric() wechat() } //阿里百川 func initFeedback() { feedbackKid = YWFeedbackKit.init(appKey: "23519848") } //Fabric func initFabric() { Fabric.with([Crashlytics.self]) } //友盟 fileprivate func umapp() { UMAnalyticsConfig.sharedInstance().appKey = AppConst.UMAppkey UMAnalyticsConfig.sharedInstance().channelId = "" MobClick.start(withConfigure: UMAnalyticsConfig.sharedInstance()) //version标识 let version: String? = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String MobClick.setAppVersion(version) //日志加密设置 MobClick.setEncryptEnabled(true) //使用集成测试服务 MobClick.setLogEnabled(true) } //个推 func pushMessageRegister() { //注册消息推送 DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: { () in #if true GeTuiSdk.start(withAppId: "d2YVUlrbRU6yF0PFQJfPkA", appKey: "yEIPB4YFxw64Ag9yJpaXT9", appSecret: "TMQWRB2KrG7QAipcBKGEyA", delegate: nil) #endif let notifySettings = UIUserNotificationSettings.init(types: [.alert, .badge, .sound], categories: nil) UIApplication.shared.registerUserNotificationSettings(notifySettings) UIApplication.shared.registerForRemoteNotifications() }) } //MARK: --Wechat fileprivate func wechat() { WXApi.registerApp("wx9dc39aec13ee3158") } func onResp(_ resp: BaseResp!) { //微信登录返回 if resp.isKind(of: SendAuthResp.classForCoder()) { let authResp:SendAuthResp = resp as! SendAuthResp NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.WechatKey.ErrorCode), object: NSNumber.init(value: resp.errCode), userInfo:nil) if authResp.errCode == 0{ let param = [SocketConst.Key.appid : AppConst.WechatKey.Appid, SocketConst.Key.code : authResp.code, SocketConst.Key.secret : AppConst.WechatKey.Secret, SocketConst.Key.grant_type : "authorization_code"] Alamofire.request(AppConst.WechatKey.AccessTokenUrl, method: .get, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: { (result) in }) } return } // 支付返回 if resp.isKind(of: PayResp.classForCoder()) { let authResp:PayResp = resp as! PayResp NotificationCenter.default.post(name: NSNotification.Name(rawValue: AppConst.WechatPay.WechatKeyErrorCode), object: NSNumber.init(value: authResp.errCode), userInfo:nil) return } } }
apache-2.0
993226b56df81dc0e028cf6dfb7c9a85
33.040404
193
0.615134
4.603825
false
false
false
false
danielmartin/swift
benchmark/single-source/StringComparison.swift
1
26610
//===--- StringComparison.swift -------------------------------------*- 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 // //===----------------------------------------------------------------------===// //////////////////////////////////////////////////////////////////////////////// // WARNING: This file is manually generated from .gyb template and should not // be directly modified. Instead, make changes to StringComparison.swift.gyb and run // scripts/generate_harness/generate_harness.py to regenerate this file. //////////////////////////////////////////////////////////////////////////////// // // Test String iteration performance over a variety of workloads, languages, // and symbols. // import TestsUtils extension String { func lines() -> [String] { return self.split(separator: "\n").map { String($0) } } } public let StringComparison: [BenchmarkInfo] = [ BenchmarkInfo( name: "StringComparison_ascii", runFunction: run_StringComparison_ascii, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_ascii) } ), BenchmarkInfo( name: "StringComparison_latin1", runFunction: run_StringComparison_latin1, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_latin1) }, legacyFactor: 2 ), BenchmarkInfo( name: "StringComparison_fastPrenormal", runFunction: run_StringComparison_fastPrenormal, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_fastPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "StringComparison_slowerPrenormal", runFunction: run_StringComparison_slowerPrenormal, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_slowerPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "StringComparison_nonBMPSlowestPrenormal", runFunction: run_StringComparison_nonBMPSlowestPrenormal, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_nonBMPSlowestPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "StringComparison_emoji", runFunction: run_StringComparison_emoji, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_emoji) }, legacyFactor: 4 ), BenchmarkInfo( name: "StringComparison_abnormal", runFunction: run_StringComparison_abnormal, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_abnormal) }, legacyFactor: 20 ), BenchmarkInfo( name: "StringComparison_zalgo", runFunction: run_StringComparison_zalgo, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_zalgo) }, legacyFactor: 25 ), BenchmarkInfo( name: "StringComparison_longSharedPrefix", runFunction: run_StringComparison_longSharedPrefix, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_longSharedPrefix) } ), ] public let StringHashing: [BenchmarkInfo] = [ BenchmarkInfo( name: "StringHashing_ascii", runFunction: run_StringHashing_ascii, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_ascii) } ), BenchmarkInfo( name: "StringHashing_latin1", runFunction: run_StringHashing_latin1, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_latin1) }, legacyFactor: 2 ), BenchmarkInfo( name: "StringHashing_fastPrenormal", runFunction: run_StringHashing_fastPrenormal, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_fastPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "StringHashing_slowerPrenormal", runFunction: run_StringHashing_slowerPrenormal, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_slowerPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "StringHashing_nonBMPSlowestPrenormal", runFunction: run_StringHashing_nonBMPSlowestPrenormal, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_nonBMPSlowestPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "StringHashing_emoji", runFunction: run_StringHashing_emoji, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_emoji) }, legacyFactor: 4 ), BenchmarkInfo( name: "StringHashing_abnormal", runFunction: run_StringHashing_abnormal, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_abnormal) }, legacyFactor: 20 ), BenchmarkInfo( name: "StringHashing_zalgo", runFunction: run_StringHashing_zalgo, tags: [.validation, .api, .String], setUpFunction: { blackHole(Workload_zalgo) }, legacyFactor: 25 ), ] public let NormalizedIterator: [BenchmarkInfo] = [ BenchmarkInfo( name: "NormalizedIterator_ascii", runFunction: run_NormalizedIterator_ascii, tags: [.validation, .String], setUpFunction: { blackHole(Workload_ascii) } ), BenchmarkInfo( name: "NormalizedIterator_latin1", runFunction: run_NormalizedIterator_latin1, tags: [.validation, .String], setUpFunction: { blackHole(Workload_latin1) }, legacyFactor: 2 ), BenchmarkInfo( name: "NormalizedIterator_fastPrenormal", runFunction: run_NormalizedIterator_fastPrenormal, tags: [.validation, .String], setUpFunction: { blackHole(Workload_fastPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "NormalizedIterator_slowerPrenormal", runFunction: run_NormalizedIterator_slowerPrenormal, tags: [.validation, .String], setUpFunction: { blackHole(Workload_slowerPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "NormalizedIterator_nonBMPSlowestPrenormal", runFunction: run_NormalizedIterator_nonBMPSlowestPrenormal, tags: [.validation, .String], setUpFunction: { blackHole(Workload_nonBMPSlowestPrenormal) }, legacyFactor: 10 ), BenchmarkInfo( name: "NormalizedIterator_emoji", runFunction: run_NormalizedIterator_emoji, tags: [.validation, .String], setUpFunction: { blackHole(Workload_emoji) }, legacyFactor: 4 ), BenchmarkInfo( name: "NormalizedIterator_abnormal", runFunction: run_NormalizedIterator_abnormal, tags: [.validation, .String], setUpFunction: { blackHole(Workload_abnormal) }, legacyFactor: 20 ), BenchmarkInfo( name: "NormalizedIterator_zalgo", runFunction: run_NormalizedIterator_zalgo, tags: [.validation, .String], setUpFunction: { blackHole(Workload_zalgo) }, legacyFactor: 25 ), ] var Workload_ascii: Workload! = Workload.ascii var Workload_latin1: Workload! = Workload.latin1 var Workload_fastPrenormal: Workload! = Workload.fastPrenormal var Workload_slowerPrenormal: Workload! = Workload.slowerPrenormal var Workload_nonBMPSlowestPrenormal: Workload! = Workload.nonBMPSlowestPrenormal var Workload_emoji: Workload! = Workload.emoji var Workload_abnormal: Workload! = Workload.abnormal var Workload_zalgo: Workload! = Workload.zalgo var Workload_longSharedPrefix: Workload! = Workload.longSharedPrefix @inline(never) public func run_StringComparison_ascii(_ N: Int) { let workload: Workload = Workload_ascii let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringComparison_latin1(_ N: Int) { let workload: Workload = Workload_latin1 let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringComparison_fastPrenormal(_ N: Int) { let workload: Workload = Workload_fastPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringComparison_slowerPrenormal(_ N: Int) { let workload: Workload = Workload_slowerPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringComparison_nonBMPSlowestPrenormal(_ N: Int) { let workload: Workload = Workload_nonBMPSlowestPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringComparison_emoji(_ N: Int) { let workload: Workload = Workload_emoji let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringComparison_abnormal(_ N: Int) { let workload: Workload = Workload_abnormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringComparison_zalgo(_ N: Int) { let workload: Workload = Workload_zalgo let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringComparison_longSharedPrefix(_ N: Int) { let workload: Workload = Workload_longSharedPrefix let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for s1 in payload { for s2 in payload { blackHole(s1 < s2) } } } } @inline(never) public func run_StringHashing_ascii(_ N: Int) { let workload: Workload = Workload.ascii let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { blackHole(str.hashValue) } } } @inline(never) public func run_StringHashing_latin1(_ N: Int) { let workload: Workload = Workload.latin1 let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { blackHole(str.hashValue) } } } @inline(never) public func run_StringHashing_fastPrenormal(_ N: Int) { let workload: Workload = Workload.fastPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { blackHole(str.hashValue) } } } @inline(never) public func run_StringHashing_slowerPrenormal(_ N: Int) { let workload: Workload = Workload.slowerPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { blackHole(str.hashValue) } } } @inline(never) public func run_StringHashing_nonBMPSlowestPrenormal(_ N: Int) { let workload: Workload = Workload.nonBMPSlowestPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { blackHole(str.hashValue) } } } @inline(never) public func run_StringHashing_emoji(_ N: Int) { let workload: Workload = Workload.emoji let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { blackHole(str.hashValue) } } } @inline(never) public func run_StringHashing_abnormal(_ N: Int) { let workload: Workload = Workload.abnormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { blackHole(str.hashValue) } } } @inline(never) public func run_StringHashing_zalgo(_ N: Int) { let workload: Workload = Workload.zalgo let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { blackHole(str.hashValue) } } } @inline(never) public func run_NormalizedIterator_ascii(_ N: Int) { let workload: Workload = Workload.ascii let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { str._withNFCCodeUnits { cu in blackHole(cu) } } } } @inline(never) public func run_NormalizedIterator_latin1(_ N: Int) { let workload: Workload = Workload.latin1 let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { str._withNFCCodeUnits { cu in blackHole(cu) } } } } @inline(never) public func run_NormalizedIterator_fastPrenormal(_ N: Int) { let workload: Workload = Workload.fastPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { str._withNFCCodeUnits { cu in blackHole(cu) } } } } @inline(never) public func run_NormalizedIterator_slowerPrenormal(_ N: Int) { let workload: Workload = Workload.slowerPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { str._withNFCCodeUnits { cu in blackHole(cu) } } } } @inline(never) public func run_NormalizedIterator_nonBMPSlowestPrenormal(_ N: Int) { let workload: Workload = Workload.nonBMPSlowestPrenormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { str._withNFCCodeUnits { cu in blackHole(cu) } } } } @inline(never) public func run_NormalizedIterator_emoji(_ N: Int) { let workload: Workload = Workload.emoji let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { str._withNFCCodeUnits { cu in blackHole(cu) } } } } @inline(never) public func run_NormalizedIterator_abnormal(_ N: Int) { let workload: Workload = Workload.abnormal let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { str._withNFCCodeUnits { cu in blackHole(cu) } } } } @inline(never) public func run_NormalizedIterator_zalgo(_ N: Int) { let workload: Workload = Workload.zalgo let tripCount = workload.tripCount let payload = workload.payload for _ in 1...tripCount*N { for str in payload { str._withNFCCodeUnits { cu in blackHole(cu) } } } } struct Workload { static let N = 100 let name: String let payload: [String] var scaleMultiplier: Double init(name: String, payload: [String], scaleMultiplier: Double = 1.0) { self.name = name self.payload = payload self.scaleMultiplier = scaleMultiplier } var tripCount: Int { return Int(Double(Workload.N) * scaleMultiplier) } static let ascii = Workload( name: "ASCII", payload: """ woodshed lakism gastroperiodynia afetal Casearia ramsch Nickieben undutifulness decorticate neognathic mentionable tetraphenol pseudonymal dislegitimate Discoidea criminative disintegratory executer Cylindrosporium complimentation Ixiama Araceae silaginoid derencephalus Lamiidae marrowlike ninepin trihemimer semibarbarous heresy existence fretless Amiranha handgravure orthotropic Susumu teleutospore sleazy shapeliness hepatotomy exclusivism stifler cunning isocyanuric pseudepigraphy carpetbagger unglory """.lines(), scaleMultiplier: 0.25 ) static let latin1 = Workload( name: "Latin1", payload: """ café résumé caférésumé ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º 1+1=3 ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹ ¡¢£¤¥¦§¨©ª«¬­® »¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍ ÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãä åæçèéêëìíîïðñò ÎÏÐÑÒÓÔÕÖëìíîïðñò óôõö÷øùúûüýþÿ 123.456£=>¥ 123.456 """.lines(), scaleMultiplier: 1/2 ) static let fastPrenormal = Workload( name: "FastPrenormal", payload: """ ĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥ ĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸ ĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲ ųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆ ƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀ Ƈ ǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖ ǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑ ȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬ ȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑ ȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰ ɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄ ɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃ ʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰ ʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦ ˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾ """.lines(), scaleMultiplier: 1/10 ) static let slowerPrenormal = Workload( name: "SlowerPrenormal", payload: """ Swiftに大幅な改良が施され、 安定していてしかも 直感的に使うことができる 向けプログラミング言語になりました。 이번 업데이트에서는 강력하면서도 \u{201c}Hello\u{2010}world\u{2026}\u{201d} 平台的编程语言 功能强大且直观易用 而本次更新对其进行了全面优化 в чащах юга жил-был цитрус \u{300c}\u{300e}今日は\u{3001}世界\u{3002}\u{300f}\u{300d} но фальшивый экземпляр """.lines(), scaleMultiplier: 1/10 ) // static let slowestPrenormal = """ // """.lines() static let nonBMPSlowestPrenormal = Workload( name: "NonBMPSlowestPrenormal", payload: """ 𓀀𓀤𓁓𓁲𓃔𓃗 𓀀𓀁𓀂𓀃𓀄𓀇𓀈𓀉𓀊𓀋𓀌𓀍𓀎𓀏𓀓𓀔𓀕𓀖𓀗𓀘𓀙𓀚𓀛𓀜𓀞𓀟𓀠𓀡𓀢𓀣 𓀤𓀥𓀦𓀧𓀨𓀩𓀪𓀫𓀬𓀭 𓁡𓁢𓁣𓁤𓁥𓁦𓁧𓁨𓁩𓁫𓁬𓁭𓁮𓁯𓁰𓁱𓁲𓁳𓁴𓁵𓁶𓁷𓁸 𓁹𓁺𓁓𓁔𓁕𓁻𓁼𓁽𓁾𓁿 𓀀𓀁𓀂𓀃𓀄𓃒𓃓𓃔𓃕𓃻𓃼𓃽𓃾𓃿𓄀𓄁𓄂𓄃𓄄𓄅𓄆𓄇𓄈𓄉𓄊𓄋𓄌𓄍𓄎 𓂿𓃀𓃁𓃂𓃃𓃄𓃅 𓃘𓃙𓃚𓃛𓃠𓃡𓃢𓃣𓃦𓃧𓃨𓃩𓃬𓃭𓃮𓃯𓃰𓃲𓃳𓃴𓃵𓃶𓃷𓃸 𓃘𓃙𓃚𓃛𓃠𓃡𓃢𓃣𓃦𓃧𓃨𓃩𓃬𓃭𓃮𓃯𓃰𓃲𓃳𓃴𓃵𓃶𓃷 𓀀𓀁𓀂𓀃𓀄𓆇𓆈𓆉𓆊𓆋𓆌𓆍𓆎𓆏𓆐𓆑𓆒𓆓𓆔𓆗𓆘𓆙𓆚𓆛𓆝𓆞𓆟𓆠𓆡𓆢𓆣𓆤 𓆥𓆦𓆧𓆨𓆩𓆪𓆫𓆬𓆭𓆮𓆯𓆰𓆱𓆲𓆳𓆴𓆵𓆶𓆷𓆸𓆹𓆺𓆻 """.lines(), scaleMultiplier: 1/10 ) static let emoji = Workload( name: "Emoji", payload: """ 👍👩‍👩‍👧‍👧👨‍👨‍👦‍👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿 👍👩‍👩‍👧‍👧👨‍👨‍👦‍👦🇺🇸🇨🇦🇲🇽👍🏿👍🏻👍🏼👍🏽👍🏾 😀🧀😀😃😄😁🤣😂😅😆 😺🎃🤖👾😸😹😻😼😾😿🙀😽🙌🙏🤝👍✌🏽 ☺️😊😇🙂😍😌😉🙃😘😗😙😚😛😝😜 😋🤑🤗🤓😎😒😏🤠🤡😞😔😟😕😖😣☹️🙁😫😩😤😠😑😐😶😡😯 😦😧😮😱😳😵😲😨😰😢😥 😪😓😭🤤😴🙄🤔🤥🤧🤢🤐😬😷🤒🤕😈💩👺👹👿👻💀☠️👽 """.lines(), scaleMultiplier: 1/4 ) static let abnormal = Workload( name: "Abnormal", payload: """ ae\u{301}ae\u{301}ae\u{302}ae\u{303}ae\u{304}ae\u{305}ae\u{306}ae\u{307} ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{300} \u{f900}\u{f901}\u{f902}\u{f903}\u{f904}\u{f905}\u{f906}\u{f907}\u{f908}\u{f909}\u{f90a} \u{f90b}\u{f90c}\u{f90d}\u{f90e}\u{f90f}\u{f910}\u{f911}\u{f912}\u{f913}\u{f914}\u{f915}\u{f916}\u{f917}\u{f918}\u{f919} \u{f900}\u{f91a}\u{f91b}\u{f91c}\u{f91d}\u{f91e}\u{f91f}\u{f920}\u{f921}\u{f922} """.lines(), scaleMultiplier: 1/20 ) // static let pathological = """ // """.lines() static let zalgo = Workload( name: "Zalgo", payload: """ ṭ̴̵̶̷̸̢̧̨̡̛̤̥̦̩̪̫̬̭̮̯̰̖̗̘̙̜̝̞̟̠̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉ͣͤ̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚͜͟͢͝͞͠͡ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡ h̀́̂̃ è͇͈͉͍͎́̂̃̄̅̆̇̈̉͊͋͌͏̡̢̧̨̛͓͔͕͖͙͚̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭͇͈͉͍͎͐͑͒͗͛̊̋̌̍̎̏̐̑̒̓̔̀́͂̓̈́͆͊͋͌͘̕̚͜͟͝͞͠ͅ͏͓͔͕͖͐͑͒ q̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆̕̚ͅ ư̴̵̶̷̸̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡ ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘ c̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼̀́̂̃̄̔̽̾̿̀́͂̓̈́͆ͣͤͥͦͧͨͩͪͫͬͭͮ̕̚͢͡ͅ k̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡ b̴̵̶̷̸̡̢̛̗̘̙̜̝̞̟̠̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡ ŗ̴̵̶̷̸̨̛̩̪̫̯̰̱̲̳̹̺̻̼̬̭̮͇̗̘̙̜̝̞̟̤̥̦͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏̡̢͓͔͕͖͙͚̠̣͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡ o w̗̘͇͈͉͍͎̓̈́͆͊͋͌ͅ͏̛͓͔͕͖͙͚̙̜̹̺̻̼͐͑͒͗͛ͣͤͥͦ̽̾̿̀́͂ͧͨͩͪͫͬͭͮ͘̚͜͟͢͝͞͠͡ n͇͈͉͍͎͊͋͌ͧͨͩͪͫͬͭͮ͏̛͓͔͕͖͙͚̗̘̙̜̹̺̻̼͐͑͒͗͛ͣͤͥͦ̽̾̿̀́͂̓̈́͆ͧͨͩͪͫͬͭͮ͘̚͜͟͢͝͞͠͡ͅ f̛̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦ͘͜͟͢͝͞͠͡ ơ̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͥͦͧͨͩͪͫͬͭͮ͘ xͣͤͥͦͧͨͩͪͫͬͭͮ """.lines(), scaleMultiplier: 1/100 ) static let longSharedPrefix = Workload( name: "LongSharedPrefix", payload: """ http://www.dogbook.com/dog/239495828/friends/mutual/2939493815 http://www.dogbook.com/dog/239495828/friends/mutual/3910583739 http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 🤔Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔 """.lines() ) } // Local Variables: // eval: (read-only-mode 1) // End:
apache-2.0
339650587a8bbd2047da4c0c5fe731ad
28.811944
451
0.641164
3.10385
false
false
false
false
sayheyrickjames/codepath-tipr
tipr/tipr/ViewController.swift
1
1842
// // ViewController.swift // tipr // // Created by Rick James! Chatas on 4/2/15. // Copyright (c) 2015 SayHey. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var boilerplateView: UIView! @IBOutlet weak var boilerplate2View: UIView! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var billField: UITextField! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var totalLabel: UILabel! var originalHelloLabelPosition: CGFloat! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tipLabel.text = "$0.00" totalLabel.text = "$0.00" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onEditingChanged(sender: AnyObject) { var tipPercentages = [0.18, 0.2, 0.22] var tipPercentage = tipPercentages [tipControl.selectedSegmentIndex] var billAmount = billField.text._bridgeToObjectiveC().doubleValue var tip = billAmount * tipPercentage var total = billAmount + tip tipLabel.text = "$\(tip)" totalLabel.text = "$\(total)" tipLabel.text = String(format: "$%.2f", tip) totalLabel.text = String(format: "$%.2f",total) } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } @IBAction func didTapBillField(sender: AnyObject) { UIView.animateWithDuration(0.5, animations: { () -> Void in self.boilerplateView.center.y = -100 self.boilerplate2View.center.y = 210 }) } }
gpl-2.0
71c32aa4dbbe29e65bbd0b79d038819e
25.314286
80
0.617264
4.723077
false
false
false
false
mozilla-mobile/focus-ios
Blockzilla/HomeViewController.swift
1
8297
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Telemetry import Onboarding protocol HomeViewControllerDelegate: AnyObject { func homeViewControllerDidTapShareTrackers(_ controller: HomeViewController, sender: UIButton) func homeViewControllerDidTapTip(_ controller: HomeViewController, tip: TipManager.Tip) func homeViewControllerDidTouchEmptyArea(_ controller: HomeViewController) } class HomeViewController: UIViewController { weak var delegate: HomeViewControllerDelegate? private lazy var tipView: UIView = { let tipView = UIView() tipView.translatesAutoresizingMaskIntoConstraints = false return tipView }() private lazy var textLogo: UIImageView = { let textLogo = UIImageView() textLogo.image = AppInfo.isKlar ? #imageLiteral(resourceName: "img_klar_wordmark") : #imageLiteral(resourceName: "img_focus_wordmark") textLogo.contentMode = .scaleAspectFit textLogo.translatesAutoresizingMaskIntoConstraints = false return textLogo }() private let tipManager: TipManager private lazy var tipsViewController = TipsPageViewController( tipManager: tipManager, tipTapped: didTap(tip:), tapOutsideAction: dismissKeyboard ) var onboardingEventsHandler: OnboardingEventsHandling! let toolbar: HomeViewToolbar = { let toolbar = HomeViewToolbar() toolbar.translatesAutoresizingMaskIntoConstraints = false return toolbar }() var tipViewConstraints: [NSLayoutConstraint] = [] var textLogoTopConstraints: [NSLayoutConstraint] = [] deinit { NotificationCenter.default.removeObserver(self) } init(tipManager: TipManager) { self.tipManager = tipManager super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() rotated() NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil) self.view.addSubview(textLogo) self.view.addSubview(toolbar) self.view.addSubview(tipView) NSLayoutConstraint.activate([ textLogo.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), textLogo.topAnchor.constraint(equalTo: self.view.centerYAnchor, constant: UIConstants.layout.textLogoOffset), textLogo.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: UIConstants.layout.textLogoMargin), textLogo.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -UIConstants.layout.textLogoMargin) ]) tipViewConstraints = [ tipView.bottomAnchor.constraint(equalTo: toolbar.topAnchor, constant: UIConstants.layout.tipViewBottomOffset), tipView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), tipView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), tipView.heightAnchor.constraint(equalToConstant: UIConstants.layout.tipViewHeight) ] NSLayoutConstraint.activate(tipViewConstraints) NSLayoutConstraint.activate([ toolbar.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), toolbar.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor), toolbar.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor) ]) refreshTipsDisplay() install(tipsViewController, on: tipView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func refreshTipsDisplay() { tipsViewController.setupPageController( with: .showEmpty( controller: ShareTrackersViewController( trackerTitle: tipManager.shareTrackersDescription(), shareTap: { [weak self] sender in guard let self = self else { return } self.delegate?.homeViewControllerDidTapShareTrackers(self, sender: sender) } ))) Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.show, object: TelemetryEventObject.trackerStatsShareButton) } @objc private func rotated() { if UIApplication.shared.orientation?.isLandscape == true { if UIDevice.current.userInterfaceIdiom == .pad { // On iPad in landscape we only show the tips. hideTextLogo() showTips() } else { // On iPhone in landscape we show neither. hideTextLogo() hideTips() } } else { // In portrait on any form factor we show both. showTextLogo() showTips() } } private func hideTextLogo() { textLogo.isHidden = true } private func showTextLogo() { textLogo.isHidden = false } private func hideTips() { tipsViewController.view.isHidden = true } private func showTips() { tipsViewController.view.isHidden = false } func logTelemetry(for tip: TipManager.Tip) { switch tip.identifier { case TipManager.TipKey.biometricTip: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.show, object: TelemetryEventObject.biometricTip) case TipManager.TipKey.requestDesktopTip: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.show, object: TelemetryEventObject.requestDesktopTip) case TipManager.TipKey.siriEraseTip: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.show, object: TelemetryEventObject.siriEraseTip) case TipManager.TipKey.siriFavoriteTip: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.show, object: TelemetryEventObject.siriFavoriteTip) case TipManager.TipKey.sitesNotWorkingTip: Telemetry.default.recordEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.show, object: TelemetryEventObject.sitesNotWorkingTip) default: break } } func updateUI(urlBarIsActive: Bool, isBrowsing: Bool = false) { toolbar.isHidden = urlBarIsActive NSLayoutConstraint.deactivate(tipViewConstraints) tipViewConstraints = [ tipView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), tipView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), tipView.heightAnchor.constraint(equalToConstant: UIConstants.layout.tipViewHeight), tipView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor) ] if isBrowsing { tipViewConstraints.append(tipView.heightAnchor.constraint(equalToConstant: 0)) } if urlBarIsActive { tipViewConstraints.append(tipView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)) } else { tipViewConstraints.append(tipView.bottomAnchor.constraint(equalTo: toolbar.topAnchor, constant: UIConstants.layout.tipViewBottomOffset)) } NSLayoutConstraint.activate(tipViewConstraints) if UIScreen.main.bounds.height == UIConstants.layout.iPhoneSEHeight { NSLayoutConstraint.deactivate(textLogoTopConstraints) textLogoTopConstraints = [self.textLogo.topAnchor.constraint(equalTo: self.view.centerYAnchor, constant: urlBarIsActive ? UIConstants.layout.textLogoOffsetSmallDevice : UIConstants.layout.textLogoOffset)] NSLayoutConstraint.activate(textLogoTopConstraints) } } private func didTap(tip: TipManager.Tip) { delegate?.homeViewControllerDidTapTip(self, tip : tip) } private func dismissKeyboard() { delegate?.homeViewControllerDidTouchEmptyArea(self) } }
mpl-2.0
507efb8f1378c21e4135452ec4642d47
41.331633
216
0.694227
5.50564
false
false
false
false
rohan-panchal/Scaffold
Scaffold/Classes/UIKit/Extensions/NSLayoutConstraint+Extensions.swift
1
7218
// // NSLayoutConstraint+Extensions.swift // Scaffold // // Created by Panchal, Rohan on 9/9/16. // // import UIKit public class NSLayoutConstraintBuilder: NSObject { var firstItem: AnyObject? var firstAttribute: NSLayoutAttribute? var relation: NSLayoutRelation? var secondItem: AnyObject? var secondAttribute: NSLayoutAttribute? var multiplier: CGFloat = 1.0 var constant: CGFloat = 0.0 public func firstItem(firstItem: AnyObject) -> NSLayoutConstraintBuilder { self.firstItem = firstItem return self } public func firstAttribute(attribute: NSLayoutAttribute) -> NSLayoutConstraintBuilder { self.firstAttribute = attribute return self } public func relatedBy(relation: NSLayoutRelation) -> NSLayoutConstraintBuilder { self.relation = relation return self } public func secondItem(secondItem: AnyObject) -> NSLayoutConstraintBuilder { self.secondItem = secondItem return self } public func secondAttribute(attribute: NSLayoutAttribute) -> NSLayoutConstraintBuilder { self.secondAttribute = attribute return self } public func multiplier(value: CGFloat) -> NSLayoutConstraintBuilder { self.multiplier = value return self } public func constant(value: CGFloat) -> NSLayoutConstraintBuilder { self.constant = value return self } public func constraint() -> NSLayoutConstraint? { guard let firstItem = self.firstItem, let firstAttribute = self.firstAttribute, let relation = self.relation, let secondItem = self.secondItem, let secondAttribute = self.secondAttribute else { return nil } return NSLayoutConstraint(item: firstItem, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: self.multiplier, constant: self.constant) } } extension NSLayoutConstraint { public class func builder() -> NSLayoutConstraintBuilder { return NSLayoutConstraintBuilder() } } extension NSLayoutConstraint { /** Constrains a subview to be equal height and width to a superview. - parameter superView: A UIView object. - parameter subView: A UIView object. - returns: An array of NSLayoutConstraints. */ public static func constrainSubViewToEqualFrames(superView: UIView, subView: UIView) -> [NSLayoutConstraint] { let views = ["_superView": superView, "_subView": subView] var constraints: [NSLayoutConstraint] = [] constraints.appendContentsOf( NSLayoutConstraint.constraintsWithVisualFormat("V:|[_subView]|", options: .AlignAllCenterX, metrics: nil, views: views)) constraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("H:|[_subView]|", options: .AlignAllCenterY, metrics: nil, views: views)) return constraints } /** Constrains a subview's center to be equal to its superview. - parameter superView: A UIView object. - parameter subView: A UIView object. - returns: An array of NSLayoutConstraints. */ public static func constrainSubViewToCenterWithinSuperview(superView: UIView, subView: UIView) -> [NSLayoutConstraint] { let views = ["_superView": superView, "_subView": subView] var constraints: [NSLayoutConstraint] = [] constraints.appendContentsOf( NSLayoutConstraint.constraintsWithVisualFormat("V:[_superView]-(<=1)-[_subView]", options: .AlignAllCenterX, metrics: nil, views: views)) constraints.appendContentsOf( NSLayoutConstraint.constraintsWithVisualFormat("H:[_superView]-(<=1)-[_subView]", options: .AlignAllCenterY, metrics: nil, views: views)) return constraints } /** Creates an NSLayoutConstraint equating the Height attribute of both the first and second view with a multiplier and a constant. - parameter firstView: A UIView. - parameter secondView: A UIView. - parameter multiplier: A CGFloat. - parameter constant: A CGFloat. - returns: An NSLayoutConstraint object. */ public static func constrainToEqualHeights(firstView: UIView, secondView: UIView, multiplier: CGFloat, constant: CGFloat) -> NSLayoutConstraint { return constraintForEqualAttribute(firstView, secondView: secondView, attribute: .Height, multiplier: multiplier, constant: constant) } /** Creates an NSLayoutConstraint equating the Width attribute of both the first and second view with a multiplier and a constant. - parameter firstView: A UIView. - parameter secondView: A UIView. - parameter multiplier: A CGFloat. - parameter constant: A CGFloat. - returns: An NSLayoutConstraint object. */ public static func constrainToEqualWidths(firstView: UIView, secondView: UIView, multiplier: CGFloat, constant: CGFloat) -> NSLayoutConstraint { return constraintForEqualAttribute(firstView, secondView: secondView, attribute: .Width, multiplier: multiplier, constant: constant) } /** Creates an NSLayoutConstraint equating a specific attribute of both the first and second view with a multiplier and a constant. - parameter firstView: A UIView. - parameter secondView: A UIView. - parameter attribute: An NSLayoutAttribute. - parameter multiplier: A CGFloat. - parameter constant: A CGFloat. - returns: An NSLayoutConstraint object. */ public static func constraintForEqualAttribute(firstView: UIView, secondView: UIView, attribute: NSLayoutAttribute, multiplier: CGFloat, constant: CGFloat) -> NSLayoutConstraint { return NSLayoutConstraint(item: firstView, attribute: attribute, relatedBy: .Equal, toItem: secondView, attribute: attribute, multiplier: multiplier, constant: constant) } }
mit
8893f7908e3a5d82c7285f60db3e69ba
36.206186
141
0.577861
6.410302
false
false
false
false
auth0/Lock.swift
LockTests/LockSpec.swift
1
9166
// LockSpec.swift // // Copyright (c) 2016 Auth0 (http://auth0.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 import UIKit import Quick import Nimble import Auth0 @testable import Lock class LockSpec: QuickSpec { override func spec() { var lock: Lock! var authentication: Authentication! var webAuth: WebAuth! describe("init") { it("should init clasic mode") { lock = Lock.classic(clientId: clientId, domain: domain) expect(lock.classicMode) == true } it("should init passwordless mode") { lock = Lock.passwordless(clientId: clientId, domain: domain) expect(lock.classicMode) == false } } beforeEach { authentication = Auth0.authentication(clientId: clientId, domain: domain) webAuth = MockWebAuth() lock = Lock(authentication: authentication, webAuth: webAuth) } describe("options") { it("should allow settings options") { _ = lock.withOptions { $0.closable = true } expect(lock.options.closable) == true } it("should have defaults if never called") { expect(lock.options.closable) == false } it("should use the latest options") { _ = lock.withOptions { $0.closable = true } _ = lock.withOptions { $0.closable = false } expect(lock.options.closable) == false } it("should return itself") { expect(lock.withOptions { _ in } ) == lock } context("loggable") { it("should be disabled by default") { expect(lock.authentication.logger).to(beNil()) expect(lock.webAuth.logger).to(beNil()) } it("should enable logging") { _ = lock.withOptions { $0.logHttpRequest = true } expect(lock.authentication.logger).toNot(beNil()) expect(lock.webAuth.logger).toNot(beNil()) } } } describe("withConnections") { it("should allow settings connections") { _ = lock.withConnections { $0.database(name: "MyDB", requiresUsername: false) } expect(lock.connections.database?.name) == "MyDB" } it("should have defaults if never called") { expect(lock.connections.database).to(beNil()) } it("should use the latest options") { _ = lock.withConnections { $0.database(name: "MyDB", requiresUsername: false) } _ = lock.withConnections { $0.database(name: "AnotherDB", requiresUsername: false) } expect(lock.connections.database?.name) == "AnotherDB" } it("should return itself") { expect(lock.withConnections { _ in } ) == lock } } describe("present") { var controller: MockViewController! beforeEach { controller = MockViewController() } it("should present lock viewcontroller") { lock.present(from: controller) expect(controller.presented).notTo(beNil()) } it("should fail if options are invalid") { _ = lock.withOptions { $0.allow = [] } waitUntil { done in lock .onError { _ in done() } .present(from: controller) } } } describe("onAction") { it("should register onAuth callback") { var credentials: Credentials? = nil let callback: (Credentials) -> () = { credentials = $0 } let _ = lock.onAuth(callback: callback) lock.observerStore.onAuth(mockCredentials()) expect(credentials).toNot(beNil()) } it("should register onError callback") { var error: Error? = nil let callback: (Error) -> () = { error = $0 } let _ = lock.onError(callback: callback) lock.observerStore.onFailure(NSError(domain: "com.auth0", code: 0, userInfo: [:])) expect(error).toNot(beNil()) } it("should register onSignUp callback") { var email: String? = nil var attributes: [String: Any]? = nil let callback: (String, [String: Any]) -> () = { email = $0; attributes = $1 } let _ = lock.onSignUp(callback: callback) lock.observerStore.onSignUp("[email protected]", [:]) expect(email).toNot(beNil()) expect(attributes).toNot(beNil()) } it("should register onCancel callback") { var executed = false let callback: () -> () = { executed = true } let _ = lock.onCancel(callback: callback) lock.observerStore.onCancel() expect(executed) == true } it("should register onForgotPassword callback") { var email: String? = nil let callback: (String) -> () = { email = $0 } let _ = lock.onForgotPassword(callback: callback) lock.observerStore.onForgotPassword("[email protected]") expect(email) == "[email protected]" } it("should register onPasswordless callback") { var email: String? = nil let callback: (String) -> () = { email = $0 } let _ = lock.onPasswordless(callback: callback) lock.observerStore.onPasswordless("[email protected]") expect(email) == "[email protected]" } } describe("native handler") { it("should regsiter native handler") { let nativeHandler = MockNativeAuthHandler() let name = "facebook" _ = lock.nativeAuthentication(forConnection: name, handler: nativeHandler) expect(lock.nativeHandlers[name]).toNot(beNil()) } it("should regsiter native handler to multiple connections") { let nativeHandler = MockNativeAuthHandler() _ = lock.nativeAuthentication(forConnection: "facebook", handler: nativeHandler) _ = lock.nativeAuthentication(forConnection: "facebookcorp", handler: nativeHandler) expect(lock.nativeHandlers["facebook"]).toNot(beNil()) expect(lock.nativeHandlers["facebookcorp"]).toNot(beNil()) } } describe("style") { beforeEach { _ = lock.withStyle { $0.title = "Test Title" $0.primaryColor = UIColor.green $0.logo = UIImage(named: "ic_auth0", in: Lock.bundle) } } it("title should be match custom title") { expect(lock.style.title).to(equal("Test Title")) } it("primary color should be match custom color") { expect(lock.style.primaryColor).to(equal(UIColor.green)) } it("logo should be match custom UIImage") { expect(lock.style.logo).to(equal(UIImage(named: "ic_auth0", in: Lock.bundle))) } } it("should allow to resume Auth") { expect(Lock.resumeAuth(.a0_url("samples.auth0.com"), options: [:])) == false } it("should allow to continue activity") { expect(Lock.continueAuth(using: NSUserActivity(activityType: "test"))) == false } } }
mit
76227214d3ecd55838199941c17a851d
35.229249
100
0.528366
5.027976
false
false
false
false
filestack/filestack-ios
Sources/Filestack/Internal/Extensions/UIImage+HEIC.swift
1
813
// // UIImage+HEIC.swift // Filestack // // Created by Ruben Nine on 11/20/17. // Copyright © 2017 Filestack. All rights reserved. // import AVFoundation import UIKit extension UIImage { func heicRepresentation(quality: Float) -> Data? { var imageData: Data? let destinationData = NSMutableData() if let destination = CGImageDestinationCreateWithData(destinationData, AVFileType.heic as CFString, 1, nil), let cgImage = cgImage { let options = [kCGImageDestinationLossyCompressionQuality: quality] CGImageDestinationAddImage(destination, cgImage, options as CFDictionary) CGImageDestinationFinalize(destination) imageData = destinationData as Data return imageData } return nil } }
mit
d36b37654a7cc1d9b282e4901f0f1f26
26.066667
116
0.668719
5.075
false
false
false
false
MQZHot/ZLaunchAdVC
Sources/ZLaunchAd/ZLaunchAd.swift
1
3069
// // ZLaunchAd.swift // ZLaunchAdSwift // // Created by MQZHot on 2017/12/30. // Copyright © 2017年 MQZHot. All rights reserved. // // https://github.com/MQZHot/ZLaunchAd // import UIKit @objc public class ZLaunchAd: NSObject { /// 创建广告view --- 进入前台时显示 /// /// - Parameters: /// - waitTime: 加载广告等待的时间,默认3s /// - showEnterForeground: 是否进入前台时显示,默认`false` /// - timeForWillEnterForeground: 控制进入后台到前台显示的时间 /// - adNetRequest: 广告网络请求。如果需要每次进入前台是显示不同的广告图片,网络请求写在此闭包中 /// - Returns: ZLaunchAdView @discardableResult @objc public class func create(waitTime: Int = 3, showEnterForeground: Bool = false, timeForWillEnterForeground: Double = 10, adNetRequest: ((ZLaunchAdView)->())? = nil) -> ZLaunchAdView { let launchAdView: ZLaunchAdView if showEnterForeground { launchAdView = ZLaunchAdView.default launchAdView.appear(showEnterForeground: showEnterForeground, timeForWillEnterForeground: timeForWillEnterForeground) } else { launchAdView = ZLaunchAdView() launchAdView.appear(showEnterForeground: false, timeForWillEnterForeground: timeForWillEnterForeground) } launchAdView.adRequest = adNetRequest launchAdView.waitTime = waitTime UIApplication.shared.delegate?.window??.addSubview(launchAdView) return launchAdView } /// 创建广告view --- 自定义通知控制出现 /// /// - Parameters: /// - waitTime: 加载广告等待的时间,默认3s /// - customNotificationName: 自定义通知名称 /// - adNetRequest: 广告网络请求。如果需要每次进入前台是显示不同的广告图片,网络请求写在此闭包中 /// - Returns: ZLaunchAdView @discardableResult @objc public class func create(waitTime: Int = 3, customNotificationName: String?, adNetRequest: ((ZLaunchAdView)->())? = nil) -> ZLaunchAdView { let launchAdView: ZLaunchAdView = ZLaunchAdView.default launchAdView.appear(showEnterForeground: false, customNotificationName: customNotificationName) launchAdView.adRequest = adNetRequest launchAdView.waitTime = waitTime UIApplication.shared.keyWindow?.addSubview(launchAdView) return launchAdView } // MARK: - 清除缓存 /// 清除全部缓存 @objc public class func clearDiskCache() { ZLaunchAdClearDiskCache() } /// 清除指定url缓存 /// /// - Parameter urlArray: url数组 @objc public class func clearDiskCacheWithImageUrlArray(_ urlArray: Array<String>) { ZLaunchAdClearDiskCacheWithImageUrlArray(urlArray) } }
mit
031a2ce3ec8cde109e75fb0ce2571348
33.820513
129
0.627025
5.01107
false
false
false
false
Miridescen/M_365key
365KEY_swift/365KEY_swift/MainController/Class/Produce/view/ProductDetailView/SKProductDetailInfoView.swift
1
15705
// // SKProductDetailInfoView.swift // 365KEY_swift // // Created by 牟松 on 2016/11/21. // Copyright © 2016年 DoNews. All rights reserved. // import UIKit class SKProductDetailInfoView: UIScrollView, UIScrollViewDelegate { var lineIndicatorView: UIScrollView? var model: SKProductDetailModel? { didSet{ // 产品相册 if (model?.produceinfo?.pimglist?.count)! > 0 { pivView = UIView(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 174)) pivView?.backgroundColor = UIColor(red: 231/255.0, green: 235/255.0, blue: 240/255.0, alpha: 1) addSubview(pivView!) contentHeight = 174 let count = (model?.produceinfo?.pimglist?.count)! let picScrollView = UIScrollView(frame: CGRect(x: 0, y: 11, width: SKScreenWidth, height: 135)) picScrollView.delegate = self picScrollView.showsHorizontalScrollIndicator = false picScrollView.showsVerticalScrollIndicator = false var picScrollViewContntSizeW: CGFloat = 16 for i in 0..<count { let pimgModel = model?.produceinfo?.pimglist?[i] as! SKProductDetailPimgModel let widthpxstr = pimgModel.width let heightpxstr = pimgModel.height let index = widthpxstr?.index((widthpxstr?.endIndex)!, offsetBy: -2) let floatWidth = ((widthpxstr?.substring(to: index!))! as NSString).floatValue let floatHeight = ((heightpxstr?.substring(to: index!))! as NSString).floatValue let relWidth = floatWidth*135.0/floatHeight let pimImage = UIImageView(frame: CGRect(x: picScrollViewContntSizeW, y: 0, width: CGFloat(relWidth), height: 135)) pimImage.isUserInteractionEnabled = true pimImage.tag = 1000+i pimImage.contentMode = .scaleAspectFit if pimgModel.showPro_img == nil { pimImage.image = UIImage(named: "pic_touxiang_little") } else { pimImage.sd_setImage(with: URL(string: pimgModel.showPro_img!), placeholderImage: UIImage(named: "pic_touxiang_little")) } let tap = UITapGestureRecognizer(target: self, action: #selector(tapPhotoImage)) tap.numberOfTouchesRequired = 1 pimImage.addGestureRecognizer(tap) picScrollView.addSubview(pimImage) picScrollViewContntSizeW += (16+CGFloat(relWidth)) } picScrollView.contentSize = CGSize(width: picScrollViewContntSizeW, height: 0) pivView?.addSubview(picScrollView) let bgLineView = UIImageView(frame: CGRect(x: 16, y: 157, width: SKScreenWidth-32, height: 6)) bgLineView.image = UIImage(named: "pic_xiangqingbg") pivView?.addSubview(bgLineView) lineIndicatorView = UIScrollView(frame: CGRect(x: 0, y: 0, width: SKScreenWidth-32, height: 6)) lineIndicatorView?.contentSize = CGSize(width: SKScreenWidth-132, height: 0) lineIndicatorView?.contentOffset = CGPoint(x: 0, y: 0) lineIndicatorView?.showsVerticalScrollIndicator = false lineIndicatorView?.showsHorizontalScrollIndicator = false bgLineView.addSubview(lineIndicatorView!) let indicatorImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 6)) indicatorImage.image = UIImage(named: "pic_xiangqing@") lineIndicatorView?.addSubview(indicatorImage) } // 产品简介 productInfo = UIView() productInfo?.backgroundColor = UIColor.white addSubview(productInfo!) productInfo?.addSubview(titleView(withString: "产品简介")) let prdiuctInfoText = UILabel() let labelSize = SKLabelSizeWith(labelText: (model?.produceinfo?.info)!, font: UIFont.systemFont(ofSize: 15), width: SKScreenWidth-32) prdiuctInfoText.frame = CGRect(origin: CGPoint(x: 16, y: 60), size: labelSize) prdiuctInfoText.text = model?.produceinfo?.info prdiuctInfoText.textColor = UIColor(white: 152/255.0, alpha: 1) prdiuctInfoText.numberOfLines = 0 prdiuctInfoText.font = UIFont.systemFont(ofSize: 15) productInfo?.addSubview(prdiuctInfoText) productInfo?.frame = CGRect(x: 0, y: contentHeight, width: SKScreenWidth, height: 80+labelSize.height) contentHeight += (80+labelSize.height) // 产品优势 if (model?.produceinfo?.advantage) != ""{ productSuperiority = UIView() productSuperiority?.backgroundColor = UIColor.white addSubview(productSuperiority!) productSuperiority?.addSubview(linewView()) productSuperiority?.addSubview(titleView(withString: "产品优势")) let prdiuctSuperiorityText = UILabel() let labelSize = SKLabelSizeWith(labelText: (model?.produceinfo?.advantage)!, font: UIFont.systemFont(ofSize: 15), width: SKScreenWidth-32) prdiuctSuperiorityText.frame = CGRect(origin: CGPoint(x: 16, y: 60), size: labelSize) prdiuctSuperiorityText.text = model?.produceinfo?.advantage prdiuctSuperiorityText.textColor = UIColor(white: 152/255.0, alpha: 1) prdiuctSuperiorityText.numberOfLines = 0 prdiuctSuperiorityText.font = UIFont.systemFont(ofSize: 15) productSuperiority?.addSubview(prdiuctSuperiorityText) productSuperiority?.frame = CGRect(x: 0, y: contentHeight, width: SKScreenWidth, height: 80+labelSize.height) contentHeight += (80+labelSize.height) } // 团队介绍 if (model?.team?.count)! > 0 { let count = (model?.team?.count)! teamView = UIView(frame: CGRect(x: 0, y: contentHeight, width: SKScreenWidth, height: CGFloat(count*120)+80)) teamView?.backgroundColor = UIColor.white addSubview(teamView!) teamView?.addSubview(linewView()) teamView?.addSubview(titleView(withString: "团队介绍")) for i in 0..<count { let teamModel = model?.team![i] as! SKProductDetailTeamModel let subTeamView = UIView(frame: CGRect(x: 0, y: CGFloat(60+i*120), width: SKScreenWidth, height: 120)) let headImage = UIImageView(frame: CGRect(x: 32, y: 16, width: 35, height: 35)) headImage.layer.cornerRadius = 17.5 headImage.layer.masksToBounds = true if teamModel.showThumbnail == nil { headImage.image = UIImage(named: "pic_touxiang_little") } else { headImage.sd_setImage(with: URL(string: teamModel.showThumbnail!), placeholderImage: UIImage(named: "pic_touxiang_little")) } subTeamView.addSubview(headImage) let nameLabel = UILabel(frame: CGRect(x: 83, y: 0, width: SKScreenWidth-96, height: 20)) nameLabel.text = teamModel.name nameLabel.textColor = UIColor.black nameLabel.font = UIFont.systemFont(ofSize: 19) subTeamView.addSubview(nameLabel) let jobLabel = UILabel(frame: CGRect(x: 83, y: 35, width: SKScreenWidth-96, height: 17)) jobLabel.text = teamModel.job jobLabel.textColor = UIColor.black jobLabel.font = UIFont.systemFont(ofSize: 16) subTeamView.addSubview(jobLabel) let introduceLabel = UILabel(frame: CGRect(x: 83, y: 62, width: SKScreenWidth-96, height: 40)) introduceLabel.text = teamModel.info introduceLabel.textColor = UIColor(white: 152/255.0, alpha: 1) introduceLabel.font = UIFont.systemFont(ofSize: 15) introduceLabel.numberOfLines = 0 subTeamView.addSubview(introduceLabel) teamView?.addSubview(subTeamView) } contentHeight += (CGFloat(count*120)+80) } // 大事记 if (model?.big_event?.count)! > 0 { let count = (model?.big_event?.count)! bigeventView = UIView(frame: CGRect(x: 0, y: contentHeight, width: SKScreenWidth, height: CGFloat(count*50+60))) bigeventView?.backgroundColor = UIColor.white addSubview(bigeventView!) bigeventView?.addSubview(linewView()) bigeventView?.addSubview(titleView(withString: "大事记")) for i in 0..<count { let bagEventModel = model?.big_event?[i] as! SKProductDetailbig_eventModel let everySubView = UIView(frame: CGRect(x: 0, y: CGFloat(60+i*50), width: SKScreenWidth, height: 50)) let dataLabel = UILabel(frame: CGRect(x: 16, y: 0, width: 70, height: 13)) let dataStr = bagEventModel.time?.description let strIndex = dataStr?.index((dataStr?.startIndex)!, offsetBy: 10) let showStr = dataStr?.substring(to: strIndex!) dataLabel.text = showStr dataLabel.textColor = UIColor(white: 152/255.0, alpha: 1) dataLabel.font = UIFont.systemFont(ofSize: 11) everySubView.addSubview(dataLabel) let bigPointView = UIView(frame: CGRect(x: 90, y: 2, width: 10, height: 10)) bigPointView.layer.cornerRadius = 5 bigPointView.layer.masksToBounds = true bigPointView.backgroundColor = UIColor(white: 152/255.0, alpha: 1) everySubView.addSubview(bigPointView) let smallPointView = UIView(frame: CGRect(x: 3, y: 3, width: 4, height: 4)) smallPointView.layer.cornerRadius = 2 smallPointView.layer.masksToBounds = true smallPointView.backgroundColor = UIColor.white bigPointView.addSubview(smallPointView) let eventLabel = UILabel(frame: CGRect(x: 126, y: 0, width: SKScreenWidth-142, height: 16)) eventLabel.text = bagEventModel.events eventLabel.textColor = UIColor(white: 152/255.0, alpha: 1) eventLabel.font = UIFont.systemFont(ofSize: 15) everySubView.addSubview(eventLabel) let lineView = UIView(frame: CGRect(x: 95, y: 12, width: 1, height: 38)) lineView.backgroundColor = UIColor(white: 245/255.0, alpha: 1) everySubView.addSubview(lineView) bigeventView?.addSubview(everySubView) } contentHeight += (CGFloat(count*50)+60) } contentSize = CGSize(width: 0, height: contentHeight) } } var pivView: UIView? var productInfo: UIView? var productSuperiority: UIView? var teamView: UIView? var bigeventView: UIView? var contentHeight: CGFloat = 0 override init(frame: CGRect) { super.init(frame: frame) showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func linewView() -> UIView { let view = UIView() view.frame = CGRect(x: 16, y: 0, width: SKScreenWidth-32, height: 0.5) view.backgroundColor = UIColor(white: 245/255.0, alpha: 1) return view } func titleView(withString: String) -> UIView { let titleView = UILabel(frame: CGRect(x: 16, y: 20, width: SKScreenWidth-32, height: 20)) titleView.text = withString titleView.textColor = UIColor.black titleView.font = UIFont.systemFont(ofSize: 19) return titleView } @objc private func tapPhotoImage(tap: UITapGestureRecognizer){ let photoAlbum = photoAlbumView(with: model?.produceinfo?.pimglist as! [SKProductDetailPimgModel]) photoAlbum.tag = (tap.view?.tag)!-1000 window?.addSubview(photoAlbum) } // 相册滑动的代理 func scrollViewDidScroll(_ scrollView: UIScrollView) { lineIndicatorView?.setContentOffset(CGPoint(x: -scrollView.contentOffset.x*(SKScreenWidth-132)/(scrollView.contentSize.width-SKScreenWidth), y: 0), animated: false) } } class photoAlbumView: UIScrollView { override var tag: Int{ didSet{ setContentOffset(CGPoint(x: CGFloat(tag)*SKScreenWidth, y: 0), animated: false) } } convenience init(with imageArray: [SKProductDetailPimgModel]){ self.init() frame = CGRect(x: 0, y: 0, width: SKScreenWidth, height: SKScreenHeight) showsVerticalScrollIndicator = false showsHorizontalScrollIndicator = false isPagingEnabled = true bounces = false backgroundColor = UIColor.black contentSize = CGSize(width: SKScreenWidth*CGFloat(imageArray.count), height: 0) for i in 0..<imageArray.count { let pimModel = imageArray[i] as SKProductDetailPimgModel let image = UIImageView() image.frame = CGRect(x: CGFloat(i)*SKScreenWidth, y: 75, width: SKScreenWidth, height: SKScreenHeight-150) image.isUserInteractionEnabled = true image.contentMode = .scaleAspectFit image.clipsToBounds = true if pimModel.showPro_img == nil { image.image = UIImage(named: "pic_touxiang_little") } else { image.sd_setImage(with: URL(string: pimModel.showPro_img!), placeholderImage: UIImage(named: "pic_touxiang_little")) } addSubview(image) } let tap = UITapGestureRecognizer(target: self, action: #selector(touchScrollView)) tap.numberOfTouchesRequired = 1 addGestureRecognizer(tap) } @objc private func touchScrollView(){ removeFromSuperview() } }
apache-2.0
0428617acf65f9ffc630bf470e2e603e
45.201183
172
0.55187
5.392265
false
false
false
false
kosua20/PtahRenderer
PtahRenderer/Mesh.swift
1
3476
// // Model.swift // PtahRenderer // // Created by Simon Rodriguez on 13/02/2016. // Copyright © 2016 Simon Rodriguez. All rights reserved. // import Foundation #if os(macOS) import simd #endif struct Face { let v0: InputVertex let v1: InputVertex let v2: InputVertex } struct FaceIndices { let v: Int let t: Int let n: Int } public final class Mesh { var vertices: [Vertex] = [] var normals: [Normal] = [] var uvs: [UV] = [] var indices: [(FaceIndices, FaceIndices, FaceIndices)] = [] var faces: [Face] = [] public init(path: String, shouldNormalize: Bool = false){ let stringContent = try? String(contentsOfFile: path, encoding: String.Encoding.utf8) guard let lines = stringContent?.components(separatedBy: CharacterSet.newlines) else { print("Couldn't load the mesh") return } for line in lines { if (line.hasPrefix("v ")){//Vertex var components = line.components(separatedBy: CharacterSet.whitespaces).filter({!$0.isEmpty}) vertices.append(Point3(Scalar(components[1])!, Scalar(components[2])!, Scalar(components[3])!)) } else if (line.hasPrefix("vt ")) {//UV coords var components = line.components(separatedBy: CharacterSet.whitespaces).filter({!$0.isEmpty}) uvs.append(Point2(Scalar(components[1])!, Scalar(components[2])!)) } else if (line.hasPrefix("vn ")) {//Normal coords var components = line.components(separatedBy: CharacterSet.whitespaces).filter({!$0.isEmpty}) normals.append(Point3(Scalar(components[1])!, Scalar(components[2])!, Scalar(components[3])!)) } else if (line.hasPrefix("f ")) {//Face with vertices/uv/normals let components = line.components(separatedBy: CharacterSet.whitespaces).filter({!$0.isEmpty}) let splittedComponents = components.map({$0.components(separatedBy: "/")}) let intComps1 = splittedComponents[1].map({ $0 == "" ? 0: Int($0)!}) let fi1 = FaceIndices(v: intComps1[0]-1, t: intComps1[1]-1, n: intComps1[2]-1) let intComps2 = splittedComponents[2].map({ $0 == "" ? 0: Int($0)!}) let fi2 = FaceIndices(v: intComps2[0]-1, t: intComps2[1]-1, n: intComps2[2]-1) let intComps3 = splittedComponents[3].map({ $0 == "" ? 0: Int($0)!}) let fi3 = FaceIndices(v: intComps3[0]-1, t: intComps3[1]-1, n: intComps3[2]-1) indices.append((fi1, fi2, fi3)) } } if shouldNormalize { center() normalize() } // Expand indices. expand() } private func center(){ var bary = vertices.reduce(Point3(0.0, 0.0, 0.0), { $0 + $1 }) bary = (1.0 / Scalar(vertices.count)) * bary vertices = vertices.map({ $0 - bary }) } private func normalize(scale: Scalar = 1.0){ var mini = vertices[0] var maxi = vertices[0] for vert in vertices { mini = min(mini, vert) maxi = max(maxi, vert) } let maxfinal = max(abs(maxi), abs(mini)) //We have the highest distance from the origin, we want it to be smaller than 1 var truemax = max(maxfinal.x, maxfinal.y, maxfinal.z) truemax = truemax == 0 ? 1.0 : truemax/scale vertices = vertices.map({ 1.0/truemax * $0 }) } private func expand(){ for (ind1, ind2, ind3) in indices { let f = Face(v0: InputVertex(v: vertices[ind1.v], t: uvs[ind1.t], n: normals[ind1.n]), v1: InputVertex(v: vertices[ind2.v], t: uvs[ind2.t], n: normals[ind2.n]), v2: InputVertex(v: vertices[ind3.v], t: uvs[ind3.t], n: normals[ind3.n]) ) faces.append(f) } } }
mit
c2594aa196299ec04b83778746bd336b
27.252033
99
0.637986
3.136282
false
false
false
false
Spriter/SwiftyHue
Sources/Base/BridgeResourceModels/Sensors/OpenCloseSensor/OpenCloseSensor.swift
1
1820
// // OpenCloseSensor.swift // Pods // // Created by Jerome Schmitz on 01.05.16. // // import Foundation import Gloss public class OpenCloseSensor: PartialSensor { let config: OpenCloseSensorConfig let state: OpenCloseSensorState required public init?(sensor: Sensor) { guard let sensorConfig = sensor.config else { return nil } guard let sensorState = sensor.state else { return nil } let config: OpenCloseSensorConfig = OpenCloseSensorConfig(sensorConfig: sensorConfig) guard let state: OpenCloseSensorState = OpenCloseSensorState(state: sensorState) else { return nil } self.config = config self.state = state super.init(identifier: sensor.identifier, uniqueId: sensor.uniqueId, name: sensor.name, type: sensor.type, modelId: sensor.modelId, manufacturerName: sensor.manufacturerName, swVersion: sensor.swVersion, recycle: sensor.recycle) } public required init?(json: JSON) { guard let config: OpenCloseSensorConfig = "config" <~~ json else { return nil } guard let state: OpenCloseSensorState = "state" <~~ json else { return nil } self.config = config self.state = state super.init(json: json) } } public func ==(lhs: OpenCloseSensor, rhs: OpenCloseSensor) -> Bool { return lhs.identifier == rhs.identifier && lhs.name == rhs.name && lhs.state == rhs.state && lhs.config == rhs.config && lhs.type == rhs.type && lhs.modelId == rhs.modelId && lhs.manufacturerName == rhs.manufacturerName && lhs.swVersion == rhs.swVersion }
mit
b84f69208d0a0888e5aa28bdee2a1594
27
236
0.594505
4.840426
false
true
false
false
Trxy/TRX
Sources/scheduler/Scheduler.swift
1
1714
import QuartzCore /** Dispatches time events to subscribers */ final class Scheduler: Dispatcher { /// Shared singleton public static let shared = Scheduler() lazy var displayLink: CADisplayLink = { let link = CADisplayLink(target: self, selector: #selector(Scheduler.update(_:))) link.isPaused = true link.add(to: RunLoop.current, forMode: RunLoopMode.commonModes) return link }() private var subscribers = Set<Proxy>() var timeStamp: TimeInterval { return displayLink.timestamp } private func runIfNeeded() { displayLink.isPaused = subscribers.count == 0 } //MARK: subscription func subscribe(_ subscriber: Subscriber) { let subscription = Proxy(subscriber: subscriber) solveOverwrite(with: subscriber) subscribers.insert(subscription) runIfNeeded() } func unsubscribe(_ subscriber: Subscriber) { if let proxy = subscribers.filter({ $0.subscriber === subscriber }).first { subscribers.remove(proxy) } runIfNeeded() } @objc private func update(_ link: CADisplayLink) { subscribers.forEach { proxy in proxy.tick(time: link.timestamp) } } //MARK: overwrite private func solveOverwrite(with subscriber: Subscriber) { if subscriber.keys.count > 0 { pauseAll(subscribers: subscribers(keys: subscriber.keys)) } } private func subscribers(keys: Set<String>) -> [Proxy] { return subscribers.filter { $0.keys.intersection(keys).count > 0 } } private func pauseAll(subscribers: [Proxy]) { subscribers.forEach { ($0.subscriber as? Tweenable)?.paused = true } } }
mit
9330b742f6ddc90c790cadd923d78bce
22.162162
72
0.644107
4.644986
false
false
false
false
piwik/piwik-sdk-ios
MatomoTracker/Session.swift
1
1113
import Foundation struct Session: Codable { /// The number of sessions of the current user. /// api-key: _idvc let sessionsCount: Int /// The timestamp of the previous visit. /// Discussion: Should this be now for the first request? /// api-key: _viewts let lastVisit: Date /// The timestamp of the fist visit. /// Discussion: Should this be now for the first request? /// api-key: _idts let firstVisit: Date } extension Session { static func current(in matomoUserDefaults: MatomoUserDefaults) -> Session { let firstVisit: Date var matomoUserDefaults = matomoUserDefaults if let existingFirstVisit = matomoUserDefaults.firstVisit { firstVisit = existingFirstVisit } else { firstVisit = Date() matomoUserDefaults.firstVisit = firstVisit } let sessionCount = matomoUserDefaults.totalNumberOfVisits let lastVisit = matomoUserDefaults.previousVisit ?? Date() return Session(sessionsCount: sessionCount, lastVisit: lastVisit, firstVisit: firstVisit) } }
mit
a730feea0765d8cb059cfc94b7317ad9
32.727273
97
0.665768
5.013514
false
false
false
false
mhplong/Projects
iOS/ServiceTracker/ServiceTimeTracker/AppDelegate.swift
1
6112
// // AppDelegate.swift // ServiceTimeTracker // // Created by Mark Long on 5/11/16. // Copyright © 2016 Mark Long. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.ml.ServiceTimeTracker" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("ServiceTimeTracker", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
a430820d92dcc10f7bdfe163bf929f57
54.054054
291
0.72034
5.904348
false
false
false
false
neotron/EDPathfinder
tools/swift/Sources/coordinate-mapper/main.swift
1
4455
import Foundation #if os(Linux) import Glibc #else import Darwin #endif import Dispatch public func autoreleasepool(_ code: () -> ()) { code() } struct Body: Decodable { var systemId64: Int64 var subType: String var terraformingState: String? var earthMasses: Float } let queue = OperationQueue() queue.maxConcurrentOperationCount = 32 //let modQueue = Dispatch.queue() var valuableSystems = [Int64:System]() var bodies = 0 var elw = 0 var ww = 0 var tf = 0 var aw = 0 var systems = 0 let lock = NSLock() func parseSystem(_ systemLine: Data) { if let body = try? JSONDecoder().decode(Body.self, from: systemLine) { synced(lock) { let existingSystem = valuableSystems[body.systemId64] if existingSystem != nil { systems += 1 } var isTF = false if let tf = body.terraformingState, tf == "Candidate for terraforming" { isTF = true } var system = existingSystem ?? System() switch (body.subType) { case "Earth-like world": system.elw += 1 elw += 1 system.value += estimatedWorth(type: .elw, mass: body.earthMasses) case "Water world": system.ww += 1 ww += 1 if isTF { system.wwt += 1 } system.value += estimatedWorth(type: .ww, mass: body.earthMasses, tf: isTF) case "Ammonia world": system.aw += 1 aw += 1 system.value += estimatedWorth(type: .aw, mass: body.earthMasses) case "Metal-rich body": if isTF { system.tf += 1 tf += 1 } system.value += estimatedWorth(type: .mr, mass: body.earthMasses, tf: isTF) case "High metal content world": if isTF { system.tf += 1 tf += 1 } system.value += estimatedWorth(type: .hmc, mass: body.earthMasses, tf: isTF) default: if isTF { system.tf += 1 tf += 1 system.value += estimatedWorth(type: .other, mass: body.earthMasses, tf: isTF) } } valuableSystems[body.systemId64] = system bodies += 1 if (bodies % 4997) == 0 { print("\rBodies: \(bodies), ELW: \(elw), WW: \(ww), AW: \(aw), TF: \(tf), T$: \(totalValue / 1000000000) Billion.", terminator: "") fflush(stdout) } } } } let semaphore = DispatchSemaphore(value: 2000) if let aStreamReader = StreamReader(path: "valuable-bodies.jsonl", chunkSize: 1024 * 1024) { defer { aStreamReader.close() } var systemLine = aStreamReader.nextLine(); while systemLine != nil { autoreleasepool { if let local = systemLine { queue.addOperation { autoreleasepool { parseSystem(local) semaphore.signal() } } } semaphore.wait(); systemLine = aStreamReader.nextLine(); } } queue.waitUntilAllOperationsAreFinished() print("\nParsed \(bodies) bodies in \(valuableSystems.count) systems, with an estimated total value of \(totalValue/1000000000) billion credits.") } else { print("Failed to open valuable-bodies.jsonl") exit(1) } FileManager.default.createFile(atPath: "valuable-systems.csv", contents: nil) guard let handle = FileHandle(forUpdatingAtPath: "valuable-systems.csv") else { print("Failed to open output") exit(1) } handle.truncateFile(atOffset: 0) var found: Int32 = 0 var saved: Int = 0 let dir = "../data/tmp" let files = (try? FileManager.default.contentsOfDirectory(atPath: dir))! for file in files { let op = SystemOperation(file: "\(dir)/\(file)", systems: valuableSystems, handle: handle); queue.addOperation(op) } while queue.operationCount > 0 { print("\rResolving system coords: \(queue.operationCount) / \(saved) / \(found) ", terminator: "") fflush(stdout) Thread.sleep(forTimeInterval: 0.1) } queue.waitUntilAllOperationsAreFinished() print("\nCompleted.") handle.closeFile() exit(0)
gpl-3.0
3d85e1d52a63afc2235b34e54759c0fc
31.282609
150
0.54523
4.437251
false
false
false
false
bfortunato/aj-framework
platforms/ios/Libs/socket.io-client-swift/Source/WebSocket.swift
3
39488
////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift // // Created by Dalton Cherry on 7/16/14. // Copyright (c) 2014-2016 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import CoreFoundation import Security public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" public protocol WebSocketDelegate: class { func websocketDidConnect(socket: WebSocket) func websocketDidDisconnect(socket: WebSocket, error: NSError?) func websocketDidReceiveMessage(socket: WebSocket, text: String) func websocketDidReceiveData(socket: WebSocket, data: Data) } public protocol WebSocketPongDelegate: class { func websocketDidReceivePong(socket: WebSocket, data: Data?) } open class WebSocket : NSObject, StreamDelegate { enum OpCode : UInt8 { case continueFrame = 0x0 case textFrame = 0x1 case binaryFrame = 0x2 // 3-7 are reserved. case connectionClose = 0x8 case ping = 0x9 case pong = 0xA // B-F reserved. } public enum CloseCode : UInt16 { case normal = 1000 case goingAway = 1001 case protocolError = 1002 case protocolUnhandledType = 1003 // 1004 reserved. case noStatusReceived = 1005 //1006 reserved. case encoding = 1007 case policyViolated = 1008 case messageTooBig = 1009 } public static let ErrorDomain = "WebSocket" enum InternalErrorCode: UInt16 { // 0-999 WebSocket status codes not used case outputStreamWriteError = 1 } // Where the callback is executed. It defaults to the main UI thread queue. public var callbackQueue = DispatchQueue.main var optionalProtocols: [String]? // MARK: - Constants let headerWSUpgradeName = "Upgrade" let headerWSUpgradeValue = "websocket" let headerWSHostName = "Host" let headerWSConnectionName = "Connection" let headerWSConnectionValue = "Upgrade" let headerWSProtocolName = "Sec-WebSocket-Protocol" let headerWSVersionName = "Sec-WebSocket-Version" let headerWSVersionValue = "13" let headerWSKeyName = "Sec-WebSocket-Key" let headerOriginName = "Origin" let headerWSAcceptName = "Sec-WebSocket-Accept" let BUFFER_MAX = 4096 let FinMask: UInt8 = 0x80 let OpCodeMask: UInt8 = 0x0F let RSVMask: UInt8 = 0x70 let MaskMask: UInt8 = 0x80 let PayloadLenMask: UInt8 = 0x7F let MaxFrameSize: Int = 32 let httpSwitchProtocolCode = 101 let supportedSSLSchemes = ["wss", "https"] class WSResponse { var isFin = false var code: OpCode = .continueFrame var bytesLeft = 0 var frameCount = 0 var buffer: NSMutableData? } // MARK: - Delegates /// Responds to callback about new messages coming in over the WebSocket /// and also connection/disconnect messages. public weak var delegate: WebSocketDelegate? /// Receives a callback for each pong message recived. public weak var pongDelegate: WebSocketPongDelegate? // MARK: - Block based API. public var onConnect: (() -> Void)? public var onDisconnect: ((NSError?) -> Void)? public var onText: ((String) -> Void)? public var onData: ((Data) -> Void)? public var onPong: ((Data?) -> Void)? public var headers = [String: String]() public var voipEnabled = false public var disableSSLCertValidation = false public var security: SSLTrustValidator? public var enabledSSLCipherSuites: [SSLCipherSuite]? public var origin: String? public var timeout = 5 public var isConnected: Bool { return connected } public var currentURL: URL { return url } // MARK: - Private private var url: URL private var inputStream: InputStream? private var outputStream: OutputStream? private var connected = false private var isConnecting = false private var writeQueue = OperationQueue() private var readStack = [WSResponse]() private var inputQueue = [Data]() private var fragBuffer: Data? private var certValidated = false private var didDisconnect = false private var readyToWrite = false private let mutex = NSLock() private let notificationCenter = NotificationCenter.default private var canDispatch: Bool { mutex.lock() let canWork = readyToWrite mutex.unlock() return canWork } /// The shared processing queue used for all WebSocket. private static let sharedWorkQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) /// Used for setting protocols. public init(url: URL, protocols: [String]? = nil) { self.url = url self.origin = url.absoluteString if let hostUrl = URL (string: "/", relativeTo: url) { var origin = hostUrl.absoluteString origin.remove(at: origin.index(before: origin.endIndex)) self.origin = origin } writeQueue.maxConcurrentOperationCount = 1 optionalProtocols = protocols } // Used for specifically setting the QOS for the write queue. public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) { self.init(url: url, protocols: protocols) writeQueue.qualityOfService = writeQueueQOS } /** Connect to the WebSocket server on a background thread. */ open func connect() { guard !isConnecting else { return } didDisconnect = false isConnecting = true createHTTPRequest() } /** Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - Parameter forceTimeout: Maximum time to wait for the server to close the socket. - Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket. */ open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) { guard isConnected else { return } switch forceTimeout { case .some(let seconds) where seconds > 0: let milliseconds = Int(seconds * 1_000) callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in self?.disconnectStream(nil) } fallthrough case .none: writeError(closeCode) default: disconnectStream(nil) break } } /** Write a string to the websocket. This sends it as a text frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter string: The string to write. - parameter completion: The (optional) completion handler. */ open func write(string: String, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion) } /** Write binary data to the websocket. This sends it as a binary frame. If you supply a non-nil completion block, I will perform it when the write completes. - parameter data: The data to write. - parameter completion: The (optional) completion handler. */ open func write(data: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(data, code: .binaryFrame, writeCompletion: completion) } /** Write a ping to the websocket. This sends it as a control frame. Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s */ open func write(ping: Data, completion: (() -> ())? = nil) { guard isConnected else { return } dequeueWrite(ping, code: .ping, writeCompletion: completion) } /** Private method that starts the connection. */ private func createHTTPRequest() { let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString, url as CFURL, kCFHTTPVersion1_1).takeRetainedValue() var port = url.port if port == nil { if supportedSSLSchemes.contains(url.scheme!) { port = 443 } else { port = 80 } } addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue) addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue) if let protocols = optionalProtocols { addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joined(separator: ",")) } addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue) addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey()) if let origin = origin { addHeader(urlRequest, key: headerOriginName, val: origin) } addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)") for (key, value) in headers { addHeader(urlRequest, key: key, val: value) } if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) { let serializedRequest = cfHTTPMessage.takeRetainedValue() initStreamsWithData(serializedRequest as Data, Int(port!)) } } /** Add a header to the CFHTTPMessage by using the NSString bridges to CFString */ private func addHeader(_ urlRequest: CFHTTPMessage, key: String, val: String) { CFHTTPMessageSetHeaderFieldValue(urlRequest, key as CFString, val as CFString) } /** Generate a WebSocket key as needed in RFC. */ private func generateWebSocketKey() -> String { var key = "" let seed = 16 for _ in 0..<seed { let uni = UnicodeScalar(UInt32(97 + arc4random_uniform(25))) key += "\(Character(uni!))" } let data = key.data(using: String.Encoding.utf8) let baseKey = data?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return baseKey! } /** Start the stream connection and write the data to the output stream. */ private func initStreamsWithData(_ data: Data, _ port: Int) { //higher level API we will cut over to at some point //NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream) // Disconnect and clean up any existing streams before setting up a new pair disconnectStream(nil, runDelegate: false) var readStream: Unmanaged<CFReadStream>? var writeStream: Unmanaged<CFWriteStream>? let h = url.host! as NSString CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) inputStream = readStream!.takeRetainedValue() outputStream = writeStream!.takeRetainedValue() guard let inStream = inputStream, let outStream = outputStream else { return } inStream.delegate = self outStream.delegate = self if supportedSSLSchemes.contains(url.scheme!) { certValidated = false inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) if disableSSLCertValidation { let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull] inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) } if let cipherSuites = self.enabledSSLCipherSuites { if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) if resIn != errSecSuccess { let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn)) disconnectStream(error) return } if resOut != errSecSuccess { let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut)) disconnectStream(error) return } } } } else { certValidated = true //not a https session, so no need to check SSL pinning } if voipEnabled { inStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType) outStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType) } CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue) CFWriteStreamSetDispatchQueue(outStream, WebSocket.sharedWorkQueue) inStream.open() outStream.open() self.mutex.lock() self.readyToWrite = true self.mutex.unlock() let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) var out = timeout * 1_000_000 // wait 5 seconds before giving up let operation = BlockOperation() operation.addExecutionBlock { [weak self, weak operation] in guard let sOperation = operation else { return } while !outStream.hasSpaceAvailable && !sOperation.isCancelled { usleep(100) // wait until the socket is ready guard !sOperation.isCancelled else { return } out -= 100 if out < 0 { WebSocket.sharedWorkQueue.async { self?.cleanupStream() } self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2)) return } else if outStream.streamError != nil { return // disconnectStream will be called. } } guard !sOperation.isCancelled, let s = self else { return } // Do the pinning now if needed if let sec = s.security, !s.certValidated { let trust = outStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust let domain = outStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String s.certValidated = sec.isValid(trust, domain: domain) if !s.certValidated { WebSocket.sharedWorkQueue.async { let error = s.errorWithDetail("Invalid SSL certificate", code: 1) s.disconnectStream(error) } return } } outStream.write(bytes, maxLength: data.count) } writeQueue.addOperation(operation) } /** Delegate for the stream methods. Processes incoming bytes */ open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { if eventCode == .hasBytesAvailable { if aStream == inputStream { processInputStream() } } else if eventCode == .errorOccurred { disconnectStream(aStream.streamError as NSError?) } else if eventCode == .endEncountered { disconnectStream(nil) } } /** Disconnect the stream object and notifies the delegate. */ private func disconnectStream(_ error: NSError?, runDelegate: Bool = true) { if error == nil { writeQueue.waitUntilAllOperationsAreFinished() } else { writeQueue.cancelAllOperations() } cleanupStream() connected = false if runDelegate { doDisconnect(error) } } /** cleanup the streams. */ private func cleanupStream() { outputStream?.delegate = nil inputStream?.delegate = nil if let stream = inputStream { CFReadStreamSetDispatchQueue(stream, nil) stream.close() } if let stream = outputStream { CFWriteStreamSetDispatchQueue(stream, nil) stream.close() } outputStream = nil inputStream = nil fragBuffer = nil } /** Handles the incoming bytes and sending them to the proper processing method. */ private func processInputStream() { let buf = NSMutableData(capacity: BUFFER_MAX) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) let length = inputStream!.read(buffer, maxLength: BUFFER_MAX) guard length > 0 else { return } var process = false if inputQueue.count == 0 { process = true } inputQueue.append(Data(bytes: buffer, count: length)) if process { dequeueInput() } } /** Dequeue the incoming input so it is processed in order. */ private func dequeueInput() { while !inputQueue.isEmpty { autoreleasepool { let data = inputQueue[0] var work = data if let buffer = fragBuffer { var combine = NSData(data: buffer) as Data combine.append(data) work = combine fragBuffer = nil } let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self) let length = work.count if !connected { processTCPHandshake(buffer, bufferLen: length) } else { processRawMessagesInBuffer(buffer, bufferLen: length) } inputQueue = inputQueue.filter{ $0 != data } } } } /** Handle checking the inital connection status */ private func processTCPHandshake(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: break case -1: fragBuffer = Data(bytes: buffer, count: bufferLen) break // do nothing, we are going to collect more data default: doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code))) } } /** Finds the HTTP Packet in the TCP stream, by looking for the CRLF. */ private func processHTTP(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] var k = 0 var totalSize = 0 for i in 0..<bufferLen { if buffer[i] == CRLFBytes[k] { k += 1 if k == 3 { totalSize = i + 1 break } } else { k = 0 } } if totalSize > 0 { let code = validateResponse(buffer, bufferLen: totalSize) if code != 0 { return code } isConnecting = false connected = true didDisconnect = false if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onConnect?() s.delegate?.websocketDidConnect(socket: s) s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self) } } totalSize += 1 //skip the last \n let restSize = bufferLen - totalSize if restSize > 0 { processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) } return 0 //success } return -1 // Was unable to find the full TCP header. } /** Validates the HTTP is a 101 as per the RFC spec. */ private func validateResponse(_ buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int { let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() CFHTTPMessageAppendBytes(response, buffer, bufferLen) let code = CFHTTPMessageGetResponseStatusCode(response) if code != httpSwitchProtocolCode { return code } if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { let headers = cfHeaders.takeRetainedValue() as NSDictionary if let acceptKey = headers[headerWSAcceptName as NSString] as? NSString { if acceptKey.length > 0 { return 0 } } } return -1 } /** Read a 16 bit big endian value from a buffer */ private static func readUint16(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 { return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) } /** Read a 64 bit big endian value from a buffer */ private static func readUint64(_ buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 { var value = UInt64(0) for i in 0...7 { value = (value << 8) | UInt64(buffer[offset + i]) } return value } /** Write a 16-bit big endian value to a buffer. */ private static func writeUint16(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) { buffer[offset + 0] = UInt8(value >> 8) buffer[offset + 1] = UInt8(value & 0xff) } /** Write a 64-bit big endian value to a buffer. */ private static func writeUint64(_ buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) { for i in 0...7 { buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) } } /** Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process. */ private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer<UInt8>) -> UnsafeBufferPointer<UInt8> { let response = readStack.last guard let baseAddress = buffer.baseAddress else {return emptyBuffer} let bufferLen = buffer.count if response != nil && bufferLen < 2 { fragBuffer = Data(buffer: buffer) return emptyBuffer } if let response = response, response.bytesLeft > 0 { var len = response.bytesLeft var extra = bufferLen - response.bytesLeft if response.bytesLeft > bufferLen { len = bufferLen extra = 0 } response.bytesLeft -= len response.buffer?.append(Data(bytes: baseAddress, count: len)) _ = processResponse(response) return buffer.fromOffset(bufferLen - extra) } else { let isFin = (FinMask & baseAddress[0]) let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0]) let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue) let isMasked = (MaskMask & baseAddress[1]) let payloadLen = (PayloadLenMask & baseAddress[1]) var offset = 2 if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode)) writeError(errCode) return emptyBuffer } let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping) if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame && receivedOpcode != .textFrame && receivedOpcode != .pong) { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcodeRawValue)", code: errCode)) writeError(errCode) return emptyBuffer } if isControlFrame && isFin == 0 { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode)) writeError(errCode) return emptyBuffer } var closeCode = CloseCode.normal.rawValue if receivedOpcode == .connectionClose { if payloadLen == 1 { closeCode = CloseCode.protocolError.rawValue } else if payloadLen > 1 { closeCode = WebSocket.readUint16(baseAddress, offset: offset) if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1011 && closeCode < 3000) { closeCode = CloseCode.protocolError.rawValue } } if payloadLen < 2 { doDisconnect(errorWithDetail("connection closed by server", code: closeCode)) writeError(closeCode) return emptyBuffer } } else if isControlFrame && payloadLen > 125 { writeError(CloseCode.protocolError.rawValue) return emptyBuffer } var dataLength = UInt64(payloadLen) if dataLength == 127 { dataLength = WebSocket.readUint64(baseAddress, offset: offset) offset += MemoryLayout<UInt64>.size } else if dataLength == 126 { dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) offset += MemoryLayout<UInt16>.size } if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { fragBuffer = Data(bytes: baseAddress, count: bufferLen) return emptyBuffer } var len = dataLength if dataLength > UInt64(bufferLen) { len = UInt64(bufferLen-offset) } if receivedOpcode == .connectionClose && len > 0 { let size = MemoryLayout<UInt16>.size offset += size len -= UInt64(size) } let data = Data(bytes: baseAddress+offset, count: Int(len)) if receivedOpcode == .connectionClose { var closeReason = "connection closed by server" if let customCloseReason = String(data: data, encoding: .utf8) { closeReason = customCloseReason } else { closeCode = CloseCode.protocolError.rawValue } doDisconnect(errorWithDetail(closeReason, code: closeCode)) writeError(closeCode) return emptyBuffer } if receivedOpcode == .pong { if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } let pongData: Data? = data.count > 0 ? data : nil s.onPong?(pongData) s.pongDelegate?.websocketDidReceivePong(socket: s, data: pongData) } } return buffer.fromOffset(offset + Int(len)) } var response = readStack.last if isControlFrame { response = nil // Don't append pings. } if isFin == 0 && receivedOpcode == .continueFrame && response == nil { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode)) writeError(errCode) return emptyBuffer } var isNew = false if response == nil { if receivedOpcode == .continueFrame { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("first frame can't be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } isNew = true response = WSResponse() response!.code = receivedOpcode! response!.bytesLeft = Int(dataLength) response!.buffer = NSMutableData(data: data) } else { if receivedOpcode == .continueFrame { response!.bytesLeft = Int(dataLength) } else { let errCode = CloseCode.protocolError.rawValue doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame", code: errCode)) writeError(errCode) return emptyBuffer } response!.buffer!.append(data) } if let response = response { response.bytesLeft -= Int(len) response.frameCount += 1 response.isFin = isFin > 0 ? true : false if isNew { readStack.append(response) } _ = processResponse(response) } let step = Int(offset + numericCast(len)) return buffer.fromOffset(step) } } /** Process all messages in the buffer if possible. */ private func processRawMessagesInBuffer(_ pointer: UnsafePointer<UInt8>, bufferLen: Int) { var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) repeat { buffer = processOneRawMessage(inBuffer: buffer) } while buffer.count >= 2 if buffer.count > 0 { fragBuffer = Data(buffer: buffer) } } /** Process the finished response of a buffer. */ private func processResponse(_ response: WSResponse) -> Bool { if response.isFin && response.bytesLeft <= 0 { if response.code == .ping { let data = response.buffer! // local copy so it is perverse for writing dequeueWrite(data as Data, code: .pong) } else if response.code == .textFrame { let str: NSString? = NSString(data: response.buffer! as Data, encoding: String.Encoding.utf8.rawValue) if str == nil { writeError(CloseCode.encoding.rawValue) return false } if canDispatch { callbackQueue.async { [weak self] in guard let s = self else { return } s.onText?(str! as String) s.delegate?.websocketDidReceiveMessage(socket: s, text: str! as String) } } } else if response.code == .binaryFrame { if canDispatch { let data = response.buffer! // local copy so it is perverse for writing callbackQueue.async { [weak self] in guard let s = self else { return } s.onData?(data as Data) s.delegate?.websocketDidReceiveData(socket: s, data: data as Data) } } } readStack.removeLast() return true } return false } /** Create an error */ private func errorWithDetail(_ detail: String, code: UInt16) -> NSError { var details = [String: String]() details[NSLocalizedDescriptionKey] = detail return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details) } /** Write an error to the socket */ private func writeError(_ code: UInt16) { let buf = NSMutableData(capacity: MemoryLayout<UInt16>.size) let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) WebSocket.writeUint16(buffer, offset: 0, value: code) dequeueWrite(Data(bytes: buffer, count: MemoryLayout<UInt16>.size), code: .connectionClose) } /** Used to write things to the stream */ private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { let operation = BlockOperation() operation.addExecutionBlock { [weak self, weak operation] in //stream isn't ready, let's wait guard let s = self else { return } guard let sOperation = operation else { return } var offset = 2 let dataLength = data.count let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize) let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self) buffer[0] = s.FinMask | code.rawValue if dataLength < 126 { buffer[1] = CUnsignedChar(dataLength) } else if dataLength <= Int(UInt16.max) { buffer[1] = 126 WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) offset += MemoryLayout<UInt16>.size } else { buffer[1] = 127 WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) offset += MemoryLayout<UInt64>.size } buffer[1] |= s.MaskMask let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset) _ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout<UInt32>.size), maskKey) offset += MemoryLayout<UInt32>.size for i in 0..<dataLength { buffer[offset] = data[i] ^ maskKey[i % MemoryLayout<UInt32>.size] offset += 1 } var total = 0 while !sOperation.isCancelled { guard let outStream = s.outputStream else { break } let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self) let len = outStream.write(writeBuffer, maxLength: offset-total) if len < 0 { var error: Error? if let streamError = outStream.streamError { error = streamError } else { let errCode = InternalErrorCode.outputStreamWriteError.rawValue error = s.errorWithDetail("output stream error during write", code: errCode) } s.doDisconnect(error as NSError?) break } else { total += len } if total >= offset { if let queue = self?.callbackQueue, let callback = writeCompletion { queue.async { callback() } } break } } } writeQueue.addOperation(operation) } /** Used to preform the disconnect delegate */ private func doDisconnect(_ error: NSError?) { guard !didDisconnect else { return } didDisconnect = true isConnecting = false connected = false guard canDispatch else {return} callbackQueue.async { [weak self] in guard let s = self else { return } s.onDisconnect?(error) s.delegate?.websocketDidDisconnect(socket: s, error: error) let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] } s.notificationCenter.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo) } } // MARK: - Deinit deinit { mutex.lock() readyToWrite = false mutex.unlock() cleanupStream() writeQueue.cancelAllOperations() } } private extension Data { init(buffer: UnsafeBufferPointer<UInt8>) { self.init(bytes: buffer.baseAddress!, count: buffer.count) } } private extension UnsafeBufferPointer { func fromOffset(_ offset: Int) -> UnsafeBufferPointer<Element> { return UnsafeBufferPointer<Element>(start: baseAddress?.advanced(by: offset), count: count - offset) } } private let emptyBuffer = UnsafeBufferPointer<UInt8>(start: nil, count: 0)
apache-2.0
9ad9253aeea651b695fdcb3722d5414e
40.348691
226
0.577593
5.490545
false
false
false
false
questbeat/SlideMenu
SlideMenuDemo/UIViewController+SlideMenu.swift
1
908
// // UIViewController+SlideMenu.swift // SlideMenuDemo // // Created by Katsuma Tanaka on 2015/10/05. // Copyright © 2015 Katsuma Tanaka. All rights reserved. // import UIKit import SlideMenu public extension UIViewController { var slideMenuController: SlideMenuController? { // Find from parent view controller var viewController = self.parentViewController while parentViewController != nil { if let slideMenuController = viewController as? SlideMenuController { return slideMenuController } viewController = viewController?.parentViewController } // Find from presenting view controller if let slideMenuController = presentingViewController as? SlideMenuController { return slideMenuController } return nil } }
mit
69be10893df557ba1dba11b10f2759c3
25.676471
87
0.639471
6.432624
false
false
false
false
ProcedureKit/ProcedureKit
Sources/ProcedureKit/TimeoutObserver.swift
2
5513
// // ProcedureKit // // Copyright © 2015-2018 ProcedureKit. All rights reserved. // import Foundation import Dispatch /** An observer which will automatically cancel (with an error) the `Procedure` to which it is attached if the `Procedure` doesn't finish executing before a time interval is expired. The timer starts right before the Procedure's `execute()` function is called (after the Procedure has been started). - IMPORTANT: This will cancel a `Procedure`. It is the responsibility of the `Procedure` subclass to handle cancellation as appropriate for it to rapidly finish after it is cancelled. - See: the documentation for `Procedure.cancel()` */ public struct TimeoutObserver: ProcedureObserver { private let delay: Delay /** Initialize the `TimeoutObserver` with a time interval. - parameter by: a `TimeInterval`. */ public init(by interval: TimeInterval) { delay = .by(interval) } /** Initialize the `TimeoutObserver` with a date. - parameter until: a `Date`. */ public init(until date: Date) { delay = .until(date) } public func will(execute procedure: Procedure, pendingExecute: PendingExecuteEvent) { switch delay.interval { case (let interval) where interval > 0.0: ProcedureTimeoutRegistrar.shared.createFinishTimeout(forProcedure: procedure, withDelay: delay) break default: break } } public func did(finish procedure: Procedure, with error: Error?) { ProcedureTimeoutRegistrar.shared.registerFinished(procedure: procedure) } } // A shared registrar of Procedure -> timeout timers. // Used to cancel all outstanding timers for a Procedure if: // - that Procedure finishes // - one of the Procedure's timers fires internal class ProcedureTimeoutRegistrar { static let shared = ProcedureTimeoutRegistrar() private let queue = DispatchQueue(label: "run.kit.procedure.ProcedureKit.ProcedureTimeouts", attributes: [.concurrent]) private let protectedFinishTimers = Protector<[Procedure : [DispatchTimerWrapper]]>([:]) func createFinishTimeout(forProcedure procedure: Procedure, withDelay delay: Delay) { let timer = DispatchTimerWrapper(queue: queue) timer.setEventHandler { [delay, weak procedure, weak registrar = self] in guard let strongProcedure = procedure else { return } guard !strongProcedure.isFinished && !strongProcedure.isCancelled else { return } strongProcedure.cancel(with: ProcedureKitError.timedOut(with: delay)) registrar?.registerTimeoutProcessed(forProcedure: strongProcedure) } protectedFinishTimers.write { guard var procedureTimers = $0[procedure] else { $0.updateValue([timer], forKey: procedure) return } procedureTimers.append(timer) $0[procedure] = procedureTimers } timer.scheduleOneshot(deadline: .now() + delay.interval) timer.resume() } // Called when a Procedure will/did Finish. // Only the first call is processed, and removes all pending timers/timeouts for that Procedure. func registerFinished(procedure: Procedure) { registerTimeoutProcessed(forProcedure: procedure) } // Removes all DispatchTimers associated with a Procedure's registered timeouts. // Is called when a Procedure finishes and when a timeout fires. private func registerTimeoutProcessed(forProcedure procedure: Procedure) { guard let dispatchTimers = protectedFinishTimers.write({ return $0.removeValue(forKey: procedure) }) else { return } for timer in dispatchTimers { timer.cancel() } } } // A wrapper for a DispatchSourceTimer that ensures that the timer is cancelled // and not suspended prior to deinitialization. fileprivate class DispatchTimerWrapper { fileprivate typealias EventHandler = @convention(block) () -> Swift.Void private let timer: DispatchSourceTimer private let lock = NSLock() private var didResume = false init(queue: DispatchQueue) { timer = DispatchSource.makeTimerSource(flags: [], queue: queue) } deinit { // ensure that the timer is cancelled and resumed before deiniting // (trying to deconstruct a suspended DispatchSource will fail) timer.cancel() lock.withCriticalScope { guard !didResume else { return } timer.resume() } } // MARK: - DispatchSourceTimer methods func setEventHandler(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], handler: @escaping EventHandler) { timer.setEventHandler(qos: qos, flags: flags, handler: handler) } func setEventHandler(handler: DispatchWorkItem) { timer.setEventHandler(handler: handler) } func scheduleOneshot(deadline: DispatchTime, leeway: DispatchTimeInterval = .nanoseconds(0)) { #if swift(>=4.0) timer.schedule(deadline: deadline, leeway: leeway) #else timer.scheduleOneshot(deadline: deadline, leeway: leeway) #endif } func resume() { lock.withCriticalScope { guard !didResume else { fatalError("Do not call resume() twice.") } timer.resume() didResume = true } } func cancel() { timer.cancel() } }
mit
f82374267b2a14dfde64e98dc89e5c92
33.666667
127
0.668541
4.912656
false
false
false
false
kevinzhow/PNChart-Swift
PNChartSwift/Source/PNBarChart.swift
1
9916
// // PNBarChart.swift // PNChartSwift // // Created by YiChen Zhou on 12/29/16. // Copyright © 2016 YiChen Zhou. All rights reserved. // import UIKit class PNBarChart: UIView { var bars = NSMutableArray() var xLabelWidth: CGFloat! var yValueMax: CGFloat! var strokeColor = PNGreen var strokeColors: Array<Any>! var xLabelHeight: CGFloat = 11 var yLabelHeight: CGFloat = 20 var labels: NSMutableArray = [] var xLabels = [String]() { didSet { if self.showLabel { self.xLabelWidth = (self.frame.size.width - self.chartMargin * 2.0 - yChartLabelWidth) / CGFloat(self.xLabels.count) } } } var yLabels = [String]() var yValues = [CGFloat]() { didSet { if self.yMaxValue != nil { self.yValueMax = self.yMaxValue } else { self.getYValueMax(yLabels: self.yValues) } self.xLabelWidth = (self.frame.size.width - self.chartMargin * 2 - yChartLabelWidth) / CGFloat(self.yValues.count) } } var yChartLabelWidth: CGFloat = 18 var chartMargin: CGFloat = 15 var showLabel = true var showChartBorder = false var chartBottomLine = CAShapeLayer() var chartLeftLine = CAShapeLayer() var barRadius: CGFloat = 0 var barWidth: CGFloat! var labelMarginTop: CGFloat = 0 var barBackgroundColor = PNLightGrey var labelTextColor = UIColor.darkGray var labelTextFont = UIFont(name: "Avenir-Medium", size: 11.0) var xLabelSkip = 1 var yLabelSum = 4 // Max value of the chart var yMaxValue: CGFloat! // Min value of the chart var yMinValue: CGFloat! var animationType: AnimationType = .Default // Initialize Methods override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = PNLightGrey self.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func strokeChart() { self.viewCleanUpForCollection(arr: self.labels) if self.showLabel { // Add X Labels var labelAddCount = 0 for index in 0..<self.xLabels.count { labelAddCount = labelAddCount + 1 if labelAddCount == self.xLabelSkip { let labeltext = self.xLabels[index] let label = PNChartLabel(frame: CGRect.zero) label.font = self.labelTextFont label.textColor = self.labelTextColor label.textAlignment = .center label.text = labeltext label.sizeToFit() let labelXPosition = (CGFloat(index) * self.xLabelWidth + yChartLabelWidth + self.chartMargin + self.xLabelWidth / 2) label.center = CGPoint(x: labelXPosition, y: self.frame.size.height - self.xLabelHeight - self.chartMargin + label.frame.size.height / 2.0 + self.labelMarginTop) labelAddCount = 0 self.labels.add(label) self.addSubview(label) } } // Add Y Labels let yLabelSectionHeight = (self.frame.size.height - self.chartMargin * 2 - self.xLabelHeight) / CGFloat(self.yLabelSum) for index in 0..<self.yLabelSum { let labelText = String(describing: Int(self.yValueMax * (CGFloat(self.yLabelSum - index) / CGFloat(self.yLabelSum)))) let label = PNChartLabel(frame: CGRect(x: self.chartMargin / 2, y: yLabelSectionHeight * CGFloat(index) + self.chartMargin - self.yLabelHeight / 2.0, width: self.yChartLabelWidth, height: self.yLabelHeight)) label.font = self.labelTextFont label.textColor = self.labelTextColor label.textAlignment = .right label.text = labelText self.labels.add(label) self.addSubview(label) } } self.viewCleanUpForCollection(arr: self.bars) // Add bars let chartCarvanHeight = self.frame.size.height - self.chartMargin * 2 - self.xLabelHeight var index = 0 for value in self.yValues { let grade = value / self.yValueMax var barXPosition: CGFloat! if self.barWidth != nil && self.barWidth > 0 { barXPosition = CGFloat(index) * self.xLabelWidth + self.yChartLabelWidth + self.chartMargin + (self.xLabelWidth / 2) - (self.barWidth / 2) } else { barXPosition = CGFloat(index) * self.xLabelWidth + self.yChartLabelWidth + self.chartMargin + self.xLabelWidth * 0.25 if self.showLabel { self.barWidth = self.xLabelWidth * 0.5 } else { self.barWidth = self.xLabelWidth * 0.6 } } let bar = PNBar(frame: CGRect(x: barXPosition, y: self.frame.size.height - chartCarvanHeight - self.xLabelHeight - self.chartMargin, width: self.barWidth, height: chartCarvanHeight)) bar.barRadius = self.barRadius bar.backgroundColor = self.barBackgroundColor if self.strokeColor != UIColor.black { bar.barColor = self.strokeColor } else { bar.barColor = self.barColorAtIndex(index: index) } if self.animationType == .Waterfall { bar.startAnimationTime = Double(index) * 0.1 } // Height of Bar bar.grade = grade // For Click Index bar.tag = index self.bars.add(bar) self.addSubview(bar) index += 1 } // Add Chart Border Lines if self.showChartBorder { self.chartBottomLine = CAShapeLayer() self.chartBottomLine.lineCap = kCALineCapButt self.chartBottomLine.fillColor = UIColor.white.cgColor self.chartBottomLine.lineWidth = 1 self.chartBottomLine.strokeEnd = 0 let progressLine = UIBezierPath() progressLine.move(to: CGPoint(x: self.chartMargin, y: self.frame.size.height - self.xLabelHeight - self.chartMargin)) progressLine.addLine(to: CGPoint(x: self.frame.size.width - self.chartMargin, y: self.frame.size.height - self.xLabelHeight - self.chartMargin)) progressLine.lineWidth = 1 progressLine.lineCapStyle = .square self.chartBottomLine.path = progressLine.cgPath let path = CABasicAnimation(keyPath: "strokeEnd") path.duration = 0.5 path.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) path.fromValue = 0 path.toValue = 1 self.chartBottomLine.add(path, forKey: "strokeEndAnimation") self.chartBottomLine.strokeEnd = 1 self.layer.addSublayer(self.chartBottomLine) // Add Left Chart Line self.chartLeftLine = CAShapeLayer() self.chartLeftLine.lineCap = kCALineCapButt self.chartLeftLine.fillColor = UIColor.white.cgColor self.chartLeftLine.lineWidth = 1 self.chartLeftLine.strokeEnd = 0 let progressLeftLine = UIBezierPath() progressLeftLine.move(to: CGPoint(x: self.chartMargin + self.yChartLabelWidth, y: self.frame.size.height - self.xLabelHeight - self.chartMargin)) progressLeftLine.addLine(to: CGPoint(x: self.chartMargin + self.yChartLabelWidth, y: self.chartMargin)) progressLeftLine.lineWidth = 1 progressLeftLine.lineCapStyle = .square self.chartLeftLine.path = progressLeftLine.cgPath self.chartLeftLine.strokeColor = PNLightGrey.cgColor let pathLeft = CABasicAnimation(keyPath: "strokeEnd") pathLeft.duration = 0.5 pathLeft.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) pathLeft.fromValue = 0 pathLeft.toValue = 1 self.chartLeftLine.add(pathLeft, forKey: "strokeEndAnimation") self.chartLeftLine.strokeEnd = 1 self.layer.addSublayer(self.chartLeftLine) } } } extension PNBarChart { enum AnimationType { case Default case Waterfall } func getYValueMax(yLabels: [CGFloat]) { let max = yLabels.max() if max == 0 { self.yValueMax = self.yMinValue } else { self.yValueMax = max } } func viewCleanUpForCollection(arr: NSMutableArray) { if arr.count > 0 { for object in arr { let view = object as! UIView view.removeFromSuperview() } arr.removeAllObjects() } } func barColorAtIndex(index: Int) -> UIColor { if self.strokeColors.count == self.yValues.count { return self.strokeColors[index] as! UIColor } else { return self.strokeColor } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.touchPoint(touches, with: event) super.touchesBegan(touches, with: event) } func touchPoint(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first let touchPoint = touch?.location(in: self) let subview = hitTest(touchPoint!, with: nil) if let barView = subview as? PNBar { self.userClickedOnBarChartIndex(barIndex: barView.tag) } } func userClickedOnBarChartIndex(barIndex: Int) { print("Click on bar \(barIndex)") } }
mit
5e43312f708fcdf31a0dad4862066865
39.304878
223
0.590419
4.923039
false
false
false
false
JonathanRitchey03/JRMutableArray
JRMutableArray/Source/JRMutableArray.swift
1
4159
import Foundation import UIKit open class JRMutableArray : NSObject { fileprivate var storage : NSMutableArray fileprivate var commandHistory : NSMutableArray fileprivate var queue : DispatchQueue fileprivate var drawKit : JRDrawKit fileprivate var markedRange : NSRange? public override init() { storage = NSMutableArray() commandHistory = NSMutableArray() queue = DispatchQueue(label: "JRMutableArray Queue", attributes: DispatchQueue.Attributes.concurrent) drawKit = JRDrawKit() } open func count() -> Int { var numItems = 0 queue.sync(execute: { [weak self] in if self != nil { numItems = (self?.storage.count)! } }) return numItems } open func swap(_ objectAtIndex: Int, withObjectAtIndex: Int) { let temp = self[objectAtIndex] self[objectAtIndex] = self[withObjectAtIndex] self[withObjectAtIndex] = temp } open subscript(index: Int) -> Any? { get { var value : Any? = nil queue.sync(execute: { [weak self] in value = self?.storage.object(at: index) as Any? }) return value } set(newValue) { queue.sync(flags: .barrier, execute: { [weak self] in if let strongSelf = self { if newValue != nil { if index < strongSelf.storage.count { strongSelf.storage.replaceObject(at: index, with: newValue!) } else { if ( index > strongSelf.storage.count ) { // fill array up with NSNull.null until index let topIndex = strongSelf.storage.count for i in topIndex..<index { strongSelf.storage.insert(NSNull(), at: i) } } strongSelf.storage.insert(newValue!, at: index) } let commandArray = NSMutableArray() commandArray.add(index) commandArray.add(newValue!) if strongSelf.markedRange != nil { commandArray.add(NSMakeRange(strongSelf.markedRange!.location, strongSelf.markedRange!.length)) } else { commandArray.add(NSNull()) } self?.commandHistory.add(commandArray) } } }) } } open func markRange(_ range:NSRange) { self.markedRange = NSMakeRange(range.location, range.length) } open func markIndex(_ index:Int?) { //drawKit.markedIndex = index } open func writeToTmp() { let tempArray = NSMutableArray() for i in 0..<commandHistory.count { let commandArray = commandHistory.object(at: i) as! NSMutableArray let index = commandArray[0] as! Int let object = commandArray[1] let markedRange = commandArray[2] if index < tempArray.count { tempArray.replaceObject(at: index, with: object) } else { tempArray.insert(object, at: index) } let image = drawKit.renderArray(tempArray,maxCount:Int(storage.count),markedRange:markedRange) let fileManager = FileManager.default let myImageData = UIImagePNGRepresentation(image) let path = "/tmp/myarray\(i).png" fileManager.createFile(atPath: path, contents: myImageData, attributes: nil) } } open func debugQuickLookObject() -> AnyObject? { var markedRange : AnyObject = NSNull() if let aMarkedRange = self.markedRange { markedRange = aMarkedRange as AnyObject } return drawKit.renderArray(storage, maxCount:Int(storage.count), markedRange:markedRange) } }
mit
7b60d21f3798decb4058c07443f1b6b0
37.155963
123
0.528252
5.436601
false
false
false
false
austinzheng/swift
stdlib/public/core/ErrorType.swift
8
8082
//===----------------------------------------------------------------------===// // // 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 /// A type representing an error value that can be thrown. /// /// Any type that declares conformance to the `Error` protocol can be used to /// represent an error in Swift's error handling system. Because the `Error` /// protocol has no requirements of its own, you can declare conformance on /// any custom type you create. /// /// Using Enumerations as Errors /// ============================ /// /// Swift's enumerations are well suited to represent simple errors. Create an /// enumeration that conforms to the `Error` protocol with a case for each /// possible error. If there are additional details about the error that could /// be helpful for recovery, use associated values to include that /// information. /// /// The following example shows an `IntParsingError` enumeration that captures /// two different kinds of errors that can occur when parsing an integer from /// a string: overflow, where the value represented by the string is too large /// for the integer data type, and invalid input, where nonnumeric characters /// are found within the input. /// /// enum IntParsingError: Error { /// case overflow /// case invalidInput(Character) /// } /// /// The `invalidInput` case includes the invalid character as an associated /// value. /// /// The next code sample shows a possible extension to the `Int` type that /// parses the integer value of a `String` instance, throwing an error when /// there is a problem during parsing. /// /// extension Int { /// init(validating input: String) throws { /// // ... /// let c = _nextCharacter(from: input) /// if !_isValid(c) { /// throw IntParsingError.invalidInput(c) /// } /// // ... /// } /// } /// /// When calling the new `Int` initializer within a `do` statement, you can use /// pattern matching to match specific cases of your custom error type and /// access their associated values, as in the example below. /// /// do { /// let price = try Int(validating: "$100") /// } catch IntParsingError.invalidInput(let invalid) { /// print("Invalid character: '\(invalid)'") /// } catch IntParsingError.overflow { /// print("Overflow error") /// } catch { /// print("Other error") /// } /// // Prints "Invalid character: '$'" /// /// Including More Data in Errors /// ============================= /// /// Sometimes you may want different error states to include the same common /// data, such as the position in a file or some of your application's state. /// When you do, use a structure to represent errors. The following example /// uses a structure to represent an error when parsing an XML document, /// including the line and column numbers where the error occurred: /// /// struct XMLParsingError: Error { /// enum ErrorKind { /// case invalidCharacter /// case mismatchedTag /// case internalError /// } /// /// let line: Int /// let column: Int /// let kind: ErrorKind /// } /// /// func parse(_ source: String) throws -> XMLDoc { /// // ... /// throw XMLParsingError(line: 19, column: 5, kind: .mismatchedTag) /// // ... /// } /// /// Once again, use pattern matching to conditionally catch errors. Here's how /// you can catch any `XMLParsingError` errors thrown by the `parse(_:)` /// function: /// /// do { /// let xmlDoc = try parse(myXMLData) /// } catch let e as XMLParsingError { /// print("Parsing error: \(e.kind) [\(e.line):\(e.column)]") /// } catch { /// print("Other error: \(error)") /// } /// // Prints "Parsing error: mismatchedTag [19:5]" public protocol Error { var _domain: String { get } var _code: Int { get } // Note: _userInfo is always an NSDictionary, but we cannot use that type here // because the standard library cannot depend on Foundation. However, the // underscore implies that we control all implementations of this requirement. var _userInfo: AnyObject? { get } #if _runtime(_ObjC) func _getEmbeddedNSError() -> AnyObject? #endif } #if _runtime(_ObjC) extension Error { /// Default implementation: there is no embedded NSError. public func _getEmbeddedNSError() -> AnyObject? { return nil } } #endif #if _runtime(_ObjC) // Helper functions for the C++ runtime to have easy access to embedded error, // domain, code, and userInfo as Objective-C values. @_silgen_name("") internal func _getErrorDomainNSString<T : Error>(_ x: UnsafePointer<T>) -> AnyObject { return x.pointee._domain._bridgeToObjectiveCImpl() } @_silgen_name("") internal func _getErrorCode<T : Error>(_ x: UnsafePointer<T>) -> Int { return x.pointee._code } @_silgen_name("") internal func _getErrorUserInfoNSDictionary<T : Error>(_ x: UnsafePointer<T>) -> AnyObject? { return x.pointee._userInfo.map { $0 as AnyObject } } // Called by the casting machinery to extract an NSError from an Error value. @_silgen_name("") internal func _getErrorEmbeddedNSErrorIndirect<T : Error>( _ x: UnsafePointer<T>) -> AnyObject? { return x.pointee._getEmbeddedNSError() } /// Called by compiler-generated code to extract an NSError from an Error value. public // COMPILER_INTRINSIC func _getErrorEmbeddedNSError<T : Error>(_ x: T) -> AnyObject? { return x._getEmbeddedNSError() } /// Provided by the ErrorObject implementation. @_silgen_name("_swift_stdlib_getErrorDefaultUserInfo") internal func _getErrorDefaultUserInfo<T: Error>(_ error: T) -> AnyObject? /// Provided by the ErrorObject implementation. /// Called by the casting machinery and by the Foundation overlay. @_silgen_name("_swift_stdlib_bridgeErrorToNSError") public func _bridgeErrorToNSError(_ error: __owned Error) -> AnyObject #endif /// Invoked by the compiler when the subexpression of a `try!` expression /// throws an error. @_silgen_name("swift_unexpectedError") public func _unexpectedError( _ error: __owned Error, filenameStart: Builtin.RawPointer, filenameLength: Builtin.Word, filenameIsASCII: Builtin.Int1, line: Builtin.Word ) { preconditionFailure( "'try!' expression unexpectedly raised an error: \(String(reflecting: error))", file: StaticString( _start: filenameStart, utf8CodeUnitCount: filenameLength, isASCII: filenameIsASCII), line: UInt(line)) } /// Invoked by the compiler when code at top level throws an uncaught error. @_silgen_name("swift_errorInMain") public func _errorInMain(_ error: Error) { fatalError("Error raised at top level: \(String(reflecting: error))") } /// Runtime function to determine the default code for an Error-conforming type. /// Called by the Foundation overlay. @_silgen_name("_swift_stdlib_getDefaultErrorCode") public func _getDefaultErrorCode<T : Error>(_ error: T) -> Int extension Error { public var _code: Int { return _getDefaultErrorCode(self) } public var _domain: String { return String(reflecting: type(of: self)) } public var _userInfo: AnyObject? { #if _runtime(_ObjC) return _getErrorDefaultUserInfo(self) #else return nil #endif } } extension Error where Self: RawRepresentable, Self.RawValue: FixedWidthInteger { // The error code of Error with integral raw values is the raw value. public var _code: Int { if Self.RawValue.isSigned { return numericCast(self.rawValue) } let uintValue: UInt = numericCast(self.rawValue) return Int(bitPattern: uintValue) } }
apache-2.0
df8edded5f4518d5ca4a5d63680f98f1
33.245763
83
0.656149
4.28072
false
false
false
false
BridgeTheGap/KRMathInputView
Example/Pods/KRMathInputView/KRMathInputView/Classes/Model/Ink.swift
1
2042
// // Ink.swift // TestScript // // Created by Joshua Park on 08/02/2017. // Copyright © 2017 Knowre. All rights reserved. // import UIKit public protocol InkType { var frame: CGRect { get } var objcType: Any { get } } public struct StrokeInk: InkType { public let path: UIBezierPath public var frame: CGRect { return path.bounds } public var objcType: Any { var arr = NSMutableArray() let points = withUnsafeMutablePointer(to: &arr) { UnsafeMutablePointer<NSMutableArray>($0) } path.cgPath.apply(info: points) { (info, element) in let bezierPoints = info?.assumingMemoryBound(to: NSMutableArray.self).pointee let points = element.pointee.points let type = element.pointee.type switch type { case .moveToPoint: bezierPoints?.add(NSValue(cgPoint: points.pointee)) break case .addLineToPoint: bezierPoints?.add(NSValue(cgPoint: points.pointee)) break case .addQuadCurveToPoint: bezierPoints?.add(NSValue(cgPoint: points.pointee)) bezierPoints?.add(NSValue(cgPoint: points.successor().pointee)) break case .addCurveToPoint: bezierPoints?.add(NSValue(cgPoint: points.pointee)) bezierPoints?.add(NSValue(cgPoint: points.successor().pointee)) bezierPoints?.add(NSValue(cgPoint: points.successor().pointee)) break default: break } } return NSArray(array: points.pointee) } public init(path: UIBezierPath) { self.path = path } } public struct CharacterInk: InkType { public let character: Character public var frame: CGRect public var objcType: Any { return character } public init(character: Character, frame: CGRect) { self.character = character self.frame = frame } }
mit
5dfe79130b501753bf58bbfe9bcc38fb
28.57971
100
0.589417
4.90625
false
false
false
false
rsattar/Voucher
Voucher iOS App/ViewController.swift
1
2594
// // ViewController.swift // Voucher iOS App // // Created by Rizwan Sattar on 11/7/15. // Copyright © 2015 Rizwan Sattar. All rights reserved. // import UIKit import Voucher class ViewController: UIViewController, VoucherServerDelegate { var server: VoucherServer? @IBOutlet var serverStatusLabel: UILabel! @IBOutlet var connectionStatusLabel: UILabel! deinit { self.server?.stop() self.server?.delegate = nil self.server = nil } override func viewDidLoad() { super.viewDidLoad() let uniqueId = "VoucherTest" self.server = VoucherServer(uniqueSharedId: uniqueId) self.server?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.server?.startAdvertising { (displayName, responseHandler) -> Void in let alertController = UIAlertController(title: "Allow Auth?", message: "Allow \"\(displayName)\" access to your login?", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Not Now", style: .cancel, handler: { action in responseHandler(nil, nil) })) alertController.addAction(UIAlertAction(title: "Allow", style: .default, handler: { action in // For our authData, use a token string (to simulate an OAuth token, for example) let authData = "THIS IS AN AUTH TOKEN".data(using: String.Encoding.utf8)! responseHandler(authData, nil) })) self.present(alertController, animated: true, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.server?.stop() } // MARK: - VoucherServerDelegate func voucherServer(_ server: VoucherServer, didUpdateAdvertising isAdvertising: Bool) { var text = "❌ Server Offline." if (isAdvertising) { text = "✅ Server Online." } self.serverStatusLabel.text = text self.connectionStatusLabel.isHidden = !isAdvertising } func voucherServer(_ server: VoucherServer, didUpdateConnectionToClient isConnectedToClient: Bool) { var text = "📡 Waiting for Connection..." if (isConnectedToClient) { text = "✅ Connected." } self.connectionStatusLabel.text = text } }
mit
fd93525e40f3bda50889e3a41e8b577e
29.761905
156
0.635449
4.950192
false
false
false
false
DrabWeb/Azusa
Source/Azusa/Azusa/Views/PluginsPreferencesCellView.swift
1
1079
// // PluginsPreferencesCellView.swift // Azusa // // Created by Ushio on 2/14/17. // import Cocoa import Yui class PluginsPreferencesCellView: NSTableCellView { // MARK: - Properties // MARK: Public Properties var representedPlugin : PluginInfo? { return _representedPlugin; } // MARK: Private Properties private var _representedPlugin : PluginInfo? = nil; @IBOutlet private weak var statusImageView: NSImageView! @IBOutlet private weak var nameLabel: NSTextField! @IBOutlet private weak var versionLabel: NSTextField! // MARK: - Methods // MARK: Public Methods func display(plugin : PluginInfo) { _representedPlugin = plugin; nameLabel.stringValue = plugin.name; versionLabel.stringValue = "v\(plugin.version)"; // TODO: Probably find a better icon for default plugin statusImageView.image = NSImage(named: plugin.isEnabled ? (plugin.isDefault ? "NSStatusPartiallyAvailable" : "NSStatusAvailable") : "NSStatusNone")!; } }
gpl-3.0
cb2ca1b10f6e64cbc8a42866ae3b2e9d
25.317073
157
0.658943
4.753304
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Service/LinkedBanks/LinkedBanksService.swift
1
3297
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import MoneyKit import RxSwift import RxToolKit import ToolKit public enum BankLinkageError: Error { case generic case server(Error) } public protocol LinkedBanksServiceAPI { /// Fetches any linked bank associated with the current user var linkedBanks: Single<[LinkedBankData]> { get } /// Starts the flow to linked a bank var bankLinkageStartup: Single<Result<BankLinkageData?, BankLinkageError>> { get } /// Returns the requested linked bank for the given id func linkedBank(for id: String) -> Single<LinkedBankData?> /// Fetches and updates the underlying cached value func fetchLinkedBanks() -> Single<[LinkedBankData]> /// Deletes a linked bank by its id /// - Parameter id: A `String` representing the bank id. func deleteBank(by id: String) -> Completable func invalidate() } final class LinkedBanksService: LinkedBanksServiceAPI { var linkedBanks: Single<[LinkedBankData]> { cachedValue.valueSingle } let bankLinkageStartup: Single<Result<BankLinkageData?, BankLinkageError>> // MARK: - Private private let cachedValue: CachedValue<[LinkedBankData]> // MARK: - Injected private let client: LinkedBanksClientAPI private let fiatCurrencyService: FiatCurrencyServiceAPI init( client: LinkedBanksClientAPI = resolve(), fiatCurrencyService: FiatCurrencyServiceAPI = resolve() ) { self.client = client self.fiatCurrencyService = fiatCurrencyService cachedValue = CachedValue( configuration: .onSubscription( schedulerIdentifier: "LinkedBanksService" ) ) cachedValue.setFetch { client.linkedBanks() .map { response -> [LinkedBankData] in // The API path is `banking-info` that includes both linked banked and bank account/beneficiary // we currently only need to display the linked banks as for beneficiaries we use older APIs. // So the filtering is a patch until we remove the older backend APIs response.compactMap(LinkedBankData.init(response:)) } .asSingle() } bankLinkageStartup = fiatCurrencyService.tradingCurrency .asSingle() .flatMap { currency -> Single<(CreateBankLinkageResponse, FiatCurrency)> in client.createBankLinkage(for: currency) .map { ($0, currency) } .asSingle() } .mapToResult( successMap: { BankLinkageData(from: $0, currency: $1) }, errorMap: { BankLinkageError.server($0) } ) } // MARK: Methods func linkedBank(for id: String) -> Single<LinkedBankData?> { linkedBanks .map { $0.first(where: { $0.identifier == id }) } } func fetchLinkedBanks() -> Single<[LinkedBankData]> { cachedValue.fetchValue } func deleteBank(by id: String) -> Completable { client.deleteLinkedBank(for: id).asObservable().ignoreElements().asCompletable() } func invalidate() { cachedValue.invalidate() } }
lgpl-3.0
a7525e51ad5b109956c4642d13bd36ff
30.09434
115
0.632282
5.094281
false
false
false
false
Ryan-Korteway/GVSSS
GVBandwagon/Pods/KGFloatingDrawer/Pod/Classes/KGDrawerSpringAnimator.swift
1
3751
// // KGDrawerAnimator.swift // KGDrawerViewController // // Created by Kyle Goddard on 2015-02-10. // Copyright (c) 2015 Kyle Goddard. All rights reserved. // import UIKit open class KGDrawerSpringAnimator: NSObject { let kKGCenterViewDestinationScale:CGFloat = 0.7 open var animationDelay: TimeInterval = 0.0 open var animationDuration: TimeInterval = 0.7 open var initialSpringVelocity: CGFloat = 9.8 // 9.1 m/s == earth gravity accel. open var springDamping: CGFloat = 0.8 // TODO: can swift have private functions in a protocol? fileprivate func applyTransforms(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView) { let direction = side.rawValue let sideWidth = drawerView.bounds.width let centerWidth = centerView.bounds.width let centerHorizontalOffset = direction * sideWidth let scaledCenterViewHorizontalOffset = direction * (sideWidth - (centerWidth - kKGCenterViewDestinationScale * centerWidth) / 2.0) let sideTransform = CGAffineTransform(translationX: centerHorizontalOffset, y: 0.0) drawerView.transform = sideTransform let centerTranslate = CGAffineTransform(translationX: scaledCenterViewHorizontalOffset, y: 0.0) let centerScale = CGAffineTransform(scaleX: kKGCenterViewDestinationScale, y: kKGCenterViewDestinationScale) centerView.transform = centerScale.concatenating(centerTranslate) } fileprivate func resetTransforms(_ views: [UIView]) { for view in views { view.transform = CGAffineTransform.identity } } } extension KGDrawerSpringAnimator: KGDrawerAnimating { public func openDrawer(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView, animated: Bool, complete: @escaping (_ finished: Bool) -> Void) { if (animated) { UIView.animate(withDuration: animationDuration, delay: animationDelay, usingSpringWithDamping: springDamping, initialSpringVelocity: initialSpringVelocity, options: UIViewAnimationOptions.curveLinear, animations: { self.applyTransforms(side, drawerView: drawerView, centerView: centerView) }, completion: complete) } else { self.applyTransforms(side, drawerView: drawerView, centerView: centerView) } } public func dismissDrawer(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView, animated: Bool, complete: @escaping (_ finished: Bool) -> Void) { if (animated) { UIView.animate(withDuration: animationDuration, delay: animationDelay, usingSpringWithDamping: springDamping, initialSpringVelocity: initialSpringVelocity, options: UIViewAnimationOptions.curveLinear, animations: { self.resetTransforms([drawerView, centerView]) }, completion: complete) } else { self.resetTransforms([drawerView, centerView]) } } public func willRotateWithDrawerOpen(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView) { } public func didRotateWithDrawerOpen(_ side: KGDrawerSide, drawerView: UIView, centerView: UIView) { UIView.animate(withDuration: animationDuration, delay: animationDelay, usingSpringWithDamping: springDamping, initialSpringVelocity: initialSpringVelocity, options: UIViewAnimationOptions.curveLinear, animations: {}, completion: nil ) } }
apache-2.0
8bd5e902cfd814043035cd053944a115
39.333333
157
0.651026
5.475912
false
false
false
false
Antondomashnev/FBSnapshotsViewer
FBSnapshotsViewerTests/PreferencesInteractorSpec.swift
1
9435
// // PreferencesInteractorSpec.swift // FBSnapshotsViewer // // Created by Anton Domashnev on 13.05.17. // Copyright © 2017 Anton Domashnev. All rights reserved. // import Quick import Nimble @testable import FBSnapshotsViewer class PreferencesInteractorSpec: QuickSpec { override func spec() { var interactor: PreferencesInteractor! var configuration: FBSnapshotsViewer.Configuration! var configurationStorage: ConfigurationStorageMock! beforeEach { configurationStorage = ConfigurationStorageMock() configuration = Configuration(derivedDataFolder: DerivedDataFolder.xcodeDefault) } describe(".setNewDerivedDataFolderPath") { context("when current configuration derived data folder type is xcodeCustom") { var newPath: String! beforeEach { newPath = "myNewPath" configurationStorage.loadConfigurationReturnValue = Configuration(derivedDataFolder: DerivedDataFolder.xcodeCustom(path: "customPath")) interactor = PreferencesInteractor(configurationStorage: configurationStorage) interactor.setNewDerivedDataFolderPath(newPath) } it("updates configuration") { let currentConfiguration = interactor.currentConfiguration() expect(currentConfiguration.derivedDataFolder.path).to(equal(newPath)) } } context("when current configuration derived data folder type is appcode") { var newPath: String! beforeEach { newPath = "myNewPath" configurationStorage.loadConfigurationReturnValue = Configuration(derivedDataFolder: DerivedDataFolder.appcode(path: "customPath")) interactor = PreferencesInteractor(configurationStorage: configurationStorage) interactor.setNewDerivedDataFolderPath(newPath) } it("updates configuration") { let currentConfiguration = interactor.currentConfiguration() expect(currentConfiguration.derivedDataFolder.path).to(equal(newPath)) } } context("when current configuration derived data folder type is xcodeDefault") { beforeEach { configurationStorage.loadConfigurationReturnValue = configuration interactor = PreferencesInteractor(configurationStorage: configurationStorage) } it("asserts") { expect { interactor.setNewDerivedDataFolderPath("myNewPath") }.to(throwAssertion()) } } } describe(".setNewDerivedDataFolderType") { context("when type is not derived data folder type") { beforeEach { configurationStorage.loadConfigurationReturnValue = configuration interactor = PreferencesInteractor(configurationStorage: configurationStorage) } it("asserts") { expect { interactor.setNewDerivedDataFolderType("Foo") }.to(throwAssertion()) } } context("when type is equal to current one") { beforeEach { configurationStorage.loadConfigurationReturnValue = configuration interactor = PreferencesInteractor(configurationStorage: configurationStorage) } it("does nothing") { interactor.setNewDerivedDataFolderType(DerivedDataFolderType.xcodeDefault.rawValue) } } context("when current type is xcodeDefault") { beforeEach { configurationStorage.loadConfigurationReturnValue = configuration interactor = PreferencesInteractor(configurationStorage: configurationStorage) } context("when set xcodeCustom type") { beforeEach { interactor.setNewDerivedDataFolderType(DerivedDataFolderType.xcodeCustom.rawValue) } it("updates configuration with xcodeCustom derived data and empty path") { expect(interactor.currentConfiguration().derivedDataFolder).to(equal(DerivedDataFolder.xcodeCustom(path: ""))) } } context("when set appcode type") { beforeEach { interactor.setNewDerivedDataFolderType(DerivedDataFolderType.appcode.rawValue) } it("updates configuration with appcode derived data and empty path") { expect(interactor.currentConfiguration().derivedDataFolder).to(equal(DerivedDataFolder.appcode(path: ""))) } } } context("when current type is xcodeCustom") { beforeEach { configurationStorage.loadConfigurationReturnValue = Configuration(derivedDataFolder: DerivedDataFolder.xcodeCustom(path: "myPath")) interactor = PreferencesInteractor(configurationStorage: configurationStorage) } context("when set xcodeDefault type") { beforeEach { interactor.setNewDerivedDataFolderType(DerivedDataFolderType.xcodeDefault.rawValue) } it("updates configuration with xcodeDefault derived data and empty path") { expect(interactor.currentConfiguration().derivedDataFolder).to(equal(DerivedDataFolder.xcodeDefault)) } } context("when set appcode type") { beforeEach { interactor.setNewDerivedDataFolderType(DerivedDataFolderType.appcode.rawValue) } it("updates configuration with appcode derived data and empty path") { expect(interactor.currentConfiguration().derivedDataFolder).to(equal(DerivedDataFolder.appcode(path: ""))) } } } context("when current type is appcode") { beforeEach { configurationStorage.loadConfigurationReturnValue = Configuration(derivedDataFolder: DerivedDataFolder.appcode(path: "myPath")) interactor = PreferencesInteractor(configurationStorage: configurationStorage) } context("when set xcodeDefault type") { beforeEach { interactor.setNewDerivedDataFolderType(DerivedDataFolderType.xcodeDefault.rawValue) } it("updates configuration with xcodeDefault derived data and empty path") { expect(interactor.currentConfiguration().derivedDataFolder).to(equal(DerivedDataFolder.xcodeDefault)) } } context("when set xcodeCustom type") { beforeEach { interactor.setNewDerivedDataFolderType(DerivedDataFolderType.xcodeCustom.rawValue) } it("updates configuration with xcodeCustom derived data and empty path") { expect(interactor.currentConfiguration().derivedDataFolder).to(equal(DerivedDataFolder.xcodeCustom(path: ""))) } } } } describe(".currentConfiguration") { beforeEach { configurationStorage.loadConfigurationReturnValue = configuration interactor = PreferencesInteractor(configurationStorage: configurationStorage) } it("returns correct configuration") { expect(interactor.currentConfiguration()).to(equal(configuration)) } } describe(".save") { beforeEach { configurationStorage.loadConfigurationReturnValue = configuration interactor = PreferencesInteractor(configurationStorage: configurationStorage) interactor.save() } it("saves configuration") { expect(configurationStorage.save_configuration_Called).to(beTrue()) expect(configurationStorage.save_configuration_ReceivedConfiguration).to(equal(configuration)) } } describe(".init") { context("when configuration storage can load configuration") { beforeEach { configurationStorage.loadConfigurationReturnValue = Configuration(derivedDataFolder: DerivedDataFolder.xcodeDefault) } it("initializes new instance") { expect(PreferencesInteractor(configurationStorage: configurationStorage)).toNot(beNil()) } } context("when configuration storage can not load configuration") { it("asserts") { expect { PreferencesInteractor(configurationStorage: configurationStorage) }.to(throwAssertion()) } } } } }
mit
90a78b5c7196c39dd39effd8c1ca974b
42.474654
155
0.586072
7.638866
false
true
false
false
sishenyihuba/Weibo
Weibo/06-Compose(发布)/Emoticon/EmioticonViewCell.swift
1
1580
// // EmioticonViewCell.swift // 09-表情键盘 // // Created by xiaomage on 16/4/12. // Copyright © 2016年 小码哥. All rights reserved. // import UIKit class EmioticonViewCell: UICollectionViewCell { // MARK:- 懒加载属性 private lazy var emoticonBtn : UIButton = UIButton() // MARK:- 定义的属性 var emoticon : Emoticon? { didSet { guard let emoticon = emoticon else { return } // 1.设置emoticonBtn的内容 emoticonBtn.setImage(UIImage(contentsOfFile: emoticon.pngPath ?? ""), forState: .Normal) emoticonBtn.setTitle(emoticon.emojiCode, forState: .Normal) // 2.设置删除按钮 if emoticon.isRemove { emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal) } } } // MARK:- 重写构造函数 override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面内容 extension EmioticonViewCell { private func setupUI() { // 1.添加子控件 contentView.addSubview(emoticonBtn) // 2.设置btn的frame emoticonBtn.frame = contentView.bounds // 3.设置btn属性 emoticonBtn.userInteractionEnabled = false emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32) } }
mit
cff48282752c1c7f32d215c758966cec
24.396552
100
0.575696
4.646688
false
false
false
false
smartmobilefactory/FolioReaderKit
Source/EPUBCore/FRResources.swift
2
3074
// // FRResources.swift // FolioReaderKit // // Created by Heberti Almeida on 29/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit class FRResources: NSObject { var resources = [String: FRResource]() /** Adds a resource to the resources. */ func add(_ resource: FRResource) { self.resources[resource.href] = resource } // MARK: Find /** Gets the first resource (random order) with the give mediatype. Useful for looking up the table of contents as it's supposed to be the only resource with NCX mediatype. */ func findByMediaType(_ mediaType: MediaType) -> FRResource? { for resource in resources.values { if resource.mediaType != nil && resource.mediaType == mediaType { return resource } } return nil } /** Gets the first resource (random order) with the give extension. Useful for looking up the table of contents as it's supposed to be the only resource with NCX extension. */ func findByExtension(_ ext: String) -> FRResource? { for resource in resources.values { if resource.mediaType != nil && resource.mediaType.defaultExtension == ext { return resource } } return nil } /** Gets the first resource (random order) with the give properties. - parameter properties: ePub 3 properties. e.g. `cover-image`, `nav` - returns: The Resource. */ func findByProperty(_ properties: String) -> FRResource? { for resource in resources.values { if resource.properties == properties { return resource } } return nil } /** Gets the resource with the given href. */ func findByHref(_ href: String) -> FRResource? { guard !href.isEmpty else { return nil } // This clean is neede because may the toc.ncx is not located in the root directory let cleanHref = href.replacingOccurrences(of: "../", with: "") return resources[cleanHref] } /** Gets the resource with the given href. */ func findById(_ id: String?) -> FRResource? { guard let id = id else { return nil } for resource in resources.values { if let resourceID = resource.id, resourceID == id { return resource } } return nil } /** Whether there exists a resource with the given href. */ func containsByHref(_ href: String) -> Bool { guard !href.isEmpty else { return false } return resources.keys.contains(href) } /** Whether there exists a resource with the given id. */ func containsById(_ id: String?) -> Bool { guard let id = id else { return false } for resource in resources.values { if let resourceID = resource.id, resourceID == id { return true } } return false } }
bsd-3-clause
06cfd1a9f9b6155edd7232df76cef723
25.964912
109
0.580351
4.780715
false
false
false
false
donnywals/CustomCollectionViewLayout
CustomCollectionViewLayout/CustomCollectionViewCell.swift
1
564
// // CustomCollectionViewCell.swift // CustomCollectionViewLayout // // Created by Donny Wals on 07-07-15. // Copyright (c) 2015 Donny Wals. All rights reserved. // import UIKit class CustomCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! override func awakeFromNib() { imageView.layer.cornerRadius = 40 imageView.clipsToBounds = true layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowRadius = 2 layer.shadowOpacity = 0.8 } }
mit
46f86e5e6427f356e0dd1750b4f2d167
22.5
55
0.714539
4.305344
false
false
false
false
Sunnyyoung/Meizi-Swift
Pods/SKPhotoBrowser/SKPhotoBrowser/SKZoomingScrollView.swift
1
10600
// // SKZoomingScrollView.swift // SKViewExample // // Created by suzuki_keihsi on 2015/10/01. // Copyright © 2015 suzuki_keishi. All rights reserved. // import UIKit public class SKZoomingScrollView: UIScrollView, UIScrollViewDelegate, SKDetectingViewDelegate, SKDetectingImageViewDelegate { var captionView: SKCaptionView! var photo: SKPhotoProtocol! { didSet { photoImageView.image = nil if photo != nil { displayImage(complete: false) } } } private(set) var photoImageView: SKDetectingImageView! private weak var photoBrowser: SKPhotoBrowser? private var tapView: SKDetectingView! private var indicatorView: SKIndicatorView! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } convenience init(frame: CGRect, browser: SKPhotoBrowser) { self.init(frame: frame) photoBrowser = browser setup() } deinit { photoBrowser = nil } func setup() { // tap tapView = SKDetectingView(frame: bounds) tapView.delegate = self tapView.backgroundColor = UIColor.clearColor() tapView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth] addSubview(tapView) // image photoImageView = SKDetectingImageView(frame: frame) photoImageView.delegate = self photoImageView.contentMode = .ScaleAspectFill photoImageView.backgroundColor = .clearColor() addSubview(photoImageView) // indicator indicatorView = SKIndicatorView(frame: frame) addSubview(indicatorView) // self backgroundColor = .clearColor() delegate = self showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false decelerationRate = UIScrollViewDecelerationRateFast autoresizingMask = [.FlexibleWidth, .FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleRightMargin, .FlexibleLeftMargin] } // MARK: - override public override func layoutSubviews() { tapView.frame = bounds indicatorView.frame = frame super.layoutSubviews() let boundsSize = bounds.size var frameToCenter = photoImageView.frame // horizon if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2) } else { frameToCenter.origin.x = 0 } // vertical if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2) } else { frameToCenter.origin.y = 0 } // Center if !CGRectEqualToRect(photoImageView.frame, frameToCenter) { photoImageView.frame = frameToCenter } } public func setMaxMinZoomScalesForCurrentBounds() { maximumZoomScale = 1 minimumZoomScale = 1 zoomScale = 1 guard let photoImageView = photoImageView else { return } let boundsSize = bounds.size let imageSize = photoImageView.frame.size let xScale = boundsSize.width / imageSize.width let yScale = boundsSize.height / imageSize.height let minScale: CGFloat = min(xScale, yScale) var maxScale: CGFloat! let scale = UIScreen.mainScreen().scale let deviceScreenWidth = UIScreen.mainScreen().bounds.width * scale // width in pixels. scale needs to remove if to use the old algorithm let deviceScreenHeight = UIScreen.mainScreen().bounds.height * scale // height in pixels. scale needs to remove if to use the old algorithm // it is the old algorithm /* if photoImageView.frame.width < deviceScreenWidth { // I think that we should to get coefficient between device screen width and image width and assign it to maxScale. I made two mode that we will get the same result for different device orientations. if UIApplication.sharedApplication().statusBarOrientation.isPortrait { maxScale = deviceScreenHeight / photoImageView.frame.width } else { maxScale = deviceScreenWidth / photoImageView.frame.width } } else if photoImageView.frame.width > deviceScreenWidth { maxScale = 1.0 } else { // here if photoImageView.frame.width == deviceScreenWidth maxScale = 2.5 } */ if photoImageView.frame.width < deviceScreenWidth { // I think that we should to get coefficient between device screen width and image width and assign it to maxScale. I made two mode that we will get the same result for different device orientations. if UIApplication.sharedApplication().statusBarOrientation.isPortrait { maxScale = deviceScreenHeight / photoImageView.frame.width } else { maxScale = deviceScreenWidth / photoImageView.frame.width } } else if photoImageView.frame.width > deviceScreenWidth { maxScale = 1.0 } else { // here if photoImageView.frame.width == deviceScreenWidth maxScale = 2.5 } maximumZoomScale = maxScale minimumZoomScale = minScale zoomScale = minScale // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the // maximum zoom scale to 0.5 // After changing this value, we still never use more /* maxScale = maxScale / scale if maxScale < minScale { maxScale = minScale * 2 } */ // reset position photoImageView.frame = CGRect(x: 0, y: 0, width: photoImageView.frame.size.width, height: photoImageView.frame.size.height) setNeedsLayout() } public func prepareForReuse() { photo = nil if captionView != nil { captionView.removeFromSuperview() captionView = nil } } // MARK: - image public func displayImage(complete flag: Bool) { // reset scale maximumZoomScale = 1 minimumZoomScale = 1 zoomScale = 1 contentSize = CGSize.zero if !flag { indicatorView.startAnimating() photo.loadUnderlyingImageAndNotify() }else { indicatorView.stopAnimating() } if let image = photo.underlyingImage { // image photoImageView.image = image var photoImageViewFrame = CGRect.zero photoImageViewFrame.origin = CGPoint.zero photoImageViewFrame.size = image.size photoImageView.frame = photoImageViewFrame contentSize = photoImageViewFrame.size setMaxMinZoomScalesForCurrentBounds() } setNeedsLayout() } public func displayImageFailure() { indicatorView.stopAnimating() } // MARK: - handle tap public func handleDoubleTap(touchPoint: CGPoint) { if let photoBrowser = photoBrowser { NSObject.cancelPreviousPerformRequestsWithTarget(photoBrowser) } if zoomScale > minimumZoomScale { // zoom out setZoomScale(minimumZoomScale, animated: true) } else { // zoom in // I think that the result should be the same after double touch or pinch /* var newZoom: CGFloat = zoomScale * 3.13 if newZoom >= maximumZoomScale { newZoom = maximumZoomScale } */ zoomToRect(zoomRectForScrollViewWith(maximumZoomScale, touchPoint: touchPoint), animated: true) } // delay control photoBrowser?.hideControlsAfterDelay() } public func zoomRectForScrollViewWith(scale: CGFloat, touchPoint: CGPoint) -> CGRect { let w = frame.size.width / scale let h = frame.size.height / scale let x = touchPoint.x - (w / 2.0) let y = touchPoint.y - (h / 2.0) return CGRect(x: x, y: y, width: w, height: h) } // MARK: - UIScrollViewDelegate public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return photoImageView } public func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) { photoBrowser?.cancelControlHiding() } public func scrollViewDidZoom(scrollView: UIScrollView) { setNeedsLayout() layoutIfNeeded() } // MARK: - SKDetectingViewDelegate func handleSingleTap(view: UIView, touch: UITouch) { if photoBrowser?.enableZoomBlackArea == true { photoBrowser?.toggleControls() } } func handleDoubleTap(view: UIView, touch: UITouch) { if photoBrowser?.enableZoomBlackArea == true { let needPoint = getViewFramePercent(view, touch: touch) handleDoubleTap(needPoint) } } private func getViewFramePercent(view: UIView, touch: UITouch) -> CGPoint { let oneWidthViewPercent = view.bounds.width / 100 let viewTouchPoint = touch.locationInView(view) let viewWidthTouch = viewTouchPoint.x let viewPercentTouch = viewWidthTouch / oneWidthViewPercent let photoWidth = photoImageView.bounds.width let onePhotoPercent = photoWidth / 100 let needPoint = viewPercentTouch * onePhotoPercent var Y: CGFloat! if viewTouchPoint.y < view.bounds.height / 2 { Y = 0 } else { Y = photoImageView.bounds.height } let allPoint = CGPoint(x: needPoint, y: Y) return allPoint } // MARK: - SKDetectingImageViewDelegate func handleImageViewSingleTap(view: UIImageView, touch: UITouch) { photoBrowser?.toggleControls() } func handleImageViewDoubleTap(view: UIImageView, touch: UITouch) { handleDoubleTap(touch.locationInView(view)) } }
mit
139daddcd293513f74f2d1bac8cac9d8
32.865815
211
0.607038
5.698387
false
false
false
false
kuangniaokuang/Cocktail-Pro
smartmixer/smartmixer/AppRoot/Welcome.swift
1
9389
// // Welcome.swift // smartmixer // // Created by 姚俊光 on 14/9/24. // Copyright (c) 2014年 smarthito. All rights reserved. // import UIKit class Welcome: UIViewController , UIGestureRecognizerDelegate { @IBOutlet var page1_bg:UIImageView! @IBOutlet var page2_bg:UIImageView! @IBOutlet var page3_bg:UIImageView! @IBOutlet var page4_bg:UIImageView! @IBOutlet var page1_content:UIImageView! @IBOutlet var page2_content:UIImageView! @IBOutlet var page3_content:UIImageView! @IBOutlet var page4_content:UIImageView! @IBOutlet var page1_desc:UIImageView! @IBOutlet var page2_desc:UIImageView! @IBOutlet var page3_desc:UIImageView! @IBOutlet var page4_desc:UIImageView! @IBOutlet var pageControl:UIPageControl! @IBOutlet var startButton:UIButton! var panGesture:UIPanGestureRecognizer! var maxpan:CGFloat = 150 var current_bg:UIImageView! var current_content:UIImageView! var current_desc:UIImageView! var show_bg:UIImageView! var show_content:UIImageView! var show_desc:UIImageView! var currentIndex:Int = 1 let animationTime:CGFloat=1 let contentPlus:CGFloat=2 let descPlus:CGFloat=3 var direction:Bool=false var firstPop:Bool=true class func WelcomeInit()->Welcome{ var welcome = UIStoryboard(name:"Launch"+deviceDefine,bundle:nil).instantiateViewControllerWithIdentifier("welcome") as Welcome return welcome } override func viewDidLoad() { super.viewDidLoad() pageControl.currentPage = 0 pageControl.numberOfPages = 4 page2_bg.alpha = 0 page2_content.alpha = 0 page2_desc.alpha = 0 page3_bg.alpha = 0 page3_content.alpha = 0 page3_desc.alpha = 0 page4_bg.alpha = 0 page4_content.alpha = 0 page4_desc.alpha = 0 current_bg = page1_bg current_content = page1_content current_desc = page1_desc panGesture = UIPanGestureRecognizer() panGesture.addTarget(self, action: "pan:") self.view.addGestureRecognizer(panGesture) self.view.userInteractionEnabled = true } func pan(sender:UIPanGestureRecognizer){ var currentPostion = sender.translationInView(self.view) if (self.panGesture.state == UIGestureRecognizerState.Began) { current_bg=(self.valueForKey("page\((currentIndex))_bg") as UIImageView!) current_content=(self.valueForKey("page\((currentIndex))_content") as UIImageView!) current_desc=(self.valueForKey("page\((currentIndex))_desc") as UIImageView!) }else if(self.panGesture.state == UIGestureRecognizerState.Ended){ if(show_bg != nil){ pageToShowAnimate(currentPostion.x) panToHideAnimate(currentPostion.x) if(currentPostion.x>maxpan/2){ currentIndex-- }else if(currentPostion.x<(-maxpan/2)){ currentIndex++ } if(currentIndex==4){ startButton.alpha=1 }else{ startButton.alpha=0 } pageControl.currentPage = currentIndex-1 } }else{ if((currentIndex<4) && currentPostion.x < -20 && currentPostion.x>(-maxpan)){//向左滑动 if(show_bg == nil || direction){ show_bg=(self.valueForKey("page\((currentIndex+1))_bg") as UIImageView!) show_content=(self.valueForKey("page\((currentIndex+1))_content") as UIImageView!) show_desc=(self.valueForKey("page\((currentIndex+1))_desc") as UIImageView!) direction = false } panToHide(currentPostion.x); pageToShow(currentPostion.x); } else if((currentIndex>1) && currentPostion.x>20 && currentPostion.x<maxpan){//向右滑动 if(show_bg == nil || !direction){ show_bg=(self.valueForKey("page\((currentIndex-1))_bg") as UIImageView!) show_content=(self.valueForKey("page\((currentIndex-1))_content") as UIImageView!) show_desc=(self.valueForKey("page\((currentIndex-1))_desc") as UIImageView!) direction = true } panToHide(currentPostion.x); pageToShow(currentPostion.x); } } } func pageToShow(offset:CGFloat){ var alph = abs(offset/maxpan) show_bg.alpha = alph show_content.alpha = alph show_desc.alpha = alph if(offset<0){ show_content.frame = CGRect(x:(maxpan+offset)*contentPlus, y: 0, width: show_content.frame.width, height: show_content.frame.height) show_desc.frame = CGRect(x: (maxpan+offset)*descPlus, y: 0, width: show_desc.frame.width, height: show_desc.frame.height) }else{ show_content.frame = CGRect(x:(offset-maxpan)*contentPlus, y: 0, width: show_content.frame.width, height: show_content.frame.height) show_desc.frame = CGRect(x: (offset-maxpan)*descPlus, y: 0, width: show_desc.frame.width, height: show_desc.frame.height) } } func pageToShowAnimate(offset:CGFloat){ if(self.show_bg != nil){ var anitime:CGFloat = (maxpan-abs(offset))/maxpan*animationTime var ialpha:CGFloat = 1 var ioffset:CGFloat = 0 if(abs(offset)<maxpan/2){//尚未移动一半 ialpha = 0 if(offset<0){ ioffset = maxpan }else{ ioffset = -maxpan } anitime = abs(offset)/maxpan*animationTime } UIView.animateWithDuration(NSTimeInterval(anitime), delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.show_bg.alpha = ialpha self.show_content.alpha = ialpha self.show_desc.alpha = ialpha self.show_content.frame = CGRect(x: ioffset*self.contentPlus, y: 0, width: self.show_content.frame.width, height: self.show_content.frame.height) self.show_desc.frame = CGRect(x: ioffset*self.descPlus, y: 0, width: self.show_desc.frame.width, height: self.show_desc.frame.height) }, completion: { _ in self.show_bg = nil }) } } func panToHide(offset:CGFloat){ if(offset<0){ current_content.frame = CGRect(x: offset*contentPlus, y: 0, width: current_content.frame.width, height: current_content.frame.height) current_desc.frame = CGRect(x: offset*descPlus, y: 0, width: current_content.frame.width, height: current_content.frame.height) }else{ current_content.frame = CGRect(x: offset*contentPlus, y: 0, width: current_content.frame.width, height: current_content.frame.height) current_desc.frame = CGRect(x: offset*descPlus, y: 0, width: current_content.frame.width, height: current_content.frame.height) } var alph = 1-abs(offset/maxpan) current_content.alpha = alph current_desc.alpha = alph current_bg.alpha = alph } func panToHideAnimate(offset:CGFloat){ if(self.show_bg != nil){ var anitime:CGFloat = (maxpan-abs(offset))/maxpan*animationTime var ialpha:CGFloat = 0 var ioffset:CGFloat = -maxpan if(offset>0){ ioffset = maxpan } if(abs(offset)<maxpan/2){//尚未移动一半 ialpha = 1 ioffset = 0 anitime = abs(offset)/maxpan*animationTime } UIView.animateWithDuration(NSTimeInterval(anitime), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.current_content.alpha = ialpha self.current_desc.alpha = ialpha self.current_bg.alpha = ialpha self.current_content.frame = CGRect(x: ioffset*self.contentPlus, y: 0, width: self.current_content.frame.width, height: self.current_content.frame.height) self.current_desc.frame = CGRect(x: ioffset*self.descPlus, y: 0, width: self.current_content.frame.width, height: self.current_content.frame.height) }, completion: nil) } } @IBAction func clicktoHidden(sender:UIButton){ UIView.animateWithDuration(0.3, animations : { self.view.alpha = 0 }, completion : {_ in if(self.firstPop){ self.view.removeFromSuperview() }else{ self.dismissViewControllerAnimated(false, completion: nil) } } ) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
bab47636d6b8a046ea80d0c064325bf9
37.440329
174
0.574457
4.578922
false
false
false
false
nathawes/swift
test/attr/attr_noescape.swift
10
20467
// RUN: %target-typecheck-verify-swift @noescape var fn : () -> Int = { 4 } // expected-error {{attribute can only be applied to types, not declarations}} func conflictingAttrs(_ fn: @noescape @escaping () -> Int) {} // expected-error {{unknown attribute 'noescape'}} func doesEscape(_ fn : @escaping () -> Int) {} func takesGenericClosure<T>(_ a : Int, _ fn : @noescape () -> T) {} // expected-error {{unknown attribute 'noescape'}} var globalAny: Any = 0 func assignToGlobal<T>(_ t: T) { // expected-note {{generic parameters are always considered '@escaping'}} globalAny = t } func takesArray(_ fns: [() -> Int]) { doesEscape(fns[0]) // Okay - array-of-function parameters are escaping } func takesVariadic(_ fns: () -> Int...) { doesEscape(fns[0]) // Okay - variadic-of-function parameters are escaping } func takesNoEscapeClosure(_ fn : () -> Int) { // expected-note 1 {{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} // expected-note@-1 6{{parameter 'fn' is implicitly non-escaping}} {{34-34=@escaping }} takesNoEscapeClosure { 4 } // ok _ = fn() // ok // This is ok, because the closure itself is noescape. takesNoEscapeClosure { fn() } doesEscape(fn) // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} takesGenericClosure(4, fn) // ok takesGenericClosure(4) { fn() } // ok. _ = [fn] // expected-error {{using non-escaping parameter 'fn' in a context expecting an @escaping closure}} _ = [doesEscape(fn)] // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} _ = [1 : fn] // expected-error {{using non-escaping parameter 'fn' in a context expecting an @escaping closure}} _ = [1 : doesEscape(fn)] // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} _ = "\(doesEscape(fn))" // expected-error {{passing non-escaping parameter 'fn' to function expecting an @escaping closure}} _ = "\(takesArray([fn]))" // expected-error {{using non-escaping parameter 'fn' in a context expecting an @escaping closure}} assignToGlobal(fn) // expected-error {{converting non-escaping parameter 'fn' to generic parameter 'T' may allow it to escape}} assignToGlobal((fn, fn)) // expected-error {{converting non-escaping value to 'T' may allow it to escape}} } class SomeClass { final var x = 42 func test() { // This should require "self." doesEscape { x } // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{17-17= [self] in}} expected-note{{reference 'self.' explicitly}} {{18-18=self.}} // Since 'takesNoEscapeClosure' doesn't escape its closure, it doesn't // require "self." qualification of member references. takesNoEscapeClosure { x } } @discardableResult func foo() -> Int { foo() func plain() { foo() } let plain2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} _ = plain2 func multi() -> Int { foo(); return 0 } let multi2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{30-30= [self] in}} expected-note{{reference 'self.' explicitly}} {{31-31=self.}} _ = multi2 doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{17-17= [self] in}} expected-note{{reference 'self.' explicitly}} {{18-18=self.}} takesNoEscapeClosure { foo() } // okay doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{17-17= [self] in}} expected-note{{reference 'self.' explicitly}} {{18-18=self.}} takesNoEscapeClosure { foo(); return 0 } // okay func outer() { func inner() { foo() } let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{21-21= [self] in}} expected-note{{reference 'self.' explicitly}} {{22-22=self.}} _ = inner2 func multi() -> Int { foo(); return 0 } let _: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{27-27= [self] in}} expected-note{{reference 'self.' explicitly}} {{28-28=self.}} doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} takesNoEscapeClosure { foo() } doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } } let _: () -> Void = { // expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{26-26= [self] in}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{26-26= [self] in}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{26-26= [self] in}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{26-26= [self] in}} func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{22-22=self.}} let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{21-21= [self] in}} expected-note{{reference 'self.' explicitly}} {{22-22=self.}} let _ = inner2 func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{29-29=self.}} let multi2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{32-32= [self] in}} expected-note{{reference 'self.' explicitly}} {{33-33=self.}} let _ = multi2 doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{30-30=self.}} doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{30-30=self.}} } doesEscape { //expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{17-17= [self] in}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{17-17= [self] in}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{17-17= [self] in}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{17-17= [self] in}} func inner() { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{22-22=self.}} let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{21-21= [self] in}} expected-note{{reference 'self.' explicitly}} {{22-22=self.}} _ = inner2 func multi() -> Int { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{29-29=self.}} let multi2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{32-32= [self] in}} expected-note{{reference 'self.' explicitly}} {{33-33=self.}} _ = multi2 doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} takesNoEscapeClosure { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{30-30=self.}} doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{30-30=self.}} return 0 } takesNoEscapeClosure { func inner() { foo() } let inner2 = { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{21-21= [self] in}} expected-note{{reference 'self.' explicitly}} {{22-22=self.}} _ = inner2 func multi() -> Int { foo(); return 0 } let multi2: () -> Int = { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{32-32= [self] in}} expected-note{{reference 'self.' explicitly}} {{33-33=self.}} _ = multi2 doesEscape { foo() } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} takesNoEscapeClosure { foo() } // okay doesEscape { foo(); return 0 } // expected-error {{call to method 'foo' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{19-19= [self] in}} expected-note{{reference 'self.' explicitly}} {{20-20=self.}} takesNoEscapeClosure { foo(); return 0 } // okay return 0 } // Implicit 'self' should be accepted when 'self' has value semantics. struct Outer { @discardableResult func bar() -> Int { bar() func plain() { bar() } let plain2 = { bar() } _ = plain2 func multi() -> Int { bar(); return 0 } let _: () -> Int = { bar(); return 0 } doesEscape { bar() } takesNoEscapeClosure { bar() } doesEscape { bar(); return 0 } takesNoEscapeClosure { bar(); return 0 } return 0 } } func structOuter() { struct Inner { @discardableResult func bar() -> Int { bar() // no-warning func plain() { bar() } let plain2 = { bar() } _ = plain2 func multi() -> Int { bar(); return 0 } let _: () -> Int = { bar(); return 0 } doesEscape { bar() } takesNoEscapeClosure { bar() } doesEscape { bar(); return 0 } takesNoEscapeClosure { bar(); return 0 } return 0 } } } return 0 } } // Implicit conversions (in this case to @convention(block)) are ok. @_silgen_name("whatever") func takeNoEscapeAsObjCBlock(_: @noescape @convention(block) () -> Void) // expected-error{{unknown attribute 'noescape'}} func takeNoEscapeTest2(_ fn : @noescape () -> ()) { // expected-error{{unknown attribute 'noescape'}} takeNoEscapeAsObjCBlock(fn) } // Autoclosure implies noescape.. func testAutoclosure(_ a : @autoclosure () -> Int) { // expected-note{{parameter 'a' is implicitly non-escaping}} doesEscape(a) // expected-error {{passing non-escaping parameter 'a' to function expecting an @escaping closure}} } // <rdar://problem/19470858> QoI: @autoclosure implies @noescape, so you shouldn't be allowed to specify both func redundant(_ fn : @noescape @autoclosure () -> Int) {} // expected-error {{unknown attribute 'noescape'}} protocol P1 { associatedtype Element } protocol P2 : P1 { associatedtype Element } func overloadedEach<O: P1, T>(_ source: O, _ transform: @escaping (O.Element) -> (), _: T) {} func overloadedEach<P: P2, T>(_ source: P, _ transform: @escaping (P.Element) -> (), _: T) {} struct S : P2 { typealias Element = Int func each(_ transform: @noescape (Int) -> ()) { // expected-error{{unknown attribute 'noescape'}} overloadedEach(self, transform, 1) } } // rdar://19763676 - False positive in @noescape analysis triggered by parameter label func r19763676Callee(_ f: @noescape (_ param: Int) -> Int) {} // expected-error{{unknown attribute 'noescape'}} func r19763676Caller(_ g: @noescape (Int) -> Int) { // expected-error{{unknown attribute 'noescape'}} r19763676Callee({ _ in g(1) }) } // <rdar://problem/19763732> False positive in @noescape analysis triggered by default arguments func calleeWithDefaultParameters(_ f: @noescape () -> (), x : Int = 1) {} // expected-error{{unknown attribute 'noescape'}} func callerOfDefaultParams(_ g: @noescape () -> ()) { // expected-error{{unknown attribute 'noescape'}} calleeWithDefaultParameters(g) } // <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape class NoEscapeImmediatelyApplied { func f() { // Shouldn't require "self.", the closure is obviously @noescape. _ = { return ivar }() } final var ivar = 42 } // Reduced example from XCTest overlay, involves a TupleShuffleExpr public func XCTAssertTrue(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { } public func XCTAssert(_ expression: @autoclosure () -> Bool, _ message: String = "", file: StaticString = #file, line: UInt = #line) -> Void { XCTAssertTrue(expression, message, file: file, line: line); } /// SR-770 - Currying and `noescape`/`rethrows` don't work together anymore func curriedFlatMap<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-error 1{{unknown attribute 'noescape'}} return { f in x.flatMap(f) } } func curriedFlatMap2<A, B>(_ x: [A]) -> (@noescape (A) -> [B]) -> [B] { // expected-error {{unknown attribute 'noescape'}} return { (f : @noescape (A) -> [B]) in x.flatMap(f) } } func bad(_ a : @escaping (Int)-> Int) -> Int { return 42 } func escapeNoEscapeResult(_ x: [Int]) -> (@noescape (Int) -> Int) -> Int { // expected-error{{unknown attribute 'noescape'}} return { f in bad(f) } } // SR-824 - @noescape for Type Aliased Closures // // Old syntax -- @noescape is the default, and is redundant typealias CompletionHandlerNE = @noescape (_ success: Bool) -> () // expected-error{{unknown attribute 'noescape'}} // Explicit @escaping is not allowed here typealias CompletionHandlerE = @escaping (_ success: Bool) -> () // expected-error{{@escaping attribute may only be used in function parameter position}} {{32-42=}} // No @escaping -- it's implicit from context typealias CompletionHandler = (_ success: Bool) -> () var escape : CompletionHandlerNE var escapeOther : CompletionHandler func doThing1(_ completion: (_ success: Bool) -> ()) { escape = completion } func doThing2(_ completion: CompletionHandlerNE) { escape = completion } func doThing3(_ completion: CompletionHandler) { escape = completion } func doThing4(_ completion: @escaping CompletionHandler) { escapeOther = completion } // <rdar://problem/19997680> @noescape doesn't work on parameters of function type func apply<T, U>(_ f: @noescape (T) -> U, g: @noescape (@noescape (T) -> U) -> U) -> U { // expected-error@-1 2{{unknown attribute 'noescape'}} return g(f) } // <rdar://problem/19997577> @noescape cannot be applied to locals, leading to duplication of code enum r19997577Type { case Unit case Function(() -> r19997577Type, () -> r19997577Type) case Sum(() -> r19997577Type, () -> r19997577Type) func reduce<Result>(_ initial: Result, _ combine: @noescape (Result, r19997577Type) -> Result) -> Result { // expected-error 1{{unknown attribute 'noescape'}} let binary: @noescape (r19997577Type, r19997577Type) -> Result = { combine(combine(combine(initial, self), $0), $1) } // expected-error{{unknown attribute 'noescape'}} switch self { case .Unit: return combine(initial, self) case let .Function(t1, t2): return binary(t1(), t2()) case let .Sum(t1, t2): return binary(t1(), t2()) } } } // type attribute and decl attribute func noescapeD(@noescape f: @escaping () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}} func noescapeT(f: @noescape () -> Bool) {} // expected-error{{unknown attribute 'noescape'}} func noescapeG<T>(@noescape f: () -> T) {} // expected-error{{attribute can only be applied to types, not declarations}} func autoclosureD(@autoclosure f: () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}} func autoclosureT(f: @autoclosure () -> Bool) {} // ok func autoclosureG<T>(@autoclosure f: () -> T) {} // expected-error{{attribute can only be applied to types, not declarations}} func noescapeD_noescapeT(@noescape f: @noescape () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}} // expected-error@-1{{unknown attribute 'noescape'}} func autoclosureD_noescapeT(@autoclosure f: @noescape () -> Bool) {} // expected-error {{attribute can only be applied to types, not declarations}} // expected-error@-1{{unknown attribute 'noescape'}}
apache-2.0
3a2d2e7c8d5d86c4784e4b6d4d3f0b38
58.497093
453
0.668833
3.973403
false
false
false
false
goaairlines/capetown-ios
capetown/Assembly/UIAssembly.swift
1
2007
// // UIAssembly.swift // capetown // // Created by Alex Berger on 1/27/16. // Copyright © 2016 goa airlines. All rights reserved. // import Swinject enum UIAssemblyError: ErrorType { case UIAssemblyMissing } class UIAssembly: AssemblyType { func assemble(container: Container) { container.register(UIRouter.self) { resolver in return UIRouter() } .inObjectScope(.Container) .initCompleted { resolver, router in router.container = container router.rootViewController = resolver.resolve(ConverterVC.self) } assembleConverter(container) } func assembleConverter(container: Container) { container.register(ConverterVC.self) { resolver in let converterVC = ConverterVC() converterVC.currencyConverter = resolver.resolve(CurrencyConverter.self) converterVC.converterView = resolver.resolve(ConverterView.self) converterVC.keyboardView = resolver.resolve(KeyboardView.self) return converterVC } container.register(CurrencyConverter.self) { _ in CurrencyConverter() } container.register(ConverterView.self) { _ in let fromCurrency = Currency(id: Currencies.EUR, name: "Euro", rate: 1.0) let toCurrency = Currency(id: Currencies.VND, name: "Vietnamese Dong", rate: 24843.90) return ConverterView(fromCurrency: fromCurrency, toCurrency: toCurrency) } container.register(KeyboardView.self) { resolver in let keyboardView = KeyboardView(frame: CGRectZero) keyboardView.keyboardKeyContainer = resolver.resolve(KeyboardKeyContainer.self) return keyboardView } container.register(KeyboardKeyContainer.self) { _ in KeyboardKeyContainer.instanceFromNib() } } }
mit
91005bf85da9c0f86c57f48ec5c83bc9
29.393939
98
0.618146
5.065657
false
false
false
false
SampleLiao/WWDC
WWDC/SessionProgressView.swift
6
2730
// // SessionStatusView.swift // WWDC // // Created by Guilherme Rambo on 19/04/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa import QuartzCore @IBDesignable class SessionProgressView: NSView { @IBInspectable var favorite: Bool = false { didSet { setNeedsDisplayInRect(bounds) } } @IBInspectable var progress: Double = 0 { didSet { setNeedsDisplayInRect(bounds) } } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) if progress >= 1 { drawStarOutlineIfNeeded() return } if favorite { drawStarBezel() } else { drawCircularBezel() } NSGraphicsContext.currentContext()?.saveGraphicsState() Theme.WWDCTheme.fillColor.set() if progress == 0 { NSRectFill(bounds) } else if progress < 1 { NSBezierPath(rect: NSMakeRect(0, 0, round(NSWidth(bounds)/2), NSHeight(bounds))).addClip() NSRectFill(bounds) } NSGraphicsContext.currentContext()?.restoreGraphicsState() drawStarOutlineIfNeeded() } // MARK: Shape drawing private var insetBounds: NSRect { get { return NSInsetRect(bounds, 5.5, 5.5) } } private var insetBoundsForStar: NSRect { get { return NSInsetRect(bounds, 5, 5) } } private func drawCircularBezel() { let circle = NSBezierPath(ovalInRect: insetBounds) Theme.WWDCTheme.backgroundColor.set() circle.fill() Theme.WWDCTheme.fillColor.set() circle.stroke() circle.addClip() } private func drawStarBezel() { let ctx = NSGraphicsContext.currentContext()?.CGContext // mask the context to the star shape let mask = Theme.WWDCTheme.starImage CGContextClipToMask(ctx, insetBoundsForStar, mask) CGContextSetFillColorWithColor(ctx, Theme.WWDCTheme.backgroundColor.CGColor) CGContextFillRect(ctx, insetBoundsForStar) } private func drawStarOutlineIfNeeded() { if !favorite { return } let ctx = NSGraphicsContext.currentContext()?.CGContext // get star outline shape let outline = Theme.WWDCTheme.starOutlineImage // draw star outline CGContextClipToMask(ctx, insetBoundsForStar, outline) CGContextSetFillColorWithColor(ctx, Theme.WWDCTheme.fillColor.CGColor) CGContextFillRect(ctx, insetBoundsForStar) } }
bsd-2-clause
3f4120fe96538d4debf7ca59eb297cd7
25.259615
102
0.59011
5.384615
false
false
false
false
yasuo-/smartNews-clone
Pods/WBSegmentControl/Framework/WBSegmentControl/WBSegmentControl.swift
1
28358
// // CustomSegmentControl2.swift // TrafficSecretary // // Created by 王继荣 on 4/9/16. // Copyright © 2016 wonderbear. All rights reserved. // import UIKit public protocol WBSegmentControlDelegate { func segmentControl(_ segmentControl: WBSegmentControl, selectIndex newIndex: Int, oldIndex: Int) } public protocol WBSegmentContentProtocol { var type: WBSegmentType { get } } public protocol WBTouchViewDelegate { func didTouch(_ location: CGPoint) } public class WBSegmentControl: UIControl { // MARK: Configuration - Content public var segments: [WBSegmentContentProtocol] = [] { didSet { innerSegments = segments.map({ (content) -> WBInnerSegment in return WBInnerSegment(content: content) }) self.setNeedsLayout() if segments.count == 0 { selectedIndex = -1 } } } var innerSegments: [WBInnerSegment] = [] // MARK: Configuration - Interaction public var delegate: WBSegmentControlDelegate? public var selectedIndex: Int = -1 { didSet { if selectedIndex != oldValue && validIndex(selectedIndex) { selectedIndexChanged(selectedIndex, oldIndex: oldValue) delegate?.segmentControl(self, selectIndex: selectedIndex, oldIndex: oldValue) } } } public var selectedSegment: WBSegmentContentProtocol? { return validIndex(selectedIndex) ? segments[selectedIndex] : nil } // MARK: Configuration - Appearance public var style: WBSegmentIndicatorStyle = .rainbow public var nonScrollDistributionStyle: WBSegmentNonScrollDistributionStyle = .average public var enableSeparator: Bool = false public var separatorColor: UIColor = UIColor.black public var separatorWidth: CGFloat = 9 public var separatorEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 8, left: 4, bottom: 8, right: 4) public var enableSlideway: Bool = false public var slidewayHeight: CGFloat = 1 public var slidewayColor: UIColor = UIColor.lightGray public var enableAnimation: Bool = true public var animationDuration: TimeInterval = 0.15 public var segmentMinWidth: CGFloat = 50 public var segmentEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) public var segmentTextBold: Bool = true public var segmentTextFontSize: CGFloat = 12 public var segmentForegroundColor: UIColor = UIColor.gray public var segmentForegroundColorSelected: UIColor = UIColor.black // Settings - Cover public typealias CoverRange = WBSegmentIndicatorRange public var cover_range: CoverRange = .segment public var cover_opacity: Float = 0.2 public var cover_color: UIColor = UIColor.black // Settings - Strip public typealias StripRange = WBSegmentIndicatorRange public typealias StripLocation = WBSegmentIndicatorLocation public var strip_range: StripRange = .content public var strip_location: StripLocation = .down public var strip_color: UIColor = UIColor.orange public var strip_height: CGFloat = 3 // Settings - Rainbow public typealias RainbowLocation = WBSegmentIndicatorLocation public var rainbow_colors: [UIColor] = [] public var rainbow_height: CGFloat = 3 public var rainbow_roundCornerRadius: CGFloat = 4 public var rainbow_location: RainbowLocation = .down public var rainbow_outsideColor: UIColor = UIColor.gray // Settings - Arrow public typealias ArrowLocation = WBSegmentIndicatorLocation public var arrow_size: CGSize = CGSize(width: 6, height: 6) public var arrow_location: ArrowLocation = .down public var arrow_color: UIColor = UIColor.orange // Settings - ArrowStrip public typealias ArrowStripLocation = WBSegmentIndicatorLocation public typealias ArrowStripRange = WBSegmentIndicatorRange public var arrowStrip_location: ArrowStripLocation = .up public var arrowStrip_color: UIColor = UIColor.orange public var arrowStrip_arrowSize: CGSize = CGSize(width: 6, height: 6) public var arrowStrip_stripHeight: CGFloat = 2 public var arrowStrip_stripRange: ArrowStripRange = .content // MARK: Inner properties fileprivate var scrollView: UIScrollView! fileprivate var touchView: WBTouchView = WBTouchView() fileprivate var layerContainer: CALayer = CALayer() fileprivate var layerCover: CALayer = CALayer() fileprivate var layerStrip: CALayer = CALayer() fileprivate var layerArrow: CALayer = CALayer() fileprivate var segmentControlContentWidth: CGFloat { let sum = self.innerSegments.reduce(0, { (max_x, segment) -> CGFloat in return max(max_x, segment.segmentFrame.maxX) }) return sum + ((self.enableSeparator && self.style != .rainbow) ? self.separatorWidth / 2 : 0) } // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) scrollView = UIScrollView() self.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)) scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.layer.addSublayer(layerContainer) scrollView.addSubview(touchView) touchView.delegate = self } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Override methods override public func layoutSubviews() { super.layoutSubviews() layerContainer.sublayers?.removeAll() // Compute Segment Size for (index, segment) in self.innerSegments.enumerated() { segment.contentSize = self.segmentContentSize(segment) segment.segmentWidth = max(segment.contentSize.width + self.segmentEdgeInsets.left + self.segmentEdgeInsets.right, self.segmentMinWidth) segment.segmentFrame = self.segmentFrame(index) } // Adjust Control Content Size & Segment Size self.scrollView.contentSize = CGSize(width: self.segmentControlContentWidth, height: self.scrollView.frame.height) if self.scrollView.contentSize.width < self.scrollView.frame.width { switch self.nonScrollDistributionStyle { case .center: self.scrollView.contentInset = UIEdgeInsets(top: 0, left: (self.scrollView.frame.width - self.scrollView.contentSize.width) / 2, bottom: 0, right: 0) case .left: self.scrollView.contentInset = UIEdgeInsets.zero case .right: self.scrollView.contentInset = UIEdgeInsets(top: 0, left: self.scrollView.frame.width - self.scrollView.contentSize.width, bottom: 0, right: 0) case .average: self.scrollView.contentInset = UIEdgeInsets.zero self.scrollView.contentSize = self.scrollView.frame.size var averageWidth: CGFloat = (self.scrollView.frame.width - (self.enableSeparator && self.style != .rainbow ? CGFloat(self.innerSegments.count) * self.separatorWidth : 0)) / CGFloat(self.innerSegments.count) let largeSegments = self.innerSegments.filter({ (segment) -> Bool in return segment.segmentWidth >= averageWidth }) let smallSegments = self.innerSegments.filter({ (segment) -> Bool in return segment.segmentWidth < averageWidth }) let sumLarge = largeSegments.reduce(0, { (total, segment) -> CGFloat in return total + segment.segmentWidth }) averageWidth = (self.scrollView.frame.width - (self.enableSeparator && self.style != .rainbow ? CGFloat(self.innerSegments.count) * self.separatorWidth : 0) - sumLarge) / CGFloat(smallSegments.count) for segment in smallSegments { segment.segmentWidth = averageWidth } for (index, segment) in self.innerSegments.enumerated() { segment.segmentFrame = self.segmentFrame(index) segment.segmentFrame.origin.x += self.separatorWidth / 2 } } } else { self.scrollView.contentInset = UIEdgeInsets.zero } // Add Touch View touchView.frame = CGRect(origin: CGPoint.zero, size: self.scrollView.contentSize) // Add Segment SubLayers for (index, segment) in self.innerSegments.enumerated() { let content_x = segment.segmentFrame.origin.x + (segment.segmentFrame.width - segment.contentSize.width) / 2 let content_y = (self.scrollView.frame.height - segment.contentSize.height) / 2 let content_frame = CGRect(x: content_x, y: content_y, width: segment.contentSize.width, height: segment.contentSize.height) // Add Decoration Layer switch self.style { case .rainbow: let layerStrip = CALayer() layerStrip.frame = CGRect(x: segment.segmentFrame.origin.x, y: index == self.selectedIndex ? 0 : segment.segmentFrame.height - self.rainbow_height, width: segment.segmentFrame.width, height: index == self.selectedIndex ? self.scrollView.frame.height : self.rainbow_height) if self.rainbow_colors.isEmpty == false { layerStrip.backgroundColor = self.rainbow_colors[index % self.rainbow_colors.count].cgColor } layerContainer.addSublayer(layerStrip) self.switchRoundCornerForLayer(layerStrip, isRoundCorner: index == self.selectedIndex) segment.layerStrip = layerStrip default: break } // Add Content Layer switch segment.content.type { case let .text(text): let layerText = CATextLayer() layerText.string = text let font = segmentTextBold ? UIFont.boldSystemFont(ofSize: self.segmentTextFontSize) : UIFont.systemFont(ofSize: self.segmentTextFontSize) layerText.font = CGFont(NSString(string:font.fontName)) layerText.fontSize = font.pointSize layerText.frame = content_frame layerText.alignmentMode = kCAAlignmentCenter layerText.truncationMode = kCATruncationEnd layerText.contentsScale = UIScreen.main.scale layerText.foregroundColor = index == self.selectedIndex ? self.segmentForegroundColorSelected.cgColor : self.segmentForegroundColor.cgColor layerContainer.addSublayer(layerText) segment.layerText = layerText case let .icon(icon): let layerIcon = CALayer() let image = icon layerIcon.frame = content_frame layerIcon.contents = image.cgImage layerContainer.addSublayer(layerIcon) segment.layerIcon = layerIcon } } // Add Indicator Layer let initLayerSeparator = { [unowned self] in let layerSeparator = CALayer() layerSeparator.frame = CGRect(x: 0, y: 0, width: self.scrollView.contentSize.width, height: self.scrollView.contentSize.height) layerSeparator.backgroundColor = self.separatorColor.cgColor let layerMask = CAShapeLayer() layerMask.fillColor = UIColor.white.cgColor let maskPath = UIBezierPath() for (index, segment) in self.innerSegments.enumerated() { index < self.innerSegments.count - 1 ? maskPath.append(UIBezierPath(rect: CGRect(x: segment.segmentFrame.maxX + self.separatorEdgeInsets.left, y: self.separatorEdgeInsets.top, width: self.separatorWidth - self.separatorEdgeInsets.left - self.separatorEdgeInsets.right, height: self.scrollView.frame.height - self.separatorEdgeInsets.top - self.separatorEdgeInsets.bottom))) : () } layerMask.path = maskPath.cgPath layerSeparator.mask = layerMask self.layerContainer.addSublayer(layerSeparator) } let initLayerCover = { [unowned self] in self.layerCover.frame = self.indicatorCoverFrame(self.selectedIndex) self.layerCover.backgroundColor = self.cover_color.cgColor self.layerCover.opacity = self.cover_opacity self.layerContainer.addSublayer(self.layerCover) } let addLayerOutside = { [unowned self] in let outsideLayerLeft = CALayer() outsideLayerLeft.frame = CGRect(x: -1 * self.scrollView.frame.width, y: self.scrollView.frame.height - self.rainbow_height, width: self.scrollView.frame.width, height: self.rainbow_height) outsideLayerLeft.backgroundColor = self.rainbow_outsideColor.cgColor self.layerContainer.addSublayer(outsideLayerLeft) let outsideLayerRight = CALayer() outsideLayerRight.frame = CGRect(x: self.scrollView.contentSize.width, y: self.scrollView.frame.height - self.rainbow_height, width: self.scrollView.frame.width, height: self.rainbow_height) outsideLayerRight.backgroundColor = self.rainbow_outsideColor.cgColor self.layerContainer.addSublayer(outsideLayerRight) } let addLayerSlideway = { [unowned self] (slidewayPosition: CGFloat, slidewayHeight: CGFloat, slidewayColor: UIColor) in let layerSlideway = CALayer() layerSlideway.frame = CGRect(x: -1 * self.scrollView.frame.width, y: slidewayPosition - slidewayHeight / 2, width: self.scrollView.contentSize.width + self.scrollView.frame.width * 2, height: slidewayHeight) layerSlideway.backgroundColor = slidewayColor.cgColor self.layerContainer.addSublayer(layerSlideway) } let initLayerStrip = { [unowned self] (stripFrame: CGRect, stripColor: UIColor) in self.layerStrip.frame = stripFrame self.layerStrip.backgroundColor = stripColor.cgColor self.layerContainer.addSublayer(self.layerStrip) } let initLayerArrow = { [unowned self] (arrowFrame: CGRect, arrowLocation: WBSegmentIndicatorLocation, arrowColor: UIColor) in self.layerArrow.frame = arrowFrame self.layerArrow.backgroundColor = arrowColor.cgColor let layerMask = CAShapeLayer() layerMask.fillColor = UIColor.white.cgColor let maskPath = UIBezierPath() var pointA = CGPoint.zero var pointB = CGPoint.zero var pointC = CGPoint.zero switch arrowLocation { case .up: pointA = CGPoint(x: 0, y: 0) pointB = CGPoint(x: self.layerArrow.bounds.width, y: 0) pointC = CGPoint(x: self.layerArrow.bounds.width / 2, y: self.layerArrow.bounds.height) case .down: pointA = CGPoint(x: 0, y: self.layerArrow.bounds.height) pointB = CGPoint(x: self.layerArrow.bounds.width, y: self.layerArrow.bounds.height) pointC = CGPoint(x: self.layerArrow.bounds.width / 2, y: 0) } maskPath.move(to: pointA) maskPath.addLine(to: pointB) maskPath.addLine(to: pointC) maskPath.close() layerMask.path = maskPath.cgPath self.layerArrow.mask = layerMask self.layerContainer.addSublayer(self.layerArrow) } switch self.style { case .cover: initLayerCover() self.enableSeparator ? initLayerSeparator() : () case .strip: let strip_frame = self.indicatorStripFrame(self.selectedIndex, stripHeight: self.strip_height, stripLocation: self.strip_location, stripRange: self.strip_range) self.enableSlideway ? addLayerSlideway(strip_frame.midY, self.slidewayHeight, self.slidewayColor) : () initLayerStrip(strip_frame, self.strip_color) self.enableSeparator ? initLayerSeparator() : () case .rainbow: addLayerOutside() case .arrow: let arrow_frame = self.indicatorArrowFrame(self.selectedIndex, arrowLocation: self.arrow_location, arrowSize: self.arrow_size) var slideway_y: CGFloat = 0 switch self.arrow_location { case .up: slideway_y = arrow_frame.origin.y + self.slidewayHeight / 2 case .down: slideway_y = arrow_frame.maxY - self.slidewayHeight / 2 } self.enableSlideway ? addLayerSlideway(slideway_y, self.slidewayHeight, self.slidewayColor) : () initLayerArrow(arrow_frame, self.arrow_location, self.arrow_color) self.enableSeparator ? initLayerSeparator() : () case .arrowStrip: let strip_frame = self.indicatorStripFrame(self.selectedIndex, stripHeight: self.arrowStrip_stripHeight, stripLocation: self.arrowStrip_location, stripRange: self.arrowStrip_stripRange) self.enableSlideway ? addLayerSlideway(strip_frame.midY, self.slidewayHeight, self.slidewayColor) : () initLayerStrip(strip_frame, self.arrowStrip_color) let arrow_frame = self.indicatorArrowFrame(self.selectedIndex, arrowLocation: self.arrowStrip_location, arrowSize: self.arrowStrip_arrowSize) initLayerArrow(arrow_frame, self.arrowStrip_location, self.arrowStrip_color) self.enableSeparator ? initLayerSeparator() : () } } // MARK: Custom methods func selectedIndexChanged(_ newIndex: Int, oldIndex: Int) { if self.enableAnimation && validIndex(oldIndex) { CATransaction.begin() CATransaction.setAnimationDuration(self.animationDuration) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)) CATransaction.setCompletionBlock({ [unowned self] in switch self.style { case .rainbow: if self.validIndex(oldIndex) { self.switchRoundCornerForLayer(self.innerSegments[oldIndex].layerStrip!, isRoundCorner: false) } default: break } }) self.scrollView.contentSize.width > self.scrollView.frame.width ? self.scrollToSegment(newIndex) : () self.didSelectedIndexChanged(newIndex, oldIndex: oldIndex) CATransaction.commit() } else { self.didSelectedIndexChanged(newIndex, oldIndex: oldIndex) } self.sendActions(for: .valueChanged) } func didSelectedIndexChanged(_ newIndex: Int, oldIndex: Int) { switch style { case .cover: self.layerCover.actions = nil self.layerCover.frame = self.indicatorCoverFrame(newIndex) case .strip: self.layerStrip.actions = nil self.layerStrip.frame = self.indicatorStripFrame(newIndex, stripHeight: self.strip_height, stripLocation: self.strip_location, stripRange: self.strip_range) case .rainbow: if validIndex(oldIndex), let old_StripLayer = self.innerSegments[oldIndex].layerStrip { let old_StripFrame = old_StripLayer.frame old_StripLayer.frame = CGRect(x: old_StripFrame.origin.x, y: self.scrollView.frame.height - self.strip_height, width: old_StripFrame.width, height: self.strip_height) } if let new_StripLayer = self.innerSegments[newIndex].layerStrip { let new_StripFrame = new_StripLayer.frame new_StripLayer.frame = CGRect(x: new_StripFrame.origin.x, y: 0, width: new_StripFrame.width, height: self.scrollView.frame.height) self.switchRoundCornerForLayer(new_StripLayer, isRoundCorner: true) } case .arrow: self.layerArrow.actions = nil self.layerArrow.frame = self.indicatorArrowFrame(newIndex, arrowLocation: self.arrow_location, arrowSize: self.arrow_size) case .arrowStrip: self.layerStrip.actions = nil self.layerStrip.frame = self.indicatorStripFrame(newIndex, stripHeight: self.arrowStrip_stripHeight, stripLocation: self.arrowStrip_location, stripRange: self.arrowStrip_stripRange) self.layerArrow.actions = nil self.layerArrow.frame = self.indicatorArrowFrame(newIndex, arrowLocation: self.arrowStrip_location, arrowSize: self.arrowStrip_arrowSize) } if validIndex(oldIndex) { switch self.innerSegments[oldIndex].content.type { case .text: if let old_contentLayer = self.innerSegments[oldIndex].layerText as? CATextLayer { old_contentLayer.foregroundColor = self.segmentForegroundColor.cgColor } default: break } } switch self.innerSegments[newIndex].content.type { case .text: if let new_contentLayer = self.innerSegments[newIndex].layerText as? CATextLayer { new_contentLayer.foregroundColor = self.segmentForegroundColorSelected.cgColor } default: break } } func switchRoundCornerForLayer(_ layer: CALayer, isRoundCorner: Bool) { if isRoundCorner { let layerMask = CAShapeLayer() layerMask.fillColor = UIColor.white.cgColor layerMask.path = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: layer.frame.size), byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: self.rainbow_roundCornerRadius, height: self.rainbow_roundCornerRadius)).cgPath layer.mask = layerMask } else { layer.mask = nil } } func scrollToSegment(_ index: Int) { let segmentFrame = self.innerSegments[index].segmentFrame let targetRect = CGRect(x: segmentFrame.origin.x - (self.scrollView.frame.width - segmentFrame.width) / 2, y: 0, width: self.scrollView.frame.width, height: self.scrollView.frame.height) self.scrollView.scrollRectToVisible(targetRect, animated: true) } func segmentContentSize(_ segment: WBInnerSegment) -> CGSize { var size = CGSize.zero switch segment.content.type { case let .text(text): size = (text as NSString).size(attributes: [ NSFontAttributeName: segmentTextBold ? UIFont.boldSystemFont(ofSize: self.segmentTextFontSize) : UIFont.systemFont(ofSize: self.segmentTextFontSize) ]) case let .icon(icon): size = icon.size } return CGSize(width: ceil(size.width), height: ceil(size.height)) } func segmentFrame(_ index: Int) -> CGRect { var segmentOffset: CGFloat = (self.enableSeparator && self.style != .rainbow ? self.separatorWidth / 2 : 0) for (idx, segment) in self.innerSegments.enumerated() { if idx == index { break } else { segmentOffset += segment.segmentWidth + (self.enableSeparator && self.style != .rainbow ? self.separatorWidth : 0) } } return CGRect(x: segmentOffset , y: 0, width: self.innerSegments[index].segmentWidth, height: self.scrollView.frame.height) } func indicatorCoverFrame(_ index: Int) -> CGRect { if validIndex(index) { var box_x: CGFloat = self.innerSegments[index].segmentFrame.origin.x var box_width: CGFloat = 0 switch self.cover_range { case .content: box_x += (self.innerSegments[index].segmentWidth - self.innerSegments[index].contentSize.width) / 2 box_width = self.innerSegments[index].contentSize.width case .segment: box_width = self.innerSegments[index].segmentWidth } return CGRect(x: box_x, y: 0, width: box_width, height: self.scrollView.frame.height) } else { return CGRect.zero } } func indicatorStripFrame(_ index: Int, stripHeight: CGFloat, stripLocation: WBSegmentIndicatorLocation, stripRange: WBSegmentIndicatorRange) -> CGRect { if validIndex(index) { var strip_x: CGFloat = self.innerSegments[index].segmentFrame.origin.x var strip_y: CGFloat = 0 var strip_width: CGFloat = 0 switch stripLocation { case .down: strip_y = self.innerSegments[index].segmentFrame.height - stripHeight case .up: strip_y = 0 } switch stripRange { case .content: strip_width = self.innerSegments[index].contentSize.width strip_x += (self.innerSegments[index].segmentWidth - strip_width) / 2 case .segment: strip_width = self.innerSegments[index].segmentWidth } return CGRect(x: strip_x, y: strip_y, width: strip_width, height: stripHeight) } else { return CGRect.zero } } func indicatorArrowFrame(_ index: Int, arrowLocation: WBSegmentIndicatorLocation, arrowSize: CGSize) -> CGRect { if validIndex(index) { let arrow_x: CGFloat = self.innerSegments[index].segmentFrame.origin.x + (self.innerSegments[index].segmentFrame.width - arrowSize.width) / 2 var arrow_y: CGFloat = 0 switch arrowLocation { case .up: arrow_y = 0 case .down: arrow_y = self.innerSegments[index].segmentFrame.height - self.arrow_size.height } return CGRect(x: arrow_x, y: arrow_y, width: arrowSize.width, height: arrowSize.height) } else { return CGRect.zero } } func indexForTouch(_ location: CGPoint) -> Int { var touch_offset_x = location.x var touch_index = 0 for (index, segment) in self.innerSegments.enumerated() { touch_offset_x -= segment.segmentWidth + (self.enableSeparator && self.style != .rainbow ? self.separatorWidth : 0) if touch_offset_x < 0 { touch_index = index break } } return touch_index } func validIndex(_ index: Int) -> Bool { return index >= 0 && index < segments.count } } extension WBSegmentControl: WBTouchViewDelegate { public func didTouch(_ location: CGPoint) { selectedIndex = indexForTouch(location) } } class WBInnerSegment { let content: WBSegmentContentProtocol var segmentFrame: CGRect = CGRect.zero var segmentWidth: CGFloat = 0 var contentSize: CGSize = CGSize.zero var layerText: CALayer! var layerIcon: CALayer! var layerStrip: CALayer! init(content: WBSegmentContentProtocol) { self.content = content } } public enum WBSegmentType { case text(String) case icon(UIImage) } public enum WBSegmentIndicatorStyle { case cover, strip, rainbow, arrow, arrowStrip } public enum WBSegmentIndicatorLocation { case up, down } public enum WBSegmentIndicatorRange { case content, segment } public enum WBSegmentNonScrollDistributionStyle { case center, left, right, average } class WBTouchView: UIView { var delegate: WBTouchViewDelegate? override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { delegate?.didTouch(touch.location(in: self)) } } }
mit
850f2b85b7d8bd19319f568c762d2764
46.409699
394
0.648407
4.906715
false
false
false
false
lukaszwas/mcommerce-api
Sources/App/Models/CategoryWithProducts.swift
1
1834
import Vapor import FluentProvider import HTTP final class CategoryWithProducts: Model { static let name = "Cat" let storage = Storage() // Columns var name: String var description: String var parentId: Identifier? var parent: Parent<CategoryWithProducts, Category> { return parent(id: parentId) } var products: Children<CategoryWithProducts, Product> { return children(foreignIdKey: Product.categoryIdKey) } // Init init( name: String, description: String, parentId: Identifier? ) { self.name = name self.description = description; self.parentId = parentId } init(row: Row) throws { name = try row.get(Category.nameKey) description = try row.get(Category.descriptionKey) parentId = try row.get(Category.parentIdKey) } // Serialize func makeRow() throws -> Row { var row = Row() try row.set(Category.nameKey, name) try row.set(Category.descriptionKey, description) try row.set(Category.parentIdKey, parentId) return row } } // Json extension CategoryWithProducts: JSONConvertible { convenience init(json: JSON) throws { try self.init( name: json.get(Category.nameKey), description: json.get(Category.descriptionKey), parentId: json.get(Category.parentIdKey) ) } func makeJSON() throws -> JSON { var json = JSON() try json.set(Category.idKey, id) try json.set(Category.nameKey, name) try json.set(Category.descriptionKey, description) try json.set(Category.parentIdKey, parentId) try json.set("test", "test") return json } }
mit
aac9de91553a7d1dbae6f6fecbaa53f7
24.123288
60
0.597601
4.643038
false
false
false
false
lukejmann/FBLA2017
Pods/Instructions/Sources/Managers/FlowManager.swift
1
9706
// FlowManager.swift // // Copyright (c) 2016 Frédéric Maquin <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class FlowManager { // MARK: - Internal Properties /// `true` if coach marks are curently being displayed, `false` otherwise. public var started: Bool { return currentIndex > -1 } /// Sometimes, the chain of coach mark display can be paused /// to let animations be performed. `true` to pause the execution, /// `false` otherwise. private(set) open var paused = false internal unowned let coachMarksViewController: CoachMarksViewController internal weak var dataSource: CoachMarksControllerProxyDataSource? /// An object implementing the delegate data source protocol, /// which methods will be called at various points. internal weak var delegate: CoachMarksControllerProxyDelegate? /// Reference to the currently displayed coach mark, supplied by the `datasource`. internal var currentCoachMark: CoachMark? /// The total number of coach marks, supplied by the `datasource`. private var numberOfCoachMarks = 0 /// Since changing size calls asynchronous completion blocks, /// we might end up firing multiple times the methods adding coach /// marks to the view. To prevent that from happening we use the guard /// property. /// /// Everything is normally happening on the main thread, atomicity should /// not be a problem. Plus, a size change is a very long process compared to /// subview addition. /// /// This property will be checked multiple time during the process of /// showing coach marks and can abort the normal flow. This, it's also /// used to prevent the normal flow when calling `stop(imediately:)`. /// /// `true` when the controller is performing a size change, `false` otherwise. private var disableFlow = false /// This property is much like `disableFlow`, except it's used only to /// prevent a coach mark from being shown multiple times (in case the user /// is tapping too fast. /// /// `true` if a new coach mark can be shown, `false` otherwise. private var canShowCoachMark = true /// The index (in `coachMarks`) of the coach mark being currently displayed. private var currentIndex = -1 init(coachMarksViewController: CoachMarksViewController) { self.coachMarksViewController = coachMarksViewController } internal func startFlow(withNumberOfCoachMarks numberOfCoachMarks: Int) { disableFlow = false self.numberOfCoachMarks = numberOfCoachMarks coachMarksViewController.prepareToShowCoachMarks { self.showNextCoachMark() } } public func resume() { if started && paused { paused = false createAndShowCoachMark(false) } } public func pause() { paused = true } internal func reset() { currentIndex = -1 paused = false canShowCoachMark = true //disableFlow will be set by startFlow, to enable quick stop. } /// Stop displaying the coach marks and perform some cleanup. /// /// - Parameter immediately: `true` to hide immediately with no animation /// `false` otherwise. /// - Parameter userDidSkip: `true` when the user canceled the flow, `false` otherwise. /// - Parameter shouldCallDelegate: `true` to notify the delegate that the flow /// was stop. internal func stopFlow(immediately: Bool = false, userDidSkip skipped: Bool = false, shouldCallDelegate: Bool = true ) { reset() let animationBlock = { () -> Void in self.coachMarksViewController.overlayView.alpha = 0.0 self.coachMarksViewController.skipView?.asView?.alpha = 0.0 self.coachMarksViewController.currentCoachMarkView?.alpha = 0.0 } let completionBlock = {(finished: Bool) -> Void in self.coachMarksViewController.detachFromParentViewController() if shouldCallDelegate { self.delegate?.didEndShowingBySkipping(skipped) } } if immediately { disableFlow = true animationBlock() completionBlock(true) } else { UIView.animate(withDuration: coachMarksViewController.overlayView.fadeAnimationDuration, animations: animationBlock, completion: completionBlock) } } internal func showNextCoachMark(hidePrevious: Bool = true) { if disableFlow || paused || !canShowCoachMark { return } canShowCoachMark = false currentIndex += 1 if currentIndex == 0 { createAndShowCoachMark() return } if let currentCoachMark = currentCoachMark { delegate?.willHide(coachMark: currentCoachMark, at: currentIndex - 1) } if hidePrevious { guard let currentCoachMark = currentCoachMark else { return } coachMarksViewController.hide(coachMark: currentCoachMark) { self.delegate?.didHide(coachMark: self.currentCoachMark!, at: self.currentIndex) self.showOrStop() } } else { showOrStop() } } internal func showOrStop() { if self.currentIndex < self.numberOfCoachMarks { self.createAndShowCoachMark() } else { self.stopFlow() } } /// Ask the datasource, create the coach mark and display it. Also /// notifies the delegate. When this method is called during a size change, /// the delegate is not notified. /// /// - Parameter shouldCallDelegate: `true` to call delegate methods, `false` otherwise. internal func createAndShowCoachMark(_ shouldCallDelegate: Bool = true) { if disableFlow { return } guard delegate?.willLoadCoachMark(at: currentIndex) ?? false else { canShowCoachMark = true showNextCoachMark(hidePrevious: false) return } // Retrieves the current coach mark structure from the datasource. // It can't be nil, that's why we'll force unwrap it everywhere. currentCoachMark = self.dataSource!.coachMark(at: currentIndex) // The coach mark will soon show, we notify the delegate, so it // can perform some things and, if required, update the coach mark structure. if shouldCallDelegate { self.delegate?.willShow(coachMark: &currentCoachMark!, at: currentIndex) } // The delegate might have paused the flow, he check whether or not it's // the case. if !self.paused { if coachMarksViewController.instructionsRootView.bounds.isEmpty { print("The overlay view added to the window has empty bounds, " + "Instructions will stop.") self.stopFlow() return } coachMarksViewController.show(coachMark: &currentCoachMark!, at: currentIndex) { self.canShowCoachMark = true if shouldCallDelegate { self.delegate?.didShow(coachMark: self.currentCoachMark!, at: self.currentIndex) } } } } /// Show the next specified Coach Mark. /// /// - Parameter numberOfCoachMarksToSkip: the number of coach marks /// to skip. open func showNext(numberOfCoachMarksToSkip numberToSkip: Int = 0) { if !self.started || !canShowCoachMark { return } if numberToSkip < 0 { print("showNext: The specified number of coach marks to skip" + "was negative, nothing to do.") return } currentIndex += numberToSkip showNextCoachMark(hidePrevious: true) } } extension FlowManager: CoachMarksViewControllerDelegate { func didTap(coachMarkView: CoachMarkView?) { showNextCoachMark() } func didTap(skipView: CoachMarkSkipView?) { stopFlow(immediately: false, userDidSkip: true, shouldCallDelegate: true) } func willTransition() { coachMarksViewController.prepareForSizeTransition() if let coachMark = currentCoachMark { coachMarksViewController.hide(coachMark: coachMark, animated: false) } } func didTransition() { coachMarksViewController.restoreAfterSizeTransitionDidComplete() createAndShowCoachMark(false) } }
mit
de871c4d940f3e9b9dd7c5285ae59389
36.612403
100
0.648083
5.3732
false
false
false
false
johnno1962d/swift
test/Interpreter/generics.swift
3
2648
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test struct BigStruct { var a,b,c,d,e,f,g,h:Int } // FIXME: missing symbol for Object destructor? //class SomeClass : Object { } func id<T>(_ x: T) -> T { return x } var int = id(1) var bigStruct = id(BigStruct(a: 1, b: 2,c: 3, d: 4, e: 5, f: 6, g: 7, h: 8)) //var someClass = SomeClass() //var someClass2 = id(someClass) func print(_ bs: BigStruct) { // FIXME: typechecker is too slow to handle this as an interpolated literal print("BigStruct(", terminator: "") print(bs.a, terminator: "") print(", ", terminator: "") print(bs.b, terminator: "") print(", ", terminator: "") print(bs.c, terminator: "") print(", ", terminator: "") print(bs.d, terminator: "") print(", ", terminator: "") print(bs.e, terminator: "") print(", ", terminator: "") print(bs.f, terminator: "") print(", ", terminator: "") print(bs.g, terminator: "") print(", ", terminator: "") print(bs.h, terminator: "") print(")") } // CHECK: 1 print(int) // CHECK: BigStruct(1, 2, 3, 4, 5, 6, 7, 8) print(bigStruct) // FIXME: missing symbol for Object destructor? // C/HECK: true //print(someClass === someClass2) //===---- // Check overload resolution of generic functions. //===---- protocol P1 {} protocol P2 : P1 {} protocol P3 : P2 {} struct S1 : P1 {} struct S2 : P2 {} struct S3 : P3 {} func foo1<T : P1>(_ x: T) { print("P1") } func foo1<T : P2>(_ x: T) { print("P2") } func foo1<T : P3>(_ x: T) { print("P3") } func foo2<T : P1>(_ x: T) { print("P1") } func foo2<T : P2>(_ x: T) { print("P2") } func foo3<T : P1>(_ x: T) { print("P1") } func foo3<T : P3>(_ x: T) { print("P3") } func foo4<T : P3, U : P1>(_ x: T, _ y: U) { print("P3, P1") } func foo4<T : P3, U : P3>(_ x: T, _ y: U) { print("P3, P3") } func checkOverloadResolution() { print("overload resolution:") // CHECK-LABEL: overload resolution foo1(S1()) // CHECK-NEXT: P1 foo1(S2()) // CHECK-NEXT: P2 foo1(S3()) // CHECK-NEXT: P3 foo2(S1()) // CHECK-NEXT: P1 foo2(S2()) // CHECK-NEXT: P2 foo2(S3()) // CHECK-NEXT: P2 foo3(S1()) // CHECK-NEXT: P1 foo3(S2()) // CHECK-NEXT: P1 foo3(S3()) // CHECK-NEXT: P3 foo4(S3(), S1()) // CHECK-NEXT: P3, P1 foo4(S3(), S2()) // CHECK-NEXT: P3, P1 foo4(S3(), S3()) // CHECK-NEXT: P3, P3 } checkOverloadResolution() class Base { var v = 0 required init() {} func map() { v = 1 } } class D1 : Base { required init() {} override func map() { v = 2 } } func parse<T:Base>() -> T { let inst = T() inst.map() return inst } var m : D1 = parse() print(m.v) // CHECK: 2
apache-2.0
a2637e52c5c891b9085c11108847ce2f
20.884298
77
0.560423
2.672048
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/OldTalkPageTopicCell.swift
1
6249
import UIKit class OldTalkPageTopicCell: CollectionViewCell { private let titleLabel = UILabel() private let unreadView = UIView() private let dividerView = UIView(frame: .zero) private let chevronImageView = UIImageView(frame: .zero) private var isDeviceRTL: Bool { return effectiveUserInterfaceLayoutDirection == .rightToLeft } var semanticContentAttributeOverride: UISemanticContentAttribute = .unspecified { didSet { textAlignmentOverride = semanticContentAttributeOverride == .forceRightToLeft ? NSTextAlignment.right : NSTextAlignment.left titleLabel.semanticContentAttribute = semanticContentAttributeOverride } } private var textAlignmentOverride: NSTextAlignment = .left { didSet { titleLabel.textAlignment = textAlignmentOverride } } override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize { let adjustedMargins = UIEdgeInsets(top: layoutMargins.top + 5, left: layoutMargins.left + 5, bottom: layoutMargins.bottom + 5, right: layoutMargins.right + 5) let unreadIndicatorSideLength = CGFloat(11) let unreadIndicatorX = !isDeviceRTL ? adjustedMargins.left : size.width - adjustedMargins.right - unreadIndicatorSideLength let chevronSize = CGSize(width: 8, height: 14) let chevronX = !isDeviceRTL ? size.width - adjustedMargins.right - chevronSize.width : adjustedMargins.left let titleX = !isDeviceRTL ? unreadIndicatorX + unreadIndicatorSideLength + 15 : chevronX + chevronSize.width + 28 let titleMaxX = !isDeviceRTL ? size.width - adjustedMargins.right - chevronSize.width - 28 : size.width - adjustedMargins.right - unreadIndicatorSideLength - 15 let titleMaximumWidth = titleMaxX - titleX let titleOrigin = CGPoint(x: titleX, y: adjustedMargins.top) let titleLabelFrame = titleLabel.wmf_preferredFrame(at: titleOrigin, maximumWidth: titleMaximumWidth, alignedBy: semanticContentAttributeOverride, apply: apply) let finalHeight = adjustedMargins.top + titleLabelFrame.size.height + adjustedMargins.bottom if apply { dividerView.frame = CGRect(x: 0, y: finalHeight - 1, width: size.width, height: 1) unreadView.frame = CGRect(x: unreadIndicatorX, y: (finalHeight / 2) - (unreadIndicatorSideLength / 2), width: unreadIndicatorSideLength, height: unreadIndicatorSideLength) chevronImageView.frame = CGRect(x: chevronX, y: (finalHeight / 2) - (chevronSize.height / 2), width: chevronSize.width, height: chevronSize.height) titleLabel.textAlignment = textAlignmentOverride } return CGSize(width: size.width, height: finalHeight) } func configure(title: String, isRead: Bool = true) { unreadView.isHidden = isRead configureTitleLabel(title: title) configureAccessibility(title: title, isRead: isRead) } private func configureAccessibility(title: String, isRead: Bool) { let readAccessibilityText = CommonStrings.readStatusAccessibilityLabel let unreadAccessibilityText = CommonStrings.unreadStatusAccessibilityLabel let readPronounciationAccessibilityAttribute = WMFLocalizedString("talk-page-discussion-read-ipa-accessibility-attribute", value: "rɛd", comment: "Accessibility ipa pronounciation for indicating that a discussion's contents have been read.") let unreadPronounciationAccessibilityAttribute = WMFLocalizedString("talk-page-discussion-unread-ipa-accessibility-attribute", value: "ʌnˈrɛd", comment: "Accessibility ipa pronounciation for indicating that a discussion's contents have not been read.") let readAccessibilityAttributedString = NSAttributedString(string: readAccessibilityText, attributes: [NSAttributedString.Key.accessibilitySpeechIPANotation: readPronounciationAccessibilityAttribute]) let unreadAccessibilityAttributedString = NSAttributedString(string: unreadAccessibilityText, attributes: [NSAttributedString.Key.accessibilitySpeechIPANotation: unreadPronounciationAccessibilityAttribute]) let readUnreadAccessibilityAttributedString = isRead ? readAccessibilityAttributedString : unreadAccessibilityAttributedString let mutableAttributedString = NSMutableAttributedString(attributedString: readUnreadAccessibilityAttributedString) let titleAttributedString = NSAttributedString(string: "\(titleLabel.attributedText?.string ?? title). ") mutableAttributedString.insert(titleAttributedString, at: 0) accessibilityAttributedLabel = mutableAttributedString.copy() as? NSAttributedString accessibilityHint = WMFLocalizedString("talk-page-discussion-accessibility-hint", value: "Double tap to open discussion thread", comment: "Accessibility hint when user is on a discussion title cell.") } private func configureTitleLabel(title: String) { let attributedString = title.byAttributingHTML(with: .body, boldWeight: .semibold, matching: traitCollection, color: titleLabel.textColor, handlingSuperSubscripts: true, tagMapping: ["a": "b"]) titleLabel.attributedText = attributedString } override func setup() { chevronImageView.image = UIImage.wmf_imageFlipped(forRTLLayoutDirectionNamed: "chevron-right") unreadView.layer.cornerRadius = 5.5 contentView.addSubview(titleLabel) contentView.addSubview(dividerView) contentView.addSubview(unreadView) contentView.addSubview(chevronImageView) titleLabel.isAccessibilityElement = false isAccessibilityElement = true super.setup() } } extension OldTalkPageTopicCell: Themeable { func apply(theme: Theme) { titleLabel.textColor = theme.colors.primaryText setBackgroundColors(theme.colors.paperBackground, selected: theme.colors.baseBackground) dividerView.backgroundColor = theme.colors.border unreadView.backgroundColor = theme.colors.unreadIndicator chevronImageView.tintColor = theme.colors.secondaryText } }
mit
15bfc4201f6a4e11f36836495416b3aa
55.261261
260
0.728743
5.621062
false
false
false
false
bazelbuild/tulsi
src/Tulsi/ProjectEditorPackageManagerViewController.swift
1
8747
// Copyright 2016 The Tulsi Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Cocoa import TulsiGenerator /// View controller for the editor that allows selection of BUILD files and high level options. final class ProjectEditorPackageManagerViewController: NSViewController, NewProjectViewControllerDelegate { /// Indices into the Add/Remove SegmentedControl (as built by Interface Builder). private enum SegmentedControlButtonIndex: Int { case add = 0 case remove = 1 } @IBOutlet var packageArrayController: NSArrayController! @IBOutlet weak var addRemoveSegmentedControl: NSSegmentedControl! var newProjectSheet: NewProjectViewController! = nil private var newProjectNeedsSaveAs = false @objc dynamic var numSelectedPackagePaths: Int = 0 { didSet { let enableRemoveButton = numSelectedPackagePaths > 0 addRemoveSegmentedControl.setEnabled(enableRemoveButton, forSegment: SegmentedControlButtonIndex.remove.rawValue) } } deinit { NSObject.unbind(NSBindingName(rawValue: "numSelectedPackagePaths")) } override func loadView() { ValueTransformer.setValueTransformer(PackagePathValueTransformer(), forName: NSValueTransformerName(rawValue: "PackagePathValueTransformer")) super.loadView() bind(NSBindingName(rawValue: "numSelectedPackagePaths"), to: packageArrayController!, withKeyPath: "selectedObjects.@count", options: nil) } override func viewDidAppear() { super.viewDidAppear() let document = representedObject as! TulsiProjectDocument // Start the new project flow if the associated document is not linked to a project. if document.fileURL != nil || document.project != nil { return } newProjectSheet = NewProjectViewController() newProjectSheet.delegate = self // Present the NewProjectViewController as a sheet. // This is done via dispatch_async because we want it to happen after the window appearance // animation is complete. DispatchQueue.main.async(execute: { self.presentAsSheet(self.newProjectSheet) }) } @IBAction func didClickAddRemoveSegmentedControl(_ sender: NSSegmentedCell) { // Ignore mouse up messages. if sender.selectedSegment < 0 { return } guard let button = SegmentedControlButtonIndex(rawValue: sender.selectedSegment) else { assertionFailure("Unexpected add/remove button index \(sender.selectedSegment)") return } switch button { case .add: didClickAddBUILDFile(sender) case .remove: didClickRemoveSelectedBUILDFiles(sender) } } func didClickAddBUILDFile(_ sender: AnyObject?) { guard let document = self.representedObject as? TulsiProjectDocument, let workspacePath = document.workspaceRootURL?.path else { return } let panel = FilteredOpenPanel.filteredOpenPanel() { (_: AnyObject, url: URL) -> Bool in var isDir: AnyObject? var isPackage: AnyObject? do { try (url as NSURL).getResourceValue(&isDir, forKey: URLResourceKey.isDirectoryKey) try (url as NSURL).getResourceValue(&isPackage, forKey: URLResourceKey.isPackageKey) if let isDir = isDir as? NSNumber, let isPackage = isPackage as? NSNumber, !isPackage.boolValue { if isDir.boolValue { return true } let filename = url.lastPathComponent if filename == "BUILD" || filename == "BUILD.bazel" { // Prevent anything outside of the selected workspace. return url.path.hasPrefix(workspacePath) && !document.containsBUILDFileURL(url) } } } catch _ { // Treat any exception as an invalid URL. } return false } panel.prompt = NSLocalizedString("ProjectEditor_AddBUILDFilePrompt", comment: "Label for the button used to confirm adding the selected BUILD file to the Tulsi project.") panel.canChooseDirectories = false panel.beginSheetModal(for: self.view.window!) { value in if value == NSApplication.ModalResponse.OK { guard let URL = panel.url else { return } if !document.addBUILDFileURL(URL) { NSSound.beep() } } } } func didClickRemoveSelectedBUILDFiles(_ sender: AnyObject?) { let document = representedObject as! TulsiProjectDocument if document.hasChildConfigDocuments { let alert = NSAlert() alert.messageText = NSLocalizedString("ProjectEditor_CloseOpenedConfigDocumentsMessage", comment: "Message asking the user if they want to continue with an operation that requires that all opened TulsiGeneratorConfig documents be closed.") alert.addButton(withTitle: NSLocalizedString("ProjectEditor_CloseOpenedConfigDocumentsButtonOK", comment: "Title for a button that will proceed with an operation that requires that all opened TulsiGeneratorConfig documents be closed.")) alert.addButton(withTitle: NSLocalizedString("ProjectEditor_CloseOpenedConfigDocumentsButtonCancel", comment: "Title for a button that will cancel an operation that requires that all opened TulsiGeneratorConfig documents be closed.")) alert.beginSheetModal(for: self.view.window!) { value in if value == NSApplication.ModalResponse.alertFirstButtonReturn { document.closeChildConfigDocuments() self.didClickRemoveSelectedBUILDFiles(sender) } } return } packageArrayController.remove(atArrangedObjectIndexes: packageArrayController.selectionIndexes) let remainingObjects = packageArrayController.arrangedObjects as! [String] document.bazelPackages = remainingObjects } @IBAction func selectBazelPath(_ sender: AnyObject?) { let document = representedObject as! TulsiProjectDocument BazelSelectionPanel.beginSheetModalBazelSelectionPanelForWindow(self.view.window!, document: document) } @IBAction func didDoubleClickPackage(_ sender: NSTableView) { let clickedRow = sender.clickedRow guard clickedRow >= 0 else { return } let package = (packageArrayController.arrangedObjects as! [String])[clickedRow] let document = representedObject as! TulsiProjectDocument let buildFile = package + "/BUILD" if let url = document.workspaceRootURL?.appendingPathComponent(buildFile) { NSWorkspace.shared.open(url) } } func document(_ document: NSDocument, didSave: Bool, contextInfo: AnyObject) { if !didSave { // Nothing useful can be done if the initial save failed so close this window. self.view.window!.close() return } } // MARK: - NewProjectViewControllerDelegate func viewController(_ vc: NewProjectViewController, didCompleteWithReason reason: NewProjectViewController.CompletionReason) { defer {newProjectSheet = nil} dismiss(vc) guard reason == .create else { // Nothing useful can be done if the user doesn't wish to create a new project, so close this // window. self.view.window!.close() return } let document = representedObject as! TulsiProjectDocument document.createNewProject(newProjectSheet.projectName!, workspaceFileURL: newProjectSheet.workspacePath!) newProjectNeedsSaveAs = true } } /// Transformer that converts a Bazel package path to an item displayable in the package table view /// This is primarily necessary to support BUILD files colocated with the workspace root. final class PackagePathValueTransformer : ValueTransformer { override class func transformedValueClass() -> AnyClass { return NSString.self } override class func allowsReverseTransformation() -> Bool { return false } override func transformedValue(_ value: Any?) -> Any? { guard let value = value as? String else { return nil } return "//\(value)" } }
apache-2.0
e11a5a6a6499908a2192e99321d8c3f0
39.123853
194
0.691666
5.356399
false
false
false
false
danieltmbr/Bencode
Sources/Bencode/BencodeKey.swift
1
929
// // BencodeKey.swift // Bencode // // Created by Daniel Tombor on 2017. 09. 16.. // import Foundation /** For ordered encoding. */ public struct BencodeKey { public let key: String public let order: Int public init(_ key: String, order: Int = Int.max) { self.key = key self.order = order } } extension BencodeKey: Hashable { public static func ==(lhs: BencodeKey, rhs: BencodeKey) -> Bool { return lhs.key == rhs.key } } extension BencodeKey: Comparable { public static func <(lhs: BencodeKey, rhs: BencodeKey) -> Bool { if lhs.order != rhs.order { return lhs.order < rhs.order } else { return lhs.key < rhs.key } } } // MARK: - String helper extension extension String { /** Convert string to BencodeKey */ var bKey: BencodeKey { return BencodeKey(self) } }
mit
52b51c031866dfeb6c2c566ce6529c38
17.58
69
0.571582
4.056769
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/DataSources/ListDataManager.swift
1
2372
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ public class ListDataManager: NSObject { var callback: ((Bool)->())! public class var sharedInstance: ListDataManager { struct Singleton { static let instance = ListDataManager() } return Singleton.instance } /** This method is invoked by the loginViewController. It makes a call to Worklight for the default list's of the user. - parameter callBack: the loginViewController to recieve data back from this call */ public func getDefaultList(callback : ((Bool)->())!){ let adapterName : String = "SummitAdapter" let procedureName: String = "getDefaultList" self.callback = callback let sharedDefaults = NSUserDefaults(suiteName: GroupDataAccess.sharedInstance.groupAppID)! let userID: String = sharedDefaults.stringForKey("userID")! let params = [userID] let caller = WLProcedureCaller(adapterName : adapterName, procedureName: procedureName) caller.invokeWithResponse(self, params: params) } } // MARK: WLDataDelegate extension ListDataManager: WLDataDelegate { /** Delgate method for WorkLight. Called when connection and return is successful - parameter response: Response from WorkLight */ public func onSuccess(response: WLResponse!) { JSONParseHelper.parseDefaultListJSON(response) // Execute the callback from the view controller that instantiated the dashboard call callback(true) } /** Delgate method for WorkLight. Called when connection or return is unsuccessful - parameter response: Response from WorkLight */ public func onFailure(response: WLFailResponse!) { if (response.errorCode.rawValue == 0) && (response.errorMsg != nil) { print("Response Failure with error: \(response.errorMsg)") } callback(false) } /** Delgate method for WorkLight. Task to do before executing a call. */ public func onPreExecute() { } /** Delgate method for WorkLight. Task to do after executing a call. */ public func onPostExecute() { } }
epl-1.0
126f5ead3246d9a8adacdea6a5f0f570
26.581395
119
0.633066
5.591981
false
false
false
false
gabek/GitYourFeedback
GitYourFeedback/Classes/UIImageExtension.swift
1
1007
// // UIImageExtension.swift // Pods // // Created by Sidney de Koning on 27/10/2016. // // import Foundation extension UIImage { func resize(to size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale) self.draw(in: CGRect(origin: CGPoint.zero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() return scaledImage! } func resizeToUploadingSize() -> UIImage { let recommendedSize = CGSize(width: 360, height: 640) let widthFactor = size.width / recommendedSize.width let heightFactor = size.height / recommendedSize.height var resizeFactor = widthFactor if size.height > size.width { resizeFactor = heightFactor } let newSize = CGSize(width: size.width / resizeFactor, height: size.height / resizeFactor) let resized = resize(to: newSize) return resized } }
mit
235a6fbfacc29b5eacffcbabe48e7e1c
26.972222
98
0.631579
4.818182
false
false
false
false
sarvex/SwiftRecepies
Graphics/Drawing Lines/Drawing Lines/View.swift
1
4081
// // View.swift // Drawing Lines // // Created by Vandad Nahavandipoor on 6/25/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit class View: UIView { /* 1 */ // override func drawRect(rect: CGRect) // { // // /* Set the color that we want to use to draw the line */ // UIColor.brownColor().set() // // /* Get the current graphics context */ // let context = UIGraphicsGetCurrentContext() // // /* Set the width for the line */ // CGContextSetLineWidth(context, 5) // // /* Start the line at this point */ // CGContextMoveToPoint(context, 50, 10) // // /* And end it at this point */ // CGContextAddLineToPoint(context, 100, 200) // // /* Use the context's current color to draw the line */ // CGContextStrokePath(context) // // } /* 2 */ // override func drawRect(rect: CGRect) { // /* Set the color that we want to use to draw the line */ // UIColor.brownColor().set() // // /* Get the current graphics context */ // let context = UIGraphicsGetCurrentContext() // // /* Set the width for the line */ // CGContextSetLineWidth(context, 5) // // /* Start the line at this point */ // CGContextMoveToPoint(context, 50, 10) // // /* And end it at this point */ // CGContextAddLineToPoint(context, 100, 100) // // /* Extend the line to another point */ // CGContextAddLineToPoint(context, 300, 100); // // /* Use the context's current color to draw the line */ // CGContextStrokePath(context) // } func drawRooftopAtTopPointOf(point: CGPoint, textToDisplay: NSString, lineJoin: CGLineJoin){ /* Set the color that we want to use to draw the line */ UIColor.brownColor().set() /* Set the color that we want to use to draw the line */ let context = UIGraphicsGetCurrentContext() /* Set the line join */ CGContextSetLineJoin(context, lineJoin) /* Set the width for the lines */ CGContextSetLineWidth(context, 20) /* Start the line at this point */ CGContextMoveToPoint(context, point.x - 140, point.y + 100) /* And end it at this point */ CGContextAddLineToPoint(context, point.x, point.y) /* Extend the line to another point to make the rooftop */ CGContextAddLineToPoint(context, point.x + 140, point.y + 100) /* Use the context's current color to draw the lines */ CGContextStrokePath(context) /* Draw the text in the rooftop using a black color */ UIColor.blackColor().set() /* Now draw the text */ let drawingPoint = CGPoint(x: point.x - 40, y: point.y + 60) let font = UIFont.boldSystemFontOfSize(30) textToDisplay.drawAtPoint(drawingPoint, withAttributes: [NSFontAttributeName : font]) } override func drawRect(rect: CGRect){ drawRooftopAtTopPointOf(CGPoint(x: 160, y: 40), textToDisplay: "Miter", lineJoin: kCGLineJoinMiter) drawRooftopAtTopPointOf(CGPoint(x: 160, y: 180), textToDisplay: "Bevel", lineJoin: kCGLineJoinBevel) drawRooftopAtTopPointOf(CGPoint(x: 160, y: 320), textToDisplay: "Round", lineJoin: kCGLineJoinRound) } }
isc
0a27739761ce1ceff8c0c3c8bd63216e
30.152672
83
0.638569
4.081
false
false
false
false
alessiobrozzi/firefox-ios
Client/Frontend/Browser/Tab.swift
1
17895
/* 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 WebKit import Storage import Shared import SwiftyJSON import XCGLogger private let log = Logger.browserLogger protocol TabHelper { static func name() -> String func scriptMessageHandlerName() -> String? func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) } @objc protocol TabDelegate { func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) @objc optional func tab(_ tab: Tab, didCreateWebView webView: WKWebView) @objc optional func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) } struct TabState { var isPrivate: Bool = false var desktopSite: Bool = false var isBookmarked: Bool = false var url: URL? var title: String? var favicon: Favicon? } class Tab: NSObject { fileprivate var _isPrivate: Bool = false internal fileprivate(set) var isPrivate: Bool { get { return _isPrivate } set { if _isPrivate != newValue { _isPrivate = newValue self.updateAppState() } } } var tabState: TabState { return TabState(isPrivate: _isPrivate, desktopSite: desktopSite, isBookmarked: isBookmarked, url: url, title: displayTitle, favicon: displayFavicon) } var webView: WKWebView? var tabDelegate: TabDelegate? weak var appStateDelegate: AppStateDelegate? var bars = [SnackBar]() var favicons = [Favicon]() var lastExecutedTime: Timestamp? var sessionData: SessionData? fileprivate var lastRequest: URLRequest? var restoring: Bool = false var pendingScreenshot = false var url: URL? /// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs. var lastTitle: String? /// Whether or not the desktop site was requested with the last request, reload or navigation. Note that this property needs to /// be managed by the web view's navigation delegate. var desktopSite: Bool = false { didSet { if oldValue != desktopSite { self.updateAppState() } } } var isBookmarked: Bool = false { didSet { if oldValue != isBookmarked { self.updateAppState() } } } fileprivate(set) var screenshot: UIImage? var screenshotUUID: UUID? // If this tab has been opened from another, its parent will point to the tab from which it was opened var parent: Tab? fileprivate var helperManager: HelperManager? fileprivate var configuration: WKWebViewConfiguration? /// Any time a tab tries to make requests to display a Javascript Alert and we are not the active /// tab instance, queue it for later until we become foregrounded. fileprivate var alertQueue = [JSAlertInfo]() init(configuration: WKWebViewConfiguration) { self.configuration = configuration } init(configuration: WKWebViewConfiguration, isPrivate: Bool) { self.configuration = configuration super.init() self.isPrivate = isPrivate } class func toTab(_ tab: Tab) -> RemoteTab? { if let displayURL = tab.url?.displayURL, RemoteTab.shouldIncludeURL(displayURL) { let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reversed()) return RemoteTab(clientGUID: nil, URL: displayURL, title: tab.displayTitle, history: history, lastUsed: Date.now(), icon: nil) } else if let sessionData = tab.sessionData, !sessionData.urls.isEmpty { let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reversed()) if let displayURL = history.first { return RemoteTab(clientGUID: nil, URL: displayURL, title: tab.displayTitle, history: history, lastUsed: sessionData.lastUsedTime, icon: nil) } } return nil } fileprivate func updateAppState() { let state = mainStore.updateState(.tab(tabState: self.tabState)) self.appStateDelegate?.appDidUpdateState(state) } weak var navigationDelegate: WKNavigationDelegate? { didSet { if let webView = webView { webView.navigationDelegate = navigationDelegate } } } func createWebview() { if webView == nil { assert(configuration != nil, "Create webview can only be called once") configuration!.userContentController = WKUserContentController() configuration!.preferences = WKPreferences() configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false let webView = TabWebView(frame: CGRect.zero, configuration: configuration!) webView.delegate = self configuration = nil webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.allowsBackForwardNavigationGestures = true webView.backgroundColor = UIColor.lightGray // Turning off masking allows the web content to flow outside of the scrollView's frame // which allows the content appear beneath the toolbars in the BrowserViewController webView.scrollView.layer.masksToBounds = false webView.navigationDelegate = navigationDelegate helperManager = HelperManager(webView: webView) restore(webView) self.webView = webView self.webView?.addObserver(self, forKeyPath: "URL", options: .new, context: nil) tabDelegate?.tab?(self, didCreateWebView: webView) } } func restore(_ webView: WKWebView) { // Pulls restored session data from a previous SavedTab to load into the Tab. If it's nil, a session restore // has already been triggered via custom URL, so we use the last request to trigger it again; otherwise, // we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL // to trigger the session restore via custom handlers if let sessionData = self.sessionData { restoring = true var urls = [String]() for url in sessionData.urls { urls.append(url.absoluteString) } let currentPage = sessionData.currentPage self.sessionData = nil var jsonDict = [String: AnyObject]() jsonDict["history"] = urls as AnyObject? jsonDict["currentPage"] = currentPage as AnyObject? guard let json = JSON(jsonDict).stringValue() else { return } let escapedJSON = json.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! let restoreURL = URL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)") lastRequest = PrivilegedRequest(url: restoreURL!) as URLRequest webView.load(lastRequest!) } else if let request = lastRequest { webView.load(request) } else { log.error("creating webview with no lastRequest and no session data: \(self.url)") } } deinit { if let webView = webView { tabDelegate?.tab?(self, willDeleteWebView: webView) webView.removeObserver(self, forKeyPath: "URL") } } var loading: Bool { return webView?.isLoading ?? false } var estimatedProgress: Double { return webView?.estimatedProgress ?? 0 } var backList: [WKBackForwardListItem]? { return webView?.backForwardList.backList } var forwardList: [WKBackForwardListItem]? { return webView?.backForwardList.forwardList } var historyList: [URL] { func listToUrl(_ item: WKBackForwardListItem) -> URL { return item.url } var tabs = self.backList?.map(listToUrl) ?? [URL]() tabs.append(self.url!) return tabs } var title: String? { return webView?.title } var displayTitle: String { if let title = webView?.title { if !title.isEmpty { return title } } // When picking a display title. Tabs with sessionData are pending a restore so show their old title. // To prevent flickering of the display title. If a tab is restoring make sure to use its lastTitle. if let url = self.url, url.isAboutHomeURL, sessionData == nil, !restoring { return "" } guard let lastTitle = lastTitle, !lastTitle.isEmpty else { return self.url?.displayURL?.absoluteString ?? "" } return lastTitle } var currentInitialURL: URL? { get { let initalURL = self.webView?.backForwardList.currentItem?.initialURL return initalURL } } var displayFavicon: Favicon? { var width = 0 var largest: Favicon? for icon in favicons { if icon.width! > width { width = icon.width! largest = icon } } return largest } var canGoBack: Bool { return webView?.canGoBack ?? false } var canGoForward: Bool { return webView?.canGoForward ?? false } func goBack() { let _ = webView?.goBack() } func goForward() { let _ = webView?.goForward() } func goToBackForwardListItem(_ item: WKBackForwardListItem) { let _ = webView?.go(to: item) } @discardableResult func loadRequest(_ request: URLRequest) -> WKNavigation? { if let webView = webView { lastRequest = request return webView.load(request) } return nil } func stop() { webView?.stopLoading() } func reload() { let userAgent: String? = desktopSite ? UserAgent.desktopUserAgent() : nil if (userAgent ?? "") != webView?.customUserAgent, let currentItem = webView?.backForwardList.currentItem { webView?.customUserAgent = userAgent // Reload the initial URL to avoid UA specific redirection loadRequest(PrivilegedRequest(url: currentItem.initialURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60) as URLRequest) return } if let _ = webView?.reloadFromOrigin() { log.info("reloaded zombified tab from origin") return } if let webView = self.webView { log.info("restoring webView from scratch") restore(webView) } } func addHelper(_ helper: TabHelper, name: String) { helperManager!.addHelper(helper, name: name) } func getHelper(name: String) -> TabHelper? { return helperManager?.getHelper(name) } func hideContent(_ animated: Bool = false) { webView?.isUserInteractionEnabled = false if animated { UIView.animate(withDuration: 0.25, animations: { () -> Void in self.webView?.alpha = 0.0 }) } else { webView?.alpha = 0.0 } } func showContent(_ animated: Bool = false) { webView?.isUserInteractionEnabled = true if animated { UIView.animate(withDuration: 0.25, animations: { () -> Void in self.webView?.alpha = 1.0 }) } else { webView?.alpha = 1.0 } } func addSnackbar(_ bar: SnackBar) { bars.append(bar) tabDelegate?.tab(self, didAddSnackbar: bar) } func removeSnackbar(_ bar: SnackBar) { if let index = bars.index(of: bar) { bars.remove(at: index) tabDelegate?.tab(self, didRemoveSnackbar: bar) } } func removeAllSnackbars() { // Enumerate backwards here because we'll remove items from the list as we go. for i in (0..<bars.count).reversed() { let bar = bars[i] removeSnackbar(bar) } } func expireSnackbars() { // Enumerate backwards here because we may remove items from the list as we go. for i in (0..<bars.count).reversed() { let bar = bars[i] if !bar.shouldPersist(self) { removeSnackbar(bar) } } } func setScreenshot(_ screenshot: UIImage?, revUUID: Bool = true) { self.screenshot = screenshot if revUUID { self.screenshotUUID = UUID() } } func toggleDesktopSite() { desktopSite = !desktopSite reload() } func queueJavascriptAlertPrompt(_ alert: JSAlertInfo) { alertQueue.append(alert) } func dequeueJavascriptAlertPrompt() -> JSAlertInfo? { guard !alertQueue.isEmpty else { return nil } return alertQueue.removeFirst() } func cancelQueuedAlerts() { alertQueue.forEach { alert in alert.cancel() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let webView = object as? WKWebView, webView == self.webView, let path = keyPath, path == "URL" else { return assertionFailure("Unhandled KVO key: \(keyPath)") } updateAppState() } func isDescendentOf(_ ancestor: Tab) -> Bool { var tab = parent while tab != nil { if tab! == ancestor { return true } tab = tab?.parent } return false } func setNoImageMode(_ enabled: Bool = false, force: Bool) { if enabled || force { webView?.evaluateJavaScript("window.__firefox__.NoImageMode.setEnabled(\(enabled))", completionHandler: nil) } } func setNightMode(_ enabled: Bool) { webView?.evaluateJavaScript("window.__firefox__.NightMode.setEnabled(\(enabled))", completionHandler: nil) } func injectUserScriptWith(fileName: String, type: String = "js", injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, mainFrameOnly: Bool = true) { guard let webView = self.webView else { return } if let path = Bundle.main.path(forResource: fileName, ofType: type), let source = try? String(contentsOfFile: path) { let userScript = WKUserScript(source: source, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly) webView.configuration.userContentController.addUserScript(userScript) } } } extension Tab: TabWebViewDelegate { fileprivate func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) { tabDelegate?.tab(self, didSelectFindInPageForSelection: selection) } } private class HelperManager: NSObject, WKScriptMessageHandler { fileprivate var helpers = [String: TabHelper]() fileprivate weak var webView: WKWebView? init(webView: WKWebView) { self.webView = webView } @objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { for helper in helpers.values { if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { if scriptMessageHandlerName == message.name { helper.userContentController(userContentController, didReceiveScriptMessage: message) return } } } } func addHelper(_ helper: TabHelper, name: String) { if let _ = helpers[name] { assertionFailure("Duplicate helper added: \(name)") } helpers[name] = helper // If this helper handles script messages, then get the handler name and register it. The Browser // receives all messages and then dispatches them to the right TabHelper. if let scriptMessageHandlerName = helper.scriptMessageHandlerName() { webView?.configuration.userContentController.add(self, name: scriptMessageHandlerName) } } func getHelper(_ name: String) -> TabHelper? { return helpers[name] } } private protocol TabWebViewDelegate: class { func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) } private class TabWebView: WKWebView, MenuHelperInterface { fileprivate weak var delegate: TabWebViewDelegate? override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return action == MenuHelper.SelectorFindInPage } @objc func menuHelperFindInPage() { evaluateJavaScript("getSelection().toString()") { result, _ in let selection = result as? String ?? "" self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection) } } fileprivate override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { // The find-in-page selection menu only appears if the webview is the first responder. becomeFirstResponder() return super.hitTest(point, with: event) } }
mpl-2.0
4c00214011c21a4078f5d1074a6f5e9e
32.511236
157
0.618441
5.322725
false
false
false
false
StratusHunter/JustEat-Test-Swift
Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift
5
2997
// // UIControl+Rx.swift // RxCocoa // // Created by Daniel Tartaglia on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit extension UIControl { /** Bindable sink for `enabled` property. */ public var rx_enabled: AnyObserver<Bool> { return UIBindingObserver(UIElement: self) { control, value in control.enabled = value }.asObserver() } /** Bindable sink for `selected` property. */ public var rx_selected: AnyObserver<Bool> { return UIBindingObserver(UIElement: self) { control, selected in control.selected = selected }.asObserver() } /** Reactive wrapper for target action pattern. - parameter controlEvents: Filter for observed event types. */ public func rx_controlEvent(controlEvents: UIControlEvents) -> ControlEvent<Void> { let source: Observable<Void> = Observable.create { [weak self] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = self else { observer.on(.Completed) return NopDisposable.instance } let controlTarget = ControlTarget(control: control, controlEvents: controlEvents) { control in observer.on(.Next()) } return AnonymousDisposable { controlTarget.dispose() } }.takeUntil(rx_deallocated) return ControlEvent(events: source) } /** You might be wondering why the ugly `as!` casts etc, well, for some reason if Swift compiler knows C is UIControl type and optimizations are turned on, it will crash. */ static func rx_value<C: AnyObject, T: Equatable>(control: C, getter: (C) -> T, setter: (C, T) -> Void) -> ControlProperty<T> { let source: Observable<T> = Observable.create { [weak weakControl = control] observer in guard let control = weakControl else { observer.on(.Completed) return NopDisposable.instance } observer.on(.Next(getter(control))) let controlTarget = ControlTarget(control: control as! UIControl, controlEvents: [.AllEditingEvents, .ValueChanged]) { _ in if let control = weakControl { observer.on(.Next(getter(control))) } } return AnonymousDisposable { controlTarget.dispose() } } .distinctUntilChanged() .takeUntil((control as! NSObject).rx_deallocated) let bindingObserver = UIBindingObserver(UIElement: control, binding: setter) return ControlProperty<T>(values: source, valueSink: bindingObserver) } } #endif
mit
fa42028a8f86435df98bd54bde910033
29.886598
139
0.583111
5.103918
false
false
false
false
accepton/accepton-apple
Example/Tests/Factory.swift
1
9534
import UIKit class FactoryProduct<T, P: Equatable>: NSObject { var properties: [P] var descriptionAddendums: [String:String]? var block: (()->(T))! var blockWithRuntimeProperties: (()->(T, [P]))! var valueEntered = false lazy var value: T = { if self.block != nil { return self.block() } else { let res = self.blockWithRuntimeProperties() self.properties += res.1 return res.0 } }() init(properties: [P], descriptionAddendums: [String:String], block: ()->(T)) { self.properties = properties self.descriptionAddendums = descriptionAddendums self.block = block } init(properties: [P], descriptionAddendums: [String:String], blockWithRuntimeProperties: ()->(T, [P])) { self.properties = properties self.descriptionAddendums = descriptionAddendums self.blockWithRuntimeProperties = blockWithRuntimeProperties } override var description: String { var res = "\(T.self) with properties: [" for p in properties { res += "\(p)" } res += "]" if let addendums = descriptionAddendums { for (k, v) in addendums { res += "\n\(k): \(v)" } } return res } } class FactoryResultQuery<T, P: Equatable>: CustomStringConvertible { var factory: Factory<T, P> var withAtleastProperties: [P]? var withoutProperties: [P] = [] init(factory: Factory<T, P>) { self.factory = factory } //Run the query with the given list of options private func runQuery() -> [FactoryProduct<T, P>] { //Start out matching all var filteredProducts = factory.products //Must contain all mentioned properties if withAtLeastProperties is set filteredProducts = filteredProducts.filter { product in return productMatchesQuery(product) } if filteredProducts.count == 0 { print("No products for \(self.dynamicType) were found that matched your query: \(self)") assertionFailure() } return filteredProducts } private func productMatchesQuery(product: FactoryProduct<T, P>) -> Bool { if let withAtleastProperties = withAtleastProperties { for p in withAtleastProperties { if product.properties.indexOf(p) == nil { return false } } } for p in withoutProperties { if product.properties.indexOf(p) != nil { return false } } return true } var description: String { return "\nwithAtleastProperties: \(withAtleastProperties)\nwithoutProperties: \(withoutProperties)" } //Loop etc. func each(block: (value: T, desc: String)->()) { let res = self.runQuery() var blockArguments: [(value: T, desc: String)] = [] let blockArgumentsQueue = NSOperationQueue() blockArgumentsQueue.maxConcurrentOperationCount = 1 for var e in res { blockArgumentsQueue.addOperation(NSBlockOperation() { let v = e.value if self.productMatchesQuery(e) { let desc = "\(e)" blockArguments.append((value: e.value, desc: desc)) if let product = productDescripions[desc] { if product != e { NSException(name: "Factory Error", reason: "Product with description \(desc) had a duplicate", userInfo: nil).raise() } } } else { puts("\(e) rejected after running post-query") } }) } blockArgumentsQueue.waitUntilAllOperationsAreFinished() for arg in blockArguments { block(arg) } } func eachWithProperties(block: (value: T, desc: String, properties: [P])->()) { let res = self.runQuery() for var e in res { block(value: e.value, desc: "\(e)", properties: e.properties) } } //----------------------------------------------------------------------------------------------------- //Fluent interface //----------------------------------------------------------------------------------------------------- func withAtleast(properties properties: [P]) -> FactoryResultQuery<T, P> { if self.withAtleastProperties == nil { self.withAtleastProperties = [] } self.withAtleastProperties! += properties return self } func withAtleast(properties: P...) -> FactoryResultQuery<T, P> { return self.withAtleast(properties: properties) } func without(properties properties: [P]) -> FactoryResultQuery<T, P> { self.withoutProperties += properties return self } func without(properties: P...) -> FactoryResultQuery<T, P> { return self.without(properties: properties) } } class Factory<T, P: Equatable> { var products: [FactoryProduct<T, P>] = [] var asyncProductsQueue: NSOperationQueue = { let q = NSOperationQueue() q.maxConcurrentOperationCount = 1 return q }() required init() {} func product(properties properties: [P], var withExtraDesc extraDescs: [String:String]=[:], block: ()->(T)) { for (k, v) in currentPrefixExtraDescs { extraDescs[k] = v } let product = FactoryProduct<T, P>(properties: properties+currentContextProperties, descriptionAddendums: extraDescs, block: block) //Do any products have matching descriptions? let desc = "\(product)" for e in products { let otherDesc = "\(e)" if otherDesc == desc { assertionFailure("product for \(self.dynamicType) with desc \(desc) has duplicates!!") } } products.append(product) } func product(properties: P..., withExtraDescs extraDescs: [String:String]=[:], block: ()->(T)) { self.product(properties: properties, withExtraDesc: extraDescs, block: block) } //Products that are 'added' after the block is called (because they cannot be computed before hand) //can have additional properties which are then checked via filter at the last minute func productWithRunTimeProperties(properties properties: [P], var withExtraDesc extraDescs: [String:String]=[:], block: ()->(value: T, extraProperties: [P])) { for (k, v) in currentPrefixExtraDescs { extraDescs[k] = v } var extraProperties: [P]! let _block: ()->(T) = { let res = block() extraProperties = res.extraProperties return res.value } let product = FactoryProduct<T, P>(properties: properties+currentContextProperties, descriptionAddendums: extraDescs, blockWithRuntimeProperties: block) //Do any products have matching descriptions? let desc = "\(product)" for e in products { let otherDesc = "\(e)" if otherDesc == desc { assertionFailure("product for \(self.dynamicType) with desc \(desc) has duplicates!!") } } products.append(product) } var currentPrefixExtraDescs: [String:String]=[:] var currentContextProperties: [P] = [] func context(properties: P..., withExtraDescs extraDescs: [String:String]=[:], block: ()->()) { let oldProperties = currentContextProperties let oldPrefixExtraDescs = currentPrefixExtraDescs currentContextProperties += properties for (k, v) in extraDescs { currentPrefixExtraDescs[k] = v } block() currentContextProperties = oldProperties currentPrefixExtraDescs = oldPrefixExtraDescs } static var query: FactoryResultQuery<T, P> { // let factory = factoryWithType(t: T.self, p: P.self) let factory = factoryWithKlass(self) return FactoryResultQuery<T, P>.init(factory: factory) } //----------------------------------------------------------------------------------------------------- //Fluent interface //----------------------------------------------------------------------------------------------------- static func withAtleast(properties: P...) -> FactoryResultQuery<T, P> { return self.query.withAtleast(properties: properties) } static func without(properties: P...) -> FactoryResultQuery<T, P> { return self.query.without(properties: properties) } static func each(block: (value: T, desc: String)->()) { return query.each(block) } static func eachWithProperties(block: (value: T, desc: String, properties: [P])->()) { return self.query.eachWithProperties(block) } } private var productDescripions: [NSObject:String] = [:] private var factories: [String:AnyObject] = [:] private func factoryWithKlass<T, P>(klass: Factory<T, P>.Type) -> Factory<T, P> { let sig = "\(klass)" if let factory = factories[sig] { puts("Factory made \(sig)") return factory as! Factory<T, P> } puts("factory new \(sig)") let factory = klass.init() factories[sig] = factory return factoryWithKlass(klass) }
mit
81677fa158c22baf5ba4d2d65520f3a3
34.578358
163
0.558947
5.128564
false
false
false
false
jackdao1992/DraggableYoutubeView
Example Draggable View/JDDraggableYoutubeView/JDDraggableYoutubeView/ViewController.swift
1
3257
// // ViewController.swift // JDDraggableYoutubeView // // Created by Jack Dao on 2/17/16. // Copyright © 2016 Rubify. All rights reserved. // import UIKit import MediaPlayer import AVKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var draggableView: JDDraggableView? var draggableViewVideoView: JDDraggableView? var player = AVPlayer() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. draggableView = JDDraggableView() let topView = UIView(frame: CGRectZero) topView.backgroundColor = UIColor.redColor() draggableView?.draggableView = topView let bottomView = UITableView(frame: CGRectZero) bottomView.dataSource = self bottomView.delegate = self draggableView?.contentView = bottomView draggableView?.miniWidth = self.view.frame.width / 2 draggableView?.miniHeight = (self.view.frame.width / 2) * 100 / 160 draggableView?.alphaForHidden = 0.2 // create movie player draggableViewVideoView = JDDraggableView() do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } catch { } let moviePath = NSBundle.mainBundle().pathForResource("demo_movie", ofType: "mov") player = AVPlayer(URL: NSURL(fileURLWithPath: moviePath!)) let playerController = AVPlayerViewController() playerController.player = player playerController.videoGravity = AVLayerVideoGravityResizeAspectFill self.addChildViewController(playerController) // player.play() draggableViewVideoView?.draggableView = playerController.view draggableViewVideoView?.contentView = bottomView draggableViewVideoView?.draggableRemoveFormSuperViewCallBack({ () -> () in self.player.pause() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func testButtonTouched(sender: AnyObject) { draggableView?.showViewInViewController(self, animated: true) // draggableView?.showViewInWindowWithAnimated(true) } @IBAction func mpMovieControllerButtonTouched(sender: AnyObject) { draggableViewVideoView?.showViewInWindowWithAnimated(true) self.player.play() } // MARK: -- table view func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("cell") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell") } cell?.textLabel?.text = "Row \(indexPath.row)" return cell! } }
mit
daf478f0b77152ddab05d37bedf59625
31.888889
109
0.65817
5.783304
false
false
false
false
dboyliao/NumSwift
NumSwift/Source/Types/MatrixType.swift
2
5488
// // Dear maintainer: // // When I wrote this code, only I and God // know what it was. // Now, only God knows! // // So if you are done trying to 'optimize' // this routine (and failed), // please increment the following counter // as warning to the next guy: // // var TotalHoursWastedHere = 0 // // Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered import Accelerate extension Matrix:Equatable {} public class Matrix<Element:Field> { // public properties public var data:[Element] { return self._data } public let rows:Int public let cols:Int public var order:CBLAS_ORDER { return self._order } public var size:(Int, Int) { return (rows, cols) } public var dtype: Element.Type { return _dtype } public var count: Int { return self.data.count } // private properties private var _order:CBLAS_ORDER private var _data:[Element] private var _dtype = Element.self public init?(data:[Element], rows:Int, cols:Int, order:CBLAS_ORDER = CblasRowMajor){ if data.count != rows*cols { return nil } self.rows = rows self.cols = cols self._data = data self._order = order } public convenience init?(data:ArraySlice<Element>, rows:Int, cols:Int, order:CBLAS_ORDER = CblasRowMajor){ let array = Array<Element>(data) self.init(data:array, rows: rows, cols: cols, order: order) } public init(_ matrix:Matrix<Element>){ self.rows = matrix.rows self.cols = matrix.cols self._order = matrix.order self._data = matrix.data } public func setDataOrder(toOrder order:CBLAS_ORDER){ if self.order == order { return } let newData = [Element](count:self.rows * self.cols, repeatedValue:Element.self(0)) switch (self.order, Element.self) { case (CblasRowMajor, is Double.Type): // convert to column major let stride = UInt.Stride(self.cols) let ptrData = UnsafePointer<Double>(self.data) let ptrNewData = UnsafeMutablePointer<Double>(newData) for offset in 0..<self.cols { let start = UInt(offset+1) let end = UInt(self.data.count + 1) let index = [UInt](start.stride(to:end, by:stride)) vDSP_vgathrD(ptrData, index, 1, ptrNewData.advancedBy(offset * self.cols), 1, UInt(self.rows)) } case (CblasRowMajor, is Float.Type): let stride = UInt.Stride(self.cols) let ptrData = UnsafePointer<Float>(data) let ptrNewData = UnsafeMutablePointer<Float>(newData) for offset in 0..<self.cols { let start = UInt(offset+1) let end = UInt(self.data.count + 1) let index = [UInt](start.stride(to:end, by:stride)) vDSP_vgathr(ptrData, index, 1, ptrNewData.advancedBy(offset * self.cols), 1, UInt(self.rows)) } case (CblasColMajor, is Double.Type): let stride = UInt.Stride(self.rows) let ptrData = UnsafePointer<Double>(data) let ptrNewData = UnsafeMutablePointer<Double>(newData) for offset in 0..<self.rows { let start = UInt(offset+1) let end = UInt(self.data.count + 1) let index = [UInt](start.stride(to:end, by:stride)) vDSP_vgathrD(ptrData, index, 1, ptrNewData.advancedBy(offset * self.rows), 1, UInt(self.cols)) } case (CblasColMajor, is Float.Type): let stride = UInt.Stride(self.rows) let ptrData = UnsafePointer<Float>(data) let ptrNewData = UnsafeMutablePointer<Float>(newData) for offset in 0..<self.rows { let start = UInt(offset+1) let end = UInt(self.data.count + 1) let index = [UInt](start.stride(to:end, by:stride)) vDSP_vgathr(ptrData, index, 1, ptrNewData.advancedBy(offset * self.rows), 1, UInt(self.cols)) } default: return } self._order = order self._data = newData } public class func Zeros<Element>(rows:Int, _ cols:Int, order:CBLAS_ORDER = CblasRowMajor) -> Matrix<Element> { return Matrix<Element>(data:[Element](count:rows*cols, repeatedValue:Element.self(0)), rows:rows, cols:cols, order:order)! } public class func Zeros<Element>(like matrix: Matrix<Element>) -> Matrix<Element>{ return Matrix<Element>.Zeros(matrix.rows, matrix.cols, order:matrix.order) } // TODO: subscript methods. public subscript(indexX:Int, indexY:Int) -> Element { let offset:Int switch self.order { case CblasRowMajor: offset = indexX * self.cols + indexY case CblasColMajor: offset = indexY * self.rows + indexX default: print("[Matrix subscription:indexX:indexY]: no such order") offset = 0 break } return self.data[offset] } /* public subscript(rangeX:Range<Int>, rangeY:Range<Int>) -> Matrix<Element> { return Matrix<Element>.Zeros(2, 2) } */ // TODO: type convertion // public func astype(type:Element.Type) -> Matrix<Element> }
mit
7706fce88ccb43ed0d6a00215852366e
31.47929
130
0.585095
4.032329
false
false
false
false
twostraws/HackingWithSwift
SwiftUI/project14/Bucketlist/EditView.swift
1
3073
// // EditView.swift // Bucketlist // // Created by Paul Hudson on 09/12/2021. // import SwiftUI struct EditView: View { enum LoadingState { case loading, loaded, failed } @Environment(\.dismiss) var dismiss var location: Location var onSave: (Location) -> Void @State private var name: String @State private var description: String @State private var loadingState = LoadingState.loading @State private var pages = [Page]() var body: some View { NavigationView { Form { Section { TextField("Place name", text: $name) TextField("Description", text: $description) } Section("Nearby…") { switch loadingState { case .loading: Text("Loading…") case .loaded: ForEach(pages, id: \.pageid) { page in Text(page.title) .font(.headline) + Text(": ") + Text(page.description) .italic() } case .failed: Text("Please try again later.") } } } .navigationTitle("Place details") .toolbar { Button("Save") { var newLocation = location newLocation.id = UUID() newLocation.name = name newLocation.description = description onSave(newLocation) dismiss() } } .task { await fetchNearbyPlaces() } } } init(location: Location, onSave: @escaping (Location) -> Void) { self.location = location self.onSave = onSave _name = State(initialValue: location.name) _description = State(initialValue: location.description) } func fetchNearbyPlaces() async { let urlString = "https://en.wikipedia.org/w/api.php?ggscoord=\(location.coordinate.latitude)%7C\(location.coordinate.longitude)&action=query&prop=coordinates%7Cpageimages%7Cpageterms&colimit=50&piprop=thumbnail&pithumbsize=500&pilimit=50&wbptterms=description&generator=geosearch&ggsradius=10000&ggslimit=50&format=json" guard let url = URL(string: urlString) else { print("Bad URL: \(urlString)") return } do { let (data, _) = try await URLSession.shared.data(from: url) let items = try JSONDecoder().decode(Result.self, from: data) pages = items.query.pages.values.sorted() loadingState = .loaded } catch { loadingState = .failed } } } struct EditView_Previews: PreviewProvider { static var previews: some View { EditView(location: Location.example) { _ in } } }
unlicense
86551d1995b79375ba8fe2d8de7a3097
30
328
0.506028
4.990244
false
false
false
false
ianchengtw/ios_30_apps_in_30_days
Day_02_GoogleMaps/MapSearch/MapSearch/SearchResultController.swift
1
6190
// // SearchResultController.swift // MapSearch // // Created by Ian on 5/9/16. // Copyright © 2016 ianchengtw_ios_30_apps_in_30_days. All rights reserved. // import UIKit import CoreLocation import GoogleMaps protocol LocateOnTheMap{ func locateWithLongitude(location: CLLocationCoordinate2D, bounds: GMSCoordinateBounds, title: String) } class SearchResultController: UITableViewController { var searchResults = [String]() var delegate: LocateOnTheMap? override func viewDidLoad() { super.viewDidLoad() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.searchResults.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath) cell.textLabel?.text = self.searchResults[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ self.dismissViewControllerAnimated(true, completion: nil) guard let URIEncodingAddress = self.searchResults[indexPath.row].stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.symbolCharacterSet()), let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(URIEncodingAddress)&sensor=false") else { return } let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (oData, res, error) -> Void in guard let data = oData else { print(error); return } do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves) as! NSDictionary guard let locationLat = json["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lat")?.objectAtIndex(0) as? Double, let locationLng = json["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lng")?.objectAtIndex(0) as? Double, let northeastLat = json["results"]?.valueForKey("geometry")?.valueForKey("bounds")?.valueForKey("northeast")?.valueForKey("lat")?.objectAtIndex(0) as? Double, let northeastLng = json["results"]?.valueForKey("geometry")?.valueForKey("bounds")?.valueForKey("northeast")?.valueForKey("lng")?.objectAtIndex(0) as? Double, let southwestLat = json["results"]?.valueForKey("geometry")?.valueForKey("bounds")?.valueForKey("southwest")?.valueForKey("lat")?.objectAtIndex(0) as? Double, let southwestLng = json["results"]?.valueForKey("geometry")?.valueForKey("bounds")?.valueForKey("southwest")?.valueForKey("lng")?.objectAtIndex(0) as? Double else { return } self.delegate?.locateWithLongitude( CLLocationCoordinate2D(latitude: locationLat, longitude: locationLng), bounds: GMSCoordinateBounds( coordinate: CLLocationCoordinate2D(latitude: northeastLat, longitude: northeastLng), coordinate: CLLocationCoordinate2D(latitude: southwestLat, longitude: southwestLng) ), title: self.searchResults[indexPath.row] ) }catch { print("Error") } } task.resume() } func reloadDataWithArray(array:[String]){ self.searchResults = array self.tableView.reloadData() } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
25caa8deadc56f101987828428f0e2f7
39.986755
182
0.626919
5.833176
false
false
false
false
ducnnguyen/TKControlsLib
Pod/CommonControl/External/EasyTipView/EasyTipView.swift
1
31401
// // EasyTipView.swift // // Copyright (c) 2015 Teodor Patraş // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public protocol EasyTipViewDelegate : class { func easyTipViewDidDismiss(_ tipView : EasyTipView) } // MARK: - Public methods extension public extension EasyTipView { // MARK:- Class methods - /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter text: The text to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forItem item: UIBarItem, withinSuperview superview: UIView? = nil, text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter text: The text to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil, text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ let ev = EasyTipView(text: text, preferences: preferences, delegate: delegate) ev.show(animated: animated, forView: view, withinSuperview: superview) } /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter contentView: The view to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forItem item: UIBarItem, withinSuperview superview: UIView? = nil, contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview, contentView: contentView, preferences: preferences, delegate: delegate) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. - parameter contentView: The view to be displayed. - parameter preferences: The preferences which will configure the EasyTipView. - parameter delegate: The delegate. */ class func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil, contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil){ let ev = EasyTipView(contentView: contentView, preferences: preferences, delegate: delegate) ev.show(animated: animated, forView: view, withinSuperview: superview) } // MARK:- Instance methods - /** Presents an EasyTipView pointing to a particular UIBarItem instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter item: The UIBarButtonItem or UITabBarItem instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIBarButtonItem instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. */ func show(animated: Bool = true, forItem item: UIBarItem, withinSuperView superview: UIView? = nil) { if let view = item.view { show(animated: animated, forView: view, withinSuperview: superview) } } /** Presents an EasyTipView pointing to a particular UIView instance within the specified superview - parameter animated: Pass true to animate the presentation. - parameter view: The UIView instance which the EasyTipView will be pointing to. - parameter superview: A view which is part of the UIView instances superview hierarchy. Ignore this parameter in order to display the EasyTipView within the main window. */ func show(animated: Bool = true, forView view: UIView, withinSuperview superview: UIView? = nil) { precondition(superview == nil || view.hasSuperview(superview!), "The supplied superview <\(superview!)> is not a direct nor an indirect superview of the supplied reference view <\(view)>. The superview passed to this method should be a direct or an indirect superview of the reference view. To display the tooltip within the main window, ignore the superview parameter.") let superview = superview ?? UIApplication.shared.windows.first! let initialTransform = preferences.animating.showInitialTransform let finalTransform = preferences.animating.showFinalTransform let initialAlpha = preferences.animating.showInitialAlpha let damping = preferences.animating.springDamping let velocity = preferences.animating.springVelocity presentingView = view arrange(withinSuperview: superview) transform = initialTransform alpha = initialAlpha let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap)) tap.delegate = self addGestureRecognizer(tap) superview.addSubview(self) let animations : () -> () = { self.transform = finalTransform self.alpha = 1 } if animated { UIView.animate(withDuration: preferences.animating.showDuration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [.curveEaseInOut], animations: animations, completion: nil) }else{ animations() } } /** Dismisses the EasyTipView - parameter completion: Completion block to be executed after the EasyTipView is dismissed. */ func dismiss(withCompletion completion: (() -> ())? = nil){ let damping = preferences.animating.springDamping let velocity = preferences.animating.springVelocity UIView.animate(withDuration: preferences.animating.dismissDuration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: [.curveEaseInOut], animations: { self.transform = self.preferences.animating.dismissTransform self.alpha = self.preferences.animating.dismissFinalAlpha }) { (finished) -> Void in completion?() self.delegate?.easyTipViewDidDismiss(self) self.removeFromSuperview() self.transform = CGAffineTransform.identity } } } // MARK: - UIGestureRecognizerDelegate implementation extension EasyTipView: UIGestureRecognizerDelegate { open override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return preferences.animating.dismissOnTap } } // MARK: - EasyTipView class implementation - open class EasyTipView: UIView { // MARK:- Nested types - public enum ArrowPosition { case any case top case bottom case right case left static let allValues = [top, bottom, right, left] } public struct Preferences { public struct Drawing { public var cornerRadius = CGFloat(5) public var arrowHeight = CGFloat(5) public var arrowWidth = CGFloat(10) public var foregroundColor = UIColor.white public var backgroundColor = UIColor.red public var arrowPosition = ArrowPosition.any public var textAlignment = NSTextAlignment.center public var borderWidth = CGFloat(0) public var borderColor = UIColor.clear public var font = UIFont.systemFont(ofSize: 15) public var shadowColor = UIColor.clear public var shadowOffset = CGSize(width: 0.0, height: 0.0) public var shadowRadius = CGFloat(0) public var shadowOpacity = CGFloat(0) } public struct Positioning { public var bubbleHInset = CGFloat(1) public var bubbleVInset = CGFloat(1) public var contentHInset = CGFloat(10) public var contentVInset = CGFloat(10) public var maxWidth = CGFloat(200) } public struct Animating { public var dismissTransform = CGAffineTransform(scaleX: 0.1, y: 0.1) public var showInitialTransform = CGAffineTransform(scaleX: 0, y: 0) public var showFinalTransform = CGAffineTransform.identity public var springDamping = CGFloat(0.7) public var springVelocity = CGFloat(0.7) public var showInitialAlpha = CGFloat(0) public var dismissFinalAlpha = CGFloat(0) public var showDuration = 0.7 public var dismissDuration = 0.7 public var dismissOnTap = true } public var drawing = Drawing() public var positioning = Positioning() public var animating = Animating() public var hasBorder : Bool { return drawing.borderWidth > 0 && drawing.borderColor != UIColor.clear } public var hasShadow : Bool { return drawing.shadowOpacity > 0 && drawing.shadowColor != UIColor.clear } public init() {} } private enum Content: CustomStringConvertible { case text(String) case view(UIView) var description: String { switch self { case .text(let text): return "text : '\(text)'" case .view(let contentView): return "view : \(contentView)" } } } // MARK:- Variables - override open var backgroundColor: UIColor? { didSet { guard let color = backgroundColor , color != UIColor.clear else {return} preferences.drawing.backgroundColor = color backgroundColor = UIColor.clear } } override open var description: String { let type = "'\(String(reflecting: Swift.type(of: self)))'".components(separatedBy: ".").last! return "<< \(type) with \(content) >>" } fileprivate weak var presentingView: UIView? fileprivate weak var delegate: EasyTipViewDelegate? fileprivate var arrowTip = CGPoint.zero fileprivate(set) open var preferences: Preferences private let content: Content // MARK: - Lazy variables - fileprivate lazy var contentSize: CGSize = { [unowned self] in switch content { case .text(let text): #if swift(>=4.2) var attributes = [NSAttributedString.Key.font : self.preferences.drawing.font] #else var attributes = [NSAttributedStringKey.font : self.preferences.drawing.font] #endif var textSize = text.boundingRect(with: CGSize(width: self.preferences.positioning.maxWidth, height: CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil).size textSize.width = ceil(textSize.width) textSize.height = ceil(textSize.height) if textSize.width < self.preferences.drawing.arrowWidth { textSize.width = self.preferences.drawing.arrowWidth } return textSize case .view(let contentView): return contentView.frame.size } }() fileprivate lazy var tipViewSize: CGSize = { [unowned self] in var tipViewSize = CGSize(width: self.contentSize.width + self.preferences.positioning.contentHInset * 2 + self.preferences.positioning.bubbleHInset * 2, height: self.contentSize.height + self.preferences.positioning.contentVInset * 2 + self.preferences.positioning.bubbleVInset * 2 + self.preferences.drawing.arrowHeight) return tipViewSize }() // MARK: - Static variables - public static var globalPreferences = Preferences() // MARK:- Initializer - public convenience init (text: String, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.init(content: .text(text), preferences: preferences, delegate: delegate) } public convenience init (contentView: UIView, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.init(content: .view(contentView), preferences: preferences, delegate: delegate) } private init (content: Content, preferences: Preferences = EasyTipView.globalPreferences, delegate: EasyTipViewDelegate? = nil) { self.content = content self.preferences = preferences self.delegate = delegate super.init(frame: CGRect.zero) self.backgroundColor = UIColor.clear #if swift(>=4.2) let notificationName = UIDevice.orientationDidChangeNotification #else let notificationName = NSNotification.Name.UIDeviceOrientationDidChange #endif NotificationCenter.default.addObserver(self, selector: #selector(handleRotation), name: notificationName, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } /** NSCoding not supported. Use init(text, preferences, delegate) instead! */ required public init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported. Use init(text, preferences, delegate) instead!") } // MARK: - Rotation support - @objc func handleRotation() { guard let sview = superview , presentingView != nil else { return } UIView.animate(withDuration: 0.3) { self.arrange(withinSuperview: sview) self.setNeedsDisplay() } } // MARK: - Private methods - fileprivate func computeFrame(arrowPosition position: ArrowPosition, refViewFrame: CGRect, superviewFrame: CGRect) -> CGRect { var xOrigin: CGFloat = 0 var yOrigin: CGFloat = 0 switch position { case .top, .any: xOrigin = refViewFrame.center.x - tipViewSize.width / 2 yOrigin = refViewFrame.y + refViewFrame.height case .bottom: xOrigin = refViewFrame.center.x - tipViewSize.width / 2 yOrigin = refViewFrame.y - tipViewSize.height case .right: xOrigin = refViewFrame.x - tipViewSize.width yOrigin = refViewFrame.center.y - tipViewSize.height / 2 case .left: xOrigin = refViewFrame.x + refViewFrame.width yOrigin = refViewFrame.y - tipViewSize.height / 2 } var frame = CGRect(x: xOrigin, y: yOrigin, width: tipViewSize.width, height: tipViewSize.height) adjustFrame(&frame, forSuperviewFrame: superviewFrame) return frame } fileprivate func adjustFrame(_ frame: inout CGRect, forSuperviewFrame superviewFrame: CGRect) { // adjust horizontally if frame.x < 0 { frame.x = 0 } else if frame.maxX > superviewFrame.width { frame.x = superviewFrame.width - frame.width } //adjust vertically if frame.y < 0 { frame.y = 0 } else if frame.maxY > superviewFrame.maxY { frame.y = superviewFrame.height - frame.height } } fileprivate func isFrameValid(_ frame: CGRect, forRefViewFrame: CGRect, withinSuperviewFrame: CGRect) -> Bool { return !frame.intersects(forRefViewFrame) } fileprivate func arrange(withinSuperview superview: UIView) { var position = preferences.drawing.arrowPosition let refViewFrame = presentingView!.convert(presentingView!.bounds, to: superview); let superviewFrame: CGRect if let scrollview = superview as? UIScrollView { superviewFrame = CGRect(origin: scrollview.frame.origin, size: scrollview.contentSize) } else { superviewFrame = superview.frame } var frame = computeFrame(arrowPosition: position, refViewFrame: refViewFrame, superviewFrame: superviewFrame) if !isFrameValid(frame, forRefViewFrame: refViewFrame, withinSuperviewFrame: superviewFrame) { for value in ArrowPosition.allValues where value != position { let newFrame = computeFrame(arrowPosition: value, refViewFrame: refViewFrame, superviewFrame: superviewFrame) if isFrameValid(newFrame, forRefViewFrame: refViewFrame, withinSuperviewFrame: superviewFrame) { if position != .any { print("[EasyTipView - Info] The arrow position you chose <\(position)> could not be applied. Instead, position <\(value)> has been applied! Please specify position <\(ArrowPosition.any)> if you want EasyTipView to choose a position for you.") } frame = newFrame position = value preferences.drawing.arrowPosition = value break } } } var arrowTipXOrigin: CGFloat switch position { case .bottom, .top, .any: if frame.width < refViewFrame.width { arrowTipXOrigin = tipViewSize.width / 2 } else { arrowTipXOrigin = abs(frame.x - refViewFrame.x) + refViewFrame.width / 2 } arrowTip = CGPoint(x: arrowTipXOrigin, y: position == .bottom ? tipViewSize.height - preferences.positioning.bubbleVInset : preferences.positioning.bubbleVInset) case .right, .left: if frame.height < refViewFrame.height { arrowTipXOrigin = tipViewSize.height / 2 } else { arrowTipXOrigin = abs(frame.y - refViewFrame.y) + refViewFrame.height / 2 } arrowTip = CGPoint(x: preferences.drawing.arrowPosition == .left ? preferences.positioning.bubbleVInset : tipViewSize.width - preferences.positioning.bubbleVInset, y: arrowTipXOrigin) } if case .view(let contentView) = content { contentView.translatesAutoresizingMaskIntoConstraints = false contentView.frame = getContentRect(from: getBubbleFrame()) } self.frame = frame } // MARK:- Callbacks - @objc func handleTap() { dismiss() } // MARK:- Drawing - fileprivate func drawBubble(_ bubbleFrame: CGRect, arrowPosition: ArrowPosition, context: CGContext) { let arrowWidth = preferences.drawing.arrowWidth let arrowHeight = preferences.drawing.arrowHeight let cornerRadius = preferences.drawing.cornerRadius let contourPath = CGMutablePath() contourPath.move(to: CGPoint(x: arrowTip.x, y: arrowTip.y)) switch arrowPosition { case .bottom, .top, .any: contourPath.addLine(to: CGPoint(x: arrowTip.x - arrowWidth / 2, y: arrowTip.y + (arrowPosition == .bottom ? -1 : 1) * arrowHeight)) if arrowPosition == .bottom { drawBubbleBottomShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } else { drawBubbleTopShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } contourPath.addLine(to: CGPoint(x: arrowTip.x + arrowWidth / 2, y: arrowTip.y + (arrowPosition == .bottom ? -1 : 1) * arrowHeight)) case .right, .left: contourPath.addLine(to: CGPoint(x: arrowTip.x + (arrowPosition == .right ? -1 : 1) * arrowHeight, y: arrowTip.y - arrowWidth / 2)) if arrowPosition == .right { drawBubbleRightShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } else { drawBubbleLeftShape(bubbleFrame, cornerRadius: cornerRadius, path: contourPath) } contourPath.addLine(to: CGPoint(x: arrowTip.x + (arrowPosition == .right ? -1 : 1) * arrowHeight, y: arrowTip.y + arrowWidth / 2)) } contourPath.closeSubpath() context.addPath(contourPath) context.clip() paintBubble(context) if preferences.hasBorder { drawBorder(contourPath, context: context) } } fileprivate func drawBubbleBottomShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) } fileprivate func drawBubbleTopShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) } fileprivate func drawBubbleRightShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.height), radius: cornerRadius) } fileprivate func drawBubbleLeftShape(_ frame: CGRect, cornerRadius: CGFloat, path: CGMutablePath) { path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y), tangent2End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x + frame.width, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y + frame.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: frame.x, y: frame.y + frame.height), tangent2End: CGPoint(x: frame.x, y: frame.y), radius: cornerRadius) } fileprivate func paintBubble(_ context: CGContext) { context.setFillColor(preferences.drawing.backgroundColor.cgColor) context.fill(bounds) } fileprivate func drawBorder(_ borderPath: CGPath, context: CGContext) { context.addPath(borderPath) context.setStrokeColor(preferences.drawing.borderColor.cgColor) context.setLineWidth(preferences.drawing.borderWidth) context.strokePath() } fileprivate func drawText(_ bubbleFrame: CGRect, context : CGContext) { guard case .text(let text) = content else { return } let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = preferences.drawing.textAlignment paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping let textRect = getContentRect(from: bubbleFrame) #if swift(>=4.2) let attributes = [NSAttributedString.Key.font : preferences.drawing.font, NSAttributedString.Key.foregroundColor : preferences.drawing.foregroundColor, NSAttributedString.Key.paragraphStyle : paragraphStyle] #else let attributes = [NSAttributedStringKey.font : preferences.drawing.font, NSAttributedStringKey.foregroundColor : preferences.drawing.foregroundColor, NSAttributedStringKey.paragraphStyle : paragraphStyle] #endif text.draw(in: textRect, withAttributes: attributes) } fileprivate func drawShadow() { if preferences.hasShadow { self.layer.masksToBounds = false self.layer.shadowColor = preferences.drawing.shadowColor.cgColor self.layer.shadowOffset = preferences.drawing.shadowOffset self.layer.shadowRadius = preferences.drawing.shadowRadius self.layer.shadowOpacity = Float(preferences.drawing.shadowOpacity) } } override open func draw(_ rect: CGRect) { let bubbleFrame = getBubbleFrame() let context = UIGraphicsGetCurrentContext()! context.saveGState () drawBubble(bubbleFrame, arrowPosition: preferences.drawing.arrowPosition, context: context) switch content { case .text: drawText(bubbleFrame, context: context) case .view (let view): addSubview(view) } drawShadow() context.restoreGState() } private func getBubbleFrame() -> CGRect { let arrowPosition = preferences.drawing.arrowPosition let bubbleWidth: CGFloat let bubbleHeight: CGFloat let bubbleXOrigin: CGFloat let bubbleYOrigin: CGFloat switch arrowPosition { case .bottom, .top, .any: bubbleWidth = tipViewSize.width - 2 * preferences.positioning.bubbleHInset bubbleHeight = tipViewSize.height - 2 * preferences.positioning.bubbleVInset - preferences.drawing.arrowHeight bubbleXOrigin = preferences.positioning.bubbleHInset bubbleYOrigin = arrowPosition == .bottom ? preferences.positioning.bubbleVInset : preferences.positioning.bubbleVInset + preferences.drawing.arrowHeight case .left, .right: bubbleWidth = tipViewSize.width - 2 * preferences.positioning.bubbleHInset - preferences.drawing.arrowHeight bubbleHeight = tipViewSize.height - 2 * preferences.positioning.bubbleVInset bubbleXOrigin = arrowPosition == .right ? preferences.positioning.bubbleHInset : preferences.positioning.bubbleHInset + preferences.drawing.arrowHeight bubbleYOrigin = preferences.positioning.bubbleVInset } return CGRect(x: bubbleXOrigin, y: bubbleYOrigin, width: bubbleWidth, height: bubbleHeight) } private func getContentRect(from bubbleFrame: CGRect) -> CGRect { return CGRect(x: bubbleFrame.origin.x + (bubbleFrame.size.width - contentSize.width) / 2, y: bubbleFrame.origin.y + (bubbleFrame.size.height - contentSize.height) / 2, width: contentSize.width, height: contentSize.height) } }
mit
a57e16116688e58065788b5242d911b5
45.041056
379
0.646688
5.190083
false
false
false
false
spearal/SpearalIOS
SpearalIOS/SpearalContextImpl.swift
1
4184
/** * == @Spearal ==> * * Copyright (C) 2014 Franck WOLFF & William DRAI (http://www.spearal.io) * * 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. */ // author: Franck WOLFF import Foundation private func bigNumberAplha() -> [UInt8] { var bytes = [UInt8]() bytes.extend("0123456789+-.E".utf8) return bytes } let BIG_NUMBER_ALPHA = bigNumberAplha() private func bigNumberAplhaMirror() -> [UInt8] { var bytes = [UInt8](count: 0xff, repeatedValue: 0) for i in 0...(BIG_NUMBER_ALPHA.count - 1) { bytes[Int(BIG_NUMBER_ALPHA[i])] = UInt8(i) } return bytes } let BIG_NUMBER_ALPHA_MIRROR = bigNumberAplhaMirror() class SpearalContextImpl: SpearalContext { private var introspector:SpearalIntrospector? private var aliasStrategy:SpearalAliasStrategy? private var coderProviders:[SpearalCoderProvider] private var codersCache:[String: SpearalCoder] private var converterProviders:[SpearalConverterProvider] private var convertersCache:[String: SpearalConverter] init() { self.coderProviders = [SpearalCoderProvider]() self.codersCache = [String: SpearalCoder]() self.converterProviders = [SpearalConverterProvider]() self.convertersCache = [String: SpearalConverter]() } func configure(introspector:SpearalIntrospector) -> SpearalContext { self.introspector = introspector return self } func configure(converterProvider:SpearalConverterProvider, append:Bool) -> SpearalContext { if append { converterProviders.append(converterProvider) } else { converterProviders.insert(converterProvider, atIndex: 0) } return self } func configure(aliasStrategy:SpearalAliasStrategy) -> SpearalContext { self.aliasStrategy = aliasStrategy return self } func configure(coderProvider:SpearalCoderProvider, append:Bool) -> SpearalContext { if append { coderProviders.append(coderProvider) } else { coderProviders.insert(coderProvider, atIndex: 0) } return self } func getIntrospector() -> SpearalIntrospector? { return self.introspector } func getAliasStrategy() -> SpearalAliasStrategy? { return self.aliasStrategy } func getCoderFor(any:Any) -> SpearalCoder? { if !coderProviders.isEmpty { let key:String = introspector!.classNameOfAny(any)! if let coder = codersCache[key] { return coder } for provider in coderProviders { if let coder = provider.coder(any) { codersCache[key] = coder return coder } } } return nil } func getConverterFor(any:Any?) -> SpearalConverter? { if !converterProviders.isEmpty { let key:String = introspector!.classNameOfAny(any)! if let converter = convertersCache[key] { return converter } for provider in converterProviders { if let converter = provider.converter(any) { convertersCache[key] = converter return converter } } } return nil } func convert(any:Any?, context:SpearalConverterContext) -> Any? { if let converter = getConverterFor(any) { return converter.convert(any, context: context) } return any } }
apache-2.0
4474d13ccc72b0d71fc50bdb751cb3e5
28.892857
95
0.613528
4.722348
false
false
false
false
hiragram/AbstractionKit
AbstractionKitTests/Dictionary+decode.swift
1
1761
// // Dictionary+decode.swift // AbstractionKit // // Created by Yuya Hirayama on 2017/09/24. // Copyright © 2017年 Yuya Hirayama. All rights reserved. // import Foundation extension Dictionary where Key == String { func getValue<T>(forKey key: Key) throws -> T { guard let value = self[key] else { throw DictionaryExtractionError.keyNotFound(key) } guard let castedValue = value as? T else { throw DictionaryExtractionError.castFailed(key: key, expectedType: T.self, actualValue: value) } return castedValue } func getArray<T>(forKey key: Key) throws -> [T] { guard let value = self[key] else { throw DictionaryExtractionError.keyNotFound(key) } guard let array = value as? [T] else { throw DictionaryExtractionError.castFailed(key: key, expectedType: [T].self, actualValue: value) } return array } func getURL(forKey key: Key) throws -> URL? { guard let value = self[key] else { return nil } guard let urlStr = value as? String else { throw DictionaryExtractionError.castFailed(key: key, expectedType: String.self, actualValue: value) } return URL.init(string: urlStr) } func getURL(forKey key: Key) throws -> URL { guard let url = try getURL(forKey: key) as URL? else { throw DictionaryExtractionError.convertToURLFailed(key: key, actualValue: self[key] as Any) } return url } } enum DictionaryExtractionError: Error { case keyNotFound(String) case castFailed(key: String, expectedType: Any.Type, actualValue: Any) case convertToURLFailed(key: String, actualValue: Any) }
mit
be2bdd03b0b2f49c55cfd70bb0a9a697
30.392857
111
0.634243
4.308824
false
false
false
false
songhailiang/NLSegmentControl
NLSegmentControlExample/Category.swift
1
1034
// // Category.swift // NLSegmentControlExample // // Created by songhailiang on 10/07/2017. // Copyright © 2017 hailiang.song. All rights reserved. // import UIKit import NLSegmentControl struct Category { var categoryTitle: String? var categoryDesc: String? var categoryImage: String? var categorySelectedImage: String? init(title: String? = nil, desc: String? = nil, image: String? = nil, selectedImage: String? = nil) { self.categoryTitle = title self.categoryDesc = desc self.categoryImage = image self.categorySelectedImage = selectedImage } } extension Category: NLSegmentDataSource { var segmentTitle: String? { return categoryTitle } var segmentImage: UIImage? { if let img = categoryImage { return UIImage(named: img) } return nil } var segmentSelectedImage: UIImage? { if let img = categorySelectedImage { return UIImage(named: img) } return nil } }
mit
66d62c23758535327206127d85f0ab2e
23.595238
105
0.63698
4.340336
false
false
false
false
gkaimakas/SwiftValidatorsReactiveExtensions
Example/SwiftValidatorsReactiveExtensions/Views/SumbitView/SumbitView.swift
1
1719
// // SumbitView.swift // SwiftValidatorsReactiveExtensions // // Created by George Kaimakas on 05/04/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import ReactiveCocoa import ReactiveSwift import Result import UIKit public class SumbitView: UIView { @IBOutlet weak var button: UIButton! public var credentialsAction: Action<Void, Credentials, NSError>? { didSet { guard let action = credentialsAction else { return } button.reactive.isEnabled <~ action.isEnabled button.reactive.pressed = CocoaAction(action) button.reactive.backgroundColor <~ action.isEnabled .producer .map({ (enabled: Bool) -> UIColor in return enabled ? UIColor.lightGray : UIColor.white }) button.setTitleColor(.white, for: .normal) button.setTitleColor(.white, for: .disabled) } } public override init(frame: CGRect) { super.init(frame: frame) initializeView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeView() } func initializeView() { let view: UIView? = Bundle(for: SumbitView.self) .loadNibNamed(String(describing: SumbitView.self), owner: self, options: nil)?.last as? UIView if let view = view { view.frame = self.bounds view.autoresizingMask = [.flexibleHeight, .flexibleWidth] addSubview(view) } self.backgroundColor = UIColor.clear } }
mit
5e15e82c8ee6a73974b8e84f459fa544
27.163934
106
0.582654
4.994186
false
false
false
false
david1mdavis/IOS-nRF-Toolbox
nRF Toolbox/UART/Pixel.swift
1
3604
// // Pixel.swift // nRF Toolbox // // Created by David on 4/27/17. // Copyright © 2017 Nordic Semiconductor. All rights reserved. // import Foundation import UIKit public struct Pixel { public var value: UInt32 //red public var R: UInt8 { get { return UInt8(value & 0xFF); } set { value = UInt32(newValue) | (value & 0xFFFFFF00) } } //green public var G: UInt8 { get { return UInt8((value >> 8) & 0xFF) } set { value = (UInt32(newValue) << 8) | (value & 0xFFFF00FF) } } //blue public var B: UInt8 { get { return UInt8((value >> 16) & 0xFF) } set { value = (UInt32(newValue) << 16) | (value & 0xFF00FFFF) } } //alpha public var A: UInt8 { get { return UInt8((value >> 24) & 0xFF) } set { value = (UInt32(newValue) << 24) | (value & 0x00FFFFFF) } } } public struct RGBAImage { public var pixels: UnsafeMutableBufferPointer<Pixel> public var width: Int public var height: Int public init?(image: UIImage) { guard let cgImage = image.cgImage else { return nil } width = Int(image.size.width) height = Int(image.size.height) let bytesPerRow = width * 4 let imageData = UnsafeMutablePointer<Pixel>.allocate(capacity: width * height) let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue bitmapInfo = bitmapInfo | CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue guard let imageContext = CGContext(data: imageData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else { return nil } imageContext.draw(cgImage, in: CGRect(origin: .zero, size: image.size)) pixels = UnsafeMutableBufferPointer<Pixel>(start: imageData, count: width * height) } public func toUIImage() -> UIImage? { let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue let bytesPerRow = width * 4 bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue guard let imageContext = CGContext(data: pixels.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) else { return nil } guard let cgImage = imageContext.makeImage() else { return nil } let image = UIImage(cgImage: cgImage) return image } public func pixel(x : Int, _ y : Int) -> Pixel? { guard x >= 0 && x < width && y >= 0 && y < height else { return nil } let address = y * width + x return pixels[address] } public func pixel(x : Int, _ y : Int, _ pixel: Pixel) { guard x >= 0 && x < width && y >= 0 && y < height else { return } let address = y * width + x pixels[address] = pixel } public func process( functor : ((Pixel) -> Pixel) ) { for y in 0..<height { for x in 0..<width { let index = y * width + x let outPixel = functor(pixels[index]) pixels[index] = outPixel } } } }
bsd-3-clause
548d2426c9255b5737b31623b1af71e8
30.330435
235
0.571191
4.459158
false
false
false
false
ivanbruel/SwipeIt
SwipeIt/Models/Link.swift
1
6408
// // Link.swift // Reddit // // Created by Ivan Bruel on 04/03/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import Foundation import ObjectMapper // https://github.com/reddit/reddit/wiki/JSON struct Link: Votable, Mappable { private static let imageExtensionRegex = "(.jpe?g|.png|.gif)" private static let imageURLRegexes = ["^https?://.*imgur.com/", "^https?://.*reddituploads.com/", "^https?://(?: www.)?gfycat.com/", "^https?://.*.media.tumblr.com/", imageExtensionRegex] private static let redditShortURL = NSURL(string: "http://redd.it/")! private static let redditURL = NSURL(string: Constants.redditURL)! // MARK: Thing var identifier: String! var name: String! var kind: String! // MARK: Votable var downs: Int! var ups: Int! var vote: Vote! var score: Int! // MARK: Created var created: NSDate! // MARK: Link var author: String! var authorFlairClass: String? var authorFlairText: String? var clicked: Bool! var domain: String! var hidden: Bool! var selfPost: Bool! var linkFlairClass: String? var linkFlairText: String? var locked: Bool! var upvoteRatio: Float? var media: Media? var secureMedia: Media? var embeddedMedia: EmbeddedMedia? var secureEmbeddedMedia: EmbeddedMedia? var previewImages: [PreviewImage]? var totalComments: Int! var nsfw: Bool! var permalink: String! var saved: Bool! var selfText: String? var selfTextHTML: String? var subreddit: String! var subredditId: String! var thumbnailURL: NSURL? var title: String! var url: NSURL! var edited: Edited! var distinguished: Distinguished? var stickied: Bool! var gilded: Int! var visited: Bool! var postHint: PostHint? // MARK: Misc var approvedBy: String! var bannedBy: String? var suggestedSort: String? var userReports: [String]? var fromKind: String? var archived: Bool! var reportReasons: String? var hideScore: Bool! var removalReason: String? var from: String? var fromId: String? var quarantine: Bool! var modReports: [String]? var totalReports: Int! // MARK: Accessors var subredditURL: NSURL { return NSURL(string: "\(Constants.redditURL)/r/\(subreddit)")! } var authorURL: NSURL { return NSURL(string: "\(Constants.redditURL)/u/\(author)")! } private var previewImage: PreviewImage? { return previewImages?.first } var imageURL: NSURL? { if let imageURL = ImgurImageProvider.imageURLFromLink(self) { return imageURL } guard postHint == .Image else { return nil } if let imageURL = previewImage?.gifSource?.url { return imageURL } if let imageURL = previewImage?.nsfwSource?.url { return imageURL } if let imageURL = previewImage?.source.url { return imageURL } return url.absoluteString.matchesWithRegex(Link.imageExtensionRegex) ? url : nil } var isSpoiler: Bool { return title.lowercaseString.containsString("spoiler") } var type: LinkType { return LinkType.typeFromLink(self) } var imageSize: CGSize? { return previewImage?.gifSource?.size ?? previewImage?.nsfwSource?.size ?? previewImage?.source.size } var shortURL: NSURL { return Link.redditShortURL.URLByAppendingPathComponent(identifier) } var permalinkURL: NSURL { return Link.redditURL.URLByAppendingPathComponent(permalink) } var scoreWithoutVote: Int { if vote == .Upvote { return score - 1 } else if vote == .Downvote { return score + 1 } return score } func scoreWithVote(voted: Vote) -> Int { switch voted { case .Upvote: return scoreWithoutVote + 1 case .Downvote: return scoreWithoutVote - 1 case .None: return scoreWithoutVote } } // MARK: JSON init?(_ map: Map) { // Fail if no data is found guard let _ = map.JSONDictionary["data"] else { return nil } } mutating func mapping(map: Map) { mappingVotable(map) mappingLink(map) mappingMisc(map) } private mutating func mappingLink(map: Map) { author <- map["data.author"] upvoteRatio <- map["data.upvote_ratio"] authorFlairClass <- map["data.author_flair_css_class"] authorFlairText <- (map["data.author_flair_text"], EmptyStringTransform()) clicked <- map["data.clicked"] domain <- map["data.domain"] hidden <- map["data.hidden"] selfPost <- map["data.is_self"] linkFlairClass <- map["data.link_flair_css_class"] linkFlairText <- (map["data.link_flair_text"], EmptyStringTransform()) locked <- map["data.locked"] media <- map["data.media"] secureMedia <- map["data.secure_media"] embeddedMedia <- map["data.media_embed"] secureEmbeddedMedia <- map["data.secure_media_embed"] thumbnailURL <- map["data.thumbnail"] totalComments <- map["data.num_comments"] nsfw <- map["data.over_18"] permalink <- map["data.permalink"] saved <- map["data.saved"] selfText <- (map["data.selftext"], EmptyStringTransform()) selfTextHTML <- map["data.selftext_html"] subreddit <- map["data.subreddit"] subredditId <- map["data.subreddit_id"] thumbnailURL <- (map["data.thumbnail"], EmptyURLTransform()) title <- (map["data.title"], HTMLEncodingTransform()) url <- (map["data.url"], EmptyURLTransform()) edited <- (map["data.edited"], EditedTransform()) distinguished <- map["data.distinguished"] stickied <- map["data.stickied"] gilded <- map["data.gilded"] visited <- map["data.visited"] previewImages <- map["data.preview.images"] postHint <- map["data.post_hint"] } private mutating func mappingMisc(map: Map) { approvedBy <- map["data.approved_by"] bannedBy <- map["data.banned_by"] suggestedSort <- map["data.suggested_sort"] userReports <- (map["data.user_reports"], EmptyArrayTransform()) fromKind <- map["data.from_kind"] archived <- map["data.archived"] reportReasons <- map["data.report_reasons"] hideScore <- map["data.hide_score"] removalReason <- map["data.removal_reason"] from <- map["data.from"] fromId <- map["data.from_id"] quarantine <- map["data.quarantine"] modReports <- (map["data.mod_reports"], EmptyArrayTransform()) totalReports <- (map["data.num_reports"], ZeroDefaultTransform()) } }
mit
2c6c11f798a169d0b34e36f8f2420647
26.978166
99
0.656938
3.911477
false
false
false
false
invalidstream/cocoaconfappextensionsclass
CocoaConf App Extensions Class/CocoaConfExtensions_07_Watch_End/CocoaConf Action + JS/ActionRequestHandler.swift
3
4287
// // ActionRequestHandler.swift // CocoaConf Action + JS // // Created by Chris Adamson on 3/25/15. // Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved. // import UIKit import MobileCoreServices class ActionRequestHandler: NSObject, NSExtensionRequestHandling { var extensionContext: NSExtensionContext? func beginRequestWithExtensionContext(context: NSExtensionContext) { // Do not call super in an Action extension with no user interface self.extensionContext = context var found = false // Find the item containing the results from the JavaScript preprocessing. outer: for item: AnyObject in context.inputItems { let extItem = item as! NSExtensionItem if let attachments = extItem.attachments { for itemProvider: AnyObject in attachments { NSLog ("itemProvider: \(itemProvider)") if itemProvider.hasItemConformingToTypeIdentifier(String(kUTTypePropertyList)) { NSLog ("property list") itemProvider.loadItemForTypeIdentifier(String(kUTTypePropertyList), options: nil, completionHandler: { (item, error) in let dictionary = item as! [String: AnyObject] print ("dictionary \(dictionary)") NSOperationQueue.mainQueue().addOperationWithBlock { self.itemLoadCompletedWithPreprocessingResults(dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as! [NSObject: AnyObject]) } // found = true // apple bug }) found = true // fix apple bug if found { break outer } } } } } if !found { self.doneWithResults(nil) } } func itemLoadCompletedWithPreprocessingResults(javaScriptPreprocessingResults: [NSObject: AnyObject]) { // Here, do something, potentially asynchronously, with the preprocessing // results. // In this very simple example, the JavaScript will have passed us the // current background color style, if there is one. We will construct a // dictionary to send back with a desired new background color style. let bgColor: AnyObject? = javaScriptPreprocessingResults["currentBackgroundColor"] if bgColor == nil || bgColor! as! String == "" { // No specific background color? Request setting the background to red. self.doneWithResults(["newBackgroundColor": "red"]) } else { // Specific background color is set? Request replacing it with green. self.doneWithResults(["newBackgroundColor": "green"]) } } func doneWithResults(resultsForJavaScriptFinalizeArg: [NSObject: AnyObject]?) { if let resultsForJavaScriptFinalize = resultsForJavaScriptFinalizeArg { // Construct an NSExtensionItem of the appropriate type to return our // results dictionary in. // These will be used as the arguments to the JavaScript finalize() // method. let resultsDictionary = [NSExtensionJavaScriptFinalizeArgumentKey: resultsForJavaScriptFinalize] let resultsProvider = NSItemProvider(item: resultsDictionary, typeIdentifier: String(kUTTypePropertyList)) let resultsItem = NSExtensionItem() resultsItem.attachments = [resultsProvider] // Signal that we're complete, returning our results. self.extensionContext!.completeRequestReturningItems([resultsItem], completionHandler: nil) } else { // We still need to signal that we're done even if we have nothing to // pass back. self.extensionContext!.completeRequestReturningItems([], completionHandler: nil) } // Don't hold on to this after we finished with it. self.extensionContext = nil } }
cc0-1.0
a7801a3499fc2a4d45222cfbf7ab8b59
43.195876
166
0.602519
6.360534
false
false
false
false
dymx101/NiuBiBookCity
BookMountain/Model/BCTBookChapterModel.swift
1
411
// Converted with Swiftify v1.0.6341 - https://objectivec2swift.com/ // // BookChapterModel.h // BookCity // // Created by apple on 16/1/14. // Copyright © 2016年 FS. All rights reserved. // import Foundation // 章节 class BCTBookChapterModel: NSObject { var hostUrl: String = "" var title: String = "" var url: String = "" var content: String = "" var htmlContent: String = "" }
gpl-3.0
5b4ef74458b0dd3e96e5bcf8dd8a00f4
20.263158
69
0.641089
3.232
false
false
false
false
rudkx/swift
test/type/opaque_return_named.swift
1
5032
// RUN: %target-typecheck-verify-swift -enable-experimental-named-opaque-types -disable-availability-checking // Tests for experimental extensions to opaque return type support. func f0() -> <T> T { return () } func f1() -> <T, U, V> T { () } // FIXME better diagnostic: expected-error@-1{{generic parameter 'U' could not be inferred}} // FIXME better diagnostic: expected-error@-2{{generic parameter 'V' could not be inferred}} func f2() -> <T: Collection, U: SignedInteger> T { // expected-note{{required by opaque return type of global function 'f2()'}} () // expected-error{{type '()' cannot conform to 'Collection'}} // expected-note@-1{{only concrete types such as structs, enums and classes can conform to protocols}} // expected-error@-2{{generic parameter 'U' could not be inferred}} } func f4() async -> <T> T { () } func g0() -> <T> { } // expected-error{{expected type for function result}} func g1() -> async <T> T { () } // expected-error{{'async' may only occur before '->'}} func g2() -> <T> T async { () } // expected-error{{'async' may only occur before '->'}} let x0: <T> Int = 1 var x1: <T> (Int, Int) = (1, 1) var x2: <T> (<U> Int, Int) = (1, 1) // expected-error{{expected type}} expected-error{{cannot convert value of type '(Int, Int)' to specified type 'Int'}} for _: <T> Int in [1, 2, 3] { } // FIXME mention of 'some' is wrong: expected-error{{some' type can only be declared on a single property declaration}} struct S0 { subscript(i: Int) -> <T> T { 1 } } protocol P { } extension Int: P { } protocol Q { } func h0() -> <T: P> T { 5 } func h1() -> <T: P> T { // expected-note{{opaque return type declared here}} 3.14159 // expected-error{{return type of global function 'h1()' requires that 'Double' conform to 'P'}} } func h2() -> <T: P & Q> T { // expected-note{{opaque return type declared here}} 3 // expected-error{{return type of global function 'h2()' requires that 'Int' conform to 'Q'}} } func test_h0() { // Make sure we can treat h0 as a P let _: P = h0() } protocol P1 { associatedtype A } protocol Q1 { associatedtype B } extension Int: P1 { typealias A = String } extension String: P1 { typealias A = String } extension Double: Q1 { typealias B = String } extension String: Q1 { typealias B = Int } func f1() -> <T: P1, U where U: Q1> (T, U) { return (3, 3.14159) } func f2(cond: Bool) -> <T: P1, U where U: Q1> (T, U) { if cond { return (3, 3.14159) } else { return (3, 2.71828) } } func f3(cond: Bool) -> <T: P1, U where U: Q1> (T, U) { // expected-error@-1{{function declares an opaque return type 'U', but the return statements in its body do not have matching underlying types}} if cond { return (3, 3.14159) // expected-note{{return statement has underlying type 'Double'}} } else { return (3, "hello") // expected-note{{return statement has underlying type 'String'}} } } func f4(cond: Bool) -> <T: P1, U where U: Q1> (T, U) { if cond { return (3, 3.14159) } else { } } func f5(cond: Bool) -> <T: P1, U where U: Q1> (T, U) { } // expected-error@-1{{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} protocol DefaultInitializable { init() } extension String: DefaultInitializable { } extension Int: DefaultInitializable { } struct Generic<T: P1 & Equatable & DefaultInitializable> where T.A: DefaultInitializable { var value: T func f() -> <U: Q1, V: P1 where U: Equatable, V: Equatable> (U, V) { return ("hello", value) } subscript(index: Int) -> <U: Q1, V: P1 where U: Equatable, V: Equatable> (U, V) { return ("hello", value) } var property: <U: Q1, V: P1 where U: Equatable, V: Equatable> (U, V) { return ("hello", value) } var property2: <U: Q1, V: P1 where U: Equatable, V: Equatable> (U, V) = ("hello", T()) var property3: <U: Q1, V: P1 where U: Equatable, V: Equatable> (U, V) = ("hello", T()) { didSet { print("here") } } // FIXME: expected-warning@+2{{redundant same-type constraint 'C.Element' == 'T.A'}} // FIXME: expected-note@+1{{previous same-type constraint 'C.Element' == 'T.A' written here}} func sameTypeParams() -> <C: Collection where C.Element == T.A> C { [ T.A(), T.A() ] } // FIXME: expected-warning@+2{{redundant same-type constraint 'C.Element' == 'T.A'}} // FIXME: expected-note@+1{{previous same-type constraint 'C.Element' == 'T.A' written here}} func sameTypeParamsBad() -> <C: Collection where C.Element == T.A> C { [ T() ] // expected-error{{cannot convert value of type 'T' to expected element type 'T.A'}} } } func testGeneric(i: Int, gs: Generic<String>, gi: Generic<Int>) { let gs1 = gs.f() let gs2 = gs.f() _ = (gs1 == gs2) let gi1 = gi.f() // FIXME: Diagnostic below is correct, but a bit misleading because these are different Us and Vs. _ = (gs1 == gi1) // expected-error{{binary operator '==' cannot be applied to operands of type '(U, V)' and '(U, V)'}} _ = gs[i] }
apache-2.0
6e743e78c3b29ff01b54d62c54a679a6
30.647799
154
0.62659
3.127408
false
false
false
false
netguru/ResponseDetective
ResponseDetective/Sources/ConsoleOutputFacility.swift
1
4480
// // ConsoleOutputFacility.swift // // Copyright © 2016-2020 Netguru S.A. All rights reserved. // Licensed under the MIT License. // import Foundation /// An output facility which outputs requests, responses and errors to console. @objc(RDTConsoleOutputFacility) public final class ConsoleOutputFacility: NSObject, OutputFacility { // MARK: Initializers /// Initializes the receiver with default print closure. public convenience override init() { self.init(printClosure: { print($0) }) } /// Initializes the receiver. /// /// - Parameters: /// - printClosure: The print closure used to output strings into the /// console. @objc(initWithPrintBlock:) public init(printClosure: @escaping @convention(block) (String) -> Void) { self.printClosure = printClosure } // MARK: Properties /// Print closure used to output strings into the console. private let printClosure: @convention(block) (String) -> Void // MARK: OutputFacility /// Prints the request in the following format: /// /// <0xbadf00d> [REQUEST] POST https://httpbin.org/post /// ├─ Headers /// │ Content-Type: application/json /// │ Content-Length: 14 /// ├─ Body /// │ { /// │ "foo": "bar" /// │ } /// /// - SeeAlso: OutputFacility.output(requestRepresentation:) public func output(requestRepresentation request: RequestRepresentation) { let headers = request.headers.reduce([]) { $0 + ["\($1.0): \($1.1)"] } let body = request.deserializedBody.map { #if swift(>=3.2) return $0.split { $0 == "\n" }.map(String.init) #else return $0.characters.split { $0 == "\n" }.map(String.init) #endif } ?? ["<none>"] printBoxString(title: "<\(request.identifier)> [REQUEST] \(request.method) \(request.urlString)", sections: [ ("Headers", headers), ("Body", body), ]) } /// Prints the response in the following format: /// /// <0xbadf00d> [RESPONSE] 200 (NO ERROR) https://httpbin.org/post /// ├─ Headers /// │ Content-Type: application/json /// │ Content-Length: 24 /// ├─ Body /// │ { /// │ "args": {}, /// │ "headers": {} /// │ } /// /// - SeeAlso: OutputFacility.output(responseRepresentation:) public func output(responseRepresentation response: ResponseRepresentation) { let headers = response.headers.reduce([]) { $0 + ["\($1.0): \($1.1)"] } let body = response.deserializedBody.map { #if swift(>=3.2) return $0.split { $0 == "\n" }.map(String.init) #else return $0.characters.split { $0 == "\n" }.map(String.init) #endif } ?? ["<none>"] printBoxString(title: "<\(response.requestIdentifier)> [RESPONSE] \(response.statusCode) (\(response.statusString.uppercased())) \(response.urlString)", sections: [ ("Headers", headers), ("Body", body), ]) } /// Prints the error in the following format: /// /// <0xbadf00d> [ERROR] NSURLErrorDomain -1009 /// ├─ User Info /// │ NSLocalizedDescriptionKey: The device is not connected to the internet. /// │ NSURLErrorKey: https://httpbin.org/post /// /// - SeeAlso: OutputFacility.output(errorRepresentation:) public func output(errorRepresentation error: ErrorRepresentation) { let userInfo = error.userInfo.reduce([]) { $0 + ["\($1.0): \($1.1)"] } printBoxString(title: "<\(error.requestIdentifier)> [ERROR] \(error.domain) \(error.code)", sections: [ ("User Info", userInfo), ]) } // MARK: Printing boxes /// Composes a box string in the following format: /// /// box title /// ├─ section title /// │ section /// │ contents /// /// - Parameters: /// - title: The title of the box /// - sections: A dictionary with section titles as keys and content /// lines as values. /// /// - Returns: A composed box string. private func composeBoxString(title: String, sections: [(String, [String])]) -> String { return "\(title)\n" + sections.reduce("") { "\($0) ├─ \($1.0)\n" + $1.1.reduce("") { "\($0) │ \($1)\n" } } } /// Composes and prints the box sting in the console. /// /// - Parameters: /// - title: The title of the box /// - sections: A dictionary with section titles as keys and content /// lines as values. private func printBoxString(title: String, sections: [(String, [String])]) { printClosure(composeBoxString(title: title, sections: sections)) } }
mit
92939aa5fa7e766a5f54d4c1138c867a
29.475862
166
0.617108
3.433566
false
false
false
false
alexcurylo/iso3166-flags-maps-worldheritage
masterlister/Masterlister/WonderlistVC.swift
1
8147
// @copyright Trollwerks Inc. import Cocoa final class WonderlistVC: NSViewController { struct Wonder: Codable { let id: Int // expect owner ID + 1...7 for wonders, 8... for finalists let title: String let url: URL let whs: Int? let twhs: Int? let link: URL? var isWonder: Bool { return (id % 100) <= 7 } var isFinalist: Bool { return !isWonder } } struct Wonders: Codable { let id: Int // expect [100, 200, 300, ...] to combine with wonder ID let title: String let url: URL let wonders: [Wonder] let finalists: [Wonder] var total: Int { return wonders.count + finalists.count } } var wondersCount = 0 var finalistsCount = 0 lazy var wondersList: [Wonders] = { let path = Bundle.main.path(forResource: "new7wonders", ofType: "json") var array: [Wonders] = [] do { // swiftlint:disable:next force_unwrapping let data = try Data(contentsOf: URL(fileURLWithPath: path!)) array = try JSONDecoder().decode([Wonders].self, from: data) } catch { print("Error decoding new7wonders.json", error) } assert(array.count == 3, "Should be 3 collections in 2018") wondersCount = array.reduce(0) { $0 + $1.wonders.count } finalistsCount = array.reduce(0) { $0 + $1.finalists.count } assert(wondersCount == 7 + 7 + 7, "Should be 21 wonders in 2018") assert(finalistsCount == 14 + 21 + 21, "Should be 56 finalists in 2018") let wondersIDs = array.map { $0.id } assert(Set(wondersIDs).count == array.count, "Should not have duplicate Wonders IDs") let wonderList: [Wonder] = array.reduce([]) { $0 + $1.wonders + $1.finalists } let wonderIDs = wonderList.map { $0.id } assert(Set(wonderIDs).count == wonderList.count, "Should not have duplicate Wonder IDs") return array }() struct Visit: Codable { let wonder: Int? let whs: Int? let twhs: Int? let visit: URL? let stay: URL? let eat: URL? } lazy var visits: [Visit] = { let path = Bundle.main.path(forResource: "visits", ofType: "json") var array: [Visit] = [] do { // swiftlint:disable:next force_unwrapping let data = try Data(contentsOf: URL(fileURLWithPath: path!)) array = try JSONDecoder().decode([Visit].self, from: data) } catch { print("Error decoding visits", error) } let ids = array.compactMap { $0.wonder } let duplicates = Array(Set(ids.filter { (i: Int) in ids.filter { $0 == i }.count > 1 })) assert(duplicates.isEmpty, "Should not have duplicate Wonder visits \(duplicates)") let wonderList: [Wonder] = wondersList.reduce([]) { $0 + $1.wonders + $1.finalists } let wonderIDs = wonderList.map { $0.id } let wrong = Set(ids).subtracting(wonderIDs) assert(wrong.isEmpty, "Should not have wrong Wonder visits \(wrong)") return array }() @IBOutlet private var output: NSTextView! var wondersVisited = 0 var finalistsVisited = 0 override func viewDidLoad() { super.viewDidLoad() generate(for: .wordpress) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } func generate(for type: Document) { writeHeader(for: type) writeWondersList() writeFooter(for: type) } func writeHeader(for type: Document) { if type == .html { let htmlHeader = NSAttributedString(string: """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sitelist</title> </head> <body>\n """) output.textStorage?.append(htmlHeader) } let textHeader = NSAttributedString(string: """ <p><strong>The <a href="https://new7wonders.com">New7Wonders</a> Master Wonderlist</strong></p> <p><small>Wonders are in plain text<br> <i>Finalists are in italic text</i></small></p> \n """) output.textStorage?.append(textHeader) } func writeWondersList() { for wonders in wondersList { let listStart = NSAttributedString(string: """ <p><strong><a href="\(wonders.url)">\(wonders.title)</a>:</strong></p> """) output.textStorage?.append(listStart) writeWonders(in: wonders.wonders) writeWonders(in: wonders.finalists) let listEnd = NSAttributedString(string: """ \n\n """) output.textStorage?.append(listEnd) } } func writeWonders(in wonders: [Wonder]) { guard let inItalic = wonders.first?.isFinalist else { return } let wondersStart = NSAttributedString(string: "<p>" + (inItalic ? "<i>" : "")) output.textStorage?.append(wondersStart) let sortedWonders = wonders.sorted { $0.title < $1.title } for wonder in sortedWonders { let link = """ <a href="\(wonder.url)">\(wonder.title)</a> """ var mark = Visited.no.rawValue var blogLinks = "" if let visited = visits.first(where: { $0.wonder == wonder.id }) { if wonder.isWonder { wondersVisited += 1 } else { finalistsVisited += 1 } mark = Visited.yes.rawValue var visitLink = "" var stayLink = "" var eatLink = "" if let visitURL = visited.visit { visitLink = " — <a href=\"\(visitURL)\">Visit</a>" } if let stayURL = visited.stay { stayLink = " — <a href=\"\(stayURL)\">Stay</a>" } if let eatURL = visited.eat { eatLink = " — <a href=\"\(eatURL)\">Eat</a>" } if !visitLink.isEmpty || !stayLink.isEmpty || !eatLink.isEmpty { blogLinks = "<small>\(visitLink)\(stayLink)\(eatLink)</small>" } } let wonderLine = NSAttributedString(string: "\(mark) \(link)\(blogLinks)<br>\n") output.textStorage?.append(wonderLine) } let wondersEnd = NSAttributedString(string: (inItalic ? "</i>" : "") + "</p>") output.textStorage?.append(wondersEnd) } func writeFooter(for type: Document) { assert(wondersVisited == 17, "Should be 17 wonders visited not \(wondersVisited) (2019.10.30)") assert(finalistsVisited == 44, "Should be 44 finalists visited not \(finalistsVisited) (2019.04.22)") let wondersPercent = String(format: "%.1f", Float(wondersVisited) / Float(wondersCount) * 100) let finalistsPercent = String(format: "%.1f", Float(finalistsVisited) / Float(finalistsCount) * 100) let total = wondersCount + finalistsCount let totalVisits = wondersVisited + finalistsVisited let totalPercent = String(format: "%.1f", Float(totalVisits) / Float(total) * 100) // swiftlint:disable line_length let textFooter = NSAttributedString(string: """ <p><small>Wonders: \(wondersVisited)/\(wondersCount) (\(wondersPercent)%) — Finalists: \(finalistsVisited)/\(finalistsCount) (\(finalistsPercent)%) — TOTAL: \(totalVisits)/\(total) (\(totalPercent)%)</small></p>\n """) // swiftlint:enable line_length output.textStorage?.append(textFooter) if type == .html { let htmlFooter = NSAttributedString(string: """ </body> </html> """) output.textStorage?.append(htmlFooter) } } }
mit
de8fdddfeec7d45551b2ff476513ccd6
35.164444
225
0.542706
4.360665
false
false
false
false
dclelland/HOWL
HOWL/Models/Settings/Property.swift
1
1074
// // InstrumentProperty.swift // HOWL // // Created by Daniel Clelland on 2/04/17. // Copyright © 2017 Daniel Clelland. All rights reserved. // import AudioKit import Persistable // MARK: Instrument properties class Property: AKInstrumentProperty, Persistable { typealias PersistentType = Float override var value: Float { didSet { self.persistentValue = value } } let defaultValue: Float let persistentKey: String init(value: Float, key: String) { self.defaultValue = value self.persistentKey = key super.init() self.register(defaultPersistentValue: value) self.value = self.persistentValue self.initialValue = value } } // MARK: Instruments extension AKInstrument { var persistentProperties: [Property] { return properties.compactMap { $0 as? Property } } func reset() { for property in persistentProperties { property.reset() } } }
mit
80c76b607dcb676b5783006a07afd76b
18.160714
58
0.59739
4.768889
false
false
false
false
parkera/swift
test/Concurrency/actor_isolation.swift
1
37531
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -emit-module-path %t/OtherActors.swiftmodule -module-name OtherActors %S/Inputs/OtherActors.swift -disable-availability-checking // RUN: %target-typecheck-verify-swift -I %t -disable-availability-checking -warn-concurrency // REQUIRES: concurrency import OtherActors let immutableGlobal: String = "hello" var mutableGlobal: String = "can't touch this" // expected-note 5{{var declared here}} @available(SwiftStdlib 5.5, *) func globalFunc() { } @available(SwiftStdlib 5.5, *) func acceptClosure<T>(_: () -> T) { } @available(SwiftStdlib 5.5, *) func acceptConcurrentClosure<T>(_: @Sendable () -> T) { } @available(SwiftStdlib 5.5, *) func acceptEscapingClosure<T>(_: @escaping () -> T) { } @available(SwiftStdlib 5.5, *) func acceptEscapingClosure<T>(_: @escaping (String) -> ()) async -> T? { nil } @available(SwiftStdlib 5.5, *) @discardableResult func acceptAsyncClosure<T>(_: () async -> T) -> T { } @available(SwiftStdlib 5.5, *) func acceptEscapingAsyncClosure<T>(_: @escaping () async -> T) { } @available(SwiftStdlib 5.5, *) func acceptInout<T>(_: inout T) {} // ---------------------------------------------------------------------- // Actor state isolation restrictions // ---------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) actor MySuperActor { var superState: Int = 25 // expected-note {{mutation of this property is only permitted within the actor}} func superMethod() { // expected-note {{calls to instance method 'superMethod()' from outside of its actor context are implicitly asynchronous}} self.superState += 5 } func superAsyncMethod() async { } subscript (index: Int) -> String { "\(index)" } } class Point { var x : Int = 0 var y : Int = 0 } @available(SwiftStdlib 5.5, *) actor MyActor: MySuperActor { // expected-error{{actor types do not support inheritance}} let immutable: Int = 17 // expected-note@+2 2{{property declared here}} // expected-note@+1 6{{mutation of this property is only permitted within the actor}} var mutable: Int = 71 // expected-note@+2 3 {{mutation of this property is only permitted within the actor}} // expected-note@+1 4{{property declared here}} var text: [String] = [] let point : Point = Point() @MainActor var name : String = "koala" // expected-note{{property declared here}} func accessProp() -> String { return self.name // expected-error{{property 'name' isolated to global actor 'MainActor' can not be referenced from actor 'MyActor' in a synchronous context}} } static func synchronousClass() { } static func synchronousStatic() { } func synchronous() -> String { text.first ?? "nothing" } // expected-note 9{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}} func asynchronous() async -> String { super.superState += 4 return synchronous() } } @available(SwiftStdlib 5.5, *) actor Camera { func accessProp(act : MyActor) async -> String { return await act.name } } @available(SwiftStdlib 5.5, *) func checkAsyncPropertyAccess() async { let act = MyActor() let _ : Int = await act.mutable + act.mutable act.mutable += 1 // expected-error {{actor-isolated property 'mutable' can not be mutated from a non-isolated context}} act.superState += 1 // expected-error {{actor-isolated property 'superState' can not be mutated from a non-isolated context}} act.text[0].append("hello") // expected-error{{actor-isolated property 'text' can not be mutated from a non-isolated context}} // this is not the same as the above, because Array is a value type var arr = await act.text arr[0].append("hello") act.text.append("no") // expected-error{{actor-isolated property 'text' can not be mutated from a non-isolated context}} act.text[0] += "hello" // expected-error{{actor-isolated property 'text' can not be mutated from a non-isolated context}} _ = act.point // expected-warning{{cannot use property 'point' with a non-sendable type 'Point' across actors}} } @available(SwiftStdlib 5.5, *) extension MyActor { nonisolated var actorIndependentVar: Int { get { 5 } set { } } nonisolated func actorIndependentFunc(otherActor: MyActor) -> Int { _ = immutable _ = mutable // expected-error{{actor-isolated property 'mutable' can not be referenced from a non-isolated}} _ = text[0] // expected-error{{actor-isolated property 'text' can not be referenced from a non-isolated context}} _ = synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}} // nonisolated _ = actorIndependentFunc(otherActor: self) _ = actorIndependentVar actorIndependentVar = 17 _ = self.actorIndependentFunc(otherActor: self) _ = self.actorIndependentVar self.actorIndependentVar = 17 // nonisolated on another actor _ = otherActor.actorIndependentFunc(otherActor: self) _ = otherActor.actorIndependentVar otherActor.actorIndependentVar = 17 // async promotion _ = synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}} // Global actors syncGlobalActorFunc() /// expected-error{{call to global actor 'SomeGlobalActor'-isolated global function 'syncGlobalActorFunc()' in a synchronous nonisolated context}} _ = syncGlobalActorFunc // Global data is okay if it is immutable. _ = immutableGlobal _ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}} // Partial application _ = synchronous // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}} _ = super.superMethod // expected-error{{actor-isolated instance method 'superMethod()' can not be referenced from a non-isolated context}} acceptClosure(synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}} acceptClosure(self.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}} acceptClosure(otherActor.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}} acceptEscapingClosure(synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}} acceptEscapingClosure(self.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}} acceptEscapingClosure(otherActor.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}} return 5 } func testAsynchronous(otherActor: MyActor) async { _ = immutable _ = mutable mutable = 0 _ = synchronous() _ = text[0] acceptInout(&mutable) // Accesses on 'self' are okay. _ = self.immutable _ = self.mutable self.mutable = 0 _ = self.synchronous() _ = await self.asynchronous() _ = self.text[0] acceptInout(&self.mutable) _ = self[0] // Accesses on 'super' are okay. _ = super.superState super.superState = 0 acceptInout(&super.superState) super.superMethod() await super.superAsyncMethod() _ = super[0] // Accesses on other actors can only reference immutable data synchronously, // otherwise the access is treated as async _ = otherActor.immutable // okay _ = otherActor.mutable // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{property access is 'async'}} _ = await otherActor.mutable otherActor.mutable = 0 // expected-error{{actor-isolated property 'mutable' can not be mutated on a non-isolated actor instance}} acceptInout(&otherActor.mutable) // expected-error{{actor-isolated property 'mutable' can not be used 'inout' on a non-isolated actor instance}} // expected-error@+2{{actor-isolated property 'mutable' can not be mutated on a non-isolated actor instance}} // expected-warning@+1{{no 'async' operations occur within 'await' expression}} await otherActor.mutable = 0 _ = otherActor.synchronous() // expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-2{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}} _ = await otherActor.asynchronous() _ = otherActor.text[0] // expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-2{{property access is 'async'}} _ = await otherActor.text[0] // okay // Global data is okay if it is immutable. _ = immutableGlobal _ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}} // Global functions are not actually safe, but we allow them for now. globalFunc() // Class methods are okay. Self.synchronousClass() Self.synchronousStatic() // Global actors syncGlobalActorFunc() // expected-error{{expression is 'async' but is not marked with 'await'}}{{5-5=await }} // expected-note@-1{{calls to global function 'syncGlobalActorFunc()' from outside of its actor context are implicitly asynchronous}} await asyncGlobalActorFunc() // Closures. let localConstant = 17 var localVar = 17 // Non-escaping closures are okay. acceptClosure { _ = text[0] _ = self.synchronous() _ = localVar _ = localConstant } // Concurrent closures might run... concurrently. var otherLocalVar = 12 acceptConcurrentClosure { [otherLocalVar] in defer { _ = otherLocalVar } _ = self.text[0] // expected-error{{actor-isolated property 'text' can not be referenced from a Sendable closure}} _ = self.mutable // expected-error{{actor-isolated property 'mutable' can not be referenced from a Sendable closure}} self.mutable = 0 // expected-error{{actor-isolated property 'mutable' can not be mutated from a Sendable closure}} acceptInout(&self.mutable) // expected-error{{actor-isolated property 'mutable' can not be used 'inout' from a Sendable closure}} _ = self.immutable _ = self.synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a Sendable closure}} _ = localVar // expected-error{{reference to captured var 'localVar' in concurrently-executing code}} localVar = 25 // expected-error{{mutation of captured var 'localVar' in concurrently-executing code}} _ = localConstant _ = otherLocalVar } otherLocalVar = 17 acceptConcurrentClosure { [weak self, otherLocalVar] in defer { _ = self?.actorIndependentVar } _ = otherLocalVar } // Escaping closures are still actor-isolated acceptEscapingClosure { _ = self.text[0] _ = self.mutable self.mutable = 0 acceptInout(&self.mutable) _ = self.immutable _ = self.synchronous() _ = localVar _ = localConstant } // Local functions might run concurrently. @Sendable func localFn1() { _ = self.text[0] // expected-error{{actor-isolated property 'text' can not be referenced from a Sendable function}} _ = self.synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a Sendable function}} _ = localVar // expected-error{{reference to captured var 'localVar' in concurrently-executing code}} localVar = 25 // expected-error{{mutation of captured var 'localVar' in concurrently-executing code}} _ = localConstant } @Sendable func localFn2() { acceptClosure { _ = text[0] // expected-error{{actor-isolated property 'text' can not be referenced from a non-isolated context}} _ = self.synchronous() // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced from a non-isolated context}} _ = localVar // expected-error{{reference to captured var 'localVar' in concurrently-executing code}} localVar = 25 // expected-error{{mutation of captured var 'localVar' in concurrently-executing code}} _ = localConstant } } acceptEscapingClosure { localFn1() localFn2() } localVar = 0 // Partial application _ = synchronous _ = super.superMethod acceptClosure(synchronous) acceptClosure(self.synchronous) acceptClosure(otherActor.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be referenced on a non-isolated actor instance}} acceptEscapingClosure(synchronous) acceptEscapingClosure(self.synchronous) acceptEscapingClosure(otherActor.synchronous) // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}} acceptAsyncClosure(self.asynchronous) acceptEscapingAsyncClosure(self.asynchronous) } } // ---------------------------------------------------------------------- // Global actor isolation restrictions // ---------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) actor SomeActor { } @globalActor @available(SwiftStdlib 5.5, *) struct SomeGlobalActor { static let shared = SomeActor() } @globalActor @available(SwiftStdlib 5.5, *) struct SomeOtherGlobalActor { static let shared = SomeActor() } @globalActor @available(SwiftStdlib 5.5, *) struct GenericGlobalActor<T> { static var shared: SomeActor { SomeActor() } } @available(SwiftStdlib 5.5, *) @SomeGlobalActor func onions() {} // expected-note{{calls to global function 'onions()' from outside of its actor context are implicitly asynchronous}} @available(SwiftStdlib 5.5, *) @MainActor func beets() { onions() } // expected-error{{call to global actor 'SomeGlobalActor'-isolated global function 'onions()' in a synchronous main actor-isolated context}} // expected-note@-1{{calls to global function 'beets()' from outside of its actor context are implicitly asynchronous}} @available(SwiftStdlib 5.5, *) actor Crystal { // expected-note@+2 {{property declared here}} // expected-note@+1 2 {{mutation of this property is only permitted within the actor}} @SomeGlobalActor var globActorVar : Int = 0 // expected-note@+1 {{mutation of this property is only permitted within the actor}} @SomeGlobalActor var globActorProp : Int { get { return 0 } set {} } @SomeGlobalActor func foo(_ x : inout Int) {} func referToGlobProps() async { _ = await globActorVar + globActorProp globActorProp = 20 // expected-error {{property 'globActorProp' isolated to global actor 'SomeGlobalActor' can not be mutated from actor 'Crystal'}} globActorVar = 30 // expected-error {{property 'globActorVar' isolated to global actor 'SomeGlobalActor' can not be mutated from actor 'Crystal'}} // expected-error@+2 {{property 'globActorVar' isolated to global actor 'SomeGlobalActor' can not be used 'inout' from actor 'Crystal'}} // expected-error@+1 {{actor-isolated property 'globActorVar' cannot be passed 'inout' to implicitly 'async' function call}} await self.foo(&globActorVar) _ = self.foo } } @available(SwiftStdlib 5.5, *) @SomeGlobalActor func syncGlobalActorFunc() { syncGlobalActorFunc() } // expected-note {{calls to global function 'syncGlobalActorFunc()' from outside of its actor context are implicitly asynchronous}} @available(SwiftStdlib 5.5, *) @SomeGlobalActor func asyncGlobalActorFunc() async { await asyncGlobalActorFunc() } @available(SwiftStdlib 5.5, *) @SomeOtherGlobalActor func syncOtherGlobalActorFunc() { } @available(SwiftStdlib 5.5, *) @SomeOtherGlobalActor func asyncOtherGlobalActorFunc() async { await syncGlobalActorFunc() await asyncGlobalActorFunc() } @available(SwiftStdlib 5.5, *) func testGlobalActorClosures() { let _: Int = acceptAsyncClosure { @SomeGlobalActor in syncGlobalActorFunc() syncOtherGlobalActorFunc() // expected-error{{expression is 'async' but is not marked with 'await'}}{{5-5=await }} // expected-note@-1{{calls to global function 'syncOtherGlobalActorFunc()' from outside of its actor context are implicitly asynchronous}} await syncOtherGlobalActorFunc() return 17 } acceptConcurrentClosure { @SomeGlobalActor in 5 } // expected-error{{converting function value of type '@SomeGlobalActor @Sendable () -> Int' to '@Sendable () -> Int' loses global actor 'SomeGlobalActor'}} } @available(SwiftStdlib 5.5, *) extension MyActor { @SomeGlobalActor func onGlobalActor(otherActor: MyActor) async { // Access to other functions in this actor are okay. syncGlobalActorFunc() await asyncGlobalActorFunc() // Other global actors are ok if marked with 'await' await syncOtherGlobalActorFunc() await asyncOtherGlobalActorFunc() _ = immutable _ = mutable // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{property access is 'async'}} _ = await mutable _ = synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}} _ = await synchronous() _ = text[0] // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{property access is 'async'}} _ = await text[0] // Accesses on 'self' are only okay for immutable and asynchronous, because // we are outside of the actor instance. _ = self.immutable _ = self.synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}} _ = await self.synchronous() _ = await self.asynchronous() _ = self.text[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{property access is 'async'}} _ = self[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{subscript access is 'async'}} _ = await self.text[0] _ = await self[0] // Accesses on 'super' are not okay without 'await'; we're outside of the actor. _ = super.superState // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{property access is 'async'}} _ = await super.superState super.superMethod() // expected-error{{expression is 'async' but is not marked with 'await'}}{{5-5=await }} // expected-note@-1{{calls to instance method 'superMethod()' from outside of its actor context are implicitly asynchronous}} await super.superMethod() await super.superAsyncMethod() _ = super[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{subscript access is 'async'}} _ = await super[0] // Accesses on other actors can only reference immutable data or // call asynchronous methods _ = otherActor.immutable // okay _ = otherActor.synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}} _ = otherActor.synchronous // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}} _ = await otherActor.asynchronous() _ = otherActor.text[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{9-9=await }} // expected-note@-1{{property access is 'async'}} _ = await otherActor.text[0] } } @available(SwiftStdlib 5.5, *) struct GenericStruct<T> { @GenericGlobalActor<T> func f() { } // expected-note {{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}} @GenericGlobalActor<T> func g() { f() // okay } @GenericGlobalActor<String> func h() { f() // expected-error{{call to global actor 'GenericGlobalActor<T>'-isolated instance method 'f()' in a synchronous global actor 'GenericGlobalActor<String>'-isolated context}} let fn = f // expected-note{{calls to let 'fn' from outside of its actor context are implicitly asynchronous}} fn() // expected-error{{call to global actor 'GenericGlobalActor<T>'-isolated let 'fn' in a synchronous global actor 'GenericGlobalActor<String>'-isolated context}} } } @available(SwiftStdlib 5.5, *) extension GenericStruct where T == String { @GenericGlobalActor<T> func h2() { f() g() h() } } @SomeGlobalActor var number: Int = 42 // expected-note {{var declared here}} // expected-note@+1 {{add '@SomeGlobalActor' to make global function 'badNumberUser()' part of global actor 'SomeGlobalActor'}} func badNumberUser() { //expected-error@+1{{var 'number' isolated to global actor 'SomeGlobalActor' can not be referenced from this synchronous context}} print("The protected number is: \(number)") } @available(SwiftStdlib 5.5, *) func asyncBadNumberUser() async { print("The protected number is: \(await number)") } // ---------------------------------------------------------------------- // Non-actor code isolation restrictions // ---------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) func testGlobalRestrictions(actor: MyActor) async { let _ = MyActor() // references to sync methods must be fully applied. _ = actor.synchronous // expected-error{{actor-isolated instance method 'synchronous()' can not be partially applied}} _ = actor.asynchronous // any kind of method can be called from outside the actor, so long as it's marked with 'await' _ = actor.synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}} _ = actor.asynchronous() // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-1{{call is 'async'}} _ = await actor.synchronous() _ = await actor.asynchronous() // stored and computed properties can be accessed. Only immutable stored properties can be accessed without 'await' _ = actor.immutable _ = await actor.immutable // expected-warning {{no 'async' operations occur within 'await' expression}} _ = actor.mutable // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-1{{property access is 'async'}} _ = await actor.mutable _ = actor.text[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-1{{property access is 'async'}} _ = await actor.text[0] _ = actor[0] // expected-error{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-1{{subscript access is 'async'}} _ = await actor[0] // nonisolated declarations are permitted. _ = actor.actorIndependentFunc(otherActor: actor) _ = actor.actorIndependentVar actor.actorIndependentVar = 5 // Operations on non-instances are permitted. MyActor.synchronousStatic() MyActor.synchronousClass() // Global mutable state cannot be accessed. _ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}} // Local mutable variables cannot be accessed from concurrently-executing // code. var i = 17 acceptConcurrentClosure { _ = i // expected-error{{reference to captured var 'i' in concurrently-executing code}} i = 42 // expected-error{{mutation of captured var 'i' in concurrently-executing code}} } print(i) acceptConcurrentClosure { [i] in _ = i } print("\(number)") //expected-error {{expression is 'async' but is not marked with 'await'}}{{12-12=await }} //expected-note@-1{{property access is 'async'}} } @available(SwiftStdlib 5.5, *) func f() { acceptConcurrentClosure { _ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}} } @Sendable func g() { _ = mutableGlobal // expected-warning{{reference to var 'mutableGlobal' is not concurrency-safe because it involves shared mutable state}} } } // ---------------------------------------------------------------------- // Local function isolation restrictions // ---------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) func checkLocalFunctions() async { var i = 0 var j = 0 func local1() { i = 17 } func local2() { // expected-error{{concurrently-executed local function 'local2()' must be marked as '@Sendable'}}{{3-3=@Sendable }} j = 42 } // Okay to call locally. local1() local2() // Non-concurrent closures don't cause problems. acceptClosure { local1() local2() } // Escaping closures can make the local function execute concurrently. acceptConcurrentClosure { local2() } print(i) print(j) var k = 17 func local4() { acceptConcurrentClosure { local3() } } func local3() { // expected-error{{concurrently-executed local function 'local3()' must be marked as '@Sendable'}} k = 25 // expected-error{{mutation of captured var 'k' in concurrently-executing code}} } print(k) } // ---------------------------------------------------------------------- // Lazy properties with initializers referencing 'self' // ---------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) actor LazyActor { var v: Int = 0 // expected-note@-1 6 {{property declared here}} let l: Int = 0 lazy var l11: Int = { v }() lazy var l12: Int = v lazy var l13: Int = { self.v }() lazy var l14: Int = self.v lazy var l15: Int = { [unowned self] in self.v }() // expected-error{{actor-isolated property 'v' can not be referenced from a non-isolated context}} lazy var l21: Int = { l }() lazy var l22: Int = l lazy var l23: Int = { self.l }() lazy var l24: Int = self.l lazy var l25: Int = { [unowned self] in self.l }() nonisolated lazy var l31: Int = { v }() // expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}} nonisolated lazy var l32: Int = v // expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}} nonisolated lazy var l33: Int = { self.v }() // expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}} nonisolated lazy var l34: Int = self.v // expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}} nonisolated lazy var l35: Int = { [unowned self] in self.v }() // expected-error@-1 {{actor-isolated property 'v' can not be referenced from a non-isolated context}} nonisolated lazy var l41: Int = { l }() nonisolated lazy var l42: Int = l nonisolated lazy var l43: Int = { self.l }() nonisolated lazy var l44: Int = self.l nonisolated lazy var l45: Int = { [unowned self] in self.l }() } // Infer global actors from context only for instance members. @available(SwiftStdlib 5.5, *) @MainActor class SomeClassInActor { enum ID: String { case best } func inActor() { } // expected-note{{calls to instance method 'inActor()' from outside of its actor context are implicitly asynchronous}} } @available(SwiftStdlib 5.5, *) extension SomeClassInActor.ID { func f(_ object: SomeClassInActor) { // expected-note{{add '@MainActor' to make instance method 'f' part of global actor 'MainActor'}} object.inActor() // expected-error{{call to main actor-isolated instance method 'inActor()' in a synchronous nonisolated context}} } } // ---------------------------------------------------------------------- // Initializers (through typechecking only) // ---------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) actor SomeActorWithInits { var mutableState: Int = 17 var otherMutableState: Int init(i1: Bool) { self.mutableState = 42 self.otherMutableState = 17 self.isolated() self.nonisolated() } init(i2: Bool) async { self.mutableState = 0 self.otherMutableState = 1 self.isolated() self.nonisolated() } convenience init(i3: Bool) { self.init(i1: i3) self.isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from a non-isolated context}} self.nonisolated() } convenience init(i4: Bool) async { self.init(i1: i4) await self.isolated() self.nonisolated() } @MainActor init(i5: Bool) { self.mutableState = 42 self.otherMutableState = 17 self.isolated() self.nonisolated() } @MainActor init(i6: Bool) async { self.mutableState = 42 self.otherMutableState = 17 self.isolated() self.nonisolated() } @MainActor convenience init(i7: Bool) { self.init(i1: i7) self.isolated() // expected-error{{actor-isolated instance method 'isolated()' can not be referenced from the main actor}} self.nonisolated() } @MainActor convenience init(i8: Bool) async { self.init(i1: i8) await self.isolated() self.nonisolated() } func isolated() { } // expected-note 2 {{calls to instance method 'isolated()' from outside of its actor context are implicitly asynchronous}} nonisolated func nonisolated() {} } @available(SwiftStdlib 5.5, *) @MainActor class SomeClassWithInits { var mutableState: Int = 17 var otherMutableState: Int static var shared = SomeClassWithInits() // expected-note 2{{static property declared here}} init() { // expected-note{{calls to initializer 'init()' from outside of its actor context are implicitly asynchronous}} self.mutableState = 42 self.otherMutableState = 17 self.isolated() } deinit { print(mutableState) // Okay, we're actor-isolated print(SomeClassWithInits.shared) // expected-error{{static property 'shared' isolated to global actor 'MainActor' can not be referenced from this synchronous context}} beets() //expected-error{{call to main actor-isolated global function 'beets()' in a synchronous nonisolated context}} } func isolated() { } static func staticIsolated() { // expected-note{{calls to static method 'staticIsolated()' from outside of its actor context are implicitly asynchronous}} _ = SomeClassWithInits.shared } func hasDetached() { Task.detached { // okay await self.isolated() self.isolated() // expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{7-7=await }} // expected-note@-2{{calls to instance method 'isolated()' from outside of its actor context are implicitly asynchronous}} print(await self.mutableState) } } } @available(SwiftStdlib 5.5, *) func outsideSomeClassWithInits() { // expected-note 3 {{add '@MainActor' to make global function 'outsideSomeClassWithInits()' part of global actor 'MainActor'}} _ = SomeClassWithInits() // expected-error{{call to main actor-isolated initializer 'init()' in a synchronous nonisolated context}} _ = SomeClassWithInits.shared // expected-error{{static property 'shared' isolated to global actor 'MainActor' can not be referenced from this synchronous context}} SomeClassWithInits.staticIsolated() // expected-error{{call to main actor-isolated static method 'staticIsolated()' in a synchronous nonisolated context}} } // ---------------------------------------------------------------------- // nonisolated let and cross-module let // ---------------------------------------------------------------------- func testCrossModuleLets(actor: OtherModuleActor) async { _ = actor.a // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{property access is 'async'}} _ = await actor.a // okay _ = actor.b // okay _ = actor.c // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{property access is 'async'}} // expected-warning@-2{{cannot use property 'c' with a non-sendable type 'SomeClass' across actors}} _ = await actor.c // expected-warning{{cannot use property 'c' with a non-sendable type 'SomeClass' across actors}} } // ---------------------------------------------------------------------- // Actor protocols. // ---------------------------------------------------------------------- @available(SwiftStdlib 5.5, *) actor A: Actor { // ok } @available(SwiftStdlib 5.5, *) class C: Actor, UnsafeSendable { // expected-error@-1{{non-actor type 'C' cannot conform to the 'Actor' protocol}} // expected-warning@-2{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}} nonisolated var unownedExecutor: UnownedSerialExecutor { fatalError() } } @available(SwiftStdlib 5.5, *) protocol P: Actor { func f() } @available(SwiftStdlib 5.5, *) extension P { func g() { f() } } @available(SwiftStdlib 5.5, *) actor MyActorP: P { func f() { } func h() { g() } } @available(SwiftStdlib 5.5, *) protocol SP { static func s() } @available(SwiftStdlib 5.5, *) actor ASP: SP { static func s() { } } @available(SwiftStdlib 5.5, *) protocol SPD { static func sd() } @available(SwiftStdlib 5.5, *) extension SPD { static func sd() { } } @available(SwiftStdlib 5.5, *) actor ASPD: SPD { } @available(SwiftStdlib 5.5, *) func testCrossActorProtocol<T: P>(t: T) async { await t.f() await t.g() t.f() // expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }} // expected-note@-2{{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}} t.g() // expected-error@-1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }} // expected-note@-2{{calls to instance method 'g()' from outside of its actor context are implicitly asynchronous}} ASP.s() ASPD.sd() } // ---------------------------------------------------------------------- // @_inheritActorContext // ---------------------------------------------------------------------- func acceptAsyncSendableClosure<T>(_: @Sendable () async -> T) { } func acceptAsyncSendableClosureInheriting<T>(@_inheritActorContext _: @Sendable () async -> T) { } @available(SwiftStdlib 5.5, *) extension MyActor { func testSendableAndInheriting() { acceptAsyncSendableClosure { synchronous() // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{calls to instance method 'synchronous()' from outside of its actor context are implicitly asynchronous}} } acceptAsyncSendableClosure { await synchronous() // ok } acceptAsyncSendableClosureInheriting { synchronous() // okay } acceptAsyncSendableClosureInheriting { await synchronous() // expected-warning{{no 'async' operations occur within 'await' expression}} } } } @available(SwiftStdlib 5.5, *) @MainActor // expected-note {{'GloballyIsolatedProto' is isolated to global actor 'MainActor' here}} protocol GloballyIsolatedProto { } // rdar://75849035 - trying to conform an actor to a global-actor isolated protocol should result in an error func test_conforming_actor_to_global_actor_protocol() { @available(SwiftStdlib 5.5, *) actor MyValue : GloballyIsolatedProto {} // expected-error@-1 {{actor 'MyValue' cannot conform to global actor isolated protocol 'GloballyIsolatedProto'}} } func test_invalid_reference_to_actor_member_without_a_call_note() { actor A { func partial() { } } actor Test { func returnPartial(other: A) async -> () async -> () { let a = other.partial // expected-error@-1 {{actor-isolated instance method 'partial()' can not be partially applied}} return a } } } // Actor isolation and "defer" actor Counter { var counter: Int = 0 func next() -> Int { defer { counter = counter + 1 } return counter } func localNext() -> Int { func doIt() { counter = counter + 1 } doIt() return counter } } /// Superclass checks for global actor-qualified class types. class C2 { } @SomeGlobalActor class C3: C2 { } // expected-error{{global actor 'SomeGlobalActor'-isolated class 'C3' has different actor isolation from nonisolated superclass 'C2'}} @GenericGlobalActor<U> class GenericSuper<U> { } @GenericGlobalActor<[T]> class GenericSub1<T>: GenericSuper<[T]> { } @GenericGlobalActor<T> class GenericSub2<T>: GenericSuper<[T]> { } // expected-error{{global actor 'GenericGlobalActor<T>'-isolated class 'GenericSub2' has different actor isolation from global actor 'GenericGlobalActor<U>'-isolated superclass 'GenericSuper'}}
apache-2.0
2e62b1ed46d6669b70742eb631888adc
37.218941
237
0.66966
4.321359
false
false
false
false
LiulietLee/BilibiliCD
Shared/Network/CoverInfoProvider.swift
1
6028
// // CoverInfoProvider.swift // BCD // // Created by Liuliet.Lee on 17/6/2017. // Copyright © 2017 Liuliet.Lee. All rights reserved. // import UIKit import BilibiliKit class CoverInfoProvider: AbstractProvider { open func getCoverInfoBy( type: CoverType, andStringID id: UInt64, completion: @escaping (Info?) -> Void ) { switch type { case .video: getInfo(forAV: id, completion) case .article: getInfo(forCV: id, completion) case .live: getInfo(forLV: id, completion) default: break } } open func getCoverInfoBy(cover: BilibiliCover, completion: @escaping (Info?) -> Void) { switch cover.type { case .video: getInfo(forAV: cover.number, completion) case .bvideo: getInfo(forBV: cover.bvid, completion) case .article: getInfo(forCV: cover.number, completion) case .live: getInfo(forLV: cover.number, completion) default: break } } private func updateServerRecord(type: CoverType, nid: String, info: Info) { guard let url = APIFactory.getCoverAPI(byType: type, andNID: nid, andInfo: info, env: env) else { fatalError("cannot generate api url") } let parameters: [String : Any] = [ "type": CoverType.stringType(type: type)!, "nid": nid, "url": info.imageURL, "title": info.title, "author": info.author ] var request = URLRequest(url: url) request.httpMethod = "POST" do { request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) } catch let error { print(error.localizedDescription) } request.addValue("application/json", forHTTPHeaderField: "Content-Type") let task = session.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } let responseString = String(data: data, encoding: .utf8) print("responseString = \(String(describing: responseString))") } task.resume() } private func fetchCoverRecordFromServer(withType type: CoverType, andID nid: String, _ completion: @escaping (Info?) -> Void) { guard let url = APIFactory.getCoverAPI(byType: type, andNID: nid, env: env) else { fatalError("cannot generate api url") } let task = session.dataTask(with: url) { data, response, error in guard error == nil, let content = data, let newInfo = try? JSONDecoder().decode(Info.self, from: content) else { completion(nil) return } if newInfo.isValid { completion(newInfo) } else { completion(nil) } } task.resume() } private func getInfo(forAV: UInt64, _ completion: @escaping (Info?) -> Void) { BKVideo.av(Int(forAV)).getInfo { guard let info = try? $0.get() else { self.fetchCoverRecordFromServer(withType: .video, andID: String(forAV), completion) return } let url = info.coverImageURL.absoluteString let newInfo = Info(stringID: "av" + String(forAV), author: info.author.name, title: info.title, imageURL: url) self.updateServerRecord(type: .video, nid: String(forAV), info: newInfo) completion(newInfo) } } private func getInfo(forBV: String, _ completion: @escaping (Info?) -> Void) { BKVideo.bv(forBV).getInfo { guard let info = try? $0.get() else { self.fetchCoverRecordFromServer(withType: .bvideo, andID: forBV, completion) return } let url = info.coverImageURL.absoluteString let newInfo = Info(stringID: forBV, author: info.author.name, title: info.title, imageURL: url) self.updateServerRecord(type: .bvideo, nid: forBV, info: newInfo) completion(newInfo) } } private func getInfo(forCV: UInt64, _ completion: @escaping (Info?) -> Void) { BKArticle(cv: Int(forCV)).getInfo { guard let info = try? $0.get() else { self.fetchCoverRecordFromServer(withType: .article, andID: String(forCV), completion) return } let url = info.coverImageURL.absoluteString let newInfo = Info(stringID: "cv" + String(forCV), author: info.author, title: info.title, imageURL: url) self.updateServerRecord(type: .article, nid: String(forCV), info: newInfo) completion(newInfo) } } private func getInfo(forLV: UInt64, _ completion: @escaping (Info?) -> Void) { BKLiveRoom(Int(forLV)).getInfo { guard let info = try? $0.get() else { self.fetchCoverRecordFromServer(withType: .live, andID: String(forLV), completion) return } BKUser(id: info.mid).getBasicInfo(then: { basicInfo in if let userInfo = try? basicInfo.get() { let url = info.coverImageURL.absoluteString let newInfo = Info(stringID: "lv" + String(forLV), author: userInfo.name, title: info.title, imageURL: url) self.updateServerRecord(type: .live, nid: String(forLV), info: newInfo) completion(newInfo) } }) } } }
gpl-3.0
6695886fdcbfe09b2f137bb5c407cf99
38.392157
131
0.564626
4.507853
false
false
false
false