repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
AlexeyGolovenkov/DocGenerator
GRMustache.swift/Sources/EachFilter.swift
1
4795
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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 let EachFilter = Filter { (box: MustacheBox) -> MustacheBox in // {{# each(nothing) }}...{{/ }} if box.isEmpty { return box } // {{# each(dictionary) }}...{{/ }} // // // Renders "firstName: Charles, lastName: Bronson." // let dictionary = ["firstName": "Charles", "lastName": "Bronson"] // let template = try! Template(string: "{{# each(dictionary) }}{{ @key }}: {{ . }}{{^ @last }}, {{/ @last }}{{/ each(dictionary) }}.") // template.registerInBaseContext("each", Box(StandardLibrary.each)) // try! template.render(Box(["dictionary": dictionary])) // // The dictionaryValue box property makes sure to return a // [String: MustacheBox] whatever the boxed dictionary-like value // (NSDictionary, [String: Int], [String: CustomObject], etc. if let dictionary = box.dictionaryValue { let count = dictionary.count let transformedBoxes = dictionary.enumerate().map { (index: Int, element: (key: String, box: MustacheBox)) -> MustacheBox in let customRenderFunction: RenderFunction = { info in // Push positional keys in the context stack and then perform // a regular rendering. var position: [String: MustacheBox] = [:] position["@index"] = Box(index) position["@indexPlusOne"] = Box(index + 1) position["@indexIsEven"] = Box(index % 2 == 0) position["@first"] = Box(index == 0) position["@last"] = Box((index == count - 1)) position["@key"] = Box(element.key) var info = info info.context = info.context.extendedContext(Box(position)) return try element.box.render(info: info) } return Box(customRenderFunction) } return Box(transformedBoxes) } // {{# each(array) }}...{{/ }} // // // Renders "1: bread, 2: ham, 3: butter" // let array = ["bread", "ham", "butter"] // let template = try! Template(string: "{{# each(array) }}{{ @indexPlusOne }}: {{ . }}{{^ @last }}, {{/ @last }}{{/ each(array) }}.") // template.registerInBaseContext("each", Box(StandardLibrary.each)) // try! template.render(Box(["array": array])) // // The arrayValue box property makes sure to return a [MustacheBox] whatever // the boxed collection: NSArray, NSSet, [String], [CustomObject], etc. if let boxes = box.arrayValue { let count = boxes.count let transformedBoxes = boxes.enumerate().map { (index: Int, box: MustacheBox) -> MustacheBox in let customRenderFunction: RenderFunction = { info in // Push positional keys in the context stack and then perform // a regular rendering. var position: [String: MustacheBox] = [:] position["@index"] = Box(index) position["@indexPlusOne"] = Box(index + 1) position["@indexIsEven"] = Box(index % 2 == 0) position["@first"] = Box(index == 0) position["@last"] = Box((index == count - 1)) var info = info info.context = info.context.extendedContext(Box(position)) return try box.render(info: info) } return Box(customRenderFunction) } return Box(transformedBoxes) } // Non-iterable value throw MustacheError(kind: .RenderError, message: "Non-enumerable argument in each filter: \(box.value)") }
mit
e3ff67cdb58762646b1f869a93773631
46
143
0.598456
4.557034
false
false
false
false
insidegui/AssetCatalogTinkerer
Asset Catalog Tinkerer/ImagesViewController.swift
1
11732
// // ViewController.swift // Asset Catalog Tinkerer // // Created by Guilherme Rambo on 27/03/16. // Copyright © 2016 Guilherme Rambo. All rights reserved. // import Cocoa class ImagesViewController: NSViewController, NSMenuItemValidation { var loadProgress = 0.0 { didSet { progressBar.progress = loadProgress if loadProgress >= 0.99 && error == nil { hideStatus() showSpinner() } } } var error: NSError? = nil { didSet { guard let error = error else { return } loadProgress = 1.0 showStatus(error.localizedDescription) tellWindowControllerToDisableSearchField() } } fileprivate var dataProvider = ImagesCollectionViewDataProvider() var images = [[String: NSObject]]() { didSet { loadProgress = 1.0 dataProvider.images = images hideSpinner() tellWindowControllerToEnableSearchField() } } override func viewDidLoad() { super.viewDidLoad() view.layer?.backgroundColor = NSColor.white.cgColor buildUI() showStatus("Extracting Images...") } // MARK: - UI fileprivate lazy var progressBar: ProgressBar = { let p = ProgressBar(frame: NSZeroRect) p.translatesAutoresizingMaskIntoConstraints = false p.tintColor = NSColor(calibratedRed:0, green:0.495, blue:1, alpha:1) p.progress = 0.0 return p }() fileprivate lazy var spinner: NSProgressIndicator = { let p = NSProgressIndicator(frame: NSZeroRect) p.translatesAutoresizingMaskIntoConstraints = false p.controlSize = .regular p.style = .spinning p.isDisplayedWhenStopped = false p.isIndeterminate = true return p }() fileprivate lazy var statusLabel: NSTextField = { let l = NSTextField(frame: NSZeroRect) l.translatesAutoresizingMaskIntoConstraints = false l.isBordered = false l.isBezeled = false l.isEditable = false l.isSelectable = false l.drawsBackground = false l.font = NSFont.systemFont(ofSize: 12.0, weight: .medium) l.textColor = NSColor.secondaryLabelColor l.lineBreakMode = .byTruncatingTail l.alphaValue = 0.0 return l }() fileprivate lazy var scrollView: NSScrollView = { let s = NSScrollView(frame: NSZeroRect) s.translatesAutoresizingMaskIntoConstraints = false s.hasVerticalScroller = true s.borderType = .noBorder return s }() fileprivate lazy var collectionView: QuickLookableCollectionView = { let c = QuickLookableCollectionView(frame: NSZeroRect) c.isSelectable = true c.allowsMultipleSelection = true c.provideQuickLookPasteboardWriters = { [weak self] indexPaths in guard let self = self else { return [] } return indexPaths.compactMap { self.dataProvider.generalPasteboardWriter(at: $0) } } return c }() fileprivate lazy var exportProgressView: NSVisualEffectView = { let vfxView = NSVisualEffectView(frame: NSZeroRect) vfxView.translatesAutoresizingMaskIntoConstraints = false vfxView.material = .contentBackground vfxView.blendingMode = .withinWindow let p = NSProgressIndicator(frame: NSZeroRect) p.translatesAutoresizingMaskIntoConstraints = false p.style = .spinning p.controlSize = .regular p.sizeToFit() vfxView.addSubview(p) p.centerYAnchor.constraint(equalTo: vfxView.centerYAnchor).isActive = true p.centerXAnchor.constraint(equalTo: vfxView.centerXAnchor).isActive = true vfxView.alphaValue = 0.0 vfxView.isHidden = true p.startAnimation(nil) return vfxView }() fileprivate func showSpinner() { if spinner.superview == nil { view.addSubview(spinner) spinner.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true spinner.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true } spinner.startAnimation(nil) } fileprivate func hideSpinner() { spinner.stopAnimation(nil) } fileprivate func buildUI() { scrollView.frame = view.bounds view.addSubview(scrollView) scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true collectionView.frame = scrollView.bounds scrollView.documentView = collectionView dataProvider.collectionView = collectionView progressBar.frame = NSRect(x: 0.0, y: view.bounds.height - 3.0, width: view.bounds.width, height: 3.0) progressBar.heightAnchor.constraint(equalToConstant: 3.0).isActive = true view.addSubview(progressBar) progressBar.topAnchor.constraint(equalTo: view.topAnchor).isActive = true progressBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true progressBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true } fileprivate func showExportProgress() { tellWindowControllerToDisableSearchField() if exportProgressView.superview == nil { exportProgressView.frame = view.bounds view.addSubview(exportProgressView) exportProgressView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true exportProgressView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true exportProgressView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true exportProgressView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true } exportProgressView.isHidden = false NSAnimationContext.runAnimationGroup({ ctx in ctx.duration = 0.4 self.exportProgressView.animator().alphaValue = 1.0 }, completionHandler: nil) } fileprivate func hideExportProgress() { tellWindowControllerToEnableSearchField() NSAnimationContext.runAnimationGroup({ ctx in ctx.duration = 0.4 self.exportProgressView.animator().alphaValue = 0.0 }, completionHandler: { self.exportProgressView.isHidden = true }) } fileprivate func showStatus(_ status: String) { if statusLabel.superview == nil { view.addSubview(statusLabel) statusLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true statusLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true } statusLabel.stringValue = status statusLabel.isHidden = false NSAnimationContext.runAnimationGroup({ ctx in ctx.duration = 0.4 self.statusLabel.animator().alphaValue = 1.0 }, completionHandler: nil) } fileprivate func hideStatus() { NSAnimationContext.runAnimationGroup({ ctx in ctx.duration = 0.4 self.statusLabel.animator().alphaValue = 0.0 }, completionHandler: { self.statusLabel.isHidden = true }) } @IBAction func search(_ sender: NSSearchField) { dataProvider.searchTerm = sender.stringValue if dataProvider.filteredImages.count == 0 { showStatus("No images found for \"\(dataProvider.searchTerm)\"") } else { hideStatus() } } fileprivate func tellWindowControllerToEnableSearchField() { NSApp.sendAction(#selector(MainWindowController.enableSearchField(_:)), to: nil, from: self) } fileprivate func tellWindowControllerToDisableSearchField() { NSApp.sendAction(#selector(MainWindowController.disableSearchField(_:)), to: nil, from: self) } // MARK: - Export @IBAction func copy(_ sender: Any?) { guard collectionView.selectionIndexPaths.count > 0 else { return } let writers = collectionView.selectionIndexPaths.compactMap { dataProvider.generalPasteboardWriter(at: $0) } NSPasteboard.general.clearContents() NSPasteboard.general.writeObjects(writers) } @IBAction func exportAllImages(_ sender: NSMenuItem) { imagesToExport = dataProvider.filteredImages launchExportPanel() } @IBAction func exportSelectedImages(_ sender: NSMenuItem) { imagesToExport = collectionView.selectionIndexes.map { return self.dataProvider.filteredImages[$0] } launchExportPanel() } fileprivate var imagesToExport: [[String: NSObject]]? fileprivate func launchExportPanel() { guard let imagesToExport = imagesToExport else { return } let panel = NSOpenPanel() panel.prompt = "Export" panel.title = "Select a directory to export the images to" panel.canChooseFiles = false panel.canChooseDirectories = true panel.canCreateDirectories = true panel.beginSheetModal(for: view.window!) { result in guard result == .OK else { return } guard panel.url != nil else { return } self.exportImages(imagesToExport, toDirectoryAt: panel.url!) } } fileprivate func exportImages(_ images: [[String: NSObject]], toDirectoryAt url: URL) { showExportProgress() DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { images.forEach { image in guard let filename = image["filename"] as? String else { return } var pathComponents = url.pathComponents pathComponents.append(filename) guard let pngData = image["png"] as? Data else { return } let path = NSString.path(withComponents: pathComponents) as String if !((try? pngData.write(to: URL(fileURLWithPath: path), options: [.atomic])) != nil) { NSLog("ERROR: Unable to write \(filename) to \(path)") } } DispatchQueue.main.async { self.hideExportProgress() } } } fileprivate enum MenuItemTags: Int { case exportAllImages = 1001 case exportSelectedImages = 1002 } func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if NSStringFromSelector(menuItem.action!) == "copy:" { return collectionView.selectionIndexPaths.count > 0 } guard let semanticMenuItem = MenuItemTags(rawValue: menuItem.tag) else { return false } switch semanticMenuItem { case .exportAllImages: return images.count > 0 case .exportSelectedImages: return collectionView.selectionIndexes.count > 0 } } }
bsd-2-clause
5023c60ba7254108adaea2dd929782da
33.101744
116
0.61427
5.528275
false
false
false
false
eswick/StreamKit
Sources/MemoryStream.swift
1
1847
public class MemoryStream: Stream { public let canRead: Bool = true public let canWrite: Bool = true public let canTimeout: Bool = false public let canSeek: Bool = true public var position: Int64 = 0 public var readTimeout: UInt = 0 public var writeTimeout: UInt = 0 public var buffer = [UInt8]() public func read(count: Int64) throws -> [UInt8] { var realCount = count if Int(position + count) > buffer.count { realCount = Int64(buffer.count - Int(position)) } if realCount == 0 { throw StreamError.ReadFailed(0) } let slice = Array(buffer[Int(position)...Int(position + realCount - 1)]) position += realCount return slice } public func write(bytes: [UInt8]) throws -> Int { if Int(position + bytes.count) >= buffer.count { for _ in buffer.count..<(Int(position + bytes.count)) { buffer.append(0) } } buffer.replaceRange(Int(position)..<(Int(position + bytes.count)), with: bytes) position += bytes.count return bytes.count } public func seek(offset: Int64, origin: SeekOrigin) throws { var refPoint: Int switch origin { case .Beginning: refPoint = 0 break case .Current: refPoint = Int(position) break case .End: refPoint = buffer.count - 1 } if Int(refPoint + offset) >= Int(buffer.count) { throw StreamError.SeekFailed(0) } position = refPoint + offset } public init() { } public func close() throws { } }
mit
7ff0b08a95e7e2603e7ac1398fc4b583
23.64
87
0.51164
4.629073
false
false
false
false
FoodForTech/Handy-Man
HandyMan/HandyMan/HandyManCore/Spring/DesignableView.swift
1
2255
// The MIT License (MIT) // // Copyright (c) 2015 Meng To (meng@designcode.io) // // 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 @IBDesignable open class DesignableView: SpringView { @IBInspectable open var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable open var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable open var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable open var shadowColor: UIColor = UIColor.clear { didSet { layer.shadowColor = shadowColor.cgColor } } @IBInspectable open var shadowRadius: CGFloat = 0 { didSet { layer.shadowRadius = shadowRadius } } @IBInspectable open var shadowOpacity: CGFloat = 0 { didSet { layer.shadowOpacity = Float(shadowOpacity) } } @IBInspectable open var shadowOffsetY: CGFloat = 0 { didSet { layer.shadowOffset.height = shadowOffsetY } } }
mit
ea80293e6fe15dc67983a40912f2a8be
32.161765
81
0.666075
4.96696
false
false
false
false
gssdromen/CedFilterView
FilterTest/Extension/FloatExtension.swift
1
1325
// // FloatExtension.swift // SecondHandHouseBroker // // Created by Cedric Wu on 3/3/16. // Copyright © 2016 FangDuoDuo. All rights reserved. // import Foundation extension Float { func toString() -> String { return String(self) } func toAreaFormat() -> String { let dou = NSString(format: "%.2f", self) let array = dou.components(separatedBy: ".") if array.count == 2 { if array[1] == "00" { return array[0] } else if array[1].hasSuffix("0") { return dou.substring(to: dou.length - 1) } else { return dou as String } } else { return "" } } func toPriceFormat() -> String { let dou = NSString(format: "%.2f", self) let array = dou.components(separatedBy: ".") if array.count == 2 { if array[1] == "00" { return array[0] } else if array[1].hasSuffix("0") { return dou.substring(to: dou.length - 1) } else { return dou as String } } else { return "" } } func toCountDownSecondFromat() -> String { let dou = NSString(format: "%.1f", self) return dou as String } }
gpl-3.0
70a6e8b48c7aa6c017b59d234a4768c2
23.981132
56
0.483384
3.940476
false
false
false
false
SFantasy/swift-tour
Enumerations&&Structures.playground/section-1.swift
1
2826
// The Swift Programming Languages // // Enumerations and Structures // 1. Write a function that compares two Rank values by comparing their raw values. enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.toRaw()) } } } func compare(val1: Rank, val2: Rank) -> Bool { return val1.toRaw() > val2.toRaw(); } let ace = Rank.Ace let aceRawValue = ace.toRaw() // Try compare compare(Rank.Ace, Rank.Queen) // 2. Add a color method to Suit that returns “black” for spades and clubs, and returns “red” for hearts and diamonds. enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } func color() -> String { switch self { case .Spades, .Clubs: return "black" case .Diamonds, .Hearts: return "red" } } } let hearts = Suit.Hearts // Show color hearts.color() // 3. Add a method to Card that creates a full deck of cards, with one card of each combination of rank and suit. struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } func getFullCard() -> Card[] { var cards: Card[] = [] var suits: Suit[] = [.Spades, .Hearts, .Diamonds, .Clubs] for s in suits { for i in 1...13 { cards += Card(rank: Rank.fromRaw(i)!, suit: s) } } return cards } } let threeOfSpades = Card(rank: .Three, suit: .Spades) threeOfSpades.simpleDescription() threeOfSpades.getFullCard() // 4. Add a third case to the ServerResponse and to the switch enum ServerResponse { case Result(String, String) case Error(String) case Timeout(String) } let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese") let timeout = ServerResponse.Timeout("Time is out") switch success { case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Error(error): let serverResponse = "Failuer.. \(error)" case let .Timeout(msg): let serverResponse = "Server.. \(msg)" }
mit
9b2f1138a97fd49050f8edf4009f4402
23.938053
118
0.590135
4.002841
false
false
false
false
bencochran/MinimalJSON
MinimalJSON/JSONError.swift
1
1334
// // JSONError.swift // MinimalJSON // // Created by Ben Cochran on 8/31/15. // Copyright © 2015 Ben Cochran. All rights reserved. // import Foundation public enum JSONErrorType { case UnableToParse case MissingKey(key: String) case OutOfBounds(index: Int) case IncompatibleType(typename: String) } public struct JSONError: ErrorType { public let type: JSONErrorType public let json: JSONValue? internal let file: String internal let line: Int internal init(_ type: JSONErrorType, json: JSONValue? = nil, file: String = __FILE__, line: Int = __LINE__) { self.type = type self.json = json self.file = file self.line = line } } extension JSONError: CustomDebugStringConvertible { public var debugDescription: String { let jsonString = "\(json)" ?? "(null)" return "JSONError(\(type), json: \(jsonString))" } } extension JSONErrorType: Equatable { } public func ==(lhs: JSONErrorType, rhs: JSONErrorType) -> Bool { switch (lhs, rhs) { case (.UnableToParse, .UnableToParse): return true case let (.MissingKey(l), .MissingKey(r)): return l == r case let (.OutOfBounds(l), .OutOfBounds(r)): return l == r case let (.IncompatibleType(l), .IncompatibleType(r)): return l == r default: return false } }
bsd-3-clause
e026c1aed192c4c3282e525c6c31671a
26.770833
113
0.648912
3.991018
false
false
false
false
michikono/how-tos
swift-using-typealiases-as-generics/swift-using-typealiases-as-generics.playground/Pages/1-0-inferred-typealiases.xcplaygroundpage/Contents.swift
1
516
//: Inferred Typealiases //: =================== //: [Previous](@previous) protocol Furniture { typealias M func mainMaterial() -> M func secondaryMaterial() -> M } class Chair: Furniture { func mainMaterial() -> String { return "Wood" } func secondaryMaterial() -> String { return "More wood" } } class Lamp: Furniture { func mainMaterial() -> Bool { return true } func secondaryMaterial() -> Bool { return true } } //: [Next](@next)
mit
20ce499799492a5b14eed450de712fb3
16.2
40
0.550388
3.938931
false
false
false
false
Cereopsis/swift-bowling
swift_oo_version/Frame.swift
1
2316
/* The MIT License (MIT) Copyright (c) 2015 Cereopsis 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 struct EndFrame: Scoreable { private let fillBall: Int? private let frame: Frame public init?(throw1: Int, throw2: Int = 0, throw3: Int? = .None) { precondition(throw1 <= 10) precondition(throw2 <= 10) let list = [throw1] + (throw2 == 0 ? [] : [throw2]) frame = Frame(list: list) fillBall = throw3 if let f = fillBall where f > 10 || frame.isOpen { // the last frame must be at least a spare to need a fill ball return nil } } public var displayString: String { let str = frame.displayString if let f = fillBall where !isStrike { return "\(str)\(f)" } return str } public var toList: [Int] { return frame.toList + (fillBall == nil ? [] : [fillBall!]) } } public struct Frame: Scoreable { private let array: [Int] private init(list: [Int]) { array = list } public init?(throw1: Int, throw2: Int = 0) { array = throw2 == 0 ? [throw1] : [throw1, throw2] if pinCount > 10 { return nil } } public var toList: [Int] { return array } }
mit
7727da9501a55f252424359d60b32615
30.726027
78
0.652418
4.210909
false
false
false
false
TouchInstinct/LeadKit
TITableKitUtils/Sources/Extensions/TableSection/TableSection+Extensions.swift
1
2160
// // Copyright (c) 2020 Touch Instinct // // 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 TableKit import class UIKit.UIView public extension TableSection { /// Initializes section with rows and zero height footer and header. /// /// - Parameter rows: Rows to insert into section. convenience init(onlyRows rows: [Row]) { self.init(rows: rows) if #available(iOS 15, *) { self.headerView = nil self.footerView = nil } else { self.headerView = UIView() self.footerView = UIView() } self.headerHeight = .leastNonzeroMagnitude self.footerHeight = .leastNonzeroMagnitude } /// Initializes an empty section. static func emptySection() -> TableSection { let tableSection = TableSection() if #available(iOS 15, *) { tableSection.headerView = nil tableSection.footerView = nil } else { tableSection.headerView = UIView() tableSection.footerView = UIView() } return tableSection } }
apache-2.0
ff0ff5686c377335b1813655be9bdab7
35
81
0.671296
4.726477
false
false
false
false
danielgindi/Charts
ChartsDemo-iOS/Swift/Demos/NegativeStackedBarChartViewController.swift
2
4551
// // NegativeStackedBarChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class NegativeStackedBarChartViewController: DemoBaseViewController { @IBOutlet var chartView: HorizontalBarChartView! lazy var customFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.negativePrefix = "" formatter.positiveSuffix = "m" formatter.negativeSuffix = "m" formatter.minimumSignificantDigits = 1 formatter.minimumFractionDigits = 1 return formatter }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Stacked Bar Chart Negative" self.options = [.toggleValues, .toggleIcons, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData, .toggleBarBorders] chartView.delegate = self chartView.chartDescription.enabled = false chartView.drawBarShadowEnabled = false chartView.drawValueAboveBarEnabled = true chartView.leftAxis.enabled = false let rightAxis = chartView.rightAxis rightAxis.axisMaximum = 25 rightAxis.axisMinimum = -25 rightAxis.drawZeroLineEnabled = true rightAxis.labelCount = 7 rightAxis.valueFormatter = DefaultAxisValueFormatter(formatter: customFormatter) rightAxis.labelFont = .systemFont(ofSize: 9) let xAxis = chartView.xAxis xAxis.labelPosition = .bothSided xAxis.drawAxisLineEnabled = false xAxis.axisMinimum = 0 xAxis.axisMaximum = 110 xAxis.centerAxisLabelsEnabled = true xAxis.labelCount = 12 xAxis.granularity = 10 xAxis.valueFormatter = self xAxis.labelFont = .systemFont(ofSize: 9) let l = chartView.legend l.horizontalAlignment = .right l.verticalAlignment = .bottom l.orientation = .horizontal l.formSize = 8 l.formToTextSpace = 8 l.xEntrySpace = 6 // chartView.legend = l self.updateChartData() } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setChartData() } func setChartData() { let yVals = [BarChartDataEntry(x: 5, yValues: [-10, 10]), BarChartDataEntry(x: 15, yValues: [-12, 13]), BarChartDataEntry(x: 25, yValues: [-15, 15]), BarChartDataEntry(x: 35, yValues: [-17, 17]), BarChartDataEntry(x: 45, yValues: [-19, 120]), BarChartDataEntry(x: 55, yValues: [-19, 19]), BarChartDataEntry(x: 65, yValues: [-16, 16]), BarChartDataEntry(x: 75, yValues: [-13, 14]), BarChartDataEntry(x: 85, yValues: [-10, 11]), BarChartDataEntry(x: 95, yValues: [-5, 6]), BarChartDataEntry(x: 105, yValues: [-1, 2]) ] let set = BarChartDataSet(entries: yVals, label: "Age Distribution") set.drawIconsEnabled = false set.valueFormatter = DefaultValueFormatter(formatter: customFormatter) set.valueFont = .systemFont(ofSize: 7) set.axisDependency = .right set.colors = [UIColor(red: 67/255, green: 67/255, blue: 72/255, alpha: 1), UIColor(red: 124/255, green: 181/255, blue: 236/255, alpha: 1) ] set.stackLabels = ["Men", "Women"] let data = BarChartData(dataSet: set) data.barWidth = 8.5 chartView.data = data chartView.setNeedsDisplay() } override func optionTapped(_ option: Option) { super.handleOption(option, forChartView: chartView) } } extension NegativeStackedBarChartViewController: AxisValueFormatter { func stringForValue(_ value: Double, axis: AxisBase?) -> String { return String(format: "%03.0f-%03.0f", value, value + 10) } }
apache-2.0
8c04a3ec39c3af76fa06eb5b631e4364
32.955224
88
0.570989
5.141243
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobile/AdUnits/Native/PlacementType.swift
1
965
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation @objcMembers public class PlacementType: SingleContainerInt { public static let FeedContent = PlacementType(1) public static let AtomicContent = PlacementType(2) public static let OutsideContent = PlacementType(3) public static let RecommendationWidget = PlacementType(4) public static let Custom = PlacementType(500) }
apache-2.0
f7371830ee1016800c0f2d6c91fe92bb
30.8
74
0.759958
4.336364
false
false
false
false
gifsy/Gifsy
Frameworks/Bond/BondTests/UIControlTests.swift
18
636
// // UIControlTests.swift // Bond // // Created by Srđan Rašić on 20/07/15. // Copyright © 2015 Srdan Rasic. All rights reserved. // import UIKit import XCTest @testable import Bond class UIControlTests: XCTestCase { func test_bnd_eventObservable() { let control = UIControl() var observedEvent: UIControlEvents = UIControlEvents.AllEvents control.bnd_controlEvent.observe { event in observedEvent = event } XCTAssert(observedEvent == UIControlEvents.AllEvents) control.sendActionsForControlEvents(.TouchDown) XCTAssert(observedEvent == UIControlEvents.TouchDown) } }
apache-2.0
41c34e46053f00e9dfbb6c96404ab4d3
21.571429
66
0.710443
4.388889
false
true
false
false
yanyuqingshi/ios-charts
Charts/Classes/Renderers/ChartXAxisRendererRadarChart.swift
4
2086
// // ChartXAxisRendererRadarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIFont public class ChartXAxisRendererRadarChart: ChartXAxisRenderer { private weak var _chart: RadarChartView!; public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, chart: RadarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: nil); _chart = chart; } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled) { return; } var labelFont = _xAxis.labelFont; var labelTextColor = _xAxis.labelTextColor; var sliceangle = _chart.sliceAngle; // calculate the factor that is needed for transforming the value to pixels var factor = _chart.factor; var center = _chart.centerOffsets; for (var i = 0, count = _xAxis.values.count; i < count; i++) { var text = _xAxis.values[i]; if (text == nil) { continue; } var angle = (sliceangle * CGFloat(i) + _chart.rotationAngle) % 360.0; var p = ChartUtils.getPosition(center: center, dist: CGFloat(_chart.yRange) * factor + _xAxis.labelWidth / 2.0, angle: angle); ChartUtils.drawText(context: context, text: text!, point: CGPoint(x: p.x, y: p.y - _xAxis.labelHeight / 2.0), align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } public override func renderLimitLines(#context: CGContext) { /// XAxis LimitLines on RadarChart not yet supported. } }
apache-2.0
5b95e0ae3103c46773ad0f6bdba6198f
30.149254
232
0.607383
4.762557
false
false
false
false
Hodglim/hacking-with-swift
Project-09/Petitions/DetailViewController.swift
2
862
// // DetailViewController.swift // Petitions // // Created by Darren Hodges on 13/10/2015. // Copyright © 2015 Darren Hodges. All rights reserved. // import UIKit import WebKit class DetailViewController: UIViewController { var webView: WKWebView! var detailItem: [String: String]! override func loadView() { webView = WKWebView() view = webView } override func viewDidLoad() { super.viewDidLoad() guard detailItem != nil else { return } if let body = detailItem["body"] { var html = "<html>" html += "<head>" html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" html += "<style> body { font-size: 150%; } </style>" html += "</head>" html += "<body>" html += body html += "</body>" html += "</html>" webView.loadHTMLString(html, baseURL: nil) } } }
mit
0587b018c17c641f30496f20286b0dd2
18.568182
85
0.616725
3.528689
false
false
false
false
sotownsend/flok-apple
Example/flok/PipeViewController.swift
1
4973
//Provides the remote pipe used in testing that talks directly to the JS environment import Foundation import CocoaAsyncSocket import flok class PipeViewController : UIViewController, GCDAsyncSocketDelegate, FlokEnginePipeDelegate, FlokEngineDelegate { var socketQueue: dispatch_queue_t! = nil var listenSocket: GCDAsyncSocket! = nil var connectedSockets: NSMutableArray! = nil var flok: FlokEngine! = nil static var sharedInstance: PipeViewController! override func viewDidLoad() { PipeViewController.sharedInstance = self socketQueue = dispatch_queue_create("socketQueue", nil) listenSocket = GCDAsyncSocket(delegate: self, delegateQueue: socketQueue) do { try listenSocket!.acceptOnPort(6969) } catch { NSException.raise("PipeViewControllerSocketListenError", format: "Could not listen on port 6969", arguments: getVaList([])) } connectedSockets = NSMutableArray(capacity: 9999) let srcPath = NSBundle.mainBundle().pathForResource("app", ofType: "js") let srcData = NSData(contentsOfFile: srcPath!) let src = NSString(data: srcData!, encoding: NSUTF8StringEncoding) as! String flok = FlokEngine(src: src, inPipeMode: true) flok.delegate = self flok.pipeDelegate = self flok.ready() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Override point for customization after application launch. // FlokViewConceierge.preload() } func socket(sock: GCDAsyncSocket!, didAcceptNewSocket newSocket: GCDAsyncSocket!) { dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in if (self == nil) { return } NSLog("Accepted host, id: \(self!.connectedSockets!.count-1)") self!.connectedSockets.addObject(newSocket) let helloPayload = NSString(string: "HELLO\r\n").dataUsingEncoding(NSUTF8StringEncoding) newSocket.writeData(helloPayload, withTimeout: -1, tag: 0) newSocket.readDataWithTimeout(-1, tag: 0) } } var stream: NSString = "" func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) { let str = NSString(data: data, encoding: NSUTF8StringEncoding) as! String stream = stream.stringByAppendingString(str) let process = { (e: String) in do { var out: AnyObject try out = NSJSONSerialization.JSONObjectWithData(e.dataUsingEncoding(NSUTF8StringEncoding) ?? NSData(), options: NSJSONReadingOptions.AllowFragments) as AnyObject dispatch_async(dispatch_get_main_queue(), { if let out = out as? [AnyObject] { self.flok.if_dispatch(out) } else { NSLog("Couldn't parse out: \(out)") } }) } catch let error { NSLog("failed to parse JSON...: \(str), \(error)") } } let components = stream.componentsSeparatedByString("\r\n") for (i, e) in components.enumerate() { if i == components.count-1 { stream = NSString(string: e) } else { process(e) } } sock.readDataWithTimeout(-1, tag: 0) } //The engine, which is just stubbed atm, received a request (which is just forwarded externally for now) func flokEngineDidReceiveIntDispatch(q: [AnyObject]) { //Send out to 'stdout' of network pipe let lastSocket = connectedSockets.lastObject if let lastSocket = lastSocket { do { var payload: NSData? try payload = NSJSONSerialization.dataWithJSONObject(q, options: NSJSONWritingOptions(rawValue: 0)) if let payload = payload { lastSocket.writeData(payload, withTimeout: -1, tag: 0) lastSocket.writeData(("\r\n" as NSString).dataUsingEncoding(NSUTF8StringEncoding), withTimeout: -1, tag: 0) } else { puts("couldn't convert object \(q) into JSON") } } catch { puts("Couldn't create payload for int_dispatch to send to pipe") } } } //----------------------------------------------------------------------------------------------------- //FlokEngineDelegate //----------------------------------------------------------------------------------------------------- func flokEngineRootView(engine: FlokEngine) -> UIView { return self.view } func flokEngine(engine: FlokEngine, didPanicWithMessage message: String) { NSLog("flok engine panic: \(message)") } }
mit
e0ceebe950bdfa13d15f4036d0b9630c
39.770492
178
0.567464
5.100513
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Transport/RetryStrategy/RetryableHost.swift
1
3069
// // RetryableHost.swift // // // Created by Vladislav Fitc on 19/02/2020. // import Foundation public struct RetryableHost { /// The url to target. public let url: URL let supportedCallTypes: CallTypeSupport var isUp: Bool var lastUpdated: Date var retryCount: Int public init(url: URL) { self.init(url: url, callType: .universal) } init(url: URL, callType: CallTypeSupport = .universal) { self.url = url self.supportedCallTypes = callType self.isUp = true self.lastUpdated = .init() self.retryCount = 0 } public func supports(_ callType: CallType) -> Bool { switch callType { case .read: return supportedCallTypes.contains(.read) case .write: return supportedCallTypes.contains(.write) } } mutating func reset() { lastUpdated = .init() isUp = true retryCount = 0 } mutating func hasTimedOut() { isUp = true lastUpdated = .init() retryCount += 1 } mutating func hasFailed() { isUp = false lastUpdated = .init() } } extension RetryableHost { struct CallTypeSupport: OptionSet { let rawValue: Int static let read = CallTypeSupport(rawValue: 1 << 0) static let write = CallTypeSupport(rawValue: 1 << 1) static let universal: CallTypeSupport = [.read, .write] } } extension RetryableHost.CallTypeSupport: CustomDebugStringConvertible { var debugDescription: String { var components: [String] = [] if contains(.read) { components.append("read") } if contains(.write) { components.append("write") } return "[\(components.joined(separator: ", "))]" } } extension RetryableHost: CustomDebugStringConvertible { public var debugDescription: String { return "Host \(supportedCallTypes.debugDescription) \(url) up: \(isUp) retry count: \(retryCount) updated: \(lastUpdated)" } } extension RetryableHost { func timeout(requestOptions: RequestOptions? = nil, default: TimeInterval) -> TimeInterval { let callType: CallType = supportedCallTypes.contains(.write) ? .write : .read let unitTimeout = requestOptions?.timeout(for: callType) ?? `default` let multiplier = retryCount + 1 return TimeInterval(multiplier) * unitTimeout } } extension Array where Element == RetryableHost { /** Reset all hosts down for more than specified interval. */ public mutating func resetExpired(expirationDelay: TimeInterval) { var updatedHosts: [RetryableHost] = [] for host in self { var mutableHost = host let timeDelayExpired = Date().timeIntervalSince(host.lastUpdated) if timeDelayExpired > expirationDelay { mutableHost.reset() } updatedHosts.append(mutableHost) } self = updatedHosts } public mutating func resetAll(for callType: CallType) { var updatedHosts: [RetryableHost] = [] for host in self { var mutableHost = host if mutableHost.supports(callType) { mutableHost.reset() } updatedHosts.append(mutableHost) } self = updatedHosts } }
mit
e100c3378e163b367250f9555c0f6a94
21.902985
126
0.668296
4.181199
false
false
false
false
caopengxu/scw
scw/Pods/Result/Result/Result.swift
31
8363
// Copyright (c) 2015 Rob Rix. All rights reserved. /// An enum representing either a failure with an explanatory error, or a success with a result value. public enum Result<T, Error: Swift.Error>: ResultProtocol, CustomStringConvertible, CustomDebugStringConvertible { case success(T) case failure(Error) // MARK: Constructors /// Constructs a success wrapping a `value`. public init(value: T) { self = .success(value) } /// Constructs a failure wrapping an `error`. public init(error: Error) { self = .failure(error) } /// Constructs a result from an `Optional`, failing with `Error` if `nil`. public init(_ value: T?, failWith: @autoclosure () -> Error) { self = value.map(Result.success) ?? .failure(failWith()) } /// Constructs a result from a function that uses `throw`, failing with `Error` if throws. public init(_ f: @autoclosure () throws -> T) { self.init(attempt: f) } /// Constructs a result from a function that uses `throw`, failing with `Error` if throws. public init(attempt f: () throws -> T) { do { self = .success(try f()) } catch var error { if Error.self == AnyError.self { error = AnyError(error) } self = .failure(error as! Error) } } // MARK: Deconstruction /// Returns the value from `success` Results or `throw`s the error. public func dematerialize() throws -> T { switch self { case let .success(value): return value case let .failure(error): throw error } } /// Case analysis for Result. /// /// Returns the value produced by applying `ifFailure` to `failure` Results, or `ifSuccess` to `success` Results. public func analysis<Result>(ifSuccess: (T) -> Result, ifFailure: (Error) -> Result) -> Result { switch self { case let .success(value): return ifSuccess(value) case let .failure(value): return ifFailure(value) } } // MARK: Errors /// The domain for errors constructed by Result. public static var errorDomain: String { return "com.antitypical.Result" } /// The userInfo key for source functions in errors constructed by Result. public static var functionKey: String { return "\(errorDomain).function" } /// The userInfo key for source file paths in errors constructed by Result. public static var fileKey: String { return "\(errorDomain).file" } /// The userInfo key for source file line numbers in errors constructed by Result. public static var lineKey: String { return "\(errorDomain).line" } /// Constructs an error. public static func error(_ message: String? = nil, function: String = #function, file: String = #file, line: Int = #line) -> NSError { var userInfo: [String: Any] = [ functionKey: function, fileKey: file, lineKey: line, ] if let message = message { userInfo[NSLocalizedDescriptionKey] = message } return NSError(domain: errorDomain, code: 0, userInfo: userInfo) } // MARK: CustomStringConvertible public var description: String { return analysis( ifSuccess: { ".success(\($0))" }, ifFailure: { ".failure(\($0))" }) } // MARK: CustomDebugStringConvertible public var debugDescription: String { return description } } // MARK: - Derive result from failable closure public func materialize<T>(_ f: () throws -> T) -> Result<T, AnyError> { return materialize(try f()) } public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, AnyError> { do { return .success(try f()) } catch { return .failure(AnyError(error)) } } @available(*, deprecated, message: "Use the overload which returns `Result<T, AnyError>` instead") public func materialize<T>(_ f: () throws -> T) -> Result<T, NSError> { return materialize(try f()) } @available(*, deprecated, message: "Use the overload which returns `Result<T, AnyError>` instead") public func materialize<T>(_ f: @autoclosure () throws -> T) -> Result<T, NSError> { do { return .success(try f()) } catch { // This isn't great, but it lets us maintain compatibility until this deprecated // method can be removed. #if _runtime(_ObjC) return .failure(error as NSError) #else // https://github.com/apple/swift-corelibs-foundation/blob/swift-3.0.2-RELEASE/Foundation/NSError.swift#L314 let userInfo = _swift_Foundation_getErrorDefaultUserInfo(error) as? [String: Any] let nsError = NSError(domain: error._domain, code: error._code, userInfo: userInfo) return .failure(nsError) #endif } } // MARK: - Cocoa API conveniences #if !os(Linux) /// Constructs a `Result` with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns an object or `nil` + an error, by reference. e.g.: /// /// Result.try { NSData(contentsOfURL: URL, options: .dataReadingMapped, error: $0) } @available(*, deprecated, message: "This will be removed in Result 4.0. Use `Result.init(attempt:)` instead. See https://github.com/antitypical/Result/issues/85 for the details.") public func `try`<T>(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> T?) -> Result<T, NSError> { var error: NSError? return `try`(&error).map(Result.success) ?? .failure(error ?? Result<T, NSError>.error(function: function, file: file, line: line)) } /// Constructs a `Result` with the result of calling `try` with an error pointer. /// /// This is convenient for wrapping Cocoa API which returns a `Bool` + an error, by reference. e.g.: /// /// Result.try { NSFileManager.defaultManager().removeItemAtURL(URL, error: $0) } @available(*, deprecated, message: "This will be removed in Result 4.0. Use `Result.init(attempt:)` instead. See https://github.com/antitypical/Result/issues/85 for the details.") public func `try`(_ function: String = #function, file: String = #file, line: Int = #line, `try`: (NSErrorPointer) -> Bool) -> Result<(), NSError> { var error: NSError? return `try`(&error) ? .success(()) : .failure(error ?? Result<(), NSError>.error(function: function, file: file, line: line)) } #endif // MARK: - ErrorConvertible conformance extension NSError: ErrorConvertible { public static func error(from error: Swift.Error) -> Self { func cast<T: NSError>(_ error: Swift.Error) -> T { return error as! T } return cast(error) } } // MARK: - Errors /// An “error” that is impossible to construct. /// /// This can be used to describe `Result`s where failures will never /// be generated. For example, `Result<Int, NoError>` describes a result that /// contains an `Int`eger and is guaranteed never to be a `failure`. public enum NoError: Swift.Error, Equatable { public static func ==(lhs: NoError, rhs: NoError) -> Bool { return true } } /// A type-erased error which wraps an arbitrary error instance. This should be /// useful for generic contexts. public struct AnyError: Swift.Error { /// The underlying error. public let error: Swift.Error public init(_ error: Swift.Error) { if let anyError = error as? AnyError { self = anyError } else { self.error = error } } } extension AnyError: ErrorConvertible { public static func error(from error: Error) -> AnyError { return AnyError(error) } } extension AnyError: CustomStringConvertible { public var description: String { return String(describing: error) } } // There appears to be a bug in Foundation on Linux which prevents this from working: // https://bugs.swift.org/browse/SR-3565 // Don't forget to comment the tests back in when removing this check when it's fixed! #if !os(Linux) extension AnyError: LocalizedError { public var errorDescription: String? { return error.localizedDescription } public var failureReason: String? { return (error as? LocalizedError)?.failureReason } public var helpAnchor: String? { return (error as? LocalizedError)?.helpAnchor } public var recoverySuggestion: String? { return (error as? LocalizedError)?.recoverySuggestion } } #endif // MARK: - migration support extension Result { @available(*, unavailable, renamed: "success") public static func Success(_: T) -> Result<T, Error> { fatalError() } @available(*, unavailable, renamed: "failure") public static func Failure(_: Error) -> Result<T, Error> { fatalError() } } extension NSError { @available(*, unavailable, renamed: "error(from:)") public static func errorFromErrorType(_ error: Swift.Error) -> Self { fatalError() } } import Foundation
mit
982f9fb184ab7b9ac2185b28b6ec6294
29.286232
179
0.693983
3.613921
false
false
false
false
FsThatOne/VOne
VOne/AppDelegate.swift
1
953
// // AppDelegate.swift // VOne // // Created by 王正一 on 16/7/19. // Copyright © 2016年 FsThatOne. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) // window!.rootViewController = FSMainViewController() let url = URL(fileURLWithPath: Bundle.main.path(forResource: "WelcomeBGM", ofType: "mp4")!) let WelcomeVC = WelcomeViewController(vFrame: UIScreen.main.bounds, sTime: 2.0) WelcomeVC.contentURL = url WelcomeVC.alwaysRepeat = true window!.rootViewController = WelcomeVC window!.makeKeyAndVisible() return true } } // 3D Touch extension AppDelegate { }
mit
0925f3ed7d286b093f25667fdf2d1e1f
25.971429
144
0.680085
4.538462
false
false
false
false
Bluthwort/Bluthwort
Sources/Classes/Style/UILabelStyle.swift
1
5974
// // UILabelStyle.swift // // Copyright (c) 2018 Bluthwort // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension Bluthwort where Base: UILabel { @discardableResult public func text(_ text: String?, attributes: [NSAttributedStringKey: Any]? = nil) -> Bluthwort { if let text = text, let attributes = attributes { // The current styled text that is displayed by the label. let attributedString = NSAttributedString(string: text, attributes: attributes) base.attributedText = attributedString } else { // The current text that is displayed by the label. base.text = text } return self } @discardableResult public func font(size: CGFloat, type: UIFont.Style = .normal) -> Bluthwort { // The font used to display the text. switch type { case .normal: base.font = UIFont.systemFont(ofSize: size) case .bold: base.font = UIFont.boldSystemFont(ofSize: size) case .italic: base.font = UIFont.bw.italicSystemFont(ofSize: size) } return self } @discardableResult // The font used to display the text. public func font(size: CGFloat, weight: UIFont.Weight) -> Bluthwort { base.font = UIFont.systemFont(ofSize: size, weight: weight) return self } @discardableResult public func textColor(_ color: UIColor) -> Bluthwort { // The color of the text. base.textColor = color return self } @discardableResult public func textAlignment(_ alignment: NSTextAlignment) -> Bluthwort { // The technique to use for aligning the text. base.textAlignment = alignment return self } @discardableResult public func lineBreakMode(_ mode: NSLineBreakMode) -> Bluthwort { // The technique to use for wrapping and truncating the label’s text. base.lineBreakMode = mode return self } @discardableResult public func isEnabled(_ flag: Bool) -> Bluthwort { // The enabled state to use when drawing the label’s text. base.isEnabled = flag return self } @discardableResult public func adjustsFontSizeToFitWidth(_ flag: Bool) -> Bluthwort { // A Boolean value indicating whether the font size should be reduced in order to fit the // title string into the label’s bounding rectangle. base.adjustsFontSizeToFitWidth = flag return self } @discardableResult public func allowsDefaultTighteningForTruncation(_ flag: Bool) -> Bluthwort { // A Boolean value indicating whether the label tightens text before truncating. base.allowsDefaultTighteningForTruncation = flag return self } @discardableResult public func baselineAdjustment(_ adjustment: UIBaselineAdjustment) -> Bluthwort { // Controls how text baselines are adjusted when text needs to shrink to fit in the label. base.baselineAdjustment = adjustment return self } @discardableResult public func minimumScaleFactor(_ factor: CGFloat) -> Bluthwort { // The minimum scale factor supported for the label’s text. base.minimumScaleFactor = factor return self } @discardableResult public func numberOfLines(_ number: Int) -> Bluthwort { // The maximum number of lines to use for rendering text. base.numberOfLines = number return self } @discardableResult public func highlightedTextColor(_ color: UIColor?) -> Bluthwort { // The highlight color applied to the label’s text. base.highlightedTextColor = color return self } @discardableResult public func isHighlighted(_ flag: Bool) -> Bluthwort { // A boolean value indicating whether the label should be drawn with a highlight. base.isHighlighted = flag return self } @discardableResult public func shadowColor(_ color: UIColor?) -> Bluthwort { // The shadow color of the text. base.shadowColor = color return self } @discardableResult public func shadowOffset(_ offset: CGSize) -> Bluthwort { // The shadow offset (measured in points) for the text. base.shadowOffset = offset return self } @discardableResult public func preferredMaxLayoutWidth(_ width: CGFloat) -> Bluthwort { // The preferred maximum width (in points) for a multiline label. base.preferredMaxLayoutWidth = width return self } @discardableResult public func isUserInteractionEnabled(_ flag: Bool) -> Bluthwort { // A boolean value that determines whether user events are ignored and removed from the // event queue. base.isUserInteractionEnabled = flag return self } }
mit
70a14bd64d542b278efbbfd02f1e6bd1
34.5
101
0.666499
5.145815
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornKit/Resources/SubtitleHashGenerator.swift
1
2164
// // This Swift 3 version is based on Swift 2 version by eduo: // https://gist.github.com/eduo/7188bb0029f3bcbf03d4 // // Created by Niklas Berglund on 2017-01-01. // import Foundation public class OpenSubtitlesHash: NSObject { private static let chunkSize: Int = 65536 public struct VideoHash { var fileHash: String var fileSize: UInt64 } public class func hashFor(_ url: URL) -> VideoHash { return self.hashFor(url.path) } public class func hashFor(_ path: String) -> VideoHash { var fileHash = VideoHash(fileHash: "", fileSize: 0) let fileHandler = FileHandle(forReadingAtPath: path)! let fileDataBegin: NSData = fileHandler.readData(ofLength: chunkSize) as NSData fileHandler.seekToEndOfFile() let fileSize: UInt64 = fileHandler.offsetInFile if (UInt64(chunkSize) > fileSize) { return fileHash } fileHandler.seek(toFileOffset: max(0, fileSize - UInt64(chunkSize))) let fileDataEnd: NSData = fileHandler.readData(ofLength: chunkSize) as NSData var hash: UInt64 = fileSize var data_bytes = UnsafeBufferPointer<UInt64>( start: UnsafePointer(fileDataBegin.bytes.assumingMemoryBound(to: UInt64.self)), count: fileDataBegin.length/MemoryLayout<UInt64>.size ) hash = data_bytes.reduce(hash,&+) data_bytes = UnsafeBufferPointer<UInt64>( start: UnsafePointer(fileDataEnd.bytes.assumingMemoryBound(to: UInt64.self)), count: fileDataEnd.length/MemoryLayout<UInt64>.size ) hash = data_bytes.reduce(hash,&+) fileHash.fileHash = String(format:"%016qx", arguments: [hash]) fileHash.fileSize = fileSize fileHandler.closeFile() return fileHash } } // Usage example: // let videoUrl = Bundle.main.url(forResource: "dummy5", withExtension: "rar") // let videoHash = OpenSubtitlesHash.hashFor(videoUrl!) // debugPrint("File hash: \(videoHash.fileHash)\nFile size: \(videoHash.fileSize)")
gpl-3.0
366c1f167571e5e1ec73077b11080ac4
32.8125
91
0.633087
4.452675
false
false
false
false
duycao2506/SASCoffeeIOS
Pods/SwiftDate/Sources/SwiftDate/CalendarName.swift
2
10259
// SwiftDate // Manage Date/Time & Timezone in Swift // // Created by: Daniele Margutti // Email: <hello@danielemargutti.com> // Web: <http://www.danielemargutti.com> // // Licensed under MIT License. import Foundation // MARK: - CalendarName Shortcut /// This enum allows you set a valid calendar using swift's type safe support public enum CalendarName: RawRepresentable { public typealias RawValue = String case current, currentAutoUpdating case gregorian, buddhist, chinese, coptic, ethiopicAmeteMihret, ethiopicAmeteAlem, hebrew, iso8601, indian, islamic, islamicCivil, japanese, persian, republicOfChina, islamicTabular, islamicUmmAlQura /// Raw value of the calendar public var rawValue: RawValue { switch self { case .currentAutoUpdating: return "current_autoupdating" case .current: return "current" case .gregorian: return "gregorian" case .buddhist: return "buddhist" case .chinese: return "chinese" case .coptic: return "coptic" case .ethiopicAmeteMihret: return "ethiopicAmeteMihret" case .ethiopicAmeteAlem: return "ethiopicAmeteAlem" case .hebrew: return "hebrew" case .iso8601: return "iso8601" case .indian: return "indian" case .islamic: return "islamic" case .islamicCivil: return "islamicCivil" case .japanese: return "japanese" case .persian: return "persian" case .republicOfChina: return "republicOfChina" case .islamicTabular: return "islamicTabular" case .islamicUmmAlQura: return "islamicUmmAlQura" } } // Initialize a new CalendarName from raw string value. If valid calendar can be created `nil` is returned public init?(rawValue: RawValue) { switch rawValue { case CalendarName.currentAutoUpdating.rawValue: self = .currentAutoUpdating case CalendarName.current.rawValue: self = .current case CalendarName.gregorian.rawValue: self = .gregorian case CalendarName.buddhist.rawValue: self = .buddhist case CalendarName.ethiopicAmeteMihret.rawValue: self = .ethiopicAmeteMihret case CalendarName.ethiopicAmeteAlem.rawValue: self = .ethiopicAmeteAlem case CalendarName.hebrew.rawValue: self = .hebrew case CalendarName.iso8601.rawValue: self = .iso8601 case CalendarName.indian.rawValue: self = .indian case CalendarName.islamic.rawValue: self = .islamic case CalendarName.islamicCivil.rawValue: self = .islamicCivil case CalendarName.japanese.rawValue: self = .japanese case CalendarName.persian.rawValue: self = .persian case CalendarName.republicOfChina.rawValue: self = .republicOfChina case CalendarName.islamicTabular.rawValue: self = .islamicTabular case CalendarName.islamicUmmAlQura.rawValue: self = .islamicUmmAlQura default: return nil } } /// Initialize a new CalendarName from identifier /// /// - Parameter identifier: identifier of the calendar, if `nil` `autoupdatingCurrent` calendar is set public init(_ identifier: Calendar.Identifier?) { guard let id = identifier else { self = CalendarName.currentAutoUpdating return } switch id { case .gregorian: self = CalendarName.gregorian case .buddhist: self = CalendarName.buddhist case .chinese: self = CalendarName.chinese case .coptic: self = CalendarName.coptic case .ethiopicAmeteMihret: self = CalendarName.ethiopicAmeteMihret case .ethiopicAmeteAlem: self = CalendarName.ethiopicAmeteAlem case .hebrew: self = CalendarName.hebrew case .iso8601: self = CalendarName.iso8601 case .indian: self = CalendarName.indian case .islamic: self = CalendarName.islamic case .islamicCivil: self = CalendarName.islamicCivil case .japanese: self = CalendarName.japanese case .persian: self = CalendarName.persian case .republicOfChina: self = CalendarName.republicOfChina case .islamicTabular: self = CalendarName.islamicTabular case .islamicUmmAlQura: self = CalendarName.islamicUmmAlQura } } /// Return a new `Calendar` instance from a given identifier public var calendar: Calendar { var identifier: Calendar.Identifier switch self { case .current: return Calendar.current case .currentAutoUpdating: return Calendar.autoupdatingCurrent case .gregorian: identifier = Calendar.Identifier.gregorian case .buddhist: identifier = Calendar.Identifier.buddhist case .chinese: identifier = Calendar.Identifier.chinese case .coptic: identifier = Calendar.Identifier.coptic case .ethiopicAmeteMihret: identifier = Calendar.Identifier.ethiopicAmeteMihret case .ethiopicAmeteAlem: identifier = Calendar.Identifier.ethiopicAmeteAlem case .hebrew: identifier = Calendar.Identifier.hebrew case .iso8601: identifier = Calendar.Identifier.iso8601 case .indian: identifier = Calendar.Identifier.indian case .islamic: identifier = Calendar.Identifier.islamic case .islamicCivil: identifier = Calendar.Identifier.islamicCivil case .japanese: identifier = Calendar.Identifier.japanese case .persian: identifier = Calendar.Identifier.persian case .republicOfChina: identifier = Calendar.Identifier.republicOfChina case .islamicTabular: identifier = Calendar.Identifier.islamicTabular case .islamicUmmAlQura: identifier = Calendar.Identifier.islamicUmmAlQura } return Calendar(identifier: identifier) } // Identifier of the calendar public var identifier: Calendar.Identifier { return self.calendar.identifier } } //MARK: Calendar.Component Extension extension Calendar.Component { fileprivate var cfValue: CFCalendarUnit { return CFCalendarUnit(rawValue: self.rawValue) } } extension Calendar.Component { /// https://github.com/apple/swift-corelibs-foundation/blob/swift-DEVELOPMENT-SNAPSHOT-2016-09-10-a/CoreFoundation/Locale.subproj/CFCalendar.h#L68-L83 internal var rawValue: UInt { switch self { case .era: return 1 << 1 case .year: return 1 << 2 case .month: return 1 << 3 case .day: return 1 << 4 case .hour: return 1 << 5 case .minute: return 1 << 6 case .second: return 1 << 7 case .weekday: return 1 << 9 case .weekdayOrdinal: return 1 << 10 case .quarter: return 1 << 11 case .weekOfMonth: return 1 << 12 case .weekOfYear: return 1 << 13 case .yearForWeekOfYear: return 1 << 14 case .nanosecond: return 1 << 15 case .calendar: return 1 << 16 case .timeZone: return 1 << 17 } } internal init?(rawValue: UInt) { switch rawValue { case Calendar.Component.era.rawValue: self = .era case Calendar.Component.year.rawValue: self = .year case Calendar.Component.month.rawValue: self = .month case Calendar.Component.day.rawValue: self = .day case Calendar.Component.hour.rawValue: self = .hour case Calendar.Component.minute.rawValue: self = .minute case Calendar.Component.second.rawValue: self = .second case Calendar.Component.weekday.rawValue: self = .weekday case Calendar.Component.weekdayOrdinal.rawValue: self = .weekdayOrdinal case Calendar.Component.quarter.rawValue: self = .quarter case Calendar.Component.weekOfMonth.rawValue: self = .weekOfMonth case Calendar.Component.weekOfYear.rawValue: self = .weekOfYear case Calendar.Component.yearForWeekOfYear.rawValue: self = .yearForWeekOfYear case Calendar.Component.nanosecond.rawValue: self = .nanosecond case Calendar.Component.calendar.rawValue: self = .calendar case Calendar.Component.timeZone.rawValue: self = .timeZone default: return nil } } } //MARK: - Calendar Extension extension Calendar { // The code below is part of the Swift.org code. It is included as rangeOfUnit is a very useful // function for the startOf and endOf functions. // As always we would prefer using Foundation code rather than inventing code ourselves. typealias CFType = CFCalendar private var cfObject: CFType { return unsafeBitCast(self as NSCalendar, to: CFCalendar.self) } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer. /// The current exposed API in Foundation on Darwin platforms is: /// `public func rangeOfUnit(unit: NSCalendarUnit, startDate datep: /// AutoreleasingUnsafeMutablePointer<NSDate?>, interval tip: /// UnsafeMutablePointer<NSTimeInterval>, forDate date: NSDate) -> Bool` /// which is not implementable on Linux due to the lack of being able to properly implement /// AutoreleasingUnsafeMutablePointer. /// /// - parameters: /// - component: the unit to determine the range for /// - date: the date to wrap the unit around /// - returns: the range (date interval) of the unit around the date /// /// - Experiment: This is a draft API currently under consideration for official import into /// Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the /// near future /// public func rangex(of component: Calendar.Component, for date: Date) -> DateTimeInterval? { var start: CFAbsoluteTime = 0.0 var ti: CFTimeInterval = 0.0 let res: Bool = withUnsafeMutablePointer(to: &start) { startp -> Bool in return withUnsafeMutablePointer(to: &ti) { tip -> Bool in let startPtr: UnsafeMutablePointer<CFAbsoluteTime> = startp let tiPtr: UnsafeMutablePointer<CFTimeInterval> = tip return CFCalendarGetTimeRangeOfUnit(cfObject, component.cfValue, date.timeIntervalSinceReferenceDate, startPtr, tiPtr) } } if res { let startDate = Date(timeIntervalSinceReferenceDate: start) return DateTimeInterval(start: startDate, duration: ti) } return nil } /// Create a new NSCalendar instance from CalendarName structure. You can also use /// <CalendarName>.calendar to get a new instance of NSCalendar with picked type. /// /// - parameter type: type of the calendar /// /// - returns: instance of the new Calendar public static func fromType(_ type: CalendarName) -> Calendar { return type.calendar } }
gpl-3.0
f8f96ccd826e27b4aedfe633fb1df83c
40.366935
151
0.717029
4.050138
false
false
false
false
feighter09/Cloud9
SoundCloud Pro/LFTableViewDataSource.swift
1
2554
// // LFTableViewDataSource.swift // ScholarsAd // // Created by Austin Feight on 12/31/14. // Copyright (c) 2014 ScholarsAd. All rights reserved. // import UIKit typealias LFConstructTableCellBlock = (UITableViewCell, AnyObject) -> Void typealias LFDeleteTableCellBlock = (NSIndexPath) -> Void class LFTableViewDataSource: NSObject, UITableViewDataSource { var dataItems = [AnyObject]() /** Callback when a cell is deleted from the table */ var deleteCellBlock: LFDeleteTableCellBlock? private var defaultCellIdentifier: String private var cellIdentifiers = [NSIndexPath: String]() private var constructCellBlock: LFConstructTableCellBlock init(defaultCellIdentifier: String, dataItems: [AnyObject] = [], constructCellBlock: LFConstructTableCellBlock) { self.defaultCellIdentifier = defaultCellIdentifier self.constructCellBlock = constructCellBlock self.dataItems = dataItems } } // MARK: - Interface extension LFTableViewDataSource { func setCellIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath) { cellIdentifiers[indexPath] = identifier } func identifierForIndexPath(indexPath: NSIndexPath) -> String { return cellIdentifiers[indexPath] == nil ? defaultCellIdentifier : cellIdentifiers[indexPath]! } func dataItemForIndexPath(indexPath: NSIndexPath) -> AnyObject { return dataItems[indexPath.row] } } // MARK: - Data Source Methods extension LFTableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataItems.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = identifierForIndexPath(indexPath) let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) let data: AnyObject = dataItemForIndexPath(indexPath) constructCellBlock(cell, data) cell.tag = indexPath.row return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { dataItems.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) deleteCellBlock?(indexPath) } 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 } } }
lgpl-3.0
7ef7eb8d6ed40b06326bcde135d68622
30.146341
118
0.74119
5.007843
false
false
false
false
steveholt55/Gear8-Demo
Gear8Demo/GameViewController.swift
1
880
// // Copyright (c) 2015 Brandon Jenniges. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true let scene = GameScene(size: skView.frame.size) scene.scaleMode = .AspectFill skView.presentScene(scene) } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .AllButUpsideDown } else { return .All } } override func prefersStatusBarHidden() -> Bool { return true } }
mit
11b1554857def9b48796d8e5e6775894
22.157895
82
0.6125
5.465839
false
false
false
false
mattdaw/SwiftBoard
SwiftBoard/ViewModels/FolderViewModel.swift
1
1620
// // FolderViewModel.swift // SwiftBoard // // Created by Matt Daw on 2014-11-15. // Copyright (c) 2014 Matt Daw. All rights reserved. // import Foundation enum FolderViewModelState { case Closed, AppHovering, PreparingToOpen, Open } protocol FolderViewModelDelegate: class { func folderViewModelDraggingDidChange(Bool) func folderViewModelEditingDidChange(Bool) func folderViewModelZoomedDidChange(Bool) func folderViewModelStateDidChange(FolderViewModelState) } class FolderViewModel: ListViewModel, ItemViewModel { var name: String var parentListViewModel: ListViewModel? weak var folderViewModelDelegate: FolderViewModelDelegate? var dragging: Bool = false { didSet { folderViewModelDelegate?.folderViewModelDraggingDidChange(dragging) } } var editing: Bool = false { didSet { folderViewModelDelegate?.folderViewModelEditingDidChange(editing) for var i=0; i < numberOfItems(); i++ { let item = itemAtIndex(i) item.editing = editing } } } var zoomed: Bool = false { didSet { folderViewModelDelegate?.folderViewModelZoomedDidChange(zoomed) } } var state: FolderViewModelState { didSet { folderViewModelDelegate?.folderViewModelStateDidChange(state) } } init(name folderName: String, viewModels initViewModels: [ItemViewModel]) { name = folderName state = .Closed super.init(viewModels: initViewModels) } }
mit
7ddaa53dd4a5cd2dfa031af90eed7995
25.129032
79
0.651235
5.0625
false
false
false
false
WangWenzhuang/ZKCommon
ZKCommon/Extension/FileManager.swift
1
2520
// // FileManager.swift // ZKCommon // // Created by 王文壮 on 2017/6/29. // Copyright © 2017年 WangWenzhuang. All rights reserved. // import UIKit public extension FileManager { final class zk { /// ZK: 判断文件或文件夹是否存在 /// /// - Parameters: /// - path: 文件路径 /// - Returns: Bool public static func exists(_ path: String) -> Bool { return FileManager.default.fileExists(atPath: path) } /// ZK: 创建文件夹 /// /// - Parameters: /// - path: 文件夹路径 public static func createDirectory(_ path: String) { do { try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) } catch { print("ZKCommon -> \(Date.zk.nowString) -> : 创建文件夹失败:\(path)") } } /// ZK: 单个文件大小 /// /// - Parameters: /// - path: 文件路径 /// - Returns: 文件大小 public static func fileSizeAtPath(_ path: String) -> Double { var size: Double = 0 if self.exists(path) { do { let attr = try FileManager.default.attributesOfItem(atPath: path) size = Double(attr[.size] as! UInt64) } catch { } } return size } /// ZK: 获取文件夹大小 /// /// - Parameters: /// - path: 文件夹路径 /// - Returns: 文件夹大小 public static func folderSizeAtPath(_ path: String) -> Double { var size: Double = 0 guard self.exists(path) else { return size } do { let files = try FileManager.default.contentsOfDirectory(atPath: path) for file in files { size += self.fileSizeAtPath("\(path)/\(file)") } } catch { } return size / 1024 / 1024 } /// ZK: 删除文件 /// /// - Parameters: /// - path: 文件路径 public static func remove(_ path: String) { do { try FileManager.default.removeItem(atPath: path) } catch { print("ZKCommon -> \(Date.zk.nowString) -> : 删除文件失败:\(path)") } } } }
mit
8efef1c5fc6e2cf7d8ab2cfd7a7ae574
28.759494
121
0.458528
4.556202
false
false
false
false
jopamer/swift
test/SILGen/constrained_extensions.swift
1
14358
// RUN: %target-swift-emit-silgen -module-name constrained_extensions -enable-sil-ownership -primary-file %s | %FileCheck %s // RUN: %target-swift-emit-sil -module-name constrained_extensions -O -primary-file %s > /dev/null // RUN: %target-swift-emit-ir -module-name constrained_extensions -primary-file %s > /dev/null extension Array where Element == Int { // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE1xSaySiGyt_tcfC : $@convention(method) (@thin Array<Int>.Type) -> @owned Array<Int> public init(x: ()) { self.init() } // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE16instancePropertySivg : $@convention(method) (@guaranteed Array<Int>) -> Int // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE16instancePropertySivs : $@convention(method) (Int, @inout Array<Int>) -> () // CHECK-LABEL: sil shared [transparent] [serialized] @$SSa22constrained_extensionsSiRszlE16instancePropertySivmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Array<Int>, @thick Array<Int>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @$SSa22constrained_extensionsSiRszlE16instancePropertySivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Array<Int>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var instanceProperty: Element { get { return self[0] } set { self[0] = newValue } } // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE14instanceMethodSiyF : $@convention(method) (@guaranteed Array<Int>) -> Int public func instanceMethod() -> Element { return instanceProperty } // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE14instanceMethod1eS2i_tF : $@convention(method) (Int, @guaranteed Array<Int>) -> Int public func instanceMethod(e: Element) -> Element { return e } // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE14staticPropertySivgZ : $@convention(method) (@thin Array<Int>.Type) -> Int public static var staticProperty: Element { return Array(x: ()).instanceProperty } // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE12staticMethodSiyFZ : $@convention(method) (@thin Array<Int>.Type) -> Int public static func staticMethod() -> Element { return staticProperty } // CHECK-LABEL: sil non_abi [serialized] @$SSa22constrained_extensionsSiRszlE12staticMethod1eS2iSg_tFZfA_ : $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE12staticMethod1eS2iSg_tFZ : $@convention(method) (Optional<Int>, @thin Array<Int>.Type) -> Int public static func staticMethod(e: Element? = nil) -> Element { return e! } // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlEySiyt_tcig : $@convention(method) (@guaranteed Array<Int>) -> Int public subscript(i: ()) -> Element { return self[0] } // CHECK-LABEL: sil @$SSa22constrained_extensionsSiRszlE21inoutAccessOfPropertyyyF : $@convention(method) (@inout Array<Int>) -> () public mutating func inoutAccessOfProperty() { func increment(x: inout Element) { x += 1 } increment(x: &instanceProperty) } } extension Dictionary where Key == Int { // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE1xSDySiq_Gyt_tcfC : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @owned Dictionary<Int, Value> { public init(x: ()) { self.init() } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE16instancePropertyq_vg : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE16instancePropertyq_vs : $@convention(method) <Key, Value where Key == Int> (@in Value, @inout Dictionary<Int, Value>) -> () // CHECK-LABEL: sil shared [transparent] [serialized] @$SSD22constrained_extensionsSiRszrlE16instancePropertyq_vmytfU_ : $@convention(method) <Key, Value where Key == Int> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Int, Value>, @thick Dictionary<Int, Value>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @$SSD22constrained_extensionsSiRszrlE16instancePropertyq_vm : $@convention(method) <Key, Value where Key == Int> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Dictionary<Int, Value>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var instanceProperty: Value { get { return self[0]! } set { self[0] = newValue } } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE14instanceMethodq_yF : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value public func instanceMethod() -> Value { return instanceProperty } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE14instanceMethod1vq_q__tF : $@convention(method) <Key, Value where Key == Int> (@in_guaranteed Value, @guaranteed Dictionary<Int, Value>) -> @out Value public func instanceMethod(v: Value) -> Value { return v } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE12staticMethodSiyFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int public static func staticMethod() -> Key { return staticProperty } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE14staticPropertySivgZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> Int public static var staticProperty: Key { return 0 } // CHECK-LABEL: sil non_abi [serialized] @$SSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZfA_ : $@convention(thin) <Key, Value where Key == Int> () -> Optional<Int> // CHECK-LABEL: sil non_abi [serialized] @$SSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZfA0_ : $@convention(thin) <Key, Value where Key == Int> () -> @out Optional<Value> // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE12staticMethod1k1vq_SiSg_q_SgtFZ : $@convention(method) <Key, Value where Key == Int> (Optional<Int>, @in_guaranteed Optional<Value>, @thin Dictionary<Int, Value>.Type) -> @out Value public static func staticMethod(k: Key? = nil, v: Value? = nil) -> Value { return v! } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE17callsStaticMethodq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value public static func callsStaticMethod() -> Value { return staticMethod() } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE16callsConstructorq_yFZ : $@convention(method) <Key, Value where Key == Int> (@thin Dictionary<Int, Value>.Type) -> @out Value public static func callsConstructor() -> Value { return Dictionary(x: ()).instanceMethod() } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlEyq_yt_tcig : $@convention(method) <Key, Value where Key == Int> (@guaranteed Dictionary<Int, Value>) -> @out Value public subscript(i: ()) -> Value { return self[0]! } // CHECK-LABEL: sil @$SSD22constrained_extensionsSiRszrlE21inoutAccessOfPropertyyyF : $@convention(method) <Key, Value where Key == Int> (@inout Dictionary<Int, Value>) -> () public mutating func inoutAccessOfProperty() { func increment(x: inout Value) { } increment(x: &instanceProperty) } } public class GenericClass<X, Y> {} extension GenericClass where Y == () { // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvs : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5valuexvm : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var value: X { get { while true {} } set {} } // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvg : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvs : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvmytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlE5emptyytvm : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public var empty: Y { get { return () } set {} } // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcig : $@convention(method) <X, Y where Y == ()> (@guaranteed GenericClass<X, ()>) -> @out X // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyxyt_tcim : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public subscript(_: Y) -> X { get { while true {} } set {} } // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcig : $@convention(method) <X, Y where Y == ()> (@in_guaranteed X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcis : $@convention(method) <X, Y where Y == ()> (@in X, @guaranteed GenericClass<X, ()>) -> () // CHECK-LABEL: sil shared [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcimytfU_ : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed GenericClass<X, ()>, @thick GenericClass<X, ()>.Type) -> () // CHECK-LABEL: sil [transparent] [serialized] @$S22constrained_extensions12GenericClassCAAytRs_rlEyyxcim : $@convention(method) <X, Y where Y == ()> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed X, @guaranteed GenericClass<X, ()>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) public subscript(_: X) -> Y { get { while true {} } set {} } } protocol VeryConstrained {} struct AnythingGoes<T> { // CHECK-LABEL: sil hidden [transparent] @$S22constrained_extensions12AnythingGoesV13meaningOfLifexSgvpfi : $@convention(thin) <T> () -> @out Optional<T> var meaningOfLife: T? = nil } extension AnythingGoes where T : VeryConstrained { // CHECK-LABEL: sil hidden @$S22constrained_extensions12AnythingGoesVA2A15VeryConstrainedRzlE13fromExtensionACyxGyt_tcfC : $@convention(method) <T where T : VeryConstrained> (@thin AnythingGoes<T>.Type) -> @out AnythingGoes<T> { // CHECK: [[INIT:%.*]] = function_ref @$S22constrained_extensions12AnythingGoesV13meaningOfLifexSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK: [[RESULT:%.*]] = alloc_stack $Optional<T> // CHECK: apply [[INIT]]<T>([[RESULT]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK: return init(fromExtension: ()) {} } extension Array where Element == Int { struct Nested { // CHECK-LABEL: sil hidden [transparent] @$SSa22constrained_extensionsSiRszlE6NestedV1eSiSgvpfi : $@convention(thin) () -> Optional<Int> var e: Element? = nil // CHECK-LABEL: sil hidden @$SSa22constrained_extensionsSiRszlE6NestedV10hasDefault1eySiSg_tFfA_ : $@convention(thin) () -> Optional<Int> // CHECK-LABEL: sil hidden @$SSa22constrained_extensionsSiRszlE6NestedV10hasDefault1eySiSg_tF : $@convention(method) (Optional<Int>, @inout Array<Int>.Nested) -> () mutating func hasDefault(e: Element? = nil) { self.e = e } } } extension Array where Element == AnyObject { class NestedClass { // CHECK-LABEL: sil hidden @$SSa22constrained_extensionsyXlRszlE11NestedClassCfd : $@convention(method) (@guaranteed Array<AnyObject>.NestedClass) -> @owned Builtin.NativeObject // CHECK-LABEL: sil hidden @$SSa22constrained_extensionsyXlRszlE11NestedClassCfD : $@convention(method) (@owned Array<AnyObject>.NestedClass) -> () deinit { } // CHECK-LABEL: sil hidden @$SSa22constrained_extensionsyXlRszlE11NestedClassCACyyXl_GycfC : $@convention(method) (@thick Array<AnyObject>.NestedClass.Type) -> @owned Array<AnyObject>.NestedClass // CHECK-LABEL: sil hidden @$SSa22constrained_extensionsyXlRszlE11NestedClassCACyyXl_Gycfc : $@convention(method) (@owned Array<AnyObject>.NestedClass) -> @owned Array<AnyObject>.NestedClass } class DerivedClass : NestedClass { // CHECK-LABEL: sil hidden [transparent] @$SSa22constrained_extensionsyXlRszlE12DerivedClassC1eyXlSgvpfi : $@convention(thin) () -> @owned Optional<AnyObject> // CHECK-LABEL: sil hidden @$SSa22constrained_extensionsyXlRszlE12DerivedClassCfE : $@convention(method) (@guaranteed Array<AnyObject>.DerivedClass) -> () var e: Element? = nil } } func referenceNestedTypes() { _ = Array<AnyObject>.NestedClass() _ = Array<AnyObject>.DerivedClass() }
apache-2.0
9624df4897b7aeca17ed26a3dbe340f8
62.513274
311
0.716734
3.94449
false
false
false
false
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Media/AwesomeMediaManager.swift
1
10357
// // AwesomeMediaManager.swift // AwesomeMedia // // Created by Evandro Harrison Hoffmann on 4/5/18. // import AVFoundation import AwesomeNetwork import AwesomeTracking public class AwesomeMediaManager: NSObject { public static var shared = AwesomeMediaManager() public var avPlayer = AVPlayer() // Private Variables fileprivate var timeObserver: AnyObject? fileprivate var playbackLikelyToKeepUpContext = 0 fileprivate var playbackBufferFullContext = 1 fileprivate var bufferTimer: Timer? // Public Variables public var bufferingState = [String: Bool]() public var mediaParams = AwesomeMediaParams() public func playMedia(withParams params: AwesomeMediaParams, reset: Bool = false, inPlayerLayer playerLayer: AVPlayerLayer? = nil, viewController: UIViewController? = nil) { guard let url = params.url?.url?.offlineURLIfAvailable else { AwesomeMedia.log("No URL provided") return } // In case there is a view controller and isn't reachable, return callback /*if let viewController = viewController, !(AwesomeNetwork.shared?.isReachable ?? false), !url.offlineFileExists { AwesomeMedia.log("No Internet connection") viewController.showNoConnectionAlert() return }*/ // set current media params mediaParams = params // prepare media if !avPlayer.isCurrentItem(withUrl: url) || reset { prepareMedia(withUrl: url) } else { avPlayer.play() notifyPlaying() } // add player to layer playerLayer?.player = avPlayer //adjust speed avPlayer.adjustSpeed() // add remote controls AwesomeMediaControlCenter.configBackgroundPlay(withParams: params) } public func prepareMedia(withUrl url: URL, andPlay play: Bool = true) { //avPlayer.attachBitmovinTracker() sharedAVPlayer.stop(resetTime: false) notifyMediaEvent(.buffering) AMAVPlayerItem.item(withUrl: url) { (playerItem) in notifyMediaEvent(.stoppedBuffering) //select current caption //AwesomeMediaManager.shared.mediaParams.currentCaption?.language // replace current item self.avPlayer.replaceCurrentItem(with: playerItem) // add observers for player and current item self.addObservers(withItem: playerItem) // at this point media will start buffering self.startedBuffering() // load saved media time playerItem.loadSavedTime() // start playing if the case if play { self.avPlayer.play() } } } // Media State public func mediaIsLoading(withParams params: AwesomeMediaParams) -> Bool { guard let url = params.url?.url?.offlineURLIfAvailable else { return false } guard sharedAVPlayer.isCurrentItem(withUrl: url) else { return false } return AwesomeMediaManager.shared.bufferingState[url.absoluteString] ?? false } public func updateMediaState(event: AwesomeMediaEvent) { if let url = sharedAVPlayer.currentItem?.url { switch event { case .buffering: bufferingState[url.absoluteString] = true case .stopped, .stoppedBuffering, .paused: bufferingState[url.absoluteString] = false default: break } } } } // MARK: - Notifications extension AwesomeMediaManager { fileprivate func addObservers(withItem item: AMAVPlayerItem? = nil) { addTimeObserver() addBufferObserver(forItem: item) avPlayer.addObserver(self, forKeyPath: "rate", options: .new, context: nil) // notification for didFinishPlaying NotificationCenter.default.addObserver(self, selector: #selector(AwesomeMediaManager.didFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: avPlayer.currentItem) } // MARK: - Buffer observer fileprivate func addBufferObserver(forItem item: AMAVPlayerItem?) { guard let item = item else { return } item.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: .new, context: &playbackLikelyToKeepUpContext) item.addObserver(self, forKeyPath: "playbackBufferFull", options: .new, context: &playbackBufferFullContext) item.addObserver(self, forKeyPath: "playbackBufferEmpty", options: .new, context: nil) item.addObserver(self, forKeyPath: "status", options: .new, context: nil) item.addObserver(self, forKeyPath: "timeControlStatus", options: .new, context: nil) } // MARK: - Time Observer fileprivate func addTimeObserver() { let timeInterval: CMTime = CMTimeMakeWithSeconds(1.0, preferredTimescale: 10) timeObserver = avPlayer.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main) { (elapsedTime: CMTime) -> Void in self.observeTime(elapsedTime) } as AnyObject? } fileprivate func observeTime(_ elapsedTime: CMTime) { guard let currentItem = avPlayer.currentItem else { return } if CMTimeGetSeconds(currentItem.duration).isFinite { notifyMediaEvent(.timeUpdated) } } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { /*switch avPlayer.timeControlStatus { case .waitingToPlayAtSpecifiedRate: AwesomeMedia.log("avPlayer.timeControlStatus: waiting \(avPlayer.reasonForWaitingToPlay ?? AVPlayer.WaitingReason(rawValue: ""))") if avPlayer.reasonForWaitingToPlay == .noItemToPlay { avPlayer.pause() } default: break // case .playing: // notifyMediaEvent(.startedPlaying) // AwesomeMedia.log("avPlayer.timeControlStatus: playing") // case .paused: // notifyMediaEvent(.pausedPlaying) // AwesomeMedia.log("avPlayer.timeControlStatus: paused") }*/ // Check for media buffering if context == &playbackLikelyToKeepUpContext || context == &playbackBufferFullContext { if let currentItem = sharedAVPlayer.currentItem, currentItem.isPlaybackLikelyToKeepUp || currentItem.isPlaybackBufferFull { stoppedBuffering() } else { startedBuffering() } } // Check for Rate Changes if keyPath == "rate" { if avPlayer.isPlaying { notifyMediaEvent(.speedRateChanged) } else { notifyMediaEvent(.paused) sharedAVPlayer.currentItem?.saveTime() } } // Check for Status Changes else if keyPath == "status" { var status: AVPlayerItem.Status = .unknown // Get the status change from the change dictionary if let statusNumber = change?[.newKey] as? NSNumber { status = AVPlayerItem.Status(rawValue: statusNumber.intValue)! } switch status { case .readyToPlay: notifyPlaying() case .failed, .unknown: notifyMediaEvent(.failed) } } } fileprivate func notifyPlaying() { notifyMediaEvent(.playing) if sharedAVPlayer.currentItem?.isVideo ?? false { notifyMediaEvent(.playingVideo, object: mediaParams as AnyObject) // in case it's video, we can choose from the app to show or not mini player if mediaParams.shouldShowMiniPlayer { notifyMediaEvent(.showMiniPlayer, object: mediaParams as AnyObject) } else { notifyMediaEvent(.hideMiniPlayer, object: mediaParams as AnyObject) } } else { notifyMediaEvent(.playingAudio, object: mediaParams as AnyObject) if mediaParams.shouldShowMiniPlayer { notifyMediaEvent(.showMiniPlayer, object: mediaParams as AnyObject) } else { notifyMediaEvent(.hideMiniPlayer, object: mediaParams as AnyObject) } } } // Handle buffering fileprivate func startedBuffering() { notifyMediaEvent(.buffering) startBufferTimer() } fileprivate func stoppedBuffering() { notifyMediaEvent(.stoppedBuffering) cancelBufferTimer() } public func startBufferTimer() { cancelBufferTimer() bufferTimer = Timer.scheduledTimer(withTimeInterval: AwesomeMedia.bufferTimeout, repeats: false, block: { (timer) in notifyMediaEvent(.timedOut) }) } public func cancelBufferTimer() { bufferTimer?.invalidate() bufferTimer = nil } // Finished Playing Observer @objc public func didFinishPlaying(){ // tracking let dict: AwesomeTrackingDictionary = [:] if let courseId = mediaParams.params["courseId"] { dict.addElement(courseId, forKey: .courseID) } if let questId = mediaParams.params["questId"] { dict.addElement(questId, forKey: .questID) } if let assetId = mediaParams.params["assetId"] { dict.addElement(assetId, forKey: .assetID) } AwesomeTracking.track(.assetCompleted, with: dict) // stop playing sharedAVPlayer.stop(resetTime: true) notifyMediaEvent(.finished) } }
mit
9419f6a86efa6be45d132504f0836699
33.523333
177
0.58936
5.511974
false
false
false
false
cwaffles/Soulcast
Soulcast/EulaVC.swift
1
1639
// // EulaVC.swift // Soulcast // // Created by June Kim on 2016-10-15. // Copyright © 2016 Soulcast-team. All rights reserved. // import Foundation import UIKit protocol EulaVCDelegate: class { func didTapOKButton(_ vc:EulaVC) } class EulaVC: UIViewController { var agreementString:String { var content = "" if let path = Bundle.main.path(forResource: "eula", ofType: "txt"){ do {try content = String(contentsOfFile: path, encoding: String.Encoding.utf8) } catch {} } return content } let okButton = UIButton(type: .system) let eulaContainerView = UIView() let eulaTextView = UITextView() weak var delegate: EulaVCDelegate? override func viewDidLoad() { let margin:CGFloat = 15 okButton.setTitle("Agree", for: UIControlState()) let buttonWidth:CGFloat = 100 let buttonHeight:CGFloat = 50 okButton.frame = CGRect( x: (screenWidth - buttonWidth)/2, y: screenHeight - buttonHeight - margin, width: buttonWidth, height: buttonHeight) okButton.addTarget(self, action: #selector(okButtonTapped), for: .touchUpInside) eulaContainerView.frame = CGRect( x: margin, y: margin, width: screenWidth - 2*margin, height: screenHeight - 3*margin - buttonHeight) view.addSubview(eulaContainerView) eulaTextView.text = agreementString eulaTextView.isEditable = false eulaTextView.isScrollEnabled = true eulaContainerView.addSubview(eulaTextView) view.addSubview(okButton) } func okButtonTapped() { okButton.isEnabled = false delegate?.didTapOKButton(self) } }
mit
ceaa0b230a39b83ad842d106dea3a8e4
24.2
86
0.679487
4.178571
false
false
false
false
MaartenBrijker/project
project/External/AudioKit-master/Examples/iOS/AudioKitParticles/AudioKitParticles/ViewController.swift
1
5460
// // ViewController.swift // AudioKitParticles // // Created by Simon Gladman on 28/12/2015. // Copyright © 2015 Simon Gladman. All rights reserved. // import UIKit import AudioKit class ViewController: UIViewController { let statusLabel = UILabel() let floatPi = Float(M_PI) var gravityWellAngle: Float = 0 var particleLab: ParticleLab! var fft: AKFFT! var amplitudeTracker: AKAmplitudeTracker! var amplitude: Float = 0 var lowMaxIndex: Float = 0 var hiMaxIndex: Float = 0 var hiMinIndex: Float = 0 override func viewDidLoad() { super.viewDidLoad() let mic = AKMicrophone() fft = AKFFT(mic) amplitudeTracker = AKAmplitudeTracker(mic) // Turn the volume all the way down on the output of amplitude tracker let noAudioOutput = AKMixer(amplitudeTracker) noAudioOutput.volume = 0 AudioKit.output = noAudioOutput AudioKit.start() let _ = Loop(every: 1 / 60) { let fftData = self.fft.fftData let count = 250 let lowMax = fftData[0 ... (count / 2) - 1].maxElement() ?? 0 let hiMax = fftData[count / 2 ... count - 1].maxElement() ?? 0 let hiMin = fftData[count / 2 ... count - 1].minElement() ?? 0 let lowMaxIndex = fftData.indexOf(lowMax) ?? 0 let hiMaxIndex = fftData.indexOf(hiMax) ?? 0 let hiMinIndex = fftData.indexOf(hiMin) ?? 0 self.amplitude = Float(self.amplitudeTracker.amplitude * 25) self.lowMaxIndex = Float(lowMaxIndex) self.hiMaxIndex = Float(hiMaxIndex - count / 2) self.hiMinIndex = Float(hiMinIndex - count / 2) } // ---- view.backgroundColor = UIColor.whiteColor() let numParticles = ParticleCount.TwoMillion if view.frame.height < view.frame.width { particleLab = ParticleLab(width: UInt(view.frame.width), height: UInt(view.frame.height), numParticles: numParticles) particleLab.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) } else { particleLab = ParticleLab(width: UInt(view.frame.height), height: UInt(view.frame.width), numParticles: numParticles) particleLab.frame = CGRect(x: 0, y: 0, width: view.frame.height, height: view.frame.width) } particleLab.particleLabDelegate = self particleLab.dragFactor = 0.9 particleLab.clearOnStep = false particleLab.respawnOutOfBoundsParticles = true view.addSubview(particleLab) statusLabel.textColor = UIColor.darkGrayColor() statusLabel.text = "AudioKit Particles" view.addSubview(statusLabel) } func particleLabStep() { gravityWellAngle = gravityWellAngle + 0.01 let radiusLow = 0.1 + (lowMaxIndex / 256) particleLab.setGravityWellProperties(gravityWell: .One, normalisedPositionX: 0.5 + radiusLow * sin(gravityWellAngle), normalisedPositionY: 0.5 + radiusLow * cos(gravityWellAngle), mass: (lowMaxIndex * amplitude), spin: -(lowMaxIndex * amplitude)) particleLab.setGravityWellProperties(gravityWell: .Four, normalisedPositionX: 0.5 + radiusLow * sin((gravityWellAngle + floatPi)), normalisedPositionY: 0.5 + radiusLow * cos((gravityWellAngle + floatPi)), mass: (lowMaxIndex * amplitude), spin: -(lowMaxIndex * amplitude)) let radiusHi = 0.1 + (0.25 + (hiMaxIndex / 1024)) particleLab.setGravityWellProperties(gravityWell: .Two, normalisedPositionX: particleLab.getGravityWellNormalisedPosition(gravityWell: .One).x + (radiusHi * sin(gravityWellAngle * 3)), normalisedPositionY: particleLab.getGravityWellNormalisedPosition(gravityWell: .One).y + (radiusHi * cos(gravityWellAngle * 3)), mass: (hiMaxIndex * amplitude), spin: (hiMinIndex * amplitude)) particleLab.setGravityWellProperties(gravityWell: .Three, normalisedPositionX: particleLab.getGravityWellNormalisedPosition(gravityWell: .Four).x + (radiusHi * sin((gravityWellAngle + floatPi) * 3)), normalisedPositionY: particleLab.getGravityWellNormalisedPosition(gravityWell: .Four).y + (radiusHi * cos((gravityWellAngle + floatPi) * 3)), mass: (hiMaxIndex * amplitude), spin: (hiMinIndex * amplitude)) } // MARK: Layout override func viewDidLayoutSubviews() { statusLabel.frame = CGRect(x: 5, y: view.frame.height - statusLabel.intrinsicContentSize().height, width: view.frame.width, height: statusLabel.intrinsicContentSize().height) } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Landscape } override func prefersStatusBarHidden() -> Bool { return true } } extension ViewController: ParticleLabDelegate { func particleLabMetalUnavailable() { // handle metal unavailable here } func particleLabDidUpdate(status: String) { statusLabel.text = status particleLab.resetGravityWells() particleLabStep() } }
apache-2.0
d855a80fb478c535fa5c70dcd19abc39
32.084848
153
0.625206
4.39533
false
false
false
false
hamilyjing/JJSwiftNetwork
Pods/JJSwiftTool/JJSwiftTool/Then/JJThen.swift
1
1548
// // JJThen.swift // PANewToapAPP // // Created by JJ on 16/9/27. // Copyright © 2016年 JJ. All rights reserved. // import Foundation import UIKit import CoreGraphics public protocol JJThen {} extension JJThen where Self: Any { /// Makes it available to set properties with closures just after initializing and copying the value types. /// /// let frame = CGRect().jjWith { /// $0.origin.x = 10 /// $0.size.width = 100 /// } public func jjWith(_ block: (inout Self) -> Void) -> Self { var copy = self block(&copy) return copy } /// Makes it available to execute something with closures. /// /// UserDefaults.standard.jjDo { /// $0.set("devxoul", forKey: "username") /// $0.set("devxoul@gmail.com", forKey: "email") /// $0.synchronize() /// } public func jjDo(_ block: (Self) -> Void) { block(self) } } extension JJThen where Self: AnyObject { /// Makes it available to set properties with closures just after initializing. /// /// let label = UILabel().jjThen { /// $0.textAlignment = .Center /// $0.textColor = UIColor.blackColor() /// $0.text = "Hello, World!" /// } public func jjThen(_ block: (Self) -> Void) -> Self { block(self) return self } } extension NSObject: JJThen {} extension CGPoint: JJThen {} extension CGRect: JJThen {} extension CGSize: JJThen {} extension CGVector: JJThen {}
mit
02c0c3e8e5d337819349ebd744008e89
24.327869
111
0.568932
3.814815
false
false
false
false
gcirone/Mama-non-mama
Mama non mama/SettingsSexVC.swift
1
1423
// // SettingsSexVC.swift // Mama non mama // // Created by freshdev on 23/11/14. // Copyright (c) 2014 Gianluca Cirone. All rights reserved. // import UIKit class SettingsSexVC: UIViewController { @IBOutlet weak var logoHeight: NSLayoutConstraint! @IBOutlet weak var closeSettings: UIButton! override func viewDidLoad() { super.viewDidLoad() //println("SettingsSexVC") //fix autolayout if SettingsApp.IS_IPHONE4 { logoHeight.constant = 140 } //hide close button closeSettings.hidden = !SettingsApp.hasLaunchedSettings } @IBAction func sexSelect(button: AnyObject) { if button.tag == 1 { SettingsApp.CNF["sex"] = "woman" } else if button.tag == 2 { SettingsApp.CNF["sex"] = "man" } self.performSegueWithIdentifier("SettingsUser", sender: self) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } @IBAction func unwindToSettingsSexVC(sender: UIStoryboardSegue) { //println("unwindToSettingsSexVC") } // MARK: - Config override func prefersStatusBarHidden() -> Bool { return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
cc2bbd877f7bcf60a89be5cbc6d1334e
21.234375
81
0.59241
4.711921
false
false
false
false
richardtin/ios-swift-practices
007.PagingCollectionView/007.PagingCollectionView/CenterCellCollectionViewFlowLayout.swift
1
2307
// // CenterCellCollectionViewFlowLayout.swift // 007.PagingCollectionView // // Created by Richard Ting on 4/12/16. // Copyright © 2016 Richard Ting. All rights reserved. // import UIKit class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout { override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { if let cv = self.collectionView { let cvBounds = cv.bounds let halfWidth = cvBounds.size.width * 0.5; let proposedContentOffsetCenterX = proposedContentOffset.x + halfWidth; if let attributesForVisibleCells = self.layoutAttributesForElementsInRect(cvBounds) { var candidateAttributes : UICollectionViewLayoutAttributes? for attributes in attributesForVisibleCells { // == Skip comparison with non-cell items (headers and footers) == // if attributes.representedElementCategory != UICollectionElementCategory.Cell { continue } if let candAttrs = candidateAttributes { let a = attributes.center.x - proposedContentOffsetCenterX let b = candAttrs.center.x - proposedContentOffsetCenterX if fabsf(Float(a)) < fabsf(Float(b)) { candidateAttributes = attributes; } } else { // == First time in the loop == // candidateAttributes = attributes; continue; } } // Beautification step , I don't know why it works! if proposedContentOffset.x == -(cv.contentInset.left) { return proposedContentOffset } print("\(CGPoint(x: floor(candidateAttributes!.center.x - halfWidth), y: proposedContentOffset.y).x) - \(proposedContentOffset.x)"); return CGPoint(x: floor(candidateAttributes!.center.x - halfWidth), y: proposedContentOffset.y) } } // fallback return super.targetContentOffsetForProposedContentOffset(proposedContentOffset) } }
mit
bcfcd501127fdd55c6d8b2dee4cf0a24
37.433333
148
0.593669
6.052493
false
false
false
false
steelwheels/Coconut
CoconutData/Source/File/CNDocumentTypeManager.swift
1
2410
/** * @file CNDocumentTypeManager.swift * @brief Define CNDocumentTypeManager class * @par Copyright * Copyright (C) 2020 Steel Wheels Project */ import Foundation public class CNDocumentTypeManager { public static let shared: CNDocumentTypeManager = CNDocumentTypeManager() private var mDocumentTypes: Dictionary<String, Array<String>> // UTI, extension public init() { mDocumentTypes = [:] if let infodict = Bundle.main.infoDictionary { /* Import document types */ if let imports = infodict["UTImportedTypeDeclarations"] as? Array<AnyObject> { collectTypeDeclarations(typeDeclarations: imports) } } } private func collectTypeDeclarations(typeDeclarations decls: Array<AnyObject>){ for decl in decls { if let dict = decl as? Dictionary<String, AnyObject> { if dict.count > 0 { collectTypeDeclaration(typeDeclaration: dict) } } else { CNLog(logLevel: .error, message: "Invalid declaration: \(decl)", atFunction: #function, inFile: #file) } } } private func collectTypeDeclaration(typeDeclaration decl: Dictionary<String, AnyObject>){ guard let uti = decl["UTTypeIdentifier"] as? String else { CNLog(logLevel: .error, message: "No UTTypeIdentifier", atFunction: #function, inFile: #file) return } guard let tags = decl["UTTypeTagSpecification"] as? Dictionary<String, AnyObject> else { CNLog(logLevel: .error, message: "No UTTypeTagSpecification", atFunction: #function, inFile: #file) return } guard let exts = tags["public.filename-extension"] as? Array<String> else { CNLog(logLevel: .error, message: "No public.filename-extension", atFunction: #function, inFile: #file) return } mDocumentTypes[uti] = exts } public var UTIs: Array<String> { get { return Array(mDocumentTypes.keys) } } public func fileExtensions(forUTIs utis: [String]) -> [String] { var result: [String] = [] for uti in utis { if let exts = mDocumentTypes[uti] { result.append(contentsOf: exts) } else { CNLog(logLevel: .error, message: "Unknown UTI: \(uti)", atFunction: #function, inFile: #file) } } return result } public func UTIs(forExtensions exts: [String]) -> [String] { var result: [String] = [] for ext in exts { for uti in mDocumentTypes.keys { if let val = mDocumentTypes[uti] { if val.contains(ext) { result.append(uti) } } } } return result } }
lgpl-2.1
1a382d98daa04d085115cbd298affff6
27.352941
106
0.691286
3.433048
false
false
false
false
yaobanglin/viossvc
viossvc/AppAPI/SocketAPI/ChatSocketAPI.swift
1
2131
// // ChatSocketAPI.swift // viossvc // // Created by yaowang on 2016/12/3. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import XCGLogger class ChatSocketAPI:BaseSocketAPI, ChatAPI { func sendMsg(chatModel:ChatMsgModel,complete:CompleteBlock,error:ErrorBlock) { XCGLogger.debug("\(chatModel)") var dict = try? OEZJsonModelAdapter.jsonDictionaryFromModel(chatModel) dict?.removeValueForKey("status_"); dict?.removeValueForKey("id_"); //对要发送的聊天信息进行编码 // let utf8str = dict?["content_"]!.dataUsingEncoding(NSUTF8StringEncoding) // let content_base64 = utf8str!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) // dict?["content_"] = content_base64 let pack = SocketDataPacket(opcode: .ChatSendMessage, dict: dict as! [String:AnyObject],type:.Chat) SocketRequestManage.shared.sendChatMsg(pack, complete: complete, error: error) } func offlineMsgList(uid:Int,complete:CompleteBlock,error:ErrorBlock) { let pack = SocketDataPacket(opcode: .ChatOfflineRequestMessage, dict: [SocketConst.Key.uid: uid],type:.Chat) startModelsRequest(pack, listName: "msg_list_", modelClass: ChatMsgModel.classForCoder(), complete: complete, error: error) } func setReceiveMsgBlock(complete:CompleteBlock) { SocketRequestManage.shared.receiveChatMsgBlock = { (response) in let jsonResponse = response as! SocketJsonResponse let model = jsonResponse.responseModel(ChatMsgModel.classForCoder()) as? ChatMsgModel if model != nil { //解码 // model?.content = try! self.decodeBase64Str(model!.content) complete(model) } } } func decodeBase64Str(base64Str:String) throws -> String{ //解码 let data = NSData(base64EncodedString: base64Str, options: NSDataBase64DecodingOptions(rawValue: 0)) let base64Decoded = String(data: data!, encoding: NSUTF8StringEncoding) return base64Decoded! } }
apache-2.0
49358bbd87255972a28e8be3d6f8afe4
40.88
131
0.678128
4.282209
false
false
false
false
iCrany/iOSExample
iOSExample/Module/UIKitExample/VC/LearnTableViewReloadRowVC.swift
1
3156
// // LearnTableViewReloadRowVC.swift // iOSExample // // Created by iCrany on 2018/9/12. // Copyright © 2018年 iCrany. All rights reserved. // import Foundation class LearnTableViewReloadRowModel { var isExpend: Bool = false var testIdentifier: String = "" } //swiftlint:disable force_cast class LearnTableViewReloadRowVC: UIViewController { private lazy var tableView: UITableView = { let v = UITableView(frame: .zero, style: UITableViewStyle.plain) v.delegate = self v.dataSource = self v.register(CanChangeHeightCell.classForCoder(), forCellReuseIdentifier: "CanChangeHeightCell") return v }() private var dataSourceList: [LearnTableViewReloadRowModel] required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { self.dataSourceList = [] super.init(nibName: nil, bundle: nil) for index in 0..<2 { let model = LearnTableViewReloadRowModel() model.isExpend = false model.testIdentifier = "xxxx - \(index)" dataSourceList.append(model) } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.view.addSubview(self.tableView) self.tableView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } } } extension LearnTableViewReloadRowVC: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSourceList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: CanChangeHeightCell = tableView.dequeueReusableCell(withIdentifier: "CanChangeHeightCell", for: indexPath) as! CanChangeHeightCell let model: LearnTableViewReloadRowModel = self.dataSourceList[indexPath.row] cell.delegate = self cell.isExpend = model.isExpend return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let model: LearnTableViewReloadRowModel = self.dataSourceList[indexPath.row] return model.isExpend == true ? CanChangeHeightCell.Constant.kExpendedHeight : CanChangeHeightCell.Constant.kNotExpendedHeight } } extension LearnTableViewReloadRowVC: CanChangeHeightCellDelegate { func expendBtnAction(cell: CanChangeHeightCell) { let index: IndexPath? = self.tableView.indexPath(for: cell) if let cellIndex = index { let model = self.dataSourceList[cellIndex.row] model.isExpend = !model.isExpend self.tableView.reloadRows(at: [cellIndex], with: .none) } } func expendBtnReloadDataAction(cell: CanChangeHeightCell) { let index: IndexPath? = self.tableView.indexPath(for: cell) if let cellIndex = index { let model = self.dataSourceList[cellIndex.row] model.isExpend = !model.isExpend self.tableView.reloadData() } } }
mit
a504ea74a42209507846a7d827a65f35
32.542553
148
0.678084
4.504286
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/General/Views/BaseTableView.swift
1
1930
// // BaseTableView.swift // HiPDA // // Created by leizh007 on 2016/11/16. // Copyright © 2016年 HiPDA. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources import MJRefresh /// BaseTableView的Rx扩展 extension Reactive where Base: BaseTableView { /// 状态 var status: UIBindingObserver<Base, DataLoadStatus> { return UIBindingObserver(UIElement: base) { (tableView, status) in tableView.status = status } } /// 是否正在编辑 var isEditing: UIBindingObserver<Base, Bool> { return UIBindingObserver(UIElement: base) { (tableView, isEditing) in tableView.isEditing = isEditing } } } class BaseTableView: UITableView, DataLoadable { var refreshHeader: MJRefreshNormalHeader? { get { return mj_header as? MJRefreshNormalHeader } set { mj_header = newValue } } var loadMoreFooter: MJRefreshBackNormalFooter? { get { return mj_footer as? MJRefreshBackNormalFooter } set { mj_footer = newValue } } var hasRefreshHeader = false { didSet { didSetHasRefreshHeader() } } var hasLoadMoreFooter = false { didSet { didSetHasLoadMoreFooter() } } weak var dataLoadDelegate: DataLoadDelegate? var status = DataLoadStatus.loading { didSet { didSetStatus() } } lazy var noResultView: NoResultView = { NoResultView.xibInstance }() override func layoutSubviews() { super.layoutSubviews() if noResultView.superview != nil { noResultView.frame = bounds noResultView.tapToLoadDelegate = self bringSubview(toFront: noResultView) } } }
mit
0b71fed9069718739dfd755ac399c22d
21.411765
77
0.581102
4.935233
false
false
false
false
wokalski/Diff.swift
Graph.playground/Sources/CharacterLabels.swift
5
1266
// // CharacterLabels.swift // Graph // // Created by Wojciech Czekalski on 25.03.2016. // Copyright © 2016 wczekalski. All rights reserved. // import UIKit public extension String { func length() -> Int { return lengthOfBytes(using: String.Encoding.utf8) } func characterLabels(withFrames frames: [CGRect]) -> [UILabel] { let characters = self.characters guard characters.count == frames.count else { return [] } let labels = characters.map { $0.label() } let sizes = labels.map { $0.frame.size } let frames = inset(rects: frames, to: sizes) zip(labels, frames).forEach { label, frame in label.frame = frame } return labels } } extension Character { func label() -> UILabel { let l = UILabel() l.textColor = .white l.text = String(self) l.sizeToFit() return l } } func inset(rects: [CGRect], to: [CGSize]) -> [CGRect] { return zip(to, rects).map { size, rect -> CGRect in return rect.inset(to: size) } } extension CGRect { func inset(to size: CGSize) -> CGRect { return self.insetBy(dx: (self.width - size.width) / 2, dy: (self.height - size.height) / 2).standardized } }
mit
2365105e0655389a7d0ae083356021d4
23.803922
112
0.592095
3.677326
false
false
false
false
edx/edx-app-ios
Source/SpinnerButton.swift
1
2073
// // SpinnerButton.swift // edX // // Created by Ehmad Zubair Chughtai on 16/09/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class SpinnerButton: UIButton { private let SpinnerViewTrailingMargin : CGFloat = 10 private let VerticalContentMargin : CGFloat = 5 private let SpinnerHorizontalMargin : CGFloat = 10 private var SpinnerViewWidthWithMargins : CGFloat { return spinnerView.intrinsicContentSize.width + 2 * SpinnerHorizontalMargin } private let spinnerView = SpinnerView(color: .white) override func layoutSubviews() { super.layoutSubviews() layoutSpinnerView() } private func layoutSpinnerView() { self.addSubview(spinnerView) self.titleLabel?.adjustsFontSizeToFitWidth = true spinnerView.snp.remakeConstraints { make in make.centerY.equalTo(self) make.width.equalTo(spinnerView.intrinsicContentSize.width) if let label = titleLabel { make.leading.equalTo(label.snp.trailing).offset(SpinnerHorizontalMargin).priority(.low) } make.trailing.equalTo(self.snp.trailing).offset(-2 * SpinnerHorizontalMargin).priority(.high) } self.setNeedsUpdateConstraints() if !showProgress { spinnerView.isHidden = true } } override var intrinsicContentSize: CGSize { let width = self.titleLabel?.intrinsicContentSize.width ?? 0 + SpinnerViewTrailingMargin + self.spinnerView.intrinsicContentSize.width let height = max(super.intrinsicContentSize.height, spinnerView.intrinsicContentSize.height + 2 * VerticalContentMargin) return CGSize(width: width, height: height) } var showProgress : Bool = false { didSet { if showProgress { spinnerView.isHidden = false spinnerView.startAnimating() } else { spinnerView.isHidden = true spinnerView.stopAnimating() } } } }
apache-2.0
8234678996ebdb80a33ae1dac1217c2f
32.983607
142
0.647371
5.248101
false
false
false
false
NSCodeMonkey/PassLock
PassLock/Configuration.swift
1
1832
// // Config.swift // PassLockDemo // // Created by edison on 9/20/16. // Copyright © 2016 NSCodeMonkey. All rights reserved. // import Foundation public typealias Password = String public enum PassLockType { case setPassword case changePassword case removePassword case unlock } extension PassLockType { var title: String? { switch self { case .setPassword: return "设置密码" case .removePassword: return "关闭密码" case .changePassword: return "更改密码" default: return nil } } var passwordInputTitle: String { switch self { case .setPassword, .removePassword, .unlock: return "请输入密码" case .changePassword: return "请输入旧密码" } } } public struct PasswordViewConfiguration { let digit: Int let spacing: CGFloat let strokeHeight: CGFloat let strokeColor: UIColor init(digit: Int = 4, spacing: CGFloat = 20, strokeHeight: CGFloat = 2, strokeColor: UIColor = UIColor.black) { self.digit = digit self.spacing = spacing self.strokeHeight = strokeHeight self.strokeColor = strokeColor } } public struct PassLockConfiguration { let passwordConfig: PasswordViewConfiguration let keychainConfig: KeychainConfiguration let retryCount: Int let usingTouchID: Bool let passLockType: PassLockType public init(passwordConfig: PasswordViewConfiguration = PasswordViewConfiguration(), keychainConfig: KeychainConfiguration = KeychainConfiguration(), retryCount: Int = 5, usingTouchID: Bool = false, passLockType: PassLockType = .setPassword) { self.passwordConfig = passwordConfig self.keychainConfig = keychainConfig self.retryCount = retryCount self.usingTouchID = usingTouchID self.passLockType = passLockType } }
mit
0ff0919c5db412f35a5d19e56cfb9a34
23.452055
112
0.707003
4.311594
false
true
false
false
Spriter/SwiftyHue
Sources/Base/BridgeResourceModels/Sensors/SwitchSensor/SwitchSensorState.swift
1
1456
// // SwitchSensorState.swift // Pods // // Created by Jerome Schmitz on 01.05.16. // // import Foundation import Gloss public class SwitchSensorState: PartialSensorState { public let buttonEvent: ButtonEvent? init?(state: SensorState) { // guard let buttonEvent: ButtonEvent = state.buttonEvent else { // Log.error("Can't create SwitchSensorState, missing required attribute \"buttonevent\""); return nil // } self.buttonEvent = state.buttonEvent super.init(lastUpdated: state.lastUpdated) } required public init?(json: JSON) { // guard let buttonEvent: ButtonEvent = "buttonevent" <~~ json else { // Log.error("Can't create SwitchSensorState, missing required attribute \"buttonevent\" in JSON:\n \(json)"); return nil // } self.buttonEvent = "buttonevent" <~~ json super.init(json: json) } public override func toJSON() -> JSON? { if var superJson = super.toJSON() { let json = jsonify([ "buttonevent" ~~> self.buttonEvent ]) superJson.unionInPlace(json!) return superJson } return nil } } public func ==(lhs: SwitchSensorState, rhs: SwitchSensorState) -> Bool { return lhs.lastUpdated == rhs.lastUpdated && lhs.buttonEvent == rhs.buttonEvent }
mit
4cea6b20c1750bb2f1aff151519c1169
25.017857
132
0.581044
4.521739
false
false
false
false
RCOS-QuickCast/quickcast_ios
new QuickCast/PopularViewController.swift
1
2407
// // PopularViewController.swift // new QuickCast // // Created by Ethan Geng on 21/10/2016. // Copyright © 2016 Ethan. All rights reserved. // import UIKit class PopularViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var menuButton: UIBarButtonItem! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return Match.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MatchTableViewCell cell.TeamImageView1.image = UIImage(named: "Dota2") cell.TeamImageView2.image = UIImage(named: "Dota2") // Configure the cell... cell.TeamName1.text = TeamNames1[indexPath.row] cell.TeamName2.text = TeamNames2[indexPath.row] return cell } var Match = ["match 1", "match 2", "match 3", "match 4", "match 5", "match 6", "match 7", "match 8", "match 9", "match 10"] var TeamNames1 = ["Team 1", "Team 3", "Team 5", "Team 7", "Team 9", "Team 11", "Team 13", "Team 15", "Team 17", "Team 19"] var TeamNames2 = ["Team 2", "Team 4", "Team 6", "Team 8", "Team 10", "Team 12", "Team 14", "Team 16", "Team 18", "Team 20"] override func viewDidLoad() { super.viewDidLoad() if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
ce5a3d5fe1340b43b9390fd6c7f1898a
37.806452
127
0.650042
4.556818
false
false
false
false
na4lapy/Na4LapyAPI
Sources/Na4LapyCore/FilesController.swift
1
6225
// // FilesController.swift // Na4lapyAPI // // Created by scoot on 02.01.2017. // // import Kitura import LoggerAPI import Foundation import SwiftyJSON public class FilesController { public let router = Router() let path: String let backend: Model public init(path: String, backend: Model) { self.path = path self.backend = backend setup() } // // MARK: konfiguracja routerów // private func setup() { router.get("/:id", handler: onGetbyId) router.post("/upload/:filename", handler: onUpload) router.delete("/:id", handler: onDelete) router.delete("/removeall/:animal", handler: onRemoveAll) router.patch("/:id", handler: onPatch) } // // MARK: obsługa requestów // private func onPatch(request: RouterRequest, response: RouterResponse, next: () -> Void) { guard let id = request.parameters["id"], let idint = Int(id) else { Log.error("Brak parametru 'id' w zapytaniu.") try? response.status(.badRequest).end() return } let newProfilFlag: Bool = request.queryParameters["profil"] == "true" ? true : false do { _ = try checkSession(request: request, response: response) // // TODO: sprawdzić, czy shelter_id zwierzaka do którego nalezy zdjęcie pasuje do sesji // let id = try backend.edit(withDictionary: [PhotoJSON.id : idint, PhotoJSON.profil : newProfilFlag]) try? response.status(.OK).send(json: JSON(["id" : id])).end() } catch (let error) { Log.error(error.localizedDescription) try? response.status(.notFound).end() } } private func onRemoveAll(request: RouterRequest, response: RouterResponse, next: () -> Void) { guard let animal = request.parameters["animal"], let animalid = Int(animal) else { Log.error("Brak parametru 'id' w zapytaniu.") try? response.status(.badRequest).end() return } do { _ = try checkSession(request: request, response: response) // // TODO: sprawdzić, czy shelter_id zwierzaka pasuje do sesji // let filename = try backend.deleteAll(byId: animalid) for item in filename { try FileManager().removeItem(atPath: path + item) } try? response.status(.OK).end() } catch (let error) { Log.error(error.localizedDescription) try? response.status(.notFound).end() } } private func onDelete(request: RouterRequest, response: RouterResponse, next: () -> Void) { guard let id = request.parameters["id"], let idint = Int(id) else { Log.error("Brak parametru 'id' w zapytaniu.") try? response.status(.badRequest).end() return } do { _ = try checkSession(request: request, response: response) // // TODO: sprawdzić, czy shelter_id zwierzaka pasuje do sesji // let filename = try backend.delete(byId: idint) try FileManager().removeItem(atPath: path + filename) try? response.status(.OK).end() } catch (let error) { Log.error(error.localizedDescription) try? response.status(.notFound).end() } } private func onUpload(request: RouterRequest, response: RouterResponse, next: () -> Void) { var content = Data() guard let animalId = request.queryParameters["animalId"], let animalIntId = Int(animalId) else { Log.error("Błąd podczas uploadu pliku") response.status(.notFound) try? response.end() return } let profilFlag = request.queryParameters["profil"] ?? "" let filename = UUID().uuidString + ".jpg" do { _ = try checkSession(request: request, response: response) // // TODO: sprawdzić, czy shelter_id zwierzaka pasuje do sesji // _ = try request.read(into: &content) let url = URL(fileURLWithPath: path + filename) try content.write(to: url) let dictionary: JSONDictionary = [PhotoJSON.animalid : animalIntId, PhotoJSON.filename : filename, PhotoJSON.profil : profilFlag] let id = try backend.add(withDictionary: dictionary) try response.status(.OK).send(json: JSON(["id" : id])).end() } catch (let error) { Log.error(error.localizedDescription) try? response.status(.notFound).end() } } /** Pobranie obiektu na podstawie identyfikatora */ private func onGetbyId(request: RouterRequest, response: RouterResponse, next: () -> Void) { guard let id = request.parameters["id"] else { Log.error("Brak parametru 'id' w zapytaniu.") try? response.status(.badRequest).end() return } // TODO: zadbać aby nazwa pliku nie zawierała ścieżki. do { // Brak sesji - włączenie cache. if request.session?[SecUserDBKey.shelterid].string == nil { response.headers.append(ResponseHeader.cacheControl, value: ResponseHeader.cacheControlValue) } try response.status(.OK).send(fileName: path + id).end() } catch { Log.error("Błąd podczas pobierania pliku: \(path + id)") try? response.status(.notFound).end() } } private func checkSession(request: RouterRequest, response: RouterResponse) throws -> Int { guard let sess = request.session, let shelterid = sess[SecUserDBKey.shelterid].string, let sessShelterid = Int(shelterid) else { Log.error("Wymagane uwierzytelnienie.") response.status(.forbidden) try? response.end() throw ResultCode.AuthorizationError } return sessShelterid } }
apache-2.0
effc0fc01dfaf38046d8a2fe2112e8a6
34.261364
141
0.567676
4.151171
false
false
false
false
srxboys/RXSwiftExtention
Pods/SwifterSwift/Source/Extensions/UIKit/UINavigationControllerExtensions.swift
1
1738
// // UINavigationControllerExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/6/16. // Copyright © 2016 Omar Albeik. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit // MARK: - Methods public extension UINavigationController { /// SwifterSwift: Pop ViewController with completion handler. /// /// - Parameter completion: optional completion handler (default is nil). public func popViewController(completion: (()->Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) popViewController(animated: true) CATransaction.commit() } /// SwifterSwift: Push ViewController with completion handler. /// /// - Parameters: /// - viewController: viewController to push. /// - Parameter completion: optional completion handler (default is nil). public func pushViewController(viewController: UIViewController, completion: (()->Void)? = nil) { // https://github.com/cotkjaer/UserInterface/blob/master/UserInterface/UIViewController.swift CATransaction.begin() CATransaction.setCompletionBlock(completion) pushViewController(viewController, animated: true) CATransaction.commit() } /// SwifterSwift: Make navigation controller's navigation bar transparent. /// /// - Parameter withTint: tint color (default is .white). public func makeTransparent(withTint: UIColor = .white) { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true navigationBar.tintColor = withTint navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: withTint] } } #endif
mit
34e51d135da3da77e40dec7920b71718
32.403846
99
0.753598
4.257353
false
false
false
false
MKGitHub/UIPheonix
Demo/Shared/Views/Collection View/SimpleCounterModelCVCell.swift
1
2347
/** UIPheonix Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved. https://github.com/MKGitHub/UIPheonix http://www.xybernic.com Copyright 2016/2017/2018/2019 Mohsan Khan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #if os(iOS) || os(tvOS) import UIKit #elseif os(macOS) import Cocoa #endif final class SimpleCounterModelCVCell:UIPBaseCollectionViewCell { // MARK: Private IB Outlet @IBOutlet private weak var ibPlusButton:UIPPlatformButton! @IBOutlet private weak var ibMinusButton:UIPPlatformButton! // MARK: Private Members private var mCounterValue:Double = 0 private var mNotificationId:String? // MARK:- UIPBaseCollectionViewCell/UIPBaseCollectionViewCellProtocol override func update(withModel model:Any, delegate:Any, collectionView:UIPPlatformCollectionView, indexPath:IndexPath) -> UIPCellSize { // apply model to view let simpleCounterModel:SimpleCounterModel = model as! SimpleCounterModel // store for later mCounterValue = Double(simpleCounterModel.pValue) mNotificationId = simpleCounterModel.pNotificationId // return view size return UIPCellSize(replaceWidth:true, width:collectionView.bounds.size.width, replaceHeight:false, height:0) } // MARK:- IBAction @IBAction func valueChanged(_ sender:UIPPlatformButton) { // we use the buttons tag for the value change mCounterValue += Double(sender.tag) // send value changed notification if (mNotificationId != nil) { NotificationCenter.default.post(name:NSNotification.Name(mNotificationId!), object:nil, userInfo:[NotificationKey.counterValue:mCounterValue]) } } }
apache-2.0
322ae5e601e083645f5ef103f48d4ca8
30.28
137
0.696078
4.807377
false
false
false
false
lukevanin/onthemap
OnTheMap/TabViewController.swift
1
3679
// // TabViewController.swift // OnTheMap // // Created by Luke Van In on 2017/01/12. // Copyright © 2017 Luke Van In. All rights reserved. // // Displays the content of the app, namely the login screen, location editor popup, and map and list tabs. Forwards // state from the app controller to the child controllers, and actions from the child controllers back to the app // controller. // import UIKit import SafariServices import FBSDKLoginKit class TabViewController: UITabBarController { // MARK: Properties fileprivate let loginSegue = "login" fileprivate let locationSegue = "location" private lazy var appController: StudentsAppController = { let instance = StudentsAppController() instance.delegate = self return instance }() // MARK: View controller life cycle override func viewDidLoad() { super.viewDidLoad() tabBar.tintColor = .white tabBar.unselectedItemTintColor = UIColor(hue: 30.0 / 360.0, saturation: 0.8, brightness: 0.8, alpha: 1.0) setupTabViewControllers() appController.loadStudents() } // MARK: Setup // // Initial configuration for child view controllers which represent the tabs to be displayed (map and list view // controllers). // private func setupTabViewControllers() { guard let viewControllers = self.viewControllers else { return } for viewController in viewControllers { setupTabViewController(viewController) } } // // Configure a controller for the a tab. Sets the initial state from the app controller, and the delegate so that // the child controller communicates with the app controller. // // Note: The content controllers themselves are each embedded in a navigation controller in order to obtain a nav // bar. This function uses recursion to descend the view controller hierarchy to access the content controller. // private func setupTabViewController(_ viewController: UIViewController) { switch viewController { // Setup app controller as delegate for map view. case let controller as MapViewController: controller.delegate = appController // Setup app controller as delegate for list view. case let controller as ListViewController: controller.delegate = appController // Navigation controller - recurse to configure top-most view controller. case let navigationController as UINavigationController: if let viewController = navigationController.topViewController { setupTabViewController(viewController) } // Unknown view controller. default: break } } // MARK: Storyboard // // Callback action for unwind segues. Provides a way define how a presented view controller may to return to this // view controller using interface builder. // @IBAction func unwindToPresenter(_ sender: UIStoryboardSegue) { appController.loadStudents() } } // // Extension which implements delegate methods for the app controller. This provides a way for the app controller to // interact with the display state, without creating implementation dependencies. // extension TabViewController: StudentsAppDelegate { func showLoginScreen() { performSegue(withIdentifier: loginSegue, sender: nil) } func showLocationEditScreen() { performSegue(withIdentifier: locationSegue, sender: nil) } }
mit
0b3aca53dcb5857e05a214ae3b9dea18
32.743119
119
0.669657
5.416789
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/CircleCodeButton.swift
1
1668
// // CircleCodeButton.swift // Wuakup // // Created by Guillermo Gutiérrez on 05/01/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import Foundation import UIKit @IBDesignable class CircleCodeButton: UIControl { @IBOutlet var textLabel: UILabel? @IBOutlet var iconView: CodeIconView? override var isEnabled: Bool { didSet { updateUI() } } fileprivate var touchingInside: Bool = false { didSet { updateUI() } } override var isHighlighted: Bool { didSet { updateUI() } } fileprivate var originalBackgroundColor: UIColor? override func awakeFromNib() { super.awakeFromNib() originalBackgroundColor = backgroundColor } func updateUI() { let isHighlighted = self.isHighlighted || isSelected || touchingInside textLabel?.isHighlighted = isHighlighted iconView?.isHighlighted = isHighlighted backgroundColor = isHighlighted ? borderColor : originalBackgroundColor } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) touchingInside = true } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) delay(0.1) { self.touchingInside = false } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) delay(0.1) { self.touchingInside = false } sendActions(for: .touchUpInside) } }
mit
7a2e318774570604f83ae23c1e0aa5fe
27.741379
83
0.643071
5.082317
false
false
false
false
frootloops/swift
test/SILGen/objc_protocols.swift
1
13439
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s // REQUIRES: objc_interop import gizmo import objc_protocols_Bas @objc protocol NSRuncing { func runce() -> NSObject func copyRuncing() -> NSObject func foo() static func mince() -> NSObject } @objc protocol NSFunging { func funge() func foo() } protocol Ansible { func anse() } // CHECK-LABEL: sil hidden @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[THIS:%.*]] : @owned $T): // -- Result of runce is autoreleased according to default objc conv // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_THIS]] : {{\$.*}}, #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[BORROWED_THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject // CHECK: end_borrow [[BORROWED_THIS]] from [[THIS]] // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[METHOD:%.*]] = objc_method [[BORROWED_THIS]] : {{\$.*}}, #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[BORROWED_THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject // CHECK: end_borrow [[BORROWED_THIS]] from [[THIS]] // -- Arguments are not consumed by objc calls // CHECK: destroy_value [[THIS]] func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) } // CHECK-LABEL: sil hidden @_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () { func objc_generic_partial_apply<T : NSRuncing>(_ x: T) { // CHECK: bb0([[ARG:%.*]] : @owned $T): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[FN:%.*]] = function_ref @[[THUNK1:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO]] : // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[ARG_COPY]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[METHOD]] _ = x.runce // CHECK: [[FN:%.*]] = function_ref @[[THUNK1]] : // CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T>() // CHECK: destroy_value [[METHOD]] _ = T.runce // CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type // CHECK: [[FN:%.*]] = function_ref @[[THUNK2:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTcTO]] // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]]) // CHECK: destroy_value [[METHOD:%.*]] _ = T.mince // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF' // CHECK: sil shared [serializable] [thunk] @[[THUNK1]] : // CHECK: bb0([[SELF:%.*]] : @owned $Self): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1_THUNK:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTO]] : // CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<Self>([[SELF]]) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK1]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK1_THUNK]] // CHECK: bb0([[SELF:%.*]] : @guaranteed $Self): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[FN:%.*]] = objc_method [[SELF_COPY]] : $Self, #NSRuncing.runce!1.foreign // CHECK: [[RESULT:%.*]] = apply [[FN]]<Self>([[SELF_COPY]]) // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '[[THUNK1_THUNK]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK2]] : // CHECK: [[FN:%.*]] = function_ref @[[THUNK2_THUNK:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTO]] // CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]<Self>(%0) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK2]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK2_THUNK]] : // CHECK: [[FN:%.*]] = objc_method %0 : $@thick Self.Type, #NSRuncing.mince!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0) // CHECK-NEXT: return [[RESULT]] // CHECK: } // end sil function '[[THUNK2_THUNK]]' // CHECK-LABEL: sil hidden @_T014objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[THIS:%.*]] : @owned $NSRuncing): // -- Result of runce is autoreleased according to default objc conv // CHECK: [[BORROWED_THIS_1:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS1:%.*]] = open_existential_ref [[BORROWED_THIS_1]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS1]] : $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]]) // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[BORROWED_THIS_2:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS2:%.*]] = open_existential_ref [[BORROWED_THIS_2]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS2]] : $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]]) // -- Arguments are not consumed by objc calls // CHECK: end_borrow [[BORROWED_THIS_2]] from [[THIS]] // CHECK: end_borrow [[BORROWED_THIS_1]] from [[THIS]] // CHECK: destroy_value [[THIS]] func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) } // CHECK-LABEL: sil hidden @_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF : $@convention(thin) (@owned NSRuncing) -> () { func objc_protocol_partial_apply(_ x: NSRuncing) { // CHECK: bb0([[ARG:%.*]] : @owned $NSRuncing): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPENED_ARG:%.*]] = open_existential_ref [[BORROWED_ARG]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]] // CHECK: [[FN:%.*]] = function_ref @_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO // CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[OPENED_ARG_COPY]]) // CHECK: destroy_value [[RESULT]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] _ = x.runce // FIXME: rdar://21289579 // _ = NSRuncing.runce } // CHECK : } // end sil function '_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF' // CHECK-LABEL: sil hidden @_T014objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F func objc_protocol_composition(_ x: NSRuncing & NSFunging) { // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.runce() // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = objc_method [[THIS]] : $[[OPENED]], #NSFunging.funge!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.funge() } // -- ObjC thunks get emitted for ObjC protocol conformances class Foo : NSRuncing, NSFunging, Ansible { // -- NSRuncing @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc static func mince() -> NSObject { return NSObject() } // -- NSFunging @objc func funge() {} // -- Both NSRuncing and NSFunging @objc func foo() {} // -- Ansible func anse() {} } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5runce{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5funge{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC3foo{{[_0-9a-zA-Z]*}}FTo // CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}} class Bar { } extension Bar : NSRuncing { @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC5runce{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC3foo{{[_0-9a-zA-Z]*}}FTo // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // runce() implementation from the original definition of Bas @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo // -- Inherited objc protocols protocol Fungible : NSFunging { } class Zim : Fungible { @objc func funge() {} @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC5funge{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC3foo{{[_0-9a-zA-Z]*}}FTo // class Zang from objc_protocols_Bas module extension Zang : Fungible { // funge() implementation from the original definition of Zim @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas4ZangC0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo // -- objc protocols with property requirements in extensions // <rdar://problem/16284574> @objc protocol NSCounting { var count: Int {get} } class StoredPropertyCount { @objc let count = 0 } extension StoredPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_T014objc_protocols19StoredPropertyCountC5countSivgTo class ComputedPropertyCount { @objc var count: Int { return 0 } } extension ComputedPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols21ComputedPropertyCountC5countSivgTo // -- adding @objc protocol conformances to native ObjC classes should not // emit thunks since the methods are already available to ObjC. // Gizmo declared in Inputs/usr/include/Gizmo.h extension Gizmo : NSFunging { } // CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}} @objc class InformallyFunging { @objc func funge() {} @objc func foo() {} } extension InformallyFunging: NSFunging { } @objc protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden @_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable { func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable { // CHECK: bb0([[META:%[0-9]+]] : @trivial $@thick Initializable.Type, [[I:%[0-9]+]] : @trivial $Int): // CHECK: [[I2_BOX:%[0-9]+]] = alloc_box ${ var Initializable } // CHECK: [[PB:%.*]] = project_box [[I2_BOX]] // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type // CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = objc_method [[I2_ALLOC]] : $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign : {{.*}} // CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_ALLOC]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable // CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*Initializable // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Initializable // CHECK: [[I2:%[0-9]+]] = load [copy] [[READ]] : $*Initializable // CHECK: destroy_value [[I2_BOX]] : ${ var Initializable } // CHECK: return [[I2]] : $Initializable var i2 = im.init(int: i) return i2 } // CHECK: } // end sil function '_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF' class InitializableConformer: Initializable { @objc required init(int: Int) {} } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols22InitializableConformerC{{[_0-9a-zA-Z]*}}fcTo final class InitializableConformerByExtension { init() {} } extension InitializableConformerByExtension: Initializable { @objc convenience init(int: Int) { self.init() } } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols33InitializableConformerByExtensionC{{[_0-9a-zA-Z]*}}fcTo // Make sure we're crashing from trying to use materializeForSet here. @objc protocol SelectionItem { var time: Double { get set } } func incrementTime(contents: SelectionItem) { contents.time += 1.0 }
apache-2.0
3364960f9255108415996afa8158c6f8
43.029508
204
0.644203
3.400608
false
false
false
false
macostea/appcluj-expenses-ios
SwiftyJSON-master/Example/ViewController.swift
6
3865
// SwiftyJSON.h // // Copyright (c) 2014 Pinglin Tang // // 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 import SwiftyJSON class ViewController: UITableViewController { var json: JSON = JSON.nullJSON // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch self.json.type { case Type.Array, Type.Dictionary: return self.json.count default: return 1 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("JSONCell", forIndexPath: indexPath) as UITableViewCell var row = indexPath.row switch self.json.type { case .Array: cell.textLabel.text = "\(row)" cell.detailTextLabel?.text = self.json.arrayValue.description case .Dictionary: let key: AnyObject = (self.json.object as NSDictionary).allKeys[row] let value = self.json[key as String] cell.textLabel.text = "\(key)" cell.detailTextLabel?.text = value.description default: cell.textLabel.text = "" cell.detailTextLabel?.text = self.json.description } return cell } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { var object: AnyObject switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) { case .OrderedSame, .OrderedDescending: object = segue.destinationViewController.topViewController case .OrderedAscending: object = segue.destinationViewController } if let nextController = object as? ViewController { if let indexPath = self.tableView.indexPathForSelectedRow() { var row = indexPath.row var nextJson: JSON = JSON.nullJSON switch self.json.type { case .Array: nextJson = self.json[row] case .Dictionary where row < self.json.dictionaryValue.count: let key = self.json.dictionaryValue.keys.array[row] if let value = self.json.dictionary?[key] { nextJson = value } default: print("") } nextController.json = nextJson print(nextJson) } } } }
mit
1362584e36fc3ad1913478f82ae3b614
37.267327
119
0.629237
5.153333
false
false
false
false
chenchangqing/learniosRAC
FRP-Swift/FRP-Swift/ViewModels/ImageViewModel.swift
1
3192
// // ImageViewModel.swift // travelMapMvvm // // Created by green on 15/8/31. // Copyright (c) 2015年 travelMapMvvm. All rights reserved. // import ReactiveCocoa import ReactiveViewModel class ImageViewModel: RVMViewModel { var urlString : String? // 图片路径 { didSet { let result = isValidPic() self.setValue(result.url, forKey: "url") self.setValue(result.request, forKey: "request") } } var url : NSURL? var request: NSURLRequest? // 被观察的图片,一旦变更及时更新视图 dynamic var image:UIImage = UIImage() var isNeedCompress = true private var imageDataSourceProtocol = ImageDataSource.shareInstance() var downloadImageCommand : RACCommand! /** * 初始化 */ init(urlString:String?,model:AnyObject? = nil,defaultImage:UIImage = UIImage(),isNeedCompress:Bool = true) { super.init(model: model) self.urlString = urlString self.image = defaultImage self.isNeedCompress = isNeedCompress // 初始化下载命令 setupCommand() } // MARK: - COMMAND private func setupCommand() { // 是否可以执行下载图片的命令 let commandEnabledSignal = RACObserve(self, "url").map { (any:AnyObject!) -> AnyObject! in if any != nil { return true } else { return false } }.distinctUntilChanged() // 初始化下载图片命令 downloadImageCommand = RACCommand(enabled: commandEnabledSignal, signalBlock: { (any:AnyObject!) -> RACSignal! in if self.isCached() { return RACSignal.empty() } return self.imageDataSourceProtocol.downloadImageWithUrl(self.url!, isNeedCompress: self.isNeedCompress) }) // 获得图片 downloadImageCommand.executionSignals.switchToLatest().subscribeNextAs { (image:UIImage) -> () in self.setValue(image, forKey: "image") } // 下载图片错误处理 downloadImageCommand.errors.subscribeNextAs { (error:NSError!) -> () in println(error.localizedDescription) } } /** * 图片是否有效 */ private func isValidPic() -> (url:NSURL?,request:NSURLRequest?) { if let picUrl=urlString { if let url=NSURL(string: picUrl) { return (url,NSURLRequest(URL: url)) } } return (nil,nil) } // MARK: - load image /** * 是否已经缓存 */ private func isCached() -> Bool { if let request=request { if let image=UIImageView.sharedImageCache().cachedImageForRequest(request) { self.setValue(image, forKey: "image") return true } } return false } }
gpl-2.0
1cba9d52946b113663613d16f19922b2
24.512605
121
0.523715
4.993421
false
false
false
false
resmio/TastyTomato
TastyTomato/Code/Types/ViewControllerClasses/PopoverVC/PopoverVC.swift
1
12425
// // PopoverVC.swift // TastyTomato // // Created by Jan Nash (resmio) on 09.08.18. // Copyright © 2018 resmio. All rights reserved. // import UIKit // MARK: // Public // MARK: - PopoverPresentationDelegate @objc public protocol PopoverPresentationDelegate: AnyObject { @objc optional func prepareToPresent(_ popover: PopoverVC) @objc optional func shouldDismiss(_ popover: PopoverVC) -> Bool @objc optional func didDismiss(_ popover: PopoverVC) } // MARK: - PopoverContainerView class PopoverContainerView: UIView {} // MARK: - PopoverVC // MARK: ObjC Extrawurst extension PopoverVC { @objc public func setSourceRect(_ sourceRect: CGRect) { self.sourceRect = sourceRect } @objc public func unsetSourceRect() { self.sourceRect = nil } } // MARK: Interface extension PopoverVC { // ReadWrite public var presentationDelegate: PopoverPresentationDelegate? { get { return self._presentationDelegate } set { self._presentationDelegate = newValue } } @objc public var sourceView: UIView? { get { return self._sourceView } set { self._sourceView = newValue } } public var sourceRect: CGRect? { get { return self._sourceRect } set { self._sourceRect = newValue } } @objc public var barButtonItem: UIBarButtonItem? { get { return self._barButtonItem } set { self._barButtonItem = newValue } } @objc public var permittedArrowDirections: UIPopoverArrowDirection { get { return self._permittedArrowDirections } set { self._permittedArrowDirections = newValue } } public var inset: CGFloat { get { return self._inset } set { self._inset = newValue } } public var cornerRadius: CGFloat { get { return self._cornerRadius } set { self._cornerRadius = newValue } } public var contentView: UIView? { get { return self._contentView } set { self._contentView = newValue } } public var backgroundColor: UIColor? { get { return self._backgroundColor } set { self._backgroundColor = newValue } } public var dimsBackground: Bool { get { return self._dimsBackground } set { self._dimsBackground = newValue } } public var displaysBorderShadow: Bool { get { return self._displaysBorderShadow } set { self._displaysBorderShadow = newValue } } public var passthroughViews: [UIView] { get { return self._passthroughViews } set { self._passthroughViews = newValue } } // Functions public func updateContentSize() { self._updateContentSize() } @objc public func dismiss(animated: Bool = true, honorShouldDismiss: Bool = false, callDidDismiss: Bool = false, completion: (() -> Void)? = nil) { self._dismiss(animated: animated, honorShouldDismiss: honorShouldDismiss, callDidDismiss: callDidDismiss, completion: completion) } @objc public func present(from viewController: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) { self._present(from: viewController, animated: animated, completion: completion) } } // MARK: Class Declaration open class PopoverVC: UIViewController { // Required Init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self._init() } // Init public init() { super.init(nibName: nil, bundle: nil) self._init() } // Common Init private func _init() { self.modalPresentationStyle = .popover } // Private Weak Variables private weak var __sourceView: UIView? private weak var _presentationDelegate: PopoverPresentationDelegate? private weak var _barButtonItem: UIBarButtonItem? // Private Variables private var __inset: CGFloat = 15 private var __cornerRadius: CGFloat = 0 private var __contentView: UIView? private var __sourceRect: CGRect? private var _backgroundColor: UIColor? private var _permittedArrowDirections: UIPopoverArrowDirection = .any private var _dimsBackground: Bool = true private var _displaysBorderShadow: Bool = true private var _passthroughViews: [UIView] = [] // View Lifecycle Overrides override open func loadView() { self.view = PopoverContainerView() } override open func viewDidLayoutSubviews() { self._viewDidLayoutSubviews() } // Readonly Overridable open var defaultBackgroundColor: UIColor { return ColorScheme.background.defaultPopover } } // MARK: Delegates / DataSources // MARK: UIPopoverPresentationControllerDelegate extension PopoverVC: UIPopoverPresentationControllerDelegate { public func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { self.presentationDelegate?.prepareToPresent?(self) } public func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool { return self._shouldBeDismissed() } public func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { self.presentationDelegate?.didDismiss?(self) } } // MARK: // Private // MARK: Computed Variables private extension PopoverVC { var _sourceView: UIView? { get { return self.__sourceView } set(newSourceView) { guard newSourceView != self.__sourceView else { return } self.__sourceView = newSourceView if let cont: UIPopoverPresentationController = self.popoverPresentationController { cont.sourceView = newSourceView if self.sourceRect == nil { cont.sourceRect = newSourceView?.bounds ?? .zero } self._triggerPopoverRepositioning() } } } var _sourceRect: CGRect? { get { return self.__sourceRect } set(newSourceRect) { guard newSourceRect != self.__sourceRect else { return } self.__sourceRect = newSourceRect if let cont: UIPopoverPresentationController = self.popoverPresentationController { cont.sourceRect = newSourceRect ?? self.sourceView?.bounds ?? .zero self._triggerPopoverRepositioning() } } } var _inset: CGFloat { get { return self.__inset } set(newInset) { guard newInset != self.__inset else { return } self.__inset = newInset self.contentView?.origin = CGPoint(x: newInset, y: newInset) self.updateContentSize() } } var _cornerRadius: CGFloat { get { return self.__cornerRadius } set(newCornerRadius) { guard newCornerRadius != self.__cornerRadius else { return } self.__cornerRadius = newCornerRadius self._updateCornerRadius(to: newCornerRadius) } } var _contentView: UIView? { get { return self.__contentView } set(newContentView) { guard newContentView != self.__contentView else { return } self.__contentView?.removeFromSuperview() self.__contentView = newContentView if let contentView: UIView = newContentView { contentView.origin = CGPoint(x: self.inset, y: self.inset) self.view.addSubview(contentView) } self.updateContentSize() } } } // MARK: View Lifecycle Override Implementations private extension PopoverVC { func _viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.updateContentSize() self._updateCornerRadius(to: self.cornerRadius) } } // MARK: Delegate Forwarding private extension PopoverVC { func _shouldBeDismissed() -> Bool { return self.presentationDelegate?.shouldDismiss?(self) ?? true } } // MARK: Update Corner Radius private extension PopoverVC { func _updateCornerRadius(to radius: CGFloat) { let view: UIView = self.view view.layer.cornerRadius = radius view.superview?.layer.cornerRadius = radius } } // MARK: Update Content Size private extension PopoverVC { func _updateContentSize() { let inset: CGFloat = self.inset var size: CGSize = self.__contentView?.bounds.size ?? .zero size.width += 2 * inset size.height += 2 * inset self.view.size = size self.preferredContentSize = size } } // MARK: Hack to trigger repositioning after changing sourceView or sourceRect private extension PopoverVC { func _triggerPopoverRepositioning() { self.preferredContentSize.height += 0.01 self.preferredContentSize.height -= 0.01 } } // MARK: Presentation private extension PopoverVC { func _present(from viewController: UIViewController, animated: Bool, completion: (() -> Void)?) { if let presentingViewController: UIViewController = self.presentingViewController { guard presentingViewController != viewController else { return } self.dismiss(animated: animated) { self.__present(from: viewController, animated: animated, completion: completion) } return } self.__present(from: viewController, animated: animated, completion: completion) } // Private Helpers private func __present(from viewController: UIViewController, animated: Bool, completion: (() -> Void)?) { class _BGView: PopoverBackgroundView { override class var backgroundColor: UIColor { get { return self._backgroundColor } set { self._backgroundColor = newValue } } override class var dimsBackground: Bool { get { return self._dimsBackground } set { self._dimsBackground = newValue } } override class var displaysBorderShadow: Bool { get { return self._displaysBorderShadow } set { self._displaysBorderShadow = newValue } } private static var _backgroundColor: UIColor = ColorScheme.background.defaultPopover private static var _dimsBackground: Bool = true private static var _displaysBorderShadow: Bool = true } let bgViewClass: _BGView.Type = _BGView.self bgViewClass.backgroundColor = self.backgroundColor ?? self.defaultBackgroundColor bgViewClass.dimsBackground = self.dimsBackground bgViewClass.displaysBorderShadow = self.displaysBorderShadow let cont: UIPopoverPresentationController? = self.popoverPresentationController // Right now, these are only set initially. // Should it be possible to change some or all // of them while the popover is being presented? cont?.delegate = self cont?.popoverBackgroundViewClass = bgViewClass let sourceView: UIView = self.sourceView ?? viewController.view cont?.sourceView = sourceView cont?.sourceRect = self.sourceRect ?? sourceView.bounds cont?.barButtonItem = self.barButtonItem cont?.permittedArrowDirections = self.permittedArrowDirections cont?.passthroughViews = self.passthroughViews viewController.present(self, animated: animated, completion: completion) } } // MARK: Dismissal private extension PopoverVC { func _dismiss(animated: Bool, honorShouldDismiss: Bool, callDidDismiss: Bool, completion: (() -> Void)?) { if honorShouldDismiss && !self._shouldBeDismissed() { return } if callDidDismiss { self.dismiss(animated: animated) { self.presentationDelegate?.didDismiss?(self) completion?() } } else { self.dismiss(animated: animated, completion: completion) } } }
mit
08f7449b72fb43b26fc6a3b3b7597494
30.938303
151
0.627415
5.366739
false
false
false
false
eric1202/LZJ_Coin
LZJ_Coin/Pods/LeanCloud/Sources/Storage/DataType/Object.swift
1
20341
// // Object.swift // LeanCloud // // Created by Tang Tianyong on 2/23/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation /** LeanCloud object type. It's a compound type used to unite other types. It can be extended into subclass while adding some other properties to form a new type. Each object is correspond to a record in data storage. */ open class LCObject: NSObject, LCValue, LCValueExtension, Sequence { /// Access control lists. open dynamic var ACL: LCACL? /// Object identifier. open fileprivate(set) dynamic var objectId: LCString? open fileprivate(set) dynamic var createdAt: LCDate? open fileprivate(set) dynamic var updatedAt: LCDate? /** The table of properties. - note: This property table may not contains all properties, because when a property did set in initializer, its setter hook will not be called in Swift. This property is intent for internal use. For accesssing all properties, please use `dictionary` property. */ fileprivate var propertyTable: LCDictionary = [:] /// The table of all properties. lazy var dictionary: LCDictionary = { self.synchronizePropertyTable() return self.propertyTable }() var hasObjectId: Bool { return objectId != nil } var actualClassName: String { let className = get("className") as? LCString return (className?.value) ?? type(of: self).objectClassName() } /// The temp in-memory object identifier. var internalId = Utility.uuid() /// Operation hub. /// Used to manage update operations. var operationHub: OperationHub! /// Whether object has data to upload or not. var hasDataToUpload: Bool { return hasObjectId ? (!operationHub.isEmpty) : true } public override required init() { super.init() operationHub = OperationHub(self) propertyTable.elementDidChange = { (key, value) in Runtime.setInstanceVariable(self, key, value) } } public convenience init(objectId: LCStringConvertible) { self.init() self.objectId = objectId.lcString } public convenience init(className: LCStringConvertible) { self.init() propertyTable["className"] = className.lcString } public convenience init(className: LCStringConvertible, objectId: LCStringConvertible) { self.init() propertyTable["className"] = className.lcString self.objectId = objectId.lcString } convenience init(dictionary: LCDictionaryConvertible) { self.init() propertyTable = dictionary.lcDictionary propertyTable.forEach { (key, value) in Runtime.setInstanceVariable(self, key, value) } } public required convenience init?(coder aDecoder: NSCoder) { self.init() propertyTable = (aDecoder.decodeObject(forKey: "propertyTable") as? LCDictionary) ?? [:] propertyTable.forEach { (key, value) in Runtime.setInstanceVariable(self, key, value) } } open func encode(with aCoder: NSCoder) { let propertyTable = self.dictionary.copy() as! LCDictionary aCoder.encode(propertyTable, forKey: "propertyTable") } open func copy(with zone: NSZone?) -> Any { return self } open override func isEqual(_ object: Any?) -> Bool { if let object = object as? LCObject { return object === self || (hasObjectId && object.objectId == objectId) } else { return false } } open override func value(forKey key: String) -> Any? { guard let value = get(key) else { return super.value(forKey: key) } return value } open func makeIterator() -> DictionaryIterator<String, LCValue> { return dictionary.makeIterator() } open var jsonValue: AnyObject { var result = dictionary.jsonValue as! [String: AnyObject] result["__type"] = "Object" as AnyObject? result["className"] = actualClassName as AnyObject? return result as AnyObject } open var jsonString: String { return ObjectProfiler.getJSONString(self) } public var rawValue: LCValueConvertible { return self } var lconValue: AnyObject? { guard let objectId = objectId else { return nil } return [ "__type" : "Pointer", "className" : actualClassName, "objectId" : objectId.value ] as AnyObject } static func instance() -> LCValue { return self.init() } func forEachChild(_ body: (_ child: LCValue) -> Void) { dictionary.forEachChild(body) } func add(_ other: LCValue) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be added.") } func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be concatenated.") } func differ(_ other: LCValue) throws -> LCValue { throw LCError(code: .invalidType, reason: "Object cannot be differed.") } /// The dispatch queue for network request task. static let backgroundQueue = DispatchQueue(label: "LeanCloud.Object", attributes: .concurrent) /** Set class name of current type. The default implementation returns the class name without root module. - returns: The class name of current type. */ open class func objectClassName() -> String { let className = String(validatingUTF8: class_getName(self))! /* Strip root namespace to cope with application package name's change. */ if let index = className.characters.index(of: ".") { return className.substring(from: className.index(after: index)) } else { return className } } /** Register current object class manually. */ open static func register() { ObjectProfiler.registerClass(self) } /** Load a property for key. If the property value for key is already existed and type is mismatched, it will throw an exception. - parameter key: The key to load. - returns: The property value. */ func getProperty<Value: LCValue>(_ key: String) throws -> Value? { let value = propertyTable[key] if let value = value { guard value is Value else { let reason = String(format: "No such a property with name \"%@\" and type \"%s\".", key, class_getName(Value.self)) throw LCError(code: .invalidType, reason: reason, userInfo: nil) } } return value as? Value } /** Load a property for key. If the property value for key is not existed, it will initialize the property. If the property value for key is already existed and type is mismatched, it will throw an exception. - parameter key: The key to load. - returns: The property value. */ func loadProperty<Value: LCValue>(_ key: String) throws -> Value { if let value: Value = try getProperty(key) { return value } let value = try! (Value.self as! LCValueExtension.Type).instance() as! Value propertyTable[key] = value return value } /** Update property with operation. - parameter operation: The operation used to update property. */ func updateProperty(_ operation: Operation) { let key = operation.key let name = operation.name let value = operation.value willChangeValue(forKey: key) switch name { case .set: propertyTable[key] = value case .delete: propertyTable[key] = nil case .increment: let amount = (value as! LCNumber).value let property = try! loadProperty(key) as LCNumber property.addInPlace(amount) case .add: let elements = (value as! LCArray).value let property = try! loadProperty(key) as LCArray property.concatenateInPlace(elements, unique: false) case .addUnique: let elements = (value as! LCArray).value let property = try! loadProperty(key) as LCArray property.concatenateInPlace(elements, unique: true) case .remove: let elements = (value as! LCArray).value let property = try! getProperty(key) as LCArray? property?.differInPlace(elements) case .addRelation: let elements = (value as! LCArray).value as! [LCRelation.Element] let relation = try! loadProperty(key) as LCRelation relation.appendElements(elements) case .removeRelation: let relation: LCRelation? = try! getProperty(key) let elements = (value as! LCArray).value as! [LCRelation.Element] relation?.removeElements(elements) } didChangeValue(forKey: key) } /** Synchronize property table. This method will synchronize nonnull instance variables into property table. Q: Why we need this method? A: When a property is set through dot syntax in initializer, its corresponding setter hook will not be called, it will result in that some properties will not be added into property table. */ func synchronizePropertyTable() { ObjectProfiler.iterateProperties(self) { (key, _) in if key == "propertyTable" { return } if let value = Runtime.instanceVariableValue(self, key) as? LCValue { propertyTable.set(key, value) } } } /** Add an operation. - parameter name: The operation name. - parameter key: The operation key. - parameter value: The operation value. */ func addOperation(_ name: Operation.Name, _ key: String, _ value: LCValue? = nil) { let operation = Operation(name: name, key: key, value: value) updateProperty(operation) operationHub.reduce(operation) } /** Transform value for key. - parameter key: The key for which the value should be transformed. - parameter value: The value to be transformed. - returns: The transformed value for key. */ func transformValue(_ key: String, _ value: LCValue?) -> LCValue? { guard let value = value else { return nil } switch key { case "ACL": return LCACL(jsonValue: value.jsonValue) case "createdAt", "updatedAt": return LCDate(jsonValue: value.jsonValue) default: return value } } /** Update a property. - parameter key: The property key to be updated. - parameter value: The property value. */ func update(_ key: String, _ value: LCValue?) { willChangeValue(forKey: key) propertyTable[key] = transformValue(key, value) didChangeValue(forKey: key) } /** Get and set value via subscript syntax. */ open subscript(key: String) -> LCValue? { get { return get(key) } set { set(key, value: newValue) } } /** Get value for key. - parameter key: The key for which to get the value. - returns: The value for key. */ open func get(_ key: String) -> LCValue? { return ObjectProfiler.propertyValue(self, key) ?? propertyTable[key] } /** Set value for key. - parameter key: The key for which to set the value. - parameter value: The new value. */ func set(_ key: String, value: LCValue?) { if let value = value { addOperation(.set, key, value) } else { addOperation(.delete, key) } } /** Set value for key. This method allows you to set a value of a Swift built-in type which confirms LCValueConvertible. - parameter key: The key for which to set the value. - parameter value: The new value. */ open func set(_ key: String, value: LCValueConvertible?) { set(key, value: value?.lcValue) } /** Unset value for key. - parameter key: The key for which to unset. */ open func unset(_ key: String) { addOperation(.delete, key, nil) } /** Increase a number by amount. - parameter key: The key of number which you want to increase. - parameter amount: The amount to increase. */ open func increase(_ key: String, by: LCNumberConvertible) { addOperation(.increment, key, by.lcNumber) } /** Append an element into an array. - parameter key: The key of array into which you want to append the element. - parameter element: The element to append. */ open func append(_ key: String, element: LCValueConvertible) { addOperation(.add, key, LCArray([element.lcValue])) } /** Append one or more elements into an array. - parameter key: The key of array into which you want to append the elements. - parameter elements: The array of elements to append. */ open func append(_ key: String, elements: LCArrayConvertible) { addOperation(.add, key, elements.lcArray) } /** Append an element into an array with unique option. - parameter key: The key of array into which you want to append the element. - parameter element: The element to append. - parameter unique: Whether append element by unique or not. If true, element will not be appended if it had already existed in array; otherwise, element will always be appended. */ open func append(_ key: String, element: LCValueConvertible, unique: Bool) { addOperation(unique ? .addUnique : .add, key, LCArray([element.lcValue])) } /** Append one or more elements into an array with unique option. - seealso: `append(key: String, element: LCValue, unique: Bool)` - parameter key: The key of array into which you want to append the element. - parameter elements: The array of elements to append. - parameter unique: Whether append element by unique or not. */ open func append(_ key: String, elements: LCArrayConvertible, unique: Bool) { addOperation(unique ? .addUnique : .add, key, elements.lcArray) } /** Remove an element from an array. - parameter key: The key of array from which you want to remove the element. - parameter element: The element to remove. */ open func remove(_ key: String, element: LCValueConvertible) { addOperation(.remove, key, LCArray([element.lcValue])) } /** Remove one or more elements from an array. - parameter key: The key of array from which you want to remove the element. - parameter elements: The array of elements to remove. */ open func remove(_ key: String, elements: LCArrayConvertible) { addOperation(.remove, key, elements.lcArray) } /** Get relation object for key. - parameter key: The key where relationship based on. - returns: The relation for key. */ open func relationForKey(_ key: String) -> LCRelation { return LCRelation(key: key, parent: self) } /** Insert an object into a relation. - parameter key: The key of relation into which you want to insert the object. - parameter object: The object to insert. */ open func insertRelation(_ key: String, object: LCObject) { addOperation(.addRelation, key, LCArray([object])) } /** Remove an object from a relation. - parameter key: The key of relation from which you want to remove the object. - parameter object: The object to remove. */ open func removeRelation(_ key: String, object: LCObject) { addOperation(.removeRelation, key, LCArray([object])) } /** Validate object before saving. Subclass can override this method to add custom validation logic. */ func validateBeforeSaving() { /* Validate circular reference. */ ObjectProfiler.validateCircularReference(self) } /** Reset operations, make object unmodified. */ func resetOperation() { operationHub.reset() } /** Asynchronize task into background queue. - parameter task: The task to be performed. - parameter completion: The completion closure to be called on main thread after task finished. */ func asynchronize<Result>(_ task: @escaping () -> Result, completion: @escaping (Result) -> Void) { LCObject.asynchronize(task, completion: completion) } /** Asynchronize task into background queue. - parameter task: The task to be performed. - parameter completion: The completion closure to be called on main thread after task finished. */ static func asynchronize<Result>(_ task: @escaping () -> Result, completion: @escaping (Result) -> Void) { Utility.asynchronize(task, backgroundQueue, completion) } /** Save object and its all descendant objects synchronously. - returns: The result of saving request. */ open func save() -> LCBooleanResult { return LCBooleanResult(response: ObjectUpdater.save(self)) } /** Save object and its all descendant objects asynchronously. - parameter completion: The completion callback closure. */ open func save(_ completion: @escaping (LCBooleanResult) -> Void) { asynchronize({ self.save() }) { result in completion(result) } } /** Delete a batch of objects in one request synchronously. - parameter objects: An array of objects to be deleted. - returns: The result of deletion request. */ open static func delete(_ objects: [LCObject]) -> LCBooleanResult { return LCBooleanResult(response: ObjectUpdater.delete(objects)) } /** Delete a batch of objects in one request asynchronously. - parameter completion: The completion callback closure. */ open static func delete(_ objects: [LCObject], completion: @escaping (LCBooleanResult) -> Void) { asynchronize({ delete(objects) }) { result in completion(result) } } /** Delete current object synchronously. - returns: The result of deletion request. */ open func delete() -> LCBooleanResult { return LCBooleanResult(response: ObjectUpdater.delete(self)) } /** Delete current object asynchronously. - parameter completion: The completion callback closure. */ open func delete(_ completion: @escaping (LCBooleanResult) -> Void) { asynchronize({ self.delete() }) { result in completion(result) } } /** Fetch a batch of objects in one request synchronously. - parameter objects: An array of objects to be fetched. - returns: The result of fetching request. */ open static func fetch(_ objects: [LCObject]) -> LCBooleanResult { return LCBooleanResult(response: ObjectUpdater.fetch(objects)) } /** Fetch a batch of objects in one request asynchronously. - parameter completion: The completion callback closure. */ open static func fetch(_ objects: [LCObject], completion: @escaping (LCBooleanResult) -> Void) { asynchronize({ fetch(objects) }) { result in completion(result) } } /** Fetch object from server synchronously. - returns: The result of fetching request. */ open func fetch() -> LCBooleanResult { return LCBooleanResult(response: ObjectUpdater.fetch(self)) } /** Fetch object from server asynchronously. - parameter completion: The completion callback closure. */ open func fetch(_ completion: @escaping (LCBooleanResult) -> Void) { asynchronize({ self.fetch() }) { result in completion(result) } } }
mit
7f39766baca901468a92e837e3ca7665
28.911765
131
0.621436
4.698545
false
false
false
false
Harley-xk/Chrysan
Chrysan/Sources/Status.swift
1
2754
// // Status.swift // Chrysan // // Created by Harley-xk on 2020/6/4. // Copyright © 2020 Harley. All rights reserved. // import Foundation import UIKit /// HUD 状态 public struct Status { public typealias ID = String /// 状态唯一标识 public let id: ID /// 显示该状态时展示的消息 public var message: String? /// 进度状态对应的进度值,没有进度的状态为空 public var progress: Double? = nil /// 进度值文本,如果进度条支持进度文本,指定后将会显示该值 /// 默认显示格式: String(format: "%.0f%%", progress * 100) public var progressText: String? = nil public init( id: ID, message: String? = nil, progress: Double? = nil, progressText: String? = nil ) { self.id = id self.message = message self.progress = progress self.progressText = progressText } } extension Status: Equatable { public static func == (lhs: Status, rhs: Status) -> Bool { return lhs.id == rhs.id } } // MARK: - Preset Status public extension Status { /// 预设状态:静默状态 static let idle = Status(id: .idle) /// 纯文本的状态,此时一般只显示文本内容 /// - Parameter message: 文本内容,支持多行 static func plain(message: String) -> Status { return Status(id: .plain, message: message) } /// 加载中状态, 所有的 loading 状态都具有相同的 id /// - Parameter message: 自定义消息内容 static func loading(message: String? = nil) -> Status { return Status(id: .loading, message: message) } /// 预设状态:带进度的状态,所有的 progress 状态都具有相同的 id static func progress( message: String? = nil, progress: Double, progressText: String? = nil ) -> Status { return Status( id: .progress, message: message, progress: progress, progressText: progressText ) } /// 预设状态:成功 static func success(message: String? = nil) -> Status { return Status(id: .success, message: message) } /// 预设状态:失败 static func failure(message: String? = nil) -> Status { return Status(id: .failure, message: message) } } public extension Status.ID { static let idle = "chrysan.status.idle" static let plain = "chrysan.status.plain" static let loading = "chrysan.status.loading" static let progress = "chrysan.status.progress" static let success = "chrysan.status.success" static let failure = "chrysan.status.failure" }
mit
ef9fc98303359bdad4747a75d7f147f7
22.696078
62
0.590815
3.673252
false
false
false
false
avhurst/week3
InstaClone/InstaClone/ImageViewController.swift
1
6925
// // ViewController.swift // InstaClone // // Created by Allen Hurst on 2/12/16. // Copyright © 2016 Allen Hurst. All rights reserved. // import UIKit class ImageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { lazy var imagePicker = UIImagePickerController() var originalImage: UIImage? var previousFilter: UIImage? @IBOutlet weak var imageView: UIImageView! @IBAction func addImageButtonSelected(sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable(.Camera) { presentActionSheet() } else { self.presentImagePicker(.PhotoLibrary) } } @IBAction func removeImageButtonSelected(sender: AnyObject) { self.imageView.image = nil self.originalImage = nil } @IBAction func editButtonSelected(sender: UIBarButtonItem) { guard let image = self.imageView.image else { return } let actionSheet = UIAlertController(title: "Filters", message: "Please select a filter", preferredStyle: .Alert) let bwAction = UIAlertAction(title: "Black & White", style: .Default) { (action) -> Void in Filters.shared.bw(image, completion: { (theImage) -> () in self.previousFilter = self.imageView.image self.imageView.image = theImage }) } let pxAction = UIAlertAction(title: "Pixelate", style: .Default) { (action) -> Void in Filters.shared.px(image, completion: { (theImage) -> () in self.previousFilter = self.imageView.image self.imageView.image = theImage }) } let invertAction = UIAlertAction(title: "Color Invert", style: .Default) { (action) -> Void in Filters.shared.invert(image, completion: { (theImage) -> () in self.previousFilter = self.imageView.image self.imageView.image = theImage }) } let sepiaAction = UIAlertAction(title: "Sepia Tone", style: .Default) { (action) -> Void in Filters.shared.sepia(image, completion: { (theImage) -> () in self.previousFilter = self.imageView.image self.imageView.image = theImage }) } let lineAction = UIAlertAction(title: "Line Screen", style: .Default) { (action) -> Void in Filters.shared.line(image, completion: { (theImage) -> () in self.previousFilter = self.imageView.image self.imageView.image = theImage }) } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in } actionSheet.addAction(bwAction) actionSheet.addAction(pxAction) actionSheet.addAction(invertAction) actionSheet.addAction(sepiaAction) actionSheet.addAction(lineAction) actionSheet.addAction(cancelAction) self.presentViewController(actionSheet, animated: true, completion: nil) } @IBAction func undoButtonSelected(sender: UIBarButtonItem) { let actionSheet = UIAlertController(title:"Undo", message:"", preferredStyle: .ActionSheet) let undo = UIAlertAction(title: "Remove filter", style: .Default) { (action) -> Void in self.imageView.image = self.previousFilter } let reset = UIAlertAction(title: "Reset image", style: .Default) { (action) -> Void in self.imageView.image = self.originalImage } let cancel = UIAlertAction(title: "Cancel", style: .Destructive) { (action) -> Void in } actionSheet.addAction(undo) actionSheet.addAction(reset) actionSheet.addAction(cancel) self.presentViewController(actionSheet, animated: true, completion: nil) } @IBAction func saveButtonSelected(sender: UIBarButtonItem) { guard let image = self.imageView.image else { return } API.shared.POST(Post(image: image)) { (success) -> () in if success { UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil) } } } func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafePointer<Void>) { if error == nil { let alertController = UIAlertController(title: "Saved!", message: "Your Image has been Saved", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default) { (action) -> Void in }) self.presentViewController(alertController, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func presentImagePicker(sourceType: UIImagePickerControllerSourceType) { self.imagePicker.delegate = self self.imagePicker.sourceType = sourceType self.presentViewController(self.imagePicker, animated: true, completion: nil) } func presentActionSheet() { let actionSheet = UIAlertController(title: "Source", message: "Please select the source type", preferredStyle: .ActionSheet) let cameraAction = UIAlertAction(title: "Camera", style: .Default) { (action) -> Void in self.presentImagePicker(.Camera) } let photoAction = UIAlertAction(title: "Photos", style: .Default) { (action) -> Void in self.presentImagePicker(.PhotoLibrary) } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action)-> Void in } actionSheet.addAction(cameraAction) actionSheet.addAction(photoAction) actionSheet.addAction(cancelAction) self.presentViewController(actionSheet, animated: true) {} } } extension ImageViewController { func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String :AnyObject]?) { self.imageView.image = image self.originalImage = image self.previousFilter = image self.dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
6d8d29a05cb243740bb89ba92dc10d2b
32.288462
136
0.606297
5.285496
false
false
false
false
yisimeng/YSMFactory-swift
YSMFactory-swift/Vendor/YSMPageView/YSMPageTitleView.swift
1
8485
// // YSMPageTitleView.swift // YSMFactory-swift // // Created by 忆思梦 on 2016/12/5. // Copyright © 2016年 忆思梦. All rights reserved. // import UIKit protocol YSMPageTitleViewDelegate : class { func titleView(_ titleView:YSMPageTitleView, didSelectIndex targetIndex:Int) } class YSMPageTitleView: UIView { weak var delegate:YSMPageTitleViewDelegate? fileprivate var titles : [String] fileprivate var style : YSMPageViewStye fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView(frame: self.bounds) scrollView.bounces = true scrollView.scrollsToTop = false scrollView.showsHorizontalScrollIndicator = false return scrollView }() fileprivate var titleLabels = [UILabel]() fileprivate lazy var bottomLine:UIView = { let bottomLine = UIView() bottomLine.backgroundColor = self.style.bottomLineColor bottomLine.frame.origin.y = self.bounds.height - self.style.bottomLineHeight bottomLine.frame.size.height = self.style.bottomLineHeight return bottomLine }() fileprivate var currentIndex:Int = 0 init(frame: CGRect, titles:[String], style:YSMPageViewStye) { self.titles = titles self.style = style super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - prepareUI extension YSMPageTitleView{ fileprivate func prepareUI() { //添加scrollView addSubview(scrollView) //添加title setupTitleLabels() //titleLabelFrame setupTitleLabelsFrame() //添加下划线 if style.isBottomLineShow { setupBottomLine() } //自适应时 设置scrollView的contentSize为最后一个label的right+titleMargin的一半 if style.isTitleAutoresize { scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.titleMargin * 0.5, height: bounds.height) } //设置默认选中 let currentLabel = titleLabels[currentIndex] currentLabel.textColor = style.titleSelectColor } fileprivate func setupTitleLabels() { for (index,title) in titles.enumerated() { let label = UILabel() label.text = title label.font = UIFont.systemFont(ofSize: style.titleFontSize) label.textAlignment = .center //默认第一个label为选中 label.textColor = style.titleNormalColor label.tag = index scrollView.addSubview(label) titleLabels.append(label) //添加触摸手势 let tap = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:))) label.addGestureRecognizer(tap) label.isUserInteractionEnabled = true } } fileprivate func setupTitleLabelsFrame() { let labelCount = titleLabels.count let y:CGFloat = 0,h:CGFloat = bounds.height for (index, label) in titleLabels.enumerated() { var x:CGFloat, w:CGFloat if style.isTitleAutoresize{ //获取title宽度 w = (titles[index] as NSString).boundingRect(with: CGSize(width:CGFloat(MAXFLOAT), height: 0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: style.titleFontSize)], context: nil).width if index == 0 { x = style.titleMargin * 0.5 }else{ //获取上一个label的right值 let lastLabel = titleLabels[index-1] x = lastLabel.frame.maxX + style.titleMargin } }else{ w = bounds.width/CGFloat(labelCount) x = CGFloat(index) * w } label.frame = CGRect(x: x, y: y, width: w, height: h) } } fileprivate func setupBottomLine() { scrollView.addSubview(bottomLine) //设置下划线的位置 if style.isBottomLineShow { let bottomLineX = titleLabels.first!.frame.minX let bottomLineW = titleLabels.first!.frame.width bottomLine.frame.origin.x = bottomLineX bottomLine.frame.size.width = bottomLineW } } } // MARK: - action extension YSMPageTitleView{ @objc fileprivate func titleLabelClick(_ tap:UITapGestureRecognizer){ // 0.获取当前Label guard let targetLabel = tap.view as? UILabel else { return } // 1.如果是重复点击同一个Title,那么直接返回 guard targetLabel.tag != currentIndex else { adjustCurrentLabelCentered(currentIndex) return } // 2.获取之前的Label let currentLabel = titleLabels[currentIndex] //修改颜色 targetLabel.textColor = style.titleSelectColor currentLabel.textColor = style.titleNormalColor //保存最新label的下标值 currentIndex = targetLabel.tag //通知代理滚动 delegate?.titleView(self, didSelectIndex: currentIndex) //调整label居中 adjustCurrentLabelCentered(currentIndex) //设置下划线跟随 if style.isBottomLineShow { UIView.animate(withDuration: 0.15, animations: { let x = targetLabel.frame.minX let w = targetLabel.frame.width self.bottomLine.frame = CGRect(x: x, y: self.bottomLine.frame.origin.y, width: w, height: self.bottomLine.frame.height) }) } } func scrollingTitle(from sourceIndex:Int, to targetIndex:Int, with progress:CGFloat) { //获取当前和目标label let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] //设置文字渐变 if style.isTitleColorCrossDissolve { let delatColor = UIColor.getRGBDelta(style.titleNormalColor,style.titleSelectColor) let normalColorCmps = style.titleNormalColor.getRGBComponents() let selectColorCmps = style.titleSelectColor.getRGBComponents() sourceLabel.textColor = UIColor(r: selectColorCmps.r-delatColor.rDelta*progress, g: selectColorCmps.g-delatColor.gDelta*progress, b: selectColorCmps.b-delatColor.bDelta*progress, alpha: selectColorCmps.alpha-delatColor.aDelta*progress) targetLabel.textColor = UIColor(r: normalColorCmps.r+delatColor.rDelta*progress, g: normalColorCmps.g+delatColor.gDelta*progress, b: normalColorCmps.b+delatColor.bDelta*progress, alpha: normalColorCmps.alpha+delatColor.aDelta*progress) } let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width //设置下划线偏移 if style.isBottomLineShow { UIView.animate(withDuration: 0.2, animations: { self.bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress self.bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress }) } } //调整label居中 func adjustCurrentLabelCentered(_ targetIndex:Int) { //设置选中label居中 guard style.isTitleAutoresize else { return } let currentLabel = titleLabels[targetIndex] //当label居中时,ScrollView的左边界到屏幕左边的距离就是偏移量 var offsetX = currentLabel.center.x - bounds.width * 0.5 //当偏移小于0时,ScrollView的左边界会在原边界的右边 if offsetX < 0{ offsetX = 0 } //当偏移量大于(scrollView.contentSize.width-scrollView.bounds.width)时,右边界会在原右边界的左边 if offsetX > scrollView.contentSize.width-scrollView.bounds.width { offsetX = scrollView.contentSize.width-scrollView.bounds.width } //设置偏移 self.scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) //保存当前下标 currentIndex = targetIndex } }
mit
195a61725ed9e834305a7a36ea9376dc
35.490909
268
0.626059
4.747487
false
false
false
false
ashfurrow/FunctionalReactiveAwesome
Pods/RxSwift/RxSwift/RxSwift/Observables/Observable+Single.swift
2
5146
// // Observable+Single.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // as observable public func asObservable<E> (source: Observable<E>) -> Observable<E> { if let asObservable = source as? AsObservable<E> { return asObservable.omega() } else { return AsObservable(source: source) } } // distinct until changed public func distinctUntilChangedOrDie<E: Equatable>(source: Observable<E>) -> Observable<E> { return distinctUntilChangedOrDie({ success($0) }, { success($0 == $1) })(source) } public func distinctUntilChangedOrDie<E, K: Equatable> (keySelector: (E) -> RxResult<K>) -> (Observable<E> -> Observable<E>) { return { source in return distinctUntilChangedOrDie(keySelector, { success($0 == $1) })(source) } } public func distinctUntilChangedOrDie<E> (comparer: (lhs: E, rhs: E) -> RxResult<Bool>) -> (Observable<E> -> Observable<E>) { return { source in return distinctUntilChangedOrDie({ success($0) }, comparer)(source) } } public func distinctUntilChangedOrDie<E, K> (keySelector: (E) -> RxResult<K>, comparer: (lhs: K, rhs: K) -> RxResult<Bool>) -> (Observable<E> -> Observable<E>) { return { source in return DistinctUntilChanged(source: source, selector: keySelector, comparer: comparer) } } public func distinctUntilChanged<E: Equatable>(source: Observable<E>) -> Observable<E> { return distinctUntilChanged({ $0 }, { ($0 == $1) })(source) } public func distinctUntilChanged<E, K: Equatable> (keySelector: (E) -> K) -> (Observable<E> -> Observable<E>) { return { source in return distinctUntilChanged(keySelector, { ($0 == $1) })(source) } } public func distinctUntilChanged<E> (comparer: (lhs: E, rhs: E) -> Bool) -> (Observable<E> -> Observable<E>) { return { source in return distinctUntilChanged({ ($0) }, comparer)(source) } } public func distinctUntilChanged<E, K> (keySelector: (E) -> K, comparer: (lhs: K, rhs: K) -> Bool) -> (Observable<E> -> Observable<E>) { return { source in return DistinctUntilChanged(source: source, selector: {success(keySelector($0)) }, comparer: { success(comparer(lhs: $0, rhs: $1))}) } } // do public func doOrDie<E> (eventHandler: (Event<E>) -> RxResult<Void>) -> (Observable<E> -> Observable<E>) { return { source in return Do(source: source, eventHandler: eventHandler) } } public func `do`<E> (eventHandler: (Event<E>) -> Void) -> (Observable<E> -> Observable<E>) { return { source in return Do(source: source, eventHandler: { success(eventHandler($0)) }) } } // doOnNext public func doOnNext<E> (actionOnNext: E -> Void) -> (Observable<E> -> Observable<E>) { return { source in return source >- `do` { event in switch event { case .Next(let boxedValue): let value = boxedValue.value actionOnNext(value) default: break } } } } // map aka select public func mapOrDie<E, R> (selector: E -> RxResult<R>) -> (Observable<E> -> Observable<R>) { return { source in return selectOrDie(selector)(source) } } public func map<E, R> (selector: E -> R) -> (Observable<E> -> Observable<R>) { return { source in return select(selector)(source) } } public func mapWithIndexOrDie<E, R> (selector: (E, Int) -> RxResult<R>) -> (Observable<E> -> Observable<R>) { return { source in return selectWithIndexOrDie(selector)(source) } } public func mapWithIndex<E, R> (selector: (E, Int) -> R) -> (Observable<E> -> Observable<R>) { return { source in return selectWithIndex(selector)(source) } } // select public func selectOrDie<E, R> (selector: (E) -> RxResult<R>) -> (Observable<E> -> Observable<R>) { return { source in return Select(source: source, selector: selector) } } public func select<E, R> (selector: (E) -> R) -> (Observable<E> -> Observable<R>) { return { source in return Select(source: source, selector: {success(selector($0)) }) } } public func selectWithIndexOrDie<E, R> (selector: (E, Int) -> RxResult<R>) -> (Observable<E> -> Observable<R>) { return { source in return Select(source: source, selector: selector) } } public func selectWithIndex<E, R> (selector: (E, Int) -> R) -> (Observable<E> -> Observable<R>) { return { source in return Select(source: source, selector: {success(selector($0, $1)) }) } } // Prefixes observable sequence with `firstElement` element. // The same functionality could be achieved using `concat([returnElement(prefix), source])`, // but this is significantly more efficient implementation. public func startWith<E> (firstElement: E) -> (Observable<E> -> Observable<E>) { return { source in return StartWith(source: source, element: firstElement) } }
mit
4b718d5d10ccb4979f171dab2176b00b
25.121827
140
0.609988
3.718208
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SwiftNetworkImages-master/SwiftNetworkImages/Extensions/UICollectionView+DefaultReuse.swift
2
5418
// // UICollectionView+DefaultReuseIdentifier.swift // SwiftNetworkImages // // Created by Arseniy Kuznetsov on 30/4/16. // Copyright © 2016 Arseniy Kuznetsov. All rights reserved. // import UIKit /// Conformance to the `ReusableViewWithDefaultIdentifierAndKind` protocol extension UICollectionReusableView: ReusableViewWithDefaultIdentifierAndKind {} /** Simplifies registering & dequeuing `UICollectionViewCell` and `UICollectionReusableView` classes & nibs. Sample usage: ``` class ImageCollectionViewCell: UICollectionViewCell {} collectionView.registerClass(ImageCollectionViewCell.self) func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell { let cell: ImageCollectionViewCell = collectionView.dequeueReusableCell(for: indexPath) // ... return cell } ``` */ extension UICollectionView { // MARK: - Register classes func registerClass<T: UICollectionViewCell>(_: T.Type) where T: ReusableViewWithDefaultIdentifier { register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } func registerClass<T: UICollectionReusableView>(_: T.Type, forSupplementaryViewOfKind elementKind: String) where T: ReusableViewWithDefaultIdentifier { register(T.self, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: T.defaultReuseIdentifier) } func registerClass<T: UICollectionReusableView>(_: T.Type) where T: ReusableViewWithDefaultIdentifierAndKind { register(T.self, forSupplementaryViewOfKind: T.defaultElementKind, withReuseIdentifier: T.defaultReuseIdentifier) } // MARK: - Register nibs func registerNib<T: UICollectionViewCell>(_: T.Type) where T: ReusableViewWithDefaultIdentifier, T: NibLoadableView { let nib = UINib(nibName: T.nibName, bundle: Bundle(for: T.self)) register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } func registerNib<T: UICollectionReusableView>(_: T.Type, forSupplementaryViewOfKind elementKind: String) where T: ReusableViewWithDefaultIdentifier, T: NibLoadableView { let nib = UINib(nibName: T.nibName, bundle: Bundle(for: T.self)) register(nib, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: T.defaultReuseIdentifier) } func registerNib<T: UICollectionReusableView>(_: T.Type) where T: ReusableViewWithDefaultIdentifierAndKind, T: NibLoadableView { let nib = UINib(nibName: T.nibName, bundle: Bundle(for: T.self)) register(nib, forSupplementaryViewOfKind: T.defaultElementKind, withReuseIdentifier: T.defaultReuseIdentifier) } // MARK: - Cells dequeueing func dequeueReusableCell<T: UICollectionViewCell>(for indexPath: IndexPath) -> T where T: ReusableViewWithDefaultIdentifier { guard let cell = dequeueReusableCell(withReuseIdentifier: T.defaultReuseIdentifier, for: indexPath as IndexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.defaultReuseIdentifier)") } return cell } // MARK: - Dequeueing of reusable views func dequeueReusableSupplementaryViewOfKind<T: UICollectionReusableView> (elementKind: String, for indexPath: IndexPath) -> T where T: ReusableViewWithDefaultIdentifier { let reuseIdentifier = T.defaultReuseIdentifier guard let reusableView = dequeueReusableSupplementaryView(ofKind: elementKind, withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as? T else { fatalError(String(format: "%@%@", "Could not dequeue reusable view of kind \(elementKind)", "with identifier: \(T.defaultReuseIdentifier)")) } return reusableView } func dequeueReusableSupplementaryViewOfKind<T: UICollectionReusableView> (for indexPath: IndexPath) -> T where T: ReusableViewWithDefaultIdentifierAndKind { guard let reusableView = dequeueReusableSupplementaryView(ofKind: T.defaultElementKind, withReuseIdentifier: T.defaultReuseIdentifier, for: indexPath as IndexPath) as? T else { fatalError(String(format: "%@%@", "Could not dequeue reusable view of kind \(T.defaultElementKind)", "with identifier: \(T.defaultReuseIdentifier)")) } return reusableView } }
mit
6c58608dfe4210d6607cab92278166b1
46.517544
117
0.593687
6.805276
false
false
false
false
CulturaMobile/culturamobile-api
Sources/App/Models/Price.swift
1
1826
import Vapor import FluentProvider import AuthProvider import HTTP final class Price: Model { fileprivate static let databaseTableName = "prices" static var entity = "prices" let storage = Storage() static let idKey = "id" static let foreignIdKey = "price_id" var value: Double init(value: Double) { self.value = value } // MARK: Row /// Initializes from the database row init(row: Row) throws { value = try row.get("value") } // Serializes object to the database func makeRow() throws -> Row { var row = Row() try row.set("value", value) return row } } // MARK: Preparation extension Price: Preparation { /// Prepares a table/collection in the database for storing objects static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.double("price") } } /// Undoes what was done in `prepare` static func revert(_ database: Database) throws { try database.delete(self) } } // MARK: JSON // How the model converts from / to JSON. // extension Price: JSONConvertible { convenience init(json: JSON) throws { try self.init( value: json.get("value") ) id = try json.get("id") } func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id) try json.set("value", value) return json } } // MARK: HTTP // This allows User models to be returned // directly in route closures extension Price: ResponseRepresentable { } extension Price: Timestampable { static var updatedAtKey: String { return "updated_at" } static var createdAtKey: String { return "created_at" } }
mit
626091c459ca76ae1955aa1c2b89bc64
21.54321
71
0.603505
4.276347
false
false
false
false
testpress/ios-app
ios-app/Model/Dashboard/DashboardResponse.swift
1
4912
// // DashboardResponse.swift // ios-app // // Created by Karthik on 29/04/21. // Copyright © 2021 Testpress. All rights reserved. // import ObjectMapper public class DashboardResponse { var dashboardSections: [DashboardSection]? var availableSections: [DashboardSection] = [] var chapterContents: [Content]? var chapterContentAttempts: [ChapterContentAttempt]? var posts: [Post]? var bannerAds: [Banner]? var leaderboardItems: [LeaderboardItem]? var chapters: [Chapter]? var courses: [Course]? var userStats: [UserStats]? var exams: [Exam]? var assessments: [Attempt]? var userVideos: [VideoAttempt]? var contents: [HtmlContent]? var videos: [Video]? var acceptedContentTypes = ["trophy_leaderboard", "banner_ad", "post", "chapter_content", "chapter_content_attempt"] private var contentMap = [Int: Content]() private var chapterMap = [Int: Chapter]() private var bannerMap = [Int: Banner]() private var postMap = [Int: Post]() private var leaderboardItemMap = [Int: LeaderboardItem]() private var chapterContentAttemptMap = [Int: ChapterContentAttempt]() private var userVideosMap = [Int: VideoAttempt]() private var examMap = [Int: Exam]() private var htmlContentMap = [Int: HtmlContent]() public required init?(map: Map) { } public func getAvailableSections() -> [DashboardSection] { if (availableSections.isEmpty) { for section in dashboardSections! { if(acceptedContentTypes.contains(section.contentType!) && (section.items?.isEmpty == false)) { availableSections.append(section) } } availableSections.sort(by: {$0.order! < $1.order!}) } return availableSections } func getContent(id: Int) -> Content? { if contentMap.isEmpty { for content in chapterContents ?? [] { contentMap[content.id] = content } } return contentMap[id] } func getChapter(id: Int) -> Chapter? { if chapterMap.isEmpty { for chapter in chapters ?? [] { chapterMap[chapter.id] = chapter } } return chapterMap[id] } func getBanner(id: Int) -> Banner? { if bannerMap.isEmpty { for banner in bannerAds ?? [] { bannerMap[banner.id!] = banner } } return bannerMap[id] } func getPost(id: Int) -> Post? { if postMap.isEmpty { for post in posts ?? [] { postMap[post.id] = post } } return postMap[id] } func getLeaderboardItem(id: Int) -> LeaderboardItem? { if leaderboardItemMap.isEmpty { for leaderboardItem in leaderboardItems ?? [] { leaderboardItemMap[leaderboardItem.id!] = leaderboardItem } } return leaderboardItemMap[id] } func getChapterContentAttempt(id: Int) -> ChapterContentAttempt? { if chapterContentAttemptMap.isEmpty { for contentAttempt in chapterContentAttempts ?? [] { chapterContentAttemptMap[contentAttempt.id!] = contentAttempt } } return chapterContentAttemptMap[id] } func getVideoAttempt(id: Int) -> VideoAttempt? { if userVideosMap.isEmpty { for userVideo in userVideos ?? [] { userVideosMap[userVideo.id!] = userVideo } } return userVideosMap[id] } func getExam(id: Int = -1) -> Exam? { if examMap.isEmpty { for exam in exams ?? [] { examMap[exam.id] = exam } } return examMap[id] } func getHtmlContent(id: Int = -1) -> HtmlContent? { if htmlContentMap.isEmpty { for htmlContent in contents ?? [] { htmlContentMap[htmlContent.id] = htmlContent } } return htmlContentMap[id] } } extension DashboardResponse: TestpressModel { public func mapping(map: Map) { dashboardSections <- map["dashboard_sections"] chapterContents <- map["chapter_contents"] chapterContentAttempts <- map["chapter_content_attempts"] posts <- map["posts"] bannerAds <- map["banner_ads"] leaderboardItems <- map["leaderboard_items"] chapters <- map["chapters"] courses <- map["courses"] userStats <- map["user_stats"] exams <- map["exams"] assessments <- map["assessments"] userVideos <- map["user_videos"] contents <- map["contents"] videos <- map["videos"] } }
mit
274da7d9550dc3a59b75348acc9a8c13
27.719298
110
0.559357
4.551437
false
false
false
false
RoshanNindrai/Mayon
Sources/MayonFramework/Platform/Apple/IOSDevice.swift
1
2739
// // IOSDevice.swift // Mayon // // Created by Roshan Nindrai on 7/15/17. // // import Foundation public typealias AMDeviceRef = UnsafeMutablePointer<am_device_notification_callback_info> public typealias AMDevicePointer = UnsafeMutablePointer<am_device> // MARK: - IOS Device struct IOSDevice: Device { /// The id of the device var deviceId: String /// The name of the device ex Roshan's iPhone var name: String /// The platform Type of the device var platform: Platform /// The os Version as string var version: String /// The proxy to internal representation of device var proxy: Proxy fileprivate var amDeviceRef: AMDeviceRef? /// Create a Device for iOS plaform /// /// - Parameter am_device: am_device instance that is used to get Device information init?(amdevice: AMDeviceRef?) { connect(amdevice); defer { disConnect(amdevice) } amDeviceRef = amdevice deviceId = (AMDeviceCopyDeviceIdentifier(amdevice!.pointee.dev).takeRetainedValue() as String) // This will return nil if the device was unplugged during discovery guard (AMDeviceCopyValue(amdevice!.pointee.dev, nil, "DeviceName" as CFString) as? String) != nil else { print("Device \(deviceId) removed") return nil } name = (AMDeviceCopyValue(amdevice!.pointee.dev, nil, "DeviceName" as CFString) as? String)! version = (AMDeviceCopyValue(amdevice!.pointee.dev, nil, "ProductVersion" as CFString) as? String)! platform = .iOS proxy = .iOS((amdevice?.pointee.dev)!) } } extension IOSDevice { /// Pointer to the device var amdevice: AMDevicePointer? { if case let .iOS(amdevice) = proxy { return amdevice } return nil } /// To execute any command, before exevuting the command /// the device connect call is made and will be disconnected at the end of execution /// /// - Parameter command: The command to be executed in the device func execute(_ command: (AMDevicePointer?) -> Void) { command(amDeviceRef?.pointee.dev) } } /// TO connect to a device to get information out of it /// /// - Parameter device: The actual AMDevice reference private func connect(_ device: AMDeviceRef?) { AMDeviceConnect(device!.pointee.dev) guard AMDeviceIsPaired(device!.pointee.dev) == 1 else { print("Please pair all the connected apple device(s)") disConnect(device) exit(1) } } /// TO disconnect from the device as part of cleanup /// /// - Parameter device: The actual AMDevice reference private func disConnect(_ device: AMDeviceRef?) { AMDeviceDisconnect(device!.pointee.dev) }
mit
7824b45b9fd17975f496eeb57cf051c0
28.451613
112
0.666302
4.156297
false
false
false
false
loudnate/Loop
Loop/Views/CarbEntryTableViewCell.swift
2
2895
// // CarbEntryTableViewCell.swift // Loop // // Copyright © 2017 LoopKit Authors. All rights reserved. // import UIKit class CarbEntryTableViewCell: UITableViewCell { @IBOutlet private weak var clampedProgressView: UIProgressView! @IBOutlet private weak var observedProgressView: UIProgressView! @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet private weak var observedValueLabel: UILabel! @IBOutlet private weak var observedDateLabel: UILabel! @IBOutlet private weak var uploadingIndicator: UIImageView! var clampedProgress: Float { get { return clampedProgressView.progress } set { clampedProgressView.progress = newValue clampedProgressView.isHidden = clampedProgress <= 0 } } var observedProgress: Float { get { return observedProgressView.progress } set { observedProgressView.progress = newValue observedProgressView.isHidden = observedProgress <= 0 } } var observedValueText: String? { get { return observedValueLabel.text } set { observedValueLabel.text = newValue if newValue != nil { observedValueLabel.superview?.isHidden = false } } } var observedDateText: String? { get { return observedDateLabel.text } set { observedDateLabel.text = newValue if newValue != nil { observedDateLabel.superview?.isHidden = false } } } var observedValueTextColor: UIColor { get { return observedValueLabel.textColor } set { observedValueLabel.textColor = newValue } } var observedDateTextColor: UIColor { get { return observedDateLabel.textColor } set { observedDateLabel.textColor = newValue } } var isUploading = false { didSet { uploadingIndicator.isHidden = !isUploading } } override func layoutSubviews() { super.layoutSubviews() contentView.layoutMargins.left = separatorInset.left contentView.layoutMargins.right = separatorInset.left } override func awakeFromNib() { super.awakeFromNib() resetViews() } override func prepareForReuse() { super.prepareForReuse() resetViews() } private func resetViews() { observedProgress = 0 clampedProgress = 0 valueLabel.text = nil dateLabel.text = nil observedValueText = nil observedDateText = nil observedValueLabel.superview?.isHidden = true uploadingIndicator.isHidden = true } }
apache-2.0
63d1c1551e7a4d1a4096ea9ccfad8413
22.528455
68
0.596061
5.63035
false
false
false
false
benlangmuir/swift
test/IRGen/concrete_inherits_generic_base.swift
22
3918
// RUN: %target-swift-frontend -module-name foo -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize // CHECK: %swift.type = type { [[INT]] } // -- Classes with generic bases can't go in the @objc_classes list, since // they need runtime initialization before they're valid. // CHECK-NOT: @objc_classes class Base<T> { var first, second: T required init(x: T) { first = x second = x } func present() { print("\(type(of: self)) \(T.self) \(first) \(second)") } } // CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s3foo12SuperDerivedCMa"( // CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s3foo12SuperDerivedCMl", i32 0, i32 0) // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s3foo12SuperDerivedCMn" to %swift.type_descriptor*)) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0 // CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ] // CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ] // CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0 // CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1 // CHECK-NEXT: ret %swift.metadata_response [[T1]] class SuperDerived: Derived { } // CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s3foo7DerivedCMa"( // CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s3foo7DerivedCMl", i32 0, i32 0) // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s3foo7DerivedCMn" to %swift.type_descriptor*)) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0 // CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1 // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ] // CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ] // CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0 // CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1 // CHECK-NEXT: ret %swift.metadata_response [[T1]] class Derived: Base<String> { var third: String required init(x: String) { third = x super.init(x: x) } override func present() { super.present() print("...and \(third)") } } func presentBase<T>(_ base: Base<T>) { base.present() } presentBase(SuperDerived(x: "two")) presentBase(Derived(x: "two")) presentBase(Base(x: "two")) presentBase(Base(x: 2)) // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s3foo12SuperDerivedCMr"(%swift.type* %0, i8* %1, i8** %2) // -- ClassLayoutFlags = 0x100 (HasStaticVTable) // CHECK: call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, {{.*}})
apache-2.0
b31f65dae4061d85b6bd6750f737537c
44.55814
211
0.616896
3.320339
false
false
false
false
jmont/tutorial-TableViewFooter
TableViewFooterExample/ViewController.swift
1
2030
// // ViewController.swift // TableViewFooterExample // // Created by Montemayor Elosua, Juan Carlos on 7/14/15. // Copyright (c) 2015 jmont. All rights reserved. // import UIKit class ViewController: UITableViewController { let items = ["1", "2", "3"] let cellReuseIdentifier = "com.jmont.table-view-footer-example.cell" let tableViewFooter : TableViewFooter required init!(coder aDecoder: NSCoder!) { self.tableViewFooter = TableViewFooter() super.init(coder: aDecoder) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.tableView.layoutFooterView(self.tableViewFooter) } override func viewDidLoad() { super.viewDidLoad() // This prevents the TableView from showing infinite cell separators before it displays content. self.tableViewFooter.titleLabel.attributedText = NSAttributedString(string: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.") self.tableViewFooter.backgroundColor = UIColor.lightGrayColor() self.tableView.tableFooterView = self.tableViewFooter self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as! UITableViewCell cell.textLabel?.text = self.items[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) } }
mit
bbb2430ed2d9eec200484d81af76c042
34.614035
218
0.727094
5.165394
false
false
false
false
astephensen/Locksmith
LocksmithHelper/Classes/KeySender.swift
1
1609
// // KeySender.swift // Locksmith // // Created by Alan Stephensen on 6/09/2014. // Copyright (c) 2014 Alan Stephensen. All rights reserved. // import Cocoa class KeySender: NSObject { func sendString(stringToSend: String) { // Create the base keyboard events. let keyEventDown = CGEventCreateKeyboardEvent(nil, 7, true).takeRetainedValue() let keyEventUp = CGEventCreateKeyboardEvent(nil, 7, false).takeRetainedValue() // Loop through each character in the UTF16 representation of the string. for character in stringToSend.utf16 { // We can now cast it directly to a UniChar, update the events and post. var unichar = character as UniChar CGEventKeyboardSetUnicodeString(keyEventDown, 1, &unichar) CGEventKeyboardSetUnicodeString(keyEventUp, 1, &unichar); CGEventPost(CGEventTapLocation(kCGHIDEventTap), keyEventDown); CGEventPost(CGEventTapLocation(kCGHIDEventTap), keyEventUp); } } func sendBackspaces(backspaceCount: Int) { // Similar to sending a string, except we send the backspace key (51) a certain number of times. let keyEventDown = CGEventCreateKeyboardEvent(nil, 51, true).takeRetainedValue() let keyEventUp = CGEventCreateKeyboardEvent(nil, 51, false).takeRetainedValue() for backspaceIndex in 0..<backspaceCount { CGEventPost(CGEventTapLocation(kCGHIDEventTap), keyEventDown); CGEventPost(CGEventTapLocation(kCGHIDEventTap), keyEventUp); } } }
mit
d7f186251f0c3a5e23cea8819dc5b17b
38.243902
104
0.674953
4.571023
false
false
false
false
Urinx/SublimeCode
Sublime/Sublime/Utils/Extension/Other.swift
1
1300
// // Other.swift // Sublime // // Created by Eular on 4/20/16. // Copyright © 2016 Eular. All rights reserved. // import Foundation // MARK: - UIImage extension UIImage { func saveToCameraRoll() { UIImageWriteToSavedPhotosAlbum(self, nil, nil, nil) } } // MARK: - UITabBar extension UITabBar { func showRedBadgeOnItem(index: Int, totalItemNums: Int) { hideRedBadgeOnItem(index) let badgeSize: CGFloat = 8 let badgeView = UIView() badgeView.tag = 888 + index badgeView.layer.cornerRadius = badgeSize / 2 badgeView.backgroundColor = Constant.TabBatItemBadgeColor let percentX = (CGFloat(index) + 0.6) / totalItemNums let x = CGFloat(ceilf(Float(percentX * self.width))) let y = CGFloat(ceilf(Float(0.1 * self.height))) badgeView.frame = CGRectMake(x, y, badgeSize, badgeSize) addSubview(badgeView) } func hideRedBadgeOnItem(index: Int) { for subView in self.subviews { if (subView.tag == 888 + index) { subView.removeFromSuperview() } } } } // MARK: - Range extension Range { func each(iterator: (Element) -> ()) { for i in self { iterator(i) } } }
gpl-3.0
440f78844b6438a43ed8427a23bcd925
23.528302
65
0.585065
4.0721
false
false
false
false
startupthekid/CoordinatorKit
CoordinatorKit/Core/Coordinator.swift
1
7106
// // Coordinator.swift // CoordinatorKit // // Created by Brendan Conron on 8/8/17. // Copyright © 2017 Brendan Conron. All rights reserved. // import UIKit import Foundation /// Base coordinator class. Represents a coordinator object which is primary /// used as a flow coordinator for your application. open class Coordinator: NSObject { // MARK: - State /// The current state of the given coordinator. /// /// - active: The coordinator is currently running and/or is performing active work. /// - inactive: The coordinator is not performing any work and is considered dormant. /// - paused: The coordinator was active but was paused. Coordinators in this state should throttle their work. public enum State { case active, inactive, paused } private(set) public var state: State = .inactive public var isActive: Bool { return state == .active } public var isInactive: Bool { return state == .inactive } public var isPaused: Bool { return state == .paused } // MARK: - Children private var children = Set<Coordinator>() // MARK: - Delegate /// Coordinator multicast delegate to allow for multiple listeners. public let delegate: MulticastDelegate<CoordinatorDelegate> = MulticastDelegate() // MARK: - Initialization public required override init() { super.init() } // MARK: - Coordinator Operations /// Start the coordinator and become active. /// Use this method to begin work. open func start() { guard isInactive else { return } state = .active delegate => { $0.coordinatorDidStart(self) } } /// Stop the coordinator and become inactive. /// Use this method to stop any and all work i.e. save state. open func stop() { guard isActive || isPaused else { return } state = .inactive stopAllChildren() delegate => { $0.coordinatorDidStop(self) } } /// Pause an active coordinator. /// Use this method to throttle work. open func pause() { guard isActive else { return } state = .paused pauseAllActiveChildren() delegate => { $0.coordinatorDidPause(self) } } /// Resume a paused coordinator. /// Use this method to resume any currently paused work. open func resume() { guard isPaused else { return } state = .active resumeAllPausedChildren() delegate => { $0.coordinatorDidResume(self) } } // MARK: - Querying /// Asks the coordinator if it has any children that are in the given state. /// /// - Parameter state: Coordinator state. /// - Returns: Bool, true if any children coordinators are in the given state. public func hasChildren(inState state: State) -> Bool { return !children.filter { $0.state == state }.isEmpty } /// Query for the number of children that are currently in the given state. /// /// - Parameter state: Coordinator state. /// - Returns: Number of children that are in the given state. public final func numberOfChildren(inState state: State) -> Int { return children.filter { $0.state == state }.count } /// Query the coordinator if it contains the given coordinator among it's children. /// /// - Parameter coordinator: Coordinator to check for. /// - Returns: Bool, true if the given coordinator is in the set of children. public final func hasChild(_ coordinator: Coordinator) -> Bool { return children.contains(coordinator) } /// Query for the number of children, regardless of current state. /// /// - Returns: Number of children. public final func numberOfChildren() -> Int { return children.count } // MARK: - Child Coordinators /// Start a child coordinator. /// /// This method should *always* be used rather than calling `coordinator.start()` /// directly. Starting a child coordinator has two important side-effects: /// 1) The parent coordinator adds itself as a delegate of the child. /// 2) The coordinator gets inserted into the set of children. /// /// - Parameter coordinator: Coordinator to start. public final func start<C: Coordinator>(coordinator: C) { guard !hasChild(coordinator) else { return } coordinator.delegate += self children.insert(coordinator) coordinator.start() } /// Stops the given child coordinator. /// /// This method *must* be used instead of calling `coordinator.stop()` directly. /// Stopping a child coordinator has two important side-effects: /// 1) The parent removes itself as a delegate. /// 2) The coordinator is removed from the list of children. /// /// - Parameter coordinator: Coordinator to stop. public final func stop<C: Coordinator>(coordinator: C) { guard hasChild(coordinator) else { return } coordinator.delegate -= self children.remove(coordinator) coordinator.stop() } /// Pauses the given child coordinator. /// /// This method is a wrapper function for convenience and consistency. /// /// - Parameter coordinator: Coordinator to pause. public final func pause<C: Coordinator>(coordinator: C) { guard hasChild(coordinator) else { return } guard !coordinator.isPaused else { return } coordinator.pause() } /// Resumes the given child coordinator. /// /// This method is a wrapper function for convenience and consistency. /// /// - Parameter coordinator: Coordinator to resume. public final func resume<C: Coordinator>(coordinator: C) { guard hasChild(coordinator) else { return } guard coordinator.isPaused else { return } coordinator.resume() } // MARK: - Helpers /// Stop all the children of the coordinator. private func stopAllChildren() { children.forEach { if $0.isPaused || $0.isActive { stop(coordinator: $0) } } } /// Pauses all currently active children. private func pauseAllActiveChildren() { children.forEach { if $0.isActive { pause(coordinator: $0) } } } /// Resumes all children that are paused. private func resumeAllPausedChildren() { children.forEach { if $0.isPaused { resume(coordinator: $0) } } } // MARK: - CoordinatorDelegate open func coordinatorDidStart(_ coordinator: Coordinator) { } open func coordinatorDidStop(_ coordinator: Coordinator) { } open func coordinatorDidPause(_ coordinator: Coordinator) { } open func coordinatorDidResume(_ coordinator: Coordinator) { } } extension Coordinator: CoordinatorDelegate {}
mit
9d5c13fd2f28827c08f8f612fb7c7045
29.891304
115
0.617593
4.934028
false
false
false
false
googlemaps/ios-on-demand-rides-deliveries-samples
swift/consumer_swiftui/App/Services/AuthTokenProvider.swift
1
2804
/* * Copyright 2022 Google LLC. 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 Foundation import GoogleRidesharingConsumer /// Provides a service that sends request and receives response from provider server. class AuthTokenProvider: NSObject, GMTCAuthorization { private struct AuthToken { let token: String let expiration: TimeInterval let tripID: String } private enum AccessTokenError: Error { case missingAuthorizationContext case missingData case missingURL } private static let tokenPath = "token/consumer/" private static let tokenKey = "jwt" private static let tokenExpirationKey = "expirationTimestamp" /// Cached token. private var authToken: AuthToken? func fetchToken( with authorizationContext: GMTCAuthorizationContext?, completion: @escaping GMTCAuthTokenFetchCompletionHandler ) { guard let authorizationContext = authorizationContext else { completion(nil, AccessTokenError.missingAuthorizationContext) return } let tripID = authorizationContext.tripID // Check if a token is cached and is valid. if let authToken = authToken, authToken.expiration > Date().timeIntervalSince1970 && authToken.tripID == tripID { completion(authToken.token, nil) return } let tokenURL = ProviderUtils.providerURL(path: Self.tokenPath) guard let tokenURLWithTripID = URL(string: tripID, relativeTo: tokenURL) else { completion(nil, AccessTokenError.missingURL) return } let request = URLRequest(url: tokenURLWithTripID) let task = URLSession.shared.dataTask(with: request) { [weak self] data, _, error in guard let strongSelf = self else { return } guard let data = data, let fetchData = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let token = fetchData[Self.tokenKey] as? String, let expirationInMilliseconds = fetchData[Self.tokenExpirationKey] as? Int else { completion(nil, AccessTokenError.missingData) return } strongSelf.authToken = AuthToken( token: token, expiration: Double(expirationInMilliseconds) / 1000.0, tripID: tripID) completion(token, nil) } task.resume() } }
apache-2.0
9c536d684f1939ec16f1e9ffc4772923
31.988235
91
0.714337
4.596721
false
false
false
false
recoveryrecord/SurveyNative
SurveyNative/Classes/TableViewCells/TableRowHeaderTableViewCell.swift
1
2605
// // TableRowHeaderTableViewCell.swift // SurveyNative // // Created by Nora Mullaney on 2/15/17. // Copyright © 2017 Recovery Record. All rights reserved. // import UIKit class TableRowHeaderTableViewCell: UITableViewCell { @IBOutlet var header1 : UILabel? @IBOutlet var header2 : UILabel? @IBOutlet var header3 : UILabel? let defaultFont = UIFont.systemFont(ofSize: 14.0) let minFontSize : CGFloat = 10.0 var headers : [String]? { didSet { if headers == nil { return } if headers!.count > 0 { header1?.text = headers![0] resizeFont(header1!) } if headers!.count > 1 { header2?.text = headers![1] resizeFont(header2!) } if headers!.count > 2 { header3?.text = headers![2] resizeFont(header3!) } } } // These are multi-line, so they won't auto-shrink, but we want to try to shrink if // the label would wrap in the middle of a word func resizeFont(_ label: UILabel) { label.font = defaultFont var currentFontSize = defaultFont.pointSize let words = label.text?.split{ $0 == " "}.map(String.init) while(hasOverflow(label, words: words!) && currentFontSize > minFontSize) { currentFontSize = currentFontSize - 1.0 label.font = UIFont.systemFont(ofSize: currentFontSize) } // If no matter how much we shrink the text, the word still wraps, might as well // make it big if hasOverflow(label, words: words!) { label.font = defaultFont } } func hasOverflow(_ label: UILabel, words: [String]) -> Bool { for word in words { let nsWord: NSString = word as NSString let size: CGSize = nsWord.size(withAttributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): label.font])) if (size.width > label.bounds.size.width) { return true } } return false } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
mit
ca69d7bc5feed5e2910f2470ce7dedfc
32.384615
182
0.638249
4.428571
false
false
false
false
reactive-swift/RDBC
Sources/RDBC/RDBC.swift
1
6768
//===--- RDBC.swift ------------------------------------------------------===// //Copyright (c) 2017 Crossroad Labs s.r.o. // //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 Boilerplate import ExecutionContext import Future private let _reserve: UInt = 1024 public class ResourcePool<Res> : Sequence, ExecutionContextTenantProtocol { public typealias Iterator = AnyIterator<Future<Res>> public let context: ExecutionContextProtocol private var _limit: UInt private let _factory: ()->Future<Res> private var _cache: [Res] private var _queue: [Promise<Res>] public init(context: ExecutionContextProtocol, limit: UInt = UInt.max, factory: @escaping ()->Future<Res>) { self.context = context //.serial self._limit = limit self._factory = factory self._cache = Array() self._queue = Array() _cache.reserveCapacity(Int([limit, _reserve].min()!)) _queue.reserveCapacity(Int([limit * 2, _reserve].min()!)) } public func reclaim(resource: Res) { context.async { guard !self._queue.isEmpty, let waiting = Optional(self._queue.removeFirst()) else { self._cache.append(resource) return } try waiting.success(value: resource) } } public func makeIterator() -> Iterator { let context = self.context return Iterator { future(context: context) { () -> Future<Res> in if !self._cache.isEmpty, let cached = Optional(self._cache.removeFirst()) { return Future<Res>(value: cached) } guard self._limit <= 0 else { self._limit -= 1 return self._factory() } let promise = Promise<Res>(context: context) self._queue.append(promise) return promise.future } } } } public protocol ConnectionFactory { func connect(url:String, params:Dictionary<String, String>) -> Future<Connection> } public protocol PoolFactory { func pool(url:String, params:Dictionary<String, String>) throws -> ConnectionPool } public extension ConnectionFactory { func connect(url:String) -> Future<Connection> { return connect(url: url, params: [:]) } } public extension PoolFactory { func pool(url:String) throws -> ConnectionPool { return try pool(url: url, params: [:]) } } public extension ResultSet { private func accumulate(rows:[Row]) -> Future<[Row]> { return self.next().map { row in (rows, row.map {rows + [$0]}) }.flatMap { (old, new) -> Future<[Row]> in if let new = new { return self.accumulate(rows: new) } else { return Future<[Row]>(value: old) } } } public func rows() -> Future<[Row]> { return accumulate(rows: [Row]()) } public func dictionaries() -> Future<[[String: Any?]]> { return columns.flatMap { cols in self.rows().map { rows in rows.map { row in cols.zipWith(other: row).map(tuple).dictionary } } } } } public class ConnectionPool : Connection { private let _rp: ResourcePool<Connection> private let _pool: ResourcePool<Connection>.Iterator public init(size: UInt, connectionFactory:@escaping ()->Future<Connection>) { _rp = ResourcePool(context: ExecutionContext(kind: .serial), limit: size, factory: connectionFactory) _pool = _rp.makeIterator() } public func execute(query: String, parameters: [Any?], named: [String : Any?]) -> Future<ResultSet?> { return connection().flatMap { (connection, release) in connection.execute(query: query, parameters: parameters, named: named).onComplete { _ in release() } } } //returns (connection, release) public func connection() -> Future<(Connection, ()->())> { let rp = _rp return _pool.next()!.map { connection in (connection, {rp.reclaim(resource: connection)}) } } } public class RDBC : ConnectionFactory, PoolFactory { public static let POOL_SIZE = "_k_poolSize" private var _drivers = [String:Driver]() private let _contextFactory:()->ExecutionContextProtocol public init() { _contextFactory = {ExecutionContext(kind: .serial)} } public func register(driver: Driver) { _drivers[driver.proto] = driver } public func register(driver: SyncDriver) { register(driver: AsyncDriver(driver: driver, contextFactory: _contextFactory)) } public func pool(url:String, params:Dictionary<String, String>) throws -> ConnectionPool { let driver = try self.driver(url: url, params: params) let poolSize = params[RDBC.POOL_SIZE].flatMap {UInt($0)}.flatMap { size in [driver.poolSizeLimit, size].max() } ?? driver.poolSizeRecommended return ConnectionPool(size: poolSize) { driver.connect(url: url, params: params) } } public func driver(url _url: String, params: Dictionary<String, String>) throws -> Driver { guard let url = URL(string: _url) else { throw RDBCFrameworkError.invalid(url: _url) } guard let proto = url.scheme else { throw RDBCFrameworkError.noProtocol } guard let driver = _drivers[proto] else { throw RDBCFrameworkError.unknown(protocol: proto) } return driver } public func connect(url: String, params: Dictionary<String, String>) -> Future<Connection> { return future(context: _contextFactory()) { try self.driver(url: url, params: params) }.flatMap { driver in driver.connect(url: url, params: params) } } }
apache-2.0
4568360b3b68b42ac8d2da1c2dbc18e2
31.695652
112
0.575059
4.613497
false
false
false
false
codestergit/swift
stdlib/public/core/RandomAccessCollection.swift
4
12448
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A collection that supports efficient random-access index traversal. /// /// In most cases, it's best to ignore this protocol and use the /// `RandomAccessCollection` protocol instead, because it has a more complete /// interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'RandomAccessCollection' instead") public typealias RandomAccessIndexable = _RandomAccessIndexable public protocol _RandomAccessIndexable : _BidirectionalIndexable { // FIXME(ABI)#54 (Recursive Protocol Constraints): there is no reason for this protocol // to exist apart from missing compiler features that we emulate with it. // rdar://problem/20531108 // // This protocol is almost an implementation detail of the standard // library. } /// A collection that supports efficient random-access index traversal. /// /// Random-access collections can move indices any distance and /// measure the distance between indices in O(1) time. Therefore, the /// fundamental difference between random-access and bidirectional collections /// is that operations that depend on index movement or distance measurement /// offer significantly improved efficiency. For example, a random-access /// collection's `count` property is calculated in O(1) instead of requiring /// iteration of an entire collection. /// /// Conforming to the RandomAccessCollection Protocol /// ================================================= /// /// The `RandomAccessCollection` protocol adds further constraints on the /// associated `Indices` and `SubSequence` types, but otherwise imposes no /// additional requirements over the `BidirectionalCollection` protocol. /// However, in order to meet the complexity guarantees of a random-access /// collection, either the index for your custom type must conform to the /// `Strideable` protocol or you must implement the `index(_:offsetBy:)` and /// `distance(from:to:)` methods with O(1) efficiency. public protocol RandomAccessCollection : _RandomAccessIndexable, BidirectionalCollection { /// A collection that represents a contiguous subrange of the collection's /// elements. associatedtype SubSequence : _RandomAccessIndexable, BidirectionalCollection = RandomAccessSlice<Self> // FIXME(ABI)#102 (Recursive Protocol Constraints): // associatedtype SubSequence : RandomAccessCollection /// A type that represents the indices that are valid for subscripting the /// collection, in ascending order. associatedtype Indices : _RandomAccessIndexable, BidirectionalCollection = DefaultRandomAccessIndices<Self> // FIXME(ABI)#103 (Recursive Protocol Constraints): // associatedtype Indices : RandomAccessCollection /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be nonuniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can result in an unexpected copy of the collection. To avoid /// the unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) var indices: Indices { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. subscript(bounds: Range<Index>) -> SubSequence { get } } /// Supply the default "slicing" `subscript` for `RandomAccessCollection` /// models that accept the default associated `SubSequence`, /// `RandomAccessSlice<Self>`. extension RandomAccessCollection where SubSequence == RandomAccessSlice<Self> { /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. @_inlineable public subscript(bounds: Range<Index>) -> RandomAccessSlice<Self> { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return RandomAccessSlice(base: self, bounds: bounds) } } // TODO: swift-3-indexing-model - Make sure RandomAccessCollection has // documented complexity guarantees, e.g. for index(_:offsetBy:). // TODO: swift-3-indexing-model - (By creating an ambiguity?), try to // make sure RandomAccessCollection models implement // index(_:offsetBy:) and distance(from:to:), or they will get the // wrong complexity. /// Default implementation for random access collections. extension _RandomAccessIndexable { /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - n: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// `limit` should be greater than `i` to have any effect. Likewise, if /// `n < 0`, `limit` should be less than `i` to have any effect. /// - Returns: An index offset by `n` from the index `i`, unless that index /// would be beyond `limit` in the direction of movement. In that case, /// the method returns `nil`. /// /// - Complexity: O(1) @_inlineable public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: tests. let l = distance(from: i, to: limit) if n > 0 ? l >= 0 && l < n : l <= 0 && n < l { return nil } return index(i, offsetBy: n) } } extension RandomAccessCollection where Index : Strideable, Index.Stride == IndexDistance, Indices == CountableRange<Index> { /// The indices that are valid for subscripting the collection, in ascending /// order. @_inlineable public var indices: CountableRange<Index> { return startIndex..<endIndex } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. @_inlineable public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: tests for the trap. _failEarlyRangeCheck( i, bounds: Range(uncheckedBounds: (startIndex, endIndex))) return i.advanced(by: 1) } @_inlineable /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. public func index(before i: Index) -> Index { let result = i.advanced(by: -1) // FIXME: swift-3-indexing-model: tests for the trap. _failEarlyRangeCheck( result, bounds: Range(uncheckedBounds: (startIndex, endIndex))) return result } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - Complexity: O(1) @_inlineable public func index(_ i: Index, offsetBy n: Index.Stride) -> Index { let result = i.advanced(by: n) // This range check is not precise, tighter bounds exist based on `n`. // Unfortunately, we would need to perform index manipulation to // compute those bounds, which is probably too slow in the general // case. // FIXME: swift-3-indexing-model: tests for the trap. _failEarlyRangeCheck( result, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex))) return result } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. /// /// - Complexity: O(1) @_inlineable public func distance(from start: Index, to end: Index) -> Index.Stride { // FIXME: swift-3-indexing-model: tests for traps. _failEarlyRangeCheck( start, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex))) _failEarlyRangeCheck( end, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex))) return start.distance(to: end) } }
apache-2.0
1c449d0eb05275fd4b7171f6d50a053b
41.054054
115
0.66356
4.400141
false
false
false
false
hooman/swift
test/Generics/unify_superclass_types_2.swift
1
2080
// RUN: %target-typecheck-verify-swift -requirement-machine=on -dump-requirement-machine 2>&1 | %FileCheck %s // Note: The GSB fails this test, because it doesn't implement unification of // superclass type constructor arguments. class Generic<T, U, V> {} protocol P1 { associatedtype X : Generic<Int, A1, B1> associatedtype A1 associatedtype B1 } protocol P2 { associatedtype X : Generic<A2, String, B2> associatedtype A2 associatedtype B2 } func sameType<T>(_: T.Type, _: T.Type) {} func takesGenericIntString<U>(_: Generic<Int, String, U>.Type) {} func unifySuperclassTest<T : P1 & P2>(_: T) { sameType(T.A1.self, String.self) sameType(T.A2.self, Int.self) sameType(T.B1.self, T.B2.self) takesGenericIntString(T.X.self) } // CHECK-LABEL: Requirement machine for <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> // CHECK-NEXT: Rewrite system: { // CHECK: - τ_0_0.[P1&P2:X].[superclass: Generic<τ_0_0, String, τ_0_1> with <τ_0_0.[P2:A2], τ_0_0.[P2:B2]>] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P1&P2:X].[layout: _NativeClass] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P1&P2:X].[superclass: Generic<Int, τ_0_0, τ_0_1> with <τ_0_0.[P1:A1], τ_0_0.[P1:B1]>] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P2:A2].[concrete: Int] => τ_0_0.[P2:A2] // CHECK-NEXT: - τ_0_0.[P1:A1].[concrete: String] => τ_0_0.[P1:A1] // CHECK-NEXT: - τ_0_0.[P2:B2] => τ_0_0.[P1:B1] // CHECK: } // CHECK-NEXT: Property map: { // CHECK-NEXT: [P1:X] => { layout: _NativeClass superclass: [superclass: Generic<Int, τ_0_0, τ_0_1> with <[P1:A1], [P1:B1]>] } // CHECK-NEXT: [P2:X] => { layout: _NativeClass superclass: [superclass: Generic<τ_0_0, String, τ_0_1> with <[P2:A2], [P2:B2]>] } // CHECK-NEXT: τ_0_0 => { conforms_to: [P1 P2] } // CHECK-NEXT: τ_0_0.[P1&P2:X] => { layout: _NativeClass superclass: [superclass: Generic<Int, τ_0_0, τ_0_1> with <τ_0_0.[P1:A1], τ_0_0.[P1:B1]>] } // CHECK-NEXT: τ_0_0.[P2:A2] => { concrete_type: [concrete: Int] } // CHECK-NEXT: τ_0_0.[P1:A1] => { concrete_type: [concrete: String] } // CHECK-NEXT: }
apache-2.0
ec482bcbab4fd9cf13ed8089fe90fe92
42.531915
149
0.617115
2.305524
false
false
false
false
Jakobeha/lAzR4t
lAzR4t Shared/Code/Grid/Elem/Cell/CellPos.swift
1
1907
// // IntPos.swift // lAzR4t // // Created by Jakob Hain on 9/29/17. // Copyright © 2017 Jakob Hain. All rights reserved. // import Foundation struct CellPos: Equatable { static let origin: CellPos = CellPos(x: 0, y: 0) static func +(_ a: CellPos, _ b: CellSize) -> CellPos { return CellPos(x: a.x + b.width, y: a.y + b.height) } static func -(_ a: CellPos, _ b: CellSize) -> CellPos { return CellPos(x: a.x - b.width, y: a.y - b.height) } static func -(_ a: CellPos, _ b: CellPos) -> CellSize { return CellSize(width: a.x - b.x, height: a.y - b.y) } static func ==(_ a: CellPos, _ b: CellPos) -> Bool { return a.x == b.x && a.y == b.y } let x: Int let y: Int var toSize: CellSize { return CellSize(width: x, height: y) } func direction(of other: CellPos) -> CellDirection { return (other - self).direction } ///How far this point is from the origin, *in the direction specified*. ///Examples: ///- `(3, 3).distanceFromOrigin(in: upRight)` is 3 ///- `(3, 3).distanceFromOrigin(in: downLeft)` is -3 ///- `(3, 3).distanceFromOrigin(in: downRight)` is 0 ///- `(3, 2).distanceFromOrigin(in: upRight)` is 2.5 func distanceFromOrigin(in direction: CellDirection) -> CGFloat { switch direction { case .right: return CGFloat(self.x) case .upRight: return CGFloat(self.x + self.y) / 2 case .up: return CGFloat(self.y) case .upLeft: return CGFloat(-self.x + self.y) / 2 case .left: return CGFloat(-self.x) case .downLeft: return CGFloat(-self.x - self.y) / 2 case .down: return CGFloat(-self.y) case .downRight: return CGFloat(self.x - self.y) / 2 } } }
mit
d5de4c287688e7c792864329dde0f1f6
27.447761
75
0.536726
3.497248
false
false
false
false
banxi1988/BXCityPicker
Example/Pods/BXiOSUtils/Pod/Classes/UIViewControllerExtenstions.swift
3
1349
// // UIViewControllerExtenstions.swift // Pods // // Created by Haizhen Lee on 15/12/18. // // import UIKit public extension UIViewController{ public func bx_promptNotAuthorized(_ message:String){ let bundleNameKey = String(kCFBundleNameKey) let title = Bundle.main.infoDictionary?[bundleNameKey] as? String ?? "提示" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "设置", style: .default){ action in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) }) present(alert, animated: true, completion: nil) } } public extension UIViewController{ public func bx_shareImageUsingSystemShare(_ image:UIImage,text:String=""){ let controller = UIActivityViewController(activityItems: [image,text], applicationActivities: nil) self.present(controller, animated: true, completion: nil) } } public extension UIViewController{ public func bx_closeSelf(){ let poped = navigationController?.popViewController(animated: true) if poped == nil{ dismiss(animated: true, completion: nil) } } public func bx_navUp(){ navigationController?.popViewController(animated: true) } }
mit
98934f19b8a489480ff1c2d853914f00
28.065217
102
0.719521
4.299035
false
false
false
false
IngmarStein/swift
stdlib/private/StdlibCollectionUnittest/RangeSelection.swift
5
3342
//===--- RangeSelection.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import StdlibUnittest public enum RangeSelection { case emptyRange case leftEdge case rightEdge case middle case leftHalf case rightHalf case full case offsets(Int, Int) public var isEmpty: Bool { switch self { case .emptyRange: return true default: return false } } public func range<C : Collection>(in c: C) -> Range<C.Index> { switch self { case .emptyRange: return c.endIndex..<c.endIndex case .leftEdge: return c.startIndex..<c.startIndex case .rightEdge: return c.endIndex..<c.endIndex case .middle: let start = c.index(c.startIndex, offsetBy: c.count / 4) let end = c.index(c.startIndex, offsetBy: 3 * c.count / 4 + 1) return start..<end case .leftHalf: let start = c.startIndex let end = c.index(start, offsetBy: c.count / 2) return start..<end case .rightHalf: let start = c.index(c.startIndex, offsetBy: c.count / 2) let end = c.endIndex return start..<end case .full: return c.startIndex..<c.endIndex case let .offsets(lowerBound, upperBound): let start = c.index(c.startIndex, offsetBy: numericCast(lowerBound)) let end = c.index(c.startIndex, offsetBy: numericCast(upperBound)) return start..<end } } public func countableRange<C : Collection>(in c: C) -> CountableRange<C.Index> { return CountableRange(range(in: c)) } public func closedRange<C : Collection>(in c: C) -> ClosedRange<C.Index> { switch self { case .emptyRange: fatalError("Closed range cannot be empty") case .leftEdge: return c.startIndex...c.startIndex case .rightEdge: let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1) return beforeEnd...beforeEnd case .middle: let start = c.index(c.startIndex, offsetBy: c.count / 4) let end = c.index(c.startIndex, offsetBy: 3 * c.count / 4) return start...end case .leftHalf: let start = c.startIndex let end = c.index(start, offsetBy: c.count / 2 - 1) return start...end case .rightHalf: let start = c.index(c.startIndex, offsetBy: c.count / 2) let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1) return start...beforeEnd case .full: let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1) return c.startIndex...beforeEnd case let .offsets(lowerBound, upperBound): let start = c.index(c.startIndex, offsetBy: numericCast(lowerBound)) let end = c.index(c.startIndex, offsetBy: numericCast(upperBound)) return start...end } } public func countableClosedRange<C : Collection>(in c: C) -> CountableClosedRange<C.Index> { return CountableClosedRange(closedRange(in: c)) } }
apache-2.0
4e20269daf5b522439afe2635eb4825f
34.553191
94
0.620886
4.115764
false
false
false
false
Archerlly/ACRouter
ACRouter/Classes/ACRouterPattern.swift
1
1412
// // ACRouterPattern.swift // ACRouter // // Created by SnowCheng on 11/03/2017. // Copyright © 2017 Archerlly. All rights reserved. // import Foundation public class ACRouterPattern: ACRouterParser { public typealias HandleBlock = ([String: AnyObject]) -> AnyObject? static let PatternPlaceHolder = "~AC~" var patternString: String var sheme: String var patternPaths: [String] var priority: uint var handle: HandleBlock var matchString: String var paramsMatchDict: [String: Int] init(_ string: String, priority: uint = 0, handle: @escaping HandleBlock) { self.patternString = string self.priority = priority self.handle = handle self.sheme = ACRouterPattern.parserSheme(string) self.patternPaths = ACRouterPattern.parserPaths(string) self.paramsMatchDict = [String: Int]() var matchPaths = [String]() for i in 0..<patternPaths.count { var pathComponent = self.patternPaths[i] if pathComponent.hasPrefix(":") { let name = pathComponent.ac_dropFirst(1) self.paramsMatchDict[name] = i pathComponent = ACRouterPattern.PatternPlaceHolder } matchPaths.append(pathComponent) } self.matchString = matchPaths.joined(separator: "/") } }
mit
c8808fdd93293dd4db171a7a4850256f
26.134615
70
0.616584
4.423197
false
false
false
false
wufeiyue/FYBannerView
Example/FYBannerView/TableHeadViewController.swift
2
3154
// // TableHeadViewController.swift // FYBannerView_Example // // Created by 武飞跃 on 2018/1/22. // Copyright © 2018年 CocoaPods. All rights reserved. // import UIKit import FYBannerView struct MockModel: BannerType { var bannerId: String var data: BannerData init(origin: [String: String]) { let urlStr = origin["banner_picture_url"]! // let title = origin["banner_title"]! bannerId = "\(urlStr.hashValue)" data = .photo(url: URL(string: urlStr), placeholder: UIImage(named: "")) } } class TableHeadViewController: UIViewController { var tableView:UITableView! var bannerView: FYBannerView! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let rect = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 200) bannerView = FYBannerView(frame: rect, option: self) bannerView.pageControl.normalColor = .red bannerView.pageControl.selectorColor = .gray tableView = UITableView(frame: view.bounds, style: .plain) tableView.delegate = self tableView.dataSource = self tableView.tableHeaderView = bannerView view.addSubview(tableView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) getData { (data) in self.bannerView.dataList = data.map({ MockModel(origin: $0) }) } } deinit { print("TableHeadViewController deinit") } func getData(completion: @escaping (_ data: [[String: String]]) -> Void) { guard let url = URL(string: "http://7xt77b.com1.z0.glb.clouddn.com/fysliderview_notext.json") else { return } let request = URLRequest(url: url) let session = URLSession.shared.dataTask(with: request) { (data, response, error) in DispatchQueue.main.async { guard let data = data else { return } let dict = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any] let dataSource = dict["data"] as! [[String: String]] completion(dataSource) } } session.resume() } } extension TableHeadViewController: BannerCustomizable { var controlStyle: BannerPageControlStyle { var style = BannerPageControlStyle() style.position.y = .marginBottom(10) return style } } extension TableHeadViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "KEY") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "KEY") } return cell! } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } }
mit
82ebc85c385ffb32587610d8afad6c9a
28.952381
119
0.60159
4.708084
false
false
false
false
DannyVancura/SwifTrix
SwifTrix/Network/STNetworkInterface.swift
1
4970
// // STNetworkInterface.swift // SwifTrix // // The MIT License (MIT) // // Copyright © 2015 Daniel Vancura // // 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 private(set) var defaultNetworkInterface: STNetworkInterface? private(set) var backgroundNetworkInterface: STNetworkInterface? private(set) var ephemeralNetworkInterface: STNetworkInterface? /** A network interface serves as the interface not to a specific server, but to a specific URL session. Over an URL session, you can request or send data, either in a background task that continues after you close the app or in the foreground. */ public class STNetworkInterface: NSObject { // MARK: - // MARK: Public variables public private(set) var URLSession: NSURLSession? public private(set) var URLSessionQueue: NSOperationQueue? // MARK: - // MARK: Initialization public override init() { super.init() } // MARK: - // MARK: Session configurations /** Starts a default URL Session with the network interface as delegate */ private func startDefaultURLSession() { let sessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() self.URLSession = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil) } /** Starts a background URL Session with the network interface as delegate - parameter backgroundSessionIdentifier: Unique identifier for the background session */ @available(OSX 10.10, *) private func startBackgroundURLSession(backgroundSessionIdentifier: String) { if backgroundSessionIdentifier.isEmpty { print("Unable to start a background URL session with an empty session identifier.") return } let sessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(backgroundSessionIdentifier) self.URLSession = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil) } /** Starts an ephemeral URL session with the network interface as delegate */ private func startEphemeralURLSession() { let sessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration() self.URLSession = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue:nil) } // MARK: - // MARK: Public singleton network interfaces /** Returns a singleton default network interface. */ public var DefaultNetworkInterface: STNetworkInterface { if defaultNetworkInterface == nil { defaultNetworkInterface = STNetworkInterface() defaultNetworkInterface?.startDefaultURLSession() } return defaultNetworkInterface! } /** Returns a singleton background network interface. Allows HTTP and HTTPS uploads or downloads to be performed in the background. */ @available(OSX 10.10, *) public var BackgroundNetworkInterface: STNetworkInterface { if backgroundNetworkInterface == nil { backgroundNetworkInterface = STNetworkInterface() backgroundNetworkInterface?.startBackgroundURLSession("SwifTrix.BackgroundSession") } return backgroundNetworkInterface! } /** Returns a singleton ephemeral network interface. Operates on a configuration that uses no persistent storage for caches, cookies, or credentials. */ public var EphemeralNetworkInterface: STNetworkInterface { if ephemeralNetworkInterface == nil { ephemeralNetworkInterface = STNetworkInterface() ephemeralNetworkInterface?.startEphemeralURLSession() } return ephemeralNetworkInterface! } }
mit
dbe3f4a48af7a34a5e6f34dbab55bbb1
39.080645
241
0.721071
5.478501
false
true
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/Model/EntrySelectItem.swift
1
1076
// // EntrySelectItem.swift // MT_iOS // // Created by CHEEBOW on 2015/06/02. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit class EntrySelectItem: BaseEntryItem { var list = [String]() var selected = "" override init() { super.init() type = "select" } override func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) aCoder.encodeObject(self.list, forKey: "list") aCoder.encodeObject(self.selected, forKey: "selected") } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.list = aDecoder.decodeObjectForKey("list") as! [String] self.selected = aDecoder.decodeObjectForKey("selected") as! String } override func value()-> String { if selected.isEmpty || list.count == 0 { return "" } return selected } override func dispValue()-> String { return self.value() } override func clear() { selected = "" } }
mit
025cb383a9ac016615cb7427d9b9ee5b
21.87234
74
0.586592
4.261905
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Models/Note/Note.swift
1
5092
// // Note.swift // MEGameTracker // // Created by Emily Ivie on 9/19/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import Foundation public struct Note: Codable { enum CodingKeys: String, CodingKey { case uuid case gameVersion case shepardUuid case gameSequenceUuid case identifyingObject case text } // MARK: Constants // MARK: Properties public var rawData: Data? // transient public internal(set) var uuid: UUID public internal(set) var shepardUuid: UUID? public internal(set) var identifyingObject: IdentifyingObject public private(set) var text: String? public var gameVersion: GameVersion /// (GameModifying Protocol) /// This value's game identifier. public var gameSequenceUuid: UUID? /// (DateModifiable Protocol) /// Date when value was created. public var createdDate = Date() /// (DateModifiable Protocol) /// Date when value was last changed. public var modifiedDate = Date() /// (CloudDataStorable Protocol) /// Flag for whether the local object has changes not saved to the cloud. public var isSavedToCloud = false /// (CloudDataStorable Protocol) /// A set of any changes to the local object since the last cloud sync. public var pendingCloudChanges = CodableDictionary() /// (CloudDataStorable Protocol) /// A copy of the last cloud kit record. public var lastRecordData: Data? // MARK: Change Listeners And Change Status Flags /// (DateModifiable) Flag to indicate that there are changes pending a core data sync. public var hasUnsavedChanges = false public static var onChange = Signal<(id: String, object: Note?)>() // MARK: Initialization public init( identifyingObject: IdentifyingObject, uuid: UUID? = nil, shepardUuid: UUID? = nil, gameSequenceUuid: UUID? = nil ) { self.uuid = uuid ?? UUID() self.shepardUuid = shepardUuid ?? App.current.game?.shepard?.uuid self.gameSequenceUuid = gameSequenceUuid ?? App.current.game?.uuid self.identifyingObject = identifyingObject gameVersion = App.current.gameVersion // TODO: set to gameSequence version when missing } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) uuid = try container.decode(UUID.self, forKey: .uuid) gameVersion = try container.decodeIfPresent(GameVersion.self, forKey: .gameVersion) ?? App.current.gameVersion // default shepardUuid = try container.decodeIfPresent(UUID.self, forKey: .shepardUuid) ?? App.current.game?.shepard?.uuid // default gameSequenceUuid = try container.decodeIfPresent(UUID.self, forKey: .gameSequenceUuid) ?? App.current.game?.uuid // default identifyingObject = try container.decode( IdentifyingObject.self, forKey: .identifyingObject ) text = try container.decodeIfPresent(String.self, forKey: .text) try unserializeDateModifiableData(decoder: decoder) try unserializeGameModifyingData(decoder: decoder) try unserializeLocalCloudData(decoder: decoder) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(uuid, forKey: .uuid) try container.encode(gameVersion, forKey: .gameVersion) try container.encode(shepardUuid, forKey: .shepardUuid) try container.encode(gameSequenceUuid, forKey: .gameSequenceUuid) try container.encode(text, forKey: .text) try container.encode(identifyingObject, forKey: .identifyingObject) try serializeDateModifiableData(encoder: encoder) try serializeGameModifyingData(encoder: encoder) try serializeLocalCloudData(encoder: encoder) } } // MARK: Retrieval Functions of Related Data extension Note { public static func getDummyNote(json: String? = nil) -> Note? { // swiftlint:disable line_length let json = json ?? "{\"uuid\":1,\"shepardUuid\":1,\"identifyingObject\":{\"type\":\"Map\",\"id\":1},\"text\":\"A note.\"}" return try? defaultManager.decoder.decode(Note.self, from: json.data(using: .utf8)!) // swiftlint:enable line_length } } // MARK: Data Change Actions extension Note { public mutating func change(text: String, isSave: Bool = true, isNotify: Bool = true) { if text != self.text { self.text = text hasUnsavedChanges = true markChanged() notifySaveToCloud(fields: ["text": text]) if isSave { _ = saveAnyChanges() } if isNotify { Note.onChange.fire((id: self.uuid.uuidString, object: self)) } } } } // MARK: DateModifiable extension Note: DateModifiable {} // MARK: GameModifying extension Note: GameModifying {} // MARK: Equatable extension Note: Equatable { public static func == (_ lhs: Note, _ rhs: Note) -> Bool { // not true equality, just same db row return lhs.uuid == rhs.uuid } } //// MARK: Hashable //extension Note: Hashable { // public var hashValue: Int { return uuid.hashValue } //}
mit
4821c968318e517e0bca75b146498c33
32.715232
124
0.689648
4.183237
false
false
false
false
mihaicris/digi-cloud
Digi Cloud/Controller/Actions/NodeActionsViewController.swift
1
8352
// // NodeActionsViewController.swift // Digi Cloud // // Created by Mihai Cristescu on 20/10/16. // Copyright © 2016 Mihai Cristescu. All rights reserved. // import UIKit final class NodeActionsViewController: UITableViewController { // MARK: - Properties var onSelect: ((ActionType) -> Void)? private var location: Location private let node: Node private var actions: [ActionType] = [] // MARK: - Initializers and Deinitializers init(location: Location, node: Node) { self.location = location self.node = node super.init(style: .plain) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Overridden Methods and Properties override func viewDidLoad() { super.viewDidLoad() registerForNotificationCenter() setupViews() setupPermittedActions() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.preferredContentSize.width = 350 self.preferredContentSize.height = tableView.contentSize.height - 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return actions.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .default, reuseIdentifier: nil) cell.textLabel?.textColor = UIColor.defaultColor switch actions[indexPath.row] { case .makeShare: cell.textLabel?.text = NSLocalizedString("Share", comment: "") case .manageShare: cell.textLabel?.text = NSLocalizedString("Manage Share", comment: "") case .shareInfo: cell.textLabel?.text = NSLocalizedString("See Share Members", comment: "") case .sendDownloadLink: cell.textLabel?.text = NSLocalizedString("Send Link", comment: "") case .sendUploadLink: cell.textLabel?.text = NSLocalizedString("Receive Files", comment: "") case .makeOffline: cell.textLabel?.text = NSLocalizedString("Make available offline", comment: "") case .bookmark: cell.textLabel?.text = self.node.bookmark == nil ? NSLocalizedString("Add Bookmark", comment: "") : NSLocalizedString("Remove Bookmark", comment: "") case .rename: cell.textLabel?.text = NSLocalizedString("Rename", comment: "") case .copy: cell.textLabel?.text = NSLocalizedString("Copy", comment: "") case .move: cell.textLabel?.text = NSLocalizedString("Move", comment: "") case .delete: cell.textLabel?.text = NSLocalizedString("Delete", comment: "") cell.textLabel?.textColor = .red case .folderInfo: cell.textLabel?.text = NSLocalizedString("Folder information", comment: "") default: break } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { dismiss(animated: false) { self.onSelect?(self.actions[indexPath.row]) } } // MARK: - Helper Functions private func registerForNotificationCenter() { NotificationCenter.default.addObserver( self, selector: #selector(handleCancel), name: .UIApplicationWillResignActive, object: nil) } private func setupViews() { if navigationController != nil { title = node.name let closeButton: UIBarButtonItem = { let button = UIBarButtonItem(title: NSLocalizedString("Close", comment: ""), style: .done, target: self, action: #selector(handleCancel)) return button }() self.navigationItem.rightBarButtonItem = closeButton } else { let headerView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: AppSettings.tableViewRowHeight)) view.backgroundColor = UIColor(white: 0.95, alpha: 1.0) return view }() let iconImage: UIImageView = { let image = node.type == "dir" ? #imageLiteral(resourceName: "folder_icon") : #imageLiteral(resourceName: "file_icon") let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() let elementName: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = node.name label.font = UIFont.boldSystemFont(ofSize: 16) return label }() let separator: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor(white: 0.8, alpha: 1) return view }() headerView.addSubview(iconImage) headerView.addSubview(elementName) headerView.addSubview(separator) let offset: CGFloat = node.type == "dir" ? 20 : 18 NSLayoutConstraint.activate([ iconImage.leftAnchor.constraint(equalTo: headerView.leftAnchor, constant: offset), iconImage.centerYAnchor.constraint(equalTo: headerView.centerYAnchor), iconImage.widthAnchor.constraint(equalToConstant: 26), iconImage.heightAnchor.constraint(equalToConstant: 26), elementName.leftAnchor.constraint(equalTo: iconImage.rightAnchor, constant: 10), elementName.rightAnchor.constraint(equalTo: headerView.rightAnchor, constant: -10), elementName.centerYAnchor.constraint(equalTo: headerView.centerYAnchor), separator.leftAnchor.constraint(equalTo: headerView.leftAnchor), separator.rightAnchor.constraint(equalTo: headerView.rightAnchor), separator.heightAnchor.constraint(equalToConstant: 1 / UIScreen.main.scale) ]) tableView.tableHeaderView = headerView } tableView.isScrollEnabled = false tableView.rowHeight = AppSettings.tableViewRowHeight tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) } private func setupPermittedActions() { // order of elements in important for UI. if node.type == "dir" { if location.mount.permissions.createLink { actions.append(.sendDownloadLink) } if location.mount.permissions.createReceiver { actions.append(.sendUploadLink) } if node.mount != nil { if node.mount?.type == "export" { actions.append(.manageShare) } } else { if location.mount.permissions.owner == true { actions.append(.makeShare) } } actions.append(.bookmark) if location.mount.canWrite { actions.append(.rename) } actions.append(.copy) // Keep order in menu if location.mount.canWrite { actions.append(.move) } actions.append(.folderInfo) } else { if location.mount.permissions.createLink { actions.append(.sendDownloadLink) } if location.mount.canWrite { actions.append(.rename) } actions.append(.copy) // Keep order in menu if location.mount.canWrite { actions.append(.move) } if location.mount.canWrite { actions.append(.delete) } } } @objc private func handleCancel() { dismiss(animated: true, completion: nil) } }
mit
df050e0329c2ba1710e036b2357c2e5c
30.632576
153
0.585439
5.436849
false
false
false
false
VincenzoFreeman/CATransition
CATransition/Classes/Home/HomeViewController.swift
1
2328
// // HomeViewController.swift // CATransition // // Created by wenzhiji on 16/4/28. // Copyright © 2016年 Manager. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class HomeViewController: UICollectionViewController { private lazy var shops : [ShopItem] = [ShopItem]() let homeCell = "homeCell" override func viewDidLoad() { super.viewDidLoad() collectionView?.dataSource // 加载数据 loadData(0) } } // MARK:- 加载数据 extension HomeViewController{ func loadData(offset : Int ){ NetworkTools.shareInstance.loadHomeData(offset) { (result, error) -> () in // 校验数据 if error != nil{ print(error) return } // 获取结果 guard let resultArray = result else{ print("获取的结果不正常") return } // 遍历数据结果转为模型 for resultDict in resultArray{ let shop = ShopItem(dict: resultDict) self.shops.append(shop) } // 刷新列表 self.collectionView?.reloadData() } } } // MARK:- UICollectionView DataSource Delegate extension HomeViewController{ override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return shops.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(homeCell, forIndexPath: indexPath) as! HomeCell cell.shop = shops[indexPath.row] // 判断是否是最后显示的cell if indexPath.item == shops.count - 1{ loadData(self.shops.count) } return cell } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let photosBrowserVC = PhotosBrowserViewController() photosBrowserVC.modalTransitionStyle = .PartialCurl // 传递模型 photosBrowserVC.shops = shops photosBrowserVC.indexPath = indexPath presentViewController(photosBrowserVC, animated: true, completion: nil) } }
mit
c6a0a13eead94566ac149c112c54b8cc
29.861111
139
0.641603
5.059226
false
false
false
false
ps2/rileylink_ios
MinimedKit/Messages/MessageType.swift
1
6474
// // MessageType.swift // Naterade // // Created by Nathan Racklyeft on 9/2/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // public enum MessageType: UInt8 { case alert = 0x01 case alertCleared = 0x02 case deviceTest = 0x03 case pumpStatus = 0x04 case pumpAck = 0x06 case pumpBackfill = 0x08 case findDevice = 0x09 case deviceLink = 0x0A case errorResponse = 0x15 case writeGlucoseHistoryTimestamp = 0x28 case setBasalProfileA = 0x30 // CMD_SET_A_PROFILE case setBasalProfileB = 0x31 // CMD_SET_B_PROFILE case changeTime = 0x40 case setMaxBolus = 0x41 // CMD_SET_MAX_BOLUS case bolus = 0x42 case PumpExperiment_OP67 = 0x43 case PumpExperiment_OP68 = 0x44 case PumpExperiment_OP69 = 0x45 // CMD_SET_VAR_BOLUS_ENABLE case selectBasalProfile = 0x4a case changeTempBasal = 0x4c case suspendResume = 0x4d case PumpExperiment_OP80 = 0x50 case setRemoteControlID = 0x51 // CMD_SET_RF_REMOTE_ID case PumpExperiment_OP82 = 0x52 // CMD_SET_BLOCK_ENABLE case setLanguage = 0x53 case PumpExperiment_OP84 = 0x54 // CMD_SET_ALERT_TYPE case PumpExperiment_OP85 = 0x55 // CMD_SET_PATTERNS_ENABLE case PumpExperiment_OP86 = 0x56 case setRemoteControlEnabled = 0x57 // CMD_SET_RF_ENABLE case PumpExperiment_OP88 = 0x58 // CMD_SET_INSULIN_ACTION_TYPE case PumpExperiment_OP89 = 0x59 case PumpExperiment_OP90 = 0x5a case buttonPress = 0x5b case PumpExperiment_OP92 = 0x5c case powerOn = 0x5d case setBolusWizardEnabled1 = 0x61 case setBolusWizardEnabled2 = 0x62 case setBolusWizardEnabled3 = 0x63 case setBolusWizardEnabled4 = 0x64 case setBolusWizardEnabled5 = 0x65 case setAlarmClockEnable = 0x67 case setMaxBasalRate = 0x6e // CMD_SET_MAX_BASAL case setBasalProfileStandard = 0x6f // CMD_SET_STD_PROFILE case readTime = 0x70 case getBattery = 0x72 case readRemainingInsulin = 0x73 case readFirmwareVersion = 0x74 case readErrorStatus = 0x75 case readRemoteControlIDs = 0x76 // CMD_READ_REMOTE_CTRL_IDS case getHistoryPage = 0x80 case getPumpModel = 0x8d case readProfileSTD512 = 0x92 case readProfileA512 = 0x93 case readProfileB512 = 0x94 case readTempBasal = 0x98 case getGlucosePage = 0x9A case readCurrentPageNumber = 0x9d case readSettings = 0xc0 case readCurrentGlucosePage = 0xcd case readPumpStatus = 0xce case unknown_e2 = 0xe2 // a7594040e214190226330000000000021f99011801e00103012c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 case unknown_e6 = 0xe6 // a7594040e60200190000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 case settingsChangeCounter = 0xec // Body[3] increments by 1 after changing certain settings 0200af0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 case readOtherDevicesIDs = 0xf0 case readCaptureEventEnabled = 0xf1 // Body[1] encodes the bool state 0101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 case changeCaptureEventEnable = 0xf2 case readOtherDevicesStatus = 0xf3 var decodeType: DecodableMessageBody.Type { switch self { case .alert: return MySentryAlertMessageBody.self case .alertCleared: return MySentryAlertClearedMessageBody.self case .pumpStatus: return MySentryPumpStatusMessageBody.self case .pumpAck: return PumpAckMessageBody.self case .readSettings: return ReadSettingsCarelinkMessageBody.self case .readTempBasal: return ReadTempBasalCarelinkMessageBody.self case .readTime: return ReadTimeCarelinkMessageBody.self case .findDevice: return FindDeviceMessageBody.self case .deviceLink: return DeviceLinkMessageBody.self case .buttonPress: return ButtonPressCarelinkMessageBody.self case .getPumpModel: return GetPumpModelCarelinkMessageBody.self case .readProfileSTD512: return DataFrameMessageBody.self case .readProfileA512: return DataFrameMessageBody.self case .readProfileB512: return DataFrameMessageBody.self case .getHistoryPage: return GetHistoryPageCarelinkMessageBody.self case .getBattery: return GetBatteryCarelinkMessageBody.self case .readRemainingInsulin: return ReadRemainingInsulinMessageBody.self case .readPumpStatus: return ReadPumpStatusMessageBody.self case .readCurrentGlucosePage: return ReadCurrentGlucosePageMessageBody.self case .readCurrentPageNumber: return ReadCurrentPageNumberMessageBody.self case .getGlucosePage: return GetGlucosePageMessageBody.self case .errorResponse: return PumpErrorMessageBody.self case .readOtherDevicesIDs: return ReadOtherDevicesIDsMessageBody.self case .readOtherDevicesStatus: return ReadOtherDevicesStatusMessageBody.self case .readRemoteControlIDs: return ReadRemoteControlIDsMessageBody.self case .readFirmwareVersion: return GetPumpFirmwareVersionMessageBody.self default: return UnknownMessageBody.self } } }
mit
3273eb251c2cc25766df5513e99cb20f
41.86755
235
0.62892
4.724818
false
false
false
false
ShareKit/ShareKit-Demo-App
ShareKit Swift Demo App (CocoaPods)/ExampleShareFileViewController.swift
1
3764
// // ExampleShareFileViewController.swift // ShareKit Swift Demo App (CocoaPods) // // Created by Vilém Kurz on 14/12/2017. // Copyright © 2017 Vilém Kurz. All rights reserved. // import UIKit import ShareKit class ExampleShareFileViewController: UITableViewController { //Configuration let shareFileWithPath = true let shareLargeVideo = true let cellIdentifier = "fileTypeToShare" let tableViewModel = ["PDF", "Video", "Audio", "Image"] override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) tableView.tableFooterView = UITableViewHeaderFooterView(frame: .zero) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableViewModel.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let result = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) result.textLabel?.text = tableViewModel[indexPath.row] return result } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var item: SHKItem switch indexPath.row { case 0: item = makePDFItem() case 1: item = makeVideoItem() case 2: item = makeAudioItem() case 3: item = makeImageItem() default: return } if let sourceView = tableView.cellForRow(at: indexPath) { presentSHKAlertController(with: item, sourceView: sourceView, sourceRect: sourceView.bounds) } } private func makePDFItem() -> SHKItem { let filePath = Bundle.main.path(forResource: "example", ofType: "pdf")! if shareFileWithPath { return SHKItem.filePath(filePath, title: "My Awesome PDF") as! SHKItem } else { return makeDataItem(from: filePath, filename: "Awesome.pdf", title: "My Awesome PDF") } } private func makeVideoItem() -> SHKItem { var filePath: String if shareLargeVideo { filePath = Bundle.main.path(forResource: "demo_large_video_share", ofType: "mp4")! } else { filePath = Bundle.main.path(forResource: "demo_video_share", ofType: "mov")! } if shareFileWithPath { return SHKItem.filePath(filePath, title: "Impressionism - blue ball") as! SHKItem } else { return makeDataItem(from: filePath, filename: "demo_video_share.mov", title: "Impressionism - blue ball") } } private func makeAudioItem() -> SHKItem { let filePath = Bundle.main.path(forResource: "demo_audio_share", ofType: "mp3")! if shareFileWithPath { return SHKItem.filePath(filePath, title: "Demo audio beat") as! SHKItem } else { return makeDataItem(from: filePath, filename: "demo_audio_share.mp3", title: "Demo audio beat") } } private func makeImageItem() -> SHKItem { let filePath = Bundle.main.path(forResource: "sanFran", ofType: "jpg")! if shareFileWithPath { return SHKItem.filePath(filePath, title: "San Francisco") as! SHKItem } else { return makeDataItem(from: filePath, filename: "sanFran.jpg", title: "San Francisco") } } private func makeDataItem(from filePath: String, filename: String, title: String) -> SHKItem { let fileURL = URL(fileURLWithPath: filePath) let fileData = try? Data(contentsOf: fileURL) return SHKItem.fileData(fileData, filename: filename, title: title) as! SHKItem } }
mit
87dcda647161be10c3f98132fe37bc48
35.163462
117
0.641053
4.493429
false
false
false
false
erik/sketches
projects/jot/Jot/Model/JournalEntry+CoreData.swift
1
1617
import CoreData import Foundation public extension JournalEntry { static func getOrCreateFor(date: Date, using: NSManagedObjectContext) -> JournalEntry { let fetchRequest = JournalEntry.fetchRequest() fetchRequest.predicate = NSPredicate(format: "%K == %@", #keyPath(JournalEntry.date), date as NSDate) do { if let journal = (try using.fetch(fetchRequest) as [JournalEntry]).first { return journal } } catch { print("failed to fetch JournalEntry \(error)") } let journal = JournalEntry(context: using) journal.date = Calendar.current.startOfDay(for: Date()) using.insert(journal) return journal } func addTodo(of task: String, using moc: NSManagedObjectContext) { let todoItem = TodoItem(context: moc) moc.performAndWait { todoItem.journalEntry = self todoItem.createdAt = Date() todoItem.isRemoved = false todoItem.isCompleted = false todoItem.task = task self.addToTodoItems(todoItem) moc.insert(todoItem) try! moc.save() } } // TODO: This feels like a hack, is this necessary? var noteOrEmpty: String { get { note ?? "" } set { print("setting = \(newValue)"); note = newValue } } var todoItemsArray: [TodoItem] { let set = (todoItems?.set ?? []) as! Set<TodoItem> return set.sorted { ($0.isCompleted ? 1 : 0, $0.createdAt!) < ($1.isCompleted ? 1 : 0, $1.createdAt!) } } }
agpl-3.0
e4be00632629647bf9604e9195188f85
29.509434
109
0.579468
4.504178
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Journey/Cells/MilestoneCell.swift
1
4261
// // CurrentMilestoneCell.swift // Steps4Impact // // Created by Aalim Mulji on 11/17/19. // Copyright © 2019 AKDN. All rights reserved. // import UIKit protocol MilestoneNameButtonDelegate: AnyObject { func milestoneNameButtonTapped(sequence: Int) } struct MilestoneContext: CellContext { var identifier: String = MilestoneCell.identifier var sequence = 0 var distance = 0 var name = "" var flagName = "" var journeyMap = "" var description = "" var title = "" var subTitle = "" var media = "" var content = "" var status: MilestoneStatus = .notCompleted } class MilestoneCell: ConfigurableTableViewCell { static let identifier: String = "MilestoneCell" weak var delegate: MilestoneNameButtonDelegate? let circle: UIView = { var view = UIView(frame: .zero) view.layer.cornerRadius = Style.Size.s12 return view }() let verticalBar: UIView = { var view = UIView(frame: .zero) view.frame.size.width = Style.Padding.p2 return view }() let milestoneCountLabel: UILabel = { var label = UILabel(typography: .smallRegular) return label }() let milestoneNameButton: UIButton = { var button = UIButton() button.contentHorizontalAlignment = .left button.titleLabel?.font = UIFont.systemFont(ofSize: Style.Size.s16, weight: .regular) return button }() override func commonInit() { super.commonInit() contentView.addSubview(circle) { $0.top.equalToSuperview() $0.leading.equalToSuperview().offset(Style.Padding.p16) $0.width.height.equalTo(Style.Size.s24) } contentView.addSubview(milestoneCountLabel) { $0.top.equalToSuperview() $0.leading.equalTo(circle.snp.trailing).offset(Style.Padding.p12) $0.trailing.equalToSuperview().inset(Style.Padding.p12) $0.height.equalTo(Style.Size.s24) } contentView.addSubview(milestoneNameButton) { $0.top.equalTo(milestoneCountLabel.snp.bottom).offset(Style.Padding.p4) $0.leading.equalTo(circle.snp.trailing).offset(Style.Padding.p12) $0.trailing.equalToSuperview().inset(Style.Padding.p12) $0.height.equalTo(Style.Size.s24) $0.bottom.equalToSuperview().inset(Style.Size.s64) } contentView.addSubview(verticalBar) { $0.top.bottom.equalToSuperview() $0.centerX.equalTo(circle) $0.width.equalTo(Style.Padding.p2) } milestoneNameButton.addTarget(self, action: #selector(milestoneNameButtonPressed), for: .touchUpInside) contentView.bringSubviewToFront(circle) } func configure(context: CellContext) { guard let milestone = context as? MilestoneContext else { return } switch milestone.status { case .notCompleted: circle.backgroundColor = Style.Colors.Seperator verticalBar.backgroundColor = Style.Colors.Seperator milestoneCountLabel.textColor = Style.Colors.FoundationGrey milestoneNameButton.setTitleColor(Style.Colors.black, for: .normal) milestoneNameButton.isEnabled = false case .completed: circle.backgroundColor = Style.Colors.FoundationGreen verticalBar.backgroundColor = Style.Colors.FoundationGreen milestoneCountLabel.textColor = Style.Colors.black milestoneNameButton.setTitleColor(Style.Colors.blue, for: .normal) milestoneNameButton.isEnabled = true case .current: circle.backgroundColor = Style.Colors.FoundationGreen verticalBar.backgroundColor = Style.Colors.FoundationGreen milestoneCountLabel.textColor = Style.Colors.black milestoneNameButton.setTitleColor(Style.Colors.blue, for: .normal) milestoneNameButton.isEnabled = true } if milestone.sequence == 0 { milestoneCountLabel.text = "Start" milestoneNameButton.isHidden = true } else { milestoneNameButton.isHidden = false milestoneCountLabel.text = "Milestone \(milestone.sequence)/8" } if milestone.sequence == 8 { verticalBar.isHidden = true } else { verticalBar.isHidden = false } milestoneNameButton.setTitle("\(milestone.name)", for: .normal) milestoneNameButton.tag = milestone.sequence } @objc func milestoneNameButtonPressed(button: UIButton) { delegate?.milestoneNameButtonTapped(sequence: button.tag) } }
bsd-3-clause
5307af4a2b6b21fa7507dcd3e8c0df56
30.791045
107
0.711502
4.143969
false
false
false
false
tinrobots/CoreDataPlus
Tests/NSEntityDescriptionUtilsTests.swift
1
10913
// CoreDataPlus import XCTest import CoreData @testable import CoreDataPlus fileprivate extension NSManagedObject { convenience init(usingContext context: NSManagedObjectContext) { let name = String(describing: type(of: self)) let entity = NSEntityDescription.entity(forEntityName: name, in: context)! self.init(entity: entity, insertInto: context) } } final class NSEntityDescriptionUtilsTests: InMemoryTestCase { func testEntity() { let context = container.viewContext let expensiveCar = ExpensiveSportCar(context: context) let entityNames = expensiveCar.entity.hierarchyEntities().compactMap { $0.name} XCTAssertTrue(entityNames.count == 2) XCTAssertTrue(entityNames.contains(Car.entityName)) XCTAssertTrue(entityNames.contains(SportCar.entityName)) XCTAssertFalse(entityNames.contains(ExpensiveSportCar.entityName), "The hierarchy should contain only super entities") } func testTopMostEntity() { /// Making sure that all the necessary bits are available guard let model = container.viewContext.persistentStoreCoordinator?.managedObjectModel else { XCTFail("Missing Model") return } let entities = model.entitiesByName.keys guard model.entitiesByName.keys.contains("Car") else { XCTFail("Car Entity not found; available entities: \(entities)") return } // Car.entity().name can be nil while running tests // To avoid some random failed tests, the entity is created by looking in a context. guard let carEntity = NSEntityDescription.entity(forEntityName: Car.entityName, in: container.viewContext) else { XCTFail("Car Entity Not Found.") return } guard let _ = carEntity.name else { fatalError("\(carEntity) should have a name.") } // Using a custom init to avoid some problems during tests. let expensiveCar = ExpensiveSportCar(usingContext: container.viewContext) let topMostAncestorEntityForExpensiveCar = expensiveCar.entity.topMostEntity XCTAssertTrue(topMostAncestorEntityForExpensiveCar == carEntity, "\(topMostAncestorEntityForExpensiveCar) should be a Car entity \(String(describing: topMostAncestorEntityForExpensiveCar.name)).") let car = Car(usingContext: container.viewContext) let topMostAncestorEntity = car.entity.topMostEntity XCTAssertTrue(topMostAncestorEntity == carEntity, "\(topMostAncestorEntity) should be a Car entity.") } func testCommonEntityAncestor() { let context = container.viewContext do { let expensiveSportCar = ExpensiveSportCar(context: context) let sportCar = SportCar(context: context) let ancestorCommontEntity = expensiveSportCar.entity.commonEntityAncestor(with: sportCar.entity) XCTAssertNotNil(ancestorCommontEntity) XCTAssertTrue(ancestorCommontEntity == sportCar.entity) } do { let sportCar = SportCar(context: context) let expensiveSportCar = ExpensiveSportCar(context: context) let ancestorCommontEntity = sportCar.entity.commonEntityAncestor(with: expensiveSportCar.entity) XCTAssertNotNil(ancestorCommontEntity) XCTAssertTrue(ancestorCommontEntity == sportCar.entity) } do { let expensiveSportCar = ExpensiveSportCar(context: context) let expensiveSportCar2 = ExpensiveSportCar(context: context) let ancestorCommontEntity = expensiveSportCar.entity.commonEntityAncestor(with: expensiveSportCar2.entity) XCTAssertNotNil(ancestorCommontEntity) XCTAssertTrue(ancestorCommontEntity == expensiveSportCar2.entity) } do { let sportCar = SportCar(context: context) let sportCar2 = SportCar(context: context) let ancestorCommontEntity = sportCar.entity.commonEntityAncestor(with: sportCar2.entity) XCTAssertNotNil(ancestorCommontEntity) XCTAssertTrue(ancestorCommontEntity == sportCar.entity) } do { let sportCar = SportCar(context: context) let car = Car(context: context) let ancestorCommontEntity = sportCar.entity.commonEntityAncestor(with: car.entity) XCTAssertNotNil(ancestorCommontEntity) XCTAssertTrue(ancestorCommontEntity == car.entity) } do { let car = Car(context: context) let sportCar = SportCar(context: context) let ancestorCommontEntity = car.entity.commonEntityAncestor(with: sportCar.entity) XCTAssertNotNil(ancestorCommontEntity) XCTAssertTrue(ancestorCommontEntity == car.entity) } do { let sportCar = SportCar(context: context) let person = Person(context: context) let ancestorCommontEntity = sportCar.entity.commonEntityAncestor(with: person.entity) XCTAssertNil(ancestorCommontEntity) } do { let sportCar = SportCar(context: context) let person = Person(context: context) let ancestorCommontEntity = person.entity.commonEntityAncestor(with: sportCar.entity) XCTAssertNil(ancestorCommontEntity) } } func testEntitiesKeepingOnlyCommonEntityAncestors() { let context = container.viewContext do { let entities = [ExpensiveSportCar(context: context).entity, ExpensiveSportCar(context: context).entity, SportCar(context: context).entity, SportCar(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == SportCar(context: context).entity) } do { let entities = [ExpensiveSportCar(context: context).entity, ExpensiveSportCar(context: context).entity, SportCar(context: context).entity, Car(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == Car(context: context).entity) } do { let entities = [Car(context: context).entity, ExpensiveSportCar(context: context).entity, ExpensiveSportCar(context: context).entity, SportCar(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == Car(context: context).entity) } do { let entities = [SportCar(context: context).entity, Car(context: context).entity, ExpensiveSportCar(context: context).entity, ExpensiveSportCar(context: context).entity, ] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == Car(context: context).entity) } do { let entities = [Car(context: context).entity, Car(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == Car(context: context).entity) } do { let entities = [SportCar(context: context).entity, Car(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == Car(context: context).entity) } do { let entities = [ExpensiveSportCar(context: context).entity, ExpensiveSportCar(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == ExpensiveSportCar(context: context).entity) } do { let entities = [ExpensiveSportCar(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == ExpensiveSportCar(context: context).entity) } do { let entities = [SportCar(context: context).entity, SportCar(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == SportCar(context: context).entity) } do { let entities = [SportCar(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 1) XCTAssertTrue(ancestors.first == SportCar(context: context).entity) } /// 2+ do { let entities = [ExpensiveSportCar(context: context).entity, ExpensiveSportCar(context: context).entity, SportCar(context: context).entity, SportCar(context: context).entity, Person(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 2) XCTAssertTrue(ancestors.contains(SportCar(context: context).entity)) XCTAssertTrue(ancestors.contains(Person(context: context).entity)) } do { let entities = [ExpensiveSportCar(context: context).entity, ExpensiveSportCar(context: context).entity, SportCar(context: context).entity, SportCar(context: context).entity, Person(context: context).entity, Car(context: context).entity] let ancestors = Set(entities).entitiesKeepingOnlyCommonEntityAncestors() XCTAssertTrue(!ancestors.isEmpty) XCTAssertTrue(ancestors.count == 2) XCTAssertTrue(ancestors.contains(Car(context: context).entity)) XCTAssertTrue(ancestors.contains(Person(context: context).entity)) } } func testIsSubEntity() { let context = container.viewContext let car = Car(context: context).entity let sportCar = SportCar(context: context).entity let expensiveCar = ExpensiveSportCar(context: context).entity XCTAssertFalse(car.isSubEntity(of: car)) XCTAssertFalse(car.isSubEntity(of: car, recursive: true)) XCTAssertTrue(sportCar.isSubEntity(of: car)) XCTAssertTrue(sportCar.isSubEntity(of: car, recursive: true)) XCTAssertFalse(expensiveCar.isSubEntity(of: car)) // ExpensiveSportCar is a sub entity of SportCar XCTAssertTrue(expensiveCar.isSubEntity(of: car, recursive: true)) XCTAssertTrue(expensiveCar.isSubEntity(of: sportCar)) XCTAssertTrue(expensiveCar.isSubEntity(of: sportCar, recursive: true)) XCTAssertFalse(car.isSubEntity(of: expensiveCar)) XCTAssertFalse(car.isSubEntity(of: expensiveCar, recursive: true)) XCTAssertFalse(sportCar.isSubEntity(of: expensiveCar)) XCTAssertFalse(sportCar.isSubEntity(of: expensiveCar, recursive: true)) } }
mit
183f0cb22820f18bbf04cf98a6ff0b33
40.337121
242
0.73582
4.296457
false
false
false
false
tonystone/geofeatures2
Tests/GeoFeaturesTests/LinearRingTests.swift
1
58799
/// /// LinearRingTests.swift /// /// Copyright (c) 2016 Tony Stone /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Created by Tony Stone on 2/10/2016. /// import XCTest @testable import GeoFeatures /// /// NOTE: This file was auto generated by gyb from file CoordinateCollectionTypesTests.swift.gyb using the following command. /// /// gyb --line-directive '' -DGeometryType=LinearRing -o LinearRing.swift CoordinateCollectionTypesTests.swift.gyb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// // MARK: - Coordinate, FloatingPrecision, Cartesian - class LinearRingCoordinate2DFloatingPrecisionCartesianTests: XCTestCase { let precision = Floating() let cs = Cartesian() // MARK: Construction func testInitWithPrecisionAndCRS() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty, true) } func testInitWithPrecision() { XCTAssertEqual(LinearRing(precision: precision).precision as? Floating, precision) } func testInitWithCRS() { XCTAssertEqual(LinearRing(coordinateSystem: cs).coordinateSystem as? Cartesian, cs) } func testInitConverting() { let input = LinearRing(converting: LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitCopy() { let input = LinearRing(other: LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitWithArrayLiteral() { let input: LinearRing = [Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)] let expected = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)]) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } // MARK: CustomStringConvertible & CustomDebugStringConvertible func testDescription() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0), (x: 2.0, y: 2.0)])" XCTAssertEqual(input.description, expected) } func testDebugDescription() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0), (x: 2.0, y: 2.0)])" XCTAssertEqual(input.debugDescription, expected) } // MARK: MutableCollection Conformance func testStartIndex() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) let expected = 0 XCTAssertEqual(input.startIndex, expected) } func testEndIndex() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) let expected = 2 XCTAssertEqual(input.endIndex, expected) } func testIndexAfter() { let input = 0 let expected = 1 XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs).index(after: input), expected) } func testSubscriptGet() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertEqual(input[1], Coordinate(x: 2.0, y: 2.0)) } func testSubscriptSet() { var input = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) input[1] = Coordinate(x: 1.0, y: 1.0) XCTAssertEqual(input[1], Coordinate(x: 1.0, y: 1.0)) } // MARK: RangeReplaceableCollection Conformance func testReplaceSubrangeAppend() { var input = (geometry: LinearRing(precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 1.0, y: 1.0)]) let expected = [Coordinate(x: 1.0, y: 1.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeInsert() { var input = (geometry: LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.0, y: 2.0)]) let expected = [Coordinate(x: 2.0, y: 2.0), Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeReplace() { var input = (geometry: LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 1.0, y: 1.0)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.0, y: 2.0)]) let expected = [Coordinate(x: 2.0, y: 2.0), Coordinate(x: 1.0, y: 1.0)] input.geometry.replaceSubrange(0..<1, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testEquals() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs).equals(LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs)), true) } func testIsEmpty() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty(), true) } func testIsEmptyFalse() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs).isEmpty(), false) } func testCount() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs).count, 2) } } // MARK: - Coordinate, FloatingPrecision, Cartesian - class LinearRingCoordinate2DMFloatingPrecisionCartesianTests: XCTestCase { let precision = Floating() let cs = Cartesian() // MARK: Construction func testInitWithPrecisionAndCRS() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty, true) } func testInitWithPrecision() { XCTAssertEqual(LinearRing(precision: precision).precision as? Floating, precision) } func testInitWithCRS() { XCTAssertEqual(LinearRing(coordinateSystem: cs).coordinateSystem as? Cartesian, cs) } func testInitConverting() { let input = LinearRing(converting: LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitCopy() { let input = LinearRing(other: LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitWithArrayLiteral() { let input: LinearRing = [Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)] let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)]) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } // MARK: CustomStringConvertible & CustomDebugStringConvertible func testDescription() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, m: 1.0), (x: 2.0, y: 2.0, m: 2.0)])" XCTAssertEqual(input.description, expected) } func testDebugDescription() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, m: 1.0), (x: 2.0, y: 2.0, m: 2.0)])" XCTAssertEqual(input.debugDescription, expected) } // MARK: MutableCollection Conformance func testStartIndex() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) let expected = 0 XCTAssertEqual(input.startIndex, expected) } func testEndIndex() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) let expected = 2 XCTAssertEqual(input.endIndex, expected) } func testIndexAfter() { let input = 0 let expected = 1 XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs).index(after: input), expected) } func testSubscriptGet() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertEqual(input[1], Coordinate(x: 2.0, y: 2.0, m: 2.0)) } func testSubscriptSet() { var input = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) input[1] = Coordinate(x: 1.0, y: 1.0, m: 1.0) XCTAssertEqual(input[1], Coordinate(x: 1.0, y: 1.0, m: 1.0)) } // MARK: RangeReplaceableCollection Conformance func testReplaceSubrangeAppend() { var input = (geometry: LinearRing(precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 1.0, y: 1.0, m: 1.0)]) let expected = [Coordinate(x: 1.0, y: 1.0, m: 1.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeInsert() { var input = (geometry: LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.0, y: 2.0, m: 2.0)]) let expected = [Coordinate(x: 2.0, y: 2.0, m: 2.0), Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeReplace() { var input = (geometry: LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 1.0, y: 1.0, m: 1.0)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.0, y: 2.0, m: 2.0)]) let expected = [Coordinate(x: 2.0, y: 2.0, m: 2.0), Coordinate(x: 1.0, y: 1.0, m: 1.0)] input.geometry.replaceSubrange(0..<1, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testEquals() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs).equals(LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs)), true) } func testIsEmpty() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty(), true) } func testIsEmptyFalse() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs).isEmpty(), false) } func testCount() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs).count, 2) } } // MARK: - Coordinate, FloatingPrecision, Cartesian - class LinearRingCoordinate3DFloatingPrecisionCartesianTests: XCTestCase { let precision = Floating() let cs = Cartesian() // MARK: Construction func testInitWithPrecisionAndCRS() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty, true) } func testInitWithPrecision() { XCTAssertEqual(LinearRing(precision: precision).precision as? Floating, precision) } func testInitWithCRS() { XCTAssertEqual(LinearRing(coordinateSystem: cs).coordinateSystem as? Cartesian, cs) } func testInitConverting() { let input = LinearRing(converting: LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitCopy() { let input = LinearRing(other: LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitWithArrayLiteral() { let input: LinearRing = [Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)] let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)]) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } // MARK: CustomStringConvertible & CustomDebugStringConvertible func testDescription() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, z: 1.0), (x: 2.0, y: 2.0, z: 2.0)])" XCTAssertEqual(input.description, expected) } func testDebugDescription() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, z: 1.0), (x: 2.0, y: 2.0, z: 2.0)])" XCTAssertEqual(input.debugDescription, expected) } // MARK: MutableCollection Conformance func testStartIndex() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) let expected = 0 XCTAssertEqual(input.startIndex, expected) } func testEndIndex() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) let expected = 2 XCTAssertEqual(input.endIndex, expected) } func testIndexAfter() { let input = 0 let expected = 1 XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs).index(after: input), expected) } func testSubscriptGet() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertEqual(input[1], Coordinate(x: 2.0, y: 2.0, z: 2.0)) } func testSubscriptSet() { var input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) input[1] = Coordinate(x: 1.0, y: 1.0, z: 1.0) XCTAssertEqual(input[1], Coordinate(x: 1.0, y: 1.0, z: 1.0)) } // MARK: RangeReplaceableCollection Conformance func testReplaceSubrangeAppend() { var input = (geometry: LinearRing(precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 1.0, y: 1.0, z: 1.0)]) let expected = [Coordinate(x: 1.0, y: 1.0, z: 1.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeInsert() { var input = (geometry: LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.0, y: 2.0, z: 2.0)]) let expected = [Coordinate(x: 2.0, y: 2.0, z: 2.0), Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeReplace() { var input = (geometry: LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 1.0, y: 1.0, z: 1.0)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.0, y: 2.0, z: 2.0)]) let expected = [Coordinate(x: 2.0, y: 2.0, z: 2.0), Coordinate(x: 1.0, y: 1.0, z: 1.0)] input.geometry.replaceSubrange(0..<1, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testEquals() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs).equals(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs)), true) } func testIsEmpty() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty(), true) } func testIsEmptyFalse() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs).isEmpty(), false) } func testCount() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs).count, 2) } } // MARK: - Coordinate, FloatingPrecision, Cartesian - class LinearRingCoordinate3DMFloatingPrecisionCartesianTests: XCTestCase { let precision = Floating() let cs = Cartesian() // MARK: Construction func testInitWithPrecisionAndCRS() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty, true) } func testInitWithPrecision() { XCTAssertEqual(LinearRing(precision: precision).precision as? Floating, precision) } func testInitWithCRS() { XCTAssertEqual(LinearRing(coordinateSystem: cs).coordinateSystem as? Cartesian, cs) } func testInitConverting() { let input = LinearRing(converting: LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitCopy() { let input = LinearRing(other: LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitWithArrayLiteral() { let input: LinearRing = [Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)] let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)]) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } // MARK: CustomStringConvertible & CustomDebugStringConvertible func testDescription() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, z: 1.0, m: 1.0), (x: 2.0, y: 2.0, z: 2.0, m: 2.0)])" XCTAssertEqual(input.description, expected) } func testDebugDescription() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, z: 1.0, m: 1.0), (x: 2.0, y: 2.0, z: 2.0, m: 2.0)])" XCTAssertEqual(input.debugDescription, expected) } // MARK: MutableCollection Conformance func testStartIndex() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) let expected = 0 XCTAssertEqual(input.startIndex, expected) } func testEndIndex() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) let expected = 2 XCTAssertEqual(input.endIndex, expected) } func testIndexAfter() { let input = 0 let expected = 1 XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs).index(after: input), expected) } func testSubscriptGet() { let input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertEqual(input[1], Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)) } func testSubscriptSet() { var input = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) input[1] = Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0) XCTAssertEqual(input[1], Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0)) } // MARK: RangeReplaceableCollection Conformance func testReplaceSubrangeAppend() { var input = (geometry: LinearRing(precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0)]) let expected = [Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeInsert() { var input = (geometry: LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)]) let expected = [Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0), Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeReplace() { var input = (geometry: LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)]) let expected = [Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0), Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0)] input.geometry.replaceSubrange(0..<1, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testEquals() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs).equals(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs)), true) } func testIsEmpty() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty(), true) } func testIsEmptyFalse() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs).isEmpty(), false) } func testCount() { XCTAssertEqual(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs).count, 2) } } // MARK: - Coordinate, Fixed, Cartesian - class LinearRingCoordinate2DFixedCartesianTests: XCTestCase { let precision = Fixed(scale: 100) let cs = Cartesian() // MARK: Construction func testInitWithPrecisionAndCRS() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty, true) } func testInitWithPrecision() { XCTAssertEqual(LinearRing(precision: precision).precision as? Fixed, precision) } func testInitWithCRS() { XCTAssertEqual(LinearRing(coordinateSystem: cs).coordinateSystem as? Cartesian, cs) } func testInitConverting() { let input = LinearRing(converting: LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitCopy() { let input = LinearRing(other: LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitWithArrayLiteral() { let input: LinearRing = [Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)] let expected = LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)]) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } // MARK: CustomStringConvertible & CustomDebugStringConvertible func testDescription() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0), (x: 2.0, y: 2.0)])" XCTAssertEqual(input.description, expected) } func testDebugDescription() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0), (x: 2.0, y: 2.0)])" XCTAssertEqual(input.debugDescription, expected) } // MARK: MutableCollection Conformance func testStartIndex() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs) let expected = 0 XCTAssertEqual(input.startIndex, expected) } func testEndIndex() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs) let expected = 2 XCTAssertEqual(input.endIndex, expected) } func testIndexAfter() { let input = 0 let expected = 1 XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs).index(after: input), expected) } func testSubscriptGet() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs) XCTAssertEqual(input[1], Coordinate(x: 2.0, y: 2.0)) } func testSubscriptSet() { var input = LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs) input[1] = Coordinate(x: 1.001, y: 1.001) XCTAssertEqual(input[1], Coordinate(x: 1.0, y: 1.0)) } // MARK: RangeReplaceableCollection Conformance func testReplaceSubrangeAppend() { var input = (geometry: LinearRing(precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 1.001, y: 1.001)]) let expected = [Coordinate(x: 1.0, y: 1.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeInsert() { var input = (geometry: LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.002, y: 2.002)]) let expected = [Coordinate(x: 2.0, y: 2.0), Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeReplace() { var input = (geometry: LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 1.001, y: 1.001)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.002, y: 2.002)]) let expected = [Coordinate(x: 2.0, y: 2.0), Coordinate(x: 1.0, y: 1.0)] input.geometry.replaceSubrange(0..<1, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testEquals() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs).equals(LinearRing([Coordinate(x: 1.0, y: 1.0), Coordinate(x: 2.0, y: 2.0)], precision: precision, coordinateSystem: cs)), true) } func testIsEmpty() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty(), true) } func testIsEmptyFalse() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs).isEmpty(), false) } func testCount() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001), Coordinate(x: 2.002, y: 2.002)], precision: precision, coordinateSystem: cs).count, 2) } } // MARK: - Coordinate, Fixed, Cartesian - class LinearRingCoordinate2DMFixedCartesianTests: XCTestCase { let precision = Fixed(scale: 100) let cs = Cartesian() // MARK: Construction func testInitWithPrecisionAndCRS() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty, true) } func testInitWithPrecision() { XCTAssertEqual(LinearRing(precision: precision).precision as? Fixed, precision) } func testInitWithCRS() { XCTAssertEqual(LinearRing(coordinateSystem: cs).coordinateSystem as? Cartesian, cs) } func testInitConverting() { let input = LinearRing(converting: LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitCopy() { let input = LinearRing(other: LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitWithArrayLiteral() { let input: LinearRing = [Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)] let expected = LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)]) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } // MARK: CustomStringConvertible & CustomDebugStringConvertible func testDescription() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, m: 1.0), (x: 2.0, y: 2.0, m: 2.0)])" XCTAssertEqual(input.description, expected) } func testDebugDescription() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, m: 1.0), (x: 2.0, y: 2.0, m: 2.0)])" XCTAssertEqual(input.debugDescription, expected) } // MARK: MutableCollection Conformance func testStartIndex() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) let expected = 0 XCTAssertEqual(input.startIndex, expected) } func testEndIndex() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) let expected = 2 XCTAssertEqual(input.endIndex, expected) } func testIndexAfter() { let input = 0 let expected = 1 XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs).index(after: input), expected) } func testSubscriptGet() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) XCTAssertEqual(input[1], Coordinate(x: 2.0, y: 2.0, m: 2.0)) } func testSubscriptSet() { var input = LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) input[1] = Coordinate(x: 1.001, y: 1.001, m: 1.001) XCTAssertEqual(input[1], Coordinate(x: 1.0, y: 1.0, m: 1.0)) } // MARK: RangeReplaceableCollection Conformance func testReplaceSubrangeAppend() { var input = (geometry: LinearRing(precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 1.001, y: 1.001, m: 1.001)]) let expected = [Coordinate(x: 1.0, y: 1.0, m: 1.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeInsert() { var input = (geometry: LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.002, y: 2.002, m: 2.002)]) let expected = [Coordinate(x: 2.0, y: 2.0, m: 2.0), Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeReplace() { var input = (geometry: LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 1.001, y: 1.001, m: 1.001)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.002, y: 2.002, m: 2.002)]) let expected = [Coordinate(x: 2.0, y: 2.0, m: 2.0), Coordinate(x: 1.0, y: 1.0, m: 1.0)] input.geometry.replaceSubrange(0..<1, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testEquals() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs).equals(LinearRing([Coordinate(x: 1.0, y: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs)), true) } func testIsEmpty() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty(), true) } func testIsEmptyFalse() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs).isEmpty(), false) } func testCount() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs).count, 2) } } // MARK: - Coordinate, Fixed, Cartesian - class LinearRingCoordinate3DFixedCartesianTests: XCTestCase { let precision = Fixed(scale: 100) let cs = Cartesian() // MARK: Construction func testInitWithPrecisionAndCRS() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty, true) } func testInitWithPrecision() { XCTAssertEqual(LinearRing(precision: precision).precision as? Fixed, precision) } func testInitWithCRS() { XCTAssertEqual(LinearRing(coordinateSystem: cs).coordinateSystem as? Cartesian, cs) } func testInitConverting() { let input = LinearRing(converting: LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitCopy() { let input = LinearRing(other: LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitWithArrayLiteral() { let input: LinearRing = [Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)] let expected = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)]) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } // MARK: CustomStringConvertible & CustomDebugStringConvertible func testDescription() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, z: 1.0), (x: 2.0, y: 2.0, z: 2.0)])" XCTAssertEqual(input.description, expected) } func testDebugDescription() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, z: 1.0), (x: 2.0, y: 2.0, z: 2.0)])" XCTAssertEqual(input.debugDescription, expected) } // MARK: MutableCollection Conformance func testStartIndex() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs) let expected = 0 XCTAssertEqual(input.startIndex, expected) } func testEndIndex() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs) let expected = 2 XCTAssertEqual(input.endIndex, expected) } func testIndexAfter() { let input = 0 let expected = 1 XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs).index(after: input), expected) } func testSubscriptGet() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs) XCTAssertEqual(input[1], Coordinate(x: 2.0, y: 2.0, z: 2.0)) } func testSubscriptSet() { var input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs) input[1] = Coordinate(x: 1.001, y: 1.001, z: 1.001) XCTAssertEqual(input[1], Coordinate(x: 1.0, y: 1.0, z: 1.0)) } // MARK: RangeReplaceableCollection Conformance func testReplaceSubrangeAppend() { var input = (geometry: LinearRing(precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 1.001, y: 1.001, z: 1.001)]) let expected = [Coordinate(x: 1.0, y: 1.0, z: 1.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeInsert() { var input = (geometry: LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.002, y: 2.002, z: 2.002)]) let expected = [Coordinate(x: 2.0, y: 2.0, z: 2.0), Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeReplace() { var input = (geometry: LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 1.001, y: 1.001, z: 1.001)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.002, y: 2.002, z: 2.002)]) let expected = [Coordinate(x: 2.0, y: 2.0, z: 2.0), Coordinate(x: 1.0, y: 1.0, z: 1.0)] input.geometry.replaceSubrange(0..<1, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testEquals() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs).equals(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0)], precision: precision, coordinateSystem: cs)), true) } func testIsEmpty() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty(), true) } func testIsEmptyFalse() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs).isEmpty(), false) } func testCount() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002)], precision: precision, coordinateSystem: cs).count, 2) } } // MARK: - Coordinate, Fixed, Cartesian - class LinearRingCoordinate3DMFixedCartesianTests: XCTestCase { let precision = Fixed(scale: 100) let cs = Cartesian() // MARK: Construction func testInitWithPrecisionAndCRS() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty, true) } func testInitWithPrecision() { XCTAssertEqual(LinearRing(precision: precision).precision as? Fixed, precision) } func testInitWithCRS() { XCTAssertEqual(LinearRing(coordinateSystem: cs).coordinateSystem as? Cartesian, cs) } func testInitConverting() { let input = LinearRing(converting: LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitCopy() { let input = LinearRing(other: LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)]), precision: precision, coordinateSystem: cs) let expected = LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } func testInitWithArrayLiteral() { let input: LinearRing = [Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)] let expected = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)]) XCTAssertTrue( (input.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs } ), "\(input) is not equal to \(expected)") } // MARK: CustomStringConvertible & CustomDebugStringConvertible func testDescription() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, z: 1.0, m: 1.0), (x: 2.0, y: 2.0, z: 2.0, m: 2.0)])" XCTAssertEqual(input.description, expected) } func testDebugDescription() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) let expected = "LinearRing([(x: 1.0, y: 1.0, z: 1.0, m: 1.0), (x: 2.0, y: 2.0, z: 2.0, m: 2.0)])" XCTAssertEqual(input.debugDescription, expected) } // MARK: MutableCollection Conformance func testStartIndex() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) let expected = 0 XCTAssertEqual(input.startIndex, expected) } func testEndIndex() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) let expected = 2 XCTAssertEqual(input.endIndex, expected) } func testIndexAfter() { let input = 0 let expected = 1 XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs).index(after: input), expected) } func testSubscriptGet() { let input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) XCTAssertEqual(input[1], Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)) } func testSubscriptSet() { var input = LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs) input[1] = Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001) XCTAssertEqual(input[1], Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0)) } // MARK: RangeReplaceableCollection Conformance func testReplaceSubrangeAppend() { var input = (geometry: LinearRing(precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001)]) let expected = [Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeInsert() { var input = (geometry: LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)]) let expected = [Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0), Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)] input.geometry.replaceSubrange(0..<0, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testReplaceSubrangeReplace() { var input = (geometry: LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001)], precision: precision, coordinateSystem: cs), newElements: [Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)]) let expected = [Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0), Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0)] input.geometry.replaceSubrange(0..<1, with: input.newElements) XCTAssertTrue(input.geometry.elementsEqual(expected) { (lhs: Coordinate, rhs: Coordinate) -> Bool in return lhs == rhs }, "\(input) is not equal to \(expected)") } func testEquals() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs).equals(LinearRing([Coordinate(x: 1.0, y: 1.0, z: 1.0, m: 1.0), Coordinate(x: 2.0, y: 2.0, z: 2.0, m: 2.0)], precision: precision, coordinateSystem: cs)), true) } func testIsEmpty() { XCTAssertEqual(LinearRing(precision: precision, coordinateSystem: cs).isEmpty(), true) } func testIsEmptyFalse() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs).isEmpty(), false) } func testCount() { XCTAssertEqual(LinearRing([Coordinate(x: 1.001, y: 1.001, z: 1.001, m: 1.001), Coordinate(x: 2.002, y: 2.002, z: 2.002, m: 2.002)], precision: precision, coordinateSystem: cs).count, 2) } }
apache-2.0
0b1bcb4e5b3e2b7beed080ab3db3164a
39.467309
343
0.611439
3.473886
false
true
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Widgets/PhotonActionSheet/PhotonActionSheetView.swift
1
14540
// 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 Storage import Shared // MARK: - PhotonActionSheetViewDelegate protocol PhotonActionSheetViewDelegate: AnyObject { func didClick(item: SingleActionViewModel?) func layoutChanged(item: SingleActionViewModel) } // This is the view contained in PhotonActionSheetContainerCell in the PhotonActionSheet table view. // More than one PhotonActionSheetView can be in the parent container cell. class PhotonActionSheetView: UIView, UIGestureRecognizerDelegate { // MARK: - PhotonActionSheetViewUX struct UX { static let StatusIconSize = CGSize(width: 24, height: 24) static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25) static let CornerRadius: CGFloat = 3 static let Padding: CGFloat = 16 static let InBetweenPadding: CGFloat = 8 static let topBottomPadding: CGFloat = 10 static let VerticalPadding: CGFloat = 2 } // MARK: - Variables private var badgeOverlay: BadgeWithBackdrop? private var item: SingleActionViewModel? weak var delegate: PhotonActionSheetViewDelegate? // MARK: - UI Elements // TODO: Needs refactoring using the `.build` style. All PhotonActionSheetViews should be tested at that point. private func createLabel() -> UILabel { let label = UILabel() label.setContentHuggingPriority(.required, for: .vertical) label.translatesAutoresizingMaskIntoConstraints = false return label } private func createIconImageView() -> UIImageView { let icon = UIImageView() icon.contentMode = .scaleAspectFit icon.clipsToBounds = true icon.layer.cornerRadius = UX.CornerRadius icon.setContentHuggingPriority(.required, for: .horizontal) icon.setContentCompressionResistancePriority(.required, for: .horizontal) return icon } private lazy var titleLabel: UILabel = { let label = createLabel() label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.setContentCompressionResistancePriority(.required, for: .horizontal) label.font = DynamicFontHelper.defaultHelper.LargeSizeRegularWeightAS return label }() private lazy var subtitleLabel: UILabel = { let label = createLabel() label.numberOfLines = 0 label.font = DynamicFontHelper.defaultHelper.SmallSizeRegularWeightAS return label }() private lazy var statusIcon: UIImageView = .build { icon in icon.contentMode = .scaleAspectFit icon.clipsToBounds = true icon.layer.cornerRadius = UX.CornerRadius icon.setContentHuggingPriority(.required, for: .horizontal) icon.setContentCompressionResistancePriority(.required, for: .horizontal) } private lazy var disclosureLabel: UILabel = { let label = UILabel() return label }() private let toggleSwitch = ToggleSwitch() private lazy var selectedOverlay: UIView = .build { selectedOverlay in selectedOverlay.backgroundColor = UX.SelectedOverlayColor selectedOverlay.isHidden = true } private lazy var disclosureIndicator: UIImageView = { let disclosureIndicator = createIconImageView() disclosureIndicator.image = UIImage(named: "menu-Disclosure")?.withRenderingMode(.alwaysTemplate) disclosureIndicator.tintColor = UIColor.theme.tableView.accessoryViewTint return disclosureIndicator }() private lazy var stackView: UIStackView = .build { stackView in stackView.spacing = UX.InBetweenPadding stackView.alignment = .center stackView.axis = .horizontal stackView.distribution = .fillProportionally } private lazy var textStackView: UIStackView = .build { textStackView in textStackView.spacing = UX.VerticalPadding textStackView.setContentHuggingPriority(.required, for: .vertical) textStackView.alignment = .fill textStackView.axis = .vertical textStackView.distribution = .fill } lazy var bottomBorder: UIView = .build { _ in } lazy var verticalBorder: UIView = .build { _ in } // MARK: - Initializers override init(frame: CGRect) { self.isSelected = false super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Gesture recognizer private lazy var tapRecognizer: UITapGestureRecognizer = { let tapRecognizer = UITapGestureRecognizer() tapRecognizer.addTarget(self, action: #selector(didClick)) tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.cancelsTouchesInView = false tapRecognizer.delegate = self return tapRecognizer }() var isSelected: Bool { didSet { selectedOverlay.isHidden = !isSelected } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) isSelected = true } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) isSelected = false } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) if let touch = touches.first { isSelected = frame.contains(touch.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) isSelected = false } @objc private func didClick(_ gestureRecognizer: UITapGestureRecognizer?) { guard let item = item, let handler = item.tapHandler else { self.delegate?.didClick(item: nil) return } isSelected = (gestureRecognizer?.state == .began) || (gestureRecognizer?.state == .changed) item.isEnabled = !item.isEnabled handler(item) self.delegate?.didClick(item: item) } // MARK: Setup override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) // The layout changes when there's multiple items in a row, // and there's not enough space in one row to show the labels without truncating if let item = item, item.multipleItemsSetup.isMultiItems, item.multipleItemsSetup.axis != .vertical, titleLabel.isTruncated { // Disabling this multipleItemsSetup feature for now - will rework to improve // item.multipleItemsSetup.axis = .vertical // delegate?.layoutChanged(item: item) } } func configure(with item: SingleActionViewModel) { self.item = item setupViews() applyTheme() titleLabel.text = item.currentTitle titleLabel.font = item.bold ? DynamicFontHelper.defaultHelper.DeviceFontLargeBold : DynamicFontHelper.defaultHelper.SemiMediumRegularWeightAS item.customRender?(titleLabel, self) subtitleLabel.text = item.text subtitleLabel.isHidden = item.text == nil accessibilityIdentifier = item.iconString ?? item.accessibilityId accessibilityLabel = item.currentTitle if item.isFlipped { transform = CGAffineTransform(scaleX: 1, y: -1) } if let iconName = item.iconString { setupActionName(action: item, name: iconName) } else { statusIcon.removeFromSuperview() } setupBadgeOverlay(action: item) addSubBorder(action: item) } func addVerticalBorder(ifShouldBeShown: Bool) { guard ifShouldBeShown else { return } titleLabel.setContentHuggingPriority(.required, for: .horizontal) textStackView.setContentHuggingPriority(.required, for: .horizontal) verticalBorder.backgroundColor = UIColor.theme.tableView.separator addSubview(verticalBorder) NSLayoutConstraint.activate([ verticalBorder.topAnchor.constraint(equalTo: topAnchor), verticalBorder.bottomAnchor.constraint(equalTo: bottomAnchor), verticalBorder.leadingAnchor.constraint(equalTo: leadingAnchor), verticalBorder.widthAnchor.constraint(equalToConstant: 1) ]) } private func setupViews() { isAccessibilityElement = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = .clear addGestureRecognizer(tapRecognizer) // Setup our StackViews textStackView.addArrangedSubview(titleLabel) textStackView.addArrangedSubview(subtitleLabel) stackView.addArrangedSubview(textStackView) stackView.addArrangedSubview(statusIcon) addSubview(stackView) addSubview(selectedOverlay) setupConstraints() } private func setupConstraints() { let padding = UX.Padding let topBottomPadding = UX.topBottomPadding NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: topAnchor, constant: topBottomPadding), stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -topBottomPadding), stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding), stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding), selectedOverlay.topAnchor.constraint(equalTo: topAnchor), selectedOverlay.bottomAnchor.constraint(equalTo: bottomAnchor), selectedOverlay.trailingAnchor.constraint(equalTo: trailingAnchor), selectedOverlay.leadingAnchor.constraint(equalTo: leadingAnchor), statusIcon.widthAnchor.constraint(equalToConstant: UX.StatusIconSize.width), statusIcon.heightAnchor.constraint(equalToConstant: UX.StatusIconSize.height), ]) } private func addSubBorder(action: SingleActionViewModel) { bottomBorder.backgroundColor = UIColor.theme.tableView.separator addSubview(bottomBorder) // Determine if border should be at top or bottom when flipping let top = bottomBorder.topAnchor.constraint(equalTo: topAnchor) let bottom = bottomBorder.bottomAnchor.constraint(equalTo: bottomAnchor) let anchor = action.isFlipped ? top : bottom NSLayoutConstraint.activate([ anchor, bottomBorder.leadingAnchor.constraint(equalTo: leadingAnchor), bottomBorder.trailingAnchor.constraint(equalTo: trailingAnchor), bottomBorder.heightAnchor.constraint(equalToConstant: 1) ]) } private func setupActionName(action: SingleActionViewModel, name: String) { switch action.iconType { case .Image: let image = UIImage(named: name)?.withRenderingMode(.alwaysTemplate) statusIcon.image = image statusIcon.tintColor = action.iconTint ?? action.tintColor ?? self.tintColor case .URL: let image = UIImage(named: name)?.createScaled(PhotonActionSheet.UX.iconSize) statusIcon.layer.cornerRadius = PhotonActionSheet.UX.iconSize.width / 2 statusIcon.image = image if let actionIconUrl = action.iconURL { ImageLoadingHandler.shared.getImageFromCacheOrDownload(with: actionIconUrl, limit: ImageLoadingConstants.NoLimitImageSize) { image, error in guard error == nil, let image = image, self.accessibilityLabel == action.currentTitle else { return } self.statusIcon.image = image.createScaled(PhotonActionSheet.UX.iconSize) self.statusIcon.layer.cornerRadius = PhotonActionSheet.UX.iconSize.width / 2 } } case .TabsButton: let label = UILabel(frame: CGRect()) label.text = action.tabCount label.font = UIFont.boldSystemFont(ofSize: UIConstants.DefaultChromeSmallSize) label.textColor = UIColor.theme.textField.textAndTint label.translatesAutoresizingMaskIntoConstraints = false let image = UIImage(named: name)?.withRenderingMode(.alwaysTemplate) statusIcon.image = image statusIcon.addSubview(label) statusIcon.tintColor = action.tintColor ?? self.tintColor NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: statusIcon.centerXAnchor), label.centerYAnchor.constraint(equalTo: statusIcon.centerYAnchor), ]) case .None: break } if statusIcon.superview == nil { if action.iconAlignment == .right { stackView.addArrangedSubview(statusIcon) } else { stackView.insertArrangedSubview(statusIcon, at: 0) } } else { if action.iconAlignment == .right { statusIcon.removeFromSuperview() stackView.addArrangedSubview(statusIcon) } } } private func setupBadgeOverlay(action: SingleActionViewModel) { guard let name = action.badgeIconName, action.isEnabled, let parent = statusIcon.superview else { return } badgeOverlay = BadgeWithBackdrop(imageName: name) badgeOverlay?.add(toParent: parent) badgeOverlay?.layout(onButton: statusIcon) badgeOverlay?.show(true) // Custom dark theme tint needed here, it is overkill to create a '.theme' color just for this. let customDarkTheme = UIColor(white: 0.3, alpha: 1) let color = LegacyThemeManager.instance.currentName == .dark ? customDarkTheme : UIColor.theme.actionMenu.closeButtonBackground badgeOverlay?.badge.tintBackground(color: color) } } extension PhotonActionSheetView: NotificationThemeable { func applyTheme() { titleLabel.textColor = UIColor.theme.tableView.rowText titleLabel.textColor = titleLabel.textColor subtitleLabel.textColor = UIColor.theme.tableView.rowText } }
mpl-2.0
6d334a6a9cd66cd3c87519fd62b9ab58
37.263158
149
0.666644
5.445693
false
false
false
false
or1onsli/Fou.run-
MusicRun/EntityManager.swift
1
4699
// // EntityManager.swift // Fou.run() // // Copyright © 2016 Shock&Awe. All rights reserved. // import Foundation import GameplayKit import SpriteKit class EntityManager { //MARK: Properties var entities = Set<GKEntity>() let scene: SKScene //MARK: Initializer init(scene: SKScene){ self.scene = scene } //MARK: Add-Remove Functions func add(entity: GKEntity){ entities.insert(entity) if let playerNode = entity.component(ofType: PlayerComponent.self)?.node{ scene.addChild(playerNode) } if let barrierNode = entity.component(ofType: BarrierComponent.self)?.node{ scene.addChild(barrierNode) let moveBarrier = SKAction.move(to: CGPoint(x: -barrierNode.size.width/2, y: barrierNode.position.y), duration: 1.5) barrierNode.run(SKAction.sequence([moveBarrier, SKAction.run { self.remove(entity: entity) }])) } if let noteNode = entity.component(ofType: NoteComponent.self)?.node{ scene.addChild(noteNode) let moveNote = SKAction.move(to: CGPoint(x: -noteNode.size.width/2, y: noteNode.position.y), duration: 1.18) //let moveNoteDone = SKAction.removeFromParent() noteNode.run(SKAction.sequence([moveNote, SKAction.run { self.remove(entity: entity) }])) } } func remove(entity: GKEntity){ if let playerNode = entity.component(ofType: PlayerComponent.self)?.node{ playerNode.removeFromParent() } if let barrierNode = entity.component(ofType: BarrierComponent.self)?.node{ barrierNode.removeFromParent() } if let noteNode = entity.component(ofType: NoteComponent.self)?.node{ noteNode.removeFromParent() } entities.remove(entity) } func getEntity(type: String) -> GKEntity?{ if type == "player"{ for entity in entities{ if let tmp = entity as? PlayerEntity{ return tmp } } } else if type == "barrier"{ for entity in entities{ if let tmp = entity as? BarrierEntity{ return tmp } } } else if type == "note"{ for entity in entities{ if let tmp = entity as? NoteEntity{ return tmp } } } return nil } //MARK: Create Functions func spawnBarriers(type: UIImage, team: Team){ let barrier = BarrierEntity(type: type) if let barrierComponent = barrier.component(ofType: BarrierComponent.self){ barrierComponent.node.anchorPoint = CGPoint(x: 0.5, y: 0.5) if let scene = self.scene as? GameScene{ if type == BarrierTexture.high { barrierComponent.node.position = CGPoint(x: (scene.view?.frame.width)! + barrierComponent.node.frame.size.width/2, y: scene.lowerBar.size.height + 40) barrierComponent.node.zPosition = 5 barrierComponent.node.xScale = 0.6 barrierComponent.node.yScale = 0.6 print("OK") } else if type == BarrierTexture.low{ barrierComponent.node.position = CGPoint(x: (scene.view?.frame.width)! + barrierComponent.node.frame.size.width/2, y: scene.lowerBar.size.height + 20) barrierComponent.node.xScale = 0.5 barrierComponent.node.yScale = 0.7 barrierComponent.node.zPosition = 5 } else if type == BarrierTexture.medium{ barrierComponent.node.position = CGPoint(x: scene.frame.size.width + barrierComponent.node.size.width/2, y: scene.lowerBar.frame.size.height + 85) barrierComponent.node.xScale = 0.35 barrierComponent.node.yScale = 0.35 barrierComponent.node.zPosition = 5 print("NOPE") } } } add(entity: barrier) } func spawnNotes(position: CGPoint){ let note = NoteEntity(position: position) if let noteComponent = note.component(ofType: BarrierComponent.self){ noteComponent.node.anchorPoint = CGPoint(x: 0.5, y: 0.5) } add(entity: note) } }
mit
c780066ae235b73d0a6150343a11f412
32.798561
170
0.541081
4.570039
false
false
false
false
wireapp/wire-ios-sync-engine
Source/UserSession/ZMUserSession.swift
1
26923
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation @objc(ZMThirdPartyServicesDelegate) public protocol ThirdPartyServicesDelegate: NSObjectProtocol { /// This will get called at a convenient point in time when Hockey and Localytics should upload their data. /// We try not to have Hockey and Localytics use the network while we're sync'ing. @objc(userSessionIsReadyToUploadServicesData:) func userSessionIsReadyToUploadServicesData(userSession: ZMUserSession) } @objc(UserSessionSelfUserClientDelegate) public protocol UserSessionSelfUserClientDelegate: NSObjectProtocol { /// Invoked when a client is successfully registered func clientRegistrationDidSucceed(accountId: UUID) /// Invoked when there was an error registering the client func clientRegistrationDidFail(_ error: NSError, accountId: UUID) } @objc(UserSessionLogoutDelegate) public protocol UserSessionLogoutDelegate: NSObjectProtocol { /// Invoked when the user successfully logged out func userDidLogout(accountId: UUID) /// Invoked when the authentication has proven invalid func authenticationInvalidated(_ error: NSError, accountId: UUID) } typealias UserSessionDelegate = UserSessionEncryptionAtRestDelegate & UserSessionSelfUserClientDelegate & UserSessionLogoutDelegate & UserSessionAppLockDelegate @objcMembers public class ZMUserSession: NSObject { private let appVersion: String private var tokens: [Any] = [] private var tornDown: Bool = false var isNetworkOnline: Bool = true var isPerformingSync: Bool = true { willSet { notificationDispatcher.operationMode = newValue ? .economical : .normal } } var hasNotifiedThirdPartyServices: Bool = false var coreDataStack: CoreDataStack! let application: ZMApplication let flowManager: FlowManagerType var mediaManager: MediaManagerType var analytics: AnalyticsType? var transportSession: TransportSessionType let storedDidSaveNotifications: ContextDidSaveNotificationPersistence let userExpirationObserver: UserExpirationObserver var updateEventProcessor: UpdateEventProcessor? var strategyDirectory: StrategyDirectoryProtocol? var syncStrategy: ZMSyncStrategy? var operationLoop: ZMOperationLoop? var notificationDispatcher: NotificationDispatcher var localNotificationDispatcher: LocalNotificationDispatcher? var applicationStatusDirectory: ApplicationStatusDirectory? var callStateObserver: CallStateObserver? var messageReplyObserver: ManagedObjectContextChangeObserver? var likeMesssageObserver: ManagedObjectContextChangeObserver? var urlActionProcessors: [URLActionProcessor]? let debugCommands: [String: DebugCommand] let eventProcessingTracker: EventProcessingTracker = EventProcessingTracker() let hotFix: ZMHotFix public lazy var featureService = FeatureService(context: syncContext) public var appLockController: AppLockType public var fileSharingFeature: Feature.FileSharing { let featureService = FeatureService(context: coreDataStack.viewContext) return featureService.fetchFileSharing() } public var selfDeletingMessagesFeature: Feature.SelfDeletingMessages { let featureService = FeatureService(context: coreDataStack.viewContext) return featureService.fetchSelfDeletingMesssages() } public var conversationGuestLinksFeature: Feature.ConversationGuestLinks { let featureService = FeatureService(context: coreDataStack.viewContext) return featureService.fetchConversationGuestLinks() } public var classifiedDomainsFeature: Feature.ClassifiedDomains { let featureService = FeatureService(context: coreDataStack.viewContext) return featureService.fetchClassifiedDomains() } public var hasCompletedInitialSync: Bool = false public var topConversationsDirectory: TopConversationsDirectory public var managedObjectContext: NSManagedObjectContext { // TODO jacob we don't want this to be public return coreDataStack.viewContext } public var syncManagedObjectContext: NSManagedObjectContext { // TODO jacob we don't want this to be public return coreDataStack.syncContext } public var searchManagedObjectContext: NSManagedObjectContext { // TODO jacob we don't want this to be public return coreDataStack.searchContext } public var sharedContainerURL: URL { // TODO jacob we don't want this to be public return coreDataStack.applicationContainer } public var selfUserClient: UserClient? { // TODO jacob we don't want this to be public return ZMUser.selfUser(in: managedObjectContext).selfClient() } public var userProfile: UserProfile? { return applicationStatusDirectory?.userProfileUpdateStatus } public var userProfileImage: UserProfileImageUpdateProtocol? { return applicationStatusDirectory?.userProfileImageUpdateStatus } public var conversationDirectory: ConversationDirectoryType { return managedObjectContext.conversationListDirectory() } public var operationStatus: OperationStatus? { // TODO jacob we don't want this to be public return applicationStatusDirectory?.operationStatus } public private(set) var networkState: ZMNetworkState = .online { didSet { if oldValue != networkState { ZMNetworkAvailabilityChangeNotification.notify(networkState: networkState, userSession: self) } } } public var isNotificationContentHidden: Bool { get { guard let value = managedObjectContext.persistentStoreMetadata(forKey: LocalNotificationDispatcher.ZMShouldHideNotificationContentKey) as? NSNumber else { return false } return value.boolValue } set { managedObjectContext.setPersistentStoreMetadata(NSNumber(value: newValue), key: LocalNotificationDispatcher.ZMShouldHideNotificationContentKey) } } weak var delegate: UserSessionDelegate? // TODO remove this property and move functionality to separate protocols under UserSessionDelegate public weak var sessionManager: SessionManagerType? public weak var thirdPartyServicesDelegate: ThirdPartyServicesDelegate? // MARK: - Tear down deinit { require(tornDown, "tearDown must be called before the ZMUserSession is deallocated") } public func tearDown() { guard !tornDown else { return } tokens.removeAll() application.unregisterObserverForStateChange(self) callStateObserver = nil syncStrategy?.tearDown() syncStrategy = nil operationLoop?.tearDown() operationLoop = nil transportSession.tearDown() applicationStatusDirectory = nil notificationDispatcher.tearDown() // Wait for all sync operations to finish syncManagedObjectContext.performGroupedBlockAndWait { } let uiMOC = coreDataStack.viewContext coreDataStack = nil let shouldWaitOnUIMoc = !(OperationQueue.current == OperationQueue.main && uiMOC.concurrencyType == .mainQueueConcurrencyType) if shouldWaitOnUIMoc { uiMOC.performAndWait { // warning: this will hang if the uiMoc queue is same as self.requestQueue (typically uiMoc queue is the main queue) } } NotificationCenter.default.removeObserver(self) tornDown = true } public init(userId: UUID, transportSession: TransportSessionType, mediaManager: MediaManagerType, flowManager: FlowManagerType, analytics: AnalyticsType?, eventProcessor: UpdateEventProcessor? = nil, strategyDirectory: StrategyDirectoryProtocol? = nil, syncStrategy: ZMSyncStrategy? = nil, operationLoop: ZMOperationLoop? = nil, application: ZMApplication, appVersion: String, coreDataStack: CoreDataStack, configuration: Configuration) { coreDataStack.syncContext.performGroupedBlockAndWait { coreDataStack.syncContext.analytics = analytics coreDataStack.syncContext.zm_userInterface = coreDataStack.viewContext } coreDataStack.viewContext.zm_sync = coreDataStack.syncContext self.application = application self.appVersion = appVersion self.flowManager = flowManager self.mediaManager = mediaManager self.analytics = analytics self.coreDataStack = coreDataStack self.transportSession = transportSession self.notificationDispatcher = NotificationDispatcher(managedObjectContext: coreDataStack.viewContext) self.storedDidSaveNotifications = ContextDidSaveNotificationPersistence(accountContainer: coreDataStack.accountContainer) self.userExpirationObserver = UserExpirationObserver(managedObjectContext: coreDataStack.viewContext) self.topConversationsDirectory = TopConversationsDirectory(managedObjectContext: coreDataStack.viewContext) self.debugCommands = ZMUserSession.initDebugCommands() self.hotFix = ZMHotFix(syncMOC: coreDataStack.syncContext) self.appLockController = AppLockController(userId: userId, selfUser: .selfUser(in: coreDataStack.viewContext), legacyConfig: configuration.appLockConfig) super.init() appLockController.delegate = self configureCaches() syncManagedObjectContext.performGroupedBlockAndWait { self.localNotificationDispatcher = LocalNotificationDispatcher(in: coreDataStack.syncContext) self.configureTransportSession() self.applicationStatusDirectory = self.createApplicationStatusDirectory() self.updateEventProcessor = eventProcessor ?? self.createUpdateEventProcessor() self.strategyDirectory = strategyDirectory ?? self.createStrategyDirectory(useLegacyPushNotifications: configuration.useLegacyPushNotifications) self.syncStrategy = syncStrategy ?? self.createSyncStrategy() self.operationLoop = operationLoop ?? self.createOperationLoop() self.urlActionProcessors = self.createURLActionProcessors() self.callStateObserver = CallStateObserver(localNotificationDispatcher: self.localNotificationDispatcher!, contextProvider: self, callNotificationStyleProvider: self) } updateEventProcessor!.eventConsumers = self.strategyDirectory!.eventConsumers registerForCalculateBadgeCountNotification() registerForRegisteringPushTokenNotification() registerForBackgroundNotifications() enableBackgroundFetch() observeChangesOnShareExtension() startEphemeralTimers() notifyUserAboutChangesInAvailabilityBehaviourIfNeeded() RequestAvailableNotification.notifyNewRequestsAvailable(self) restoreDebugCommandsState() } private func configureTransportSession() { transportSession.pushChannel.clientID = selfUserClient?.remoteIdentifier transportSession.setNetworkStateDelegate(self) transportSession.setAccessTokenRenewalFailureHandler { [weak self] (response) in self?.transportSessionAccessTokenDidFail(response: response) } } private func configureCaches() { let cacheLocation = FileManager.default.cachesURLForAccount(with: coreDataStack.account.userIdentifier, in: coreDataStack.applicationContainer) ZMUserSession.moveCachesIfNeededForAccount(with: coreDataStack.account.userIdentifier, in: coreDataStack.applicationContainer) let userImageCache = UserImageLocalCache(location: cacheLocation) let fileAssetCache = FileAssetCache(location: cacheLocation) managedObjectContext.zm_userImageCache = userImageCache managedObjectContext.zm_fileAssetCache = fileAssetCache managedObjectContext.zm_searchUserCache = NSCache() syncManagedObjectContext.performGroupedBlockAndWait { self.syncManagedObjectContext.zm_userImageCache = userImageCache self.syncManagedObjectContext.zm_fileAssetCache = fileAssetCache } } private func createStrategyDirectory(useLegacyPushNotifications: Bool) -> StrategyDirectoryProtocol { return StrategyDirectory(contextProvider: coreDataStack, applicationStatusDirectory: applicationStatusDirectory!, cookieStorage: transportSession.cookieStorage, pushMessageHandler: localNotificationDispatcher!, flowManager: flowManager, updateEventProcessor: updateEventProcessor!, localNotificationDispatcher: localNotificationDispatcher!, useLegacyPushNotifications: useLegacyPushNotifications) } private func createUpdateEventProcessor() -> EventProcessor { return EventProcessor(storeProvider: self.coreDataStack, syncStatus: applicationStatusDirectory!.syncStatus, eventProcessingTracker: eventProcessingTracker) } private func createApplicationStatusDirectory() -> ApplicationStatusDirectory { let applicationStatusDirectory = ApplicationStatusDirectory(withManagedObjectContext: self.syncManagedObjectContext, cookieStorage: transportSession.cookieStorage, requestCancellation: transportSession, application: application, syncStateDelegate: self, analytics: analytics) applicationStatusDirectory.clientRegistrationStatus.prepareForClientRegistration() self.hasCompletedInitialSync = !applicationStatusDirectory.syncStatus.isSlowSyncing return applicationStatusDirectory } private func createURLActionProcessors() -> [URLActionProcessor] { return [ DeepLinkURLActionProcessor(contextProvider: coreDataStack, transportSession: transportSession, eventProcessor: updateEventProcessor!), ConnectToBotURLActionProcessor(contextprovider: coreDataStack, transportSession: transportSession, eventProcessor: updateEventProcessor!) ] } private func createSyncStrategy() -> ZMSyncStrategy { return ZMSyncStrategy(contextProvider: coreDataStack, notificationsDispatcher: notificationDispatcher, applicationStatusDirectory: applicationStatusDirectory!, application: application, strategyDirectory: strategyDirectory!, eventProcessingTracker: eventProcessingTracker) } private func createOperationLoop() -> ZMOperationLoop { return ZMOperationLoop(transportSession: transportSession, requestStrategy: syncStrategy, updateEventProcessor: updateEventProcessor!, applicationStatusDirectory: applicationStatusDirectory!, uiMOC: managedObjectContext, syncMOC: syncManagedObjectContext) } func startRequestLoopTracker() { transportSession.requestLoopDetectionCallback = { path in guard !path.hasSuffix("/typing") else { return } Logging.network.warn("Request loop happening at path: \(path)") DispatchQueue.main.async { NotificationCenter.default.post(name: Notification.Name(rawValue: ZMLoggingRequestLoopNotificationName), object: nil, userInfo: ["path": path]) } } } private func registerForCalculateBadgeCountNotification() { tokens.append(NotificationInContext.addObserver(name: .calculateBadgeCount, context: managedObjectContext.notificationContext) { [weak self] (_) in self?.calculateBadgeCount() }) } /// Count number of conversations with unread messages and update the application icon badge count. private func calculateBadgeCount() { let accountID = coreDataStack.account.userIdentifier let unreadCount = Int(ZMConversation.unreadConversationCount(in: self.syncManagedObjectContext)) Logging.push.safePublic("Updating badge count for \(accountID) to \(SanitizedString(stringLiteral: String(unreadCount)))") self.sessionManager?.updateAppIconBadge(accountID: accountID, unreadCount: unreadCount) } private func registerForBackgroundNotifications() { application.registerObserverForDidEnterBackground(self, selector: #selector(applicationDidEnterBackground(_:))) application.registerObserverForWillEnterForeground(self, selector: #selector(applicationWillEnterForeground(_:))) } private func enableBackgroundFetch() { // We enable background fetch by setting the minimum interval to something different from UIApplicationBackgroundFetchIntervalNever application.setMinimumBackgroundFetchInterval(10.0 * 60.0 + Double.random(in: 0..<300)) } private func notifyUserAboutChangesInAvailabilityBehaviourIfNeeded() { syncManagedObjectContext.performGroupedBlock { self.localNotificationDispatcher?.notifyAvailabilityBehaviourChangedIfNeeded() } } // MARK: - Network public func requestSlowSync() { applicationStatusDirectory?.requestSlowSync() } private func transportSessionAccessTokenDidFail(response: ZMTransportResponse) { managedObjectContext.performGroupedBlock { [weak self] in guard let strongRef = self else { return } let selfUser = ZMUser.selfUser(in: strongRef.managedObjectContext) let error = NSError.userSessionErrorWith(.accessTokenExpired, userInfo: selfUser.loginCredentials.dictionaryRepresentation) strongRef.notifyAuthenticationInvalidated(error) } } // MARK: - Perform changes public func saveOrRollbackChanges() { managedObjectContext.saveOrRollback() } @objc(performChanges:) public func perform(_ changes: @escaping () -> Void) { managedObjectContext.performGroupedBlockAndWait { [weak self] in changes() self?.saveOrRollbackChanges() } } @objc(enqueueChanges:) public func enqueue(_ changes: @escaping () -> Void) { enqueue(changes, completionHandler: nil) } @objc(enqueueChanges:completionHandler:) public func enqueue(_ changes: @escaping () -> Void, completionHandler: (() -> Void)?) { managedObjectContext.performGroupedBlock { [weak self] in changes() self?.saveOrRollbackChanges() completionHandler?() } } @objc(enqueueDelayedChanges:completionHandler:) public func enqueueDelayed(_ changes: @escaping () -> Void, completionHandler: (() -> Void)?) { managedObjectContext.performGroupedBlock { [weak self] in changes() self?.saveOrRollbackChanges() let group = ZMSDispatchGroup(label: "enqueueDelayedChanges") self?.managedObjectContext.enqueueDelayedSave(with: group) group?.notify(on: DispatchQueue.global(qos: .background), block: { self?.managedObjectContext.performGroupedBlock { completionHandler?() } }) } } // MARK: - Account public func initiateUserDeletion() { syncManagedObjectContext.performGroupedBlock { self.syncManagedObjectContext.setPersistentStoreMetadata(NSNumber(value: true), key: DeleteAccountRequestStrategy.userDeletionInitiatedKey) RequestAvailableNotification.notifyNewRequestsAvailable(self) } } } extension ZMUserSession: ZMNetworkStateDelegate { public func didReceiveData() { managedObjectContext.performGroupedBlock { [weak self] in self?.isNetworkOnline = true self?.updateNetworkState() } } public func didGoOffline() { managedObjectContext.performGroupedBlock { [weak self] in self?.isNetworkOnline = false self?.updateNetworkState() self?.saveOrRollbackChanges() } } func updateNetworkState() { let state: ZMNetworkState if isNetworkOnline { if isPerformingSync { state = .onlineSynchronizing } else { state = .online } } else { state = .offline } networkState = state } } extension ZMUserSession: ZMSyncStateDelegate { public func didStartSlowSync() { managedObjectContext.performGroupedBlock { [weak self] in self?.isPerformingSync = true self?.notificationDispatcher.isEnabled = false self?.updateNetworkState() } } public func didFinishSlowSync() { managedObjectContext.performGroupedBlock { [weak self] in self?.hasCompletedInitialSync = true self?.notificationDispatcher.isEnabled = true if let context = self?.managedObjectContext { ZMUserSession.notifyInitialSyncCompleted(context: context) } } } public func didStartQuickSync() { managedObjectContext.performGroupedBlock { [weak self] in self?.isPerformingSync = true self?.updateNetworkState() } } public func didFinishQuickSync() { processEvents() managedObjectContext.performGroupedBlock { [weak self] in self?.notifyThirdPartyServices() } fetchFeatureConfigs() } func processEvents() { managedObjectContext.performGroupedBlock { [weak self] in self?.isPerformingSync = true self?.updateNetworkState() } let hasMoreEventsToProcess = updateEventProcessor!.processEventsIfReady() let isSyncing = applicationStatusDirectory?.syncStatus.isSyncing == true if !hasMoreEventsToProcess { hotFix.applyPatches() } managedObjectContext.performGroupedBlock { [weak self] in self?.isPerformingSync = hasMoreEventsToProcess || isSyncing self?.updateNetworkState() } } private func fetchFeatureConfigs() { let action = GetFeatureConfigsAction { result in if case let .failure(reason) = result { Logging.network.error("Failed to fetch feature configs: \(String(describing: reason))") } } action.send(in: syncContext.notificationContext) } public func didRegisterSelfUserClient(_ userClient: UserClient!) { // If during registration user allowed notifications, // The push token can only be registered after client registration transportSession.pushChannel.clientID = userClient.remoteIdentifier registerCurrentPushToken() UserClient.triggerSelfClientCapabilityUpdate(syncContext) managedObjectContext.performGroupedBlock { [weak self] in guard let accountId = self?.managedObjectContext.selfUserId else { return } self?.delegate?.clientRegistrationDidSucceed(accountId: accountId) } } public func didFailToRegisterSelfUserClient(error: Error!) { managedObjectContext.performGroupedBlock { [weak self] in guard let accountId = self?.managedObjectContext.selfUserId else { return } self?.delegate?.clientRegistrationDidFail(error as NSError, accountId: accountId) } } public func didDeleteSelfUserClient(error: Error!) { notifyAuthenticationInvalidated(error) } public func notifyThirdPartyServices() { if !hasNotifiedThirdPartyServices { hasNotifiedThirdPartyServices = true thirdPartyServicesDelegate?.userSessionIsReadyToUploadServicesData(userSession: self) } } private func notifyAuthenticationInvalidated(_ error: Error) { managedObjectContext.performGroupedBlock { [weak self] in guard let accountId = self?.managedObjectContext.selfUserId else { return } self?.delegate?.authenticationInvalidated(error as NSError, accountId: accountId) } } } extension ZMUserSession: URLActionProcessor { func process(urlAction: URLAction, delegate: PresentationDelegate?) { urlActionProcessors?.forEach({ $0.process(urlAction: urlAction, delegate: delegate)}) } } private extension NSManagedObjectContext { var selfUserId: UUID? { ZMUser.selfUser(in: self).remoteIdentifier } } extension ZMUserSession: ContextProvider { public var account: Account { return coreDataStack.account } public var viewContext: NSManagedObjectContext { return coreDataStack.viewContext } public var syncContext: NSManagedObjectContext { return coreDataStack.syncContext } public var searchContext: NSManagedObjectContext { return coreDataStack.searchContext } public var eventContext: NSManagedObjectContext { return coreDataStack.eventContext } }
gpl-3.0
bb7fc20681c98bbf3865d2e7ba1e11cc
38.826923
166
0.682131
6.004237
false
false
false
false
tiagomartinho/webhose-cocoa
webhose-cocoa/Pods/Nimble/Sources/Nimble/Adapters/NimbleXCTestHandler.swift
69
2801
import Foundation import XCTest /// Default handler for Nimble. This assertion handler passes failures along to /// XCTest. public class NimbleXCTestHandler: AssertionHandler { public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) { if !assertion { recordFailure("\(message.stringValue)\n", location: location) } } } /// Alternative handler for Nimble. This assertion handler passes failures along /// to XCTest by attempting to reduce the failure message size. public class NimbleShortXCTestHandler: AssertionHandler { public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) { if !assertion { let msg: String if let actual = message.actualValue { msg = "got: \(actual) \(message.postfixActual)" } else { msg = "expected \(message.to) \(message.postfixMessage)" } recordFailure("\(msg)\n", location: location) } } } /// Fallback handler in case XCTest is unavailable. This assertion handler will abort /// the program if it is invoked. class NimbleXCTestUnavailableHandler: AssertionHandler { func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) { fatalError("XCTest is not available and no custom assertion handler was configured. Aborting.") } } #if !SWIFT_PACKAGE /// Helper class providing access to the currently executing XCTestCase instance, if any @objc final internal class CurrentTestCaseTracker: NSObject, XCTestObservation { @objc static let sharedInstance = CurrentTestCaseTracker() private(set) var currentTestCase: XCTestCase? @objc func testCaseWillStart(_ testCase: XCTestCase) { currentTestCase = testCase } @objc func testCaseDidFinish(_ testCase: XCTestCase) { currentTestCase = nil } } #endif func isXCTestAvailable() -> Bool { #if _runtime(_ObjC) // XCTest is weakly linked and so may not be present return NSClassFromString("XCTestCase") != nil #else return true #endif } private func recordFailure(_ message: String, location: SourceLocation) { #if SWIFT_PACKAGE XCTFail("\(message)", file: location.file, line: location.line) #else if let testCase = CurrentTestCaseTracker.sharedInstance.currentTestCase { testCase.recordFailure(withDescription: message, inFile: location.file, atLine: location.line, expected: true) } else { let msg = "Attempted to report a test failure to XCTest while no test case was running. " + "The failure was:\n\"\(message)\"\nIt occurred at: \(location.file):\(location.line)" NSException(name: .internalInconsistencyException, reason: msg, userInfo: nil).raise() } #endif }
mit
e2bf2176db8bcfc6622bbe01c19d0dae
35.855263
118
0.696894
4.905429
false
true
false
false
YunsChou/LovePlay
LovePlay-Swift3/LovePlay/Class/News/View/NewsNormalCell.swift
1
4028
// // NewsNormalCell.swift // LovePlay // // Created by weiying on 2017/5/19. // Copyright © 2017年 yuns. All rights reserved. // import UIKit class NewsNormalCell: UITableViewCell { class func cellWithTableView(tableView : UITableView) -> NewsNormalCell { let ID = NSStringFromClass(self) var cell : NewsNormalCell? = tableView.dequeueReusableCell(withIdentifier: ID) as? NewsNormalCell if cell == nil { cell = NewsNormalCell(style: .default, reuseIdentifier: ID) } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.addSubViews() self.snp_subViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - private private func addSubViews() { self.contentView.addSubview(self.imgView) self.contentView.addSubview(self.titleTextLabel) self.contentView.addSubview(self.replyButton) self.contentView.addSubview(self.underLineView) } private func snp_subViews() { self.imgView.snp.makeConstraints { (make) in make.width.height.equalTo(80) make.top.equalToSuperview().offset(10) make.left.equalToSuperview().offset(10) } self.titleTextLabel.snp.makeConstraints { (make) in make.top.equalTo(imgView); make.left.equalTo(imgView.snp.right).offset(10); make.right.equalToSuperview().offset(-10); } self.replyButton.snp.makeConstraints { (make) in make.width.equalTo(50); make.height.equalTo(20); make.left.equalTo(titleTextLabel.snp.left); make.bottom.equalTo(imgView.snp.bottom); } self.underLineView.snp.makeConstraints { (make) in make.height.equalTo(0.5); make.top.equalTo(imgView.snp.bottom).offset(10); make.left.bottom.right.equalToSuperview(); } } fileprivate var _listModel : NewsListModel? // MARK: - public var listModel : NewsListModel? { set { _listModel = newValue var imgURL : URL? = URL(string: "") if !(newValue?.imgsrc.isEmpty)! { let imgSrc = (newValue?.imgsrc.first)! imgURL = URL(string: imgSrc) } self.imgView.kf.setImage(with: imgURL) self.titleTextLabel.text = newValue?.title self.replyButton .setTitle(newValue?.replyCount.stringValue, for: .normal) } get { return _listModel } } // MARK: - lazy load lazy var imgView : UIImageView = { let imgView : UIImageView = UIImageView() return imgView }() lazy var titleTextLabel : UILabel = { let titleTextLabel : UILabel = UILabel() titleTextLabel.numberOfLines = 2 titleTextLabel.textColor = RGB(r: 36, g: 36, b: 36) titleTextLabel.font = UIFont.systemFont(ofSize: 16) return titleTextLabel }() lazy var replyButton : UIButton = { let replyButton : UIButton = UIButton() replyButton.setTitleColor(RGB(r: 150, g: 150, b: 150), for: .normal) replyButton.titleLabel?.font = UIFont.systemFont(ofSize: 10) replyButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5) replyButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0) replyButton.setTitle("0", for: .normal) replyButton.setImage(UIImage(named: "common_chat_new"), for: .normal) return replyButton }() lazy var underLineView : UIView = { let underLineView : UIView = UIView() underLineView.backgroundColor = RGB(r: 222, g: 222, b: 222) return underLineView }() }
mit
0d58bf2847853396ca250085f2c2e8f0
31.723577
105
0.596522
4.472222
false
false
false
false
einsteinx2/iSub
Classes/AudioEngine/Bass Wrapper/BassStreamController.swift
1
1617
// // BassStreamController.swift // iSub Beta // // Created by Benjamin Baron on 9/17/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation class BassStreamController { let deviceNumber: UInt32 var outStream: HSTREAM = 0 var mixerStream: HSTREAM = 0 let bassStreamsLock = SpinLock() var bassStreams = [BassStream]() var currentBassStream: BassStream? { return bassStreamsLock.synchronizedResult { return bassStreams.first } } var nextBassStream: BassStream? { return bassStreamsLock.synchronizedResult { return bassStreams.second } } var bassOutputBufferLengthMillis: UInt32 = 0 init(deviceNumber: UInt32) { self.deviceNumber = deviceNumber } func add(bassStream: BassStream) { bassStreamsLock.synchronized { bassStreams.append(bassStream) } } func remove(bassStream: BassStream) { // Remove the stream from the queue BASS_SetDevice(deviceNumber) BASS_StreamFree(bassStream.stream) bassStreamsLock.synchronized { if let index = bassStreams.index(of: bassStream) { _ = bassStreams.remove(at: index) } } } func cleanup() { BASS_SetDevice(deviceNumber) bassStreamsLock.synchronized { for bassStream in bassStreams { bassStream.shouldBreakWaitLoopForever = true BASS_Mixer_ChannelRemove(bassStream.stream) BASS_StreamFree(bassStream.stream) } bassStreams.removeAll() } } }
gpl-3.0
519d4f2cb6285eda5a3a4507a4474e0a
28.381818
113
0.631807
4.488889
false
false
false
false
sehkai/SKSwiftExtension
Pod/Classes/String+extension.swift
1
5005
// // String+extension.swift // SKSwiftExtension // // Created by Matthew Nguyen on 8/15/15. // Copyright (c) 2015 Solfanto, Inc. All rights reserved. // import Foundation public func t(text: String, comment: String = "") -> String { return NSLocalizedString(text, comment: comment) } extension String { public subscript (i: Int) -> String { if self.characters.count > i && i >= 0 { return String(self[self.characters.index(self.startIndex, offsetBy: i)]) } else if i <= 0 && i >= -self.characters.count { return String(self[self.characters.index(self.startIndex, offsetBy: self.characters.count + i)]) } return "" } public subscript (r: Range<Int>) -> String { var firstIndex = r.lowerBound var lastIndex = r.upperBound let length = self.characters.count if length == 0 { return "" } // authorize out of bounds range if firstIndex < -length { firstIndex = -length } if lastIndex < -length { lastIndex = -length } if firstIndex > length { firstIndex = length } if lastIndex > length { lastIndex = length } // modulo in Swift sucks if firstIndex < 0 { firstIndex = (length + (firstIndex % length)) % length // exception with index = -1 if lastIndex == 0 { lastIndex = length } } if lastIndex < 0 { lastIndex = (length + (lastIndex % length)) % length } // ensure the order is fine if firstIndex > lastIndex { let tmpIndex = firstIndex firstIndex = lastIndex lastIndex = tmpIndex } return substring(with: Range(characters.index(startIndex, offsetBy: firstIndex)..<characters.index(startIndex, offsetBy: lastIndex))) } public subscript (r: CountableClosedRange<Int>) -> String { var firstIndex = r.lowerBound var lastIndex = r.upperBound let length = self.characters.count if length == 0 { return "" } // modulo in Swift sucks let moduloedFirstIndex = (length + (firstIndex % length)) % length let moduloedLastIndex = (length + (lastIndex % length)) % length if moduloedFirstIndex > moduloedLastIndex { firstIndex = firstIndex + 1 // exception with index = -1 if firstIndex == 0 { firstIndex = length } } else { lastIndex = lastIndex + 1 // exception with index = -1 if lastIndex == 0 { lastIndex = length } } // ensure the order is fine if firstIndex > lastIndex { let tmpIndex = firstIndex firstIndex = lastIndex lastIndex = tmpIndex } return self[firstIndex ..< lastIndex] } public func replace(_ pattern: String, withString text: String, options: [String:AnyObject]!) -> String { let length = self.characters.count var regexOptions: NSRegularExpression.Options if let caseSensitive = options["caseSensitive"] { if caseSensitive as? Bool == true { regexOptions = NSRegularExpression.Options.init(rawValue: 0) } else { regexOptions = NSRegularExpression.Options.caseInsensitive } } else { regexOptions = NSRegularExpression.Options.init(rawValue: 0) } let regex = try! NSRegularExpression(pattern: pattern, options: regexOptions) return regex.stringByReplacingMatches(in: self, options: [], range: NSMakeRange(0, length), withTemplate: text) } public func split(_ splitter: String) -> Array<String> { return self.components(separatedBy: splitter) } // http://stackoverflow.com/questions/25138339/nsrange-to-rangestring-index public func nsRange(from range: Range<String.Index>) -> NSRange { let from = range.lowerBound.samePosition(in: utf16) let to = range.upperBound.samePosition(in: utf16) return NSRange(location: utf16.distance(from: utf16.startIndex, to: from), length: utf16.distance(from: from, to: to)) } public func range(from nsRange: NSRange) -> Range<String.Index>? { guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex), let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex), let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) else { return nil } return from ..< to } }
mit
12659b7336013d06d69c28ee4ab695bb
32.590604
141
0.560639
4.89726
false
false
false
false
woodcockjosh/FastContact
Core/FastContactTableViewController.swift
1
7438
// // FastContactTableViewController.swift // FastContact // // Created by Josh Woodcock on 8/22/15. // Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved. // import UIKit class FastContactTableViewController: UITableViewController { private var _currentViewState: FastContactViewState!; internal var _fastContactListManager: FastContactListManager!; internal var _currentListIndex: Int!; internal var _lists: Array<Array<Array<IListItem>>>!; @IBAction func provideAccessWithNoAccessClicked(sender: UIButton) { APAddressBook.requestAccess { (didProvideAccess: Bool, error: NSError!) -> Void in var state: FastContactViewState!; if(didProvideAccess) { state = .ManyWithAccessAndFiller; }else{ state = FastContactHelper.getViewStateWithListCountAndAccess(self._lists[self._currentListIndex], useFiller: self.shouldShowFillerInNonEmptyList()); } self._fastContactListManager.updateListsForState(state); } } @IBAction func provideAccessWithBlockedAccessClicked(sender: UIButton) { if(FastContactConstant.IOS_MAIN_VERSION >= 8.0) { UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!); } } override func viewDidLoad() { super.viewDidLoad() self._currentViewState = FastContactHelper.getDefaultViewStateBasedOnPhoneContactAccess(); self._fastContactListManager = FastContactListManager( listCount: self.getListCount(), itemsBeforeEmptyListMax: self.getItemsBeforeEmptyListMax(), updateBlock: {()->Void in self._lists = self._fastContactListManager.getLists(); self._updateViewStateAndData(); } ); self._currentListIndex = self.getDefaultListItem(); self._lists = self._fastContactListManager.getLists(); } 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 _lists[_currentListIndex].count; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _lists[_currentListIndex][section].count; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = _getTableViewCellForState(tableView, cellForRowAtIndexPath: indexPath, state: _currentViewState); return cell; } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var list = _lists[_currentListIndex]; var section = list[indexPath.section]; var row = section[indexPath.row]; if(!(row is EmptyListItem)) { return super.tableView(tableView, heightForRowAtIndexPath: indexPath); }else{ return self._getEmptyTableViewCellHeight(indexPath); } } /// MARK FastContactTableViewController internal func getListCount() -> Int { return 1; } internal func getDefaultListItem() -> Int { return 0; } internal func getEmptyTableViewCell(tableView: UITableView, state: FastContactViewState) -> UITableViewCell { return UITableViewCell(); } internal func getNonEmptyTableViewCell(tableView: UITableView, state: FastContactViewState) -> UITableViewCell { return UITableViewCell(); } internal func setViewState(state: FastContactViewState) { self._currentViewState = state; } internal func getViewState()->FastContactViewState { return self._currentViewState; } internal func getItemsBeforeEmptyListMax()->Int { if(FastContactConstant.IOS_MAIN_VERSION >= 8) { return 3; }else{ return 2; } } internal func shouldShowFillerInNonEmptyList() -> Bool { return true; } internal func setProvideAccessButton(button: UIButton) { switch(_currentViewState!) { case .EmptyNoAccess: self._setProvideNoAccessButton(button); break; case .ManyNoAccess: self._setProvideNoAccessButton(button); break; case .EmptyBlockedAccess: self._setProvideBlockedAccessButton(button); break; case .ManyBlockedAccess: self._setProvideBlockedAccessButton(button); break; default: break; } } private func _updateViewStateAndData() { self._currentViewState = FastContactHelper.getViewStateWithListCountAndAccess(self._lists[self._currentListIndex], useFiller: shouldShowFillerInNonEmptyList()); self.tableView.reloadData(); } /// MARK Private methods private func _getTableViewCellForState(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, state: FastContactViewState) -> UITableViewCell { var cell: UITableViewCell!; var listItem: IListItem = _lists[_currentListIndex][indexPath.section][indexPath.row]; if(listItem is EmptyListItem) { cell = getEmptyTableViewCell(tableView, state: state); cell = _getEmptyCellWithAttributes(cell); }else{ cell = getNonEmptyTableViewCell(tableView, state: state); } return cell; } private func _getEmptyCellWithAttributes(cell: UITableViewCell) -> UITableViewCell { cell.selectionStyle = .None; return cell; } private func _getEmptyTableViewCellHeight(indexPath: NSIndexPath) -> CGFloat { var height: CGFloat = tableView.frame.height; var list = _lists[_currentListIndex]; if(navigationController != nil) { height -= navigationController!.navigationBar.frame.height; } height -= 20; // Subtract the height of the rows and sections var itemCount = 0; for section in list { var sectionHeight = self.tableView(self.tableView, heightForHeaderInSection: indexPath.section); height -= sectionHeight; for item in section { if(!(item is EmptyListItem)) { var cellHeight = super.tableView(self.tableView, heightForRowAtIndexPath: indexPath); height -= cellHeight; itemCount++; if(itemCount >= getItemsBeforeEmptyListMax()) { return height; } } } } return height; } private func _setProvideNoAccessButton(button: UIButton) { button.addTarget(self, action: "provideAccessWithNoAccessClicked:", forControlEvents: UIControlEvents.TouchUpInside); } private func _setProvideBlockedAccessButton(button: UIButton) { button.addTarget(self, action: "provideAccessWithBlockedAccessClicked:", forControlEvents: UIControlEvents.TouchUpInside); } }
mit
02ddeff5213a6a191a844711c00f56dc
34.084906
168
0.635386
5.397678
false
false
false
false
devinross/curry-fire
curryfire/UIView+TwelvePrinciples.swift
1
18812
// // UIView+TwelvePrinciples.swift // Created by Devin Ross on 9/13/16. // /* curryfire || https://github.com/devinross/curry-fire 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 extension UIView { /** Zoom view to point. @param toYPoint The place to zoom to. @param completion The completion callback handler. */ @objc public func zoomToYPoint(_ toYPoint: CGFloat, completion: ((Bool) -> Void)? ) { zoomToYPoint(toYPoint, duration: 0.7, delay: 0, completion: completion) } /** Zoom view to point. @param toYPoint The place to zoom to. @param duration The duration of the animation. @param delay The delay before the animation is played. @param completion The completion callback handler. */ @objc public func zoomToYPoint(_ toYPoint: CGFloat, duration: TimeInterval, delay: TimeInterval, completion: ((Bool) -> Void)? ) { zoomToYPoint(toYPoint, anticipation: 30, duration: duration, delay: delay, completion: completion) } /** Zoom view to point. @param toYPoint The place to zoom to. @param anticipation How much of a windup the view moves before zooming off. @param duration The duration of the animation. @param delay The delay before the animation is played. @param completion The completion callback handler. */ @objc public func zoomToYPoint(_ toYPoint: CGFloat, anticipation: CGFloat, duration: TimeInterval, delay: TimeInterval, completion: ((Bool) -> Void)? ) { var antic = anticipation let baseTransform = self.transform if toYPoint > self.centerY { let yy: CGFloat = self.frame.minY self.layer.anchorPoint = CGPoint(x: 0.5, y: 0) self.center = CGPoint(x: self.centerX, y: yy) antic *= -1 } else { let yy: CGFloat = self.frame.maxY self.layer.anchorPoint = CGPoint(x: 0.5, y: 1) self.center = CGPoint(x: self.centerX, y: yy) } let xScale: CGFloat = 1 let yScale: CGFloat = 1 UIView.animateKeyframes(withDuration: duration, delay: delay, options: .calculationModeCubic, animations: {() -> Void in UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2, animations: {() -> Void in self.transform = CGConcat(baseTransform, CGScale(xScale + 0.1, yScale - 0.3)) }) UIView.addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 0.3, animations: {() -> Void in self.transform = CGScale(xScale - 0.3, yScale + 0.3) }) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.4, animations: {() -> Void in self.centerY += antic }) UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.6, animations: {() -> Void in self.center = CGPoint(x: self.centerX, y: toYPoint) }) }, completion: {(finished: Bool) -> Void in self.transform = baseTransform let minY: CGFloat = self.minY + self.height / 2.0 self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.centerY = minY if (completion != nil) { completion!(finished) } }) } /** Zoom view to point. @param toXPoint The place to zoom to. @param completion The completion callback handler. */ @objc public func zoomToXPoint(_ toXPoint: CGFloat, completion: ((Bool) -> Void)? ) { zoomToXPoint(toXPoint, duration: 0.7, delay: 0, completion: completion) } /** Zoom view to point. @param toXPoint The place to zoom to. @param duration The duration of the animation. @param delay The delay before the animation is played. @param completion The completion callback handler. */ @objc public func zoomToXPoint(_ toXPoint: CGFloat, duration: TimeInterval, delay: TimeInterval, completion: ((Bool) -> Void)? ) { zoomToXPoint(toXPoint, anticipation: 30, duration: duration, delay: delay, completion: completion) } /** Zoom view to point. @param toXPoint The place to zoom to. @param anticipation How much of a windup the view moves before zooming off. @param duration The duration of the animation. @param delay The delay before the animation is played. @param completion The completion callback handler. */ @objc public func zoomToXPoint(_ toXPoint: CGFloat, anticipation: CGFloat, duration: TimeInterval, delay: TimeInterval, completion: ((Bool) -> Void)? ) { var antic = anticipation let baseTransform = self.transform if toXPoint > self.centerX { let xx: CGFloat = self.frame.minX self.layer.anchorPoint = CGPoint(x: 0, y: 0.5) self.center = CGPoint(x: xx, y: self.centerY) antic *= -1 } else { let xx: CGFloat = self.frame.maxX self.layer.anchorPoint = CGPoint(x: 1, y: 1) self.center = CGPoint(x: xx, y: self.centerY) } let xScale: CGFloat = self.transform.a let yScale: CGFloat = self.transform.d UIView.animateKeyframes(withDuration: duration, delay: delay, options: .calculationModeCubic, animations: {() -> Void in UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2, animations: {() -> Void in self.transform = CGScale(xScale - 0.3, yScale + 0.1) }) UIView.addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 0.3, animations: {() -> Void in self.transform = CGScale(xScale + 0.3, yScale - 0.3) }) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.4, animations: {() -> Void in self.centerX += antic }) UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.6, animations: {() -> Void in self.center = CGPoint(x: toXPoint, y: self.centerY) }) }, completion: {(finished: Bool) -> Void in self.transform = baseTransform let minX: CGFloat = self.minX + self.width / 2.0 self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.centerX = minX if (completion != nil) { completion!(finished) } }) } /// Tickle the view. @objc public func tickle(){ tickle(1, delay: 0, downScale: 1, completion: nil) } /** Tickle the view. @param completion The completion callback handler. */ @objc public func tickle(_ completion: ((Bool) -> ())? ){ tickle(1, delay: 0, downScale: 1, completion: completion) } /** Tickle the view. @param duration The duration of the animation. @param downScale Downscale. @param delay The delay before the animation is played. @param completion The completion callback handler. */ @objc public func tickle(_ duration: TimeInterval, delay: TimeInterval, downScale: CGFloat, completion: ((Bool) -> ())? ){ let baseTransform = self.transform; let x = downScale UIView.animateKeyframes(withDuration: duration, delay: delay, options: [.calculationModeCubic,.allowUserInteraction] , animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.1, animations: { self.transform = CGConcat(baseTransform, CGScale(x, x)) }) UIView.addKeyframe(withRelativeStartTime: 0.1, relativeDuration: 0.2, animations: { self.transform = CGConcat(baseTransform, CGScale(x+0.05, x-0.05)) }) UIView.addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 0.2, animations: { self.transform = CGConcat(baseTransform, CGScale(x-0.05, x+0.05)) }) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.2, animations: { self.transform = CGConcat(baseTransform, CGScale(x+0.05, x-0.05)) }) UIView.addKeyframe(withRelativeStartTime: 0.7, relativeDuration: 0.2, animations: { self.transform = baseTransform }) UIView.addKeyframe(withRelativeStartTime: 0.9, relativeDuration: 0.1, animations: { self.transform = baseTransform }) },completion: { (finished) in if let complete = completion{ complete(finished) } }); } /// Wiggle the view. @objc public func wiggle() { self.wiggle(0.06) } /** Wiggle the view. @param withRotationAngle The range the view wiggle. */ @objc public func wiggle(_ withRotationAngle: CGFloat) { self.wiggle(0.5, delay: 0, rotation: withRotationAngle) } /** Wiggle the view. @param withDuration The duration of the animation. @param delay The delay before the animation is played. @param angle The range the view wiggle. */ @objc public func wiggle(_ withDuration: TimeInterval, delay: TimeInterval, rotation angle: CGFloat) { self.wiggle(withDuration, delay: delay, betweenAngleOne: angle, angleTwo: -angle) } /** Wiggle the view. @param withDuration The duration of the animation. @param delay The delay before the animation is played. @param angleOne The range the view wiggle. @param angleTwo The range the view wiggle. */ @objc public func wiggle(_ withDuration: TimeInterval, delay: TimeInterval, betweenAngleOne angleOne: CGFloat, angleTwo: CGFloat) { let transform = self.transform let currentAngle: CGFloat = atan2(transform.b, transform.a) var animation: CABasicAnimation? var second = CATransform3DMakeRotation(angleTwo, 0, 0, 1.0) var secondBeginTime: CFTimeInterval if angleOne == currentAngle || angleTwo == currentAngle { if angleTwo == currentAngle { second = CATransform3DMakeRotation(angleOne, 0, 0, 1.0) } secondBeginTime = CACurrentMediaTime() + delay } else { let first = CATransform3DMakeRotation(angleOne, 0, 0, 1.0) animation = CABasicAnimation(keyPath: "transform") animation?.fromValue = NSCATransform3D(self.layer.transform) animation?.toValue = NSCATransform3D(first) animation?.duration = withDuration / 2.0 animation?.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut) animation?.isRemovedOnCompletion = false animation?.beginTime = CACurrentMediaTime() + delay animation?.fillMode = CAMediaTimingFillMode.forwards self.add(animation) secondBeginTime = CACurrentMediaTime() + withDuration / 2.0 + delay } animation = CABasicAnimation(keyPath: "transform") // Create a basic animation to animate the layer's transform animation!.toValue = NSCATransform3D(second) // Assign the transform as the animation's value animation!.autoreverses = true animation!.duration = withDuration animation!.repeatCount = Float.infinity animation!.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) animation!.beginTime = secondBeginTime animation!.isRemovedOnCompletion = false animation!.fillMode = CAMediaTimingFillMode.forwards self.add(animation) } /// Hop the view. @objc public func hop() { self.hop(self.superview!.width * 1.5, hopHeight: 40, duration: 0.7, delay: 0, completion: { _ in }) } /** Hop the view. @param xPoint The place to hop. @param hopHeight The height of the hop. @param duration The duration of the animation. @param delay The delay before the animation is played. @param completion The completion callback handler. */ @objc public func hop(_ xPoint: CGFloat, hopHeight: CGFloat, duration: TimeInterval, delay: TimeInterval, completion: ((Bool) -> Void)?) { let y: CGFloat = self.center.y let baseTransform = self.transform let midPoint = CGPointGetMidpoint(self.center, CGPoint(x: xPoint,y: self.centerY)) UIView.animateKeyframes(withDuration: duration, delay: delay, options: .calculationModeCubic, animations: {() -> Void in UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.3, animations: {() -> Void in self.transform = CGConcat(CGScale(0.8, 1.0), CGRotate((-15.0 * CGFloat.pi) / 180.0)) }) UIView.addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 0.3, animations: {() -> Void in self.center = CGPoint(x: midPoint.x, y: y - hopHeight) self.transform = CGConcat(CGScale(1.4, 1), CGRotate((0.0 * CGFloat.pi) / 180.0)) }) UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.4, animations: {() -> Void in self.center = CGPoint(x: xPoint, y: y) }) UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.2, animations: {() -> Void in self.transform = CGConcat(CGScale(1.1, 1), CGRotate(15.0 * CGFloat.pi / 180.0)) }) UIView.addKeyframe(withRelativeStartTime: 0.8, relativeDuration: 0.2, animations: {() -> Void in self.transform = baseTransform }) }, completion: completion) } /** Shake the view. @param withDuration The duration of the animation. @param delay The delay before the animation is played. @param completion The completion callback handler. */ @objc public func shake(_ withDuration: TimeInterval, delay: TimeInterval, completion: ((Bool) -> Void)? ) { let centerY: CGFloat = self.centerY let centerX: CGFloat = self.centerX UIView.animateKeyframes(withDuration: 0.6, delay: 0, options: .calculationModeCubicPaced, animations: {() -> Void in UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.2, animations: {() -> Void in self.center = CGPoint(x: centerX - 15, y: centerY) }) UIView.addKeyframe(withRelativeStartTime: 0.2, relativeDuration: 0.2, animations: {() -> Void in self.center = CGPoint(x: centerX + 15, y: centerY) }) UIView.addKeyframe(withRelativeStartTime: 0.4, relativeDuration: 0.2, animations: {() -> Void in self.center = CGPoint(x: centerX - 10, y: centerY) }) UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.2, animations: {() -> Void in self.center = CGPoint(x: centerX + 10, y: centerY) }) UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.2, animations: {() -> Void in self.center = CGPoint(x: centerX + 0, y: centerY) }) }, completion: completion) } /** Shake the view. @param completion The completion callback handler. */ @objc public func shake(_ completion: ((Bool) -> Void)? ) { self.shake(0.6, delay: 0, completion: completion) } /** Run forrest. Run. @param toPoint The place run to. @param withCompletion The completion callback handler. */ @objc public func runForrestRun(_ toPoint: CGPoint, withCompletion completion: ((Bool) -> Void)?) { self.runForrestRun(1, delay: 0, toPoint: toPoint, completion: completion) } /** Run forrest. Run. @param duration The duration of the animation. @param delay The delay before the animation is played. @param point The place run to. @param completion The completion callback handler. */ @objc public func runForrestRun(_ duration: TimeInterval, delay: TimeInterval, toPoint point: CGPoint, completion: ((Bool) -> Void)?) { let movingRight = point.x > self.centerX let baseTransform = self.transform var transform = baseTransform transform.c = movingRight ? 0.5 : -0.5 let animation = CABasicAnimation(keyPath: "transform") animation.autoreverses = true animation.fromValue = NSValue(caTransform3D: CATransform3DMakeAffineTransform(baseTransform)) animation.toValue = NSValue(caTransform3D: CATransform3DMakeAffineTransform(transform)) animation.duration = duration / 4 self.layer.add(animation, forKey: "forrest") UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.4, options: [], animations: {() -> Void in self.center = point }, completion: completion) } /** Stop on a dime @param endXPoint The duration of the animation. @param duration The duration of the animation. @param delay The delay before the animation is played. @param completion The completion callback handler. */ @objc public func turnOnADime(_ endXPoint: CGFloat, duration: TimeInterval, delay: TimeInterval, completion: ((Bool) -> Void)?) { let movingRight = endXPoint > self.centerX let anchorX: CGFloat = movingRight ? self.maxX : self.minX let anchorY: CGFloat = self.maxY let mult: CGFloat = movingRight ? 1 : -1 self.layer.anchorPoint = movingRight ? CGPoint(x: 1, y: 1) : CGPoint(x: 0, y: 1) let twist: CGFloat = movingRight ? 0.1 : -0.1 var twistTransform = CGAffineTransform.identity twistTransform.c = twist let x: CGFloat = endXPoint + (movingRight ? 1 : -1) * self.width / 2 self.center = CGPoint(x: anchorX, y: anchorY) UIView.animateKeyframes(withDuration: duration, delay: delay, options: .calculationModeCubic, animations: { () -> Void in var s: Double = 0.0 var dur: Double = 0.3 UIView.addKeyframe(withRelativeStartTime: s, relativeDuration: dur / 2, animations: {() -> Void in self.transform = twistTransform }) UIView.addKeyframe(withRelativeStartTime: s + dur / 2, relativeDuration: dur / 2, animations: {() -> Void in var transform = CGAffineTransform.identity transform.c = 0 self.transform = transform }) UIView.addKeyframe(withRelativeStartTime: s, relativeDuration: dur, animations: {() -> Void in self.center = CGPoint(x: x + 20 * mult, y: anchorY) }) s += dur dur = 0.2 UIView.addKeyframe(withRelativeStartTime: s, relativeDuration: dur, animations: {() -> Void in var transform = CGAffineTransform.identity transform.c = 0 transform = CGConcat(transform, CGRotate(-2 * CGFloat.pi / 180.0)) self.transform = transform self.center = CGPoint(x: x + 30 * mult, y: anchorY - 16) }) s += dur dur = 0.2 UIView.addKeyframe(withRelativeStartTime: s, relativeDuration: dur, animations: {() -> Void in var transform = CGAffineTransform.identity transform.c = 0 transform = CGConcat(transform, CGRotate(-1 * CGFloat.pi / 180.0)) self.transform = transform self.center = CGPoint(x: x + 15 * mult, y: anchorY - 20) }) s += dur dur = 0.2 UIView.addKeyframe(withRelativeStartTime: s, relativeDuration: dur, animations: {() -> Void in var transform = CGAffineTransform.identity transform = CGConcat(transform, CGRotate(0 * CGFloat.pi / 180.0)) self.transform = transform self.center = CGPoint(x: x, y: anchorY) }) }, completion: { (finished) in let xx: CGFloat = self.frame.midX let yy: CGFloat = self.frame.midY self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) self.center = CGPoint(x: xx, y: yy) if (completion != nil) { completion!(finished) } }) } }
mit
f04d8da516dbb14903b10a9a322b35c1
37.235772
154
0.707687
3.692247
false
false
false
false
LoopKit/LoopKit
LoopKitUI/Views/CustomOverrideCollectionViewCell.swift
1
1970
// // CustomOverrideCollectionViewCell.swift // LoopKitUI // // Created by Michael Pangburn on 11/5/19. // Copyright © 2019 LoopKit Authors. All rights reserved. // import UIKit final class CustomOverrideCollectionViewCell: UICollectionViewCell, IdentifiableClass { @IBOutlet weak var titleLabel: UILabel! private lazy var overlayDimmerView: UIView = { let view = UIView() view.backgroundColor = .systemBackground view.alpha = 0 view.translatesAutoresizingMaskIntoConstraints = false return view }() override func awakeFromNib() { super.awakeFromNib() let selectedBackgroundView = UIView() self.selectedBackgroundView = selectedBackgroundView selectedBackgroundView.backgroundColor = .tertiarySystemFill backgroundColor = .secondarySystemGroupedBackground layer.cornerCurve = .continuous layer.cornerRadius = 16 addSubview(overlayDimmerView) NSLayoutConstraint.activate([ overlayDimmerView.leadingAnchor.constraint(equalTo: leadingAnchor), overlayDimmerView.trailingAnchor.constraint(equalTo: trailingAnchor), overlayDimmerView.topAnchor.constraint(equalTo: topAnchor), overlayDimmerView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } override func prepareForReuse() { removeOverlay(animated: false) } func applyOverlayToFade(animated: Bool) { if animated { UIView.animate(withDuration: 0.3, animations: { self.overlayDimmerView.alpha = 0.5 }) } else { self.overlayDimmerView.alpha = 0.5 } } func removeOverlay(animated: Bool) { if animated { UIView.animate(withDuration: 0.3, animations: { self.overlayDimmerView.alpha = 0 }) } else { self.overlayDimmerView.alpha = 0 } } }
mit
0cafc96edbb3600ef13e1253352431b5
27.955882
87
0.64906
5.609687
false
false
false
false
KevinGong2013/ChineseIDCardOCR
Sources/KGUtils.swift
1
1532
// // KGUtils.swift // ChineseIDCardOCR // // Created by GongXiang on 9/22/17. // Copyright © 2017 Kevin.Gong. All rights reserved. // import CoreImage import CoreGraphics public extension CGImage { func pixelBuffer(_ colorspace: CGColorSpace = CGColorSpaceCreateDeviceGray()) -> CVPixelBuffer? { var pb: CVPixelBuffer? = nil CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_OneComponent8, nil, &pb) guard let pixelBuffer = pb else { return nil } CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue:0)) let bitmapContext = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer), width: width, height: height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: colorspace, bitmapInfo: 0)! bitmapContext.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height)) return pixelBuffer } } public extension CGRect { public func scaled(to size: CGSize) -> CGRect { return CGRect( x: self.origin.x * size.width, y: self.origin.y * size.height, width: self.size.width * size.width, height: self.size.height * size.height ) } } #if os(macOS) import AppKit public extension CIImage { public convenience init?(image: NSImage) { guard let tiffData = image.tiffRepresentation else { return nil } self.init(data: tiffData) } } #endif
apache-2.0
f4dd0ae3e56876814abcb6a4c9cec061
27.351852
226
0.658393
4.386819
false
false
false
false
airspeedswift/swift-compiler-crashes
crashes-duplicates/01161-getselftypeforcontainer.swift
12
989
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol b { func a<d>() -> [c<d>] { } var _ = i() { } func c<d { enum c { } } protocol A { } struct B<T : A> { } protocol C { } struct D : C { func g<T where T.E == F>(f: B<T>) { } } func some<S: SequenceType, T where Optional<T> == S.Generator.Element>(xs : S) -> T? { for (mx : T?) in xs { if let x = mx { } } } protocol a { } class b<h : c, i : c where h.g == i> : a { } class b<h, i> { } protocol c { } struct d<f : e, g: e where g.h == f.h> { } protocol e { } var f1: Int -> Int = { } let succeeds: Int = { (x: Int, f: Int -> Int) -> Int in }(x1, f1) let crashes: Int = { x, f in }(x1, f1) func f() { } protocol a { } class b: a { } protocol A { } struct X<Y> : A { func b(b: X.Type) { } } class A<T : A> { } class c { func b((Any, c))(a: (Any, AnyObject)) { } } func a<T>() { enum b { } } protocol c : b { func b
mit
0581617f69d9d355b39f75cbfa376ca2
13.128571
87
0.548028
2.321596
false
false
false
false
e-how/kingTrader
kingTrader/Pods/CryptoSwift/CryptoSwift/SHA2.swift
20
12132
// // SHA2.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 24/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // import Foundation final class SHA2 : HashProtocol { var size:Int { return variant.rawValue } let variant:SHA2.Variant let message: NSData init(_ message:NSData, variant: SHA2.Variant) { self.variant = variant self.message = message } enum Variant: RawRepresentable { case sha224, sha256, sha384, sha512 typealias RawValue = Int var rawValue: RawValue { switch (self) { case .sha224: return 224 case .sha256: return 256 case .sha384: return 384 case .sha512: return 512 } } init?(rawValue: RawValue) { switch (rawValue) { case 224: self = .sha224 break; case 256: self = .sha256 break; case 384: self = .sha384 break; case 512: self = .sha512 break; default: return nil } } var size:Int { return self.rawValue } private var h:[UInt64] { switch (self) { case .sha224: return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4] case .sha256: return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] case .sha384: return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4] case .sha512: return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179] } } private var k:[UInt64] { switch (self) { case .sha224, .sha256: return [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2] case .sha384, .sha512: return [0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817] } } private func resultingArray<T>(hh:[T]) -> [T] { var finalHH:[T] = hh; switch (self) { case .sha224: finalHH = Array(hh[0..<7]) break; case .sha384: finalHH = Array(hh[0..<6]) break; default: break; } return finalHH } } //FIXME: I can't do Generic func out of calculate32 and calculate64 (UInt32 vs UInt64), but if you can - please do pull request. func calculate32() -> NSData { let tmpMessage = self.prepare(64) // hash values var hh = [UInt32]() variant.h.forEach {(h) -> () in hh.append(UInt32(h)) } // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits. tmpMessage.appendBytes((message.length * 8).bytes(64 / 8)); // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 for chunk in NSDataSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into sixty-four 32-bit words: var M:[UInt32] = [UInt32](count: variant.k.count, repeatedValue: 0) for x in 0..<M.count { switch (x) { case 0...15: var le:UInt32 = 0 chunk.getBytes(&le, range:NSRange(location:x * sizeofValue(le), length: sizeofValue(le))); M[x] = le.bigEndian break default: let s0 = rotateRight(M[x-15], n: 7) ^ rotateRight(M[x-15], n: 18) ^ (M[x-15] >> 3) //FIXME: n let s1 = rotateRight(M[x-2], n: 17) ^ rotateRight(M[x-2], n: 19) ^ (M[x-2] >> 10) M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1 break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] var F = hh[5] var G = hh[6] var H = hh[7] // Main loop for j in 0..<variant.k.count { let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22) let maj = (A & B) ^ (A & C) ^ (B & C) let t2 = s0 &+ maj let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25) let ch = (E & F) ^ ((~E) & G) let t1 = H &+ s1 &+ ch &+ UInt32(variant.k[j]) &+ M[j] H = G G = F F = E E = D &+ t1 D = C C = B B = A A = t1 &+ t2 } hh[0] = (hh[0] &+ A) hh[1] = (hh[1] &+ B) hh[2] = (hh[2] &+ C) hh[3] = (hh[3] &+ D) hh[4] = (hh[4] &+ E) hh[5] = (hh[5] &+ F) hh[6] = (hh[6] &+ G) hh[7] = (hh[7] &+ H) } // Produce the final hash value (big-endian) as a 160 bit number: let buf: NSMutableData = NSMutableData(); variant.resultingArray(hh).forEach{ (item) -> () in var i:UInt32 = UInt32(item.bigEndian) buf.appendBytes(&i, length: sizeofValue(i)) } return buf.copy() as! NSData; } func calculate64() -> NSData { let tmpMessage = self.prepare(128) // hash values var hh = [UInt64]() variant.h.forEach {(h) -> () in hh.append(h) } // append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits. tmpMessage.appendBytes((message.length * 8).bytes(64 / 8)); // Process the message in successive 1024-bit chunks: let chunkSizeBytes = 1024 / 8 // 128 var leftMessageBytes = tmpMessage.length for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes { let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes))) // break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 64-bit words into eighty 64-bit words: var M = [UInt64](count: variant.k.count, repeatedValue: 0) for x in 0..<M.count { switch (x) { case 0...15: var le:UInt64 = 0 chunk.getBytes(&le, range:NSRange(location:x * sizeofValue(le), length: sizeofValue(le))); M[x] = le.bigEndian break default: let s0 = rotateRight(M[x-15], n: 1) ^ rotateRight(M[x-15], n: 8) ^ (M[x-15] >> 7) let s1 = rotateRight(M[x-2], n: 19) ^ rotateRight(M[x-2], n: 61) ^ (M[x-2] >> 6) M[x] = M[x-16] &+ s0 &+ M[x-7] &+ s1 break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] var F = hh[5] var G = hh[6] var H = hh[7] // Main loop for j in 0..<variant.k.count { let s0 = rotateRight(A,n: 28) ^ rotateRight(A,n: 34) ^ rotateRight(A,n: 39) //FIXME: n: let maj = (A & B) ^ (A & C) ^ (B & C) let t2 = s0 &+ maj let s1 = rotateRight(E,n: 14) ^ rotateRight(E,n: 18) ^ rotateRight(E,n: 41) let ch = (E & F) ^ ((~E) & G) let t1 = H &+ s1 &+ ch &+ variant.k[j] &+ UInt64(M[j]) H = G G = F F = E E = D &+ t1 D = C C = B B = A A = t1 &+ t2 } hh[0] = (hh[0] &+ A) hh[1] = (hh[1] &+ B) hh[2] = (hh[2] &+ C) hh[3] = (hh[3] &+ D) hh[4] = (hh[4] &+ E) hh[5] = (hh[5] &+ F) hh[6] = (hh[6] &+ G) hh[7] = (hh[7] &+ H) } // Produce the final hash value (big-endian) let buf: NSMutableData = NSMutableData(); variant.resultingArray(hh).forEach({ (item) -> () in var i = item.bigEndian buf.appendBytes(&i, length: sizeofValue(i)) }) return buf.copy() as! NSData; } }
apache-2.0
9381e9e6801504f94c9774e5eb607569
41.247387
183
0.508743
3.06859
false
false
false
false