repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
CodetrixStudio/CSJson
CSJson/CSSerializable.swift
1
6692
// // CSJson.swift // CSJson // // Created by Parveen Khatkar on 11/3/15. // Copyright © 2015 Codetrix Studio. All rights reserved. // import Foundation public protocol CSSerializable { mutating func deserialize(_ val: AnyObject, settings: CSJsonSettings?); func dateFormat(_ key: String) -> String func serialize() -> Any; } extension CSSerializable { public func dateFormat(_ key: String) -> String { return CSJsonSettings.GlobalSettings.DateFormat; } public func serialize() -> Any { return self; } } extension Bool: CSSerializable { mutating public func deserialize(_ val: AnyObject, settings: CSJsonSettings?) { self = Int(val as! NSNumber) == 1; } } extension Double: CSSerializable { mutating public func deserialize(_ val: AnyObject, settings: CSJsonSettings?) { if let num = Double(val as! String) { self = num; } } } extension Float: CSSerializable { mutating public func deserialize(_ val: AnyObject, settings: CSJsonSettings?) { if let num = Float(val as! String) { self = num; } } } extension Int: CSSerializable { mutating public func deserialize(_ val: AnyObject, settings: CSJsonSettings?) { if let num = Int(val as! String) { self = num; } } } //extension NSDate: CSSerializable //{ // public convenience init(val: String) // { // self.init(); // self = val.toDate(CSJson.dateFormat(key, settings: settings)); // } //} extension NSObject: CSSerializable { public func deserialize(_ val: AnyObject, settings: CSJsonSettings?) { let json = val as! [String: AnyObject]; let properties = Mirror(reflecting: self).children; for (key,value) in json { let property = properties.filter({ (label: String?, value: Any) -> Bool in if label == key { return true; } return false; }).first; if property == nil { continue; } let currentProperty = property! // Debugging.. // if key == "favFriend" // { // print(String(currentProperty.value.dynamicType)) // let elementType = CSJson.csOptionalTypeDictionary[String(currentProperty.value.dynamicType)] // print(elementType!) // } if type(of: currentProperty.value) == Date?.self || String(describing: type(of: currentProperty.value)) == "__NSTaggedDate" { var settings: CSJsonSettings? if let dataSource = self as? CSJsonDataSource { settings = dataSource.settings(); } self.setValue((value as! String).toDate(CSJson.dateFormat(key, settings: settings)), forKey: key); } else if let elementType = CSJsonHelper.modelType(type(of: currentProperty.value)) { let obj = elementType.init(); var settings: CSJsonSettings? if let dataSource = obj as? CSJsonDataSource { settings = dataSource.settings(); } obj.deserialize(value, settings: settings); self.setValue(obj, forKey: key); } else if let elementType = CSJsonHelper.modelArrayType(type(of: currentProperty.value)) { var array = [AnyObject](); let jsonArray = value as! [[String:AnyObject]] for json in jsonArray { var obj: CSSerializable = elementType.init(); obj.deserialize(json as AnyObject, settings: nil); array.append(obj as AnyObject); } self.setValue(array, forKey: key); } else { self.setValue(value, forKey: key); } } } public func serialize() -> Any { var json = Dictionary<String, AnyObject>() var mirror: Mirror = Mirror(reflecting: self); repeat { for property in mirror.children { if let name = property.label { if property.value as? Date != nil { var settings: CSJsonSettings? if let dataSource = self as? CSJsonDataSource { settings = dataSource.settings(); } json[name] = (self.value(forKey: name) as? Date)?.toString(CSJson.dateFormat(name, settings: settings)) as AnyObject?; } else if let _ = CSJsonHelper.modelType(type(of: property.value)) { //this is a nested NSObject object but still doesn't confirm to CSSerializable ???? json[name] = (self.value(forKey: name) as! NSObject).serialize() as? AnyObject; print("aaa"); } else if let _ = CSJsonHelper.modelArrayType(type(of: property.value)) { var array = [AnyObject](); let csArray = self.value(forKey: name) as! [NSObject]; for item in csArray { array.append(item.serialize() as AnyObject); } json[name] = array as AnyObject?; } else if property.value is CSSerializable || property.value as? String != nil //type(of: (property.value) as AnyObject) is String?.Type { json[name] = self.value(forKey: name) as AnyObject?; } } } if let superMirror = mirror.superclassMirror { mirror = superMirror; } else { break; } } while mirror.subjectType != NSObject.self return json; } } extension String: CSSerializable { mutating public func deserialize(_ val: AnyObject, settings: CSJsonSettings?) { self = String(format: val as! String); } }
gpl-3.0
3a6c47a2e5512bebb832cbf2cfedcce4
29.834101
154
0.491107
5.057445
false
false
false
false
MadAppGang/SmartLog
iOS/SmartLog/Managers/PebbleDataSaver.swift
1
9269
// // PebbleDataSaver.swift // SmartLog // // Created by Dmytro Lisitsyn on 7/7/16. // Copyright © 2016 MadAppGang. All rights reserved. // import Foundation final class PebbleDataSaver { private let storageService: StorageService private var pebbleDataHandlingRunning = false private var pebbleDataToHandleIDs: Set<Int> = [] private var dataSavingCompletionBlocks: [Int: () -> Void] = [:] init(storageService: StorageService) { self.storageService = storageService storageService.fetchPebbleDataIDs() { pebbleDataToHandleIDs in self.pebbleDataToHandleIDs = pebbleDataToHandleIDs self.handlePebbleData() } } func save(bytes: [UInt8], of pebbleDataType: PebbleData.DataType, sessionTimestamp: UInt32, completion: (() -> Void)? = nil) { DispatchQueue.global(qos: .utility).async { let id = UUID().hashValue let sessionID = Int(sessionTimestamp) let binaryData = Data(bytes: bytes, count: bytes.count) let pebbleData = PebbleData(id: id, sessionID: sessionID, dataType: pebbleDataType, binaryData: binaryData) self.storageService.create(pebbleData, completionQueue: .main) { self.pebbleDataToHandleIDs.insert(id) if let completion = completion { self.dataSavingCompletionBlocks[id] = completion } if !self.pebbleDataHandlingRunning { self.handlePebbleData() } } } } private func handlePebbleData() { pebbleDataHandlingRunning = pebbleDataToHandleIDs.first != nil guard let pebbleDataID = pebbleDataToHandleIDs.first else { return } let utilityQueue: DispatchQueue = .global(qos: .utility) utilityQueue.async { self.storageService.fetchPebbleData(pebbleDataID: pebbleDataID, completionQueue: utilityQueue) { pebbleData in guard let pebbleData = pebbleData else { return } let completion: () -> Void = { self.pebbleDataToHandleIDs.remove(pebbleDataID) if let completionBlock = self.dataSavingCompletionBlocks[pebbleDataID] { self.dataSavingCompletionBlocks.removeValue(forKey: pebbleDataID) completionBlock() } self.handlePebbleData() } switch pebbleData.dataType { case .accelerometerData: self.createAccelerometerData(from: pebbleData, completionQueue: .main, completion: completion) case .markers: self.createMarkers(from: pebbleData, completionQueue: .main, completion: completion) case .activityType: self.handleActivityType(from: pebbleData, completionQueue: .main, completion: completion) } } } } private func createAccelerometerData(from pebbleData: PebbleData, completionQueue: DispatchQueue, completion: @escaping () -> Void) { var accelerometerData: [AccelerometerData] = [] var bytes = [UInt8](repeating: 0, count: pebbleData.binaryData.count) pebbleData.binaryData.copyBytes(to: &bytes, count: bytes.count) let batchSize = 10 // Batch size in bytes (configured in pebble app). let bytesBatchesToConvert = bytes.count / batchSize - 1 for index in 0...bytesBatchesToConvert { let batchFirstByteIndex = index * batchSize let batchLastByteIndex = batchFirstByteIndex + batchSize let accelerometerDataBytes = Array(bytes[batchFirstByteIndex..<batchLastByteIndex]) let tenthOfTimestamp = TimeInterval(index % 10) / 10 let accelerometerDataSample = convertToAccelerometerData(bytes: accelerometerDataBytes, sessionID: pebbleData.sessionID, tenthOfTimestamp: tenthOfTimestamp) accelerometerData.append(accelerometerDataSample) } getOrCreateSession(sessionID: pebbleData.sessionID, completionQueue: completionQueue) { session in var session = session session.samplesCount.accelerometerData = session.samplesCountValue.accelerometerData + accelerometerData.count let batchesPerSecond = 10 // Based on 10Hz frequency presetted in Pebble app session.duration = Double(session.samplesCountValue.accelerometerData) / Double(batchesPerSecond) self.storageService.createOrUpdate(session, completionQueue: completionQueue) { self.storageService.create(accelerometerData, completionQueue: completionQueue) { self.storageService.deletePebbleData(pebbleDataID: pebbleData.id, completionQueue: completionQueue) { completion() } } } } } private func convertToAccelerometerData(bytes: [UInt8], sessionID: Int, tenthOfTimestamp: TimeInterval) -> AccelerometerData { var range = 0..<MemoryLayout<Int16>.size let x = Int(UnsafePointer(Array(bytes[range])).withMemoryRebound(to: Int16.self, capacity: 1, { $0.pointee })) range = range.upperBound..<(range.upperBound + MemoryLayout<Int16>.size) let y = Int(UnsafePointer(Array(bytes[range])).withMemoryRebound(to: Int16.self, capacity: 1, { $0.pointee })) range = range.upperBound..<(range.upperBound + MemoryLayout<Int16>.size) let z = Int(UnsafePointer(Array(bytes[range])).withMemoryRebound(to: Int16.self, capacity: 1, { $0.pointee })) range = range.upperBound..<(range.upperBound + MemoryLayout<UInt32>.size) let timestamp = TimeInterval(UnsafePointer(Array(bytes[range])).withMemoryRebound(to: UInt32.self, capacity: 1, { $0.pointee })) let accelerometerData = AccelerometerData(sessionID: sessionID, x: x, y: y, z: z, dateTaken: Date(timeIntervalSince1970: timestamp + tenthOfTimestamp)) return accelerometerData } private func createMarkers(from pebbleData: PebbleData, completionQueue: DispatchQueue, completion: @escaping () -> Void) { var bytes = [UInt8](repeating: 0, count: pebbleData.binaryData.count) pebbleData.binaryData.copyBytes(to: &bytes, count: bytes.count) let markersData = pebbleData.binaryData.withUnsafeBytes { pointer -> [UInt32] in return Array(UnsafeBufferPointer<UInt32>(start: pointer, count: pebbleData.binaryData.count / MemoryLayout<UInt32>.size)) } let markers = markersData .map({ Marker(sessionID: pebbleData.sessionID, dateAdded: Date(timeIntervalSince1970: TimeInterval($0))) }) .filter({ $0.dateAdded.timeIntervalSince1970 != 0 }) getOrCreateSession(sessionID: pebbleData.sessionID, completionQueue: completionQueue) { session in var session = session session.markersCount = session.markersCountValue + markers.count self.storageService.createOrUpdate(session, completionQueue: completionQueue) { self.storageService.create(markers, completionQueue: completionQueue) { self.storageService.deletePebbleData(pebbleDataID: pebbleData.id, completionQueue: completionQueue) { completion() } } } } } private func handleActivityType(from pebbleData: PebbleData, completionQueue: DispatchQueue, completion: @escaping () -> Void) { var activityTypeData = [UInt8](repeating: 0, count: pebbleData.binaryData.count) pebbleData.binaryData.copyBytes(to: &activityTypeData, count: activityTypeData.count) getOrCreateSession(sessionID: pebbleData.sessionID, completionQueue: completionQueue) { session in var session = session if let rawValue = activityTypeData.first, let activityType = ActivityType(rawValue: Int(rawValue)) { session.activityType = activityType } self.storageService.createOrUpdate(session, completionQueue: completionQueue) { self.storageService.deletePebbleData(pebbleDataID: pebbleData.id, completionQueue: completionQueue) { completion() } } } } private func getOrCreateSession(sessionID: Int, completionQueue: DispatchQueue, completion: @escaping (_ session: Session) -> Void) { storageService.fetchSession(sessionID: sessionID, completionQueue: completionQueue) { existingSession in if let existingSession = existingSession { completion(existingSession) } else { let session = Session(id: sessionID, dateStarted: Date(timeIntervalSince1970: TimeInterval(sessionID))) completion(session) } } } }
mit
00d19cefb80ee316f49d807bd48a2c1b
47.52356
168
0.629586
5.14603
false
false
false
false
scamps88/ASBubbleMenu
UIConcept/ASBubbleMenu/ASMenuBubble.swift
1
14119
// // ASMenuBubble.swift // // // Created by alberto.scampini on 12/01/2016. // Copyright © 2016 Alberto Scampini. All rights reserved. // import UIKit protocol ASMenuBubbleDelegate { func ASMenuBubbleSelectedMenuItemAtIndex (index : NSInteger) } class ASMenuBubble: UIView { let animationTime = 0.2 let backgrowndAlpha = 0.5 var delegate : ASMenuBubbleDelegate? var sheetView : UIView? var scrollView : UIScrollView? var bubbleDimension : CGFloat? var bubbleCloseDimension : CGFloat? var unitSize : CGFloat! var bubblesCount : NSInteger! var currentIcons : Array<UIImage>! //MARK: initialisations override init(frame: CGRect) { let mainWindow : UIWindow = UIApplication.sharedApplication().keyWindow! super.init(frame: mainWindow.bounds) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } func commonInit() { self.backgroundColor = UIColor.clearColor() //orientation notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "orientationChanged", name: UIDeviceOrientationDidChangeNotification, object: nil) } func orientationChanged() { self.performSelector("updateOrientation", withObject: nil, afterDelay: 0.2) } func updateOrientation() { self.mathCalculations() self.openAnimated(false) } //MARK: public methods func showWithIcons(icons : Array<UIImage?>) { //check bubble dimension if (self.bubbleDimension == nil) { bubbleDimension = 100 } else if (bubbleDimension < 40) { self.bubbleDimension = 40 NSLog(" ! ASMenuBubble - bubbleDimension too small") } //check icons currentIcons = Array<UIImage>() for icon in icons { if (icon == nil) { currentIcons.append(UIImage(named: "menuBubbleV")!) } else { currentIcons.append(icon!) } } self.createLayout() self.mathCalculations() //add the clese bubble in starting position (out of the screen) let initialCloseFrame = CGRect(x: (self.sheetView!.frame.size.width - self.bubbleCloseDimension!) / 2, y: self.sheetView!.frame.size.height, width: self.bubbleCloseDimension!, height: self.bubbleCloseDimension!) self.addBubbleWithFrame(initialCloseFrame, image: UIImage(named: "menuBubbleX")!, tag: -1) //add the bubbles in starting position (out of the screen) let initialFrame = CGRect(x: (self.sheetView!.frame.size.width - bubbleDimension!) / 2, y: self.scrollView!.contentSize.height, width: bubbleDimension!, height: bubbleDimension!) for index in 0...(self.currentIcons.count - 1) { self.addBubbleWithFrame(initialFrame, image: currentIcons[index], tag: index + 1) } self.openAnimated(true) } func createLayout() { //add self as a layer let mainWindow : UIWindow = UIApplication.sharedApplication().keyWindow! mainWindow.addSubview(self) //self layout self.translatesAutoresizingMaskIntoConstraints = false let selfTop = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: mainWindow, attribute: .Top, multiplier: 1, constant: 0) let selfBottom = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: mainWindow, attribute: .Bottom, multiplier: 1, constant: 0) let selfLeft = NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: mainWindow, attribute: .Left, multiplier: 1, constant: 0) let selfRight = NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: mainWindow, attribute: .Right, multiplier: 1, constant: 0) mainWindow.addConstraints([selfTop, selfBottom, selfLeft, selfRight]) //create container view self.sheetView?.removeFromSuperview() self.sheetView = UIView.init(frame:self.bounds) self.sheetView?.backgroundColor = UIColor.clearColor() self.addSubview(self.sheetView!) //sheetWiew constraint self.sheetView!.translatesAutoresizingMaskIntoConstraints = false let sheetViewTop = NSLayoutConstraint(item: self.sheetView!, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0) let sheetViewBottom = NSLayoutConstraint(item: self.sheetView!, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0) let sheetViewRight = NSLayoutConstraint(item: self.sheetView!, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1, constant: 0) let sheetViewLeft = NSLayoutConstraint(item: self.sheetView!, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 0) self.addConstraints([sheetViewTop, sheetViewBottom, sheetViewLeft, sheetViewRight]) //create the scroll view self.scrollView = UIScrollView(frame:self.bounds) self.sheetView?.addSubview(self.scrollView!) self.scrollView?.translatesAutoresizingMaskIntoConstraints = false //sheetWiew constraint let scrollViewTop = NSLayoutConstraint(item: self.scrollView!, attribute: .Top, relatedBy: .Equal, toItem: self.sheetView, attribute: .Top, multiplier: 1, constant: 0) let scrollViewBottom = NSLayoutConstraint(item: self.scrollView!, attribute: .Bottom, relatedBy: .Equal, toItem: self.sheetView, attribute: .Bottom, multiplier: 1, constant: 0) let scrollViewRight = NSLayoutConstraint(item: self.scrollView!, attribute: .Right, relatedBy: .Equal, toItem: self.sheetView, attribute: .Right, multiplier: 1, constant: 0) let scrollViewLeft = NSLayoutConstraint(item: self.scrollView!, attribute: .Left, relatedBy: .Equal, toItem: self.sheetView, attribute: .Left, multiplier: 1, constant: 0) self.sheetView!.addConstraints([scrollViewTop, scrollViewBottom, scrollViewLeft, scrollViewRight]) } func mathCalculations() { //calculate number of bubble per row let unitsCount = NSInteger(self.frame.size.width / (self.bubbleDimension! / 2)) bubblesCount = NSInteger(unitsCount / 2) - 1 self.unitSize = (self.frame.size.width - (CGFloat(self.bubblesCount) * bubbleDimension!)) / (CGFloat(self.bubblesCount) + 1) //calculate close bubble dimension self.bubbleCloseDimension = bubbleDimension! * 0.8 //calculate scroll view content size let rowNumber = ceilNSInteger(CGFloat(self.currentIcons.count) / CGFloat(self.bubblesCount)) var scrollContentHeight = (CGFloat(rowNumber) * (self.bubbleDimension! + self.unitSize)) + self.bubbleCloseDimension! + 2 * self.unitSize if (scrollContentHeight < self.scrollView!.frame.size.height) { scrollContentHeight = self.scrollView!.frame.size.height } self.scrollView!.contentSize = CGSize(width: self.scrollView!.frame.size.width, height: scrollContentHeight) self.scrollView!.setContentOffset(CGPoint(x: 0, y: scrollContentHeight - self.scrollView!.frame.size.height), animated: false) } func openAnimated(animated : Bool) { let scrollContentHeight = self.scrollView!.contentSize.height //reposition first bubble (close button) at bottom center var rowOffset : CGFloat = self.sheetView!.frame.size.height - self.bubbleCloseDimension! - self.unitSize self.moveBubbleWithTag(-1, toFrame: CGRectMake((self.sheetView!.frame.size.width - self.bubbleCloseDimension!) / 2, rowOffset, self.bubbleCloseDimension!, self.bubbleCloseDimension!), animated: animated) rowOffset = (scrollContentHeight - self.bubbleCloseDimension! - self.unitSize) - bubbleDimension! - self.unitSize //reposition the bubbles (in top of close button) var currentBubbleIndex = self.currentIcons.count while (currentBubbleIndex > 0 ) { if (currentBubbleIndex >= self.bubblesCount) { //full row for index in 0...(self.bubblesCount - 1) { let emptySpaceOffset = self.unitSize * CGFloat(index + 1) let xOffset = emptySpaceOffset + bubbleDimension! * CGFloat(index) //add bubble currentBubbleIndex = currentBubbleIndex - 1 self.moveBubbleWithTag(currentBubbleIndex + 1, toFrame: CGRectMake(xOffset, rowOffset, bubbleDimension!, bubbleDimension!), animated: animated) } } else { //calculate row x offset let fullBubbleSpace = (CGFloat(currentBubbleIndex) * bubbleDimension!) let fullEmptySpace = CGFloat(currentBubbleIndex + 1) * self.unitSize let startOffset = (self.frame.size.width - (fullBubbleSpace + fullEmptySpace) ) / 2 //remining elements row for index in 0...(currentBubbleIndex - 1) { let emptySpaceOffset = self.unitSize * CGFloat(index + 1) let xOffset = emptySpaceOffset + bubbleDimension! * CGFloat(index) + startOffset //add bubble currentBubbleIndex = currentBubbleIndex - 1 self.moveBubbleWithTag(currentBubbleIndex + 1, toFrame: CGRectMake(xOffset, rowOffset, bubbleDimension!, bubbleDimension!), animated: animated) } } rowOffset = rowOffset - bubbleDimension! - self.unitSize } //background animation UIView.animateWithDuration(self.animationTime) { () -> Void in self.sheetView?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: CGFloat(self.backgrowndAlpha)) } } func closeAnimated() { //add the clese bubble in starting position (out of the screen) let initialCloseFrame = CGRect(x: (self.sheetView!.frame.size.width - self.bubbleCloseDimension!) / 2, y: self.sheetView!.frame.size.height, width: self.bubbleCloseDimension!, height: self.bubbleCloseDimension!) self.moveBubbleWithTag(-1, toFrame: initialCloseFrame, animated: true) //add the bubbles in starting position (out of the screen) let initialFrame = CGRect(x: (self.sheetView!.frame.size.width - bubbleDimension!) / 2, y: self.scrollView!.contentSize.height, width: bubbleDimension!, height: bubbleDimension!) for index in 0...(self.currentIcons.count - 1) { self.moveBubbleWithTag(index + 1, toFrame: initialFrame, animated: true) } //background animation UIView.animateWithDuration(self.animationTime, animations: { () -> Void in self.sheetView?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) }) { (flag) -> Void in self.removeFromSuperview() } } //MARK: private method private func addBubbleWithFrame(frame : CGRect, image : UIImage, tag : NSInteger) { let bubble = UIImageView.init(frame: frame) bubble.tag = tag bubble.contentMode = .ScaleAspectFit bubble.image = image //customize bubble.backgroundColor = UIColor.whiteColor() bubble.layer.cornerRadius = frame.size.height / 2 bubble.clipsToBounds = true //add touch response bubble.userInteractionEnabled = true let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:") bubble.addGestureRecognizer(tapGestureRecognizer) if (tag == -1) { //add bubble close self.sheetView!.addSubview(bubble) bubble.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 0.8) } else { //add self.scrollView!.addSubview(bubble) } } private func moveBubbleWithTag(tag : NSInteger, toFrame : CGRect, animated : Bool) { let currentBubble = self.sheetView!.viewWithTag(tag)! as UIView if (animated == true) { UIView.animateWithDuration(self.animationTime) { () -> Void in currentBubble.frame = toFrame } } else { currentBubble.frame = toFrame } } func handleTap(gestureRecognizer: UIGestureRecognizer) { if (gestureRecognizer.view?.tag == -1) { self.closeAnimated() } else { self.delegate?.ASMenuBubbleSelectedMenuItemAtIndex(NSInteger(gestureRecognizer.view!.tag) - 1) } } //MARK: math private method private func ceilNSInteger(value: CGFloat) -> NSInteger { var int = NSInteger(value) if (value - CGFloat(int) > 0) { int = int + 1 } return int } }
mit
14b393c94330ca5be22108409d9509d8
39.222222
163
0.602352
4.789009
false
false
false
false
spire-inc/Bond
Sources/AppKit/NSTextField.swift
4
2039
// // The MIT License (MIT) // // Copyright (c) 2016 Tony Arnold (@tonyarnold) // // 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 ReactiveKit import AppKit extension NSTextField { public var bnd_font: Bond<NSTextField, NSFont?> { return Bond(target: self) { $0.font = $1 } } public var bnd_textColor: Bond<NSTextField, NSColor?> { return Bond(target: self) { $0.textColor = $1 } } public var bnd_backgroundColor: Bond<NSTextField, NSColor?> { return Bond(target: self) { $0.backgroundColor = $1 } } public var bnd_placeholderString: Bond<NSTextField, String?> { return Bond(target: self) { $0.placeholderString = $1 } } public var bnd_placeholderAttributedString: Bond<NSTextField, NSAttributedString?> { return Bond(target: self) { $0.placeholderAttributedString = $1 } } } extension NSTextField: BindableProtocol { public func bind(signal: Signal<String, NoError>) -> Disposable { return bnd_stringValue.bind(signal: signal) } }
mit
67cb5fde913e26b9d08272eee8ebc72e
35.410714
86
0.725356
4.119192
false
false
false
false
crepashok/The-Complete-Watch-OS2-Developer-Course
Section-8/Baby Name Generator/Baby Name Generator WatchKit Extension/InterfaceController.swift
1
2384
// // InterfaceController.swift // Baby Name Generator WatchKit Extension // // Created by Pavlo Cretsu on 4/19/16. // Copyright © 2016 Pasha Cretsu. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet var lblName: WKInterfaceLabel! @IBOutlet var btnBoyOrGirl: WKInterfaceButton! var nameBoyArray = ["John", "Blake", "Roy", "Pasha", "Michael", "Vova", "Vasya", "Serhiy", "Slavik", "Vadim", "Bohdan", "Sasha", "Yulik", "Dyma", "Vladyk", "Mark", "Stive", "Daniel"] var nameGirlArray = ["Jane", "Joy", "Michelle", "Ashley", "Nataly", "Vika", "Nastya", "Iryna", "Olha", "Viorica", "Ljudmila", "Liana", "Joanne", "Katya", "Sveta", "Ljuda", "Sofia", "Yana"] var isGirl : Bool = true var randomIndex : Int = 0 var colorGirl = UIColor.redColor() var colorBoy = UIColor.blueColor() override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) chooseName() } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } @IBAction func btnAnotherNameClick() { chooseName() } @IBAction func btnGirlOrBoyClick() { chooseGirlOrBoy() } func chooseGirlOrBoy() { let newName : String = isGirl == true ? "Boy" : "Girl" btnBoyOrGirl.setTitle(newName) isGirl = !isGirl chooseName() } func chooseName() { var newName : String = "" if isGirl == false { randomIndex = Int(arc4random_uniform(UInt32(nameBoyArray.count - 1))) newName = nameBoyArray[randomIndex] } else { randomIndex = Int(arc4random_uniform(UInt32(nameGirlArray.count - 1))) newName = nameGirlArray[randomIndex] } let newColor = (isGirl == false) ? colorBoy : colorGirl let attString = NSMutableAttributedString(string: newName) attString.setAttributes([NSForegroundColorAttributeName: newColor], range: NSMakeRange(0, newName.characters.count)) lblName.setAttributedText(attString) } }
gpl-3.0
af4199d2f03a27916f7437f76a767f98
24.902174
192
0.576584
4.278276
false
false
false
false
materik/meviewextensions
Swift/UIView.swift
2
1733
// // UIView.swift // WatchTheDaysLeft // // Created by materik on 12/03/15. // Copyright (c) 2015 materik. All rights reserved. // import UIKit public extension UIView { // MARK: properties var x: CGFloat { set { self.frame.x = newValue } get { return self.frame.x } } var y: CGFloat { set { self.frame.y = newValue } get { return self.frame.y } } var w: CGFloat { set { self.width = newValue } get { return self.width } } var h: CGFloat { set { self.height = newValue } get { return self.height } } var width: CGFloat { set { self.frame.size.width = newValue } get { return self.frame.width } } var height: CGFloat { set { self.frame.size.height = newValue } get { return self.frame.height } } var top: CGFloat { set { self.y = newValue } get { return self.y } } var right: CGFloat { set { self.x = newValue - self.w } get { return self.x + self.w } } var bottom: CGFloat { set { self.y = newValue - self.h } get { return self.y + self.h } } var left: CGFloat { set { self.x = newValue } get { return self.x } } var origin: CGPoint { set { self.frame.origin = newValue } get { return self.frame.origin } } var size: CGSize { set { self.frame.size = newValue } get { return self.frame.size } } // MARK: init convenience init(origin: CGPoint) { self.init(frame: CGRect(origin: origin)) } convenience init(size: CGSize) { self.init(frame: CGRect(size: size)) } }
mit
321c28306743456ff0e956a0cce48696
21.506494
52
0.528563
3.726882
false
false
false
false
pvzig/SlackKit
SKServer/Sources/Model/MessageActionRequest.swift
2
2400
// // MessageActionRequest.swift // // Copyright © 2017 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !COCOAPODS import SKCore #endif public struct MessageActionRequest { public let action: Action? public let callbackID: String? public let team: Team? public let channel: Channel? public let user: User? public let actionTS: String? public let messageTS: String? public let attachmentID: String? public let token: String? public let originalMessage: Message? public let responseURL: String? internal init(response: [String: Any]?) { action = (response?["actions"] as? [Any])?.map({$0 as? [String: Any]}).first.map({Action(action: $0)}) callbackID = response?["callback_id"] as? String team = Team(team: response?["team"] as? [String: Any]) channel = Channel(channel: response?["channel"] as? [String: Any]) user = User(user: response?["user"] as? [String: Any]) actionTS = response?["action_ts"] as? String messageTS = response?["message_ts"] as? String attachmentID = response?["attachment_id"] as? String token = response?["token"] as? String originalMessage = Message(dictionary: response?["original_message"] as? [String: Any]) responseURL = response?["response_url"] as? String } }
mit
2dfb27b50523d8213ad367b285089725
43.425926
110
0.70321
4.338156
false
false
false
false
piscis/XCodeAdventuresSwift
TodoApp/TodoApp/AddViewController.swift
1
2330
// // AddViewController.swift // TodoApp // // Created by Alexander Pirsig on 18.07.14. // Copyright (c) 2014 IworxIT. All rights reserved. // import UIKit class AddViewController: UIViewController { @IBOutlet strong var titleTextField: UITextField! = UITextField() @IBOutlet strong var notesTextView: UITextView! = UITextView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addButtonTapped(sender: AnyObject) { var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() var itemList:NSMutableArray? = userDefaults.objectForKey("itemList") as? NSMutableArray var dataSet:NSMutableDictionary = NSMutableDictionary() dataSet.setObject(titleTextField.text, forKey: "itemTitle") dataSet.setObject(notesTextView.text, forKey:"itemNote") if (itemList){ var newMutableList:NSMutableArray = NSMutableArray() for dict:AnyObject in itemList! { newMutableList.addObject(dict as NSDictionary) } userDefaults.removeObjectForKey("itemList") newMutableList.addObject(dataSet) userDefaults.setObject(newMutableList, forKey: "itemList") }else{ userDefaults.removeObjectForKey("itemList") itemList = NSMutableArray() itemList!.addObject(dataSet) userDefaults.setObject(itemList, forKey: "itemList") } userDefaults.synchronize() self.navigationController.popToRootViewControllerAnimated(true) } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
unlicense
d749dd02b065359f97a25dc9a30c10a1
28.871795
106
0.632189
5.810474
false
false
false
false
CherishSmile/ZYBase
ZYBase/ThirdLib/LBXScan/LBXPermissions.swift
5
1113
// // LBXPermissions.swift // swiftScan // // Created by xialibing on 15/12/15. // Copyright © 2015年 xialibing. All rights reserved. // import UIKit import AVFoundation import Photos import AssetsLibrary class LBXPermissions: NSObject { //MARK: ---相机权限 static func isGetCameraPermission()->Bool { let authStaus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if authStaus != AVAuthorizationStatus.denied { return true } else { return false } } //MARK: ----获取相册权限 static func isGetPhotoPermission()->Bool { var bResult = false if #available(iOS 8.0, *) { if ( PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.denied ) { bResult = true } } else { if( ALAssetsLibrary.authorizationStatus() != ALAuthorizationStatus.denied ) { bResult = true } } return bResult } }
mit
509bb8098a55b7a225e6cec08c425996
19.566038
91
0.550459
4.801762
false
false
false
false
xindong-liujingfeng/new
finalMoney/finalMoney/ViewController.swift
1
21809
// // ViewController.swift // IMONEY // // Copyright © 2016年 L_J_F. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController,UIScrollViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,NSURLSessionDataDelegate,UISearchBarDelegate { var button:UIButton? var keyArray : NSMutableArray? var valueArray : NSMutableArray? var pickView: UIPickerView? var leftTableVeiw : UITableView? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.keyArray = NSMutableArray() self.valueArray = NSMutableArray() _ = self.scrollview leftTableView() creatPickView() requestUrl("http://app-cdn.2q10.com/api/v2/currency?ver=iphone") // 自定义view创建 creatSelfView() creatButton() } func creatButton() -> Void { self.button = UIButton(type: UIButtonType.System) self.button?.frame = CGRectMake(10 + (self.leftTableVeiw?.frame.width)!, self.scrollview.frame.height / 2 - 40, 40, 80) self.button!.backgroundColor = UIColor.whiteColor() self.button!.setTitle("添加", forState: UIControlState.Normal) self.button!.setTitleColor(UIColor.blackColor(),forState: .Normal) self.button!.addTarget(self, action: #selector(ViewController.buttonDid), forControlEvents: UIControlEvents.TouchUpInside) self.scrollview.addSubview(self.button!) } // MARK:button点击事件 func buttonDid() -> Void { //alertViewController创建 let alert:UIAlertController = creatAleartController() self.presentViewController(alert, animated: true, completion: nil) } func creatAleartController() -> UIAlertController { let alert:UIAlertController = UIAlertController(title: "添加", message: "添加新货币", preferredStyle: UIAlertControllerStyle.Alert) let aleartAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default) { (action:UIAlertAction) in let textField1 = alert.textFields?.first let textField2 = alert.textFields?.last self.keyArray?.insertObject((textField1?.text)!, atIndex: 0) let string = (textField2?.text)! as NSString let float = string.floatValue let number = NSNumber(float: float) self.valueArray?.insertObject(number, atIndex: 0) self.pickView?.reloadAllComponents() for i:Int in 0...3{ self.pickView?.selectRow(0, inComponent: i, animated: true) let textField = self.scrollview.viewWithTag(200 + i) as! UITextField textField.text = nil textField.placeholder = "0.00" } for i:Int in 0...3 { self.pickerView(self.pickView!, didSelectRow: 0, inComponent: i) } self.leftTableVeiw?.reloadData() } let alearAction1 = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil) alert.addTextFieldWithConfigurationHandler { (textfield:UITextField) in textfield.placeholder = "输入三字码" } alert.addTextFieldWithConfigurationHandler { (textfield:UITextField) in textfield.placeholder = "输入对美元的汇率值" } alert.addAction(alearAction1) alert.addAction(aleartAction) return alert } func creatSelfView() -> Void { for i:Int in 0...3{ let newview = newView() newview.frame = CGRectMake(10 + view.frame.size.width, CGFloat(70 * i + 30) , view.frame.size.width - 20 , 60) newview.tag = 100 + i newview.textField?.delegate = self newview.textField?.tag = 200 + i self.scrollview.addSubview(newview) } } lazy var scrollview:UIScrollView = { let width:CGFloat = self.view.frame.size.width * 2 let height:CGFloat = self.view.frame.size.height // scrollview的属性设置 var scrollView:UIScrollView = UIScrollView() scrollView.frame = CGRectMake(0, 20, width / 2, height + 20) scrollView.contentSize = CGSizeMake(width, height) scrollView.bounces = false scrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0) scrollView.showsHorizontalScrollIndicator = false scrollView.pagingEnabled = true scrollView.delegate = self let imageView = UIImageView(image: UIImage(named: "back.jpg")) imageView.frame = CGRectMake(0, 0, width, height) // scrollview添加到视图上 self.view.addSubview(scrollView) scrollView.addSubview(imageView) return scrollView }() // MARK:取消键盘的第一响应(失去焦点) 渐变效果 func scrollViewDidScroll(scrollView: UIScrollView) { self.view.endEditing(true) let width:CGFloat = self.view.bounds.size.width for i in 0...3 { var newview:newView = newView() newview = self.scrollview.viewWithTag(100 + i) as! newView let newTag:Int = newview.tag - 100 if self.scrollview.contentOffset.x < width * 0.6 { UIView.animateWithDuration(1, animations: { self.pickView?.alpha = 0.5 }) switch newTag{ case 0: UIView.animateWithDuration(1, animations: { newview.frame.origin.x = 2 * width }) case 1: viewOut(newview, delay: 0.3, width: width) case 2: viewOut(newview, delay: 0.6, width: width) case 3: viewOut(newview, delay: 0.9, width: width) default: break } }else{ UIView.animateWithDuration(1, animations: { self.pickView?.alpha = 0.8 }) switch newview.tag - 100{ case 0: UIView.animateWithDuration(0.5, animations: { newview.frame.origin.x = 10 + self.view.bounds.width }) case 1: viewIn(newview, delay: 0.3) case 2: viewIn(newview, delay: 0.4) case 3: viewIn(newview, delay: 0.5) default: break } } } } func viewIn(newview:newView,delay:Double) -> Void { UIView.animateWithDuration(0.5, delay: delay, options: UIViewAnimationOptions.CurveEaseInOut, animations: { newview.frame.origin.x = 10 + self.view.bounds.width }, completion: { (Bool) in }) } func viewOut(newview:newView,delay:Double,width:CGFloat) -> Void { UIView.animateWithDuration(1, delay: delay, options: UIViewAnimationOptions.CurveEaseInOut, animations: { newview.frame.origin.x = 2 * width }, completion: { (Bool) in }) } // MARK:自定义view class newView:UIView,UITextFieldDelegate { var imageView:UIImageView? var label:UILabel? var textField:UITextField? // MARK:重写初始化方法并初始化自定义view内部控件 override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.grayColor() self.alpha = 0.8 imageView = UIImageView(frame: CGRectZero) imageView?.backgroundColor = UIColor.yellowColor() self.addSubview(imageView!) label = UILabel(frame: CGRectZero ) label?.text = "HRK" label?.textColor = UIColor.whiteColor() // label?.backgroundColor = UIColor.orangeColor() self.addSubview(label!) textField = UITextField(frame: CGRectZero ) textField?.textColor = UIColor.whiteColor() textField?.placeholder = "0.00" textField?.textAlignment = NSTextAlignment.Left self.addSubview(textField!) } // 在layoutsubviews设置自定义控件的frame override func layoutSubviews() { super.layoutSubviews() imageView?.frame = CGRectMake(0, 0, self.frame.size.width / 4,self.frame.size.height) let imageW:CGFloat = (imageView?.frame.size.width)! label?.frame = CGRectMake(imageW, 0, self.frame.size.width - imageW,self.frame.size.height/2) textField?.frame = CGRectMake(imageW, self.frame.size.height / 2, self.frame.size.width - imageW,self.frame.size.height / 2) textField?.keyboardType = UIKeyboardType.NumbersAndPunctuation } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:pickview func creatPickView(){ pickView = UIPickerView() let h:CGFloat = self.view.frame.size.height let w:CGFloat = self.view.frame.size.width pickView?.backgroundColor = UIColor.grayColor() pickView?.alpha = 0.8 pickView?.frame = CGRectMake(10 + self.view.frame.size.width, h * 0.6, w - 20, h / 3) pickView?.delegate = self pickView?.dataSource = self self.scrollview.addSubview(pickView!) } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 4 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return (self.keyArray?.count)! } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.keyArray![row] as? String } func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 45 } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let view:newView? view = newView() switch component { case 0: (self.scrollview.viewWithTag(100) as!newView).label?.text = self.keyArray![row] as? String self.textFieldDidEndEditing(self.scrollview.viewWithTag(200) as! UITextField) case 1: (self.scrollview.viewWithTag(101) as!newView).label?.text = self.keyArray![row] as? String self.textFieldDidEndEditing(self.scrollview.viewWithTag(201) as! UITextField) case 2: (self.scrollview.viewWithTag(102) as!newView).label?.text = self.keyArray![row] as? String self.textFieldDidEndEditing(self.scrollview.viewWithTag(202) as! UITextField) case 3: (self.scrollview.viewWithTag(103) as!newView).label?.text = self.keyArray![row] as? String self.textFieldDidEndEditing(self.scrollview.viewWithTag(203) as! UITextField) default: break } } // MARK:textField的代理方法 func textFieldDidBeginEditing(textField: UITextField) { textField.placeholder = "按此输入金额" } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // MARK:计算用户输入的倍数并且刷新所有textfield的数据 func textFieldDidEndEditing(textField: UITextField) { if textField.text == "" || textField.text == "0.00" { textField.placeholder = "0.00" } else{ // 用户输入数字转换为浮点型显示 let value = (textField.text! as NSString ).floatValue textField.text = String(format: "%.2f", value) // 计算选中的textfield与其本身汇率的倍数 let multiple = self.editMultiple(textField) // 找出非被选中textfield的存在值,并且乘以对应倍数,刷新其对应倍率的数据 self.editUnSelected(textField , multiple:multiple ) } } func editMultiple(textField:UITextField) -> Float { //选中的textField所在的自定义view,获取其对比美金的汇率 let view:newView = self.scrollview.viewWithTag(textField.tag - 100 )as! newView var index: Int = 0 //取出label.text对应的汇率 for string in self.keyArray! { if string.isEqualToString((view.label?.text)!) { break } index += 1 } // 获得选中textfield的汇率值(兑美元) let number:NSNumber = self.valueArray![index] as! NSNumber let valueString:String = textField.text! let newString = NSString(string: valueString).floatValue let multiple:Float = newString / number.floatValue return multiple } func editUnSelected(textField:UITextField,multiple:Float) -> Void { for i:Int in 0...3{ if i != textField.tag - 200 { let myView:newView = self.scrollview.viewWithTag(100 + i) as! newView var newIndex: Int = 0 //取出label.text对应的汇率 for string in self.keyArray! { if string.isEqualToString((myView.label?.text)!) { break } newIndex += 1 } let newNumber:NSNumber = self.valueArray![newIndex] as! NSNumber let answer:Float = newNumber.floatValue * multiple myView.textField?.text = String(format: "%.2f", answer) } } } // MARK:lefttableview func leftTableView(){ let rect:CGRect = CGRectMake(10, 20, self.view.frame.size.width - 50, self.view.frame.size.height - 60) self.leftTableVeiw = UITableView(frame:rect, style: UITableViewStyle.Grouped) self.leftTableVeiw!.backgroundColor = UIColor.grayColor() self.leftTableVeiw!.dataSource = self self.leftTableVeiw!.delegate = self self.leftTableVeiw?.tableHeaderView = self.searchBar self.scrollview.addSubview(self.leftTableVeiw!) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.keyArray?.count)! } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // 直接取tableview得cell判断没有再去创建 var cell = tableView.dequeueReusableCellWithIdentifier("tableView") if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "tableView") } if self.keyArray!.count > indexPath.row { cell?.textLabel?.text = self.keyArray![indexPath.row] as? String } cell?.backgroundColor = UIColor.grayColor() return cell! } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat.min } // MARK:tableview的编辑模式 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { self.keyArray?.removeObjectAtIndex(indexPath.row) self.valueArray?.removeObjectAtIndex(indexPath.row) self.leftTableVeiw?.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade) } // MARK:searchbar的创建 lazy var searchBar:UISearchBar = { let search:UISearchBar = UISearchBar() search.frame = CGRectMake(0, 0, 10, 44) search.delegate = self search.placeholder = "搜索" return search }() func searchBarSearchButtonClicked(searchBar: UISearchBar) { if self.keyArray?.count == 0 { let alertController:UIAlertController = UIAlertController(title: "网络错误", message: "还没有数据呢请耐心等待", preferredStyle: UIAlertControllerStyle.Alert) let alertAction:UIAlertAction = UIAlertAction(title: "确定", style: UIAlertActionStyle.Cancel, handler: nil) let alertAction1 = UIAlertAction(title: "重新连接", style: UIAlertActionStyle.Default, handler: { (action) in self.requestUrl("http://app-cdn.2q10.com/api/v2/currency?ver=iphone") }) alertController.addAction(alertAction) alertController.addAction(alertAction1) self.presentViewController(alertController, animated: true, completion: nil) }else{ for string in self.keyArray! { if string as? String == searchBar.text { }else{ let alertController:UIAlertController = UIAlertController(title: nil, message: "找不到搜索内容", preferredStyle: UIAlertControllerStyle.ActionSheet) let alertAction:UIAlertAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil) alertController.addAction(alertAction) self.presentViewController(alertController, animated: true, completion: nil) return } } } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.tableView(self.leftTableVeiw!, commitEditingStyle: UITableViewCellEditingStyle.Delete, forRowAtIndexPath: indexPath) self.pickView?.reloadAllComponents() for i:Int in 0...3 { let text:UITextField = self.scrollview.viewWithTag(200 + i)as! UITextField text.text = nil text.placeholder = "0.00" } for i:Int in 0...3{ self.pickView?.selectRow(0, inComponent: i, animated: true) } for i:Int in 0...3 { self.pickerView(self.pickView!, didSelectRow: 0, inComponent: i) } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // MARK:网络请求 func requestUrl(urlString: String){ let url:NSURL = NSURL(string: urlString)! // 转换为requset let requets:NSURLRequest = NSURLRequest(URL: url) //NSURLSession 对象都由一个 NSURLSessionConfiguration 对象来进行初始化,后者指定了刚才提到的那些策略以及一些用来增强移动设备上性能的新选项 let configuration:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() let session:NSURLSession = NSURLSession(configuration: configuration) let task:NSURLSessionDataTask = session.dataTaskWithRequest(requets, completionHandler: { (data:NSData?,response:NSURLResponse?,error:NSError?)->Void in if error == nil{ do{ let responseData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary let newDic = responseData.valueForKey("rates") let array :NSArray = (newDic?.allKeys)! self.keyArray = NSMutableArray(array: array) let array1 :NSArray = (newDic?.allValues)! self.valueArray = NSMutableArray(array:array1) // 在主线程刷新ui dispatch_async(dispatch_get_main_queue()){ self.leftTableVeiw?.reloadData() self.pickView?.reloadAllComponents() } } catch{ } }else{ // print(error) } }) // 启动任务 task.resume() } }
apache-2.0
74c31e1a4488ae53548e68ce830c931d
33.892562
212
0.557935
5.18164
false
false
false
false
TomLinthwaite/SKTilemap
SKTilemap.swift
1
17216
/* SKTilemap SKTilemap.swift Created by Thomas Linthwaite on 07/04/2016. GitHub: https://github.com/TomLinthwaite/SKTilemap Website (Guide): http://tomlinthwaite.com/ Wiki: https://github.com/TomLinthwaite/SKTilemap/wiki YouTube: https://www.youtube.com/channel/UCAlJgYx9-Ub_dKD48wz6vMw Twitter: https://twitter.com/Mr_Tomoso ----------------------------------------------------------------------------------------------------------------------- MIT License Copyright (c) 2016 Tom Linthwaite 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 SpriteKit import GameplayKit // MARK: SKTilemapOrientation enum SKTilemapOrientation : String { case Orthogonal = "orthogonal"; case Isometric = "isometric"; /** Change these values in code if you wish to have your tiles have a different anchor point upon layer initialization. */ func tileAnchorPoint() -> CGPoint { switch self { case .Orthogonal: return CGPoint(x: 0.5, y: 0.5) case .Isometric: return CGPoint(x: 0.5, y: 0.5) } } } // MARK: SKTilemap class SKTilemap : SKNode { //MARK: Properties /** Properties shared by all TMX object types. */ var properties: [String : String] = [:] /** The current version of the tilemap. */ var version: Double = 0 /** The dimensions of the tilemap in tiles. */ let size: CGSize private var sizeHalved: CGSize { get { return CGSize(width: width / 2, height: height / 2) } } var width: Int { return Int(size.width) } var height: Int { return Int(size.height) } /** The size of the grid for the tilemap. Note that tilesets may have differently sized tiles. */ let tileSize: CGSize private var tileSizeHalved: CGSize { get { return CGSize(width: tileSize.width / 2, height: tileSize.height / 2) } } /** The orientation of the tilemap. See SKTilemapOrientation for valid orientations. */ let orientation: SKTilemapOrientation /** The tilesets this tilemap contains. */ private var tilesets: Set<SKTilemapTileset> = [] /** The layers this tilemap contains. */ private var tileLayers: Set<SKTilemapLayer> = [] /** The object groups this tilemap contains */ private var objectGroups: Set<SKTilemapObjectGroup> = [] /** The display bounds the viewable area of this tilemap should be constrained to. Tiles positioned outside this rectangle will not be shown. This should speed up performance for large tilemaps when tile clipping is enabled. If this property is set to nil, the SKView bounds will be used instead as default. */ var displayBounds: CGRect? /** Internal property for the layer alignment. */ private var layerAlignment = CGPoint(x: 0.5, y: 0.5) /** Used to set how the layers are aligned within the map much like an anchorPoint on a sprite node. + 0 - The layers left/bottom most edge will rest at 0 in the scene + 0.5 - The center of the layer will rest at 0 in the scene + 1 - The layers right/top most edge will rest at 0 in the scene */ var alignment: CGPoint { get { return layerAlignment } set { self.layerAlignment = newValue tileLayers.forEach({ self.alignLayer($0) }) } } /** Internal var for whether tile clipping is enabled or disabled. */ private var useTileClipping = false /** Enables tile clipping on this tilemap. */ var enableTileClipping: Bool { get { return useTileClipping } set { if newValue == true { if displayBounds == nil && scene == nil && scene?.view == nil { print("SKTiledMap: Failed to enable tile clipping. Tilemap not added to Scene and no Display Bounds set.") useTileClipping = false return } else if (scene != nil && scene?.view != nil) || displayBounds != nil { for y in 0..<height { for x in 0..<width { for layer in tileLayers { if let tile = layer.tileAtCoord(x, y) { tile.hidden = true } } } } print("SKTilemap: Tile clipping enabled.") useTileClipping = true clipTilesOutOfBounds(tileBufferSize: 1) } } else { for y in 0..<height { for x in 0..<width { for layer in tileLayers { if let tile = layer.tileAtCoord(x, y) { tile.hidden = false } } } } print("SKTilemap: Tile clipping disabled.") useTileClipping = false } } } /** When tile clipping is enabled this property will disable it when the scale passed in goes below this threshold. This is important because the tile clipping can cause serious slow down when a lot of tiles are drawn on screen. Experiment with this value to see what's best for your map. This is only needed if you plan on scaling the tilemap.*/ var minTileClippingScale: CGFloat = 0.6 private var disableTileClipping = false /** The graph used for path finding around the tilemap. To initialize it implement one of the SKTilemapPathFindingProtocol functions. */ var pathFindingGraph: GKGridGraph? var removedGraphNodes: [GKGridGraphNode] = [] /** Returns the next available global ID to use. Useful for adding new tiles to a tileset or working out a tilesets first GID property. */ var nextGID: Int { var highestGID = 0 for tileset in tilesets { if tileset.lastGID > highestGID { highestGID = tileset.lastGID } } return highestGID + 1 } // MARK: Initialization /** Initialize an empty tilemap object. */ init(name: String, size: CGSize, tileSize: CGSize, orientation: SKTilemapOrientation) { self.size = size self.tileSize = tileSize self.orientation = orientation super.init() self.name = name } /** Initialize a tilemap from tmx parser attributes. Should probably only be called by SKTilemapParser. */ init?(filename: String, tmxParserAttributes attributes: [String : String]) { guard let version = attributes["version"] where (Double(version) != nil), let width = attributes["width"] where (Int(width) != nil), let height = attributes["height"] where (Int(height) != nil), let tileWidth = attributes["tilewidth"] where (Int(tileWidth) != nil), let tileHeight = attributes["tileheight"] where (Int(tileHeight) != nil), let orientation = attributes["orientation"] where (SKTilemapOrientation(rawValue: orientation) != nil) else { print("SKTilemap: Failed to initialize with tmxAttributes.") return nil } self.version = Double(version)! self.orientation = SKTilemapOrientation(rawValue: orientation)! size = CGSize(width: Int(width)!, height: Int(height)!) tileSize = CGSize(width: Int(tileWidth)!, height: Int(tileHeight)!) super.init() self.name = filename } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Loads a tilemap from .tmx file. */ class func loadTMX(name name: String) -> SKTilemap? { let time = NSDate() if let tilemap = SKTilemapParser().loadTilemap(filename: name) { tilemap.printDebugDescription() print("\nSKTilemap: Loaded tilemap '\(name)' in \(NSDate().timeIntervalSinceDate(time)) seconds.") return tilemap } print("SKTilemap: Failed to load tilemap '\(name)'.") return nil } // MARK: Debug func printDebugDescription() { print("\nTilemap: \(name!) (\(version)), Size: \(size), TileSize: \(tileSize), Orientation: \(orientation)") print("Properties: \(properties)") for tileset in tilesets { tileset.printDebugDescription() } for tileLayer in tileLayers { tileLayer.printDebugDescription() } for objectGroup in objectGroups { objectGroup.printDebugDescription() } } // MARK: Tilesets /** Adds a tileset to the tilemap. Returns nil on failure. (A tileset with the same name already exists). Or or returns the tileset. */ func add(tileset tileset: SKTilemapTileset) -> SKTilemapTileset? { if tilesets.contains({ $0.hashValue == tileset.hashValue }) { print("SKTilemap: Failed to add tileset. A tileset with the same name already exists.") return nil } tilesets.insert(tileset) return tileset } /** Returns a tileset with specified name or nil if it doesn't exist. */ func getTileset(name name: String) -> SKTilemapTileset? { if let index = tilesets.indexOf( { $0.name == name } ) { return tilesets[index] } return nil } /** Will return a SKTilemapTileData object with matching id from one of the tilesets associated with this tilemap or nil if no match can be found. */ func getTileData(id id: Int) -> SKTilemapTileData? { for tileset in tilesets { if let tileData = tileset.getTileData(id: id) { return tileData } } return nil } // MARK: Tile Layers /** Adds a tile layer to the tilemap. A zPosition can be supplied and will be applied to the layer. If no zPosition is supplied, the layer is assumed to be placed on top of all others. Returns nil on failure. (A layer with the same name already exists. Or returns the layer. */ func add(tileLayer tileLayer: SKTilemapLayer, zPosition: CGFloat? = nil) -> SKTilemapLayer? { if tileLayers.contains({ $0.hashValue == tileLayer.hashValue }) { print("SKTilemap: Failed to add tile layer. A tile layer with the same name already exists.") return nil } if zPosition != nil { tileLayer.zPosition = zPosition! } else { var highestZPosition: CGFloat? for layer in tileLayers { if highestZPosition == nil { highestZPosition = layer.zPosition } else if layer.zPosition > highestZPosition { highestZPosition = layer.zPosition } } if highestZPosition == nil { highestZPosition = -1 } tileLayer.zPosition = highestZPosition! + 1 } tileLayers.insert(tileLayer) addChild(tileLayer) alignLayer(tileLayer) return tileLayer } /** Positions a tilemap layer so that its center position is resting at the tilemaps 0,0 position. */ private func alignLayer(layer: SKTilemapLayer) { var position = CGPointZero if orientation == .Orthogonal { let sizeInPoints = CGSize(width: size.width * tileSize.width, height: size.height * tileSize.height) position.x = -sizeInPoints.width * alignment.x position.y = sizeInPoints.height - alignment.y * sizeInPoints.height } if orientation == .Isometric { let sizeInPoints = CGSize(width: (size.width + size.height) * tileSize.width, height: (size.width + size.height) * tileSize.height) position.x = ((sizeHalved.width - sizeHalved.height) * tileSize.width) - alignment.x * (sizeInPoints.width / 2) position.y = ((sizeHalved.width + sizeHalved.height) * tileSize.height) - alignment.y * (sizeInPoints.height / 2) print(position.x) } layer.position = position /* Apply the layers offset */ layer.position.x += (layer.offset.x + layer.offset.x * orientation.tileAnchorPoint().x) layer.position.y -= (layer.offset.y - layer.offset.y * orientation.tileAnchorPoint().y) } /* Get all layers in a set. */ func getLayers() -> Set<SKTilemapLayer> { return tileLayers } /** Returns a tilemap layer with specified name or nil if one does not exist. */ func getLayer(name name: String) -> SKTilemapLayer? { if let index = tileLayers.indexOf( { $0.name == name } ) { return tileLayers[index] } return nil } /** Returns "any" tilemap layer. Useful if you want access to functions within a layer and not bothered which layer it is. In reality this just returns the first tilemap layer that was added. Can return nil if there are no layers. */ func anyLayer() -> SKTilemapLayer? { return tileLayers.first } /** Removes a layer from the tilemap. The layer removed is returned or nil if the layer wasn't found. */ func removeLayer(name name: String) -> SKTilemapLayer? { if let layer = getLayer(name: name) { layer.removeFromParent() tileLayers.remove(layer) return layer } return nil } /** Will "clip" tiles outside of the tilemaps 'displayBounds' property if set or the SKView bounds (if it's a child of a view... which it should be). You must call this function when ever you reposition the tilemap so it can update the visible tiles. For example in a scenes TouchesMoved function if scrolling the tilemap with a touch or mouse. */ func clipTilesOutOfBounds(scale scale: CGFloat = 1.0, tileBufferSize: CGFloat = 2) { if !useTileClipping && disableTileClipping == false { return } if scale < minTileClippingScale && disableTileClipping == false { disableTileClipping = true enableTileClipping = false } if scale >= minTileClippingScale && disableTileClipping == true { disableTileClipping = false enableTileClipping = true } if disableTileClipping { return } for layer in tileLayers { layer.clipTilesOutOfBounds(displayBounds, scale: scale, tileBufferSize: tileBufferSize) } } // MARK: Object Groups /** Adds an object group to the tilemap. Returns nil on failure. (An object group with the same name already exists. Or returns the object group. */ func add(objectGroup objectGroup: SKTilemapObjectGroup) -> SKTilemapObjectGroup? { if objectGroups.contains({ $0.hashValue == objectGroup.hashValue }) { print("SKTilemap: Failed to add object layer. An object layer with the same name already exists.") return nil } objectGroups.insert(objectGroup) return objectGroup } /** Returns a object group with specified name or nil if it does not exist. */ func getObjectGroup(name name: String) -> SKTilemapObjectGroup? { if let index = objectGroups.indexOf( { $0.name == name } ) { return objectGroups[index] } return nil } }
mit
4a8efb4528825926a46a90f922197e91
37.777027
143
0.587941
4.765015
false
false
false
false
24/ios-o2o-c
gxc/Model/GX_UserLogin.swift
1
1400
// // GX_UserLogin.swift // gx // // Created by gx on 14/11/10. // Copyright (c) 2014年 gx. All rights reserved. // import Foundation class GX_UserLogin :Deserializable{ var code: Int? var userLogin :GX_UserLoginModel? var foot :Foot? var message: String? var page: String? required init(data: [String : AnyObject]) { code <<< data["code"] userLogin <<<< data["data"] message <<< data["message"] foot <<<< data["foot"] page <<< data["page"] } } class GX_UserLoginModel: Deserializable { var IsFixSecret: Bool? var Phone: String? var Token: String? required init(data: [String : AnyObject]) { IsFixSecret <<< data["IsFixSecret"] Phone <<< data["Phone"] Token <<< data["Token"] } } //class Foot: Deserializable { // var operationTime :String? // var servicePhone :String? // // required init(data: [String : AnyObject]) { // // operationTime <<< data["operationTime"] // servicePhone <<< data["servicePhone"] // } //} //{ // code = 200; // data = { // IsFixSecret = 0; // Phone = 110; // Token = 24308e90f9504b9db8ad69a845352ae6; // }; // foot = { // operationTime = "2014-11-16 21:00:03"; // servicePhone = "110"; // }; // message = ""; // page = "<null>"; //}
mit
93e85cf4da0580bc40777dde5e39d8e2
20.19697
51
0.534335
3.426471
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Rank/Views/RankHeaderView.swift
1
3066
// // RankHeaderView.swift // MusicApp // // Created by Hưng Đỗ on 6/29/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit import RxSwift import Action class RankHeaderView: UIView { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var bannerImageView: UIImageView! @IBOutlet weak var playButton: UIButton! var bannerImageViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var songBannerImageViewBottomConstraint: NSLayoutConstraint! { didSet { bannerImageViewBottomConstraint = songBannerImageViewBottomConstraint } } @IBOutlet weak var playlistBannerImageViewBottomConstraint: NSLayoutConstraint! { didSet { bannerImageViewBottomConstraint = playlistBannerImageViewBottomConstraint } } @IBOutlet weak var videoBannerImageViewBottomConstraint: NSLayoutConstraint! { didSet { bannerImageViewBottomConstraint = videoBannerImageViewBottomConstraint } } func configure(country: String, type: String) { switch type { case kRankTypeSong: titleLabel.text = "BXH Bài hát" case kRankTypePlaylist: titleLabel.text = "BXH Playlist" case kRankTypeVideo: titleLabel.text = "BXH Video" default: break } switch country { case kRankCountryVietnam: bannerImageView.image = #imageLiteral(resourceName: "BXH-App-Banner_VN_V") case kRankCountryEurope: bannerImageView.image = #imageLiteral(resourceName: "BXH-App-Banner_US_V") case kRankCountryKorea: bannerImageView.image = #imageLiteral(resourceName: "BXH-App-Banner_KR_V") default: break } } var action: CocoaAction? { didSet { if let buttonAction = action { playButton?.rx.action = buttonAction } } } func configureAnimation(with tableView: UITableView) { let startOffset: CGFloat = tableView.contentOffset.y let startHeight: CGFloat = frame.height let minHeight: CGFloat = 64 // status (20) + navigation bar (44) let maxOffset: CGFloat = startHeight - minHeight let startImageConstant = bannerImageViewBottomConstraint.constant tableView.rx.didScroll .map { _ in tableView.contentOffset.y } .subscribe(onNext: { [weak self] contentOffset in let offset = contentOffset - startOffset if offset < maxOffset { self?.frame.size.height = startHeight - offset self?.bannerImageViewBottomConstraint.constant = startImageConstant + offset let alpha = (maxOffset - minHeight - offset) / (maxOffset - minHeight) self?.titleLabel.alpha = alpha } }) .addDisposableTo(rx_disposeBag) } }
mit
32faf7eff98cee8f596ea112bc70c212
31.2
96
0.611311
5.256014
false
false
false
false
iadmir/Signal-iOS
Signal/src/Jobs/SessionResetJob.swift
3
2122
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit @objc(OWSSessionResetJob) class SessionResetJob: NSObject { let TAG = "SessionResetJob" let recipientId: String let thread: TSThread let storageManager: TSStorageManager let messageSender: MessageSender required init(recipientId: String, thread: TSThread, messageSender: MessageSender, storageManager: TSStorageManager) { self.thread = thread self.recipientId = recipientId self.messageSender = messageSender self.storageManager = storageManager } func run() { Logger.info("\(TAG) Local user reset session.") OWSDispatch.sessionStoreQueue().async { Logger.info("\(self.TAG) deleting sessions for recipient: \(self.recipientId)") self.storageManager.deleteAllSessions(forContact: self.recipientId) DispatchQueue.main.async { let endSessionMessage = EndSessionMessage(timestamp:NSDate.ows_millisecondTimeStamp(), in: self.thread) self.messageSender.send(endSessionMessage, success: { Logger.info("\(self.TAG) successfully sent EndSession<essage.") let message = TSInfoMessage(timestamp: NSDate.ows_millisecondTimeStamp(), in: self.thread, messageType: TSInfoMessageType.typeSessionDidEnd) message.save() }, failure: {error in Logger.error("\(self.TAG) failed to send EndSessionMessage with error: \(error.localizedDescription)") }) } } } class func run(contactThread: TSContactThread, messageSender: MessageSender, storageManager: TSStorageManager) { let job = self.init(recipientId: contactThread.contactIdentifier(), thread: contactThread, messageSender: messageSender, storageManager: storageManager) job.run() } }
gpl-3.0
9dd7c2d65e042b8d9c538a50e72c8050
37.581818
122
0.614986
5.554974
false
false
false
false
iosliutingxin/DYVeideoVideo
DYZB/DYZB/Classes/Home/View/recomeGameView.swift
1
1616
// // recomeGameView.swift // DYZB // // Created by 李孔文 on 2018/3/11. // Copyright © 2018年 iOS _Liu. All rights reserved. // import UIKit private var cellID = "recomeGameID" private var EdgeInsertMargin : CGFloat = 10 class recomeGameView: UIView { @IBOutlet weak var collection: UICollectionView! override func awakeFromNib() { //不随父控件的拉伸而拉伸 self.autoresizingMask = UIViewAutoresizing(rawValue: 0) //普通注册 // collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID) collection.register(UINib(nibName: "gameCell", bundle: nil), forCellWithReuseIdentifier: cellID) //设置内边距 collection.contentInset = UIEdgeInsetsMake(0, EdgeInsertMargin, 0, EdgeInsertMargin) collection.dataSource = self } } //类扩展 extension recomeGameView{ //提供一个快速创建View的类方法 class func createCycleView() -> recomeGameView { return Bundle.main.loadNibNamed("recomeGameView", owner: nil, options: nil)?.first as! recomeGameView } } //遵守数据源方法 extension recomeGameView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! gameCell return cell } }
mit
ef4231e1b3ce8d5ce1220b34648413e1
28.269231
121
0.699737
4.584337
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Settings/View/LicenseTableViewCell.swift
1
1909
// // LicenseTableViewCell.swift // DereGuide // // Created by zzk on 2017/1/30. // Copyright © 2017年 zzk. All rights reserved. // import UIKit import SnapKit class LicenseTableViewCell: UITableViewCell { var titleLabel: UILabel! var siteLabel: UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) titleLabel = UILabel() titleLabel.font = UIFont.systemFont(ofSize: 14) contentView.addSubview(titleLabel) titleLabel.snp.makeConstraints { (make) in make.top.equalTo(8) make.left.equalTo(10) make.right.lessThanOrEqualTo(-10) } titleLabel.numberOfLines = 0 siteLabel = UILabel() siteLabel.font = UIFont.systemFont(ofSize: 12) contentView.addSubview(siteLabel) siteLabel.snp.makeConstraints { (make) in make.top.equalTo(titleLabel.snp.bottom).offset(5) make.left.equalTo(titleLabel) make.right.lessThanOrEqualTo(-10) make.bottom.equalToSuperview().offset(-8) } siteLabel.textColor = UIColor.darkGray } func setup(title: String, site: String) { self.titleLabel.text = title self.siteLabel.text = site if site == "" { accessoryType = .none siteLabel.snp.updateConstraints({ (update) in update.top.equalTo(titleLabel.snp.bottom).offset(0) }) } else { accessoryType = .disclosureIndicator siteLabel.snp.updateConstraints({ (update) in update.top.equalTo(titleLabel.snp.bottom).offset(5) }) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
bcb2814179a3ecdc56546ad0d3fbbc66
28.323077
74
0.598636
4.64878
false
false
false
false
frtlupsvn/Vietnam-To-Go
Pods/Former/Former/Cells/FormSwitchCell.swift
1
1465
// // FormSwitchCell.swift // Former-Demo // // Created by Ryo Aoyama on 7/27/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public class FormSwitchCell: FormCell, SwitchFormableRow { // MARK: Public public private(set) weak var titleLabel: UILabel! public private(set) weak var switchButton: UISwitch! public func formTitleLabel() -> UILabel? { return titleLabel } public func formSwitch() -> UISwitch { return switchButton } public override func setup() { super.setup() let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.insertSubview(titleLabel, atIndex: 0) self.titleLabel = titleLabel let switchButton = UISwitch() accessoryView = switchButton self.switchButton = switchButton let constraints = [ NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[label]-0-|", options: [], metrics: nil, views: ["label": titleLabel] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:|-15-[label(>=0)]", options: [], metrics: nil, views: ["label": titleLabel] ) ].flatMap { $0 } contentView.addConstraints(constraints) } }
mit
909b34fc3c92ef39f7a235e621116abe
26.12963
68
0.56694
5.503759
false
false
false
false
pguth/OccupyHdM
ios/app/occupyhdm/occupyhdm/AppDelegate.swift
1
4266
import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let userDefaults = NSUserDefaults.standardUserDefaults() if userDefaults.integerForKey("accuracy") == 0 { userDefaults.setInteger(63, forKey: "accuracy") } if userDefaults.integerForKey("distance") == 0 { userDefaults.setInteger(28, forKey: "distance") } if userDefaults.integerForKey("refreshRate") == 0 { userDefaults.setInteger(15, forKey: "refreshRate") } let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) var viewController = storyboard.instantiateViewControllerWithIdentifier("main") if NSUserDefaults.standardUserDefaults().stringForKey("username") == nil { viewController = storyboard.instantiateViewControllerWithIdentifier("login") } self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.rootViewController = viewController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { } func applicationWillTerminate(application: UIApplication) { self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager .defaultManager() .URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource("occupyhdm", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator( managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory .URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType( NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext( concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
c4540fa8dc27a2513db072bb8575e390
34.848739
98
0.661275
6.301329
false
false
false
false
jensmeder/DarkLightning
Sources/Utils/Sources/SocketStream.swift
1
4062
/** * * DarkLightning * * * * The MIT License (MIT) * * Copyright (c) 2017 Jens Meder * * 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 internal final class SocketStream: DataStream { private let readReaction: StreamDelegate private let writeReaction: StreamDelegate private let inputStream: Memory<InputStream?> private let outputStream: Memory<OutputStream?> private let handle: Memory<CFSocketNativeHandle> // MARK: Init internal convenience init(handle: Memory<CFSocketNativeHandle>, inputStream: Memory<InputStream?>, outputStream: Memory<OutputStream?>) { self.init( handle: handle, inputStream: inputStream, outputStream: outputStream, readReaction: StreamDelegates(), writeReaction: StreamDelegates() ) } internal required init(handle: Memory<CFSocketNativeHandle>, inputStream: Memory<InputStream?>, outputStream: Memory<OutputStream?>, readReaction: StreamDelegate, writeReaction: StreamDelegate) { self.handle = handle self.inputStream = inputStream self.outputStream = outputStream self.readReaction = readReaction self.writeReaction = writeReaction } // MARK: DataStream func open(in queue: DispatchQueue) { var inputStream: Unmanaged<CFReadStream>? = nil var outputStream: Unmanaged<CFWriteStream>? = nil CFStreamCreatePairWithSocket( kCFAllocatorDefault, handle.rawValue, &inputStream, &outputStream ) CFReadStreamSetProperty( inputStream!.takeUnretainedValue(), CFStreamPropertyKey( rawValue: kCFStreamPropertyShouldCloseNativeSocket ), kCFBooleanTrue ) CFWriteStreamSetProperty( outputStream!.takeUnretainedValue(), CFStreamPropertyKey( rawValue: kCFStreamPropertyShouldCloseNativeSocket ), kCFBooleanTrue ) self.inputStream.rawValue = inputStream!.takeRetainedValue() as InputStream self.outputStream.rawValue = outputStream!.takeRetainedValue() as OutputStream queue.sync { self.inputStream.rawValue?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode) self.outputStream.rawValue?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode) self.inputStream.rawValue?.delegate = self.readReaction self.outputStream.rawValue?.delegate = self.writeReaction self.inputStream.rawValue?.open() self.outputStream.rawValue?.open() } queue.async { RunLoop.current.run() } } func close() { if inputStream.rawValue?.streamStatus != .closed { inputStream.rawValue?.close() inputStream.rawValue = nil } if outputStream.rawValue?.streamStatus != .closed { outputStream.rawValue?.close() outputStream.rawValue = nil } } }
mit
7c1c0d7dea89b4bf4d98705161b9a625
36.611111
196
0.689562
5.090226
false
false
false
false
ludoded/ReceiptBot
ReceiptBot/Scene/Inbox/DataSource/InboxDataSourceInteractor.swift
1
2429
// // InboxDataSourceInteractor.swift // ReceiptBot // // Created by Haik Ampardjian on 4/7/17. // Copyright (c) 2017 receiptbot. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol InboxDataSourceInteractorOutput { func presentInvoices(response: InboxDataSourceModel.Invoices.Response) func presentFilteredInvoices(response: InboxDataSourceModel.Filtered.Response) } class InboxDataSourceInteractor { var output: InboxDataSourceInteractorOutput! var worker: InboxDataSourceWorker! var invoices: [SyncConvertedInvoiceResponse]! var filteredInvoices: [SyncConvertedInvoiceResponse]! // MARK: - Business logic func fetchInvoices(with query: String) { AppSettings.shared.config.loadConfigs { [weak self] in let entityId = AppSettings.shared.user.entityId self?.worker = InboxDataSourceWorker(entityId: entityId) self?.worker.fetchInvoices { [weak self] (wrappedArray) in self?.storeInvoices(for: wrappedArray) self?.filter(with: query) } } } func filter(with query: String) { if query.lowercased() == "all" { passFiltered(invoices: invoices) } else { filteredInvoices = invoices.filter({ RebotInvoiceStatusMapper.toFrontEnd(from: $0.type).lowercased() == query.lowercased() }) passFiltered(invoices: filteredInvoices) } } func pass(data: RebotValueWrapper<[SyncConvertedInvoiceResponse]>) { let response = InboxDataSourceModel.Invoices.Response(data: data) output.presentInvoices(response: response) } func passFiltered(invoices: [SyncConvertedInvoiceResponse]) { let response = InboxDataSourceModel.Filtered.Response(invoices: invoices) output.presentFilteredInvoices(response: response) } /// Save invoices in interactor for later usage /// /// - Parameter data: Wrapper of Sync Converted Invoice Response func storeInvoices(for data: RebotValueWrapper<[SyncConvertedInvoiceResponse]>) { switch data { case .value(let invoices): self.invoices = invoices self.filteredInvoices = invoices default: break } } }
lgpl-3.0
1c164b7731c37626c423fbbca45873ec
34.202899
137
0.676822
4.489834
false
false
false
false
zmian/xcore.swift
Sources/Xcore/SwiftUI/Components/Device/Device+Model.swift
1
17223
// // Xcore // Copyright © 2014 Xcore // MIT license, see LICENSE file for details // // swiftlint:disable switch_case_on_newline import SwiftUI extension Device { public indirect enum Model: Hashable, CustomStringConvertible { case unknown(String) case simulator(Model) // iPhone case iPhone2G case iPhone3G case iPhone3Gs case iPhone4, iPhone4s case iPhone5, iPhone5c, iPhone5s case iPhoneSE case iPhone6, iPhone6Plus case iPhone6s, iPhone6sPlus case iPhone7, iPhone7Plus case iPhone8, iPhone8Plus case iPhoneX case iPhoneXS, iPhoneXSMax case iPhoneXR case iPhone11, iPhone11Pro, iPhone11ProMax case iPhoneSE2 case iPhone12, iPhone12Mini, iPhone12Pro, iPhone12ProMax // iPad case iPad_1 case iPad_2 case iPad_3 case iPad_4 case iPad_5 case iPad_6 case iPad_7 case iPad_8 case iPadMini_1 case iPadMini_2 case iPadMini_3 case iPadMini_4 case iPadMini_5 case iPadAir_1 case iPadAir_2 case iPadAir_3 case iPadAir_4 case iPadPro_97Inch case iPadPro_10Inch case iPadPro_11Inch_1 case iPadPro_11Inch_2 case iPadPro_11Inch_3 case iPadPro_12Inch_1 case iPadPro_12Inch_2 case iPadPro_12Inch_3 case iPadPro_12Inch_4 case iPadPro_12Inch_5 // Apple Watch case appleWatchSeries0_38mm case appleWatchSeries0_42mm case appleWatchSeries1_38mm case appleWatchSeries1_42mm case appleWatchSeries2_38mm case appleWatchSeries2_42mm case appleWatchSeries3_38mm case appleWatchSeries3_42mm case appleWatchSeries4_40mm case appleWatchSeries4_44mm case appleWatchSeries5_40mm case appleWatchSeries5_44mm case appleWatchSeries6_40mm case appleWatchSeries6_44mm case appleWatchSE_40mm case appleWatchSE_44mm // Apple TV case appleTV1 case appleTV2 case appleTV3 case appleTVHD case appleTV4K case appleTV4K2 // iPod case iPodTouch1 case iPodTouch2 case iPodTouch3 case iPodTouch4 case iPodTouch5 case iPodTouch6 case iPodTouch7 // HomePod case homePod fileprivate init(identifier: String) { var value: Self { switch identifier { // MARK: - iPhone case "iPhone1,1": return .iPhone2G case "iPhone1,2": return .iPhone3G case "iPhone2,1": return .iPhone3Gs case "iPhone3,1", "iPhone3,2", "iPhone3,3": return .iPhone4 case "iPhone4,1": return .iPhone4s case "iPhone5,1", "iPhone5,2": return .iPhone5 case "iPhone5,3", "iPhone5,4": return .iPhone5c case "iPhone6,1", "iPhone6,2": return .iPhone5s case "iPhone8,4": return .iPhoneSE case "iPhone7,2": return .iPhone6 case "iPhone7,1": return .iPhone6Plus case "iPhone8,1": return .iPhone6s case "iPhone8,2": return .iPhone6sPlus case "iPhone9,1", "iPhone9,3": return .iPhone7 case "iPhone9,2", "iPhone9,4": return .iPhone7Plus case "iPhone10,1", "iPhone10,4": return .iPhone8 case "iPhone10,2", "iPhone10,5": return .iPhone8Plus case "iPhone10,3", "iPhone10,6": return .iPhoneX case "iPhone11,2": return .iPhoneXS case "iPhone11,4", "iPhone11,6": return .iPhoneXSMax case "iPhone11,8": return .iPhoneXR case "iPhone12,1": return .iPhone11 case "iPhone12,3": return .iPhone11Pro case "iPhone12,5": return .iPhone11ProMax case "iPhone12,8": return .iPhoneSE2 case "iPhone13,2": return .iPhone12 case "iPhone13,1": return .iPhone12Mini case "iPhone13,3": return .iPhone12Pro case "iPhone13,4": return .iPhone12ProMax // MARK: - iPad case "iPad1,1", "iPad1,2": return .iPad_1 case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return .iPad_2 case "iPad3,1", "iPad3,2", "iPad3,3": return .iPad_3 case "iPad3,4", "iPad3,5", "iPad3,6": return .iPad_4 case "iPad6,11", "iPad6,12": return .iPad_5 case "iPad7,5", "iPad7,6": return .iPad_6 case "iPad7,11", "iPad7,12": return .iPad_7 case "iPad11,6", "iPad11,7": return .iPad_8 case "iPad4,1", "iPad4,2", "iPad4,3": return .iPadAir_1 case "iPad5,3", "iPad5,4": return .iPadAir_2 case "iPad11,3", "iPad11,4": return .iPadAir_3 case "iPad13,1", "iPad13,2": return .iPadAir_4 case "iPad2,5", "iPad2,6", "iPad2,7": return .iPadMini_1 case "iPad4,4", "iPad4,5", "iPad4,6": return .iPadMini_2 case "iPad4,7", "iPad4,8", "iPad4,9": return .iPadMini_3 case "iPad5,1", "iPad5,2": return .iPadMini_4 case "iPad11,1", "iPad11,2": return .iPadMini_5 case "iPad6,3", "iPad6,4": return .iPadPro_97Inch case "iPad7,3", "iPad7,4": return .iPadPro_10Inch case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": return .iPadPro_11Inch_1 case "iPad8,9", "iPad8,10": return .iPadPro_11Inch_2 case "iPad13,4", "iPad13,5", "iPad13,6", "iPad13,7": return .iPadPro_11Inch_3 case "iPad6,7", "iPad6,8": return .iPadPro_12Inch_1 case "iPad7,1", "iPad7,2": return .iPadPro_12Inch_2 case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": return .iPadPro_12Inch_3 case "iPad8,11", "iPad8,12": return .iPadPro_12Inch_4 case "iPad13,8", "iPad13,9", "iPad13,10", "iPad13,11": return .iPadPro_12Inch_5 // MARK: - Apple Watch case "Watch1,1": return .appleWatchSeries0_38mm case "Watch1,2": return .appleWatchSeries0_42mm case "Watch2,6": return .appleWatchSeries1_38mm case "Watch2,7": return .appleWatchSeries1_42mm case "Watch2,3": return .appleWatchSeries2_38mm case "Watch2,4": return .appleWatchSeries2_42mm case "Watch3,1", "Watch3,3": return .appleWatchSeries3_38mm case "Watch3,2", "Watch3,4": return .appleWatchSeries3_42mm case "Watch4,1", "Watch4,3": return .appleWatchSeries4_40mm case "Watch4,2", "Watch4,4": return .appleWatchSeries4_44mm case "Watch5,1", "Watch5,3": return .appleWatchSeries5_40mm case "Watch5,2", "Watch5,4": return .appleWatchSeries5_44mm case "Watch6,1", "Watch6,3": return .appleWatchSeries6_40mm case "Watch6,2", "Watch6,4": return .appleWatchSeries6_44mm case "Watch5,9", "Watch5,11": return .appleWatchSE_40mm case "Watch5,10", "Watch5,12": return .appleWatchSE_44mm // MARK: - Apple TV case "AppleTV1,1": return .appleTV1 case "AppleTV2,1": return .appleTV2 case "AppleTV3,1", "AppleTV3,2": return .appleTV3 case "AppleTV5,3": return .appleTVHD case "AppleTV6,2": return .appleTV4K case "AppleTV11,1": return .appleTV4K2 // MARK: - iPod case "iPod1,1": return .iPodTouch1 case "iPod2,1": return .iPodTouch2 case "iPod3,1": return .iPodTouch3 case "iPod4,1": return .iPodTouch4 case "iPod5,1": return .iPodTouch5 case "iPod7,1": return .iPodTouch6 // MARK: - HomePod case "AudioAccessory1,1": return .homePod default: return .unknown(identifier) } } #if targetEnvironment(simulator) self = .simulator(value) #else self = value #endif } public var description: String { switch self { case let .simulator(model): return "Simulator (\(model))" case .iPhone2G: return "iPhone 2G" case .iPhone3G: return "iPhone 3G" case .iPhone3Gs: return "iPhone 3Gs" case .iPhone4: return "iPhone 4" case .iPhone4s: return "iPhone 4s" case .iPhone5: return "iPhone 5" case .iPhone5c: return "iPhone 5c" case .iPhone5s: return "iPhone 5s" case .iPhoneSE: return "iPhone SE" case .iPhone6: return "iPhone 6" case .iPhone6Plus: return "iPhone 6 Plus" case .iPhone6s: return "iPhone 6s" case .iPhone6sPlus: return "iPhone 6s Plus" case .iPhone7: return "iPhone 7" case .iPhone7Plus: return "iPhone 7 Plus" case .iPhone8: return "iPhone 8" case .iPhone8Plus: return "iPhone 8 Plus" case .iPhoneX: return "iPhone X" case .iPhoneXS: return "iPhone Xs" case .iPhoneXSMax: return "iPhone Xs Max" case .iPhoneXR: return "iPhone Xʀ" case .iPhone11: return "iPhone 11" case .iPhone11Pro: return "iPhone 11 Pro" case .iPhone11ProMax: return "iPhone 11 Pro Max" case .iPhoneSE2: return "iPhone SE (2nd generation)" case .iPhone12: return "iPhone 12" case .iPhone12Mini: return "iPhone 12 mini" case .iPhone12Pro: return "iPhone 12 Pro" case .iPhone12ProMax: return "iPhone 12 Pro Max" case .iPad_1: return "iPad (1st generation)" case .iPad_2: return "iPad (2nd generation)" case .iPad_3: return "iPad (3rd generation)" case .iPad_4: return "iPad (4th generation)" case .iPad_5: return "iPad (5th generation)" case .iPad_6: return "iPad (6th generation)" case .iPad_7: return "iPad (7th generation)" case .iPad_8: return "iPad (8th generation)" case .iPadAir_1: return "iPad Air (1st generation)" case .iPadAir_2: return "iPad Air (2nd generation)" case .iPadAir_3: return "iPad Air (3rd generation)" case .iPadAir_4: return "iPad Air (4th generation)" case .iPadMini_1: return "iPad Mini (1st generation)" case .iPadMini_2: return "iPad Mini (2nd generation)" case .iPadMini_3: return "iPad Mini (3rd generation)" case .iPadMini_4: return "iPad Mini (4th generation)" case .iPadMini_5: return "iPad Mini (5th generation)" case .iPadPro_97Inch: return "iPad Pro (9.7-inch)" case .iPadPro_10Inch: return "iPad Pro (10.5-inch)" case .iPadPro_11Inch_1: return "iPad Pro (11-inch)" case .iPadPro_11Inch_2: return "iPad Pro (11-inch) (2nd generation)" case .iPadPro_11Inch_3: return "iPad Pro (11-inch) (3rd generation)" case .iPadPro_12Inch_1: return "iPad Pro (12.9-inch)" case .iPadPro_12Inch_2: return "iPad Pro (12.9-inch) (2nd generation)" case .iPadPro_12Inch_3: return "iPad Pro (12.9-inch) (3rd generation)" case .iPadPro_12Inch_4: return "iPad Pro (12.9-inch) (4th generation)" case .iPadPro_12Inch_5: return "iPad Pro (12.9-inch) (5th generation)" case .appleWatchSeries0_38mm: return "Apple Watch (1st generation) 38mm" case .appleWatchSeries0_42mm: return "Apple Watch (1st generation) 42mm" case .appleWatchSeries1_38mm: return "Apple Watch Series 1 38mm" case .appleWatchSeries1_42mm: return "Apple Watch Series 1 42mm" case .appleWatchSeries2_38mm: return "Apple Watch Series 2 38mm" case .appleWatchSeries2_42mm: return "Apple Watch Series 2 42mm" case .appleWatchSeries3_38mm: return "Apple Watch Series 3 38mm" case .appleWatchSeries3_42mm: return "Apple Watch Series 3 42mm" case .appleWatchSeries4_40mm: return "Apple Watch Series 4 40mm" case .appleWatchSeries4_44mm: return "Apple Watch Series 4 44mm" case .appleWatchSeries5_40mm: return "Apple Watch Series 5 40mm" case .appleWatchSeries5_44mm: return "Apple Watch Series 5 44mm" case .appleWatchSeries6_40mm: return "Apple Watch Series 6 40mm" case .appleWatchSeries6_44mm: return "Apple Watch Series 6 44mm" case .appleWatchSE_40mm: return "Apple Watch SE 40mm" case .appleWatchSE_44mm: return "Apple Watch SE 44mm" case .appleTV1: return "Apple TV 1" case .appleTV2: return "Apple TV 2" case .appleTV3: return "Apple TV 3" case .appleTVHD: return "Apple TV HD" case .appleTV4K: return "Apple TV 4K" case .appleTV4K2: return "Apple TV 4K (2nd generation)" case .iPodTouch1: return "iPod touch (1st generation)" case .iPodTouch2: return "iPod touch (2nd generation)" case .iPodTouch3: return "iPod touch (3rd generation)" case .iPodTouch4: return "iPod touch (4th generation)" case .iPodTouch5: return "iPod touch (5th generation)" case .iPodTouch6: return "iPod touch (6th generation)" case .iPodTouch7: return "iPod touch (7th generation)" case .homePod: return "HomePod" case let .unknown(identifier): return identifier } } } } // MARK: - Model extension Device { /// A strongly typed model type of the current device. /// /// ```swift /// // Strongly typed model type /// Device.current.model // e.g., Model.iPhone13Pro /// /// // User-friendly device name /// print(Device.current.model.name) // iPhone 13 Pro /// /// // Compile-time safe conditional check /// if Device.current.model == .iPhone13Pro { /// ... /// } /// ``` public var model: Model { .init(identifier: Model.internalIdentifier) } } // MARK: - Instance Properties extension Device.Model { /// The name of the device model (e.g., "iPhone 12 Pro"). /// /// The value of this property is an arbitrary alphanumeric string that is /// associated with the device as an identifier. For example, you can find the /// name of an iOS device in the `General > About` settings. public var name: String { #if os(iOS) || os(tvOS) return UIDevice.current.name #elseif os(watchOS) return WKInterfaceDevice.current().name #elseif os(macOS) return ProcessInfo.shared.hostName #endif } /// The family name of the device model (e.g., "iPhone" or "iPod touch"). public var family: String { #if os(iOS) || os(tvOS) return UIDevice.current.model #elseif os(watchOS) return WKInterfaceDevice.current().model #elseif os(macOS) #warning("TODO: Implement") return "" #endif } /// The model identifier of the device (e.g., "iPhone9,2"). public var identifier: String { let id = Self.internalIdentifier #if targetEnvironment(simulator) return "Simulator (\(id))" #else return id #endif } /// The model identifier of the current device (e.g., "iPhone9,2"). fileprivate static var internalIdentifier: String { if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulatorModelIdentifier } var systemInfo = utsname() uname(&systemInfo) let machine = systemInfo.machine let mirror = Mirror(reflecting: machine) var identifier = "" for child in mirror.children { if let value = child.value as? Int8, value != 0 { identifier.append(String(UnicodeScalar(UInt8(value)))) } } return identifier } }
mit
9690afd839ded0c3535045b9831d0ed6
41.73201
99
0.547761
4.060599
false
false
false
false
AxziplinLib/Regex
Sources/Core/State.swift
1
3795
// // Status.swift // Regex // // Created by devedbox on 2017/5/7. // Copyright © 2017年 AxziplinLib. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation // MARK: CharacterConvertible. /// Types conform to this protocol can generate a instance of `Character`, or throws an error of `RegexError` if cannot. public protocol CharacterConvertible { /// Creates or transition to a instance of `Character`. /// /// - Throws: An error of `RegexError` if failed. /// - Returns: An instance of `Character`. func asCharacter() throws -> Character } extension CharacterConvertible { /// Get character object by variable. var character: Character? { return try? asCharacter() } } extension Character: CharacterConvertible { public func asCharacter() throws -> Character { return self } } extension String: CharacterConvertible { public func asCharacter() throws -> Character { guard characters.count > 0 else { throw RegexError.convertFailed(.outOfBounds) } return characters[characters.startIndex] } } public protocol StateReadable { var status: State.Status { get } func result(of character: CharacterConvertible?) throws -> State.Result } public protocol StateChainable { mutating func link(to character: CharacterConvertible?) -> State } extension State { public enum Result { case matched, missed var matched: Bool { return self == .matched } } } extension State { public enum Status { case initial, intermediate, final } } public struct State { fileprivate var _next: Any? public var character: CharacterConvertible? public var states: [(CharacterConvertible&StateReadable)?] = [] public init(_ character: CharacterConvertible? = nil, next: State? = nil) { self.character = character _next = next } } extension State { /// The next state object, may be nil. public var next: State? { return _next as? State } /// Creates a state object which is status of initial. public static var initial: State { return State() } } extension State: StateReadable { public var status: State.Status { return .intermediate } public func result(of character: CharacterConvertible?) throws -> State.Result { guard let lhs = self.character?.character, let rhs = character?.character else { return .missed } guard lhs == rhs else { return .missed } return .matched } } extension State: StateChainable { @discardableResult public mutating func link(to character: CharacterConvertible? = nil) -> State { _next = State() self.character = character return next! } }
mit
c0f835d1dbc000bef21d68e52dacf777
31.973913
120
0.696466
4.440281
false
false
false
false
zhenghuadong11/firstGitHub
旅游app_useSwift/旅游app_useSwift/MYMyticketHaveTableViewCell.swift
1
5130
import Foundation import UIKit class MYMyticketHaveTableViewCell:UITableViewCell { weak var _tableViewImageView: UIImageView? weak var _nameLabel: UILabel? weak var _one_wordLabel: UILabel? weak var _needMoneyLabel: UILabel? var _isHaveEvaluationLabel:UILabel = UILabel() var _myTicketModel:MYMYticketHaveModel{ set{ self._collectModelTmp = newValue self.setUpSubViewWithDiffrentWithAgoModel(newValue) } get { return _collectModelTmp! } } var _collectModelTmp:MYMYticketHaveModel? func setUpSubViewWithDiffrentWithAgoModel(diffrentWithAgoModel:MYMYticketHaveModel) -> Void { _tableViewImageView?.image = UIImage(named: (diffrentWithAgoModel.picture!)) _nameLabel?.text = diffrentWithAgoModel.name _one_wordLabel?.text = diffrentWithAgoModel.one_word _needMoneyLabel?.text = diffrentWithAgoModel.date?.description } static func firstPageCellWithTableView(tableView:UITableView) -> MYMyticketHaveTableViewCell { let cellID="MYMyticketHaveTableViewCell" var cell:MYMyticketHaveTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellID) as? MYMyticketHaveTableViewCell if cell == nil { cell = MYMyticketHaveTableViewCell(style: UITableViewCellStyle.Default , reuseIdentifier: cellID) } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let deleteLabel = UILabel() deleteLabel.backgroundColor = UIColor.redColor() deleteLabel.text = "退票" self.contentView.addSubview(deleteLabel) deleteLabel.snp_makeConstraints { (make) in make.left.equalTo(self.snp_right) make.top.equalTo(self.contentView) make.bottom.equalTo(self.contentView).offset(1) make.width.equalTo(self.contentView) } let tableViewImageView = UIImageView() self.selectionStyle = UITableViewCellSelectionStyle.None self.addSubview(tableViewImageView) _tableViewImageView = tableViewImageView let nameLabel = UILabel() self.addSubview(nameLabel) _nameLabel = nameLabel let one_wordLabel = UILabel() self.addSubview(one_wordLabel) _one_wordLabel = one_wordLabel let needMoneyLabel = UILabel() self.addSubview(needMoneyLabel) _needMoneyLabel = needMoneyLabel self.addSubview(_isHaveEvaluationLabel) _isHaveEvaluationLabel.textColor = UIColor.grayColor() } override func layoutSubviews() { _tableViewImageView?.frame = CGRectMake(10, 10, self.frame.width * 0.25, self.frame.height - 20) _nameLabel?.snp_makeConstraints(closure: { (make) in make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.top.equalTo(self.snp_top).offset(10) make.right.equalTo(self.snp_right).offset(-10) make.height.equalTo(self.snp_height).multipliedBy(0.25) }) _one_wordLabel?.snp_makeConstraints(closure: { (make) in make.top.equalTo(_nameLabel!.snp_bottom).offset(10) make.right.equalTo(self.snp_right).offset(-10) make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.height.equalTo(self.snp_height).multipliedBy(0.25) }) _needMoneyLabel?.snp_makeConstraints(closure: { (make) in make.top.equalTo(_one_wordLabel!.snp_bottom).offset(10) make.right.equalTo(self.snp_right).offset(-10) make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.height.equalTo(self.snp_height).multipliedBy(0.25) }) _isHaveEvaluationLabel.snp_makeConstraints { (make) in make.top.equalTo(self).offset(10) make.right.equalTo(self).offset(-10) make.height.equalTo(30) make.width.equalTo(100) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
bd07207c115295f0794268421756f7d8
33.870748
135
0.541553
5.626784
false
false
false
false
walokra/Haikara
Haikara/Views/SearchFooter.swift
1
2874
/** * Copyright (c) 2017 Razeware LLC * * 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. */ // // SearchFooter.swift // highkara // import UIKit class SearchFooter: UIView { var filteringText: String = NSLocalizedString("SEARCH_FOOTER_FILTER", comment: "") var filteringNoMatch: String = NSLocalizedString("SEARCH_FOOTER_NO_MATCH", comment: "") let label: UILabel = UILabel() override public init(frame: CGRect) { super.init(frame: frame) configureView() } required public init?(coder: NSCoder) { super.init(coder: coder) configureView() } func configureView() { backgroundColor = Theme.tintColor alpha = 0.0 // Configure label label.textAlignment = .center label.textColor = UIColor.white addSubview(label) } override func draw(_ rect: CGRect) { label.frame = bounds } //MARK: - Animation fileprivate func hideFooter() { UIView.animate(withDuration: 0.7) {[unowned self] in self.alpha = 0.0 } } fileprivate func showFooter() { UIView.animate(withDuration: 0.7) {[unowned self] in self.alpha = 1.0 } } } extension SearchFooter { //MARK: - Public API public func setNotFiltering() { label.text = "" hideFooter() } public func setIsFilteringToShow(filteredItemCount: Int, of totalItemCount: Int) { if (filteredItemCount == totalItemCount) { setNotFiltering() } else if (filteredItemCount == 0) { label.text = filteringNoMatch showFooter() } else { label.text = "\(filteringText) \(filteredItemCount) / \(totalItemCount)" showFooter() } } }
mit
747e6476216b186019b2a95e174a3041
29.252632
91
0.642658
4.547468
false
false
false
false
thelukester92/swift-engine
swift-engine/Engine/Classes/LGDeserializer.swift
1
2632
// // LGDeserializer.swift // swift-engine // // Created by Luke Godfrey on 9/4/14. // Copyright (c) 2014 Luke Godfrey. See LICENSE. // public class LGDeserializer { // TODO: Don't use this hidden wrapper around LGDeserializable // This is currently needed because Swift is stupid and has a segfault at compile time if we pass LGDeserializable.Type directly struct Deserializable { var requiredProps: [String] var optionalProps: [String] var instantiate: () -> LGDeserializable var actualDeserializable: LGDeserializable.Type init(requiredProps: [String], optionalProps: [String], instantiate: @autoclosure () -> LGDeserializable, actualDeserializable: LGDeserializable.Type) { self.requiredProps = requiredProps self.optionalProps = optionalProps self.instantiate = instantiate self.actualDeserializable = actualDeserializable } } // TODO: Use stored property when Swift allows it struct Static { static var deserializables = [String:Deserializable]() static var initialized = false } public class func initialize() { if !Static.initialized { LGDeserializer.registerDeserializable(LGAnimatable) LGDeserializer.registerDeserializable(LGPhysicsBody) LGDeserializer.registerDeserializable(LGPosition) LGDeserializer.registerDeserializable(LGSprite) LGDeserializer.registerDeserializable(LGScriptable) LGDeserializer.registerDeserializable(LGTweenable) Static.initialized = true } } public class func registerDeserializable<T: LGDeserializable>(deserializable: T.Type) { // TODO: Don't be so ridiculous when Swift doesn't require it... Static.deserializables[deserializable.type()] = Deserializable( requiredProps: deserializable.requiredProps, optionalProps: deserializable.optionalProps, instantiate: deserializable.instantiate(), actualDeserializable: deserializable ) } public class func deserialize(serialized: String, withType type: String) -> LGComponent? { initialize() if let deserializable = Static.deserializables[type] { if let json = LGJSON.JSONFromString(serialized) { let component = deserializable.instantiate() for prop in deserializable.requiredProps { if let val = json[prop] { if component.setValue(val, forKey: prop) { continue } } // if json[prop] == nil || !component(prop, val: val) return nil } for prop in deserializable.optionalProps { if let val = json[prop] { component.setValue(val, forKey: prop) } } return component } } return nil } }
mit
213d6cdd1885b56625613e607314c095
25.32
151
0.716565
3.842336
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/TXTReader/Reader/Service/ZSReaderManager.swift
1
3020
// // ZSReaderManager.swift // zhuishushenqi // // Created by yung on 2018/7/9. // Copyright © 2018年 QS. All rights reserved. // import UIKit final class ZSReaderManager { var cachedChapter:[String:QSChapter] = [:] // 获取下一个页面 func getNextPage(record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){ //2.获取当前阅读的章节与页码,这里由于是网络小说,有几种情况 //(1).当前章节信息为空,那么这一章只有一页,翻页直接进入了下一页,章节加一 //(2).当前章节信息不为空,说明已经请求成功了,那么计算当前页码是否为该章节的最后一页 //这是2(2) if let chapterModel = record.chapterModel { let page = record.page if page < chapterModel.pages.count - 1 { let pageIndex = page + 1 let pageModel = chapterModel.pages[pageIndex] callback?(pageModel) } else { // 新的章节 getNewChapter(chapterOffset: 1,record: record,chaptersInfo: chaptersInfo,callback: callback) } } else { getNewChapter(chapterOffset: 1,record: record,chaptersInfo: chaptersInfo,callback: callback) } } func getLastPage(record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){ if let chapterModel = record.chapterModel { let page = record.page if page > 0 { // 当前页存在 let pageIndex = page - 1 let pageModel = chapterModel.pages[pageIndex] callback?(pageModel) } else {// 当前章节信息不存在,必然是新的章节 getNewChapter(chapterOffset: -1,record: record,chaptersInfo: chaptersInfo,callback: callback) } } else { getNewChapter(chapterOffset: -1,record: record,chaptersInfo: chaptersInfo,callback: callback) } } func getNewChapter(chapterOffset:Int,record:QSRecord,chaptersInfo:[ZSChapterInfo]?,callback:ZSSearchWebAnyCallback<QSPage>?){ let chapter = record.chapter + chapterOffset if chapter > 0 && chapter < (chaptersInfo?.count ?? 0) { if let chapterInfo = chaptersInfo?[chapter] { let link = chapterInfo.link // 内存缓存 if let model = cachedChapter[link] { callback?(model.pages.first) } else { callback?(nil) // viewModel.fetchChapter(key: link, { (body) in // if let bodyInfo = body { // if let network = self.cacheChapter(body: bodyInfo, index: chapter) { // callback?(network.pages.first) // } // } // }) } } } } }
mit
c0d9b42f5a8060f73a38c3da4c473e2f
36.712329
129
0.550672
4.13985
false
false
false
false
buscarini/vitemo
vitemo/Carthage/Checkouts/GRMustache.swift/Mustache/Rendering/Context.swift
4
10076
// 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 /** A Context represents a state of the Mustache "context stack". The context stack grows and shrinks as the Mustache engine enters and leaves Mustache sections. The top of the context stack is called the "current context". It is the value rendered by the `{{.}}` tag: // Renders "Kitty, Pussy, Melba, " let template = Template(string: "{{#cats}}{{.}}, {{/cats}}")! template.render(Box(["cats": ["Kitty", "Pussy", "Melba"]]))! Key lookup starts with the current context and digs down the stack until if finds a value: // Renders "<child>, <parent>, " let template = Template(string: "{{#children}}<{{name}}>, {{/children}}")! let data = [ "name": "parent", "children": [ ["name": "child"], [:] // a child without a name ] ] template.render(Box(data))! :see: Configuration :see: TemplateRepository :see: RenderFunction */ final public class Context { // ========================================================================= // MARK: - Creating Contexts /** Builds an empty Context. */ public convenience init() { self.init(type: .Root) } /** Builds a context that contains the provided box. :param: box A box :returns: a new context that contains the provided box. */ public convenience init(_ box: MustacheBox) { self.init(type: .Box(box: box, parent: Context())) } /** Builds a context with a registered key. Registered keys are looked up first when evaluating Mustache tags. :param: key An identifier :param: box The box registered for `key` */ public convenience init(registeredKey key: String, box: MustacheBox) { self.init(type: .Root, registeredKeysContext: Context(Box([key: box]))) } // ========================================================================= // MARK: - Deriving New Contexts /** Returns a new context with the provided box pushed at the top of the context stack. :param: box The box pushed on the top of the context stack :returns: a new context */ public func extendedContext(box: MustacheBox) -> Context { return Context(type: .Box(box: box, parent: self), registeredKeysContext: registeredKeysContext) } /** Returns a new context with the provided box at the top of the context stack. Registered keys are looked up first when evaluating Mustache tags. :param: key An identifier :param: box The box registered for `key` :returns: a new context */ public func contextWithRegisteredKey(key: String, box: MustacheBox) -> Context { let registeredKeysContext = (self.registeredKeysContext ?? Context()).extendedContext(Box([key: box])) return Context(type: self.type, registeredKeysContext: registeredKeysContext) } // ========================================================================= // MARK: - Fetching Values from the Context Stack /** Returns the top box of the context stack, the one that would be rendered by the `{{.}}` tag. */ public var topBox: MustacheBox { switch type { case .Root: return Box() case .Box(box: let box, parent: _): return box case .InheritedPartial(inheritedPartial: _, parent: let parent): return parent.topBox } } /** Returns the boxed value stored in the context stack for the given key. The following search pattern is used: 1. If the key is "registered", returns the registered box for that key. 2. Otherwise, searches the context stack for a box that has a non-empty box for the key (see `InspectFunction`). 3. If none of the above situations occurs, returns the empty box. let data = ["name": "Groucho Marx"] let context = Context(Box(data)) // "Groucho Marx" context["name"].value If you want the value for a full Mustache expression such as `user.name` or `uppercase(user.name)`, use the `boxForMustacheExpression` method. :see: boxForMustacheExpression */ public subscript (key: String) -> MustacheBox { if let registeredKeysContext = registeredKeysContext { let box = registeredKeysContext[key] if !box.isEmpty { return box } } switch type { case .Root: return Box() case .Box(box: let box, parent: let parent): let innerBox = box[key] if innerBox.isEmpty { return parent[key] } else { return innerBox } case .InheritedPartial(inheritedPartial: _, parent: let parent): return parent[key] } } /** Evaluates a Mustache expression such as `name`, or `uppercase(user.name)`. let data = ["person": ["name": "Albert Einstein"]] let context = Context(Box(data)) // "Albert Einstein" context.boxForMustacheExpression("person.name")!.value :param: string The expression string :param: error If there is a problem parsing or evaluating the expression, upon return contains an NSError object that describes the problem. :returns: The value of the expression */ public func boxForMustacheExpression(string: String, error: NSErrorPointer = nil) -> MustacheBox? { let parser = ExpressionParser() var empty = false if let expression = parser.parse(string, empty: &empty, error: error) { let invocation = ExpressionInvocation(expression: expression) let invocationResult = invocation.invokeWithContext(self) switch invocationResult { case .Error(let invocationError): if error != nil { error.memory = invocationError } return nil case .Success(let box): return box } } return nil } // ========================================================================= // MARK: - Not public private enum Type { case Root case Box(box: MustacheBox, parent: Context) case InheritedPartial(inheritedPartial: TemplateASTNode.InheritedPartial, parent: Context) } private var registeredKeysContext: Context? private let type: Type var willRenderStack: [WillRenderFunction] { switch type { case .Root: return [] case .Box(box: let box, parent: let parent): if let willRender = box.willRender { return [willRender] + parent.willRenderStack } else { return parent.willRenderStack } case .InheritedPartial(inheritedPartial: _, parent: let parent): return parent.willRenderStack } } var didRenderStack: [DidRenderFunction] { switch type { case .Root: return [] case .Box(box: let box, parent: let parent): if let didRender = box.didRender { return parent.didRenderStack + [didRender] } else { return parent.didRenderStack } case .InheritedPartial(inheritedPartial: _, parent: let parent): return parent.didRenderStack } } var inheritedPartialStack: [TemplateASTNode.InheritedPartial] { switch type { case .Root: return [] case .Box(box: _, parent: let parent): return parent.inheritedPartialStack case .InheritedPartial(inheritedPartial: let inheritedPartial, parent: let parent): return [inheritedPartial] + parent.inheritedPartialStack } } private init(type: Type, registeredKeysContext: Context? = nil) { self.type = type self.registeredKeysContext = registeredKeysContext } func extendedContext(# inheritedPartial: TemplateASTNode.InheritedPartial) -> Context { return Context(type: .InheritedPartial(inheritedPartial: inheritedPartial, parent: self), registeredKeysContext: registeredKeysContext) } } extension Context: DebugPrintable { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { switch type { case .Root: return "Context.Root" case .Box(box: let box, parent: let parent): return "Context.Box(\(box)):\(parent.debugDescription)" case .InheritedPartial(inheritedPartial: let inheritedPartial, parent: let parent): return "Context.inheritedPartial:\(parent.debugDescription)" } } }
mit
4cc97d2f953e285abfdc71599ed05523
33.272109
143
0.601787
4.86715
false
false
false
false
Liujlai/DouYuD
DYTV/DYTV/BaseViewModel.swift
1
1493
// // BaseViewModel.swift // DYTV // // Created by idea on 2017/8/16. // Copyright © 2017年 idea. All rights reserved. // import UIKit class BaseViewModel { lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() } extension BaseViewModel{ // func loadAnchorData(isGroupData : Bool, URLString: String ,parameters : [String : Any]? = nil , finishedCallBack : @escaping () -> () ){ NetworkTools.requestData(URLString: URLString, type: .get , parameters: parameters as? [String : NSString]) { (result) in // 对结果进行处理-->转成字典 guard let resultDict = result as? [String: Any] else{ return } guard let dataArray = resultDict["data"] as? [[String: Any]] else { return} if isGroupData{ // 便利数组中的字典 for dict in dataArray{ self.anchorGroups.append(AnchorGroup(dict: dict)) } }else{ // 创建组 let group = AnchorGroup() // 遍历dataArray的所有的字典 for dict in dataArray{ group.anchors.append(AnchorModel(dict : dict)) } // 将group。添加到anchorGroup self.anchorGroups.append(group) } //完成回调 finishedCallBack() } } }
mit
1a4dec01b70258323e6627b48ca5282a
29.042553
143
0.502833
4.852234
false
false
false
false
icapps/swiftGenericWebService
Documentation/FaroPlayground.playground/Pages/9. Retry.xcplaygroundpage/Contents.swift
3
2012
//: [Previous](@previous) //: # Retry import Faro import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true //: # Retry StubbedFaroURLSession.setup() let call = Call(path: "posts") let post_1 = """ [ { "id": 1, "title": "Post 1" }, { "id": 2, "title": "Post 2" }, { "id": 3, "title": "Post 3" } ] """.data(using: .utf8)! let post_2 = """ [ { "id": 10, "title": "Post 10" } ] """.data(using: .utf8)! let errorData = """ [ { "message": "Token invalid" } ] """.data(using: .utf8)! //: The stubbing we use allows you to write multiple repsonses for every time a request is performed. call.stub(statusCode: 401, data: errorData) call.stub(statusCode: 200, data:post_1) call.stub(statusCode: 200, data: post_2) class Post: Decodable { let uuid: Int var title: String? private enum CodingKeys: String, CodingKey { case uuid = "id" case title } } //: Session with multiple tasks not autostarted //: If you put autoStart to false the task that is returned after a perform is not started. This is what we want in this case where we start multiple requests with different repsonses. let service = StubServiceHandler<Post>(call: call, autoStart: false) { let posts = try? $0() } service.session.enableRetry { (data, response, error) -> Bool in guard let response = response as? HTTPURLResponse, response.statusCode == 401 else { return false } return true } let task1 = service.performArray() let authenticationFailedTask = service.performArray() let task2 = service.performArray() authenticationFailedTask?.resume() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) { task1?.resume() task2?.resume() } /*: 1. Suspend all tasks when you get a 401 2. Make it possible to define any failure based on the reponse 3. Start a refresh request token request 4. Make every task valid again 5. Resume all suspended and fixed tasks */ //: [Next](@next)
mit
274fdffc47de5f0360642e75c7745710
19.530612
184
0.661034
3.536028
false
false
false
false
avaidyam/Parrot
Parrot/Event.swift
1
12628
import MochaUI import ParrotServiceExtension import Carbon // FIXME: dear lord why /* TODO: Storing everything in UserDefaults is a bad idea... use a Dictionary! */ public struct ConversationSettings { public let serviceIdentifier: Service.IdentifierType public let identifier: Conversation.IdentifierType private var keyName: String { return "settings/\(self.serviceIdentifier)/\(self.identifier)/" } public var vibrate: Bool { get { return Settings.get(forKey: self.keyName + #function, default: false) } set { Settings.set(forKey: self.keyName + #function, value: newValue) } } public var sound: NSSound? { get { return Settings.archivedGet(forKey: self.keyName + #function, default: nil) } set { Settings.archivedSet(forKey: self.keyName + #function, value: newValue) } } public var outgoingColor: NSColor? { get { return Settings.archivedGet(forKey: self.keyName + #function, default: nil) } set { Settings.archivedSet(forKey: self.keyName + #function, value: newValue) } } public var incomingColor: NSColor? { get { return Settings.archivedGet(forKey: self.keyName + #function, default: nil) } set { Settings.archivedSet(forKey: self.keyName + #function, value: newValue) } } public var backgroundImage: NSImage? { get { return Settings.archivedGet(forKey: self.keyName + #function, default: nil) } set { Settings.archivedSet(forKey: self.keyName + #function, value: newValue) } } } public struct EventDescriptor { public let identifier: String public let contents: String? public let description: String? public let image: NSImage? public let sound: NSSound? public let vibrate: Bool? public let script: URL? } public protocol EventAction { static func perform(with: EventDescriptor) } // input: identifier, contents, description, image // properties: actions public enum BannerAction: EventAction { public static func perform(with event: EventDescriptor) { let notification = NSUserNotification() notification.identifier = event.identifier notification.title = event.contents ?? "" //notification.subtitle = event.contents notification.informativeText = event.description ?? "" notification.deliveryDate = Date() //notification.alwaysShowsActions = true //notification.hasReplyButton = true //notification.otherButtonTitle = "Mute" //notification.responsePlaceholder = "Send a message..." notification.identityImage = event.image notification.identityStyle = .circle //notification.soundName = event.sound?.absoluteString//"texttone:Bamboo" // this works!! //notification.set(option: .customSoundPath, value: event.sound?.absoluteString) //notification.set(option: .vibrateForceTouch, value: true) notification.set(option: .alwaysShow, value: true) // Post the notification "uniquely" -- that is, replace it while it is displayed. NSUserNotification.notifications() .filter { $0.identifier == notification.identifier } .forEach { $0.remove() } notification.post() } } // input: contents, image public enum BezelAction: EventAction { public static func perform(with event: EventDescriptor) { SystemBezel(image: event.image, text: event.contents) .show().hide(after: 5.seconds) } } // input: none // properties: filename public enum SoundAction: EventAction { public static func perform(with event: EventDescriptor) { event.sound?.play() } } // input: none public enum VibrateAction: EventAction { public static func perform(with event: EventDescriptor) { guard let x = event.vibrate, x else { return } NSHapticFeedbackManager.vibrate(length: 1000, interval: 10) } } // input: none public enum BounceDockAction: EventAction { public static func perform(with event: EventDescriptor) { let id = NSApp.requestUserAttention(.criticalRequest) DispatchQueue.main.asyncAfter(deadline: 2.seconds.later) { NSApp.cancelUserAttentionRequest(id) } } } // input: none public enum FlashLEDAction: EventAction { public static func perform(with event: EventDescriptor) { KeyboardBrightnessAnimation().start() } } // input: contents, description public enum SpeakAction: EventAction { public static func perform(with event: EventDescriptor) { let text = (event.contents ?? "") + (event.description ?? "") NSApp.say(text) } } // input: none // properties: script path public enum ScriptAction: EventAction { public static func perform(with event: EventDescriptor) { guard let s = event.script else { return } // Branch to each possible script type: if s.pathExtension.starts(with: "wflow") || s.pathExtension.starts(with: "workflow") { // Automator let task = try? NSUserAutomatorTask(url: s) //task?.variables = nil task?.execute(withInput: "Event!" as NSString, completionHandler: {print($0 ?? $1 ?? "undefined")}) } else if s.pathExtension.starts(with: "scpt") { // AppleScript/JSX let message = NSAppleEventDescriptor(string: "Event!") let desc = ScriptAction.descriptor(for: "main", [message]) _ = try? NSUserAppleScriptTask(url: s).execute(withAppleEvent: desc, completionHandler: {print($0 ?? $1 ?? "undefined")}) } else { // probably Unix _ = try? NSUserUnixTask(url: s).execute(withArguments: ["Event!"], completionHandler: {print($0 ?? "undefined")}) } } // Create a "function call" AEDesc to invoke the script with. private static func descriptor(for functionName: String, _ parameters: [NSAppleEventDescriptor]) -> NSAppleEventDescriptor { let event = NSAppleEventDescriptor( eventClass: UInt32(kASAppleScriptSuite), eventID: UInt32(kASSubroutineEvent), targetDescriptor: .currentProcess(), returnID: Int16(kAutoGenerateReturnID), transactionID: Int32(kAnyTransactionID) ) let function = NSAppleEventDescriptor(string: functionName) let params = NSAppleEventDescriptor.list() parameters.forEach { params.insert($0, at: 1) } event.setParam(function, forKeyword: AEKeyword(keyASSubroutineName)) event.setParam(params, forKeyword: AEKeyword(keyDirectObject)) return event } } public extension ParrotAppController { /// An archive of all the Hangouts events we're watching; besides connect/disconnect, /// they all have to do with Conversation changes like focus/events/participants. public func registerEvents() { self.watching = [ AutoSubscription(kind: Notification.Service.DidConnect) { _ in let event = EventDescriptor(identifier: "Parrot.ConnectionStatus", contents: "Parrot has connected.", description: nil, image: NSImage(named: .connectionOutline), sound: nil, vibrate: nil, script: nil) let actions: [EventAction.Type] = [BannerAction.self, SoundAction.self, BezelAction.self] actions.forEach { $0.perform(with: event) } }, AutoSubscription(kind: Notification.Service.DidDisconnect) { _ in DispatchQueue.main.async { // FIXME why does wrapping it twice work?? let event = EventDescriptor(identifier: "Parrot.ConnectionStatus", contents: "Parrot has disconnected.", description: nil, image: NSImage(named: .connectionOutline), sound: nil, vibrate: nil, script: nil) let actions: [EventAction.Type] = [BannerAction.self, SoundAction.self, BezelAction.self] actions.forEach { $0.perform(with: event) } } }, AutoSubscription(kind: Notification.Conversation.DidJoin) { _ in }, AutoSubscription(kind: Notification.Conversation.DidLeave) { _ in }, AutoSubscription(kind: Notification.Conversation.DidChangeFocus) { _ in }, AutoSubscription(kind: Notification.Conversation.DidReceiveWatermark) { _ in }, AutoSubscription(kind: Notification.Conversation.WillSendEvent) { _ in // TODO: This is currently hard-wired... NSSound(assetName: .sentMessage)?.play() }, AutoSubscription(kind: Notification.Conversation.DidReceiveEvent) { e in let c = ServiceRegistry.services.first!.value guard let event = e.userInfo?["event"] as? Event, let conv = e.object as? Conversation else { return } // Handle specific `Message` and chat occlusion cases: var showNote = true if let m = MessageListViewController.openConversations[conv.identifier] { showNote = !(m.view.window?.isKeyWindow ?? false) } // FIXME: We don't handle events for non-`Message` types yet. guard let msg = event as? Message else { return } if !msg.sender.me && showNote { let settings = ConversationSettings(serviceIdentifier: conv.serviceIdentifier, identifier: conv.identifier) // The message text contained the user's full or first name: it's a specific mention. // FIXME: We don't support mention hot-words yet. var desc = msg.text if (msg.text ?? "").contains(c.directory.me.firstName) || (msg.text ?? "").contains(c.directory.me.fullName) { desc = "Mentioned you" } // Perform the event via its descriptor. let event = EventDescriptor(identifier: conv.identifier, contents: msg.sender.firstName, description: desc, image: msg.sender.image, sound: settings.sound, vibrate: settings.vibrate, script: nil) let actions: [EventAction.Type] = [BannerAction.self, SoundAction.self, VibrateAction.self] actions.forEach { $0.perform(with: event) } } }, AutoSubscription(kind: NSUserNotification.didActivateNotification) { let c = ServiceRegistry.services.first!.value guard let notification = $0.object as? NSUserNotification, let conv = c.conversations.conversations[notification.identifier ?? ""] else { return } switch notification.activationType { case .contentsClicked: MessageListViewController.show(conversation: conv, parent: self.conversationsController) case .actionButtonClicked: conv.muted = true case .replied where notification.response?.string != nil: MessageListViewController.sendMessage(notification.response!.string, conv) default: break } } ] } } /* FocusEvent: A person changed their focus (viewing or typing in a conversation). Includes self. PresenceEvent: A person's presence changed. Includes self. Includes dis/connections. MessageEvent: A message was sent or received. Includes self. Properties: Group?, Background?, Sent? InvitationEvent: A person was invited to join a conversation. MentionEvent: A name or a keyword was mentioned in a conversation. */ // add "action" property -- if the event is "acted on", the handler is invoked // i.e. notification button // i.e. dock bounce --> NSAppDelegate checks if bounce, then calls handler (otherwise bail) /* let ev = Event(identifier: event.conversation_id, contents: user.firstName + " (via Hangouts)", description: event.text, image: fetchImage(user: user, monogram: true)) let actions: [EventAction.Type] = [BannerAction.self, BezelAction.self, SoundAction.self, VibrateAction.self, BounceDockAction.self, FlashLEDAction.self, SpeakAction.self, ScriptAction.self] actions.forEach { $0.perform(with: ev) } */
mpl-2.0
ebcff2c875df1fa537faf4563d2d29e4
43.939502
191
0.629474
4.72428
false
false
false
false
tkremenek/swift
test/IDE/complete_func_reference.swift
7
10355
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VOID_VOID_0 | %FileCheck %s -check-prefix=VOID_VOID // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VOID_VOID_1 | %FileCheck %s -check-prefix=VOID_VOID // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VOID_VOID_2 | %FileCheck %s -check-prefix=VOID_VOID // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VOID_VOID_3 | %FileCheck %s -check-prefix=VOID_VOID // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VOID_VOID_4 | %FileCheck %s -check-prefix=VOID_VOID // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ANY_INT_0 | %FileCheck %s -check-prefix=ANY_INT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ANY_INT_1 | %FileCheck %s -check-prefix=ANY_INT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ANY_INT_2 > %t.results // RUN:%FileCheck %s -check-prefix=ANY_INT < %t.results // RUN:%FileCheck %s -check-prefix=ANY_INT_STATIC_CURRY < %t.results // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ANY_INT_3 | %FileCheck %s -check-prefix=ANY_INT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ANY_INT_4 | %FileCheck %s -check-prefix=ANY_INT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INT_ANY_0 | %FileCheck %s -check-prefix=INT_ANY // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INT_ANY_1 | %FileCheck %s -check-prefix=INT_ANY // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INT_ANY_2 > %t.results // RUN: %FileCheck %s -check-prefix=INT_ANY < %t.results // RUN: %FileCheck %s -check-prefix=INT_ANY_STATIC_CURRY < %t.results // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=INT_ANY_3 > %t.results // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VOID_INT_INT_0 | %FileCheck %s -check-prefix=VOID_INT_INT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VOID_INT_INT_1 | %FileCheck %s -check-prefix=VOID_INT_INT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=VOID_INT_INT_2 | %FileCheck %s -check-prefix=VOID_INT_INT func voidToVoid() {} func voidToInt() -> Int {} func intToInt(a: Int) -> Int {} func intToVoid(a: Int) {} func voidToAny() -> Any {} func anyToAny(a: Any) -> Any {} func anyToVoid(a: Any) {} func intToAny(a: Int) -> Any {} func anyToInt(a: Any) -> Int {} func returnsIntToInt() -> (Int) -> Int {} struct S0 { func voidToVoid() {} func voidToInt() -> Int {} func intToInt(a: Int) -> Int {} func intToVoid(a: Int) {} func voidToAny() -> Any {} func anyToAny(a: Any) -> Any {} func anyToVoid(a: Any) {} func intToAny(a: Int) -> Any {} func anyToInt(a: Any) -> Int {} func returnsIntToInt() -> (Int) -> Int {} static func voidToVoid() {} static func voidToInt() -> Int {} static func intToInt(a: Int) -> Int {} static func intToVoid(a: Int) {} static func voidToAny() -> Any {} static func anyToAny(a: Any) -> Any {} static func anyToVoid(a: Any) {} static func intToAny(a: Int) -> Any {} static func anyToInt(a: Any) -> Int {} static func returnsIntToInt() -> (Int) -> Int {} } do { func take(_: @escaping ()->()) {} take(#^VOID_VOID_0^#) } // VOID_VOID: Begin completions // VOID_VOID-DAG: Decl{{.*}}/TypeRelation[Identical]: voidToVoid[#() -> ()#]; // VOID_VOID-DAG: Decl{{.*}}/TypeRelation[Invalid]: anyToVoid({#a: Any#})[#Void#]; // VOID_VOID-DAG: Decl{{.*}}/TypeRelation[Invalid]: intToVoid({#a: Int#})[#Void#]; // VOID_VOID-DAG: Decl{{.*}}: anyToAny({#a: Any#})[#Any#]; // VOID_VOID-DAG: Decl{{.*}}: intToAny({#a: Int#})[#Any#]; // VOID_VOID-DAG: Decl{{.*}}: voidToInt()[#Int#]; // VOID_VOID-DAG: Decl{{.*}}: anyToInt({#a: Any#})[#Int#]; // VOID_VOID-DAG: Decl{{.*}}: intToInt({#a: Int#})[#Int#]; // VOID_VOID-DAG: Decl{{.*}}: voidToAny()[#Any#]; // VOID_VOID-DAG: Decl{{.*}}: returnsIntToInt()[#(Int) -> Int#]; // VOID_VOID: End completions do { func take(_: Int, _: Int, c: @escaping ()->()) {} take(1, 2, c: #^VOID_VOID_1^#) } do { let take: ()->() take = #^VOID_VOID_2^# } do { let take: ()->() take = S0().#^VOID_VOID_3^# } do { let take: ()->() take = S0.#^VOID_VOID_4^# } do { func take(_: @escaping (Any)->Int) {} take(#^ANY_INT_0^#) } do { func take(_: @escaping (Any)->Int) {} take(S0().#^ANY_INT_1^#) } do { func take(_: @escaping (Any)->Int) {} take(S0.#^ANY_INT_2^#) } do { func take(_: @escaping ((Any)->Int)???!) {} take(S0().#^ANY_INT_3^#) } do { let take: ((Any)->Int)? take = S0().#^ANY_INT_4^# } // ANY_INT: Begin completions // ANY_INT_DAG: Decl{{.*}}/TypeRelation[Identical]: anyToInt(a:); name=anyToInt(a:) // ANY_INT-DAG: Decl{{.*}}/TypeRelation[Invalid]: intToVoid({#a: Int#})[#Void#]; // ANY_INT-DAG: Decl{{.*}}/TypeRelation[Invalid]: anyToVoid({#a: Any#})[#Void#]; // ANY_INT-DAG: Decl{{.*}}/TypeRelation[Invalid]: voidToVoid()[#Void#]; // ANY_INT-DAG: Decl{{.*}}: voidToAny()[#Any#]; // ANY_INT-DAG: Decl{{.*}}: intToInt({#a: Int#})[#Int#]; // ANY_INT-DAG: Decl{{.*}}: intToAny({#a: Int#})[#Any#]; // ANY_INT-DAG: Decl{{.*}}: anyToAny({#a: Any#})[#Any#]; // ANY_INT-DAG: Decl{{.*}}: voidToInt()[#Int#]; // ANY_INT-DAG: Decl{{.*}}: returnsIntToInt()[#(Int) -> Int#]; // ANY_INT: End completions // ANY_INT_STATIC_CURRY: Begin completions // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: anyToInt({#(self): S0#})[#(a: Any) -> Int#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: voidToVoid({#(self): S0#})[#() -> Void#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: intToVoid({#(self): S0#})[#(a: Int) -> Void#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: anyToVoid({#(self): S0#})[#(a: Any) -> Void#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: voidToInt({#(self): S0#})[#() -> Int#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: intToInt({#(self): S0#})[#(a: Int) -> Int#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: voidToAny({#(self): S0#})[#() -> Any#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: anyToAny({#(self): S0#})[#(a: Any) -> Any#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: intToAny({#(self): S0#})[#(a: Int) -> Any#]; // ANY_INT_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: returnsIntToInt({#(self): S0#})[#() -> (Int) -> Int#]; // ANY_INT_STATIC_CURRY: End completions do { func take(_: @escaping (Int)->Any) {} take(#^INT_ANY_0^#) } // INT_ANY: Begin completions // INT_ANY-DAG: Decl{{.*}}/TypeRelation[Identical]: intToAny(a:)[#(Int) -> Any#]; // INT_ANY-DAG: Decl{{.*}}/TypeRelation[Convertible]: intToInt(a:)[#(Int) -> Int#]; // INT_ANY-DAG: Decl{{.*}}/TypeRelation[Convertible]: intToVoid(a:)[#(Int) -> ()#]; // INT_ANY-DAG: Decl{{.*}}/TypeRelation[Convertible]: anyToAny(a:)[#(Any) -> Any#]; // INT_ANY-DAG: Decl{{.*}}/TypeRelation[Convertible]: anyToInt(a:)[#(Any) -> Int#]; // INT_ANY-DAG: Decl{{.*}}/TypeRelation[Convertible]: anyToVoid(a:)[#(Any) -> ()#]; // INT_ANY-DAG: Decl{{.*}}/TypeRelation[Convertible]: returnsIntToInt()[#(Int) -> Int#]; // INT_ANY-DAG: Decl{{.*}}/TypeRelation[Invalid]: voidToVoid()[#Void#]; // INT_ANY-DAG: Decl{{.*}}: voidToInt()[#Int#]; // INT_ANY-DAG: Decl{{.*}}: voidToAny()[#Any#]; // INT_ANY: End completions // INT_ANY_STATIC_CURRY: Begin completions // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: intToInt({#(self): S0#})[#(a: Int) -> Int#]; // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: intToVoid({#(self): S0#})[#(a: Int) -> Void#]; // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: anyToAny({#(self): S0#})[#(a: Any) -> Any#]; // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: anyToVoid({#(self): S0#})[#(a: Any) -> Void#]; // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Identical]: intToAny({#(self): S0#})[#(a: Int) -> Any#]; // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Convertible]: anyToInt({#(self): S0#})[#(a: Any) -> Int#]; // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: returnsIntToInt({#(self): S0#})[#() -> (Int) -> Int#]; // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: voidToAny({#(self): S0#})[#() -> Any#]; // INT_ANY_STATIC_CURRY-DAG: Decl[InstanceMethod]/CurrNominal: voidToInt({#(self): S0#})[#() -> Int#]; // INT_ANY_STATIC_CURRY: End completions do { func take(_: @escaping (Int)->Any) {} take(S0().#^INT_ANY_1^#) } do { func take(_: @escaping (Int)->Any) {} take(S0.#^INT_ANY_2^#) } do { func take(_: @escaping ((Int)->Any)?) {} take(S0.#^INT_ANY_3^#) } do { func take(_: @escaping ()->(Int)->Int) {} take(#^VOID_INT_INT_0^#) } do { func take(_: @escaping ()->(Int)->Int) {} take(S0().#^VOID_INT_INT_1^#) } do { func take(_: @escaping ()->(Int)->Int) {} take(S0.#^VOID_INT_INT_2^#) } // VOID_INT_INT-DAG: Decl{{.*}}/TypeRelation[Identical]: returnsIntToInt[#() -> (Int) -> Int#]; // VOID_INT_INT-DAG: Decl{{.*}}/TypeRelation[Invalid]: intToVoid({#a: Int#})[#Void#]; // VOID_INT_INT-DAG: Decl{{.*}}/TypeRelation[Invalid]: anyToVoid({#a: Any#})[#Void#]; // VOID_INT_INT-DAG: Decl{{.*}}/TypeRelation[Invalid]: voidToVoid()[#Void#]; // VOID_INT_INT-DAG: Decl{{.*}}: voidToAny()[#Any#]; // VOID_INT_INT-DAG: Decl{{.*}}: intToAny({#a: Int#})[#Any#]; // VOID_INT_INT-DAG: Decl{{.*}}: anyToAny({#a: Any#})[#Any#]; // VOID_INT_INT-DAG: Decl{{.*}}: voidToInt()[#Int#]; // VOID_INT_INT-DAG: Decl{{.*}}: anyToInt({#a: Any#})[#Int#]; // VOID_INT_INT-DAG: Decl{{.*}}: intToInt({#a: Int#})[#Int#];
apache-2.0
cc19ce3fd7932b87714339d8bfe1bcaf
47.615023
148
0.627233
3.252198
false
true
false
false
146BC/StyleKit
StyleKit/Stylist.swift
1
7577
import Foundation class Stylist { typealias Style = [String:AnyObject] typealias setValueForControlState = @convention(c) (AnyObject, Selector, AnyObject, UInt) -> Void let data: Style let aliases: Style let styleParser: StyleParsable var currentComponent: AnyClass? var viewStack = [UIAppearanceContainer.Type]() init(data: Style, styleParser: StyleParsable?) { self.styleParser = styleParser ?? StyleParser() var tmpAlias = Style() var tmpData = Style() for (key, value) in data { if key.hasPrefix("@") { tmpAlias[key] = value } else { tmpData[key] = value } } self.data = tmpData self.aliases = tmpAlias } func apply() { SKTryCatch.try( { self.validateAndApply(self.data) }, catch: { exception in SKLogger.severe("There was an error while applying styles: \(exception.debugDescription)") }, finallyBlock: nil) } private func validateAndApply(_ data: Style) { for (key, value) in data { if let value = value as? Style , NSClassFromString(key) != nil { if selectCurrentComponent(key), let appearanceContainer = self.currentComponent! as? UIAppearanceContainer.Type { viewStack.append(appearanceContainer) } validateAndApply(value) _ = viewStack.popLast() if viewStack.count > 0 { self.currentComponent = viewStack.last } } else { SKTryCatch.try( { if let currentComponent = self.currentComponent { self.applyStyle(key, object: value, currentComponent: currentComponent) } else { SKLogger.error("Style \(value) not applied on \(key) for \(self.currentComponent.debugDescription)") } }, catch: { exception in SKLogger.error("Style \(value) not applied on \(key) for \(self.currentComponent.debugDescription) Error \(exception.debugDescription)") }, finallyBlock: nil) } } } private func selectCurrentComponent(_ name: String) -> Bool { SKLogger.debug("Switching to: \(name)") guard let currentComponent = NSClassFromString(name) else { SKLogger.debug("Component \(name) cannot be selected") return false } self.currentComponent = currentComponent return true } private func applyStyle(_ name: String, object: AnyObject, currentComponent: AnyClass) { var selectorName = name let nameState = name.components(separatedBy: ":") var state: AnyObject? if nameState.count == 2 { selectorName = "\(nameState.first!):forState" state = ControlStateHelper.parseControlState(nameState.last!) as AnyObject? } else { state = nil } SKLogger.debug("Applying: \(selectorName) on level \(self.viewStack.count)") if let styles = object as? Stylist.Style { var stylesToApply = Stylist.Style() for (style, value) in styles { stylesToApply[style] = styleParser.getStyle(forName: name, value: self.getValue(value)) } callAppearanceSelector(selectorName, valueOne: stylesToApply as AnyObject?, valueTwo: state) } else { let value = styleParser.getStyle(forName: name, value: self.getValue(object)) callAppearanceSelector(selectorName, valueOne: value, valueTwo: state) } } /** Checks if the value is an alias, and if it is resolves to the correct value. Otherwise, it will return the passed value. - Parameter value: The alias name or actual value */ private func getValue(_ value: AnyObject) -> AnyObject { guard let stringValue = value as? String, stringValue.hasPrefix("@") else { return value } if let aliasValue = aliases[stringValue] { return aliasValue } else { SKLogger.error("Value declared is using Alias \(value) which has not been defined") return value } } private func callAppearanceSelector(_ selector: String, valueOne: AnyObject?, valueTwo: AnyObject?) { let modifiedSelector = "set\(selector.capitalizeFirstLetter()):" var viewStack = self.viewStack _ = viewStack.popLast() let isViewStackRelevant = viewStack.count > 0 viewStack = viewStack.reversed() if valueOne == nil && valueTwo == nil { if isViewStackRelevant { if #available(iOS 9.0, *) { _ = (self.currentComponent!.appearance(whenContainedInInstancesOf: viewStack) as! NSObject).perform(Selector(modifiedSelector)) } else { _ = (self.currentComponent!.styleKitAppearanceWhenContained(within: viewStack) as! NSObject).perform(Selector(modifiedSelector)) } } else { _ = (self.currentComponent!.appearance() as! NSObject).perform(Selector(modifiedSelector)) } } else if valueOne != nil && valueTwo != nil { if isViewStackRelevant { if #available(iOS 9.0, *) { let methodSignature = (self.currentComponent!.appearance(whenContainedInInstancesOf: viewStack) as! NSObject).method(for: Selector(modifiedSelector)) let callback = unsafeBitCast(methodSignature, to: setValueForControlState.self) callback(self.currentComponent!.appearance(whenContainedInInstancesOf: viewStack), Selector(modifiedSelector), valueOne!, valueTwo as! UInt) } else { let methodSignature = (self.currentComponent!.styleKitAppearanceWhenContained(within: viewStack) as! NSObject).method(for: Selector(modifiedSelector)) let callback = unsafeBitCast(methodSignature, to: setValueForControlState.self) callback(self.currentComponent!.styleKitAppearanceWhenContained(within: viewStack), Selector(modifiedSelector), valueOne!, valueTwo as! UInt) } } else { let methodSignature = (self.currentComponent!.appearance() as! NSObject).method(for: Selector(modifiedSelector)) let callback = unsafeBitCast(methodSignature, to: setValueForControlState.self) callback(self.currentComponent!.appearance(), Selector(modifiedSelector), valueOne!, valueTwo as! UInt) } } else if valueOne != nil { if isViewStackRelevant { if #available(iOS 9.0, *) { _ = (self.currentComponent!.appearance(whenContainedInInstancesOf: viewStack) as! NSObject).perform(Selector(modifiedSelector), with: valueOne!) } else { _ = self.currentComponent!.styleKitAppearanceWhenContained(within: viewStack).perform(Selector(modifiedSelector), with: valueOne!) } } else { _ = (self.currentComponent!.appearance() as! NSObject).perform(Selector(modifiedSelector), with: valueOne!) } } } }
mit
c72dd64ff90a1f667eee7a237b82b49c
42.797688
170
0.586512
5.126522
false
false
false
false
zisko/swift
stdlib/public/SDK/ObjectiveC/ObjectiveC.swift
2
6460
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import ObjectiveC import _SwiftObjectiveCOverlayShims //===----------------------------------------------------------------------===// // Objective-C Primitive Types //===----------------------------------------------------------------------===// /// The Objective-C BOOL type. /// /// On 64-bit iOS, the Objective-C BOOL type is a typedef of C/C++ /// bool. Elsewhere, it is "signed char". The Clang importer imports it as /// ObjCBool. @_fixed_layout public struct ObjCBool : ExpressibleByBooleanLiteral { #if os(macOS) || (os(iOS) && (arch(i386) || arch(arm))) // On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char". var _value: Int8 init(_ value: Int8) { self._value = value } public init(_ value: Bool) { self._value = value ? 1 : 0 } #else // Everywhere else it is C/C++'s "Bool" var _value: Bool public init(_ value: Bool) { self._value = value } #endif /// The value of `self`, expressed as a `Bool`. public var boolValue: Bool { #if os(macOS) || (os(iOS) && (arch(i386) || arch(arm))) return _value != 0 #else return _value #endif } /// Create an instance initialized to `value`. @_transparent public init(booleanLiteral value: Bool) { self.init(value) } } extension ObjCBool : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: boolValue) } } extension ObjCBool : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self.boolValue.description } } // Functions used to implicitly bridge ObjCBool types to Swift's Bool type. public // COMPILER_INTRINSIC func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool { return ObjCBool(x) } public // COMPILER_INTRINSIC func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool { return x.boolValue } /// The Objective-C SEL type. /// /// The Objective-C SEL type is typically an opaque pointer. Swift /// treats it as a distinct struct type, with operations to /// convert between C strings and selectors. /// /// The compiler has special knowledge of this type. @_fixed_layout public struct Selector : ExpressibleByStringLiteral { var ptr: OpaquePointer /// Create a selector from a string. public init(_ str : String) { ptr = str.withCString { sel_registerName($0).ptr } } // FIXME: Fast-path this in the compiler, so we don't end up with // the sel_registerName call at compile time. /// Create an instance initialized to `value`. public init(stringLiteral value: String) { self = sel_registerName(value) } } public func ==(lhs: Selector, rhs: Selector) -> Bool { return sel_isEqual(lhs, rhs) } extension Selector : Equatable, Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// - Note: the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. public var hashValue: Int { return ptr.hashValue } } extension Selector : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return String(_sel: self) } } extension String { /// Construct the C string representation of an Objective-C selector. public init(_sel: Selector) { // FIXME: This misses the ASCII optimization. self = String(cString: sel_getName(_sel)) } } extension Selector : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: String(_sel: self)) } } //===----------------------------------------------------------------------===// // NSZone //===----------------------------------------------------------------------===// @_fixed_layout public struct NSZone { var pointer: OpaquePointer } // Note: NSZone becomes Zone in Swift 3. typealias Zone = NSZone //===----------------------------------------------------------------------===// // @autoreleasepool substitute //===----------------------------------------------------------------------===// public func autoreleasepool<Result>( invoking body: () throws -> Result ) rethrows -> Result { let pool = _swift_objc_autoreleasePoolPush() defer { _swift_objc_autoreleasePoolPop(pool) } return try body() } //===----------------------------------------------------------------------===// // Mark YES and NO unavailable. //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Use 'Bool' value 'true' instead") public var YES: ObjCBool { fatalError("can't retrieve unavailable property") } @available(*, unavailable, message: "Use 'Bool' value 'false' instead") public var NO: ObjCBool { fatalError("can't retrieve unavailable property") } //===----------------------------------------------------------------------===// // NSObject //===----------------------------------------------------------------------===// // NSObject implements Equatable's == as -[NSObject isEqual:] // NSObject implements Hashable's hashValue() as -[NSObject hash] // FIXME: what about NSObjectProtocol? extension NSObject : Equatable, Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// - Note: the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. @objc open var hashValue: Int { return hash } } public func == (lhs: NSObject, rhs: NSObject) -> Bool { return lhs.isEqual(rhs) } extension NSObject : CVarArg { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs public var _cVarArgEncoding: [Int] { _autorelease(self) return _encodeBitsAsWords(self) } }
apache-2.0
ebe041279b51f4769d2259e4ee10aa0e
27.45815
80
0.583746
4.558927
false
false
false
false
migueloruiz/la-gas-app-swift
lasgasmx/HomeViewController.swift
1
8818
// // ViewController.swift // lasgasmx // // Created by Desarrollo on 3/21/17. // Copyright © 2017 migueloruiz. All rights reserved. // import UIKit import GoogleMaps import GoogleMobileAds class HomeViewController: UIViewController { let gasPriceDatasorce = GasPricesDatasorce() var gasPricesController : GasPricesCarrouselController? = nil var stationsMap: GasStationsMapController? = nil var adsManeger: AdModManager? = nil var adsView: GADBannerView? = nil let pager = UICustomePager() lazy var gasPricesCarrousell: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.showsHorizontalScrollIndicator = false cv.backgroundColor = .clear cv.isPagingEnabled = true return cv }() lazy var centerButton: UIMapControlButton = { let cb = UIMapControlButton(withTarget: self, action: #selector(HomeViewController.tapOnCenterUserButton), radius: 20, type: .navigation) cb.imageEdgeInsets = UIEdgeInsetsMake(10, 4, 7, 7) return cb }() lazy var refreshButton: UIMapControlButton = { let cb = UIMapControlButton(withTarget: self, action: #selector(HomeViewController.refreshMap), radius: 20, type: .refresh) cb.imageEdgeInsets = UIEdgeInsetsMake(6, 7, 6, 6) return cb }() lazy var closeInfoButton: UIButton = { let b = UIButton() b.addTarget(self, action: #selector(HomeViewController.closeInfo), for: .touchUpInside) b.backgroundColor = .clear b.tintColor = .black b.setImage( #imageLiteral(resourceName: "down-arrow").withRenderingMode(.alwaysTemplate), for: .normal) b.imageView?.contentMode = .scaleAspectFit b.alpha = 0 return b }() var mapView: GMSMapView = { let view = GMSMapView() return view }() lazy var infoView: InfoView = { let iv = InfoView(root: self) iv.alpha = 0 return iv }() init() { super.init(nibName: nil, bundle: nil) } init( adsManager: AdModManager) { super.init(nibName: nil, bundle: nil) self.adsManeger = adsManager } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white stationsMap = GasStationsMapController(map: mapView) stationsMap?.delegate = self gasPricesController = GasPricesCarrouselController(collectionView: gasPricesCarrousell, datasorce: gasPriceDatasorce) gasPricesController?.delegate = self gasPriceDatasorce.fetchStroage() setupSubViews() setAds() } override func viewWillAppear(_ animated: Bool) { setupNavigationBar() gasPriceDatasorce.updateCarrousell() stationsMap?.askForUserLocation() pager.numberOfPages = (gasPriceDatasorce.objects != nil) ? gasPriceDatasorce.objects!.count : 1 } func setupNavigationBar() { guard let nav = self.navigationController else { return } nav.isNavigationBarHidden = true UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: true) } func setupSubViews() { pager.numberOfPages = (gasPriceDatasorce.objects != nil) ? gasPriceDatasorce.objects!.count : 1 view.addSubview(mapView) view.addSubview(infoView) view.addSubview(gasPricesCarrousell) view.addSubview(pager) view.addSubview(centerButton) view.addSubview(refreshButton) view.addSubview(closeInfoButton) pager.anchorCenterXToSuperview() pager.anchor(top: gasPricesCarrousell.bottomAnchor, left: gasPricesCarrousell.leftAnchor, bottom: nil, right: gasPricesCarrousell.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 20) gasPricesCarrousell.anchor(top: topLayoutGuide.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 10, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 70) infoView.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) infoView.anchorCenterXToSuperview() mapView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: infoView.topAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) centerButton.anchor(top: nil, left: nil, bottom: infoView .topAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 60, rightConstant: 5, widthConstant: 40, heightConstant: 40) refreshButton.anchor(top: nil, left: nil, bottom: centerButton.topAnchor, right: centerButton.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 10, rightConstant: 0, widthConstant: 40, heightConstant: 40) closeInfoButton.anchor(top: self.view.topAnchor, left: self.view.leftAnchor, bottom: nil, right: nil, topConstant: 25, leftConstant: 15, bottomConstant: 0, rightConstant: 0, widthConstant: 20, heightConstant: 20) } func setAds() { guard let ad = adsManeger else { return } adsView = ad.getBanner(with: "3431553183") adsView?.rootViewController = self let request = ad.getTestRequest() adsView?.load(request) view.addSubview(adsView!) adsView?.anchor(top: nil, left: nil, bottom: mapView.bottomAnchor, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 320, heightConstant: 50) adsView?.anchorCenterXToSuperview() } func tapOnCenterUserButton() { stationsMap?.setCameraInUserPosition() } func refreshMap() { stationsMap?.updateUserLocation() } func closeInfo() { animateInfoView(with: nil) stationsMap?.setLastCameraPosition() } func animateInfoView(with station: GasStation?) { let isNil = (station == nil) self.infoView.gasStation = station self.infoView.layoutIfNeeded() for contrain in self.infoView.constraints { if contrain.identifier == "height" { self.infoView.removeConstraint(contrain) } } let heigth = (station == nil) ? 0 : self.infoView.estimatedHeight let newConstrain = self.infoView.heightAnchor.constraint(equalToConstant: heigth) newConstrain.isActive = true newConstrain.identifier = "height" UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.curveEaseInOut, animations: { self.gasPricesCarrousell.alpha = isNil ? 1 : 0 self.pager.alpha = isNil ? 1 : 0 self.centerButton.alpha = isNil ? 1 : 0 self.refreshButton.alpha = isNil ? 1 : 0 self.closeInfoButton.alpha = isNil ? 0 : 1 self.infoView.alpha = isNil ? 0 : 1 if let ad = self.adsView { ad.alpha = isNil ? 1 : 0 } self.infoView.layoutIfNeeded() self.view.layoutIfNeeded() }) } } extension HomeViewController: GasPricesCarrouselDelegate { func datasourseWasUpdated() { guard let items = gasPriceDatasorce.objects else { return } pager.numberOfPages = items.count } internal func updateCounter(counter: Int) { guard let items = gasPriceDatasorce.objects else { pager.numberOfPages = 1 pager.currentPage = 1 return } pager.numberOfPages = items.count pager.currentPage = counter } internal func gasCellSelected(price: GasPriceInState) { guard let nav = self.navigationController else { return } nav.pushViewController(CalculatorViewController(gasPrice: price), animated: true) } internal func gasEmptyCellSelected() { guard let nav = self.navigationController else { return } nav.pushViewController(NewLocationViewController(), animated: true) } } extension HomeViewController: GasStationsMapDelegate { func gasStation(tappedStation: GasStation?) { animateInfoView(with: tappedStation) } }
mit
3b6688851db731f5a09da40101feb40e
37.168831
258
0.655552
4.660148
false
false
false
false
roelspruit/RSMetronome
Sources/RSMetronome/NoteValue.swift
1
1581
// // NoteValue.swift // // Created by Roel Spruit on 03/12/15. // Copyright © 2015 DinkyWonder. All rights reserved. // import Foundation public enum NoteValue: Int { case ThirtySecond = 32 case Sixteenth = 16 case Eight = 8 case Quarter = 4 case Half = 2 case Whole = 1 func numberOfNotesInNote(note: NoteValue) -> Int{ return self.rawValue / note.rawValue } func timeIntervalWithTempo(tempo: Int, tempoNote: NoteValue) -> UInt64 { let secondsBetweenBeats = 60.0 / Double(tempo) let secondsForNote = secondsBetweenBeats / Double(numberOfNotesInNote(note: tempoNote)) return TimeBase.toAbs(nanos: secondsForNote * Double(TimeBase.NANOS_PER_SEC)) } } private class TimeBase { static let NANOS_PER_USEC: UInt64 = 1000 static let NANOS_PER_MILLISEC: UInt64 = 1000 * NANOS_PER_USEC static let NANOS_PER_SEC: UInt64 = 1000 * NANOS_PER_MILLISEC static var timebaseInfo: mach_timebase_info! = { var tb = mach_timebase_info(numer: 0, denom: 0) let status = mach_timebase_info(&tb) if status == KERN_SUCCESS { return tb } else { return nil } }() static func toNanos(abs: UInt64) -> UInt64 { return (abs * UInt64(timebaseInfo.numer)) / UInt64(timebaseInfo.denom) } static func toAbs(nanos: Double) -> UInt64 { let absoluteTime = (nanos * Double(timebaseInfo.denom)) / Double(timebaseInfo.numer) return UInt64(absoluteTime) } }
mit
023abe20b8b002743346435e6eaf491f
28.259259
95
0.622152
3.632184
false
false
false
false
solinor/paymenthighway-ios-framework
PaymentHighway/SecureSigner.swift
1
1491
// // SecureSigner.swift // PaymentHighway // // Copyright © 2018 Payment Highway Oy. All rights reserved. // import Foundation import CryptoSwift public class SecureSigner { let signatureScheme = "SPH1" let signatureKeyId: String let signatureSecret: String public init(signatureKeyId: String, signatureSecret: String) { self.signatureKeyId = signatureKeyId self.signatureSecret = signatureSecret } public func createSignature(method: String, uri: String, keyValues: [(String, String)], body: String) -> String { return "\(self.signatureScheme) \(self.signatureKeyId) \(self.sign(method: method, uri: uri, keyValues: keyValues, body: body))" } public func sign(method: String, uri: String, keyValues: [(String, String)], body: String) -> String { let stringToSign = "\(method)\n\(uri)\n\(createKeyValueString(keyValues: keyValues))\n\(body.trimmingCharacters(in: .whitespacesAndNewlines))" // swiftlint:disable force_try let hmac = try! HMAC(key: signatureSecret, variant: HMAC.Variant.sha256).authenticate(Array(stringToSign.utf8)) return Data(bytes: hmac).toHexString() } public func createKeyValueString(keyValues: [(String, String)]) -> String { return keyValues .filter { $0.0.lowercased().hasPrefix("sph-") } .sorted { $0.0 < $1.0 } .map { "\($0.0.lowercased()):\($0.1)" } .joined(separator: "\n") } }
mit
d35b16ea7dff07d17bf957d4b5f5d9aa
37.205128
150
0.649664
4.150418
false
false
false
false
cmoulton/grokSwiftREST_v1.2
grokSwiftREST/File.swift
1
1172
// // File.swift // grokSwiftREST // // Created by Christina Moulton on 2016-04-18. // Copyright © 2016 Teak Mobile Inc. All rights reserved. // import Foundation import SwiftyJSON class File: NSObject, NSCoding, ResponseJSONObjectSerializable { var filename: String? var raw_url: String? var content: String? required init?(json: JSON) { self.filename = json["filename"].string self.raw_url = json["raw_url"].string } init?(aName: String?, aContent: String?) { self.filename = aName self.content = aContent } // MARK: NSCoding @objc func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.filename, forKey: "filename") aCoder.encodeObject(self.raw_url, forKey: "raw_url") aCoder.encodeObject(self.content, forKey: "content") } @objc required convenience init?(coder aDecoder: NSCoder) { let filename = aDecoder.decodeObjectForKey("filename") as? String let content = aDecoder.decodeObjectForKey("content") as? String // use the existing init function self.init(aName: filename, aContent: content) self.raw_url = aDecoder.decodeObjectForKey("raw_url") as? String } }
mit
68116fede84eea85823a730b81ceac56
26.880952
69
0.694278
3.916388
false
false
false
false
marselan/patient-records
Patient-Records/Patient-Records/PatientsViewController.swift
1
2619
// // PatientsViewController.swift // Patient-Records // // Created by Mariano Arselan on 15/5/17. // Copyright © 2017 Mariano Arselan. All rights reserved. // import UIKit class PatientsViewController : UIViewController, UITableViewDelegate, UITableViewDataSource { var patients : [Patient] = [] var tempPatients : [Patient] = [] var simpleTableId = "SimplePatientTableId" @IBOutlet var patientsView : UITableView! override func viewDidLoad() { super.viewDidLoad() patientsView.delegate = self patientsView.dataSource = self self.title = "Patients" loadPatients() } func loadPatients() { let url = URL(string: "\(Config.instance.backendUrl)/PatientManager/PatientService/patients") var request = URLRequest(url: url!) request.setValue(Config.instance.user, forHTTPHeaderField: "user") request.setValue(Config.instance.user, forHTTPHeaderField: "password") let session = URLSession.shared let dataTask = session.dataTask(with: request, completionHandler: patientsReceived) dataTask.resume() } func patientsReceived(_ data : Data?, _ response : URLResponse?, _ error : Error?) { guard error == nil else { return } if let json = data { do { self.tempPatients = try JSONDecoder().decode([Patient].self, from: json) DispatchQueue.main.async(execute: patientsLoaded) } catch { return } } } func patientsLoaded() { self.patients = self.tempPatients patientsView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return patients.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = patientsView.dequeueReusableCell(withIdentifier: simpleTableId) let patient = patients[indexPath.row] cell!.textLabel?.text = patient.name return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let patient = patients[indexPath.row] let storyboard = UIStoryboard(name: "RecordsStoryboard", bundle: nil) let recordsViewController = storyboard.instantiateViewController(withIdentifier: "Records") as! RecordsViewController recordsViewController.patient = patient self.navigationController?.pushViewController(recordsViewController, animated: true) } }
gpl-3.0
08f367df33db2e486e61495ac5c5028c
33
125
0.65317
4.8125
false
false
false
false
sora0077/AppleMusicKit
Sources/Response/AnyResource.swift
1
3143
// // AnyResource.swift // AppleMusicKit // // Created by 林 達也 on 2017/07/05. // Copyright © 2017年 jp.sora0077. All rights reserved. // import Foundation public enum Track<Song: SongDecodable, MusicVideo: MusicVideoDecodable, R: Decodable>: Decodable { case song(Resource<Song, R>), musicVideo(Resource<MusicVideo, R>) private enum CodingKeys: String, CodingKey { case type } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) switch try c.decode(ResourceType.self, forKey: .type) { case .songs: self = .song(try Resource(from: decoder)) case .musicVideos: self = .musicVideo(try Resource(from: decoder)) default: throw DecodingError.dataCorrupted(.init(codingPath: c.codingPath, debugDescription: "\(#function)@\(#line)")) } } } public enum AnyResource< Song: SongDecodable, Album: AlbumDecodable, Artist: ArtistDecodable, MusicVideo: MusicVideoDecodable, Playlist: PlaylistDecodable, Curator: CuratorDecodable, AppleCurator: AppleCuratorDecodable, Activity: ActivityDecodable, Station: StationDecodable, Storefront: StorefrontDecodable, Genre: GenreDecodable, Recommendation: RecommendationDecodable, Relationships: Decodable >: Decodable { case song(Resource<Song, Relationships>) case album(Resource<Album, Relationships>) case artist(Resource<Artist, Relationships>) case musicVideo(Resource<MusicVideo, Relationships>) case playlist(Resource<Playlist, Relationships>) case curator(Resource<Curator, Relationships>) case appleCurator(Resource<AppleCurator, Relationships>) case activities(Resource<Activity, Relationships>) case station(Resource<Station, Relationships>) case storefront(Resource<Storefront, Relationships>) case genre(Resource<Genre, Relationships>) case recommendation(Resource<Recommendation, Relationships>) private enum CodingKeys: String, CodingKey { case type } public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) switch try c.decode(ResourceType.self, forKey: .type) { case .songs: self = .song(try Resource(from: decoder)) case .albums: self = .album(try Resource(from: decoder)) case .artists: self = .artist(try Resource(from: decoder)) case .musicVideos: self = .musicVideo(try Resource(from: decoder)) case .playlists: self = .playlist(try Resource(from: decoder)) case .curators: self = .curator(try Resource(from: decoder)) case .appleCurators: self = .appleCurator(try Resource(from: decoder)) case .activities: self = .activities(try Resource(from: decoder)) case .stations: self = .station(try Resource(from: decoder)) case .storefronts: self = .storefront(try Resource(from: decoder)) case .genres: self = .genre(try Resource(from: decoder)) case .personalRecommendation: self = .recommendation(try Resource(from: decoder)) } } }
mit
f993edb62923924d0d524669412053af
38.175
121
0.691449
4.346741
false
false
false
false
Snail93/iOSDemos
SnailSwiftDemos/Pods/EZSwiftExtensions/Sources/EZSwiftFunctions.swift
2
12216
// // EZSwiftFunctions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 13/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // //TODO: others standart video, gif import Foundation public struct ez { /// EZSE: Returns app's name public static var appDisplayName: String? { if let bundleDisplayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String { return bundleDisplayName } else if let bundleName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String { return bundleName } return nil } /// EZSE: Returns app's version number public static var appVersion: String? { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String } /// EZSE: Return app's build number public static var appBuild: String? { return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String } /// EZSE: Return app's bundle ID public static var appBundleID: String? { return Bundle.main.bundleIdentifier } /// EZSE: Returns both app's version and build numbers "v0.3(7)" public static var appVersionAndBuild: String? { if appVersion != nil && appBuild != nil { if appVersion == appBuild { return "v\(appVersion!)" } else { return "v\(appVersion!)(\(appBuild!))" } } return nil } /// EZSE: Return device version "" public static var deviceVersion: String { var size: Int = 0 sysctlbyname("hw.machine", nil, &size, nil, 0) var machine = [CChar](repeating: 0, count: Int(size)) sysctlbyname("hw.machine", &machine, &size, nil, 0) return String(cString: machine) } /// EZSE: Returns true if DEBUG mode is active //TODO: Add to readme public static var isDebug: Bool { #if DEBUG return true #else return false #endif } /// EZSE: Returns true if RELEASE mode is active //TODO: Add to readme public static var isRelease: Bool { #if DEBUG return false #else return true #endif } /// EZSE: Returns true if its simulator and not a device //TODO: Add to readme public static var isSimulator: Bool { #if (arch(i386) || arch(x86_64)) && os(iOS) return true #else return false #endif } /// EZSE: Returns true if its on a device and not a simulator //TODO: Add to readme public static var isDevice: Bool { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif } #if !os(macOS) /// EZSE: Returns true if app is running in test flight mode /// Acquired from : http://stackoverflow.com/questions/12431994/detect-testflight public static var isInTestFlight: Bool { return Bundle.main.appStoreReceiptURL?.path.contains("sandboxReceipt") == true } #endif #if os(iOS) || os(tvOS) /// EZSE: Returns the top ViewController public static var topMostVC: UIViewController? { let topVC = UIApplication.topViewController() if topVC == nil { print("EZSwiftExtensions Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.") } return topVC } #if os(iOS) /// EZSE: Returns current screen orientation public static var screenOrientation: UIInterfaceOrientation { return UIApplication.shared.statusBarOrientation } #endif /// EZSwiftExtensions public static var horizontalSizeClass: UIUserInterfaceSizeClass { return self.topMostVC?.traitCollection.horizontalSizeClass ?? UIUserInterfaceSizeClass.unspecified } /// EZSwiftExtensions public static var verticalSizeClass: UIUserInterfaceSizeClass { return self.topMostVC?.traitCollection.verticalSizeClass ?? UIUserInterfaceSizeClass.unspecified } #endif #if os(iOS) || os(tvOS) /// EZSE: Returns screen width public static var screenWidth: CGFloat { #if os(iOS) if UIInterfaceOrientationIsPortrait(screenOrientation) { return UIScreen.main.bounds.size.width } else { return UIScreen.main.bounds.size.height } #elseif os(tvOS) return UIScreen.main.bounds.size.width #endif } /// EZSE: Returns screen height public static var screenHeight: CGFloat { #if os(iOS) if UIInterfaceOrientationIsPortrait(screenOrientation) { return UIScreen.main.bounds.size.height } else { return UIScreen.main.bounds.size.width } #elseif os(tvOS) return UIScreen.main.bounds.size.height #endif } #endif #if os(iOS) /// EZSE: Returns StatusBar height public static var screenStatusBarHeight: CGFloat { return UIApplication.shared.statusBarFrame.height } /// EZSE: Return screen's height without StatusBar public static var screenHeightWithoutStatusBar: CGFloat { if UIInterfaceOrientationIsPortrait(screenOrientation) { return UIScreen.main.bounds.size.height - screenStatusBarHeight } else { return UIScreen.main.bounds.size.width - screenStatusBarHeight } } #endif /// EZSE: Returns the locale country code. An example value might be "ES". //TODO: Add to readme public static var currentRegion: String? { return (Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode) as? String } #if os(iOS) || os(tvOS) /// EZSE: Calls action when a screen shot is taken public static func detectScreenShot(_ action: @escaping () -> Void) { let mainQueue = OperationQueue.main NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil, queue: mainQueue) { notification in // executes after screenshot action() } } #endif //TODO: Document this, add tests to this /// EZSE: Iterates through enum elements, use with (for element in ez.iterateEnum(myEnum)) /// http://stackoverflow.com/questions/24007461/how-to-enumerate-an-enum-with-string-type public static func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> { var i = 0 return AnyIterator { let next = withUnsafePointer(to: &i) { $0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } } if next.hashValue != i { return nil } i += 1 return next } } // MARK: - Dispatch /// EZSE: Runs the function after x seconds public static func dispatchDelay(_ second: Double, closure:@escaping () -> Void) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(second * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } /// EZSE: Runs function after x seconds public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) { runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after) } //TODO: Make this easier /// EZSE: Runs function after x seconds with dispatch_queue, use this syntax: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0) public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) { let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: time, execute: after) } /// EZSE: Submits a block for asynchronous execution on the main queue public static func runThisInMainThread(_ block: @escaping () -> Void) { DispatchQueue.main.async(execute: block) } /// EZSE: Runs in Default priority queue public static func runThisInBackground(_ block: @escaping () -> Void) { DispatchQueue.global(qos: .default).async(execute: block) } /// EZSE: Runs every second, to cancel use: timer.invalidate() @discardableResult public static func runThisEvery(seconds: TimeInterval, startAfterSeconds: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> Timer { let fireDate = startAfterSeconds + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, seconds, 0, 0, handler) CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes) return timer! } /// EZSE: Gobal main queue @available(*, deprecated: 1.7, renamed: "DispatchQueue.main") public var globalMainQueue: DispatchQueue { return DispatchQueue.main } /// EZSE: Gobal queue with user interactive priority @available(*, deprecated: 1.7, renamed: "DispatchQueue.main") public var globalUserInteractiveQueue: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } /// EZSE: Gobal queue with user initiated priority @available(*, deprecated: 1.7, renamed: "DispatchQueue.global()") public var globalUserInitiatedQueue: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } /// EZSE: Gobal queue with utility priority @available(*, deprecated: 1.7, renamed: "DispatchQueue.global()") public var globalUtilityQueue: DispatchQueue { return DispatchQueue.global(qos: .utility) } /// EZSE: Gobal queue with background priority @available(*, deprecated: 1.7, renamed: "DispatchQueue.global()") public var globalBackgroundQueue: DispatchQueue { return DispatchQueue.global(qos: .background) } /// EZSE: Gobal queue with default priority @available(*, deprecated: 1.7, renamed: "DispatchQueue.global()") public var globalQueue: DispatchQueue { return DispatchQueue.global(qos: .default) } // MARK: - DownloadTask #if os(iOS) || os(tvOS) /// EZSE: Downloads image from url string public static func requestImage(_ url: String, success: @escaping (UIImage?) -> Void) { requestURL(url, success: { (data) -> Void in if let d = data { success(UIImage(data: d)) } }) } #endif /// EZSE: Downloads JSON from url string public static func requestJSON(_ url: String, success: @escaping ((Any?) -> Void), error: ((NSError) -> Void)?) { requestURL(url, success: { (data) -> Void in let json = self.dataToJsonDict(data) success(json) }, error: { (err) -> Void in if let e = error { e(err) } }) } /// EZSE: converts NSData to JSON dictionary fileprivate static func dataToJsonDict(_ data: Data?) -> Any? { if let d = data { var error: NSError? let json: Any? do { json = try JSONSerialization.jsonObject( with: d, options: JSONSerialization.ReadingOptions.allowFragments) } catch let error1 as NSError { error = error1 json = nil } if let _ = error { return nil } else { return json } } else { return nil } } /// EZSE: fileprivate static func requestURL(_ url: String, success: @escaping (Data?) -> Void, error: ((NSError) -> Void)? = nil) { guard let requestURL = URL(string: url) else { assertionFailure("EZSwiftExtensions Error: Invalid URL") return } URLSession.shared.dataTask( with: URLRequest(url: requestURL), completionHandler: { data, response, err in if let e = err { error?(e as NSError) } else { success(data) } }).resume() } }
apache-2.0
412f9acbf7c055a0512036e9fcde9040
31.927224
167
0.62017
4.764431
false
false
false
false
noor1122/AudioQuran
AudioQuran/AudioQuran/UtilityConstants.swift
1
1542
// // UtilityConstants.swift // AudioQuran // // Created by Noor on 26/06/2015. // Copyright (c) 2015 Noor. All rights reserved. // import UIKit class UtilityConstants: NSObject { enum UIUserInterfaceIdiom : Int { case Unspecified case Phone case Pad } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width static let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_6 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6P = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0 } // image constants let TAB_BAR_BACKGROUND_IMG = "Mosque" let QURAN_IMG = "Quran" let MOON_STARS_IMG = "Moon" // height and width let TAB_BAR_HEIGHT = 100 let TAB_BAR_WIDTH_IPHONE_5 = 320 let TAB_BAR_WIDTH_IPHONE_6 = 375 let TAB_BAR_WIDTH_IPHONE_6P = 414 }
mit
34aa74b5d00c7f9d731940cc913763ef
31.808511
135
0.661479
3.943734
false
false
false
false
aschwaighofer/swift
test/ScanDependencies/Inputs/ModuleDependencyGraph.swift
1
4539
//===--------------- ModuleDependencyGraph.swift --------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation enum ModuleDependencyId: Hashable { case swift(String) case clang(String) var moduleName: String { switch self { case .swift(let name): return name case .clang(let name): return name } } } extension ModuleDependencyId: Codable { enum CodingKeys: CodingKey { case swift case clang } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { let moduleName = try container.decode(String.self, forKey: .swift) self = .swift(moduleName) } catch { let moduleName = try container.decode(String.self, forKey: .clang) self = .clang(moduleName) } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .swift(let moduleName): try container.encode(moduleName, forKey: .swift) case .clang(let moduleName): try container.encode(moduleName, forKey: .clang) } } } /// Bridging header struct BridgingHeader: Codable { var path: String var sourceFiles: [String] var moduleDependencies: [String] } /// Details specific to Swift modules. struct SwiftModuleDetails: Codable { /// The module interface from which this module was built, if any. var moduleInterfacePath: String? /// The bridging header, if any. var bridgingHeader: BridgingHeader? } /// Details specific to Clang modules. struct ClangModuleDetails: Codable { /// The path to the module map used to build this module. var moduleMapPath: String /// The context hash used to discriminate this module file. var contextHash: String /// The Clang command line arguments that need to be passed through /// to the -emit-pcm action to build this module. var commandLine: [String] = [] } struct ModuleDependencies: Codable { /// The path for the module. var modulePath: String /// The source files used to build this module. var sourceFiles: [String] = [] /// The set of direct module dependencies of this module. var directDependencies: [ModuleDependencyId] = [] /// Specific details of a particular kind of module. var details: Details /// Specific details of a particular kind of module. enum Details { /// Swift modules may be built from a module interface, and may have /// a bridging header. case swift(SwiftModuleDetails) /// Clang modules are built from a module map file. case clang(ClangModuleDetails) } } extension ModuleDependencies.Details: Codable { enum CodingKeys: CodingKey { case swift case clang } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { let details = try container.decode(SwiftModuleDetails.self, forKey: .swift) self = .swift(details) } catch { let details = try container.decode(ClangModuleDetails.self, forKey: .clang) self = .clang(details) } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .swift(let details): try container.encode(details, forKey: .swift) case .clang(let details): try container.encode(details, forKey: .clang) } } } /// Describes the complete set of dependencies for a Swift module, including /// all of the Swift and C modules and source files it depends on. struct ModuleDependencyGraph: Codable { /// The name of the main module. var mainModuleName: String /// The complete set of modules discovered var modules: [ModuleDependencyId: ModuleDependencies] = [:] /// Information about the main module. var mainModule: ModuleDependencies { modules[.swift(mainModuleName)]! } } let fileName = CommandLine.arguments[1] let data = try! Data(contentsOf: URL(fileURLWithPath: fileName)) let decoder = JSONDecoder() let moduleDependencyGraph = try! decoder.decode( ModuleDependencyGraph.self, from: data) print(moduleDependencyGraph)
apache-2.0
ab93944d737ee28e244456e643fc4231
28.474026
81
0.685173
4.402522
false
false
false
false
TwoRingSoft/shared-utils
Sources/PippinLibrary/Foundation/Bool/Tribool.swift
1
4286
// // Tribool.swift // Pippin // // Created by Andrew McKnight on 10/31/16. // Copyright © 2017 andrew mcknight. All rights reserved. // /** See https://en.wikipedia.org/wiki/Three-valued_logic for an introduction to three valued logic. The truth table for the implemented logic functions follows: ``` Kleene Łukasiewicz | p q | ¬p | ¬q | p ∧ q | p v q | p → q | p → q | ------------------------------------------------- | - - | + | + | - | - | + | + | | - 0 | + | 0 | - | 0 | + | + | | - + | + | - | - | + | + | + | | 0 - | 0 | + | - | 0 | 0 | 0 | | 0 0 | 0 | 0 | 0 | 0 | 0 | + | | 0 + | 0 | - | 0 | + | + | + | | + - | - | + | - | + | - | - | | + 0 | - | 0 | 0 | + | 0 | 0 | | + + | - | - | + | + | + | + | ------------------------------------------------- ``` */ public typealias Tribool = Bool? enum Implication { case Kleene case Łukasiewicz } /** Constants specifying the numeric values of the three possible logical states. Based on assigned values from "balanced ternary logic": -1 for false, 0 for unknown, and +1 for true, or simply -, 0 and +. - note: These constants are represented as `_false` = -1, `_undecided` = 0 and `_true` = 1 to reduce the logical operations conjunction, disjunction, negation and the kleene and lukasiewicz implications to simple primitive operations. */ public enum TriboolValue: Int { /// The ternary logical value for "yes" or "true", defined in balanced ternary logic as +1. case _true = 1 /// The ternary logical value for "unknown", "unknowable/undecidable", "irrelevant", or "both", defined in balanced ternary logic as 0. case _undecided = 0 /// The ternary logical value for "no" or "false", defined in balanced ternary logic as -1. case _false = -1 init(tribool: Tribool) { if tribool == nil { self = ._undecided } else { self = TriboolValue(bool: tribool!) } } init(bool: Bool) { self = bool ? ._true : ._false } func tribool() -> Tribool { switch self { case ._false: return false case ._true: return true case ._undecided: return nil } } /// - returns: `false` if either `_false` or `_undecided`, `true` otherwise func negativelyBiasedBoolean() -> Bool { if self == ._true { return true } return false } /// - returns: `true` if either `_true` or `_undecided`, `false` otherwise func positivelyBiasedBoolean() -> Bool { if self == ._false { return false } return true } } // MARK: Logical OR public func ||(lhs: Tribool, rhs: Tribool) -> Tribool { let a = TriboolValue(tribool: lhs).rawValue let b = TriboolValue(tribool: rhs).rawValue let result = max(a, b) return TriboolValue(rawValue: result)!.tribool() } // MARK: Logical AND public func &&(lhs: Tribool, rhs: Tribool) -> Tribool { let a = TriboolValue(tribool: lhs).rawValue let b = TriboolValue(tribool: rhs).rawValue let result = min(a, b) return TriboolValue(rawValue: result)!.tribool() } // MARK: Logical NOT public prefix func !(receiver: Tribool) -> Tribool { let val = TriboolValue(tribool: receiver).rawValue return TriboolValue(rawValue: val * -1)!.tribool() } // MARK: Implication infix operator →* infix operator →→ /// Kleene implication public func →*(lhs: Tribool, rhs: Tribool) -> Tribool { return imply(lhs: lhs, rhs: rhs, type: .Kleene) } /// Łukasiewicz implication public func →→(lhs: Tribool, rhs: Tribool) -> Tribool { return imply(lhs: lhs, rhs: rhs, type: .Łukasiewicz) } func imply(lhs: Tribool, rhs: Tribool, type: Implication) -> Tribool { let a = TriboolValue(tribool: lhs).rawValue let b = TriboolValue(tribool: rhs).rawValue var result: Int switch type { case .Kleene: result = max(-1 * a, b) case .Łukasiewicz: result = min(1, 1 - a + b) } return TriboolValue(rawValue: result)!.tribool() }
mit
ed37cbdb90b35d53f546fb76c6975b18
28.37931
235
0.541549
3.215094
false
false
false
false
bingoogolapple/SwiftNote-PartOne
TableViewController/TableViewController/CityViewController.swift
1
1112
// // CityViewController.swift // TableViewController // // Created by bingoogol on 14-6-21. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class CityViewController:UITableViewController { var cities:NSArray! override func viewDidLoad() { super.viewDidLoad() } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return cities.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cellIdentifier = "myCity" var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier:cellIdentifier) } cell?.textLabel.text = cities[indexPath.row] as String return cell } override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { } }
apache-2.0
72468313f91adce7935dfd18484b0aa4
28.236842
121
0.676577
5.441176
false
false
false
false
natecook1000/swift
stdlib/public/SDK/CoreFoundation/CoreFoundation.swift
26
881
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import CoreFoundation public protocol _CFObject: class, Hashable {} extension _CFObject { public var hashValue: Int { return Int(bitPattern: CFHash(self)) } public func hash(into hasher: inout Hasher) { hasher.combine(self.hashValue) } public static func ==(left: Self, right: Self) -> Bool { return CFEqual(left, right) } }
apache-2.0
af5e99629bdb1836cd739d2097c79c53
32.884615
80
0.585698
4.736559
false
false
false
false
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/MenuViewController/MenuView/MenuView.swift
2
10214
// // MenuView.swift // WikiRaces // // Created by Andrew Finke on 2/23/19. // Copyright © 2019 Andrew Finke. All rights reserved. // import UIKit import StoreKit import WKRUIKit final class MenuView: UIView { // MARK: Types enum InterfaceState { case joinOrCreate, noOptions, joinOptions, plusOptions, noInterface } enum ListenerUpdate { case presentDebug, presentLeaderboard case presentJoinPublicRace, presentJoinPrivateRace case presentCreateRace case presentAlert(UIAlertController) case presentStats, presentSubscription } // MARK: - Closures var listenerUpdate: ((ListenerUpdate) -> Void)? // MARK: - Properties /// Used to track if the menu should be animating var state = InterfaceState.noInterface // MARK: - Interface Elements /// The top of the menu (everything on white). Animates out of the left side. let topView = UIView() /// The bottom of the menu (everything not white). Animates out of the bottom. let bottomView = UIView() /// The "WikiRaces" label let titleLabel = UILabel() /// The "Conquer..." label let subtitleLabel = UILabel() let joinButton = WKRUIButton() let createButton = WKRUIButton() let publicButton = WKRUIButton() let privateButton = WKRUIButton() let backButton = UIButton() let plusButton = UIButton() let statsButton = WKRUIButton() /// The Wiki Points tile var leftMenuTile: MenuTile? /// The average points tile var middleMenuTile: MenuTile? /// The races tile var rightMenuTile: MenuTile? /// The puzzle piece view let movingPuzzleView = MovingPuzzleView() /// The easter egg medal view let medalView = MedalView() // MARK: - Constraints /// Used to animate the top view in and out var topViewLeftConstraint: NSLayoutConstraint! /// Used to animate the bottom view in and out var bottomViewAnchorConstraint: NSLayoutConstraint! /// Used for safe area layout adjustments var bottomViewHeightConstraint: NSLayoutConstraint! var puzzleViewHeightConstraint: NSLayoutConstraint! /// Used for adjusting y coord of title label based on screen height var titleLabelConstraint: NSLayoutConstraint! /// Used for adjusting button widths and heights based on screen width var joinButtonLeftConstraint: NSLayoutConstraint! var joinButtonWidthConstraint: NSLayoutConstraint! var joinButtonHeightConstraint: NSLayoutConstraint! var createButtonWidthConstraint: NSLayoutConstraint! var publicButtonWidthConstraint: NSLayoutConstraint! var privateButtonLeftConstraint: NSLayoutConstraint! var privateButtonWidthConstraint: NSLayoutConstraint! var backButtonLeftConstraintForJoinOptions: NSLayoutConstraint! var backButtonLeftConstraintForStats: NSLayoutConstraint! var backButtonWidth: NSLayoutConstraint! var statsButtonLeftConstraint: NSLayoutConstraint! var statsButtonWidthConstraint: NSLayoutConstraint! // MARK: - View Life Cycle init() { super.init(frame: .zero) let recognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognizerFired)) recognizer.numberOfTapsRequired = 2 recognizer.numberOfTouchesRequired = 2 titleLabel.addGestureRecognizer(recognizer) titleLabel.isUserInteractionEnabled = true topView.translatesAutoresizingMaskIntoConstraints = false addSubview(topView) bottomView.translatesAutoresizingMaskIntoConstraints = false addSubview(bottomView) topViewLeftConstraint = topView.leftAnchor.constraint(equalTo: leftAnchor) bottomViewAnchorConstraint = bottomView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 250) bottomViewHeightConstraint = bottomView.heightAnchor.constraint(equalToConstant: 250) setupTopView() setupBottomView() let constraints = [ topView.topAnchor.constraint(equalTo: topAnchor), topView.bottomAnchor.constraint(equalTo: bottomView.topAnchor), topView.widthAnchor.constraint(equalTo: widthAnchor), bottomView.leftAnchor.constraint(equalTo: leftAnchor), bottomView.widthAnchor.constraint(equalTo: widthAnchor), bottomViewHeightConstraint!, topViewLeftConstraint!, bottomViewAnchorConstraint! ] NSLayoutConstraint.activate(constraints) } @objc func tapGestureRecognizerFired() { listenerUpdate?(.presentDebug) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func safeAreaInsetsDidChange() { super.safeAreaInsetsDidChange() puzzleViewHeightConstraint.constant = 75 + safeAreaInsets.bottom / 2 bottomViewHeightConstraint.constant = 250 + safeAreaInsets.bottom / 2 } override func layoutSubviews() { super.layoutSubviews() titleLabel.text = "WikiRaces" bottomView.backgroundColor = .wkrMenuBottomViewColor(for: traitCollection) let textColor: UIColor = .wkrTextColor(for: traitCollection) titleLabel.textColor = textColor subtitleLabel.textColor = textColor backButton.tintColor = textColor backButton.layer.borderColor = textColor.cgColor backButton.layer.borderWidth = 1.7 plusButton.tintColor = backButton.tintColor plusButton.layer.borderColor = backButton.layer.borderColor plusButton.layer.borderWidth = backButton.layer.borderWidth // Button Styles let buttonStyle: WKRUIButtonStyle let buttonWidth: CGFloat let buttonHeight: CGFloat if frame.size.width > 420 { buttonStyle = .large buttonWidth = 150 buttonHeight = 50 } else { buttonStyle = .normal buttonWidth = 100 buttonHeight = 40 } if frame.size.width < UIScreen.main.bounds.width / 1.8 { leftMenuTile?.title = "WIKI\nPOINTS" middleMenuTile?.title = "AVG PER\nRACE" rightMenuTile?.title = "RACES\nPLAYED" } else { leftMenuTile?.title = "WIKI POINTS" middleMenuTile?.title = "AVG PER RACE" rightMenuTile?.title = "RACES PLAYED" } joinButton.style = buttonStyle createButton.style = buttonStyle publicButton.style = buttonStyle privateButton.style = buttonStyle statsButton.style = buttonStyle // Label Fonts titleLabel.font = UIFont.systemFont(ofSize: min(frame.size.width / 10.0, 55), weight: .semibold) subtitleLabel.font = UIFont.systemFont(ofSize: min(frame.size.width / 18.0, 30), weight: .medium) // Constraints if UIDevice.current.userInterfaceIdiom == .pad { titleLabelConstraint.constant = frame.size.height / 8 } else { titleLabelConstraint.constant = frame.size.height / 11 } switch state { case .joinOrCreate: joinButtonLeftConstraint.constant = 30 privateButtonLeftConstraint.constant = -privateButton.frame.width * 2 statsButtonLeftConstraint.constant = -statsButton.frame.width topViewLeftConstraint.constant = 0 bottomViewAnchorConstraint.constant = 0 if frame.size.height < 650 { bottomViewAnchorConstraint.constant = 75 } case .noOptions: joinButtonLeftConstraint.constant = -createButton.frame.width privateButtonLeftConstraint.constant = -privateButton.frame.width statsButtonLeftConstraint.constant = -statsButton.frame.width case .joinOptions: joinButtonLeftConstraint.constant = -createButton.frame.width privateButtonLeftConstraint.constant = 30 backButtonLeftConstraintForStats.isActive = false backButtonLeftConstraintForJoinOptions.isActive = true case .noInterface: topViewLeftConstraint.constant = -topView.frame.width bottomViewAnchorConstraint.constant = bottomView.frame.height joinButtonLeftConstraint.constant = 30 privateButtonLeftConstraint.constant = 30 case .plusOptions: joinButtonLeftConstraint.constant = -createButton.frame.width statsButtonLeftConstraint.constant = 30 backButtonLeftConstraintForJoinOptions.isActive = false backButtonLeftConstraintForStats.isActive = true } joinButtonHeightConstraint.constant = buttonHeight joinButtonWidthConstraint.constant = buttonWidth + 10 createButtonWidthConstraint.constant = buttonWidth + 40 publicButtonWidthConstraint.constant = buttonWidth + 34 privateButtonWidthConstraint.constant = buttonWidth + 44 statsButtonWidthConstraint.constant = buttonWidth + 20 backButtonWidth.constant = buttonHeight - 10 backButton.layer.cornerRadius = backButtonWidth.constant / 2 plusButton.layer.cornerRadius = backButton.layer.cornerRadius } func promptGlobalRacesPopularity() -> Bool { guard !Defaults.promptedGlobalRacesPopularity else { return false } Defaults.promptedGlobalRacesPopularity = true let message = "Most racers use private races to play with friends. Create a private race and invite a friend for the best chance at joining a race. You can also start a solo race at any time." let alertController = UIAlertController(title: "Public Races", message: message, preferredStyle: .alert) let action = UIAlertAction(title: "Find Public Race", style: .default, handler: { _ in PlayerFirebaseAnalytics.log(event: .userAction("promptGlobalRacesPopularity:ok")) self.animateMenuOut { self.listenerUpdate?(.presentJoinPublicRace) } }) alertController.addAction(action) listenerUpdate?(.presentAlert(alertController)) return true } }
mit
1c184a7a8ed0c052114a309ea6c2d4a2
34.461806
200
0.685303
5.532503
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Browser/Punycode.swift
1
6015
/* 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 private let base = 36 private let tMin = 1 private let tMax = 26 private let initialBias = 72 private let initialN: Int = 128 // 0x80 private let delimiter: Character = "-"; // '\x2D' private let prefixPunycode = "xn--" private let asciiPunycode = [Character]("abcdefghijklmnopqrstuvwxyz0123456789".characters) extension String { private func toValue(index: Int) -> Character { return asciiPunycode[index] } private func toIndex(value: Character) -> Int { return asciiPunycode.indexOf(value)! } private func adapt(delta: Int, numPoints: Int, firstTime: Bool) -> Int { let skew = 38 let damp = firstTime ? 700 : 2 var delta = delta delta = delta / damp delta += delta / numPoints var k = 0 while (delta > ((base - tMin) * tMax) / 2) { delta /= (base - tMin) k += base } return k + ((base - tMin + 1) * delta) / (delta + skew) } private func encode(input: String) -> String { var output = "" var d: Int = 0 var extendedChars = [Int]() for c in input.unicodeScalars { if Int(c.value) < initialN { d += 1 output.append(c) } else { extendedChars.append(Int(c.value)) } } if extendedChars.count == 0 { return output } if d > 0 { output.append(delimiter) } var n = initialN var delta = 0 var bias = initialBias var h: Int = 0 var b: Int = 0 if d > 0 { h = output.unicodeScalars.count - 1 b = output.unicodeScalars.count - 1 } else { h = output.unicodeScalars.count b = output.unicodeScalars.count } while h < input.unicodeScalars.count { var char = Int(0x7fffffff) for c in input.unicodeScalars { let ci = Int(c.value) if char > ci && ci >= n { char = ci } } delta = delta + (char - n) * (h + 1) if delta < 0 { print("error: invalid char:") output = "" return output } n = char for c in input.unicodeScalars { let ci = Int(c.value) if ci < n || ci < initialN { delta += 1 continue } if ci > n { continue } var q = delta var k = base while true { let t = max(min(k - bias, tMax), tMin) if q < t { break } let code = t + ((q - t) % (base - t)) output.append(toValue(code)) q = (q - t) / (base - t) k += base } output.append(toValue(q)) bias = self.adapt(delta, numPoints: h + 1, firstTime: h == b) delta = 0 h += 1 } delta += 1 n += 1 } return output } private func decode(punycode: String) -> String { var input = [Character](punycode.characters) var output = [Character]() var i = 0 var n = initialN var bias = initialBias var pos = 0 if let ipos = input.indexOf(delimiter) { pos = ipos output.appendContentsOf(input[0 ..< pos]) pos += 1 } var outputLength = output.count let inputLength = input.count while pos < inputLength { let oldi = i var w = 1 var k = base while true { let digit = toIndex(input[pos]) pos += 1 i += digit * w let t = max(min(k - bias, tMax), tMin) if digit < t { break } w = w * (base - t) k += base } outputLength += 1 bias = adapt(i - oldi, numPoints: outputLength, firstTime: (oldi == 0)) n = n + i / outputLength i = i % outputLength output.insert(Character(UnicodeScalar(n)), atIndex: i) i += 1 } return String(output) } private func isValidUnicodeScala(s: String) -> Bool { for c in s.unicodeScalars { let ci = Int(c.value) if ci >= initialN { return false } } return true } private func isValidPunycodeScala(s: String) -> Bool { return s.hasPrefix(prefixPunycode) } public func utf8HostToAscii() -> String { if isValidUnicodeScala(self) { return self } var labels = self.componentsSeparatedByString(".") for (i, part) in labels.enumerate() { if !isValidUnicodeScala(part) { let a = encode(part) labels[i] = prefixPunycode + a } } let resultString = labels.joinWithSeparator(".") return resultString } public func asciiHostToUTF8() -> String { var labels = self.componentsSeparatedByString(".") for (index, part) in labels.enumerate() { if isValidPunycodeScala(part) { let changeStr = part.substringFromIndex(part.startIndex.advancedBy(4)) labels[index] = decode(changeStr) } } let resultString = labels.joinWithSeparator(".") return resultString } }
mpl-2.0
acad63a4d4d0e753f582470d2bb64bd0
29.378788
90
0.467664
4.641204
false
false
false
false
MengQuietly/MQDouYuTV
MQDouYuTV/MQDouYuTV/Classes/Home/View/MQAmuseTopMenuCell.swift
1
1843
// // MQAmuseTopMenuCell.swift // MQDouYuTV // // Created by mengmeng on 17/1/17. // Copyright © 2017年 mengQuietly. All rights reserved. // import UIKit private let kAmuseTopMenuWithGameCellID = "kAmuseTopMenuWithGameCellID" class MQAmuseTopMenuCell: UICollectionViewCell { var anchorGroupModelList: [MQAnchorGroupModel]? { didSet { amuseTopMenuCollection.reloadData() } } @IBOutlet weak var amuseTopMenuCollection: UICollectionView! override func awakeFromNib() { super.awakeFromNib() amuseTopMenuCollection.register(UINib(nibName: "MQRecommendGameCell", bundle: nil), forCellWithReuseIdentifier: kAmuseTopMenuWithGameCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = amuseTopMenuCollection.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 let itemW:CGFloat = self.bounds.width / 4 let itemH:CGFloat = self.bounds.height / 2 layout.scrollDirection = .vertical layout.itemSize = CGSize(width: itemW, height: itemH) } } extension MQAmuseTopMenuCell: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return anchorGroupModelList?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kAmuseTopMenuWithGameCellID, for: indexPath) as! MQRecommendGameCell cell.clipsToBounds = true // cell 不展示 BottomLine cell.baseGameModel = anchorGroupModelList![indexPath.item] return cell } }
mit
5a09118e9e7a11a6526f28005a4e2bab
34.269231
148
0.713195
4.997275
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/Aztec/Renderers/SpecialTagAttachmentRenderer.swift
1
2987
import Foundation import UIKit import Aztec // MARK: - SpecialTagAttachmentRenderer. This render aims rendering WordPress specific tags. // final class SpecialTagAttachmentRenderer { /// Text Color /// var textColor = UIColor.gray } // MARK: - TextViewCommentsDelegate Methods // extension SpecialTagAttachmentRenderer: TextViewAttachmentImageProvider { func textView(_ textView: TextView, shouldRender attachment: NSTextAttachment) -> Bool { guard let commentAttachment = attachment as? CommentAttachment else { return false } return Tags.supported.contains(commentAttachment.text) } func textView(_ textView: TextView, imageFor attachment: NSTextAttachment, with size: CGSize) -> UIImage? { guard let attachment = attachment as? CommentAttachment else { return nil } UIGraphicsBeginImageContextWithOptions(size, false, 0) let label = attachment.text.uppercased() let attributes = [NSForegroundColorAttributeName: textColor] let colorMessage = NSAttributedString(string: label, attributes: attributes) let textRect = colorMessage.boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) let textPosition = CGPoint(x: ((size.width - textRect.width) * 0.5), y: ((size.height - textRect.height) * 0.5)) colorMessage.draw(in: CGRect(origin: textPosition, size: CGSize(width: size.width, height: textRect.size.height))) let path = UIBezierPath() let dashes = [ Constants.defaultDashCount, Constants.defaultDashCount ] path.setLineDash(dashes, count: dashes.count, phase: 0.0) path.lineWidth = Constants.defaultDashWidth let centerY = round(size.height * 0.5) path.move(to: CGPoint(x: 0, y: centerY)) path.addLine(to: CGPoint(x: ((size.width - textRect.width) * 0.5) - Constants.defaultDashWidth, y: centerY)) path.move(to: CGPoint(x: ((size.width + textRect.width) * 0.5) + Constants.defaultDashWidth, y: centerY)) path.addLine(to: CGPoint(x: size.width, y: centerY)) textColor.setStroke() path.stroke() let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } func textView(_ textView: TextView, boundsFor attachment: NSTextAttachment, with lineFragment: CGRect) -> CGRect { let padding = textView.textContainer.lineFragmentPadding let width = lineFragment.width - padding * 2 return CGRect(origin: .zero, size: CGSize(width: width, height: Constants.defaultHeight)) } } // MARK: - Constants // extension SpecialTagAttachmentRenderer { struct Constants { static let defaultDashCount = CGFloat(8.0) static let defaultDashWidth = CGFloat(2.0) static let defaultHeight = CGFloat(44.0) } struct Tags { static let supported = ["more", "nextpage"] } }
gpl-2.0
d010f22f244b90cbbbe757f9d1e0d271
33.333333
128
0.683964
4.623839
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Kendra/Kendra_Error.swift
1
3064
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for Kendra public struct KendraErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case conflictException = "ConflictException" case internalServerException = "InternalServerException" case resourceAlreadyExistException = "ResourceAlreadyExistException" case resourceInUseException = "ResourceInUseException" case resourceNotFoundException = "ResourceNotFoundException" case resourceUnavailableException = "ResourceUnavailableException" case serviceQuotaExceededException = "ServiceQuotaExceededException" case throttlingException = "ThrottlingException" case validationException = "ValidationException" } private let error: Code public let context: AWSErrorContext? /// initialize Kendra public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } public static var accessDeniedException: Self { .init(.accessDeniedException) } public static var conflictException: Self { .init(.conflictException) } public static var internalServerException: Self { .init(.internalServerException) } public static var resourceAlreadyExistException: Self { .init(.resourceAlreadyExistException) } public static var resourceInUseException: Self { .init(.resourceInUseException) } public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } public static var resourceUnavailableException: Self { .init(.resourceUnavailableException) } public static var serviceQuotaExceededException: Self { .init(.serviceQuotaExceededException) } public static var throttlingException: Self { .init(.throttlingException) } public static var validationException: Self { .init(.validationException) } } extension KendraErrorType: Equatable { public static func == (lhs: KendraErrorType, rhs: KendraErrorType) -> Bool { lhs.error == rhs.error } } extension KendraErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
2b871d09db514326ea31c896d387b0a6
40.405405
117
0.692559
5.246575
false
false
false
false
SmallElephant/FEAlgorithm-Swift
5-Tree/5-Tree/TreeUtil.swift
1
2029
// // TreeUtil.swift // 5-Tree // // Created by FlyElephant on 16/12/12. // Copyright © 2016年 FlyElephant. All rights reserved. // import Foundation class TreeUtil { var rootIndex:Int = -1 var rootList:String = "" func createBinaryTree(data:[String]) -> TreeNode? { if data.count == 0 { return nil } var nodeList:[TreeNode?] = [] var rootNode:TreeNode? for i in 0..<data.count { let node:TreeNode? = TreeNode(data: data[i],leftChild: nil,rightChild: nil) if i == 0 { rootNode = node } nodeList.append(node) } for index in 0..<data.count/2 { let node:TreeNode? = nodeList[index] node?.leftChild = nodeList[index*2+1] node?.rightChild = nodeList[(index+1)*2] } return rootNode } //二叉树创建 func createTreeByPreOrder(root:inout TreeNode?) -> Void { rootIndex = rootIndex+1 if rootIndex >= rootList.characters.count { return } let data = rootList[rootIndex] as String if data != "#" { root = TreeNode() root?.data = data createTreeByPreOrder(root: &root!.leftChild) createTreeByPreOrder(root: &root!.rightChild) } else { root = nil } } func createTreeByPreOrderData(root:inout TreeNode?,listData:[String]) { rootIndex = rootIndex+1 if rootIndex >= listData.count { return } let data = listData[rootIndex] as String if data != "#" { root = TreeNode() root?.data = data createTreeByPreOrderData(root: &root!.leftChild,listData: listData) createTreeByPreOrderData(root: &root!.rightChild,listData: listData) } else { root = nil } } }
mit
21ae3edbac38a752e91177231c8b2e5f
24.518987
88
0.509425
4.430769
false
false
false
false
eliasbloemendaal/KITEGURU
KITEGURU/KITEGURU/SignInViewController.swift
1
5033
// // SignInViewController.swift // KITEGURU // // Created by Elias Houttuijn Bloemendaal on 13-01-16. // Copyright © 2016 Elias Houttuijn Bloemendaal. All rights reserved. // import UIKit class SignInViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var userName: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var errorLabel: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var activityLabel: UILabel! @IBOutlet weak var SettingButton: UIButton! @IBOutlet weak var SignUpButton: UIButton! @IBOutlet weak var FreeWeatherButton: UIButton! @IBOutlet weak var logInButton: UIButton! override func viewDidLoad() { super.viewDidLoad() SettingButton.hidden = false // delegate variables userName.delegate = self password.delegate = self self.activityIndicator.hidden = true self.navigationController?.navigationBar.hidden = true self.SettingButton.hidden = true // http://stackoverflow.com/questions/26614395/swift-background-image-does-not-fit-showing-small-part-of-the-all-image let backgroundImage = UIImageView(frame: UIScreen.mainScreen().bounds) backgroundImage.image = UIImage(named: "kiteBackOne") backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill self.view.insertSubview(backgroundImage, atIndex: 0) // https://teamtreehouse.com/community/how-do-i-make-a-rounded-button-with-a-border-in-swift SignUpButton.layer.cornerRadius = 10 FreeWeatherButton.layer.cornerRadius = 10 logInButton.layer.cornerRadius = 10 } // Als de loginbutton aangetikt word, gaan een een antaal functies zich afspelen @IBAction func logInButton(sender: AnyObject) { // check if the fields are empty if SignIn.hasEmptyFields(userName.text!, password: password.text!) { self.errorLabel.text = Error.incorrectSignIn.description return } self.activityIndicator.hidden = false activityIndicator.startAnimating() errorLabel.text = "Logging In Now..." // https://github.com/kevincaughman/Resume-App/blob/master/Resume/SignInViewController.swift // extra button's worden disabled, textfield worden leeg gemaakt dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { SignIn.loginUserAsync(self.userName.text!, password: self.password.text!, completion: { (success: Bool) -> Void in //update UI if success { self.SignUpButton.enabled = false self.FreeWeatherButton.enabled = false dispatch_async(dispatch_get_main_queue()) { ParseModel.delay(seconds: 2, completion: { print("Login successful") self.errorLabel.text = "Login Successful" ParseModel.delay(seconds: 1.5, completion: { self.performSegueWithIdentifier("jaap", sender: nil) self.activityIndicator.stopAnimating() self.activityIndicator.hidden = true self.userName.text = "" self.password.text = "" self.errorLabel.text = "" self.SignUpButton.enabled = true self.FreeWeatherButton.enabled = true }) }) } } else { dispatch_async(dispatch_get_main_queue()) { self.activityIndicator.stopAnimating() self.userName.resignFirstResponder() self.activityLabel.text = "" self.errorLabel.text = Error.incorrectSignIn.description } } }) } } // free weather button zal de error weer clearen @IBAction func FreeWeatherButton(sender: AnyObject) { self.errorLabel.text = "" } // Segue als free weather predictionsbutton word aangeraakt @IBAction func freeWeatherpredicitonButton(sender: AnyObject) { performSegueWithIdentifier("freeWeatherSignIn", sender: nil) } // Als de user klaar is met het keyboard verdwijnt als er buiten het keyboard word gedrukt override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } }
mit
7c69ff339c14228527ec0c48ead80a25
40.933333
126
0.568362
5.313622
false
false
false
false
huangboju/Moots
Examples/UIScrollViewDemo/UIScrollViewDemo/Controllers/Sku/Views/SKUCellModel.swift
1
7009
// // SKUCellModel.swift // UIScrollViewDemo // // Created by 黄渊 on 2022/10/28. // Copyright © 2022 伯驹 黄. All rights reserved. // import Foundation class SKUSectionModel { let title: String let items: [SKUItemCellModel] init(section: Int, variants: Variants, stateMap: [Variant: VariantState]) { title = variants.name items = variants.values .map { Variant(id: variants.id, name: variants.name, value: $0) } .enumerated() .map { SKUItemCellModel(variant: $1, state: stateMap[$1] ?? VariantState(), indexPath: IndexPath(row: $0, section: section)) } } } class SKUCellModel: SKUCellModelPresenter { let cellHeight: CGFloat let sections: [SKUSectionModel] var selectedGoods: SkuGoods? private var selectedItemSet: Set<SKUItemCellModel> = [] // 后端计算好的sku组合goods let goodsMap: [Set<Variant>: SkuGoods] let allItems: [SKUItemCellModel] // 选中的规格数据要等于规格分类数才是有效的选择 var isValid: Bool { selectedItemSet.count == sections.count } init(_ allVariant: GoodsAllVariant = GoodsAllVariant(), selectedGoods: SkuGoods? = nil) { self.selectedGoods = selectedGoods let stateMap: [Variant: VariantState] (stateMap, goodsMap) = Self.initMap(allVariant) sections = allVariant.variants.enumerated().map { SKUSectionModel(section: $0, variants: $1, stateMap: stateMap) } allItems = sections.flatMap { $0.items } cellHeight = Self.countCellHeight(sections) // 注意需要先设置状态,updateHighlightItem中canSelected依赖status setDefaultStatus() updateHighlightItem() } static func initMap(_ allVariant: GoodsAllVariant) -> ([Variant: VariantState], [Set<Variant>: SkuGoods]) { // 找出所有匹配规格中,状态rawValue最小的,用于规格的默认status // 找出是活动的规格 var dict: [Variant: VariantState] = [:] var skuMap: [Set<Variant>: SkuGoods] = [:] for goods in allVariant.goodsList { for variant in goods.variants { if let state = dict[variant] { state.goodsMap[goods.variantSet] = goods } else { let state = VariantState(with: goods) dict[variant] = state } skuMap[goods.variantSet] = goods } } return (dict, skuMap) } func updateHighlightItem() { guard let selctedGoods = selectedGoods else { return } for item in allItems { guard item.canSelected, selctedGoods.variantSet.contains(item.variant) else { continue } item.isSelected = true add(item: item) } } func didSelectItem(at indexPath: IndexPath) { let item = item(at: indexPath) if item.isSelected { item.isSelected = false remove(item: item) } else { removeItem(at: indexPath) item.isSelected = true add(item: item) } } func item(at indexPath: IndexPath) -> SKUItemCellModel { section(at: indexPath).items[indexPath.row] } func section(at indexPath: IndexPath) -> SKUSectionModel { sections[indexPath.section] } func removeItem(at indexPath: IndexPath) { for item in sections[indexPath.section].items where item.isSelected { item.isSelected = false remove(item: item) } } func add(item: SKUItemCellModel) { selectedItemSet.insert(item) updateItemStatus(with: item) } func remove(item: SKUItemCellModel) { selectedItemSet.remove(item) updateItemStatus(with: item) } func updateItemStatus(with item: SKUItemCellModel) { setSelectedGoodsIfNeeded() setSelectedStatus(with: item) } func setDefaultStatus() { for item in allItems { item.setStatus(with: item.state.optimalStatus, isActivity: item.state.optimalActivity) } } func setSelectedStatus(with changedItem: SKUItemCellModel) { if selectedItemSet.isEmpty { setDefaultStatus() return } let selectedItemSets = selectedItemSets() for item in allItems where changedItem.indexPath.section != item.indexPath.section { let result = selectedItemSets[item.indexPath.section] var tuple: (SKUItemStatus, Bool) = (.unfound, false) for (key, value) in item.state.goodsMap where result.0.isSubset(of: key) { let new = VariantState.status(with: value.status) tuple.0 = new.rawValue < tuple.0.rawValue ? new : tuple.0 tuple.1 = item.state.optimalActivity && result.1 } item.setStatus(with: tuple.0, isActivity: tuple.1) } } func setSelectedGoodsIfNeeded() { guard isValid, let goods = goodsMap[Set(selectedItemSet.map { $0.variant })] else { return } selectedGoods = goods } func selectedItemSets() -> [(Set<Variant>, Bool)] { var result: [(Set<Variant>, Bool)] = Array(repeating: (Set<Variant>(), false), count: sections.count) for section in 0 ..< result.count { var tuple: (Set<Variant>, Bool) = ([], true) for item in selectedItemSet where item.indexPath.section != section { tuple.0.insert(item.variant) tuple.1 = tuple.1 && item.state.optimalActivity } result[section] = tuple } return result } } extension SKUCellModel { static func countCellHeight(_ sections: [SKUSectionModel]) -> CGFloat { if sections.isEmpty { return 0 } // header 30, footer 20, minSpacing 12 * (rowCount - 1), cell 28 * rowCount var height: CGFloat = 0 let maxWidth = UIScreen.main.bounds.width - 16 * 2 let stringInset: CGFloat = 12 let cellSpacing: CGFloat = 12 let cellLineSpacing: CGFloat = 12 let cellHeight: CGFloat = 28 let sectionHeaderHeight: CGFloat = 30 let sectionFooterHeight: CGFloat = 20 for section in sections { var rowCount: CGFloat = 1 var curWidth: CGFloat = 0 for item in section.items { let stringWidth = item.cellSize.width if (stringWidth + curWidth) > maxWidth { rowCount += 1 curWidth = 0 } curWidth += stringWidth + stringInset * 2 + cellSpacing } height += sectionHeaderHeight + sectionFooterHeight + rowCount * cellHeight + (rowCount - 1) * cellLineSpacing } return height } }
mit
c794083c41c3ad909e5f5bde016eccf7
31.464455
122
0.585109
4.427925
false
false
false
false
toshiapp/toshi-ios-client
Toshi/Models/Converters/BaseConverter.swift
1
5851
// Copyright (c) 2018 Token Browser, Inc // // 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/>. // Convert between strings in arbitrary base, ported from http://danvk.org/hex2dec.html struct BaseConverter { let base: Int // Adds two arrays for the given base (10 or 16) func add(_ x: [Int], y: [Int]) -> [Int] { var z: [Int] = [] let n = max(x.count, y.count) var carry = 0 var i = 0 while i < n || carry > 0 { let xi = (i < x.count ? x[i] : 0) let yi = (i < y.count ? y[i] : 0) let zi = carry + xi + yi z.append(zi % base) carry = zi / base i += 1 } return z } // Returns a * x, where x is an array of decimal digits and a is an ordinary // Int. The array should be in the base of the instance. func multiplyByNumber(_ num: Int, x: [Int]) -> [Int] { assert(num >= 0, "Positive numbers only") assert(num <= Int(Int32.max), "32 bit power max") var numU: UInt32 = UInt32(num) if numU == 0 { return [] } var result: [Int] = [] var power = x while true { if numU & 1 > 0 { result = add(result, y: power) } numU = numU >> 1 if numU == 0 { break } power = add(power, y: power) } return result } func parseToDigitsArray(_ str: String) -> [Int] { var digits: [String] = [] for char in str { digits.append(String(char)) } var ary: [Int] = [] if !digits.isEmpty { for i in (0 ... (digits.count - 1)).reversed() { guard let digit = stringToInt(digits[i]) else { assert(false, "Invalid digit") continue } ary.append(digit) } } return ary } static func convertBase(_ str: String, fromBase: Int, toBase: Int) -> String { let fromBaseConverter = self.init(base: fromBase) let toBaseConverter = self.init(base: toBase) let digits = fromBaseConverter.parseToDigitsArray(str) var outArray: [Int] = [] var power = [1] for digit in digits { // invariant: at this point, fromBase^i = power let digitsTimesPower: [Int] = toBaseConverter.multiplyByNumber(digit, x: power) outArray = toBaseConverter.add(outArray, y: digitsTimesPower) power = toBaseConverter.multiplyByNumber(fromBase, x: power) } if outArray.isEmpty { return "0" } var out: String = "" if !outArray.isEmpty { for i in (0 ... (outArray.count - 1)).reversed() { out += toBaseConverter.intToString(outArray[i]) } } return out } func stringToInt(_ digit: String) -> Int? { switch base { case 2, 3, 4, 5, 6, 7, 8, 9, 10: return Int(digit) case 16: switch digit { case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9": return Int(digit) case "A", "a": return 10 case "B", "b": return 11 case "C", "c": return 12 case "D", "d": return 13 case "E", "e": return 14 case "F", "f": return 15 default: assert(false, "Invalid hex digit") return nil } default: assert(false, "Only base 2-10 and 16 are supported") return nil } } func intToString(_ digit: Int) -> String { switch base { case 2, 3, 4, 5, 6, 7, 8, 9, 10: return digit.description case 16: switch digit { case 0 ... 9: return digit.description case 10: return "A" case 11: return "B" case 12: return "C" case 13: return "D" case 14: return "E" case 15: return "F" default: assert(false, "Invalid hex digit") return "" } case 58: // This is a bitcoin specific variant! let alphabet: [String] = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] return alphabet[digit] default: assert(false, "Only base 2-10, 16 and 58 are supported") return "" } } static func decToHex(_ decStr: String) -> String { return convertBase(decStr, fromBase: 10, toBase: 16) } static func hexToDec(_ hexStr: String) -> String { return convertBase(hexStr, fromBase: 16, toBase: 10) } }
gpl-3.0
2511d9fbc78e2fdf59a35c77ab91ae13
29.005128
327
0.473082
3.867151
false
false
false
false
Ryan-Korteway/GVSSS
GVBandwagon/Pods/KGFloatingDrawer/Pod/Classes/KGDrawerViewController.swift
1
8591
// // KGDrawerViewController.swift // KGDrawerViewController // // Created by Kyle Goddard on 2015-02-10. // Copyright (c) 2015 Kyle Goddard. All rights reserved. // import UIKit public enum KGDrawerSide: CGFloat { case none = 0 case left = 1 case right = -1 } open class KGDrawerViewController: UIViewController { let defaultDuration:TimeInterval = 0.3 // MARK: Initialization override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func loadView() { view = drawerView } fileprivate var _drawerView: KGDrawerView? var drawerView: KGDrawerView { get { if let retVal = _drawerView { return retVal } let rect = UIScreen.main.bounds let retVal = KGDrawerView(frame: rect) _drawerView = retVal return retVal } } // TODO: Add ability to supply custom animator. fileprivate var _animator: KGDrawerSpringAnimator? open var animator: KGDrawerSpringAnimator { get { if let retVal = _animator { return retVal } let retVal = KGDrawerSpringAnimator() _animator = retVal return retVal } } // MARK: Interaction open func openDrawer(_ side: KGDrawerSide, animated:Bool, complete: @escaping (_ finished: Bool) -> Void) { if currentlyOpenedSide != side { if let sideView = drawerView.viewContainerForDrawerSide(side) { let centerView = drawerView.centerViewContainer if currentlyOpenedSide != .none { closeDrawer(side, animated: animated) { finished in self.animator.openDrawer(side, drawerView: sideView, centerView: centerView, animated: animated, complete: complete) } } else { self.animator.openDrawer(side, drawerView: sideView, centerView: centerView, animated: animated, complete: complete) } addDrawerGestures() drawerView.willOpenDrawer(self) } } currentlyOpenedSide = side } open func closeDrawer(_ side: KGDrawerSide, animated: Bool, complete: @escaping (_ finished: Bool) -> Void) { if (currentlyOpenedSide == side && currentlyOpenedSide != .none) { if let sideView = drawerView.viewContainerForDrawerSide(side) { let centerView = drawerView.centerViewContainer animator.dismissDrawer(side, drawerView: sideView, centerView: centerView, animated: animated, complete: complete) currentlyOpenedSide = .none restoreGestures() drawerView.willCloseDrawer(self) } } } open func toggleDrawer(_ side: KGDrawerSide, animated: Bool, complete: @escaping (_ finished: Bool) -> Void) { if side != .none { if side == currentlyOpenedSide { closeDrawer(side, animated: animated, complete: complete) } else { openDrawer(side, animated: animated, complete: complete) } } } // MARK: Gestures func addDrawerGestures() { centerViewController?.view.isUserInteractionEnabled = false drawerView.centerViewContainer.addGestureRecognizer(toggleDrawerTapGestureRecognizer) } func restoreGestures() { drawerView.centerViewContainer.removeGestureRecognizer(toggleDrawerTapGestureRecognizer) centerViewController?.view.isUserInteractionEnabled = true } func centerViewContainerTapped(_ sender: AnyObject) { closeDrawer(currentlyOpenedSide, animated: true) { (finished) -> Void in // Do nothing } } // MARK: Helpers func viewContainer(_ side: KGDrawerSide) -> UIViewController? { switch side { case .left: return self.leftViewController case .right: return self.rightViewController case .none: return nil } } func replaceViewController(_ sourceViewController: UIViewController?, destinationViewController: UIViewController, container: UIView) { sourceViewController?.willMove(toParentViewController: nil) sourceViewController?.view.removeFromSuperview() sourceViewController?.removeFromParentViewController() self.addChildViewController(destinationViewController) container.addSubview(destinationViewController.view) let destinationView = destinationViewController.view destinationView?.translatesAutoresizingMaskIntoConstraints = false container.removeConstraints(container.constraints) let views: [String:UIView] = ["v1" : destinationView!] container.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v1]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) container.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v1]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) destinationViewController.didMove(toParentViewController: self) } // MARK: Private computed properties open var currentlyOpenedSide: KGDrawerSide = .none // MARK: Accessors fileprivate var _leftViewController: UIViewController? open var leftViewController: UIViewController? { get { return _leftViewController } set { self.replaceViewController(self.leftViewController, destinationViewController: newValue!, container: self.drawerView.leftViewContainer) _leftViewController = newValue! } } fileprivate var _rightViewController: UIViewController? open var rightViewController: UIViewController? { get { return _rightViewController } set { self.replaceViewController(self.rightViewController, destinationViewController: newValue!, container: self.drawerView.rightViewContainer) _rightViewController = newValue } } fileprivate var _centerViewController: UIViewController? open var centerViewController: UIViewController? { get { return _centerViewController } set { self.replaceViewController(self.centerViewController, destinationViewController: newValue!, container: self.drawerView.centerViewContainer) _centerViewController = newValue } } fileprivate lazy var toggleDrawerTapGestureRecognizer: UITapGestureRecognizer = { [unowned self] in let gesture = UITapGestureRecognizer(target: self, action: #selector(KGDrawerViewController.centerViewContainerTapped(_:))) return gesture }() open var leftDrawerWidth: CGFloat { get { return drawerView.leftViewContainerWidth } set { drawerView.leftViewContainerWidth = newValue } } open var rightDrawerWidth: CGFloat { get { return drawerView.rightViewContainerWidth } set { drawerView.rightViewContainerWidth = newValue } } open var leftDrawerRevealWidth: CGFloat { get { return drawerView.leftViewContainerWidth } } open var rightDrawerRevealWidth: CGFloat { get { return drawerView.rightViewContainerWidth } } open var backgroundImage: UIImage? { get { return drawerView.backgroundImageView.image } set { drawerView.backgroundImageView.image = newValue } } // MARK: Status Bar override open var childViewControllerForStatusBarHidden : UIViewController? { return centerViewController } override open var childViewControllerForStatusBarStyle : UIViewController? { return centerViewController } // MARK: Memory Management override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
6bdcc3767a483e9bee38b794a3f7e4ec
32.29845
167
0.627401
5.87218
false
false
false
false
apple/swift-nio-http2
Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift
1
24798
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest import NIOCore import NIOEmbedded import NIOHPACK @testable import NIOHTTP2 struct TestCaseError: Error { } // MARK: Helper assertions for outbound frame actions. // We need these to work around the fact that neither EventLoopPromise or MarkedCircularBuffer have equatable // conformances. extension OutboundFrameAction { internal func assertForward(file: StaticString = #filePath, line: UInt = #line) { guard case .forward = self else { XCTFail("Expected .forward, got \(self)", file: (file), line: line) return } } internal func assertNothing(file: StaticString = #filePath, line: UInt = #line) { guard case .nothing = self else { XCTFail("Expected .nothing, got \(self)", file: (file), line: line) return } } internal func assertForwardAndDrop(file: StaticString = #filePath, line: UInt = #line) throws -> (MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise<Void>?)>, NIOHTTP2Errors.StreamClosed) { guard case .forwardAndDrop(let promises, let error) = self else { XCTFail("Expected .forwardAndDrop, got \(self)", file: (file), line: line) throw TestCaseError() } return (promises, error) } internal func assertSucceedAndDrop(file: StaticString = #filePath, line: UInt = #line) throws -> (MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise<Void>?)>, NIOHTTP2Errors.StreamClosed) { guard case .succeedAndDrop(let promises, let error) = self else { XCTFail("Expected .succeedAndDrop, got \(self)", file: (file), line: line) throw TestCaseError() } return (promises, error) } } final class ConcurrentStreamBufferTests: XCTestCase { var loop: EmbeddedEventLoop! override func setUp() { self.loop = EmbeddedEventLoop() } override func tearDown() { XCTAssertNoThrow(try self.loop.syncShutdownGracefully()) self.loop = nil } func testBasicFunctionality() throws { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 2) // Write frames for three streams. let frames = stride(from: 1, through: 5, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: HPACKHeaders([])))) } let results: [OutboundFrameAction] = try assertNoThrowWithValue(frames.map { let result = try manager.processOutboundFrame($0, promise: nil, channelWritable: true) if case .forward = result { manager.streamCreated($0.streamID) } return result }) // Only two of these should have been passed through. results[0].assertForward() results[1].assertForward() results[2].assertNothing() // Asking for pending writes should do nothing. XCTAssertNil(manager.nextFlushedWritableFrame()) // Completing stream 1 should not produce a write yet. XCTAssertNil(manager.streamClosed(1)) XCTAssertNil(manager.nextFlushedWritableFrame()) // Now we flush. This should cause the remaining HEADERS frame to be written. manager.flushReceived() guard let write = manager.nextFlushedWritableFrame() else { XCTFail("Did not flush a frame") return } XCTAssertNil(manager.nextFlushedWritableFrame()) write.0.assertFrameMatches(this: frames.last!) XCTAssertNil(write.1) } func testToleratesNegativeNumbersOfStreams() throws { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 2) // Write frames for three streams and flush them. let frames = stride(from: 1, through: 5, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: HPACKHeaders([])))) } let results: [OutboundFrameAction] = try assertNoThrowWithValue(frames.map { let result = try manager.processOutboundFrame($0, promise: nil, channelWritable: true) if case .forward = result { manager.streamCreated($0.streamID) } return result }) // Only two of these should have been passed through. results[0].assertForward() results[1].assertForward() results[2].assertNothing() // Flushing doesn't move anything. manager.flushReceived() XCTAssertNil(manager.nextFlushedWritableFrame()) // Now we're going to drop the number of allowed concurrent streams to 1. manager.maxOutboundStreams = 1 // No change. XCTAssertNil(manager.nextFlushedWritableFrame()) // Write a new stream. This should be buffered. let newStreamFrame = HTTP2Frame(streamID: 7, payload: .headers(.init(headers: HPACKHeaders([]), endStream: true))) XCTAssertNoThrow(try manager.processOutboundFrame(newStreamFrame, promise: nil, channelWritable: true).assertNothing()) XCTAssertNil(manager.nextFlushedWritableFrame()) // Complete stream 1. Nothing should happen, as only one stream is allowed through. XCTAssertNil(manager.streamClosed(1)) XCTAssertNil(manager.nextFlushedWritableFrame()) // Now complete another stream. This unblocks the next stream, but only one. XCTAssertNil(manager.streamClosed(3)) guard let write = manager.nextFlushedWritableFrame() else { XCTFail("Did not flush a frame") return } XCTAssertNil(manager.nextFlushedWritableFrame()) write.0.assertFrameMatches(this: frames.last!) XCTAssertNil(write.1) } func testCascadingFrames() throws { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 1) // We're going to test a cascade of frames as a result of stream closure. To do this, we set up, let's say, 100 // streams where all but the first has an END_STREAM frame in it. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrames: [HTTP2Frame] = stride(from: 3, to: 201, by: 2).map { streamID in HTTP2Frame(streamID: HTTP2StreamID(streamID), payload: .headers(.init(headers: HPACKHeaders([]), endStream: true))) } // Write the first frame, and all the subsequent frames, and flush them. This will lead to one flushed frame. XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) for frame in subsequentFrames { XCTAssertNoThrow(try manager.processOutboundFrame(frame, promise: nil, channelWritable: true).assertNothing()) } manager.flushReceived() XCTAssertNil(manager.nextFlushedWritableFrame()) // Ok, now we're going to tell the buffer that the first stream is closed, and then spin over the manager getting // new frames and closing them until there are no more to get. var cascadedFrames: [HTTP2Frame] = Array() XCTAssertNil(manager.streamClosed(1)) while let write = manager.nextFlushedWritableFrame() { cascadedFrames.append(write.0) XCTAssertNil(write.1) XCTAssertNil(manager.streamClosed(write.0.streamID)) } subsequentFrames.assertFramesMatch(cascadedFrames) } func testBufferedFramesPassedThroughOnStreamClosed() { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 1) // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We'll flush some, but not all of them let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) XCTAssertNoThrow(try (0..<15).forEach { _ in XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: nil, channelWritable: true).assertNothing()) }) manager.flushReceived() XCTAssertNoThrow(try (0..<15).forEach { _ in XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: nil, channelWritable: true).assertNothing()) }) XCTAssertNil(manager.nextFlushedWritableFrame()) // Ok, now we're going to unblock stream 3 by completing stream 1. XCTAssertNil(manager.streamClosed(1)) // The flushed writes should all be passed through. var flushedFrames: [HTTP2Frame] = Array() while let write = manager.nextFlushedWritableFrame() { flushedFrames.append(write.0) XCTAssertNil(write.1) } flushedFrames.assertFramesMatch(Array(repeating: subsequentFrame, count: 15)) // A subsequent flush will drive the rest of the frames through. manager.flushReceived() while let write = manager.nextFlushedWritableFrame() { flushedFrames.append(write.0) XCTAssertNil(write.1) } flushedFrames.assertFramesMatch(Array(repeating: subsequentFrame, count: 30)) } func testResetStreamOnUnbufferingStream() throws { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 1) // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We'll flush some, but not all of them let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) var writeStatus: [Bool?] = Array(repeating: nil, count: 30) var writePromises: [EventLoopFuture<Void>] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) return p.futureResult }) manager.flushReceived() XCTAssertNoThrow(try writePromises.append(contentsOf: (0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) return p.futureResult })) for (idx, promise) in writePromises.enumerated() { promise.map { writeStatus[idx] = true }.whenFailure { error in XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) writeStatus[idx] = false } } XCTAssertNil(manager.nextFlushedWritableFrame()) // Now we're going to unblock stream 3 by completing stream 1. This will leave our buffer still in place, as we can't // pass on the unflushed writes. XCTAssertNil(manager.streamClosed(1)) var flushedFrames: [HTTP2Frame] = Array() while let write = manager.nextFlushedWritableFrame() { flushedFrames.append(write.0) write.1?.succeed(()) } flushedFrames.assertFramesMatch(Array(repeating: subsequentFrame, count: 15)) // Only the first 15 are done. XCTAssertEqual(writeStatus, Array(repeating: true as Bool?, count: 15) + Array(repeating: nil as Bool?, count: 15)) // Now we're going to write a RST_STREAM frame on stream 3 let rstStreamFrame = HTTP2Frame(streamID: 3, payload: .rstStream(.cancel)) let (droppedWrites, error) = try assertNoThrowWithValue(manager.processOutboundFrame(rstStreamFrame, promise: nil, channelWritable: true).assertForwardAndDrop()) // Fail all these writes. for write in droppedWrites { write.1?.fail(error) } XCTAssertEqual(error, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) XCTAssertEqual(writeStatus, Array(repeating: true as Bool?, count: 15) + Array(repeating: false as Bool?, count: 15)) } func testResetStreamOnBufferingStream() throws { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 1) // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We won't flush stream 3. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) var writeStatus: [Bool?] = Array(repeating: nil, count: 15) let writePromises: [EventLoopFuture<Void>] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) return p.futureResult }) for (idx, promise) in writePromises.enumerated() { promise.map { writeStatus[idx] = true }.whenFailure { error in XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) writeStatus[idx] = false } } // No new writes other than the first frame. XCTAssertNil(manager.nextFlushedWritableFrame()) XCTAssertEqual(writeStatus, Array(repeating: nil as Bool?, count: 15)) // Now we're going to send RST_STREAM on 3. All writes should fail, and we should be asked to drop the RST_STREAM frame. let rstStreamFrame = HTTP2Frame(streamID: 3, payload: .rstStream(.cancel)) let (droppedWrites, error) = try assertNoThrowWithValue(manager.processOutboundFrame(rstStreamFrame, promise: nil, channelWritable: true).assertSucceedAndDrop()) // Fail all these writes. for write in droppedWrites { write.1?.fail(error) } XCTAssertEqual(writeStatus, Array(repeating: false as Bool?, count: 15)) // Flushing changes nothing. manager.flushReceived() XCTAssertNil(manager.nextFlushedWritableFrame()) } func testGoingBackwardsInStreamIDIsNotAllowed() { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 1) // We're going to create stream 1 and stream 11. Stream 1 will be passed through, stream 11 will have to wait. let oneFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let elevenFrame = HTTP2Frame(streamID: 11, payload: .headers(.init(headers: HPACKHeaders([])))) XCTAssertNoThrow(try manager.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) XCTAssertNoThrow(try manager.processOutboundFrame(elevenFrame, promise: nil, channelWritable: true).assertNothing()) // Now we're going to try to write a frame for stream 5. This will fail. let fiveFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders([])))) XCTAssertThrowsError(try manager.processOutboundFrame(fiveFrame, promise: nil, channelWritable: true)) { error in XCTAssertTrue(error is NIOHTTP2Errors.StreamIDTooSmall) } } func testFramesForNonLocalStreamIDsAreIgnoredClient() { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 1) // We're going to create stream 1 and stream 3, which will be buffered. let oneFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let threeFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders([])))) XCTAssertNoThrow(try manager.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) XCTAssertNoThrow(try manager.processOutboundFrame(threeFrame, promise: nil, channelWritable: true).assertNothing()) // Now we're going to try to write a frame for stream 4, a server-initiated stream. This will be passed through safely. let fourFrame = HTTP2Frame(streamID: 4, payload: .headers(.init(headers: HPACKHeaders([])))) XCTAssertNoThrow(try manager.processOutboundFrame(fourFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(4) XCTAssertEqual(manager.currentOutboundStreams, 1) } func testFramesForNonLocalStreamIDsAreIgnoredServer() { var manager = ConcurrentStreamBuffer(mode: .server, initialMaxOutboundStreams: 1) // We're going to create stream 2 and stream 4. First, however, we reserve them. These are not buffered, per RFC 7540 § 5.1.2: // // > Streams in either of the "reserved" states do not count toward the stream limit. let twoFramePromise = HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 2, headers: HPACKHeaders([])))) let fourFramePromise = HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 4, headers: HPACKHeaders([])))) XCTAssertNoThrow(try manager.processOutboundFrame(twoFramePromise, promise: nil, channelWritable: true).assertForward()) XCTAssertNoThrow(try manager.processOutboundFrame(fourFramePromise, promise: nil, channelWritable: true).assertForward()) // Now we're going to try to initiate these by sending HEADERS frames. This will buffer the second one. let twoFrame = HTTP2Frame(streamID: 2, payload: .headers(.init(headers: HPACKHeaders([])))) let fourFrame = HTTP2Frame(streamID: 4, payload: .headers(.init(headers: HPACKHeaders([])))) XCTAssertNoThrow(try manager.processOutboundFrame(twoFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(2) XCTAssertNoThrow(try manager.processOutboundFrame(fourFrame, promise: nil, channelWritable: true).assertNothing()) // Now we're going to try to write a frame for stream 3, a client-initiated stream. This will be passed through safely. let threeFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders([])))) XCTAssertNoThrow(try manager.processOutboundFrame(threeFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(3) XCTAssertEqual(manager.currentOutboundStreams, 1) } func testDropsFramesOnStreamClosure() throws { // Here we're going to buffer up a bunch of frames, pull one out, and then close the stream. This should drop the frames. var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 1) // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) manager.streamCreated(1) var writeStatus: [Bool?] = Array(repeating: nil, count: 15) let writePromises: [EventLoopFuture<Void>] = try assertNoThrowWithValue((0..<15).map { _ in let p = self.loop.makePromise(of: Void.self) XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) return p.futureResult }) for (idx, promise) in writePromises.enumerated() { promise.map { writeStatus[idx] = true }.whenFailure { error in XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) writeStatus[idx] = false } } manager.flushReceived() XCTAssertNil(manager.nextFlushedWritableFrame()) // Ok, now we're going to unblock stream 3 by completing stream 1. XCTAssertNil(manager.streamClosed(1)) // Let's now start stream 3. manager.streamCreated(3) // Now, let's close stream 3. guard let droppedFrames = manager.streamClosed(3) else { XCTFail("Didn't return dropped frames") return } for (_, promise) in droppedFrames { promise?.fail(NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) } XCTAssertEqual(writeStatus, Array(repeating: false, count: 15)) } func testBufferingWithBlockedChannel() throws { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 100) // Write a frame for the first stream. This will be buffered, as the connection isn't writable. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: false).assertNothing()) // Write a frame for the second stream. This should also be buffered, as the connection still isn't writable. let secondFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try manager.processOutboundFrame(secondFrame, promise: nil, channelWritable: false).assertNothing()) manager.flushReceived() // Grab a pending write, simulating the connection becoming writable. guard let firstWritableFrame = manager.nextFlushedWritableFrame() else { XCTFail("Did not write frame") return } firstWritableFrame.0.assertFrameMatches(this: firstFrame) manager.streamCreated(1) // Now write a frame for stream 5. Even though the connection is writable, this should be buffered. let thirdFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders()))) XCTAssertNoThrow(try manager.processOutboundFrame(thirdFrame, promise: nil, channelWritable: true).assertNothing()) // Now we're going to try to write data once to each stream, simulating the channel being blocked. Stream 1 should // progress, as the stream is actually open, while the writes for stream 3 and 5 should be buffered. let fourthFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) XCTAssertNoThrow(try manager.processOutboundFrame(fourthFrame, promise: nil, channelWritable: true).assertForward()) let fifthFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) XCTAssertNoThrow(try manager.processOutboundFrame(fifthFrame, promise: nil, channelWritable: true).assertNothing()) let sixthFrame = HTTP2Frame(streamID: 5, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) XCTAssertNoThrow(try manager.processOutboundFrame(sixthFrame, promise: nil, channelWritable: true).assertNothing()) manager.flushReceived() // Now the remaining frames should come out. var frames = [HTTP2Frame]() while let frame = manager.nextFlushedWritableFrame() { frames.append(frame.0) } frames.assertFramesMatch([secondFrame, fifthFrame, thirdFrame, sixthFrame]) } }
apache-2.0
51d8b992d15ac0cac5defad2b31b1a69
49.606122
193
0.677663
4.616831
false
true
false
false
danielpi/SwiftMatrix
Matrix.swift
1
10647
// // Matrix.swift // SwiftMatrixExample // // Created by Daniel Pink on 30/08/2014. // Copyright (c) 2014 Electronic Innovations. All rights reserved. // import Cocoa import Foundation import Accelerate // Lets just worry about 2 dimensional float matrices public protocol SummableMultipliable: Equatable { func +(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self } extension Int: SummableMultipliable {} extension Float: SummableMultipliable {} extension Double: SummableMultipliable {} // SignedNumberType is a good general purpose number type as it includes Int Float and Double // http://nshipster.com/swift-comparison-protocols/ public struct Matrix: Equatable, Printable { var grid: [Double] public let rows: Int public let cols: Int public var size: (rows: Int, cols: Int) { get { return (rows, cols) } } public var T: Matrix { get { return self.transpose() } } public var description: String { var textualRepresentation = "\t\(rows)x\(cols) Double Matrix\n\n" var formatter = NSNumberFormatter() formatter.numberStyle = .DecimalStyle for var i = 0; i < rows; ++i { textualRepresentation += "" for var j = 0; j < cols; ++j { let valueString: String = NSString(format:"% 1.2f", self[i,j]) as String //let valueString: String = formatter.stringFromNumber(self[i,j]) textualRepresentation += "\t\(valueString)" } textualRepresentation += "\n" } textualRepresentation += "" return textualRepresentation } public init(rows: Int, cols: Int, repeatedValue: Double) { self.rows = rows self.cols = cols grid = Array(count: rows * cols, repeatedValue: repeatedValue) } public init(rows: Int, cols: Int) { self.init(rows: rows, cols: cols, repeatedValue: 0.0) } public init(_ rows: Int,_ cols: Int) { self.init(rows: rows, cols: cols, repeatedValue: 0.0) } public init(_ data: [Double]) { grid = data rows = 1 cols = data.count } public init(_ data: [[Double]]) { var matrix = Matrix(rows: data.count, cols: data[0].count) let no_columns = data[0].count for (i, row) in enumerate(data) { assert(no_columns == row.count, "Each row must be of the same length") for (j, value) in enumerate(row) { matrix[i, j] = value } } self = matrix } //public init(_ data: [[[Double]]]) { // Three dimensional array func indexIsValidForRow(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < cols } public subscript(row: Int) -> Double { get { // assert return grid[row] } set { grid[row] = newValue } } public subscript(row: Int, column: Int) -> Double { get { assert(indexIsValidForRow(row, column: column), "Index out of range") return grid[(row * cols) + column] } set { assert(indexIsValidForRow(row, column: column), "Index out of range") grid[(row * cols) + column] = newValue } } public subscript(rows: [Int], cols: [Int]) -> Matrix { get { var matrix = Matrix(rows.count, cols.count) for (i, r) in enumerate(rows) { for (j, c) in enumerate(cols) { assert(indexIsValidForRow(r, column: c), "Index out of range") matrix[i,j] = self[r,c] } } return matrix } set { for (i, r) in enumerate(rows) { for (j, c) in enumerate(cols) { assert(indexIsValidForRow(r, column: c), "Index out of range") grid[(i * self.cols) + j] = newValue[r,c] } } } } public subscript(rows: Range<Int>, cols: Range<Int>) -> Matrix { get { var matrix = Matrix(rows.endIndex - rows.startIndex, cols.endIndex - cols.startIndex) for (i, r) in enumerate(rows) { for (j, c) in enumerate(cols) { assert(indexIsValidForRow(r, column: c), "Index out of range") matrix[i,j] = self[r,c] } } return matrix } } /* // This is from swix. Needs asarray which also needs arange. I don't understand how they work yet. subscript(r: Range<Int>, c: Range<Int>) -> matrix { // x[0..<2, 0..<2] get { var rr = asarray(r) var cc = asarray(c) return self[rr, cc] } set { var rr = asarray(r) var cc = asarray(c) self[rr, cc] = newValue } } */ public func transpose() -> Matrix { var newMatrix = Matrix(rows: cols, cols: rows) vDSP_mtransD(grid, 1, &newMatrix.grid, 1, vDSP_Length(cols), vDSP_Length(rows)) return newMatrix } } // MARK: Literal extension Matrix: ArrayLiteralConvertible { //typealias Element = Double public init(arrayLiteral elements: Double...) { let data = elements var matrix = Matrix(data) self = matrix } /*public static func convertFromArrayLiteral(elements: Double...) -> Matrix { let data = elements as [Double] var matrix = Matrix(data) return matrix } public static func convertFromArrayLiteral(elements: [Double]...) -> Matrix { let data = elements as [[Double]] var matrix = Matrix(data) return matrix }*/ } // Equality for Doubles extension Double { static var minNormal: Double { return 2.2250738585072014e-308 } static var min: Double { return 4.9406564584124654e-324 } static var max: Double { return 1.7976931348623157e308 } } public func nearlyEqual(a: Double, b: Double, epsilon: Double) -> Bool { let absA = abs(a) let absB = abs(b) let diff = abs(a - b) if (a == b) { return true } else if (a == 0 || b == 0 || diff < Double.minNormal) { return diff < (epsilon * Double.minNormal) } else { return (diff / (absA + absB)) < epsilon } } public func nearlyEqual(a: Double, b: Double) -> Bool { return nearlyEqual(a, b, 0.00000000000001) } // MARK: Factory methods public func ones(rows: Int, cols: Int) -> Matrix { return Matrix(rows: rows, cols: cols, repeatedValue: 1.0) } public func zeros(rows: Int, cols: Int) -> Matrix { return Matrix(rows: rows, cols: cols, repeatedValue: 0.0) } public func eye(rows: Int) -> Matrix { var newMatrix = Matrix(rows: rows, cols: rows, repeatedValue: 0.0) for var index = 0; index < rows; ++index { newMatrix[index,index] = 1.0 } return newMatrix } public func rand(rows: Int, cols: Int) -> Matrix { var x = Matrix(rows, cols) var distributionOption:__CLPK_integer = 1 // Uniform 0 to 1 var seed = [__CLPK_integer(arc4random_uniform(4095)), __CLPK_integer(arc4random_uniform(4095)), __CLPK_integer(arc4random_uniform(4095)), __CLPK_integer((arc4random_uniform(2000) * 2) + 1)] var count:__CLPK_integer = __CLPK_integer(rows * cols) dlarnv_(&distributionOption, &seed, &count, UnsafeMutablePointer<Double>(x.grid)) return x } public func randn(rows: Int, cols: Int) -> Matrix { var x = zeros(rows, cols) var distributionOption:__CLPK_integer = 3 // Normal 0 to 1 var seed = [__CLPK_integer(arc4random_uniform(4095)), __CLPK_integer(arc4random_uniform(4095)), __CLPK_integer(arc4random_uniform(4095)), __CLPK_integer((arc4random_uniform(2000) * 2) + 1)] var count:__CLPK_integer = __CLPK_integer(rows * cols) dlarnv_(&distributionOption, &seed, &count, UnsafeMutablePointer<Double>(x.grid)) return x } public func randn(rows: Int, cols: Int, #mean: Double, #sigma: Double) -> Matrix { return (randn(rows, cols) * sigma) + mean } // MARK: Operators public func == (left: Matrix, right: Matrix) -> Bool { var result: Bool = true for (i, value) in enumerate(left.grid) { result = (result && nearlyEqual(value, right.grid[i])) } return result } public func + (left: Matrix, right: Matrix) -> Matrix { assert( (left.rows == right.rows) && (left.cols == right.cols) ) var result = Matrix(rows: left.rows, cols: left.cols) vDSP_vaddD( left.grid, 1, right.grid, 1, &result.grid, 1, vDSP_Length(left.grid.count) ) return result } public func + (left: Matrix, right: Double) -> Matrix { var result = Matrix(left.rows, left.cols) for (i, value) in enumerate(left.grid) { result[i] = value + right } return result } public func + (left: Double, right: Matrix) -> Matrix { var result = Matrix(right.rows, right.cols) for (i, value) in enumerate(right.grid) { result[i] = value + left } return result } public func - (left: Matrix, right: Matrix) -> Matrix { assert( (left.rows == right.rows) && (left.cols == right.cols) ) var result = Matrix(rows: left.rows, cols: left.cols) vDSP_vsubD( right.grid, 1, left.grid, 1, &result.grid, 1, vDSP_Length(left.grid.count) ) return result } public func * (left: Matrix, right:Double) -> Matrix { var result = Matrix(rows: left.rows, cols: left.cols) //vDSP_vsmulD( left.grid, 1, &right, &result.grid, 1, vDSP_Length(left.grid.count)) // Can't seem to get this to work for (i, value) in enumerate(left.grid) { result[i] = value * right } return result } public func * (left: Double, right:Matrix) -> Matrix { var result = Matrix(rows: right.rows, cols: right.cols) //vDSP_vsmulD( left.grid, 1, &right, &result.grid, 1, vDSP_Length(left.grid.count)) // Can't seem to get this to work for (i, value) in enumerate(right.grid) { result[i] = value * left } return result } // What to use for a transpose operator? // Matlab and Julia use ' (But swift won't let me use that) // Numpy uses .T (Two characters for such a common task) // Not allowed but would be cool: ᵀ // Allowed but not standared: † ′ ‵ ⊺ τ postfix operator ⊺ {} public postfix func ⊺ (matrix: Matrix) -> Matrix { return matrix.transpose() }
mit
5ec9a70d53d5029be1277b7c1adcdeeb
30.642857
193
0.578725
3.733146
false
false
false
false
brokenseal/WhereIsMaFood
WhereIsMaFood/MapManager.swift
1
4842
// // MapManager.swift // WhereIsMaFood // // Created by Davide Callegari on 13/07/17. // Copyright © 2017 Davide Callegari. All rights reserved. // import Foundation import MapKit struct Pin { let title: String let latitude: Double let longitude: Double let rawData: Any? var selected: Bool var location: CLLocation { return CLLocation( latitude: latitude, longitude: longitude ) } } class MapManager: NSObject { enum ExternalMapDirectionsProvider { case apple case google func getDirectionsUrlsUsing( from: CLLocation, to: CLLocation ) -> URL { var directionsUrl: String switch self { case .apple: directionsUrl = "http://maps.apple.com/?saddr=\(from.coordinate.latitude),\(from.coordinate.longitude)&daddr=\(to.coordinate.latitude),\(to.coordinate.longitude)" case .google: directionsUrl = "comgooglemaps://?saddr=&daddr=\(from.coordinate.latitude),\(from.coordinate.longitude)" } return URL(string: directionsUrl)! } func getDirections( from: CLLocation, to: CLLocation ){ let directionsUrl = getDirectionsUrlsUsing( from: from, to: to ) if UIApplication.shared.canOpenURL(directionsUrl) { UIApplication.shared.open( directionsUrl, options: [:], completionHandler: nil ) } else { App.main.trigger(App.Message.warnUser, object: "Can't open directions app: is it installed?") } } } internal let map:MKMapView private var managedPins: [(Pin, MKAnnotation)] = [] var regionRadius: Double init( _ map: MKMapView, regionRadius: Double = 2000.0 ){ self.map = map self.regionRadius = regionRadius super.init() map.delegate = self } func getCurrentRegion( using coordinate: CLLocationCoordinate2D ) -> MKCoordinateRegion { return MKCoordinateRegionMakeWithDistance( coordinate, regionRadius * 2, regionRadius * 2 ) } func showRegion(latitude: Double, longitude: Double){ let location = CLLocationCoordinate2D( latitude: latitude, longitude: longitude ) let region = MKCoordinateRegionMakeWithDistance( location, regionRadius * 2, regionRadius * 2 ) map.setRegion(region, animated: true) } func centerMapToUser(){ showRegion( latitude: map.userLocation.coordinate.latitude, longitude: map.userLocation.coordinate.longitude ) } func addPin(_ pin: Pin){ let annotation = MKPointAnnotation() annotation.title = pin.title annotation.coordinate = CLLocationCoordinate2D( latitude: pin.latitude, longitude: pin.longitude ) map.addAnnotation(annotation) if pin.selected == true { map.selectAnnotation(annotation, animated: true) } managedPins.append((pin, annotation)) } func addPins(_ pinsData: [Pin], removeOldPins: Bool = true){ if removeOldPins == true { removeAllPins() } for pin in pinsData { addPin(pin) } } func removeAllPins(){ managedPins = [] if map.annotations.count == 0 { return } map.removeAnnotations(map.annotations) } func getPinFromAnnotation(annotation: MKAnnotation) -> Pin? { for managedPin in managedPins { if managedPin.1 === annotation { return managedPin.0 } } return nil } func getCurrentlySelectedPin() -> Pin? { if map.selectedAnnotations.count == 0 { return nil } let selectedAnnotation = map.selectedAnnotations[0] return Pin( title: selectedAnnotation.title!!, latitude: selectedAnnotation.coordinate.latitude, longitude: selectedAnnotation.coordinate.longitude, rawData: nil, selected: true ) } } // MARK: map view delegate extension extension MapManager: MKMapViewDelegate { func getLocationsForDirections() -> (CLLocation, CLLocation)? { guard let currentlySelectedPin = getCurrentlySelectedPin(), let userLocation = map.userLocation.location else { return nil } return (currentlySelectedPin.location, userLocation) } func showDirectionsUsingCurrentLocations() { // FIXME: Inform user? if let (selectedPinLocation, userLocation) = getLocationsForDirections() { showDirectionsUsing( provider: .apple, from: userLocation, to: selectedPinLocation ) } } func showDirectionsUsing( provider: ExternalMapDirectionsProvider, from: CLLocation, to: CLLocation ){ provider.getDirections(from: from, to: to) } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { App.main.trigger(App.Message.annotationViewSelected, object: view) } }
mit
e2c6d6f16f7e1000938f2c3c70facd82
22.965347
183
0.652758
4.541276
false
false
false
false
sangonz/Swift-data-structures
DataStructures/DataStructures/Queue.swift
1
6406
// // Queue.swift // // Copyright (c) 2015 Santiago González. // import Foundation /** Container that inserts and removes elements in LIFO (last-in first-out) order. New elements are pushed at the back and popped from the front. */ public protocol QueueType: Container { /// Element at the back the container var back: Self.Generator.Element? { get } /// Element at the front the container var front: Self.Generator.Element? { get } /// Insert a new element at the back mutating func pushBack(item: Self.Generator.Element) /// Remove an element from the front, returning it mutating func popFront() -> Self.Generator.Element? } /** Implementation of a queue as a circular array. The whole implementation is delegated to `CircularArray`. We do not inherit from it to avoid exposing its whole implementation as a safety mechanism (queues are not expected to allow `pushFront()` or `popBack()`). Subscripting and looping go from front to back. */ public struct CircularArrayQueue<T>: QueueType { internal var delegate: CircularArray<T> /// Initialize as a new circular array with a given capacity public init(capacity: Int) { delegate = CircularArray<T>(capacity: capacity) } /// Initialize from a circular array public init(circularArray: CircularArray<T>) { delegate = circularArray } /// Returns the underlying circular array var circularArray: CircularArray<T> { get { return delegate } } // MARK: Container protocol /// Whether the container is empty public var isEmpty: Bool { return delegate.isEmpty } /// Number of elements in the container public var count: Int { return delegate.count } /// Remove all elements in the container public mutating func removeAll() { delegate.removeAll() } // MARK: QueueType protocol /// Element at the back the queue. Assigning `nil` removes the back element. public var back: T? { get { return delegate.back } set { delegate.back = newValue } } /// Element at the front the queue. Assigning `nil` removes the front element. public var front: T? { get { return delegate.front } set { delegate.front = newValue } } /// Enqueue a new element at the tail public mutating func pushBack(item: T) { delegate.pushBack(item) } /// Dequeue an element from the head, returning it public mutating func popFront() -> T? { return delegate.popFront() } } /** Make CircularArrayQueue iterable. */ extension CircularArrayQueue: MutableCollectionType { /// Always zero public var startIndex: Int { return delegate.startIndex } /// Equal to the number of elements in the array public var endIndex: Int { return delegate.endIndex } /// The position must be within bounds. Otherwise it might crash. Complexity: O(1) public subscript (position: Int) -> T { get { return delegate[position] } set { delegate[position] = newValue } } public func generate() -> CircularArrayGenerator<T> { return delegate.generate() } } extension CircularArrayQueue: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return delegate.description } public var debugDescription: String { return delegate.debugDescription } } /** Implementation of a queue as a circular array. The whole implementation is delegated to `LinkedList`. We do not inherit from it to avoid exposing its whole implementation as a safety mechanism (queues are not expected to allow `pushFront()` or `popBack()`). */ public struct LinkedListQueue<T>: QueueType { internal var delegate: LinkedList<T> /// Initialize as a new linked list public init() { delegate = LinkedList<T>() } /// Initialize from a linked list public init(linkedList: LinkedList<T>) { delegate = linkedList } /// Returns the underlying linked list public var linkedList: LinkedList<T> { get { return delegate } } // MARK: Container protocol /// Whether the container is empty public var isEmpty: Bool { return delegate.isEmpty } /// Number of elements in the container public var count: Int { return delegate.count } /// Remove all elements in the container public mutating func removeAll() { delegate.removeAll() } // MARK: QueueType protocol /// Element at the back the queue. Assigning `nil` removes the back element. public var back: T? { get { return delegate.back } set { delegate.back = newValue } } /// Element at the front the queue. Assigning `nil` removes the front element. public var front: T? { get { return delegate.front } set { delegate.front = newValue } } /// Enqueue a new element at the tail public mutating func pushBack(item: T) { delegate.pushBack(item) } /// Dequeue an element from the head, returning it public mutating func popFront() -> T? { return delegate.popFront() } } /** Make LinkedListQueue iterable. */ extension LinkedListQueue: MutableCollectionType { /// Always zero public var startIndex: Int { return delegate.startIndex } /// Equal to the number of elements in the arrpublic ay public var endIndex: Int { return delegate.endIndex } /// The position must be within bounds. Otherwise it might crash. Complexity: O(1) public subscript (position: Int) -> T { get { return delegate[position] } set { delegate[position] = newValue } } public func generate() -> LinkedListGenerator<T> { return delegate.generate() } } extension LinkedListQueue: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return delegate.description } public var debugDescription: String { return delegate.debugDescription } }
mit
e0b9a8259ccb3c975f752a6e95623c7b
26.029536
312
0.630601
4.859636
false
false
false
false
boolkybear/WSDL-Parser
WSDLParser/WSDLParserDelegate.swift
1
18647
// // WSDLParserDelegate.swift // WSDLParser // // Created by Boolky Bear on 13/2/15. // Copyright (c) 2015 ByBDesigns. All rights reserved. // import Cocoa enum WSDLTag: String { case Definitions = "wsdl:definitions" case Types = "wsdl:types" case Schema = "s:schema" case Import = "s:import" case Element = "s:element" case ComplexType = "s:complexType" case Sequence = "s:sequence" case Message = "wsdl:message" case Part = "wsdl:part" case PortType = "wsdl:portType" case Operation = "wsdl:operation" case Input = "wsdl:input" case Output = "wsdl:output" case Binding = "wsdl:binding" case SoapBinding = "soap:binding" case Soap12Binding = "soap12:binding" case SoapOperation = "soap:operation" case Soap12Operation = "soap12:operation" case SoapBody = "soap:body" case Soap12Body = "soap12:body" case Service = "wsdl:service" case Port = "wsdl:port" case SoapAddress = "soap:address" case Soap12Address = "soap12:address" } typealias StringStack = Stack<String> class WSDLParserDelegate: NSObject { class Definitions { var targetNamespace: String? = nil var namespaces: [ String : String ] = [ String : String ]() var types: Types? = nil var messages: [ Message ] = [Message]() var portTypes: [ PortType ] = [PortType]() var bindings: [ Binding ] = [Binding]() var services: [ Service ] = [Service]() func appendMessage(message: Message) { self.messages.append(message) } func appendPortType(portType: PortType) { self.portTypes.append(portType) } func appendBinding(binding: Binding) { self.bindings.append(binding) } func appendService(service: Service) { self.services.append(service) } } class Types { var schemas: [ Schema ] = [Schema]() func appendSchema(schema: Schema) { self.schemas.append(schema) } } class Schema { var elementFormDefault: String? = nil var targetNamespace: String? = nil var importNamespaces: [ String ] = [String]() var elements: [ Element ] = [Element]() var complexTypes: [ ComplexType ] = [ComplexType]() func appendNamespace(namespace: String) { self.importNamespaces.append(namespace) } func appendElement(element: Element) { self.elements.append(element) } func appendComplexType(complexType: ComplexType) { self.complexTypes.append(complexType) } } class Element { var name: String? = nil // Schema Element var complexType: ComplexType? = nil // Sequence Element var minOccurs: Int = 0 var maxOccurs: Int? = nil var type: String? = nil var isNillable: Bool = false func asOuterString() -> String { let complexString = self.complexType?.asString() let compoundString = self.type == nil ? "" : "Compound type \(self.type!) not yet supported\n" return "class \(self.name!) {\n" + (complexString ?? "") + "\n" + compoundString + "}" } func asInnerString() -> String { let varType: String = { switch (self.minOccurs, self.maxOccurs) { case (0, .Some): return "\(self.type!)?" case (1, .Some): return "\(self.type!)" case (_, nil): return "[\(self.type!)]" default: return "UNKNOWN" } }() return "var \(self.name!): \(varType)" } } class ComplexType { // Schema Complex Type var name: String? = nil var sequence: Sequence? = nil func asString() -> String { return self.sequence?.asString() ?? "" } } class Sequence { var elements: [ Element ] = [Element]() func appendElement(element: Element) { self.elements.append(element) } func asString() -> String { let elementStrings = self.elements.map { $0.asInnerString() } return join("\n", elementStrings) } } class Message { var name: String? = nil var parts: [ String : String ] = [String:String]() } class PortType { var name: String? = nil var operations: [ Operation ] = [Operation]() func appendOperation(operation: Operation) { self.operations.append(operation) } func operationNamed(name: String) -> Operation? { let cleanName = name.stringByRemovingTNSPrefix() let filteredOperations = self.operations.filter { $0.name == cleanName } if countElements(filteredOperations) == 1 { return filteredOperations.first! } return nil } } class Operation { var name: String? = nil var input: InputOutput? = nil var output: InputOutput? = nil var soapOperation: SoapOperation? = nil } class InputOutput { var message: String? = nil var soapBody: SoapBody? = nil } class Binding { var name: String? = nil var type: String? = nil var soapBinding: SoapBinding? = nil var operations: [ Operation ] = [Operation]() func appendOperation(operation: Operation) { self.operations.append(operation) } } class SoapBinding { var transport: String? = nil } class SoapOperation { var soapAction: String? = nil var style: String? = nil } class SoapBody { var use: String? = nil } class Service { var name: String? = nil var ports: [ Port ] = [Port]() func appendPort(port: Port) { self.ports.append(port) } } class Port { var name: String? = nil var binding: String? = nil var soapAddress: SoapAddress? = nil } class SoapAddress { var location: String? = nil } private var stack: StringStack = StringStack() private var currentSchema: Schema? = nil private var currentElement: Element? = nil private var currentComplexType: ComplexType? = nil private var currentSequence: Sequence? = nil private var currentMessage: Message? = nil private var currentPortType: PortType? = nil private var currentOperation: Operation? = nil private var currentBinding: Binding? = nil private var currentInputOutput: InputOutput? = nil private var currentService: Service? = nil private var currentPort: Port? = nil private(set) var definitions: Definitions? = nil } extension WSDLParserDelegate: NSXMLParserDelegate { func parserDidStartDocument(parser: NSXMLParser) { self.stack = StringStack() self.definitions = nil } func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) { let parentName = self.stack.top() self.stack.push(elementName) if let element = WSDLTag(rawValue: elementName) { switch element { case .Definitions: self.definitions = parseDefinitionsAttributes(attributeDict) case .Types: self.definitions?.types = Types() case .Schema: self.currentSchema = parseSchemaAttributes(attributeDict) if let currentSchema = self.currentSchema { self.definitions?.types?.appendSchema(currentSchema) } case .Import: parseImportAttributes(self.currentSchema, attributeDict: attributeDict) case .Element: if parentName == WSDLTag.Schema.rawValue { self.currentElement = parseSchemaElementAttributes(self.currentSchema, attributeDict: attributeDict) } else if parentName == WSDLTag.Sequence.rawValue { parseSequenceElementAttributes(self.currentSequence, attributeDict: attributeDict) } case .ComplexType: if parentName == WSDLTag.Schema.rawValue { self.currentComplexType = parseSchemaComplexTypeAttributes(self.currentSchema, attributeDict: attributeDict) } else if parentName == WSDLTag.Element.rawValue { self.currentComplexType = parseElementComplexTypeAttributes(self.currentElement, attributeDict: attributeDict) } case .Sequence: self.currentSequence = parseSequenceAttributes(self.currentComplexType, attributeDict: attributeDict) case .Message: self.currentMessage = parseMessageAttributes(attributeDict) if let currentMessage = self.currentMessage { self.definitions?.appendMessage(currentMessage) } case .Part: parsePartAttributes(self.currentMessage, attributeDict: attributeDict) case .PortType: self.currentPortType = parsePortTypeAttributes(attributeDict) if let currentPortType = self.currentPortType { self.definitions?.appendPortType(currentPortType) } case .Operation: if parentName == WSDLTag.PortType.rawValue { self.currentOperation = parsePortTypeOperationAttributes(self.currentPortType, attributeDict: attributeDict) } else if parentName == WSDLTag.Binding.rawValue { self.currentOperation = parseBindingOperationAttributes(self.currentBinding, attributeDict: attributeDict) } case .Input: self.currentInputOutput = parseInputAttributes(self.currentOperation, attributeDict: attributeDict) case .Output: self.currentInputOutput = parseOutputAttributes(self.currentOperation, attributeDict: attributeDict) case .Binding: self.currentBinding = parseBindingAttributes(attributeDict) if let currentBinding = self.currentBinding { self.definitions?.appendBinding(currentBinding) } case .SoapBinding: fallthrough case .Soap12Binding: parseSoapBindingAttributes(self.currentBinding, attributeDict: attributeDict) case .SoapOperation: fallthrough case .Soap12Operation: parseSoapOperationAttributes(self.currentOperation, attributeDict: attributeDict) case .SoapBody: fallthrough case .Soap12Body: parseSoapBodyAttributes(self.currentInputOutput, attributeDict: attributeDict) case .Service: self.currentService = parseServiceAttributes(attributeDict) if let currentService = self.currentService { self.definitions?.appendService(currentService) } case .Port: self.currentPort = parsePortAttributes(self.currentService, attributeDict: attributeDict) case .SoapAddress: fallthrough case .Soap12Address: parseSoapAddressAttributes(self.currentPort, attributeDict: attributeDict) } } } func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) { self.stack.pop() let parentName = self.stack.top() if let element = WSDLTag(rawValue: elementName) { switch element { case .Definitions: break case .Types: break case .Schema: self.currentSchema = nil case .Import: break case .Element: if parentName == WSDLTag.Schema.rawValue { self.currentElement = nil } case .ComplexType: self.currentComplexType = nil case .Sequence: self.currentSequence = nil case .Message: self.currentMessage = nil case .Part: break case .PortType: self.currentPortType = nil case .Operation: self.currentOperation = nil case .Input: fallthrough case .Output: self.currentInputOutput = nil case .Binding: self.currentBinding = nil case .SoapBinding: fallthrough case .Soap12Binding: break case .SoapOperation: fallthrough case .Soap12Operation: break case .SoapBody: fallthrough case .Soap12Body: break case .Service: self.currentService = nil case .Port: self.currentPort = nil case .SoapAddress: fallthrough case .Soap12Address: break } } } } // Helpers extension WSDLParserDelegate { func parseDefinitionsAttributes(attributeDict: [ NSObject : AnyObject ]) -> Definitions { let definitions = Definitions() definitions.targetNamespace = attributeDict["targetNamespace"] as? String attributeDict.filter { key, value in (key as? String)?.hasPrefix("xmlns:") ?? false }.each { key, value in definitions.namespaces[(key as? NSString)?.substringFromIndex(6) ?? NSString(string: "")] = (value as? String) ?? "" } return definitions } func parseSchemaAttributes(attributeDict: [ NSObject : AnyObject ]) -> Schema { let schema = Schema() schema.elementFormDefault = attributeDict["elementFormDefault"] as? String schema.targetNamespace = attributeDict["targetNamespace"] as? String return schema } func parseImportAttributes(schema: Schema?, attributeDict: [ NSObject : AnyObject ]) { schema?.appendNamespace(attributeDict["namespace"] as? String ?? "") } func parseSchemaElementAttributes(schema: Schema?, attributeDict: [ NSObject : AnyObject ]) -> Element { let element = Element() element.name = attributeDict["name"] as? String schema?.appendElement(element) return element } func parseSequenceElementAttributes(sequence: Sequence?, attributeDict: [ NSObject : AnyObject ]) { let element = Element() element.name = attributeDict["name"] as? String element.minOccurs = (attributeDict["minOccurs"] as? NSString)?.integerValue ?? 0 if let maxOccurs = attributeDict["maxOccurs"] as? String { element.maxOccurs = maxOccurs == "unbounded" ? nil : maxOccurs.toInt() } else { element.maxOccurs = nil } element.isNillable = (attributeDict["nillable"] as? NSString)?.isEqualToString("true") ?? true element.type = attributeDict["type"] as? String sequence?.appendElement(element) } func parseSchemaComplexTypeAttributes(schema: Schema?, attributeDict: [ NSObject : AnyObject ]) -> ComplexType { let complexType = ComplexType() complexType.name = attributeDict["name"] as? String schema?.appendComplexType(complexType) return complexType } func parseElementComplexTypeAttributes(element: Element?, attributeDict: [ NSObject : AnyObject ]) -> ComplexType { let complexType = ComplexType() element?.complexType = complexType return complexType } func parseSequenceAttributes(complexType: ComplexType?, attributeDict: [ NSObject : AnyObject ]) -> Sequence { let sequence = Sequence() complexType?.sequence = sequence return sequence } func parseMessageAttributes(attributeDict: [ NSObject : AnyObject ]) -> Message { let message = Message() message.name = attributeDict["name"] as? String return message } func parsePartAttributes(message: Message?, attributeDict: [ NSObject : AnyObject ]) { message?.parts[(attributeDict["name"] as? String) ?? ""] = (attributeDict["element"] as? String) ?? "" } func parsePortTypeAttributes(attributeDict: [ NSObject : AnyObject ]) -> PortType { let portType = PortType() portType.name = attributeDict["name"] as? String return portType } func parsePortTypeOperationAttributes(portType: PortType?, attributeDict: [ NSObject : AnyObject ]) -> Operation { let operation = Operation() operation.name = attributeDict["name"] as? String portType?.appendOperation(operation) return operation } func parseInputAttributes(operation: Operation?, attributeDict: [ NSObject : AnyObject ]) -> InputOutput { let input = InputOutput() input.message = attributeDict["message"] as? String operation?.input = input return input } func parseOutputAttributes(operation: Operation?, attributeDict: [ NSObject : AnyObject ]) -> InputOutput { let output = InputOutput() output.message = attributeDict["message"] as? String operation?.output = output return output } func parseBindingAttributes(attributeDict: [ NSObject : AnyObject ]) -> Binding { let binding = Binding() binding.name = attributeDict["name"] as? String binding.type = attributeDict["type"] as? String return binding } func parseSoapBindingAttributes(binding: Binding?, attributeDict: [ NSObject : AnyObject ]) { let soapBinding = SoapBinding() soapBinding.transport = attributeDict["transport"] as? String binding?.soapBinding = soapBinding } func parseBindingOperationAttributes(binding: Binding?, attributeDict: [ NSObject : AnyObject ]) -> Operation { let operation = Operation() operation.name = attributeDict["name"] as? String binding?.appendOperation(operation) return operation } func parseSoapOperationAttributes(operation: Operation?, attributeDict: [ NSObject : AnyObject ]) { let soapOperation = SoapOperation() soapOperation.soapAction = attributeDict["soapAction"] as? String soapOperation.style = attributeDict["style"] as? String operation?.soapOperation = soapOperation } func parseSoapBodyAttributes(inputOutput: InputOutput?, attributeDict: [ NSObject : AnyObject ]) { let soapBody = SoapBody() soapBody.use = attributeDict["use"] as? String inputOutput?.soapBody = soapBody } func parseServiceAttributes(attributeDict: [ NSObject : AnyObject ]) -> Service { let service = Service() service.name = attributeDict["name"] as? String return service } func parsePortAttributes(service: Service?, attributeDict: [ NSObject : AnyObject ]) -> Port { let port = Port() port.name = attributeDict["name"] as? String port.binding = attributeDict["binding"] as? String service?.appendPort(port) return port } func parseSoapAddressAttributes(port: Port?, attributeDict: [ NSObject : AnyObject ]) { let soapAddress = SoapAddress() soapAddress.location = attributeDict["location"] as? String port?.soapAddress = soapAddress } } // Search extension String { func stringByRemovingTNSPrefix() -> String { if self.hasPrefix("tns:") { return self.substringFromIndex(advance(self.startIndex, 4)) } return self } } extension WSDLParserDelegate { func bindingNamed(name: String) -> Binding? { let cleanName = name.stringByRemovingTNSPrefix() if let bindings = self.definitions?.bindings.filter({ $0.name == cleanName }) { if countElements(bindings) == 1 { return bindings.first! } } return nil } func portTypeNamed(name: String) -> PortType? { let cleanName = name.stringByRemovingTNSPrefix() if let portTypes = self.definitions?.portTypes.filter({ $0.name == cleanName }) { if countElements(portTypes) == 1 { return portTypes.first! } } return nil } func messageNamed(name: String) -> Message? { let cleanName = name.stringByRemovingTNSPrefix() if let messages = self.definitions?.messages.filter({ $0.name == cleanName }) { if countElements(messages) == 1 { return messages.first! } } return nil } func elementNamed(name: String) -> Element? { let cleanName = name.stringByRemovingTNSPrefix() if let elements = self.definitions?.types?.schemas.first?.elements.filter({ $0.name == cleanName }) { if countElements(elements) == 1 { return elements.first! } } return nil } }
mit
333110ab6e040feac1af4880487c45bf
22.545455
176
0.689816
3.721956
false
false
false
false
wdxgtsh/SwiftPasscodeLock
SwiftPasscodeLock/Keychain/ArchiveKey.swift
5
1774
// // ArchiveKey.swift // SwiftKeychain // // Created by Yanko Dimitrov on 11/13/14. // Copyright (c) 2014 Yanko Dimitrov. All rights reserved. // import Foundation public class ArchiveKey: BaseKey { public var object: NSCoding? private var secretData: NSData? { if let objectToArchive = object { return NSKeyedArchiver.archivedDataWithRootObject(objectToArchive) } return nil } /////////////////////////////////////////////////////// // MARK: - Initializers /////////////////////////////////////////////////////// init(keyName: String, object: NSCoding? = nil) { self.object = object super.init(name: keyName) } /////////////////////////////////////////////////////// // MARK: - KeychainItem /////////////////////////////////////////////////////// public override func makeQueryForKeychain(keychain: KeychainService) -> KeychainQuery { let query = KeychainQuery(keychain: keychain) query.addField(kSecClass as String, withValue: kSecClassGenericPassword) query.addField(kSecAttrService as String, withValue: keychain.serviceName) query.addField(kSecAttrAccount as String, withValue: name) return query } public override func fieldsToLock() -> NSDictionary { var fields = NSMutableDictionary() if let data = secretData { fields[kSecValueData as String] = data } return fields } public override func unlockData(data: NSData) { object = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? NSCoding } }
mit
14300875c2bb06cc4b3fcbd21a97e99f
25.878788
91
0.519729
6.013559
false
false
false
false
fabiomassimo/eidolon
Kiosk/Auction Listings/TableCollectionViewCell.swift
1
3388
import UIKit class TableCollectionViewCell: ListingsCollectionViewCell { private lazy var infoView: UIView = { let view = UIView() view.addSubview(self.lotNumberLabel) view.addSubview(self.artistNameLabel) view.addSubview(self.artworkTitleLabel) self.lotNumberLabel.alignTop("0", bottom: nil, toView: view) self.lotNumberLabel.alignLeading("0", trailing: "0", toView: view) self.artistNameLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: self.lotNumberLabel, predicate: "5") self.artistNameLabel.alignLeading("0", trailing: "0", toView: view) self.artworkTitleLabel.alignLeading("0", trailing: "0", toView: view) self.artworkTitleLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: self.artistNameLabel, predicate: "0") self.artworkTitleLabel.alignTop(nil, bottom: "0", toView: view) return view }() private lazy var cellSubviews: [UIView] = [self.artworkImageView, self.infoView, self.currentBidLabel, self.numberOfBidsLabel, self.bidButton] override func setup() { super.setup() contentView.constrainWidth("\(TableCollectionViewCell.Width)") // Configure subviews numberOfBidsLabel.textAlignment = .Center artworkImageView.contentMode = .ScaleAspectFill artworkImageView.clipsToBounds = true // Add subviews cellSubviews.map{ self.contentView.addSubview($0) } // Constrain subviews artworkImageView.alignAttribute(.Width, toAttribute: .Height, ofView: artworkImageView, predicate: nil) artworkImageView.alignTop("14", leading: "0", bottom: "-14", trailing: nil, toView: contentView) artworkImageView.constrainHeight("56") infoView.alignAttribute(.Left, toAttribute: .Right, ofView: artworkImageView, predicate: "28") infoView.alignCenterYWithView(artworkImageView, predicate: "0") infoView.constrainWidth("300") currentBidLabel.alignAttribute(.Left, toAttribute: .Right, ofView: infoView, predicate: "33") currentBidLabel.alignCenterYWithView(artworkImageView, predicate: "0") currentBidLabel.constrainWidth("180") numberOfBidsLabel.alignAttribute(.Left, toAttribute: .Right, ofView: currentBidLabel, predicate: "33") numberOfBidsLabel.alignCenterYWithView(artworkImageView, predicate: "0") numberOfBidsLabel.alignAttribute(.Right, toAttribute: .Left, ofView: bidButton, predicate: "-33") bidButton.alignBottom(nil, trailing: "0", toView: contentView) bidButton.alignCenterYWithView(artworkImageView, predicate: "0") bidButton.constrainWidth("127") } override func layoutSubviews() { super.layoutSubviews() contentView.drawBottomSolidBorderWithColor(UIColor.artsyMediumGrey()) } } extension TableCollectionViewCell { private struct SharedDimensions { var width: CGFloat = 0 var height: CGFloat = 84 static var instance = SharedDimensions() } class var Width: CGFloat { get { return SharedDimensions.instance.width } set (newWidth) { SharedDimensions.instance.width = newWidth } } class var Height: CGFloat { return SharedDimensions.instance.height } }
mit
91359c447c88553350ae61e8d452e7ce
39.819277
146
0.678276
5.148936
false
false
false
false
xcodeswift/xcproj
Sources/XcodeProj/Workspace/XCWorkspaceData.swift
1
4220
import AEXML import Foundation import PathKit public final class XCWorkspaceData { public var children: [XCWorkspaceDataElement] public init(children: [XCWorkspaceDataElement]) { self.children = children } } extension XCWorkspaceData: Equatable { public static func == (lhs: XCWorkspaceData, rhs: XCWorkspaceData) -> Bool { lhs.children == rhs.children } } extension XCWorkspaceData: Writable { /// Initializes the workspace with the path where the workspace is. /// The initializer will try to find an .xcworkspacedata inside the workspace. /// If the .xcworkspacedata cannot be found, the init will fail. /// /// - Parameter path: .xcworkspace path. /// - Throws: throws an error if the workspace cannot be initialized. public convenience init(path: Path) throws { if !path.exists { throw XCWorkspaceDataError.notFound(path: path) } let xml = try AEXMLDocument(xml: path.read()) let children = try xml .root .children .compactMap(XCWorkspaceDataElement.init(element:)) self.init(children: children) } // MARK: - <Writable> public func write(path: Path, override: Bool = true) throws { let document = AEXMLDocument() let workspace = document.addChild(name: "Workspace", value: nil, attributes: ["version": "1.0"]) _ = children .map { $0.xmlElement() } .map(workspace.addChild) if override, path.exists { try path.delete() } try path.write(document.xmlXcodeFormat) } } // MARK: - XCWorkspaceDataElement AEXMLElement decoding and encoding private extension XCWorkspaceDataElement { init(element: AEXMLElement) throws { switch element.name { case "FileRef": self = try .file(XCWorkspaceDataFileRef(element: element)) case "Group": self = try .group(XCWorkspaceDataGroup(element: element)) default: throw Error.unknownName(element.name) } } func xmlElement() -> AEXMLElement { switch self { case let .file(fileRef): return fileRef.xmlElement() case let .group(group): return group.xmlElement() } } } // MARK: - XCWorkspaceDataGroup AEXMLElement decoding and encoding private extension XCWorkspaceDataGroup { enum Error: Swift.Error { case wrongElementName case missingLocationAttribute } convenience init(element: AEXMLElement) throws { guard element.name == "Group" else { throw Error.wrongElementName } guard let location = element.attributes["location"] else { throw Error.missingLocationAttribute } let locationType = try XCWorkspaceDataElementLocationType(string: location) let name = element.attributes["name"] let children = try element.children.map(XCWorkspaceDataElement.init(element:)) self.init(location: locationType, name: name, children: children) } func xmlElement() -> AEXMLElement { var attributes = ["location": location.description] attributes["name"] = name let element = AEXMLElement(name: "Group", value: nil, attributes: attributes) _ = children .map { $0.xmlElement() } .map(element.addChild) return element } } // MARK: - XCWorkspaceDataFileRef AEXMLElement decoding and encoding private extension XCWorkspaceDataFileRef { enum Error: Swift.Error { case wrongElementName case missingLocationAttribute } convenience init(element: AEXMLElement) throws { guard element.name == "FileRef" else { throw Error.wrongElementName } guard let location = element.attributes["location"] else { throw Error.missingLocationAttribute } self.init(location: try XCWorkspaceDataElementLocationType(string: location)) } func xmlElement() -> AEXMLElement { AEXMLElement(name: "FileRef", value: nil, attributes: ["location": location.description]) } }
mit
d2121fc72dd1eba1bf7e661b94d7a037
29.80292
104
0.632464
4.867359
false
false
false
false
xtcan/playerStudy_swift
TCVideo_Study/TCVideo_Study/Classes/Live/ViewModel/RoomViewModel.swift
1
1972
// // RoomViewModel.swift // TCVideo_Study // // Created by tcan on 2018/1/10. // Copyright © 2018年 tcan. All rights reserved. // import UIKit class RoomViewModel: NSObject { lazy var liveURL : String = "" } extension RoomViewModel { func loadLiveURL(_ roomid : Int, _ userId : String, _ completion : @escaping () -> ()) { let URLString = "http://qf.56.com/play/v2/preLoading.ios" let parameters : [String : Any] = ["imei" : "36301BB0-8BBA-48B0-91F5-33F1517FA056", "roomId" : roomid, "signature" : "f69f4d7d2feb3840f9294179cbcb913f", "userId" : userId] NetworkTool.getRequestWithURL(path: URLString, parameter: parameters, success: { result in // 1.获取结果字典 guard let resultDict = result as? [String : Any] else { return } // 2.获取信息 guard let msgDict = resultDict["message"] as? [String : Any] else { return } // 3.获取直播的请求地址 guard let requestURL = msgDict["rUrl"] as? String else { return } // 4.请求直播地址 self.loadOnliveURL(requestURL, completion) }) { error in } } fileprivate func loadOnliveURL(_ URLString : String, _ complection : @escaping () -> ()) { NetworkTool.requestData(.get, URLString: URLString, finishedCallback: { result in // 1.获取结果字典 guard let resultDict = result as? [String : Any] else { return } // 2.获取地址 guard let liveURL = resultDict["url"] as? String else { return } // 3.保存地址 self.liveURL = liveURL // 4.回调出去 complection() }) } }
apache-2.0
c5dd6b0d128f3df8cc3434310c8443ca
31.465517
98
0.503983
4.289294
false
false
false
false
sjsoad/SKUtils
SKUtils/Misc/Animations/UIView+Animations.swift
1
4463
// // UIView+Animations.swift // SKUtils // // Created by Sergey on 23.06.2018. // Copyright © 2018 Sergey Kostyan. All rights reserved. // import UIKit import SKAnimator public extension UIView { @discardableResult func animate(animationBlock: @escaping () -> Void, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0, completion: (() -> Void)? = nil) -> UIViewPropertyAnimator { let animator = animatorProvider.animator() animator.addAnimations(animationBlock) animator.addCompletion { (_) in completion?() } animator.startAnimation(afterDelay: delay) return animator } } public extension UIView { // MARK: - Identity - func cancelAllTransformations(animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = .identity } // MARK: - Movement - func move(by point: CGPoint, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = transform.translatedBy(x: point.x, y: point.y) } func moveX(by xPosition: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = transform.translatedBy(x: xPosition, y: 0) } func moveY(by yPosition: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = transform.translatedBy(x: 0, y: yPosition) } func set(position: CGPoint, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = CGAffineTransform(translationX: position.x, y: position.y) } func set(xPosition: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = CGAffineTransform(translationX: xPosition, y: transform.ty) } func set(yPosition: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = CGAffineTransform(translationX: transform.tx, y: yPosition) } // MARK: - Scaling - func scale(by scale: CGPoint, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = transform.scaledBy(x: scale.x, y: scale.y) } func scaleX(by xScale: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = transform.scaledBy(x: xScale, y: yScale) } func scaleY(by yScale: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = transform.scaledBy(x: xScale, y: yScale) } func set(scale: CGPoint, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = CGAffineTransform(scaleX: scale.x, y: scale.y) } func set(xScale: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = CGAffineTransform(scaleX: xScale, y: yScale) } func set(yScale: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = CGAffineTransform(scaleX: xScale, y: yScale) } // MARK: - Alpha - func alpha(to alpha: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { self.alpha = alpha } // MARK: - Rotation - func rotate(to angle: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = CGAffineTransform(rotationAngle: radians(from: angle)) } func rotate(by angle: CGFloat, animatorProvider: AnimatorProvider = DefaultAnimatorProvider(), delay: TimeInterval = 0.0) { transform = transform.rotated(by: radians(from: angle)) } // MARK: - Private - private func radians(from angle: CGFloat) -> CGFloat { return angle * (180 / CGFloat.pi) } private var xScale: CGFloat { return sqrt(pow(transform.a, 2) + pow(transform.c, 2)) } private var yScale: CGFloat { return sqrt(pow(transform.b, 2) + pow(transform.d, 2)) } }
mit
ba377121b57be3bef575482aaec43714
36.813559
130
0.668983
4.516194
false
false
false
false
ostatnicky/kancional-ios
Pods/BonMot/Sources/FontFeatures.swift
2
8084
// // FontFeatures.swift // BonMot // // Created by Brian King on 8/31/16. // Copyright © 2016 Raizlabs. All rights reserved. // #if os(OSX) import AppKit #else import UIKit #endif // This is not supported on watchOS #if os(iOS) || os(tvOS) || os(OSX) /// Protocol to provide values to be used by `UIFontFeatureTypeIdentifierKey` /// and `UIFontFeatureSelectorIdentifierKey`. You can typically find these /// values in CoreText.SFNTLayoutTypes. public protocol FontFeatureProvider { func featureSettings() -> [(type: Int, selector: Int)] } public extension BONFont { /// Create a new font and attempt to enable the specified font features. /// The returned font will have all features enabled that it supports. /// - parameter withFeatures: the features to attempt to enable on the /// font. /// - returns: a new font with the specified features enabled. public func font(withFeatures featureProviders: [FontFeatureProvider]) -> BONFont { guard featureProviders.count > 0 else { return self } let newFeatures = featureProviders.flatMap { $0.featureAttributes() } guard newFeatures.count > 0 else { return self } var fontAttributes = fontDescriptor.fontAttributes var features = fontAttributes[BONFontDescriptorFeatureSettingsAttribute] as? [[BONFontDescriptor.FeatureKey: Any]] ?? [] features.append(contentsOf: newFeatures) fontAttributes[BONFontDescriptorFeatureSettingsAttribute] = features let descriptor = BONFontDescriptor(fontAttributes: fontAttributes) #if os(OSX) return BONFont(descriptor: descriptor, size: pointSize)! #else return BONFont(descriptor: descriptor, size: pointSize) #endif } } /// A feature provider for changing the number case, also known as "figure /// style". public enum NumberCase: FontFeatureProvider { /// Uppercase numbers, also known as "lining figures", are the same height /// as uppercase letters, and they do not extend below the baseline. case upper /// Lowercase numbers, also known as "oldstyle figures", are similar in /// size and visual weight to lowercase letters, allowing them to /// blend in better in a block of text. They may have descenders /// which drop below the typographic baseline. case lower public func featureSettings() -> [(type: Int, selector: Int)] { switch self { case .upper: return [(type: kNumberCaseType, selector: kUpperCaseNumbersSelector)] case .lower: return [(type: kNumberCaseType, selector: kLowerCaseNumbersSelector)] } } } /// A feature provider for changing the number spacing, also known as /// "figure spacing". public enum NumberSpacing: FontFeatureProvider { /// Monospaced numbers, also known as "tabular figures", each take up /// the same amount of horizontal space, meaning that different numbers /// will line up when arranged in columns. case monospaced /// Proportionally spaced numbers, also known as "proprotional figures", /// are of variable width. This makes them look better in most cases, /// but they should be avoided when numbers need to line up in columns. case proportional public func featureSettings() -> [(type: Int, selector: Int)] { switch self { case .monospaced: return [(type: kNumberSpacingType, selector: kMonospacedNumbersSelector)] case .proportional: return [(type: kNumberSpacingType, selector: kProportionalNumbersSelector)] } } } /// A feature provider for displaying a fraction. public enum Fractions: FontFeatureProvider { /// No fraction formatting. case disabled /// Diagonal Fractions, when written on paper, are written on one line /// with the numerator diagonally above and to the left of the /// demoninator, with the slash ("/") between them. case diagonal /// Vertical Fractions, when written on paper, are written on one line /// with the numerator directly above the /// demoninator, with a line lying horizontally between them. case vertical public func featureSettings() -> [(type: Int, selector: Int)] { switch self { case .disabled: return [(type: kFractionsType, selector: kNoFractionsSelector)] case .diagonal: return [(type: kFractionsType, selector: kDiagonalFractionsSelector)] case .vertical: return [(type: kFractionsType, selector: kVerticalFractionsSelector)] } } } /// A feature provider for changing the vertical position of characters /// using predefined styles in the font, such as superscript and subscript. public enum VerticalPosition: FontFeatureProvider { /// No vertical position adjustment is applied. case normal /// Superscript (superior) glpyh variants are used, as in footnotes¹. case superscript /// Subscript (inferior) glyph variants are used: vₑ. case `subscript` /// Ordinal glyph variants are used, as in the common typesetting of 4th. case ordinals /// Scientific inferior glyph variants are used: H₂O case scientificInferiors public func featureSettings() -> [(type: Int, selector: Int)] { let selector: Int switch self { case .normal: selector = kNormalPositionSelector case .superscript: selector = kSuperiorsSelector case .`subscript`: selector = kInferiorsSelector case .ordinals: selector = kOrdinalsSelector case .scientificInferiors: selector = kScientificInferiorsSelector } return [(type: kVerticalPositionType, selector: selector)] } } /// A feature provider for changing small caps behavior. /// - Note: `fromUppercase` and `fromLowercase` can be combined: they are not /// mutually exclusive. public enum SmallCaps: FontFeatureProvider { /// No small caps are used. case disabled /// Uppercase letters in the source string are replaced with small caps. /// Lowercase letters remain unmodified. case fromUppercase /// Lowercase letters in the source string are replaced with small caps. /// Uppercase letters remain unmodified. case fromLowercase public func featureSettings() -> [(type: Int, selector: Int)] { switch self { case .disabled: return [ (type: kLowerCaseType, selector: kDefaultLowerCaseSelector), (type: kUpperCaseType, selector: kDefaultUpperCaseSelector), ] case .fromUppercase: return [(type: kUpperCaseType, selector: kUpperCaseSmallCapsSelector)] case .fromLowercase: return [(type: kLowerCaseType, selector: kLowerCaseSmallCapsSelector)] } } } extension FontFeatureProvider { /// - returns: an array of dictionaries, each representing one feature /// for the attributes key in the font attributes dictionary. func featureAttributes() -> [[BONFontDescriptor.FeatureKey: Any]] { let featureSettings = self.featureSettings() return featureSettings.map { return [ BONFontFeatureTypeIdentifierKey: $0.type, BONFontFeatureSelectorIdentifierKey: $0.selector, ] } } } #endif
mit
0a8ca459f4103c2a97456f737fbc5c28
35.718182
132
0.618841
5.242051
false
false
false
false
lilongcnc/firefox-ios
Storage/SQL/BrowserTable.swift
3
16940
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger // To keep SwiftData happy. typealias Args = [AnyObject?] let TableBookmarks = "bookmarks" let TableFavicons = "favicons" let TableHistory = "history" let TableDomains = "domains" let TableVisits = "visits" let TableFaviconSites = "favicon_sites" let TableQueuedTabs = "queue" let ViewWidestFaviconsForSites = "view_favicons_widest" let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon" let ViewIconForURL = "view_icon_for_url" let IndexHistoryShouldUpload = "idx_history_should_upload" let IndexVisitsSiteIDDate = "idx_visits_siteID_date" // Removed in v6. let IndexVisitsSiteIDIsLocalDate = "idx_visits_siteID_is_local_date" // Added in v6. private let AllTables: Args = [ TableDomains, TableFaviconSites, TableHistory, TableVisits, TableBookmarks, TableQueuedTabs, ] private let AllViews: Args = [ ViewHistoryIDsWithWidestFavicons, ViewWidestFaviconsForSites, ViewIconForURL, ] private let AllIndices: Args = [ IndexHistoryShouldUpload, IndexVisitsSiteIDIsLocalDate, ] private let AllTablesIndicesAndViews: Args = AllViews + AllIndices + AllTables private let log = XCGLogger.defaultInstance() /** * The monolithic class that manages the inter-related history etc. tables. * We rely on SQLiteHistory having initialized the favicon table first. */ public class BrowserTable: Table { static let DefaultVersion = 7 let version: Int var name: String { return "BROWSER" } let sqliteVersion: Int32 let supportsPartialIndices: Bool public init(version: Int = DefaultVersion) { self.version = version let v = sqlite3_libversion_number() self.sqliteVersion = v self.supportsPartialIndices = v >= 3008000 // 3.8.0. let ver = String.fromCString(sqlite3_libversion())! log.info("SQLite version: \(ver) (\(v)).") } func run(db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool { let err = db.executeChange(sql, withArgs: args) if err != nil { log.error("Error running SQL in BrowserTable. \(err?.localizedDescription)") log.error("SQL was \(sql)") } return err == nil } // TODO: transaction. func run(db: SQLiteDBConnection, queries: [(String, Args?)]) -> Bool { for (sql, args) in queries { if !run(db, sql: sql, args: args) { return false } } return true } func runValidQueries(db: SQLiteDBConnection, queries: [(String?, Args?)]) -> Bool { for (sql, args) in queries { if let sql = sql { if !run(db, sql: sql, args: args) { return false } } } return true } func prepopulateRootFolders(db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.Folder.rawValue let root = BookmarkRoots.RootID let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let args: Args = [ root, BookmarkRoots.RootGUID, type, "Root", root, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root, ] let sql = "INSERT INTO bookmarks (id, guid, type, url, title, parent) VALUES " + "(?, ?, ?, NULL, ?, ?), " + // Root "(?, ?, ?, NULL, ?, ?), " + // Mobile "(?, ?, ?, NULL, ?, ?), " + // Menu "(?, ?, ?, NULL, ?, ?), " + // Toolbar "(?, ?, ?, NULL, ?, ?) " // Unsorted return self.run(db, sql: sql, args: args) } func getHistoryTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String? { return "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. (version > 5 ? "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " : "") + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" } func getDomainsTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String? { if version <= 5 { return nil } return "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" } func getQueueTableCreationString(forVersion version: Int = BrowserTable.DefaultVersion) -> String? { if version <= 4 { return nil } return "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " } func create(db: SQLiteDBConnection, version: Int) -> Bool { // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = "CREATE TABLE IF NOT EXISTS \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "\(TableFavicons).id AS iconID, " + "\(TableFavicons).url AS iconURL, " + "\(TableFavicons).date AS iconDate, " + "\(TableFavicons).type AS iconType, " + "MAX(\(TableFavicons).width) AS iconWidth " + "FROM \(TableFaviconSites), \(TableFavicons) WHERE " + "\(TableFaviconSites).faviconID = \(TableFavicons).id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT \(TableHistory).id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM \(TableHistory) " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).id = icons.siteID " let bookmarks = "CREATE TABLE IF NOT EXISTS \(TableBookmarks) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + "type TINYINT NOT NULL, " + "url TEXT, " + "parent INTEGER REFERENCES \(TableBookmarks)(id) NOT NULL, " + "faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL, " + "title TEXT" + ") " let queries: [(String?, Args?)] = [ (getDomainsTableCreationString(forVersion: version), nil), (getHistoryTableCreationString(forVersion: version), nil), (visits, nil), (bookmarks, nil), (faviconSites, nil), (indexShouldUpload, nil), (indexSiteIDDate, nil), (widestFavicons, nil), (historyIDsWithIcon, nil), (iconForURL, nil), (getQueueTableCreationString(forVersion: version), nil) ] assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?") log.debug("Creating \(queries.count) tables, views, and indices.") return self.runValidQueries(db, queries: queries) && self.prepopulateRootFolders(db) } func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool { if from == to { log.debug("Skipping update from \(from) to \(to).") return true } if from == 0 { // This is likely an upgrade from before Bug 1160399. log.debug("Updating browser tables from zero. Assuming drop and recreate.") return drop(db) && create(db, version: to) } if from > to { // This is likely an upgrade from before Bug 1160399. log.debug("Downgrading browser tables. Assuming drop and recreate.") return drop(db) && create(db, version: to) } if from < 4 && to >= 4 { return drop(db) && create(db, version: to) } if from < 5 && to >= 5 { let queries: [(String?, Args?)] = [(getQueueTableCreationString(forVersion: to), nil)] if !self.runValidQueries(db, queries: queries) { return false } } if from < 6 && to >= 6 { if !self.run(db, queries: [ ("DROP INDEX IF EXISTS \(IndexVisitsSiteIDDate)", nil), ("CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) ON \(TableVisits) (siteID, is_local, date)", nil) ]) { return false } } if from < 7 && to >= 7 { let queries: [(String?, Args?)] = [ (getDomainsTableCreationString(forVersion: to), nil), ("ALTER TABLE \(TableHistory) ADD COLUMN domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE", nil) ] if !self.runValidQueries(db, queries: queries) { return false } let urls = db.executeQuery("SELECT DISTINCT url FROM \(TableHistory)", factory: { $0["url"] as! String }) if !fillDomainNamesFromCursor(urls, db: db) { return false } } return true } private func fillDomainNamesFromCursor(cursor: Cursor<String>, db: SQLiteDBConnection) -> Bool { if cursor.count == 0 { return true } // URL -> hostname, flattened to make args. var pairs = Args() pairs.reserveCapacity(cursor.count * 2) for url in cursor { if let url = url, host = url.asURL?.normalizedHost() { pairs.append(url) pairs.append(host) } } cursor.close() let tmpTable = "tmp_hostnames" let table = "CREATE TEMP TABLE \(tmpTable) (url TEXT NOT NULL UNIQUE, domain TEXT NOT NULL, domain_id INT)" if !self.run(db, sql: table, args: nil) { log.error("Can't create temporary table. Unable to migrate domain names. Top Sites is likely to be broken.") return false } // Now insert these into the temporary table. Chunk by an even number, for obvious reasons. let chunks = chunk(pairs, by: BrowserDB.MaxVariableNumber - (BrowserDB.MaxVariableNumber % 2)) for chunk in chunks { let ins = "INSERT INTO \(tmpTable) (url, domain) VALUES " + ", ".join(Array<String>(count: chunk.count / 2, repeatedValue: "(?, ?)")) if !self.run(db, sql: ins, args: Array(chunk)) { log.error("Couldn't insert domains into temporary table. Aborting migration.") return false } } // Now make those into domains. let domains = "INSERT OR IGNORE INTO \(TableDomains) (domain) SELECT DISTINCT domain FROM \(tmpTable)" // … and fill that temporary column. let domainIDs = "UPDATE \(tmpTable) SET domain_id = (SELECT id FROM \(TableDomains) WHERE \(TableDomains).domain = \(tmpTable).domain)" // Update the history table from the temporary table. let updateHistory = "UPDATE \(TableHistory) SET domain_id = (SELECT domain_id FROM \(tmpTable) WHERE \(tmpTable).url = \(TableHistory).url)" // Clean up. let dropTemp = "DROP TABLE \(tmpTable)" // Now run these. if !self.run(db, queries: [(domains, nil), (domainIDs, nil), (updateHistory, nil), (dropTemp, nil)]) { log.error("Unable to migrate domains.") return false } return true } /** * The Table mechanism expects to be able to check if a 'table' exists. In our (ab)use * of Table, that means making sure that any of our tables and views exist. * We do that by fetching all tables from sqlite_master with matching names, and verifying * that we get back more than one. * Note that we don't check for views -- trust to luck. */ func exists(db: SQLiteDBConnection) -> Bool { return db.tablesExist(AllTables) } func drop(db: SQLiteDBConnection) -> Bool { log.debug("Dropping all browser tables.") let additional: [(String, Args?)] = [ ("DROP TABLE IF EXISTS faviconSites", nil) // We renamed it to match naming convention. ] let queries: [(String, Args?)] = AllViews.map { ("DROP VIEW IF EXISTS \($0!)", nil) } as [(String, Args?)] + AllIndices.map { ("DROP INDEX IF EXISTS \($0!)", nil) } as [(String, Args?)] + AllTables.map { ("DROP TABLE IF EXISTS \($0!)", nil) } as [(String, Args?)] + additional return self.run(db, queries: queries) } }
mpl-2.0
348f16c01dcd5fc352c4beceb696c2f4
40.114078
231
0.591156
4.611489
false
false
false
false
ITzTravelInTime/TINU
TINU/EFIFolderReplcament.swift
1
8797
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Cocoa #if useEFIReplacement && !macOnlyMode public class EFIReplacementView: NSView, ViewID{ public let id: String = "EFIFolderReplacement" //titles let titleLabel = NSTextField() let expLabel = NSTextField() //folder opened let pathLabel = NSTextField() let checkImage = NSImageView() //buttons let openButton = NSButton() let resetButton = NSButton() //draw code override public func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) setupUI() } var bootloader: SupportedEFIFolders = .clover{ didSet{ setupUI() } } override public func viewDidMoveToSuperview() { super.viewDidMoveToSuperview() setupUI() } private func setupUI(){ //size constants let buttonsHeigth: CGFloat = 32 let fieldHeigth: CGFloat = 20 let imgSide: CGFloat = 40 //titles titleLabel.isEditable = false titleLabel.isSelectable = false titleLabel.drawsBackground = false titleLabel.isBordered = false titleLabel.isBezeled = false titleLabel.alignment = .center titleLabel.frame.origin = NSPoint(x: 5, y: self.frame.size.height - fieldHeigth - 5) titleLabel.frame.size = NSSize(width: self.frame.size.width - 10 , height: fieldHeigth) titleLabel.font = NSFont.boldSystemFont(ofSize: 13) self.addSubview(titleLabel) expLabel.isEditable = false expLabel.isSelectable = false expLabel.drawsBackground = false expLabel.isBordered = false expLabel.isBezeled = false expLabel.alignment = .left expLabel.frame.origin = NSPoint(x: 5, y: self.frame.size.height - fieldHeigth * 5 - 5) expLabel.frame.size = NSSize(width: self.frame.size.width - 10 , height: fieldHeigth * 4) expLabel.font = NSFont.systemFont(ofSize: 13) let replaceList = ["{drive}": cvm.shared.disk?.current?.driveName ?? "[error getting drive name]", "{bootloader}": bootloader.rawValue] /* titleLabel.stringValue = "\(bootloader.rawValue) EFI folder installer" expLabel.stringValue = "This option automatically installs the selected \(bootloader.rawValue) EFI folder inside the EFI partition of the drive \"\(drive)\".\nOnly UEFI 64Bits \(bootloader.rawValue) EFI folders are supported." */ let desc = TextManager!.getViewString(context: self, stringID: "desc")! expLabel.stringValue = desc.parsed(usingKeys: replaceList) let title = TextManager!.getViewString(context: self, stringID: "title")! titleLabel.stringValue = title.parsed(usingKeys: replaceList) self.addSubview(expLabel) //efi folder check pathLabel.isEditable = false pathLabel.isSelectable = false pathLabel.drawsBackground = false pathLabel.isBordered = false pathLabel.isBezeled = false pathLabel.alignment = .left pathLabel.frame.origin = NSPoint(x: 5, y: buttonsHeigth + 10) pathLabel.frame.size = NSSize(width: self.frame.size.width - 10 - imgSide , height: 26) pathLabel.font = NSFont.systemFont(ofSize: 12) pathLabel.stringValue = "" self.addSubview(pathLabel) checkImage.image = IconsManager.shared.checkIcon.themedImage() if #available(macOS 11.0, *), look.usesSFSymbols(){ checkImage.contentTintColor = .systemGreen } checkImage.frame.size = NSSize(width: imgSide, height: imgSide) checkImage.frame.origin = NSPoint(x: self.frame.size.width - 5 - imgSide, y: pathLabel.frame.origin.y + (pathLabel.frame.height / 2) - (imgSide / 2)) checkImage.imageScaling = .scaleProportionallyUpOrDown checkImage.isEditable = false self.addSubview(checkImage) //buttons openButton.title = TextManager.getViewString(context: self, stringID: "buttonChoose") openButton.bezelStyle = .rounded openButton.setButtonType(.momentaryPushIn) openButton.frame.size = NSSize(width: 150, height: buttonsHeigth) openButton.frame.origin = NSPoint(x: self.frame.size.width - openButton.frame.size.width - 5, y: 5) openButton.font = NSFont.systemFont(ofSize: 13) openButton.isContinuous = true openButton.target = self openButton.action = #selector(EFIReplacementView.openClick) self.addSubview(openButton) resetButton.title = TextManager.getViewString(context: self, stringID: "buttonRemoove") resetButton.bezelStyle = .rounded resetButton.setButtonType(.momentaryPushIn) resetButton.frame.size = NSSize(width: 100, height: buttonsHeigth) resetButton.frame.origin = NSPoint(x: 5, y: 5) resetButton.font = NSFont.systemFont(ofSize: 13) resetButton.isContinuous = true resetButton.target = self resetButton.action = #selector(EFIReplacementView.resetClick) self.addSubview(resetButton) checkOriginFolder() //check states if EFIFolderReplacementManager.shared.checkSavedEFIFolder() == nil{ resetButton.isEnabled = false openButton.isEnabled = true }else{ resetButton.isEnabled = true openButton.isEnabled = false } } @objc func openClick(){ let open = NSOpenPanel() open.allowsMultipleSelection = false open.canChooseDirectories = true open.canChooseFiles = false open.isExtensionHidden = false open.showsHiddenFiles = true open.beginSheetModal(for: CustomizationWindowManager.shared.referenceWindow, completionHandler: {response in if response != NSApplication.ModalResponse.OK{ return } if open.urls.isEmpty{ return } let cbootloader = self.bootloader let url = open.urls.first! DispatchQueue.global(qos: .background).async{ if let opener = EFIFolderReplacementManager.shared.loadEFIFolder(url.path, currentBootloader: cbootloader){ if !opener{ DispatchQueue.main.async { msgboxWithManager(self, name: "errorDialog") } }else{ DispatchQueue.main.sync { self.checkOriginFolder() } } }else{ DispatchQueue.main.sync { let replaceList = ["{path}": url.path, "{pathName}": url.lastPathComponent, "{bootloader}": cbootloader.rawValue, "{missing}" : EFIFolderReplacementManager.shared.missingFileFromOpenedFolder!] msgboxWithManager(self, name: "improperDialog", parseList: replaceList) EFIFolderReplacementManager.shared.resetMissingFileFromOpenedFolder() } } } }) } @objc func resetClick(){ DispatchQueue.global(qos: .background).async{ EFIFolderReplacementManager.shared.unloadEFIFolder() DispatchQueue.main.async { self.checkOriginFolder() } /* if !EFIFolderReplacementManager.shared.unloadEFIFolder(){ DispatchQueue.main.async { //is this really usefoul or needed? can this be batter? //msgBoxWarning("TINU: Error while unloading the EFI folder", "There was an error while unloading the stored efi foleer from the program memory") msgboxWithManager(self, name: "errorUnloading") } }else{ DispatchQueue.main.async { self.checkOriginFolder() } } */ } } func checkOriginFolder(){ if EFIFolderReplacementManager.shared.openedDirectory == nil{ pathLabel.stringValue = "" checkImage.isHidden = true self.resetButton.isEnabled = false self.openButton.isEnabled = true }else{ if EFIFolderReplacementManager.shared.currentEFIFolderType == self.bootloader{ var str = EFIFolderReplacementManager.shared.openedDirectory! if str.count > 45{ str = str[0...45] + "..." } pathLabel.stringValue = str checkImage.isHidden = false }else{ let t = EFIFolderReplacementManager.shared.currentEFIFolderType.rawValue //this is still imprecise because it doesn't accounts for the usage of the h as the first letter, but for now it's enough pathLabel.stringValue = TextManager.getViewString(context: self, stringID: "alreadyChoosen").parsed(usingKeys: ["{bootloader}" : t]) //pathLabel.stringValue = "You have alreay chosen " + (t.first!.isVowel() ? "an " : "a ") + t + " EFI folder" checkImage.isHidden = true } self.resetButton.isEnabled = true self.openButton.isEnabled = false } } } #endif
gpl-2.0
4a9bc6a963acdf79c630f2f431eea6b8
29.439446
229
0.719109
3.782029
false
false
false
false
nakajijapan/NKJMovieComposer
Sources/Classes/NKJMovieComposer.swift
1
5244
// // NKJMovieComposer.m // // Created by nakajijapan. // Copyright 2014 nakajijapan. All rights reserved. // import Foundation import AVFoundation import CoreMedia open class NKJMovieComposer { open var mixComposition = AVMutableComposition() open var instruction: AVMutableVideoCompositionInstruction! open var videoComposition = AVMutableVideoComposition() open var assetExportSession: AVAssetExportSession! open var currentTimeDuration: CMTime = .zero // AVMutableVideoCompositionLayerInstruction's List open var layerInstructions:[AVVideoCompositionLayerInstruction] = [] public init() { // AVMutableVideoComposition videoComposition.renderSize = CGSize(width: 640, height: 640) videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 24) } // Add Video open func addVideo(_ movieURL: URL) -> AVMutableVideoCompositionLayerInstruction! { let videoAsset = AVURLAsset(url:movieURL, options:nil) var compositionVideoTrack: AVMutableCompositionTrack! var compositionAudioTrack: AVMutableCompositionTrack! let videoTrack = videoAsset.tracks(withMediaType: AVMediaType.video)[0] compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: 0) do { try compositionVideoTrack.insertTimeRange( CMTimeRange(start: CMTime.zero, duration: videoAsset.duration), of: videoTrack, at: currentTimeDuration) } catch _ { print("Error: AVMediaTypeVideo") } compositionVideoTrack.preferredTransform = videoTrack.preferredTransform compositionAudioTrack = mixComposition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: 0) do { try compositionAudioTrack.insertTimeRange( CMTimeRange(start: CMTime.zero, duration: videoAsset.duration), of: videoAsset.tracks(withMediaType: AVMediaType.audio)[0] , at: currentTimeDuration) } catch _ { print("Error: AVMediaTypeAudio") } currentTimeDuration = mixComposition.duration // Add Layer Instruction let layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack) // Hide layerInstruction.setOpacity(0.0, at: currentTimeDuration) layerInstructions.append(layerInstruction) return layerInstruction } // Cover Video open func covertVideo(_ movieURL: URL, scale: CGAffineTransform, transform: CGAffineTransform) -> AVMutableVideoCompositionLayerInstruction { let videoAsset = AVURLAsset(url:movieURL, options:nil) var compositionVideoTrack:AVMutableCompositionTrack! let videoTrack = videoAsset.tracks(withMediaType: AVMediaType.video)[0] compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid)) do { try compositionVideoTrack.insertTimeRange( CMTimeRange(start: CMTime.zero, duration: videoAsset.duration), of: videoTrack, at: CMTime.zero) } catch _ { print("Error: AVMediaTypeVideo") } compositionVideoTrack.preferredTransform = videoTrack.preferredTransform var layerInstruction:AVMutableVideoCompositionLayerInstruction layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionVideoTrack) layerInstruction.setTransform(scale.concatenating(transform), at: CMTime.zero) // Hide layerInstruction.setOpacity(0.0, at: currentTimeDuration) layerInstructions.append(layerInstruction) return layerInstruction } // Export open func readyToComposeVideo(_ composedMoviePath: String) -> AVAssetExportSession! { // create instruction instruction = AVMutableVideoCompositionInstruction() instruction.timeRange = CMTimeRange(start: CMTime.zero, duration: mixComposition.duration) videoComposition.instructions = [instruction] instruction.layerInstructions = layerInstructions.reversed() // generate AVAssetExportSession based on the composition assetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPreset1280x720) assetExportSession.videoComposition = videoComposition assetExportSession.outputFileType = AVFileType.mov assetExportSession.outputURL = URL(fileURLWithPath: composedMoviePath) assetExportSession.shouldOptimizeForNetworkUse = true // delete file if FileManager.default.fileExists(atPath: composedMoviePath) { do { try FileManager.default.removeItem(atPath: composedMoviePath) } catch _ { print("Error: AVMediaTypeVideo") } } return assetExportSession } }
mit
3335acf47154298fe13a4f9473e292ff
39.030534
165
0.680397
6.162162
false
false
false
false
passt0r/MyLocator
MyLocator/AppDelegate.swift
1
5508
// // AppDelegate.swift // MyLocator // // Created by Dmytro Pasinchuk on 13.06.17. // Copyright © 2017 Dmytro Pasinchuk. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var persistContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "DataModel") container.loadPersistentStores(completionHandler: { storeDescription, error in if let error = error { fatalError("Could load data store: \(error)") } }) return container }() lazy var managedObjectContext: NSManagedObjectContext = self.persistContainer.viewContext func listenForFatalCoreDataENotofication() { NotificationCenter.default.addObserver(forName: MyMannagedObjectContextSaveDidFailNotification, object: nil, queue: OperationQueue.main, using: { notification in let alert = UIAlertController(title: "Internal alert", message: "There was a fatal error in the app and we cannot continue\n\n" + "Press OK to terminate the app. Sorry for the inconvenience", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: {_ in let exeption = NSException(name: NSExceptionName.internalInconsistencyException, reason: "Fatal Core Data error", userInfo: nil) exeption.raise() }) alert.addAction(action) self.viewControllerForShowingAlert().present(alert, animated: true, completion: nil) }) } func viewControllerForShowingAlert() -> UIViewController { let rootViewController = self.window!.rootViewController! if let presentedViewController = rootViewController.presentedViewController { return presentedViewController } else { return rootViewController } } func customizeAppearance() { UINavigationBar.appearance().barTintColor = UIColor.black UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] UITabBar.appearance().barTintColor = UIColor.black let tintColor = UIColor(red: 255/255.0, green: 238/255.0, blue: 136/255.0, alpha: 1.0) UITabBar.appearance().tintColor = tintColor } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. customizeAppearance() let tabBarController = window?.rootViewController as! UITabBarController if let tabBarViewControllers = tabBarController.viewControllers { let currentLocationViewController = tabBarViewControllers[0] as! CurrentLocationViewControler currentLocationViewController.managedObgectContext = managedObjectContext let navigationController = tabBarViewControllers[1] as! UINavigationController let locationsViewController = navigationController.topViewController as! LocationsTableViewController locationsViewController.managedObjectContext = managedObjectContext //thats fix bug with adding new element to CoreData before locationViewController loads let _ = locationsViewController.view let mapViewController = tabBarViewControllers[2] as! MapViewController mapViewController.managedObjectContext = managedObjectContext } listenForFatalCoreDataENotofication() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-3.0
d218e5ae9105177d8b30ec8c85be6e58
49.522936
285
0.700381
6.091814
false
false
false
false
AgaKhanFoundation/WCF-iOS
Pods/Quick/Sources/Quick/DSL/DSL.swift
3
14189
// swiftlint:disable line_length /** Defines a closure to be run prior to any examples in the test suite. You may define an unlimited number of these closures, but there is no guarantee as to the order in which they're run. If the test suite crashes before the first example is run, this closure will not be executed. - parameter closure: The closure to be run prior to any examples in the test suite. */ public func beforeSuite(_ closure: @escaping BeforeSuiteClosure) { World.sharedWorld.beforeSuite(closure) } /** Defines a closure to be run after all of the examples in the test suite. You may define an unlimited number of these closures, but there is no guarantee as to the order in which they're run. If the test suite crashes before all examples are run, this closure will not be executed. - parameter closure: The closure to be run after all of the examples in the test suite. */ public func afterSuite(_ closure: @escaping AfterSuiteClosure) { World.sharedWorld.afterSuite(closure) } /** Defines a group of shared examples. These examples can be re-used in several locations by using the `itBehavesLike` function. - parameter name: The name of the shared example group. This must be unique across all shared example groups defined in a test suite. - parameter closure: A closure containing the examples. This behaves just like an example group defined using `describe` or `context`--the closure may contain any number of `beforeEach` and `afterEach` closures, as well as any number of examples (defined using `it`). */ public func sharedExamples(_ name: String, closure: @escaping () -> Void) { World.sharedWorld.sharedExamples(name) { _ in closure() } } /** Defines a group of shared examples. These examples can be re-used in several locations by using the `itBehavesLike` function. - parameter name: The name of the shared example group. This must be unique across all shared example groups defined in a test suite. - parameter closure: A closure containing the examples. This behaves just like an example group defined using `describe` or `context`--the closure may contain any number of `beforeEach` and `afterEach` closures, as well as any number of examples (defined using `it`). The closure takes a SharedExampleContext as an argument. This context is a function that can be executed to retrieve parameters passed in via an `itBehavesLike` function. */ public func sharedExamples(_ name: String, closure: @escaping SharedExampleClosure) { World.sharedWorld.sharedExamples(name, closure: closure) } /** Defines an example group. Example groups are logical groupings of examples. Example groups can share setup and teardown code. - parameter description: An arbitrary string describing the example group. - parameter closure: A closure that can contain other examples. */ public func describe(_ description: String, closure: () -> Void) { World.sharedWorld.describe(description, closure: closure) } /** Defines an example group. Equivalent to `describe`. */ public func context(_ description: String, closure: () -> Void) { World.sharedWorld.context(description, closure: closure) } /** Defines a closure to be run prior to each example in the current example group. This closure is not run for pending or otherwise disabled examples. An example group may contain an unlimited number of beforeEach. They'll be run in the order they're defined, but you shouldn't rely on that behavior. - parameter closure: The closure to be run prior to each example. */ public func beforeEach(_ closure: @escaping BeforeExampleClosure) { World.sharedWorld.beforeEach(closure) } /** Identical to Quick.DSL.beforeEach, except the closure is provided with metadata on the example that the closure is being run prior to. */ public func beforeEach(_ closure: @escaping BeforeExampleWithMetadataClosure) { World.sharedWorld.beforeEach(closure: closure) } /** Defines a closure to be run after each example in the current example group. This closure is not run for pending or otherwise disabled examples. An example group may contain an unlimited number of afterEach. They'll be run in the order they're defined, but you shouldn't rely on that behavior. - parameter closure: The closure to be run after each example. */ public func afterEach(_ closure: @escaping AfterExampleClosure) { World.sharedWorld.afterEach(closure) } /** Identical to Quick.DSL.afterEach, except the closure is provided with metadata on the example that the closure is being run after. */ public func afterEach(_ closure: @escaping AfterExampleWithMetadataClosure) { World.sharedWorld.afterEach(closure: closure) } /** Defines a closure to that wraps each example in the current example group. This closure is not run for pending or otherwise disabled examples. The closure you pass to aroundEach receives a callback as its argument, which it MUST call exactly one for the example to run properly: aroundEach { runExample in doSomeSetup() runExample() doSomeCleanup() } This callback is particularly useful for test decartions that can’t split into a separate beforeEach and afterEach. For example, running each example in its own autorelease pool requires aroundEach: aroundEach { runExample in autoreleasepool { runExample() } checkObjectsNoLongerRetained() } You can also use aroundEach to guarantee proper nesting of setup and cleanup operations in situations where their relative order matters. An example group may contain an unlimited number of aroundEach callbacks. They will nest inside each other, with the first declared in the group nested at the outermost level. - parameter closure: The closure that wraps around each example. */ public func aroundEach(_ closure: @escaping AroundExampleClosure) { World.sharedWorld.aroundEach(closure) } /** Identical to Quick.DSL.aroundEach, except the closure receives metadata about the example that the closure wraps. */ public func aroundEach(_ closure: @escaping AroundExampleWithMetadataClosure) { World.sharedWorld.aroundEach(closure) } /** Defines an example. Examples use assertions to demonstrate how code should behave. These are like "tests" in XCTest. - parameter description: An arbitrary string describing what the example is meant to specify. - parameter closure: A closure that can contain assertions. - parameter file: The absolute path to the file containing the example. A sensible default is provided. - parameter line: The line containing the example. A sensible default is provided. */ public func it(_ description: String, file: FileString = #file, line: UInt = #line, closure: @escaping () throws -> Void) { World.sharedWorld.it(description, file: file, line: line, closure: closure) } /** Inserts the examples defined using a `sharedExamples` function into the current example group. The shared examples are executed at this location, as if they were written out manually. - parameter name: The name of the shared examples group to be executed. This must be identical to the name of a shared examples group defined using `sharedExamples`. If there are no shared examples that match the name given, an exception is thrown and the test suite will crash. - parameter file: The absolute path to the file containing the current example group. A sensible default is provided. - parameter line: The line containing the current example group. A sensible default is provided. */ public func itBehavesLike(_ name: String, file: FileString = #file, line: UInt = #line) { itBehavesLike(name, file: file, line: line, sharedExampleContext: { return [:] }) } /** Inserts the examples defined using a `sharedExamples` function into the current example group. The shared examples are executed at this location, as if they were written out manually. This function also passes those shared examples a context that can be evaluated to give the shared examples extra information on the subject of the example. - parameter name: The name of the shared examples group to be executed. This must be identical to the name of a shared examples group defined using `sharedExamples`. If there are no shared examples that match the name given, an exception is thrown and the test suite will crash. - parameter sharedExampleContext: A closure that, when evaluated, returns key-value pairs that provide the shared examples with extra information on the subject of the example. - parameter file: The absolute path to the file containing the current example group. A sensible default is provided. - parameter line: The line containing the current example group. A sensible default is provided. */ public func itBehavesLike(_ name: String, file: FileString = #file, line: UInt = #line, sharedExampleContext: @escaping SharedExampleContext) { World.sharedWorld.itBehavesLike(name, sharedExampleContext: sharedExampleContext, file: file, line: line) } /** Inserts the examples defined using a `Behavior` into the current example group. The shared examples are executed at this location, as if they were written out manually. This function also passes a strongly-typed context that can be evaluated to give the shared examples extra information on the subject of the example. - parameter behavior: The type of `Behavior` class defining the example group to be executed. - parameter context: A closure that, when evaluated, returns an instance of `Behavior`'s context type to provide its example group with extra information on the subject of the example. - parameter file: The absolute path to the file containing the current example group. A sensible default is provided. - parameter line: The line containing the current example group. A sensible default is provided. */ public func itBehavesLike<C>(_ behavior: Behavior<C>.Type, file: FileString = #file, line: UInt = #line, context: @escaping () -> C) { World.sharedWorld.itBehavesLike(behavior, context: context, file: file, line: line) } /** Defines an example or example group that should not be executed. Use `pending` to temporarily disable examples or groups that should not be run yet. - parameter description: An arbitrary string describing the example or example group. - parameter closure: A closure that will not be evaluated. */ public func pending(_ description: String, closure: () -> Void) { World.sharedWorld.pending(description, closure: closure) } /** Use this to quickly mark a `describe` closure as pending. This disables all examples within the closure. */ public func xdescribe(_ description: String, closure: () -> Void) { World.sharedWorld.xdescribe(description, closure: closure) } /** Use this to quickly mark a `context` closure as pending. This disables all examples within the closure. */ public func xcontext(_ description: String, closure: () -> Void) { xdescribe(description, closure: closure) } /** Use this to quickly mark an `it` closure as pending. This disables the example and ensures the code within the closure is never run. */ public func xit(_ description: String, file: FileString = #file, line: UInt = #line, closure: @escaping () throws -> Void) { World.sharedWorld.xit(description, file: file, line: line, closure: closure) } /** Use this to quickly mark an `itBehavesLike` closure as pending. This disables the example group defined by this behavior and ensures the code within is never run. */ public func xitBehavesLike<C>(_ behavior: Behavior<C>.Type, file: FileString = #file, line: UInt = #line, context: @escaping () -> C) { World.sharedWorld.xitBehavesLike(behavior, context: context, file: file, line: line) } /** Use this to quickly focus a `describe` closure, focusing the examples in the closure. If any examples in the test suite are focused, only those examples are executed. This trumps any explicitly focused or unfocused examples within the closure--they are all treated as focused. */ public func fdescribe(_ description: String, closure: () -> Void) { World.sharedWorld.fdescribe(description, closure: closure) } /** Use this to quickly focus a `context` closure. Equivalent to `fdescribe`. */ public func fcontext(_ description: String, closure: () -> Void) { fdescribe(description, closure: closure) } /** Use this to quickly focus an `it` closure, focusing the example. If any examples in the test suite are focused, only those examples are executed. */ public func fit(_ description: String, file: FileString = #file, line: UInt = #line, closure: @escaping () throws -> Void) { World.sharedWorld.fit(description, file: file, line: line, closure: closure) } /** Use this to quickly focus an `itBehavesLike` closure. */ public func fitBehavesLike(_ name: String, file: FileString = #file, line: UInt = #line) { fitBehavesLike(name, file: file, line: line, sharedExampleContext: { return [:] }) } /** Use this to quickly focus an `itBehavesLike` closure. */ public func fitBehavesLike(_ name: String, file: FileString = #file, line: UInt = #line, sharedExampleContext: @escaping SharedExampleContext) { World.sharedWorld.fitBehavesLike(name, sharedExampleContext: sharedExampleContext, file: file, line: line) } /** Use this to quickly focus on `itBehavesLike` closure. */ public func fitBehavesLike<C>(_ behavior: Behavior<C>.Type, file: FileString = #file, line: UInt = #line, context: @escaping () -> C) { World.sharedWorld.fitBehavesLike(behavior, context: context, file: file, line: line) } // swiftlint:enable line_length
bsd-3-clause
cc69b5d05b48ccdd00034bb11ab7ba6d
44.617363
188
0.725594
4.651475
false
false
false
false
Arcovv/CleanArchitectureRxSwift
Domain/Entries/Comment.swift
1
921
// // Comment.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import Foundation public struct Comment { public let body: String public let email: String public let name: String public let postId: String public let uid: String public init(body: String, email: String, name: String, postId: String, uid: String) { self.body = body self.email = email self.name = name self.postId = postId self.uid = uid } } extension Comment: Equatable { public static func == (lhs: Comment, rhs: Comment) -> Bool { return lhs.uid == rhs.uid && lhs.name == rhs.name && lhs.body == rhs.body && lhs.postId == rhs.postId && lhs.email == rhs.email } }
mit
5041b87c90caa1d33653a0c6ceff05ad
22.589744
64
0.553261
4.181818
false
false
false
false
Fidetro/SwiftFFDB
Sources/FFDBSafeOperation.swift
1
7623
// // FFDBSafeOperation.swift // Swift-FFDB // // Created by Fidetro on 11/12/2017. // Copyright © 2017 Fidetro. All rights reserved. // import FMDB public struct FFDBSafeOperation {} // MARK: Insert extension FFDBSafeOperation { /// insert object /// /// ```` /// let john = Person.init(primaryID: nil, name: "john", age: 10, address: "China") /// /// FFDBManager.insert(john) // primaryID = 1,name = "john",age = 10,address = "China" /// /// FFDBManager.insert(john,["name","age"]) // primaryID = 1,name = "john",age = 10 /// ```` /// - Parameters: /// - object: object /// - columns: column name public static func insert(_ object:FFObject, _ columns:[String]? = nil, completion: UpdateResult?) { executeDBUpdate { (db) in do{ try FFDBManager.insert(object, columns, database: db) if let completion = completion { completion(true) } }catch{ if let completion = completion { completion(false) } debugPrintLog("failed: \(error.localizedDescription)") } } } /// insert value in table /// /// - Parameters: /// - table: FFObject.Type /// - columns: insert columns /// - values: the value of column public static func insert(_ table:FFObject.Type, _ columns:[String], values:[Any], completion: UpdateResult?) { executeDBUpdate { (db) in do{ try FFDBManager.insert(table, columns, values: values, database: db) if let completion = completion { completion(true) } }catch{ if let completion = completion { completion(false) } debugPrintLog("failed: \(error.localizedDescription)") } } } } // MARK: Select extension FFDBSafeOperation { /// select column from table /// /// - Parameters: /// - table: table of FFObject.Type /// - columns: select columns,if columns is nil,return table all columns /// - condition: for example, "age > ? and address = ? " /// - values: use params query /// - type: The type of reception /// - callBack: return select objects public static func select<T:FFObject,U:Decodable>(table:T.Type, columns:[String]? = nil, where condition:String? = nil, values:[Any]? = nil, limit: String?=nil, return type:U.Type, completion: QueryResult?) { executeDBQuery { (db) in do{ let objects = try FFDBManager.select(table, columns, where: condition, values: values, order: nil, limit: limit, return: type, database: db) if let completion = completion { completion(objects) } }catch{ if let completion = completion { completion(nil) } debugPrintLog("failed: \(error.localizedDescription)") } } } /// select column from table /// /// - Parameters: /// - table: table of FFObject.Type /// - columns: select columns,if columns is nil,return table all columns /// - condition: for example, "age > ? and address = ? " /// - values: use params query /// - callBack: return select objects public static func select<T:FFObject>(table:T.Type, columns:[String]? = nil, where condition:String? = nil, values:[Any]? = nil, limit: String?=nil, completion:QueryResult? = nil) { executeDBQuery { (db) in do{ let objects = try FFDBManager.select(table, columns, where: condition, values: values, order: nil, limit: limit, database: db) if let completion = completion { completion(objects) } }catch{ if let completion = completion { completion(nil) } debugPrintLog("failed: \(error.localizedDescription)") } } } } // MARK: Update extension FFDBSafeOperation { /// update value of the table /// /// - Parameters: /// - table: table of FFObject.Type /// - setFormat: for example,you want to update Person name and age,you can set "name = ?,age = ?" /// - condition: for example, "age > ? and address = ? " /// - values: use params query public static func update(_ table:FFObject.Type, set setFormat:String, where condition:String?, values:[Any]? = nil, completion: UpdateResult?) { executeDBUpdate { (db) in do{ try FFDBManager.update(table, set: setFormat, where: condition, values: values, database: db) if let completion = completion { completion(true) } }catch{ if let completion = completion { completion(false) } debugPrintLog("failed: \(error.localizedDescription)") } } } } // MARK: Delete extension FFDBSafeOperation { /// delete row of the table /// /// - Parameters: /// - table: table of FFObject.Type /// - condition: for example, "age > ? and address = ? " /// - values: use params query public static func delete(_ table:FFObject.Type, where condition:String? = nil, values:[Any]? = nil, completion: UpdateResult?) { executeDBUpdate { (db) in do{ try FFDBManager.delete(table, where: condition, values: values, database: db) if let completion = completion { completion(true) } }catch{ if let completion = completion { completion(false) } debugPrintLog("failed: \(error.localizedDescription)") } } } } extension FFDBSafeOperation { public static func executeDBQuery(block:((FMDatabase)->())) { let queue = FMDatabaseQueue.init(url: FFDB.share.connection().databasePathURL()) queue?.inDatabase(block) } public static func executeDBUpdate(block:((FMDatabase)->())) { let queue = FMDatabaseQueue.init(url: FFDB.share.connection().databasePathURL()) queue?.inDatabase(block) } }
apache-2.0
c9a17fc49b1d34b65922007cf06de6fd
36.546798
109
0.460771
5.23489
false
false
false
false
JacopoMangiavacchi/KituraBotFrontendEchoSample
Sources/ResourcePathHandler.swift
1
3219
// // ResourcePathHandler.swift // ResourcePathHandler // // Created by Jacopo Mangiavacchi on 10/3/16. // Cloned by Kitura // import Foundation import Kitura import LoggerAPI class ResourcePathHandler { static private let separatorCharacter: Character = "/" static private let separator = String(separatorCharacter) static func getAbsolutePath(for path: String) -> String { var path = path if path.hasSuffix(separator) { path = String(path.characters.dropLast()) } // If we received a path with a tilde (~) in the front, expand it. path = NSString(string: path).expandingTildeInPath if isAbsolute(path: path) { return path } let fileManager = FileManager() let absolutePath = fileManager.currentDirectoryPath + separator + path if fileManager.fileExists(atPath: absolutePath) { return absolutePath } // the file does not exist on a path relative to the current working directory // return the path relative to the original repository directory guard let originalRepositoryPath = getOriginalRepositoryPath() else { return absolutePath } return originalRepositoryPath + separator + path } static private func getOriginalRepositoryPath() -> String? { // this file is at // <original repository directory>/Sources/Kitura/staticFileServer/ResourcePathHandler.swift // the original repository directory is four path components up let currentFilePath = #file var pathComponents = currentFilePath.characters.split(separator: separatorCharacter).map(String.init) let numberOfComponentsFromKituraRepositoryDirectoryToThisFile = 4 guard pathComponents.count >= numberOfComponentsFromKituraRepositoryDirectoryToThisFile else { Log.error("unable to get original repository path for \(currentFilePath)") return nil } pathComponents.removeLast(numberOfComponentsFromKituraRepositoryDirectoryToThisFile) pathComponents = removePackagesDirectory(pathComponents: pathComponents) return separator + pathComponents.joined(separator: separator) } static private func removePackagesDirectory(pathComponents: [String]) -> [String] { var pathComponents = pathComponents let numberOfComponentsFromKituraPackageToDependentRepository = 2 let packagesComponentIndex = pathComponents.endIndex - numberOfComponentsFromKituraPackageToDependentRepository if pathComponents.count > numberOfComponentsFromKituraPackageToDependentRepository && pathComponents[packagesComponentIndex] == "Packages" { pathComponents.removeLast(numberOfComponentsFromKituraPackageToDependentRepository) } return pathComponents } static private func isAbsolute(path: String) -> Bool { return path.hasPrefix(separator) } static private func isSeparator(_ string: String) -> Bool { return string == separator } }
apache-2.0
a9ff7db8c1695ffe011397efab39acdb
36
119
0.678161
5.727758
false
false
false
false
harungunaydin/Agenda-Master
Pods/StarWars/StarWars/StarWarsGLAnimator/StarWarsGLAnimator.swift
4
5012
// // Created by Artem Sidorenko on 9/14/15. // Copyright © 2015 Yalantis. All rights reserved. // // Licensed under the MIT license: http://opensource.org/licenses/MIT // Latest version can be found at https://github.com/Yalantis/StarWars.iOS // import UIKit import GLKit public class StarWarsGLAnimator: NSObject, UIViewControllerAnimatedTransitioning { public var duration: NSTimeInterval = 2 public var spriteWidth: CGFloat = 8 private var sprites: [BlowSprite] = [] private var glContext: EAGLContext! private var texture: ViewTexture! private var effect: GLKBaseEffect! private var fromView: UIView! private var glView: GLKView! private var displayLink: CADisplayLink! private var lastUpdateTime: NSTimeInterval? private var startTransitionTime: NSTimeInterval! private var transitionContext: UIViewControllerContextTransitioning! private var render: BlowSpriteRender! public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return self.duration } public func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView()! let fromView = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!.view let toView = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!.view containerView.addSubview(toView) containerView.sendSubviewToBack(toView) func randomFloatBetween(smallNumber: CGFloat, and bigNumber: CGFloat) -> Float { let diff = bigNumber - smallNumber return Float(CGFloat(arc4random()) / 100.0 % diff + smallNumber) } self.glContext = EAGLContext(API: .OpenGLES2) EAGLContext.setCurrentContext(glContext) glView = GLKView(frame: fromView.frame, context: glContext) glView.enableSetNeedsDisplay = true glView.delegate = self glView.opaque = false containerView.addSubview(glView) texture = ViewTexture() texture.setupOpenGL() texture.renderView(fromView) effect = GLKBaseEffect() let projectionMatrix = GLKMatrix4MakeOrtho(0, Float(texture.width), 0, Float(texture.height), -1, 1) effect.transform.projectionMatrix = projectionMatrix render = BlowSpriteRender(texture: texture, effect: effect) let size = CGSize(width: CGFloat(texture.width), height: CGFloat(texture.height)) let scale = UIScreen.mainScreen().scale let width = spriteWidth * scale let height = width for x in CGFloat(0).stride(through: size.width, by: width) { for y in CGFloat(0).stride(through: size.height, by: height) { let region = CGRect(x: x, y: y, width: width, height: height) var sprite = BlowSprite() sprite.slice(region, textureSize: size) sprite.moveVelocity = Vector2(x: randomFloatBetween(-100, and: 100), y: randomFloatBetween(-CGFloat(texture.height)*1.3/CGFloat(duration), and: -CGFloat(texture.height)/CGFloat(duration))) sprites.append(sprite) } } fromView.removeFromSuperview() self.transitionContext = transitionContext displayLink = CADisplayLink(target: self, selector: "displayLinkTick:") displayLink.paused = false displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) self.startTransitionTime = NSDate.timeIntervalSinceReferenceDate() } public func animationEnded(transitionCompleted: Bool) { self.displayLink.invalidate() self.displayLink = nil } func displayLinkTick(displayLink: CADisplayLink) { if let lastUpdateTime = lastUpdateTime { let timeSinceLastUpdate = NSDate.timeIntervalSinceReferenceDate() - lastUpdateTime self.lastUpdateTime = NSDate.timeIntervalSinceReferenceDate() for index in 0..<sprites.count { sprites[index].update(timeSinceLastUpdate) } } else { self.lastUpdateTime = NSDate.timeIntervalSinceReferenceDate() } self.glView.setNeedsDisplay() if NSDate.timeIntervalSinceReferenceDate() - self.startTransitionTime > self.duration { self.transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } } extension StarWarsGLAnimator: GLKViewDelegate { public func glkView(view: GLKView, drawInRect rect: CGRect) { glClearColor(0, 0, 0, 0) glClear(UInt32(GL_COLOR_BUFFER_BIT)) glBlendFunc(GLenum(GL_SRC_ALPHA), GLenum(GL_ONE_MINUS_SRC_ALPHA)) glEnable(GLenum(GL_BLEND)) render.render(self.sprites) } }
mit
84e7bd00c8b01090014f36dffa994e6b
39.088
204
0.671124
5.134221
false
false
false
false
Bathlamos/RTDC
ios/RTDC/Impl/iOSStorage.swift
1
854
// // IOSStorage.swift // RTDC // // Created by Nicolas Ménard on 2015-10-08. // Copyright © 2015 Clermont, Ermel, Fortin-Boulay, Legault & Ménard. All rights reserved. // import Foundation class IOSStorage: ImplStorage, ImplStorageProtocol { private let settings = NSUserDefaults.standardUserDefaults() private var INSTANCE: IOSStorage? = nil func get() -> IOSStorage { if INSTANCE == nil{ INSTANCE = IOSStorage() } return INSTANCE! } func addWithNSString(key: String!, withNSString data: String!) { settings.setObject(data, forKey: key) } func retrieveWithNSString(key: String!) -> String? { return settings.stringForKey(key) } func removeWithNSString(key: String!) { settings.removeObjectForKey(key) } }
mit
05ee95c3ce2480905fd7e471673c936b
22.666667
91
0.626322
4.171569
false
false
false
false
Eonil/EditorLegacy
Modules/EditorCommon/EditorCommon/FileUtility.swift
1
2946
// // FileUtility.swift // Precompilation // // Created by Hoon H. on 2015/01/12. // Copyright (c) 2015 Eonil. All rights reserved. // import Foundation public struct FileUtility { /// Tries to create a new file with autogenerated name. /// Returns URL to the created folder if succeeded. /// An error on failure. public static func createNewFileInFolder(parentFolderURL:NSURL) -> Resolution<NSURL> { assert(parentFolderURL.existingAsDirectoryFile) let u = parentFolderURL // let u2 = parentFolder // let u = u2.existingAsDirectoryFile ? u2 : u2.URLByDeletingLastPathComponent! let PREFIX = "New File" if let nm = generateUniqueUserFriendlyNameWithPrefixAtParentDirectoryAtURL(u, prefixString: PREFIX) { assert(u.URLByAppendingPathComponent("\(nm)", isDirectory: false).existingAsDataFile == false) assert(u.URLByAppendingPathComponent("\(nm)", isDirectory: true).existingAsDirectoryFile == false) let u1 = u.URLByAppendingPathComponent("\(nm)", isDirectory: false) var err = nil as NSError? let ok = NSData().writeToURL(u1, options: NSDataWritingOptions.DataWritingWithoutOverwriting, error: &err) if !ok { return Resolution.failure(err!) } else { return Resolution.success(u1) } } else { // No proper name could be made. Sigh... let inf = [NSLocalizedDescriptionKey: "There're too many files named \"\(PREFIX)...\". Please erase some before proceeding."] let err = NSError(domain: "", code: 0, userInfo: inf) return Resolution.failure(err) } } /// Tries to create a new empty directory with autogenerated name. /// Returns URL to the created folder if succeeded. /// An error on failure. public static func createNewFolderInFolder(parentFolderURL:NSURL) -> Resolution<NSURL> { assert(parentFolderURL.existingAsDirectoryFile) let u = parentFolderURL // let u2 = parentFolder // let u = u2.existingAsDirectoryFile ? u2 : u2.URLByDeletingLastPathComponent! // assert(u.existingAsDirectoryFile) let PREFIX = "New Folder" if let nm = generateUniqueUserFriendlyNameWithPrefixAtParentDirectoryAtURL(u, prefixString: PREFIX) { assert(u.URLByAppendingPathComponent("\(nm)", isDirectory: false).existingAsDataFile == false) assert(u.URLByAppendingPathComponent("\(nm)", isDirectory: true).existingAsDirectoryFile == false) let u1 = u.URLByAppendingPathComponent("\(nm)", isDirectory: true) var err = nil as NSError? let ok = NSFileManager.defaultManager().createDirectoryAtURL(u1, withIntermediateDirectories: true, attributes: nil, error: &err) if !ok { return Resolution.failure(err!) } else { return Resolution.success(u1) } } else { // No proper name could be made. Sigh... let inf = [NSLocalizedDescriptionKey: "There're too many files named \"\(PREFIX)...\". Please erase some before proceeding."] let err = NSError(domain: "", code: 0, userInfo: inf) return Resolution.failure(err) } } }
mit
a6a6ce1874821d15427f1f2da3529fa7
36.769231
132
0.722675
3.601467
false
false
false
false
gregomni/swift
test/AutoDiff/compiler_crashers_fixed/sr15891-inout-adjoint-param-idx.swift
7
1106
// RUN: %target-swift-frontend -emit-sil -verify %s // SR-15891: The parameter indices used for copying // inout tangent vectors were calculated improperly // in presence of other pullback parameters (e.g. // captures) import _Differentiation struct Foo { var bar : Float var baz : Float var name : String? } func outerFunc(doIterations : Int, value: inout Float) -> (Float, (Float) -> Float) { @differentiable(reverse, wrt: param) func innerFunc1(param: Float, other: Foo) -> Float { value += param * other.bar return value * param * 2.0 } @differentiable(reverse, wrt: param1) func loop(param1 : Float, other1: Foo) -> Float { var res : Float; res = 0.0 if (doIterations > 0) { res = innerFunc1(param: param1, other: other1) } return res } @differentiable(reverse) func curriedFunc(param: Float) -> Float { let other = Foo(bar: 7, baz: 9) return loop(param1: param, other1: other) } let valAndPullback = valueWithPullback(at: value, of: curriedFunc) return (value + valAndPullback.value, valAndPullback.pullback) }
apache-2.0
6765bd9fa41fbf3be84289ca270c91fa
25.333333
85
0.664557
3.511111
false
false
false
false
twostraws/HackingWithSwift
SwiftUI/project2/GuessTheFlag/ContentView.swift
1
2834
// // ContentView.swift // GuessTheFlag // // Created by Paul Hudson on 20/10/2021. // import SwiftUI struct ContentView: View { @State private var showingScore = false @State private var scoreTitle = "" @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Russia", "Spain", "UK", "US"].shuffled() @State private var correctAnswer = Int.random(in: 0...2) var body: some View { ZStack { RadialGradient(stops: [ .init(color: Color(red: 0.1, green: 0.2, blue: 0.45), location: 0.3), .init(color: Color(red: 0.76, green: 0.15, blue: 0.26), location: 0.3) ], center: .top, startRadius: 200, endRadius: 700) .ignoresSafeArea() VStack { Spacer() Text("Guess the Flag") .font(.largeTitle.bold()) .foregroundColor(.white) VStack(spacing: 15) { VStack { Text("Tap the flag of") .foregroundStyle(.secondary) .font(.subheadline.weight(.heavy)) Text(countries[correctAnswer]) .font(.largeTitle.weight(.semibold)) } ForEach(0..<3) { number in Button { flagTapped(number) } label: { Image(countries[number]) .renderingMode(.original) .clipShape(Capsule()) .shadow(radius: 5) } } } .frame(maxWidth: .infinity) .padding(.vertical, 20) .background(.regularMaterial) .clipShape(RoundedRectangle(cornerRadius: 20)) Spacer() Spacer() Text("Score: ???") .foregroundColor(.white) .font(.title.bold()) Spacer() } .padding() } .alert(scoreTitle, isPresented: $showingScore) { Button("Continue", action: askQuestion) } message: { Text("Your score is ???") } } func flagTapped(_ number: Int) { if number == correctAnswer { scoreTitle = "Correct" } else { scoreTitle = "Wrong" } showingScore = true } func askQuestion() { countries.shuffle() correctAnswer = Int.random(in: 0...2) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
unlicense
532cd7025effa4af1a04e2cc2a5586b2
28.520833
150
0.447777
4.954545
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-422/SafeRide/Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/OFB.swift
6
1853
// // OFB.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 08/03/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // // Output Feedback (OFB) // struct OFBModeEncryptGenerator: BlockModeGenerator { typealias Element = Array<UInt8> private let iv: Element private let inputGenerator: AnyGenerator<Element> private let cipherOperation: CipherOperationOnBlock private var prevCiphertext: Element? init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock, inputGenerator: AnyGenerator<Array<UInt8>>) { self.iv = iv self.cipherOperation = cipherOperation self.inputGenerator = inputGenerator } mutating func next() -> Element? { guard let plaintext = inputGenerator.next(), let ciphertext = cipherOperation(block: prevCiphertext ?? iv) else { return nil } self.prevCiphertext = ciphertext return xor(plaintext, ciphertext) } } struct OFBModeDecryptGenerator: BlockModeGenerator { typealias Element = Array<UInt8> private let iv: Element private let inputGenerator: AnyGenerator<Element> private let cipherOperation: CipherOperationOnBlock private var prevCiphertext: Element? init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock, inputGenerator: AnyGenerator<Element>) { self.iv = iv self.cipherOperation = cipherOperation self.inputGenerator = inputGenerator } mutating func next() -> Element? { guard let ciphertext = inputGenerator.next(), let decrypted = cipherOperation(block: self.prevCiphertext ?? iv) else { return nil } let plaintext = xor(decrypted, ciphertext) self.prevCiphertext = decrypted return plaintext } }
gpl-3.0
d2887b9bff46d8cb6118ab58b5c8eebc
27.953125
113
0.671706
4.938667
false
false
false
false
Trevi-Swift/Trevi-sys
Sources/Work.swift
1
2441
// // Work.swift // Trevi // // Created by JangTaehwan on 2016. 2. 25.. // Copyright © 2016 Trevi Community. All rights reserved. // import Libuv import Foundation /** Provides a threadpool on Tcp.onConnection and Stream.onRead events. */ public class Work { public let workRequest : uv_work_ptr init(){ self.workRequest = uv_work_ptr.alloc(1) } deinit{ self.workRequest.dealloc(1) } public func setWorkData(dataPtr : void_ptr) { self.workRequest.memory.data = dataPtr } } // Work static functions. extension Work { struct connectionInfo { var handle : uv_stream_ptr var status : Int32 } // Not implemented on Trevi. // Consider using between Thread and Process server model. public static var onConnection : uv_connection_cb = { (handle, status) in let work : Work = Work() let info = UnsafeMutablePointer<connectionInfo>.alloc(1) info.memory.handle = handle info.memory.status = status work.workRequest.memory.data = void_ptr(info) uv_queue_work( uv_default_loop(), work.workRequest, workConnection, afterWork ) } struct readInfo { var handle : uv_stream_ptr var nread : Int var buffer : uv_buf_const_ptr } public static var onRead : uv_read_cb = { (handle, nread, buffer) in let work : Work = Work() let info = UnsafeMutablePointer<readInfo>.alloc(1) info.memory.handle = handle info.memory.nread = nread info.memory.buffer = buffer uv_queue_work( uv_default_loop(), work.workRequest, workRead, afterWork ) } } // Work static callbacks. extension Work { public static var workConnection : uv_work_cb = { (handle) in let info = UnsafeMutablePointer<connectionInfo>(handle.memory.data) Tcp.onConnection(info.memory.handle, info.memory.status) info.dealloc(1) } public static var workRead : uv_work_cb = { (handle) in let info = UnsafeMutablePointer<readInfo>(handle.memory.data) Tcp.onRead(info.memory.handle, info.memory.nread, info.memory.buffer) info.dealloc(1) } public static var afterWork : uv_after_work_cb = { (handle, status) in handle.dealloc(1) } }
apache-2.0
ef6c0ad7d1cd1684a1dda9fb2e8315ce
22.921569
87
0.60041
4
false
false
false
false
alvarorgtr/swift_data_structures
DataStructures/AVLTreeMap/AVLTreeIterator.swift
1
898
// // Created by alvaro on 14/10/16. // import Foundation internal struct AVLTreeIterator<Key: Comparable, Value, Iterable>: IteratorProtocol { internal typealias Element = Iterable private var index: AVLTreeIndex<Key, Value> private var iterableExtractor: (AVLTreeNode<Key, Value>) -> Element init(tree: AVLTreeMap<Key, Value>, iteratedOver iterator: @escaping (AVLTreeNode<Key, Value>) -> Element) { index = AVLTreeIndex<Key, Value>(tree: tree) iterableExtractor = iterator } internal mutating func next() -> Element? { if let node = index.node { index = index.next() return iterableExtractor(node) } else { return nil } } public static func defaultIterator(forTree tree: AVLTreeMap<Key, Value>) -> AVLTreeIterator<Key, Value, (Key, Value)> { return AVLTreeIterator<Key, Value, (Key, Value)>(tree: tree, iteratedOver: { (node) in (node.key, node.value) }) } }
gpl-3.0
f9e07ea13f939f7bf8ee8e541c7c22b9
28.933333
120
0.713808
3.414449
false
false
false
false
OscarSwanros/swift
test/Serialization/search-paths-relative.swift
14
1730
// RUN: %empty-directory(%t) // RUN: %empty-directory(%t/secret) // RUN: %target-swift-frontend -emit-module -o %t/secret %S/Inputs/struct_with_operators.swift // RUN: %empty-directory(%t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule) // RUN: %target-swift-frontend -emit-module -o %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/%target-swiftmodule-name %S/Inputs/alias.swift -module-name has_alias // RUN: cd %t/secret && %target-swiftc_driver -emit-module -o %t/has_xref.swiftmodule -I . -F ../Frameworks -parse-as-library %S/Inputs/has_xref.swift %S/../Inputs/empty.swift -Xfrontend -serialize-debugging-options -Xcc -ivfsoverlay -Xcc %S/../Inputs/unextended-module-overlay.yaml -Xcc -DDUMMY // RUN: %target-swift-frontend %s -typecheck -I %t // Check the actual serialized search paths. // RUN: llvm-bcanalyzer -dump %t/has_xref.swiftmodule > %t/has_xref.swiftmodule.txt // RUN: %FileCheck %s < %t/has_xref.swiftmodule.txt // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/has_xref.swiftmodule.txt // XFAIL: linux import has_xref numeric(42) // CHECK-LABEL: <OPTIONS_BLOCK // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-working-directory' // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '{{.+}}/secret' // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-DDUMMY' // CHECK: </OPTIONS_BLOCK> // CHECK-LABEL: <INPUT_BLOCK // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1 op1=0/> blob data = '{{.+}}/secret/../Frameworks' // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=0 op1=0/> blob data = '{{.+}}/secret/.' // CHECK: </INPUT_BLOCK> // NEGATIVE-NOT: '.' // NEGATIVE-NOT: '../Frameworks' // This should be filtered out. // NEGATIVE-NOT: -ivfsoverlay{{.*}}unextended-module-overlay.yaml
apache-2.0
0f2a9005124ece1d3a641a90ab3be98b
48.428571
295
0.683815
2.977625
false
false
false
false
satyamexilant/ExilantHome
ExilantHome/ExilantHome/ExilantHome/SourceFiles/ViewControllers/LoginViewController.swift
1
2142
// // ViewController.swift // ExilantHome // // Created by medidi vv satyanarayana murty on 20/12/16. // Copyright © 2016 Medidi V V Satyanarayana Murty. All rights reserved. // import UIKit class LoginViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var userName: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var login: UIButton! override func viewDidLoad() { super.viewDidLoad() configure(userName) configure(password) userName.becomeFirstResponder() userName.addTarget(self, action:#selector(LoginViewController.textDidChange(text:)) , for: UIControlEvents.editingChanged) userName.delegate = self password.delegate = self password.addTarget(self, action:#selector(LoginViewController.textDidChange(text:)) , for: UIControlEvents.editingChanged) } /* - whenever text changes in username or password notifies to this function. - Enables login button true or false according to validation. */ public func textDidChange(text:UITextField) { guard let name = userName.text , name.hasSuffix("@exilant.com"), let pwd = password.text , pwd.characters.count > 6 else { login.isEnabled = false login.alpha = 0.5 return } login.isEnabled = true login.alpha = 1 } @IBAction func loginUser(_ sender: UIButton) { // service to check username and password if true move to nextview controller else show alert performSegue(withIdentifier: "Home", sender:self) } private func configure(_ view: UIView) { view.layer.cornerRadius = 4 view.layer.borderColor = UIColor(colorLiteralRed: 32/250, green: 115/250, blue: 176/250, alpha: 1).cgColor view.layer.borderWidth = 1 } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
gpl-3.0
0cde63777ee7be7d881d544625ed7a3d
29.585714
130
0.624942
4.967517
false
false
false
false
CoolCodeFactory/Antidote
AntidoteArchitectureExample/PageBasedFlowCoordinator.swift
1
1777
// // Page-BasedFlowCoordinator.swift // AntidoteArchitectureExample // // Created by Dmitriy Utmanov on 16/09/16. // Copyright © 2016 Dmitry Utmanov. All rights reserved. // import UIKit class PageBasedFlowCoordinator: ModalCoordinatorProtocol { var childCoordinators: [CoordinatorProtocol] = [] weak var navigationController: NavigationViewController! var closeHandler: () -> () = { fatalError() } let viewControllersFactory = PageBasedViewControllersFactory() weak var pageBasedViewController: PageBasedViewController! weak var presentingViewController: UIViewController! required init(presentingViewController: UIViewController) { self.presentingViewController = presentingViewController } func start(animated: Bool) { pageBasedViewController = viewControllersFactory.pageBasedViewController() let navigationController = NavigationViewController(rootViewController: pageBasedViewController) let userFlowCoordinator = UserPageBasedFlowCoordinator(pageViewController: pageBasedViewController) addChildCoordinator(userFlowCoordinator) userFlowCoordinator.closeHandler = { [unowned userFlowCoordinator] in userFlowCoordinator.finish(animated: animated) self.removeChildCoordinator(userFlowCoordinator) self.closeHandler() } userFlowCoordinator.start(animated: animated) presentingViewController.present(navigationController, animated: animated, completion: nil) self.navigationController = navigationController } func finish(animated: Bool) { removeAllChildCoordinators() navigationController.dismiss(animated: animated, completion: nil) } }
mit
806d928832cbb12aaa0b21fee376ba30
33.823529
107
0.734234
6
false
false
false
false
18775134221/SwiftBase
SwiftTest/SwiftTest/Classes/tools/Extention/UIColor-Extension.swift
2
2556
import UIKit extension UIColor { // 如果需要高频率使用一个实例对象,可以使用拓展 static let myOwnColor = UIColor(red: 23_3.0/255, green: 23_4.0/255, blue: 23_5.0/255, alpha: 1) // 便利构造器 convenience init(r : CGFloat, g : CGFloat, b : CGFloat) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0) } // 获取随机颜色 class func randomColor() -> UIColor { return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256))) } class func RGB_Float(r:CGFloat,g:CGFloat,b:CGFloat) -> UIColor? { return UIColor.init(red: r, green: g, blue: b, alpha: 1.0) } class func RGB(r:Int,g:Int,b:Int) -> UIColor? { return UIColor.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: 1.0) } func alpha(_ alpha: CGFloat) -> UIColor { return self.withAlphaComponent(alpha) } // MARK: - 根据十六进制获取颜色 class func RGB(_ rgbValue: String) -> UIColor? { /// 支持格式包括: #ff21af64 #21af64 0x21af64 if (rgbValue.hasPrefix("#") || (rgbValue.hasPrefix("0x"))) { let mutStr = (rgbValue as NSString).mutableCopy() as! NSMutableString if (rgbValue.hasPrefix("#")) { mutStr.deleteCharacters(in: NSRange.init(location: 0, length: 1)) } else { mutStr.deleteCharacters(in: NSRange.init(location: 0, length: 2)) } if (mutStr.length == 6) { mutStr.insert("ff", at: 0) } let aStr = mutStr.substring(with: NSRange.init(location: 0, length: 2)) let rStr = mutStr.substring(with: NSRange.init(location: 2, length: 2)) let gStr = mutStr.substring(with: NSRange.init(location: 4, length: 2)) let bStr = mutStr.substring(with: NSRange.init(location: 6, length: 2)) let alpha = aStr.hexValue() let red = rStr.hexValue() let green = gStr.hexValue() let blue = bStr.hexValue() return UIColor.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha) / 255.0) }else{ assert(false, "16进制字符串转UIColor:格式不支持") return nil } } }
apache-2.0
13d1c71d3c607bda94aa6bc28e0e3357
35.848485
149
0.548109
3.550365
false
false
false
false
aotian16/HideKeyboardButton
HideKeyboardButton/ViewController.swift
1
5471
// // ViewController.swift // HideKeyboardButton // // Created by 童进 on 15/9/21. // Copyright © 2015年 qefee. All rights reserved. // import UIKit class ViewController: UIViewController { var hideKeyboardButton: UIButton? let hideKeyboardButtonWidth:CGFloat = 40 let hideKeyboardButtonHeight:CGFloat = 30 var keyboardAnimationDuration: Double = 0 var keyboardAnimationCurve: UInt = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // add keyboard observer NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardDidShow:"), name:UIKeyboardDidShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardDidHide:"), name:UIKeyboardDidHideNotification, object: nil) } deinit { // remove keyboard observer NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** keyboardDidShow - parameter notification: notification */ func keyboardDidShow(notification: NSNotification) { let info = notification.userInfo! keyboardAnimationDuration = info[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue keyboardAnimationCurve = UInt(info[UIKeyboardAnimationCurveUserInfoKey]!.intValue) let frame = getKeyboardFrame(notification) if frame.h == 0 { return } var button: UIButton! if let btn = hideKeyboardButton { btn.removeFromSuperview() } button = UIButton(frame: CGRectMake(frame.w - hideKeyboardButtonWidth, frame.y - hideKeyboardButtonHeight, hideKeyboardButtonWidth, hideKeyboardButtonHeight)) button.setTitle("hide", forState: UIControlState.Normal) button.backgroundColor = UIColor(red: 173.0/255.0, green: 181.0/255.0, blue: 189.0/255.0, alpha: 1) button.addTarget(self, action: "onHideKeyboardButtonClick:", forControlEvents: UIControlEvents.TouchUpInside) button.alpha = 0 hideKeyboardButton = button let origCenter = button.center let newCenter = CGPointMake(origCenter.x, origCenter.y + hideKeyboardButtonHeight) button.center = newCenter self.view.addSubview(button) UIView.animateWithDuration(keyboardAnimationDuration, delay: 0, options: UIViewAnimationOptions(rawValue: keyboardAnimationCurve), animations: { () -> Void in button.alpha = 0.75 button.center = origCenter }) { (finish) -> Void in print("animate state = \(finish)") } } /** getKeyboardFrame - parameter notification: notification - returns: frame */ private func getKeyboardFrame(notification: NSNotification) -> (x:CGFloat,y:CGFloat,w:CGFloat,h:CGFloat) { let info = notification.userInfo! let value: AnyObject = info[UIKeyboardFrameEndUserInfoKey]! let rawFrame = value.CGRectValue let keyboardFrame = view.convertRect(rawFrame, fromView: nil) let x = keyboardFrame.origin.x let y = keyboardFrame.origin.y let w = keyboardFrame.width let h = keyboardFrame.height return (x,y,w,h) } var hidingKeyboardFlag: Bool = false /** onHideKeyboardButtonClick - parameter sender: sender */ func onHideKeyboardButtonClick(sender: UIButton) { hidingKeyboardFlag = true if let btn = hideKeyboardButton { UIView.animateWithDuration(keyboardAnimationDuration, delay: 0, options: UIViewAnimationOptions(rawValue: keyboardAnimationCurve), animations: { () -> Void in btn.alpha = 0 btn.center = CGPointMake(btn.center.x, UIScreen.mainScreen().applicationFrame.height - self.hideKeyboardButtonHeight/2) }) { (finish) -> Void in btn.removeFromSuperview() print("animate state = \(finish)") } } self.view.endEditing(false) } /** keyboardDidHide - parameter notification: notification */ func keyboardDidHide(notification: NSNotification) { } /** keyboardWillShow - parameter notification: notification */ func keyboardWillShow(notification: NSNotification) { } /** keyboardWillHide - parameter notification: notification */ func keyboardWillHide(notification: NSNotification) { if hidingKeyboardFlag { hidingKeyboardFlag = false return } if let btn = hideKeyboardButton { btn.alpha = 0 btn.removeFromSuperview() } } }
mit
cb97627f6aa8abe5d4e3a8ab19369f82
31.52381
170
0.635432
5.644628
false
false
false
false
pascalbros/PAPermissions
PAPermissions/Classes/Checks/PACameraPermissionsCheck.swift
1
1379
// // PACameraPermissionsCheck.swift // PAPermissionsApp // // Created by Pasquale Ambrosini on 06/09/16. // Copyright © 2016 Pasquale Ambrosini. All rights reserved. // import AVFoundation import UIKit public class PACameraPermissionsCheck: PAPermissionsCheck { var mediaType = AVMediaType.video public override func checkStatus() { let currentStatus = self.status if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) { let authStatus = AVCaptureDevice.authorizationStatus(for: mediaType) switch authStatus { case .authorized: self.status = .enabled case .denied: self.status = .disabled case .notDetermined: self.status = .disabled default: self.status = .unavailable } }else{ self.status = .unavailable } if self.status != currentStatus { self.updateStatus() } } public override func defaultAction() { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) { let authStatus = AVCaptureDevice.authorizationStatus(for: mediaType) if authStatus == .denied { self.openSettings() }else{ AVCaptureDevice.requestAccess(for: mediaType, completionHandler: { (result) in if result { self.status = .enabled }else{ self.status = .disabled } }) self.updateStatus(); } } } }
mit
ddf81af4a5c5579ec2b28d62a48bafd0
22.758621
95
0.711176
3.994203
false
false
false
false
Yurssoft/QuickFile
Carthage/Checkouts/LNPopupController/LNPopupControllerExample/LNPopupControllerExample/DemoAlbumTableViewController.swift
1
4149
// // DemoAlbumTableViewController.swift // LNPopupControllerExample // // Created by Leo Natan on 8/7/15. // Copyright © 2015 Leo Natan. All rights reserved. // import UIKit import LNPopupController class DemoAlbumTableViewController: UITableViewController { var images: [UIImage] var titles: [String] var subtitles: [String] required init?(coder aDecoder: NSCoder) { images = [] titles = [] subtitles = [] super.init(coder:aDecoder) } override func viewDidLoad() { tabBarController?.view.tintColor = view.tintColor super.viewDidLoad() for idx in 1...self.tableView(tableView, numberOfRowsInSection: 0) { images += [UIImage(named: "genre\(idx)")!] titles += [LoremIpsum.title()] subtitles += [LoremIpsum.sentence()] } tableView.backgroundColor = LNRandomDarkColor() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if ProcessInfo.processInfo.operatingSystemVersion.majorVersion >= 10 { navigationController?.navigationBar.isTranslucent = false } if ProcessInfo.processInfo.operatingSystemVersion.majorVersion <= 10 { let insets = UIEdgeInsetsMake(topLayoutGuide.length, 0, bottomLayoutGuide.length, 0) tableView.contentInset = insets tableView.scrollIndicatorInsets = insets } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.setContentOffset(CGPoint(x: 0, y: -tableView.contentInset.top), animated: false) } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 2 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let separator = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 1 / UIScreen.main.scale)) separator.backgroundColor = UIColor.white.withAlphaComponent(0.4) separator.autoresizingMask = .flexibleWidth let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 2)) view.addSubview(separator) return view } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MusicCell", for: indexPath) cell.imageView?.image = images[(indexPath as NSIndexPath).row] cell.textLabel?.text = titles[(indexPath as NSIndexPath).row] cell.textLabel?.textColor = UIColor.white cell.detailTextLabel?.text = subtitles[(indexPath as NSIndexPath).row] cell.detailTextLabel?.textColor = UIColor.white let selectionView = UIView() selectionView.backgroundColor = UIColor.white.withAlphaComponent(0.45) cell.selectedBackgroundView = selectionView return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let popupContentController = storyboard?.instantiateViewController(withIdentifier: "DemoMusicPlayerController") as! DemoMusicPlayerController popupContentController.songTitle = titles[(indexPath as NSIndexPath).row] popupContentController.albumTitle = subtitles[(indexPath as NSIndexPath).row] popupContentController.albumArt = images[(indexPath as NSIndexPath).row] popupContentController.popupItem.accessibilityHint = NSLocalizedString("Double Tap to Expand the Mini Player", comment: "") tabBarController?.popupContentView.popupCloseButton.accessibilityLabel = NSLocalizedString("Dismiss Now Playing Screen", comment: "") tabBarController?.presentPopupBar(withContentViewController: popupContentController, animated: true, completion: nil) tabBarController?.popupBar.tintColor = UIColor(white: 38.0 / 255.0, alpha: 1.0) tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.backgroundColor = UIColor.clear } }
mit
05fef6193d2f1efc1c5db31861848eb2
35.069565
143
0.751929
4.5038
false
false
false
false
GuilhermeMachado/iOSArchitectures
MVP/MVP/Presenter/ProdutcsPresenter.swift
1
3033
// // ProdutcsPresenter.swift // MVP // // Created by Guilherme Machado on 8/26/17. // Copyright © 2017 Guilherme Machado. All rights reserved. // import Foundation import UIKit protocol ProductsViewPresenter { func fetchProducts() } class ProductsPresenter: NSObject { var view: ProductsView var isSearching: Bool = false var dataSource: [Product] = [] { didSet { view.reloadTableView() } } init(view: ProductsView) { self.view = view } } extension ProductsPresenter: ProductsViewPresenter { func fetchProducts() { APIManager.fetchProducts { (products) in dataSource = products } } } extension ProductsPresenter: ProductsViewDelegate { func searchBarDelegateForProductsView() -> UISearchBarDelegate { return self } func tableViewDataSourceForProductsView() -> UITableViewDataSource { return self } } extension ProductsPresenter: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let product: Product = dataSource[indexPath.row] if product.type == .featured { let cell: FeaturedCell = tableView.dequeueReusableCell(withIdentifier: "featuredCell", for: indexPath) as! FeaturedCell cell.set(product: product) return cell } let cell: NormalProductcell = tableView.dequeueReusableCell(withIdentifier: "normalCell", for: indexPath) as! NormalProductcell cell.set(product: product) return cell } } extension ProductsPresenter: UISearchBarDelegate { func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { view.endEditing() isSearching = false APIManager.fetchProducts { (products) in dataSource = products } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { isSearching = true if let searchTerm = searchBar.text { if searchTerm.characters.count < 3 { let alert = UIAlertController(title: "Busca inválida", message: "A busca deve conter mais de três caracteres", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) view.show(viewController: alert) } else { dataSource = dataSource.filter { $0.name == searchTerm } } } } }
mit
c0f89f3ef1a8a7b67b47abd51123a08e
23.435484
135
0.559076
5.590406
false
false
false
false
VadimPavlov/SMVC
PerfectProject/Classes/Base/EventsViewController.swift
1
4215
// // EventsViewController.swift // PerfectProject // // Created by Vadim Pavlov on 10/7/16. // Copyright © 2016 Vadim Pavlov. All rights reserved. // import UIKit typealias ViewEventAction = () -> Void struct ViewEvents { let onDidLoad: ViewEventAction? let onWillLayout: ViewEventAction? let onDidLayout: ViewEventAction? let onWillAppear: ViewEventAction? let onDidAppear: ViewEventAction? let onWillDisappear: ViewEventAction? let onDidDisappear: ViewEventAction? init(onDidLoad: ViewEventAction? = nil, onWillLayout: ViewEventAction? = nil, onDidLayout: ViewEventAction? = nil, onWillAppear: ViewEventAction? = nil, onDidAppear: ViewEventAction? = nil, onWillDisappear: ViewEventAction? = nil, onDidDisappear: ViewEventAction? = nil) { self.onDidLoad = onDidLoad self.onWillLayout = onWillLayout self.onDidLayout = onDidLayout self.onWillAppear = onWillAppear self.onDidAppear = onDidAppear self.onWillDisappear = onWillDisappear self.onDidDisappear = onDidDisappear } static func onDidLoad(_ action: @escaping ViewEventAction) -> ViewEvents { return ViewEvents(onDidLoad: action) } } class EventsViewController: UIViewController { var events: ViewEvents? override func viewDidLoad() { super.viewDidLoad() self.events?.onDidLoad?() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.events?.onWillLayout?() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.events?.onDidLayout?() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.events?.onWillAppear?() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.events?.onDidAppear?() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.events?.onWillDisappear?() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.events?.onDidDisappear?() } } class EventsTableViewController: UITableViewController { var events: ViewEvents? override func viewDidLoad() { super.viewDidLoad() self.events?.onDidLoad?() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.events?.onWillLayout?() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.events?.onDidLayout?() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.events?.onWillAppear?() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.events?.onDidAppear?() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.events?.onWillDisappear?() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.events?.onDidDisappear?() } } class EventsCollectionViewController: UICollectionViewController { var events: ViewEvents? override func viewDidLoad() { super.viewDidLoad() self.events?.onDidLoad?() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.events?.onWillLayout?() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.events?.onDidLayout?() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.events?.onWillAppear?() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.events?.onDidAppear?() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.events?.onWillDisappear?() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.events?.onDidDisappear?() } }
mit
b3cd7d94d3890d7fb76579048ba232d7
30.214815
276
0.670147
4.928655
false
false
false
false
luckymore0520/leetcode
ValidParentheses.playground/Contents.swift
1
1331
//: Playground - noun: a place where people can play import UIKit class Stack<T>{ var stack: [T] init(){ stack = [T]() } func push(element:T){ stack.append(element) } func pop() -> T?{ if (stack.isEmpty) { return nil; } return stack.removeLast() } func isEmpty() -> Bool { return stack.isEmpty; } func peek() -> T? { return stack.last } func size() -> Int { return stack.count; } } class Solution { let left = ["(".characters.first!,"[".characters.first!,"{".characters.first!] let right = [")".characters.first!,"]".characters.first!,"}".characters.first!] func isValid(_ s: String) -> Bool { let stack = Stack<Character>() for character in s.characters { if left.contains(character) { stack.push(element: character) } else if let rightIndex = right.index(of: character) { let leftPair = left[rightIndex] let top = stack.pop(); if (leftPair != top) { return false } } else { return false } } return stack.isEmpty() } } let solution = Solution() solution.isValid("[]()([])")
mit
147e712f7a3c8a8345f79c945cbb6637
23.666667
83
0.49136
4.321429
false
false
false
false
zhou9734/ZCJImagePicker
ZCJImagePicker/SelectedPhotoCell.swift
1
2488
// // SelectedPhotoCell.swift // ZCJImagePicker // // Created by zhoucj on 16/8/28. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit import AssetsLibrary protocol SelectedPhotoCellDelegate: NSObjectProtocol{ func deletePhoto(cell: SelectedPhotoCell) } class SelectedPhotoCell: UICollectionViewCell { var delegate: SelectedPhotoCellDelegate? var alsseet: ALAsset?{ didSet{ imageView.image = UIImage(CGImage: alsseet!.thumbnail().takeUnretainedValue()) } } var isLast = false{ didSet{ if isLast{ imageView.image = UIImage(named: "compose_pic_add") } deleteBtn.hidden = isLast } } var image: UIImage?{ didSet{ imageView.image = image } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ contentView.addSubview(imageView) contentView.addSubview(deleteBtn) } private lazy var imageView = UIImageView() private lazy var deleteBtn: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "camera_tag_delete_right"), forState: .Normal) btn.addTarget(self, action: Selector("selectPhoto"), forControlEvents: .TouchUpInside) return btn }() @objc private func selectPhoto(){ delegate?.deletePhoto(self) } override func layoutSubviews() { imageView.translatesAutoresizingMaskIntoConstraints = false deleteBtn.translatesAutoresizingMaskIntoConstraints = false let dict = ["imageView": imageView, "deleteBtn": deleteBtn] var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[imageView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[imageView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict) cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[deleteBtn(30)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[deleteBtn(30)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict) contentView.addConstraints(cons) } }
mit
c73a8b34d7458b45d140d4849260d12c
36.651515
162
0.666398
4.901381
false
false
false
false
colemancda/Hakawai
HakawaiDemo/HakawaiDemo/SimpleChooserView.swift
2
2068
// // SimpleChooserView.swift // HakawaiDemo // // Created by Austin Zheng on 2/17/15. // Copyright (c) 2015 LinkedIn. All rights reserved. // import Foundation import UIKit class SimpleChooserView : UIView, UIPickerViewDataSource, UIPickerViewDelegate, HKWChooserViewProtocol { weak var delegate: HKWCustomChooserViewDelegate? = nil var borderMode : HKWChooserBorderMode = .Top // Protocol factory method @objc(chooserViewWithFrame:delegate:) class func chooserViewWithFrame(frame: CGRect, delegate: HKWCustomChooserViewDelegate) -> AnyObject { let item = NSBundle.mainBundle().loadNibNamed("SimpleChooserView", owner: nil, options: nil)[0] as SimpleChooserView item.delegate = delegate item.frame = frame item.setNeedsLayout() return item } override func awakeFromNib() { super.awakeFromNib() pickerView.dataSource = self pickerView.delegate = self } required init(coder: NSCoder) { super.init(coder: coder) } func becomeVisible() { hidden = false setNeedsLayout() } func resetScrollPositionAndHide() { // Don't do anything hidden = true } @IBOutlet weak var pickerView: UIPickerView! @IBAction func chooseButtonTapped(sender: UIButton) { let idx = pickerView.selectedRowInComponent(0) delegate?.modelObjectSelectedAtIndex(idx) } // Reload the data func reloadData() { pickerView.reloadComponent(0) } // MARK: Picker view delegate and data source func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { let model = delegate?.modelObjectForIndex(row) as HKWMentionsEntityProtocol return model.entityName() } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return delegate?.numberOfModelObjects() ?? 0 } }
apache-2.0
3d9b679c19140d42ebb71f4ac2700c26
27.328767
124
0.680368
4.809302
false
false
false
false
biohazardlover/NintendoEverything
Pods/SwiftSoup/Sources/Attributes.swift
1
7853
// // Attributes.swift // SwifSoup // // Created by Nabil Chatbi on 29/09/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation /** * The attributes of an Element. * <p> * Attributes are treated as a map: there can be only one value associated with an attribute key/name. * </p> * <p> * Attribute name and value comparisons are <b>case sensitive</b>. By default for HTML, attribute names are * normalized to lower-case on parsing. That means you should use lower-case strings when referring to attributes by * name. * </p> * * */ open class Attributes: NSCopying { open static var dataPrefix: String = "data-" var attributes: OrderedDictionary<String, Attribute> = OrderedDictionary<String, Attribute>() // linked hash map to preserve insertion order. // null be default as so many elements have no attributes -- saves a good chunk of memory public init() {} /** Get an attribute value by key. @param key the (case-sensitive) attribute key @return the attribute value if set; or empty string if not set. @see #hasKey(String) */ open func get(key: String) -> String { let attr: Attribute? = attributes.get(key:key) return attr != nil ? attr!.getValue() : "" } /** * Get an attribute's value by case-insensitive key * @param key the attribute name * @return the first matching attribute value if set; or empty string if not set. */ open func getIgnoreCase(key: String )throws -> String { try Validate.notEmpty(string: key) for attrKey in (attributes.keySet()) { if attrKey.equalsIgnoreCase(string: key) { return attributes.get(key: attrKey)!.getValue() } } return "" } /** Set a new attribute, or replace an existing one by key. @param key attribute key @param value attribute value */ open func put(_ key: String, _ value: String) throws { let attr = try Attribute(key: key, value: value) put(attribute: attr) } /** Set a new boolean attribute, remove attribute if value is false. @param key attribute key @param value attribute value */ open func put(_ key: String, _ value: Bool) throws { if (value) { try put(attribute: BooleanAttribute(key: key)) } else { try remove(key: key) } } /** Set a new attribute, or replace an existing one by key. @param attribute attribute */ open func put(attribute: Attribute) { attributes.put(value: attribute, forKey:attribute.getKey()) } /** Remove an attribute by key. <b>Case sensitive.</b> @param key attribute key to remove */ open func remove(key: String)throws { try Validate.notEmpty(string: key) attributes.remove(key: key) } /** Remove an attribute by key. <b>Case insensitive.</b> @param key attribute key to remove */ open func removeIgnoreCase(key: String ) throws { try Validate.notEmpty(string: key) for attrKey in attributes.keySet() { if (attrKey.equalsIgnoreCase(string: key)) { attributes.remove(key: attrKey) } } } /** Tests if these attributes contain an attribute with this key. @param key case-sensitive key to check for @return true if key exists, false otherwise */ open func hasKey(key: String) -> Bool { return attributes.containsKey(key: key) } /** Tests if these attributes contain an attribute with this key. @param key key to check for @return true if key exists, false otherwise */ open func hasKeyIgnoreCase(key: String) -> Bool { for attrKey in attributes.keySet() { if (attrKey.equalsIgnoreCase(string: key)) { return true } } return false } /** Get the number of attributes in this set. @return size */ open func size() -> Int { return attributes.count//TODO: check retyrn right size } /** Add all the attributes from the incoming set to this set. @param incoming attributes to add to these attributes. */ open func addAll(incoming: Attributes?) { guard let incoming = incoming else { return } if (incoming.size() == 0) { return } attributes.putAll(all: incoming.attributes) } // open func iterator() -> IndexingIterator<Array<Attribute>> { // if (attributes.isEmpty) { // let args: [Attribute] = [] // return args.makeIterator() // } // return attributes.orderedValues.makeIterator() // } /** Get the attributes as a List, for iteration. Do not modify the keys of the attributes via this view, as changes to keys will not be recognised in the containing set. @return an view of the attributes as a List. */ open func asList() -> Array<Attribute> { var list: Array<Attribute> = Array(/*attributes.size()*/) for entry in attributes.orderedValues { list.append(entry) } return list } /** * Retrieves a filtered view of attributes that are HTML5 custom data attributes; that is, attributes with keys * starting with {@code data-}. * @return map of custom data attributes. */ //Map<String, String> open func dataset() -> Dictionary<String, String> { var dataset = Dictionary<String, String>() for attribute in attributes { let attr = attribute.1 if(attr.isDataAttribute()) { let key = attr.getKey().substring(Attributes.dataPrefix.count) dataset[key] = attribute.1.getValue() } } return dataset } /** Get the HTML representation of these attributes. @return HTML @throws SerializationException if the HTML representation of the attributes cannot be constructed. */ open func html()throws -> String { let accum = StringBuilder() try html(accum: accum, out: Document("").outputSettings()) // output settings a bit funky, but this html() seldom used return accum.toString() } public func html(accum: StringBuilder, out: OutputSettings ) throws { for attribute in attributes.orderedValues { accum.append(" ") attribute.html(accum: accum, out: out) } } open func toString()throws -> String { return try html() } /** * Checks if these attributes are equal to another set of attributes, by comparing the two sets * @param o attributes to compare with * @return if both sets of attributes have the same content */ open func equals(o: AnyObject?) -> Bool { if(o == nil) {return false} if (self === o.self) {return true} guard let that: Attributes = o as? Attributes else {return false} return (attributes == that.attributes) } /** * Calculates the hashcode of these attributes, by iterating all attributes and summing their hashcodes. * @return calculated hashcode */ open func hashCode() -> Int { return attributes.hashCode() } public func copy(with zone: NSZone? = nil) -> Any { let clone = Attributes() clone.attributes = attributes.clone() return clone } open func clone() -> Attributes { return self.copy() as! Attributes } fileprivate static func dataKey(key: String) -> String { return dataPrefix + key } } extension Attributes : Sequence { public func makeIterator() -> AnyIterator<Attribute> { var list = attributes.orderedValues return AnyIterator { return list.count > 0 ? list.removeFirst() : nil } } }
mit
0d5e6540c3f190ad7e2de3754edfe835
28.742424
126
0.616403
4.354964
false
false
false
false
Beaver/BeaverCodeGen
Pods/Diff/Sources/Diff.swift
1
11535
public protocol DiffProtocol: Collection { associatedtype DiffElementType #if swift(>=3.1) // The typealias is causing crashes in SourceKitService under Swift 3.1 snapshots. #else // TODO: Verify that the typealias workaround is still required when Xcode 8.3 is released. typealias Index = Int #endif var elements: [DiffElementType] { get } } /** A sequence of deletions and insertions where deletions point to locations in the source and insertions point to locations in the output. Examples: "12" -> "": D(0)D(1) "" -> "12": I(0)I(1) SeeAlso: Diff */ public struct Diff: DiffProtocol { public enum Element { case insert(at: Int) case delete(at: Int) } /// 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`. public func index(after i: Int) -> Int { return i + 1 } /// An array of particular diff operations public let elements: [Diff.Element] } extension Diff.Element { public init?(trace: Trace) { switch trace.type() { case .insertion: self = .insert(at: trace.from.y) case .deletion: self = .delete(at: trace.from.x) case .matchPoint: return nil } } func at() -> Int { switch self { case let .delete(at): return at case let .insert(at): return at } } } public struct Point { public let x: Int public let y: Int } extension Point: Equatable {} public func ==(l: Point, r: Point) -> Bool { return (l.x == r.x) && (l.y == r.y) } /// A data structure representing single trace produced by the diff algorithm. See the [paper](http://www.xmailserver.org/diff2.pdf) for more information on traces. public struct Trace { public let from: Point public let to: Point public let D: Int } extension Trace: Equatable { public static func ==(l: Trace, r: Trace) -> Bool { return (l.from == r.from) && (l.to == r.to) } } enum TraceType { case insertion case deletion case matchPoint } extension Trace { func type() -> TraceType { if from.x + 1 == to.x && from.y + 1 == to.y { return .matchPoint } else if from.y < to.y { return .insertion } else { return .deletion } } func k() -> Int { return from.x - from.y } } public extension String { /// Creates a diff between the calee and `to` string /// /// - parameter to: a string to compare the calee to. /// - complexity: O((N+M)*D) /// - returns: a Diff between the calee and `to` string public func diff(to: String) -> Diff { if self == to { return Diff(elements: []) } return characters.diff(to.characters) } /// Creates an extended diff (includes insertions, deletions, and moves) between the calee and `other` string /// /// - parameter other: a string to compare the calee to. /// - complexity: O((N+M)*D) /// - returns: an ExtendedDiff between the calee and `other` string public func extendedDiff(_ other: String) -> ExtendedDiff { if self == other { return ExtendedDiff( source: Diff(elements: []), sourceIndex: [], reorderedIndex: [], elements: [], moveIndices: Set() ) } return characters.extendedDiff(other.characters) } } extension Array { func value(at index: Index) -> Iterator.Element? { if index < 0 || index >= self.count { return nil } return self[index] } } struct TraceStep { let D: Int let k: Int let previousX: Int? let nextX: Int? } public typealias EqualityChecker<T: Collection> = (T.Iterator.Element, T.Iterator.Element) -> Bool public extension Collection { /// Creates a diff between the calee and `other` collection /// /// - parameter other: a collection to compare the calee to /// - complexity: O((N+M)*D) /// - returns: a Diff between the calee and `other` collection public func diff( _ other: Self, isEqual: EqualityChecker<Self> ) -> Diff { let diffPath = outputDiffPathTraces( to: other, isEqual: isEqual ) return Diff(elements: diffPath .flatMap { Diff.Element(trace: $0) } ) } /// Generates all traces required to create an output diff. See the [paper](http://www.xmailserver.org/diff2.pdf) for more information on traces. /// /// - parameter to: other collection /// /// - returns: all traces required to create an output diff public func diffTraces( to: Self, isEqual: EqualityChecker<Self> ) -> [Trace] { if self.count == 0 && to.count == 0 { return [] } else if self.count == 0 { return tracesForInsertions(to: to) } else if to.count == 0 { return tracesForDeletions() } else { return myersDiffTraces(to: to, isEqual: isEqual) } } /// Returns the traces which mark the shortest diff path. public func outputDiffPathTraces( to: Self, isEqual: EqualityChecker<Self> ) -> [Trace] { return findPath( diffTraces(to: to, isEqual: isEqual), n: Int(self.count), m: Int(to.count) ) } fileprivate func tracesForDeletions() -> [Trace] { var traces = [Trace]() for index in 0 ..< Int(self.count) { let intIndex = Int(index) traces.append(Trace(from: Point(x: Int(intIndex), y: 0), to: Point(x: Int(intIndex) + 1, y: 0), D: 0)) } return traces } fileprivate func tracesForInsertions(to: Self) -> [Trace] { var traces = [Trace]() for index in 0 ..< Int(to.count) { let intIndex = Int(index) traces.append(Trace(from: Point(x: 0, y: Int(intIndex)), to: Point(x: 0, y: Int(intIndex) + 1), D: 0)) } return traces } fileprivate func myersDiffTraces( to: Self, isEqual: (Iterator.Element, Iterator.Element) -> Bool ) -> [Trace] { let fromCount = Int(self.count) let toCount = Int(to.count) var traces = Array<Trace>() let max = fromCount + toCount // this is arbitrary, maximum difference between from and to. N+M assures that this algorithm always finds from diff var vertices = Array(repeating: -1, count: 2 * Int(max) + 1) // from [0...2*max], it is -max...max in the whitepaper vertices[max + 1] = 0 for numberOfDifferences in 0 ... max { for k in stride(from: (-numberOfDifferences), through: numberOfDifferences, by: 2) { let index = k + max let traceStep = TraceStep(D: numberOfDifferences, k: k, previousX: vertices.value(at: index - 1), nextX: vertices.value(at: index + 1)) if let trace = bound(trace: nextTrace(traceStep), maxX: fromCount, maxY: toCount) { var x = trace.to.x var y = trace.to.y traces.append(trace) // keep going as long as they match on diagonal k while x >= 0 && y >= 0 && x < fromCount && y < toCount { let targetItem = to.itemOnStartIndex(advancedBy: y) let baseItem = itemOnStartIndex(advancedBy: x) if isEqual(baseItem, targetItem) { x += 1 y += 1 traces.append(Trace(from: Point(x: x - 1, y: y - 1), to: Point(x: x, y: y), D: numberOfDifferences)) } else { break } } vertices[index] = x if x >= fromCount && y >= toCount { return traces } } } } return [] } fileprivate func bound(trace: Trace, maxX: Int, maxY: Int) -> Trace? { guard trace.to.x <= maxX && trace.to.y <= maxY else { return nil } return trace } fileprivate func nextTrace(_ traceStep: TraceStep) -> Trace { let traceType = nextTraceType(traceStep) let k = traceStep.k let D = traceStep.D if traceType == .insertion { let x = traceStep.nextX! return Trace(from: Point(x: x, y: x - k - 1), to: Point(x: x, y: x - k), D: D) } else { let x = traceStep.previousX! + 1 return Trace(from: Point(x: x - 1, y: x - k), to: Point(x: x, y: x - k), D: D) } } fileprivate func nextTraceType(_ traceStep: TraceStep) -> TraceType { let D = traceStep.D let k = traceStep.k let previousX = traceStep.previousX let nextX = traceStep.nextX if k == -D { return .insertion } else if k != D { if let previousX = previousX, let nextX = nextX, previousX < nextX { return .insertion } return .deletion } else { return .deletion } } fileprivate func findPath(_ traces: [Trace], n: Int, m: Int) -> [Trace] { guard traces.count > 0 else { return [] } var array = [Trace]() var item = traces.last! array.append(item) if item.from != Point(x: 0, y: 0) { for trace in traces.reversed() { if trace.to.x == item.from.x && trace.to.y == item.from.y { array.insert(trace, at: 0) item = trace if trace.from == Point(x: 0, y: 0) { break } } } } return array } } public extension Collection where Iterator.Element: Equatable { /// - seealso: `diff(_:isEqual:)` public func diff( _ other: Self ) -> Diff { return diff(other, isEqual: { $0 == $1 }) } /// - seealso: `diffTraces(to:isEqual:)` public func diffTraces( to: Self ) -> [Trace] { return diffTraces(to: to, isEqual: { $0 == $1 }) } /// - seealso: `outputDiffPathTraces(to:isEqual:)` public func outputDiffPathTraces( to: Self ) -> [Trace] { return outputDiffPathTraces(to: to, isEqual: { $0 == $1 }) } } extension DiffProtocol { public typealias IndexType = Array<DiffElementType>.Index public var startIndex: IndexType { return elements.startIndex } public var endIndex: IndexType { return elements.endIndex } public subscript(i: IndexType) -> DiffElementType { return elements[i] } } public extension Diff { public init(traces: [Trace]) { elements = traces.flatMap { Diff.Element(trace: $0) } } } extension Diff.Element: CustomDebugStringConvertible { public var debugDescription: String { switch self { case let .delete(at): return "D(\(at))" case let .insert(at): return "I(\(at))" } } }
mit
a95a0861731e9522066fbe608d9a6271
27.481481
164
0.534894
4.077413
false
false
false
false
mirego/PinLayout
Example/PinLayoutSample/UI/Examples/SafeArea/SafeAreaView.swift
1
2751
// Copyright (c) 2017 Luc Dion // 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 PinLayout class SafeAreaView: UIView { private let topTextLabel = UILabel() private let scanButton = RoundedButton(text: "Scan", icon: UIImage(named: "Barcode")!) private let iconImageView = UIImageView(image: UIImage(named: "IconOrder")!) private let textLabel = UILabel() init() { super.init(frame: .zero) backgroundColor = .white topTextLabel.text = "Add items to your cart" topTextLabel.textColor = UIColor.darkGray topTextLabel.font = UIFont.boldSystemFont(ofSize: 22) topTextLabel.sizeToFit() addSubview(topTextLabel) addSubview(scanButton) addSubview(iconImageView) textLabel.text = "Scan the item's barcode to add it to your cart" textLabel.textColor = UIColor.lightGray textLabel.textAlignment = .center textLabel.numberOfLines = 0 textLabel.font = UIFont.boldSystemFont(ofSize: 17) addSubview(textLabel) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func safeAreaInsetsDidChange() { if #available(iOS 11.0, *) { super.safeAreaInsetsDidChange() } } override func layoutSubviews() { super.layoutSubviews() topTextLabel.pin.top(pin.safeArea.top + 10).hCenter() iconImageView.pin.hCenter().vCenter(-10%) textLabel.pin.below(of: iconImageView).hCenter().width(60%).maxWidth(400).marginTop(20).sizeToFit(.width) scanButton.pin.bottom(pin.safeArea.bottom + 5).hCenter().width(80%).maxWidth(300).height(40) } }
mit
85947d6dc54f3b459184a4ef79653c1c
39.455882
113
0.696111
4.451456
false
false
false
false
sivu22/AnyTracker
AnyTracker/Item.swift
1
5223
// // Item.swift // AnyTracker // // Created by Cristian Sava on 10/07/16. // Copyright © 2016 Cristian Sava. All rights reserved. // import Foundation protocol ItemInit { init() // Convenience in disguise func initItem(withName name: String, ID: String, description: String, useDate: Bool, startDate: Date, endDate: Date) } protocol ItemJSON { func getItemAsJSONDictionary() -> JSONDictionary static func getItemFromJSONDictionary(_ input: String?) -> (JSONDictionary, String, String, String, String, String, Bool, Date, Date)? } protocol ItemChangeDelegate { func itemChanged() } protocol NotifyItemUpdate { var itemChangeDelegate: ItemChangeDelegate? { get set } } protocol Item: Version, NameAndID, ItemInit, ItemJSON { var name: String { get set } var ID: String { get set } var description: String { get set } var type: ItemType { get } var useDate: Bool { get set } var startDate: Date { get set } var endDate: Date { get set } func isEmpty() -> Bool func toString() -> String? func saveToFile() throws // true if item changed at all, false if item is the same as before func updateWith(newName name: String, newDescription description: String, newUseDate useDate: Bool, newStartDate startDate: Date, newEndDate endDate: Date) throws -> Bool } // MARK: - Item common init extension Item { func initItem(withName name: String, ID: String, description: String, useDate: Bool, startDate: Date, endDate: Date) { self.name = name self.ID = ID self.description = description self.useDate = useDate self.startDate = startDate self.endDate = endDate } } // MARK: - Item common JSON functions extension Item { func getItemAsJSONDictionary() -> JSONDictionary { var dict: JSONDictionary = [:] dict["version"] = version as JSONObject? dict["name"] = name as JSONObject? dict["ID"] = ID as JSONObject? dict["description"] = description as JSONObject? dict["type"] = type.rawValue as JSONObject? dict["useDate"] = useDate as JSONObject? dict["startDate"] = Utils.timeFromDate(startDate) as JSONObject? dict["endDate"] = Utils.timeFromDate(endDate) as JSONObject? return dict } static func getItemFromJSONDictionary(_ input: String?) -> (JSONDictionary, String, String, String, String, String, Bool, Date, Date)? { let dict = Utils.getDictionaryFromJSON(input) guard dict != nil else { return nil } guard let version = dict!["version"] as? String else { Utils.debugLog("Item version invalid") return nil } guard let name = dict!["name"] as? String else { Utils.debugLog("Item name invalid") return nil } guard let ID = dict!["ID"] as? String else { Utils.debugLog("Item ID invalid") return nil } guard let description = dict!["description"] as? String else { Utils.debugLog("Item description invalid") return nil } guard let type = dict!["type"] as? ItemType.RawValue else { Utils.debugLog("Item type invalid") return nil } guard let useDate = dict!["useDate"] as? Bool else { Utils.debugLog("Item using date invalid") return nil } guard let startDate = Utils.dateFromTime(dict!["startDate"] as? String) else { Utils.debugLog("Item start date invalid") return nil } guard let endDate = Utils.dateFromTime(dict!["endDate"] as? String) else { Utils.debugLog("Item end date invalid") return nil } return (dict!, version, name, ID, description, type, useDate, startDate, endDate) } } // MARK: - Item general purpose functions extension Item { func saveToFile() throws { guard let JSONString = toString() else { Utils.debugLog("Failed to serialize JSON item") throw Status.errorJSONSerialize } if !Utils.createFile(withName: ID, withContent: JSONString, overwriteExisting: true) { Utils.debugLog("Failed to save item to file") throw Status.errorItemFileSave } } func updateWith(newName name: String, newDescription description: String, newUseDate useDate: Bool, newStartDate startDate: Date, newEndDate endDate: Date) throws -> Bool { let changed = self.name != name || self.description != description || self.useDate != useDate || self.startDate != startDate || self.endDate != endDate if changed { Utils.debugLog("Item changed, will try to update ...") self.name = name self.description = description self.useDate = useDate self.startDate = startDate self.endDate = endDate do { try saveToFile() } catch { throw error } } return changed } }
mit
efbfbd1ebb71b47f9aad852bced1d510
32.050633
176
0.602643
4.650045
false
false
false
false
xwu/swift
test/decl/func/operator.swift
5
17586
// RUN: %target-typecheck-verify-swift infix operator %%% infix operator %%%% func %%%() {} // expected-error {{operators must have one or two arguments}} func %%%%(a: Int, b: Int, c: Int) {} // expected-error {{operators must have one or two arguments}} struct X {} struct Y {} func +(lhs: X, rhs: X) -> X {} // okay func <=>(lhs: X, rhs: X) -> X {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=infix operator <=> : <# Precedence Group #>\n}} extension X { static func <=>(lhs: X, rhs: X) -> X {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=infix operator <=> : <# Precedence Group #>\n}} } extension X { struct Z { static func <=> (lhs: Z, rhs: Z) -> Z {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=infix operator <=> : <# Precedence Group #>\n}} } } extension X { static prefix func <=>(lhs: X) -> X {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=prefix operator <=> : <# Precedence Group #>\n}} } extension X { struct ZZ { static prefix func <=>(lhs: ZZ) -> ZZ {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=prefix operator <=> : <# Precedence Group #>\n}} } } infix operator ++++ : ReallyHighPrecedence precedencegroup ReallyHighPrecedence { higherThan: BitwiseShiftPrecedence associativity: left } infix func fn_binary(_ lhs: Int, rhs: Int) {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} func ++++(lhs: X, rhs: X) -> X {} func ++++(lhs: Y, rhs: Y) -> Y {} // okay func useInt(_ x: Int) {} func test() { var x : Int let y : Int = 42 // Produce a diagnostic for using the result of an assignment as a value. // rdar://12961094 useInt(x = y) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} _ = x } prefix operator ~~ postfix operator ~~ infix operator ~~ postfix func foo(_ x: Int) {} // expected-error {{'postfix' requires a function with an operator identifier}} postfix func ~~(x: Int) -> Float { return Float(x) } postfix func ~~(x: Int, y: Int) {} // expected-error {{'postfix' requires a function with one argument}} prefix func ~~(x: Float) {} func test_postfix(_ x: Int) { ~~x~~ } prefix operator ~~~ // expected-note 2{{prefix operator found here}} // Unary operators require a prefix or postfix attribute func ~~~(x: Float) {} // expected-error{{prefix unary operator missing 'prefix' modifier}}{{1-1=prefix }} protocol P { static func ~~~(x: Self) // expected-error{{prefix unary operator missing 'prefix' modifier}}{{10-10=prefix }} } prefix func +// this should be a comment, not an operator (arg: Int) -> Int { return arg } prefix func -/* this also should be a comment, not an operator */ (arg: Int) -> Int { return arg } func +*/ () {} // expected-error {{expected identifier in function declaration}} expected-error {{unexpected end of block comment}} expected-error {{closure expression is unused}} expected-error{{top-level statement cannot begin with a closure expression}} expected-note{{did you mean to use a 'do' statement?}} {{13-13=do }} func errors() { */ // expected-error {{unexpected end of block comment}} // rdar://12962712 - reject */ in an operator as it should end a block comment. */+ // expected-error {{unexpected end of block comment}} } prefix operator ... prefix func ... (arg: Int) -> Int { return arg } func resyncParser() {} // Operator decl refs (<op>) infix operator +-+ prefix operator +-+ prefix operator -+- postfix operator -+- infix operator +-+= infix func +-+ (x: Int, y: Int) -> Int {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} prefix func +-+ (x: Int) -> Int {} prefix func -+- (y: inout Int) -> Int {} // expected-note 2{{found this candidate}} postfix func -+- (x: inout Int) -> Int {} // expected-note 2{{found this candidate}} infix func +-+= (x: inout Int, y: Int) -> Int {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} var n = 0 // Infix by context _ = (+-+)(1, 2) // Prefix by context _ = (+-+)(1) // Ambiguous -- could be prefix or postfix (-+-)(&n) // expected-error{{ambiguous use of operator '-+-'}} // Assignment operator refs become inout functions _ = (+-+=)(&n, 12) (+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{8-8=&}} var f1 : (Int, Int) -> Int = (+-+) var f2 : (Int) -> Int = (+-+) var f3 : (inout Int) -> Int = (-+-) // expected-error{{ambiguous use of operator '-+-'}} var f4 : (inout Int, Int) -> Int = (+-+=) var r5 : (a : (Int, Int) -> Int, b : (Int, Int) -> Int) = (+, -) var r6 : (a : (Int, Int) -> Int, b : (Int, Int) -> Int) = (b : +, a : -) // expected-warning {{expression shuffles the elements of this tuple; this behavior is deprecated}} struct f6_S { subscript(op : (Int, Int) -> Int) -> Int { return 42 } } var f6_s : f6_S var junk = f6_s[+] // Unicode operator names infix operator ☃ infix operator ☃⃠ // Operators can contain (but not start with) combining characters func ☃(x: Int, y: Int) -> Bool { return x == y } func ☃⃠(x: Int, y: Int) -> Bool { return x != y } var x, y : Int _ = x☃y _ = x☃⃠y // rdar://14705150 - crash on invalid func test_14705150() { let a = 4 var b! = a // expected-error {{type annotation missing in pattern}} // expected-error @-1 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error @-2 {{expected expression}} } postfix operator ++ prefix operator ++ prefix postfix func ++(x: Int) {} // expected-error {{'postfix' contradicts previous modifier 'prefix'}} {{8-16=}} postfix prefix func ++(x: Float) {} // expected-error {{'prefix' contradicts previous modifier 'postfix'}} {{9-16=}} postfix prefix infix func ++(x: Double) {} // expected-error {{'prefix' contradicts previous modifier 'postfix'}} {{9-16=}} expected-error {{'infix' contradicts previous modifier 'postfix'}} {{16-22=}} infix prefix func +-+(x: Double, y: Double) {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} expected-error{{'prefix' contradicts previous modifier 'infix'}} {{7-14=}} // Don't allow one to define a postfix '!'; it's built into the // language. Also illegal to have any postfix operator starting with '!'. postfix operator ! // expected-error {{cannot declare a custom postfix '!' operator}} expected-error {{postfix operator names starting with '?' or '!' are disallowed}} prefix operator & // expected-error {{cannot declare a custom prefix '&' operator}} // <rdar://problem/14607026> Restrict use of '<' and '>' as prefix/postfix operator names postfix operator > // expected-error {{cannot declare a custom postfix '>' operator}} prefix operator < // expected-error {{cannot declare a custom prefix '<' operator}} infix operator = // expected-error {{cannot declare a custom infix '=' operator}} infix operator -> // expected-error {{cannot declare a custom infix '->' operator}} postfix func !(x: Int) { } // expected-error{{cannot declare a custom postfix '!' operator}} postfix func!(x: Int8) { } // expected-error{{cannot declare a custom postfix '!' operator}} prefix func & (x: Int) {} // expected-error {{cannot declare a custom prefix '&' operator}} // Only allow operators at global scope: func operator_in_func_bad () { prefix func + (input: String) -> String { return "+" + input } // expected-error {{operator functions can only be declared at global or in type scope}} } infix operator ? // expected-error {{cannot declare a custom infix '?' operator}} prefix operator ? // expected-error {{cannot declare a custom prefix '?' operator}} infix operator ??= func ??= <T>(result : inout T?, rhs : Int) { // ok } // <rdar://problem/14296004> [QoI] Poor diagnostic/recovery when two operators (e.g., == and -) are adjacted without spaces. _ = n*-4 // expected-error {{missing whitespace between '*' and '-' operators}} {{6-6= }} {{7-7= }} if n==-1 {} // expected-error {{missing whitespace between '==' and '-' operators}} {{5-5= }} {{7-7= }} prefix operator ☃⃠ prefix func☃⃠(a : Int) -> Int { return a } postfix operator ☃⃠ postfix func☃⃠(a : Int) -> Int { return a } _ = n☃⃠ ☃⃠ n // Ok. _ = n ☃⃠ ☃⃠n // Ok. _ = n ☃⃠☃⃠ n // expected-error {{cannot find operator '☃⃠☃⃠' in scope}} _ = n☃⃠☃⃠n // expected-error {{ambiguous missing whitespace between unary and binary operators}} // expected-note @-1 {{could be binary '☃⃠' and prefix '☃⃠'}} {{12-12= }} {{18-18= }} // expected-note @-2 {{could be postfix '☃⃠' and binary '☃⃠'}} {{6-6= }} {{12-12= }} _ = n☃⃠☃⃠ // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = ~!n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = -+n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = -++n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} // <rdar://problem/16230507> Cannot use a negative constant as the second operator of ... operator _ = 3...-5 // expected-error {{ambiguous missing whitespace between unary and binary operators}} expected-note {{could be postfix '...' and binary '-'}} expected-note {{could be binary '...' and prefix '-'}} protocol P0 { static func %%%(lhs: Self, rhs: Self) -> Self } protocol P1 { func %%%(lhs: Self, rhs: Self) -> Self // expected-error{{operator '%%%' declared in protocol must be 'static'}}{{3-3=static }} } struct S0 { static func %%%(lhs: S0, rhs: S0) -> S0 { return lhs } } extension S0 { static func %%%%(lhs: S0, rhs: S0) -> S0 { return lhs } } struct S1 { func %%%(lhs: S1, rhs: S1) -> S1 { return lhs } // expected-error{{operator '%%%' declared in type 'S1' must be 'static'}}{{3-3=static }} } extension S1 { func %%%%(lhs: S1, rhs: S1) -> S1 { return lhs } // expected-error{{operator '%%%%' declared in extension of 'S1' must be 'static'}}{{3-3=static }} } class C0 { static func %%%(lhs: C0, rhs: C0) -> C0 { return lhs } } class C1 { final func %%%(lhs: C1, rhs: C1) -> C1 { return lhs } // expected-error{{operator '%%%' declared in type 'C1' must be 'static'}}{{3-3=static }} } final class C2 { class func %%%(lhs: C2, rhs: C2) -> C2 { return lhs } } class C3 { class func %%%(lhs: C3, rhs: C3) -> C3 { return lhs } // expected-error{{operator '%%%' declared in non-final class 'C3' must be 'final'}}{{3-3=final }} } class C4 { func %%%(lhs: C4, rhs: C4) -> C4 { return lhs } // expected-error{{operator '%%%' declared in type 'C4' must be 'static'}}{{3-3=static }} } struct Unrelated { } struct S2 { static func %%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> S2 { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> S2.Type { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} // Okay: refers to S2 static func %%%(lhs: S2, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: inout S2, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: inout S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: S2) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: inout S2) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: S2.Type) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: inout S2.Type) -> Unrelated { } } extension S2 { static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> S2 { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> S2.Type { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} // Okay: refers to S2 static func %%%%(lhs: S2, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout S2, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: S2) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout S2) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: S2.Type) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout S2.Type) -> Unrelated { } } protocol P2 { static func %%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> Self // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> Self.Type // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} // Okay: refers to Self static func %%%(lhs: Self, rhs: Unrelated) -> Unrelated static func %%%(lhs: inout Self, rhs: Unrelated) -> Unrelated static func %%%(lhs: Self.Type, rhs: Unrelated) -> Unrelated static func %%%(lhs: inout Self.Type, rhs: Unrelated) -> Unrelated static func %%%(lhs: Unrelated, rhs: Self) -> Unrelated static func %%%(lhs: Unrelated, rhs: inout Self) -> Unrelated static func %%%(lhs: Unrelated, rhs: Self.Type) -> Unrelated static func %%%(lhs: Unrelated, rhs: inout Self.Type) -> Unrelated } extension P2 { static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Self { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Self.Type { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} // Okay: refers to Self static func %%%%(lhs: Self, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout Self, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Self.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout Self.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: Self) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout Self) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: Self.Type) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout Self.Type) -> Unrelated { } } protocol P3 { // Okay: refers to P3 static func %%%(lhs: P3, rhs: Unrelated) -> Unrelated } extension P3 { // Okay: refers to P3 static func %%%%(lhs: P3, rhs: Unrelated) -> Unrelated { } } // rdar://problem/27940842 - recovery with a non-static '=='. class C5 { func == (lhs: C5, rhs: C5) -> Bool { return false } // expected-error{{operator '==' declared in type 'C5' must be 'static'}} func test1(x: C5) { _ = x == x } } class C6 { static func == (lhs: C6, rhs: C6) -> Bool { return false } func test1(x: C6) { if x == x && x = x { } // expected-error{{use of '=' in a boolean context, did you mean '=='?}} {{20-21===}} // expected-error@-1 {{cannot convert value of type 'C6' to expected argument type 'Bool'}} } } prefix operator ∫ prefix func ∫(arg: (Int, Int)) {} func testPrefixOperatorOnTuple() { let foo = (1, 2) _ = ∫foo _ = (∫)foo // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-warning@-2 {{expression of type '(Int, Int)' is unused}} (∫)(foo) _ = ∫(1, 2) _ = (∫)(1, 2) // expected-error {{operator function '∫' expects a single parameter of type '(Int, Int)'}} (∫)((1, 2)) } postfix operator § postfix func §<T, U>(arg: (T, (U, U), T)) {} // expected-note {{in call to operator '§'}} func testPostfixOperatorOnTuple<A, B>(a: A, b: B) { let foo = (a, (b, b), a) _ = foo§ // FIX-ME: "...could not be inferred" is irrelevant _ = (§)foo // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} // expected-error@-3 {{generic parameter 'U' could not be inferred}} // expected-warning@-4 {{expression of type '(A, (B, B), A)' is unused}} (§)(foo) _ = (a, (b, b), a)§ _ = (§)(a, (b, b), a) // expected-error {{operator function '§' expects a single parameter of type '(T, (U, U), T)'}} (§)((a, (b, b), a)) _ = (a, ((), (b, (a, a), b)§), a)§ } func testNonexistentPowerOperatorWithPowFunctionOutOfScope() { func a(_ value: Double) { } let x: Double = 3.0 let y: Double = 3.0 let z: Double = x**y // expected-error {{cannot find operator '**' in scope}} let w: Double = a(x**2.0) // expected-error {{cannot find operator '**' in scope}} }
apache-2.0
eda261fe4eb1d222d2f7bc54b6b8ca6a
39.412037
327
0.630485
3.543333
false
false
false
false
Ekhoo/Device
Source/macOS/DeviceMacOS.swift
1
2696
// // DeviceMacOS.swift // Device // // Created by Tom Baranes on 16/08/16. // Copyright © 2016 Ekhoo. All rights reserved. // #if os(OSX) import Cocoa public class Device { static private func getVersionCode() -> String { var size : Int = 0 sysctlbyname("hw.model", nil, &size, nil, 0) var model = [CChar](repeating: 0, count: Int(size)) sysctlbyname("hw.model", &model, &size, nil, 0) return String.init(validatingUTF8: model) ?? "" } static private func getType(code: String) -> Type { let versionCode = Device.getVersionCode() if versionCode.hasPrefix("MacPro") { return Type.macPro } else if versionCode.hasPrefix("iMac") { return Type.iMac } else if versionCode.hasPrefix("MacBookPro") { return Type.macBookPro } else if versionCode.hasPrefix("MacBookAir") { return Type.macBookAir } else if versionCode.hasPrefix("MacBook") { return Type.macBook } else if versionCode.hasPrefix("MacMini") { return Type.macMini } else if versionCode.hasPrefix("Xserve") { return Type.xserve } return Type.unknown } private static func sizeInInches() -> CGFloat { let screen = NSScreen.main let description = screen?.deviceDescription let displayPhysicalSize = CGDisplayScreenSize(description?[NSDeviceDescriptionKey(rawValue: "NSScreenNumber")] as? CGDirectDisplayID ?? 0) return floor(sqrt(pow(displayPhysicalSize.width, 2) + pow(displayPhysicalSize.height, 2)) * 0.0393701); } static public func size() -> Size { let sizeInInches = Device.sizeInInches() switch sizeInInches { case 11: return Size.screen11Inch case 12: return Size.screen12Inch case 13: return Size.screen13Inch case 15: return Size.screen15Inch case 16: return Size.screen16Inch case 17: return Size.screen17Inch case 20: return Size.screen20Inch case 21: return Size.screen21_5Inch case 24: return Size.screen24Inch case 27: return Size.screen27Inch default: return Size.unknownSize } } static public func version() -> String { return String(describing: Device.type()) + " " + String(describing: Device.sizeInInches()) + "-inch" } static public func type() -> Type { let versionName = Device.getVersionCode() return Device.getType(code: versionName) } } #endif
mit
cd04569cb80284346a4131f48a147039
29.977011
146
0.595918
4.367909
false
false
false
false