repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
allevato/SwiftCGI
Sources/SwiftCGI/FCGINameValueSerialization.swift
1
4502
// Copyright 2015 Tony Allevato // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Parses a serialized byte array of FCGI name/value pairs and returns them in a dictionary. /// /// - Parameter bytes: The byte array containing the serialized FCGI name/value pairs. /// - Returns: A dictionary with the deserialized name/value pairs. func FCGINameValueDictionaryFromBytes(bytes: [UInt8]) -> [String: String] { var index = 0 var dictionary = [String:String]() while index < bytes.count { let nameLength = readLength(bytes, index: &index) let valueLength = readLength(bytes, index: &index) let name = readString(bytes, length: nameLength, index: &index) let value = readString(bytes, length: valueLength, index: &index) if let name = name, value = value { dictionary[name] = value } } return dictionary } /// Serializes a dictionary into a byte array of FCGI name/value pairs. /// /// - Parameter dictionary: A dictionary whose keys and values are strings. /// - Returns: A byte array containing the serialized FCGI name/value pairs. func FCGIBytesFromNameValueDictionary(dictionary: [String: String]) -> [UInt8] { var bytes = [UInt8]() for (name, value) in dictionary { writeLength(&bytes, length: name.utf8.count) writeLength(&bytes, length: value.utf8.count) writeString(&bytes, string: name) writeString(&bytes, string: value) } return bytes } /// Reads an integer representing the length of a name or value, automatically handling both /// 8-bit and 32-bit length values. /// /// - Parameter bytes: The byte array from which to read the length. /// - Parameter index: The position in the array from which to read the length; this value will be /// advanced the appropriate amount once the length has been read. /// - Returns: The length value read from the byte array. private func readLength(bytes: [UInt8], inout index: Int) -> Int { let firstByte = bytes[index++] if firstByte & 0x80 == 0 { return Int(firstByte) } else { let lengthB3 = Int(firstByte & 0x7F) let lengthB2 = Int(bytes[index++]) let lengthB1 = Int(bytes[index++]) let lengthB0 = Int(bytes[index++]) return lengthB0 | lengthB1 << 8 | lengthB2 << 16 | lengthB3 << 24 } } /// Reads a UTF-8-encoded string of the given length. /// /// - Parameter bytes: The byte array from which to read the string. /// - Parameter length: The length of the string, in bytes. /// - Parameter index: The position in the buffer from which to read the string; this value will be /// advanced the appropriate amount once the string has been read. /// - Returns: The string read from the byte array, or nil if there was a problem decoding the UTF-8 /// data. private func readString(bytes: [UInt8], length: Int, inout index: Int) -> String? { var chars = bytes[index..<(index + length)] chars.append(0) index += length return chars.withUnsafeBufferPointer { pointer in String.fromCString(UnsafePointer<CChar>(pointer.baseAddress)) } } /// Writes an integer representing a length of a name or value, automatically handling both 8-bit /// and 32-bit length values. /// /// - Parameter bytes: The byte array to which the length should be written. /// - Parameter length: The length value to write to the byte array. private func writeLength(inout bytes: [UInt8], length: Int) { if length > 127 { bytes.append(UInt8((length >> 24 & 0xFF) | 0x80)) bytes.append(UInt8(length >> 16 & 0xFF)) bytes.append(UInt8(length >> 8 & 0xFF)) bytes.append(UInt8(length & 0xFF)) } else { bytes.append(UInt8(length)) } } /// Writes a UTF-8-encoding string to the given byte array. The string is not nil-terminated in the /// destination array. /// /// - Parameter bytes: The byte array to which the string should be written. /// - Parameter string: The string to be written to the byte array. private func writeString(inout bytes: [UInt8], string: String) { for byte in string.utf8 { bytes.append(byte) } }
apache-2.0
c09f072fb84e1905912d462893d22561
37.810345
100
0.704354
3.945662
false
false
false
false
GregPDesSCH/DETERGO
iOS App/Detergo(iOSApp)/dataModels/PodDetergent.swift
1
3699
/* DETERGO - Laundry Detergent Calculation App Data Model - Pod Detergent Programmed by Gregory Desrosiers Start Date: July 4, 2017 End Date: July 9, 2017 File Name: PodDetergent.swift Source Code © 2017 Gregory Desrosiers. All rights reserved. */ import Foundation public class PodDetergent: Detergent, DetergentFunc { // Constructor override init(dirtLevel: DirtLevel, drumCapacityUse: DrumCapacityUse, waterHardness: WaterHardness) { super.init(dirtLevel: dirtLevel, drumCapacityUse: drumCapacityUse, waterHardness: waterHardness) } // Calculates amount of detergent needed to wash the load. (In this case, number of pods) func calculateAmountNeededForWashing() -> Int { var podsNeeded: Float = 1 // Base amount of detergent // Adjust amount based on how much of the drum the laundry occupies in a linear fashion switch self.drumCapacityUse { case DrumCapacityUse.BETWEEN_ONE_QUARTER_AND_ONE_HALF: podsNeeded = 1.33; break case DrumCapacityUse.ONE_HALF: podsNeeded = 1.66; break case DrumCapacityUse.BETWEEN_ONE_HALF_AND_THREE_QUARTERS: podsNeeded = 2; break case DrumCapacityUse.THREE_QUARTERS: podsNeeded = 2.33; break case DrumCapacityUse.BETWEEN_THREE_QUARTERS_AND_NINE_TENTHS: podsNeeded = 2.66; break case DrumCapacityUse.NINE_TENTHS: podsNeeded = 3; break default: break } // Adjust amount based on how much dirt (stains, soil, sweat, etc.) has been accumulated in the laundry. switch self.dirtLevel { case DirtLevel.VERY_LOW: podsNeeded -= Detergent.changeInAmountBasedOnSoil * 2; break case DirtLevel.LOW: podsNeeded -= Detergent.changeInAmountBasedOnSoil; break case DirtLevel.HIGH: podsNeeded += Detergent.changeInAmountBasedOnSoil; break case DirtLevel.VERY_HIGH: podsNeeded += Detergent.changeInAmountBasedOnSoil * 2; break default: break } // Adjust amount based on the concentration of minerals, including calcium, in the water supply switch self.waterHardness { case WaterHardness.VERY_SOFT: podsNeeded -= Detergent.changeInAmountBasedOnWaterHardness * 2; break case WaterHardness.SOFT: podsNeeded -= Detergent.changeInAmountBasedOnWaterHardness; break case WaterHardness.HARD: podsNeeded += Detergent.changeInAmountBasedOnWaterHardness; break case WaterHardness.VERY_HARD: podsNeeded += Detergent.changeInAmountBasedOnWaterHardness * 2; break default: break } // Make sure the number of pods is at least one. if (podsNeeded < 1) { podsNeeded = 1 } // Return an integer of the number of pods needed. return Int(round(podsNeeded)) } // Retrieve the output message based on the parameters given in the model. public func amountNeededForWashing() -> String { // If there's too little or too much laundry to wash, display an invalid message. if (self.drumCapacityUse == DrumCapacityUse.LESS_THAN_ONE_QUARTER) { return Detergent.tooLittleLaundryMessage } else if (self.drumCapacityUse == DrumCapacityUse.MORE_THAN_NINE_TENTHS) { return Detergent.tooMuchLaundryMessage } else { // Otherwise, get the message for how much detergent needed. let numberOfPods: Int = calculateAmountNeededForWashing() let firstPartOfMessage: String = "Add \(numberOfPods) pod" let secondPartOfMessage: String = numberOfPods != 1 ? "s" : "" return "\(firstPartOfMessage)\(secondPartOfMessage) to it." } } }
mit
bb8cbfbe26452a711abff20232b10bb5
44.109756
112
0.687939
4.576733
false
false
false
false
harlanhaskins/trill
Sources/Options/OutputFormat.swift
2
1992
/// /// OutputFormat.swift /// /// Copyright 2016-2017 the Trill project authors. /// Licensed under the MIT License. /// /// Full license text available at https://github.com/trill-lang/trill /// import Foundation import Basic import Utility public enum Mode { case emit(OutputFormat) case jit, onlyDiagnostics } public enum OutputFormat: String, ArgumentKind { case ast case asm case obj = "object" case binary case llvm = "ir" case bitCode = "bitcode" public init(argument: String) throws { guard let fmt = OutputFormat(rawValue: argument) else { throw ArgumentParserError.invalidValue(argument: argument, error: .unknown(value: argument)) } self = fmt } public func addExtension(to basename: String) -> String { var url = URL(fileURLWithPath: basename) url.deletePathExtension() return url.appendingPathExtension(fileExtension).lastPathComponent } public var fileExtension: String { switch self { case .llvm: return "ll" case .asm: return "s" case .obj, .binary: return "o" case .bitCode: return "bc" default: fatalError("should not be serializing \(self)") } } public var description: String { switch self { case .llvm: return "LLVM IR" case .binary: return "Executable" case .asm: return "Assembly" case .obj: return "Object File" case .ast: return "AST" case .bitCode: return "LLVM Bitcode File" } } public static var completion: ShellCompletion { return .values([ (value: "ast", description: "Emit the parsed AST."), (value: "asm", description: "Emit assembly for the target architecture."), (value: "object", description: "Emit a .o file for the target architecture."), (value: "binary", description: "Emit an executable for the target architecture."), (value: "ir", description: "Emit LLVM IR."), (value: "bitcode", description: "Emit LLVM Bitcode."), ]) } }
mit
9b3a70ada4e65ba17142417328b5d7f3
26.666667
88
0.654116
4.184874
false
false
false
false
huangboju/Moots
算法学习/数据结构/DataStructures/DataStructures/Classes/LinkList.swift
1
3506
// // LinkList.swift // DataStructures // // Created by xiAo_Ju on 2018/10/20. // Copyright © 2018 黄伯驹. All rights reserved. // import Foundation public class LinkedList<T> { public class LinkedListNode<T> { var value: T var next: LinkedListNode? weak var previous: LinkedListNode? public init(value: T) { self.value = value } } public typealias Node = LinkedListNode<T> private var head: Node? public var isEmpty: Bool { return head == nil } public var first: Node? { return head } public var last: Node? { guard var node = head else { return nil } while let next = node.next { node = next } return node } public func append(value: T) { let newNode = Node(value: value) if let lastNode = last { newNode.previous = lastNode lastNode.next = newNode } else { head = newNode } } public var count: Int { guard var node = head else { return 0 } var count = 1 while let next = node.next { node = next count += 1 } return count } public func node(atIndex index: Int) -> Node { if index == 0 { return head! } else { var node = head!.next for _ in 1..<index { node = node?.next if node == nil { //(*1) break } } return node! } } public subscript(index: Int) -> T { let node = self.node(atIndex: index) return node.value } public func insert(_ node: Node, atIndex index: Int) { let newNode = node if index == 0 { newNode.next = head head?.previous = newNode head = newNode } else { let prev = self.node(atIndex: index - 1) let next = prev.next newNode.previous = prev newNode.next = prev.next prev.next = newNode next?.previous = newNode } } public func removeAll() { head = nil } public func remove(node: Node) -> T { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } next?.previous = prev node.previous = nil node.next = nil return node.value } public func removeLast() -> T { assert(!isEmpty) return remove(node: last!) } public func remove(at index: Int) -> T { let node = self.node(atIndex: index) return remove(node: node) } public func reverse() { var node = head while let currentNode = node { node = currentNode.next swap(&currentNode.next, &currentNode.previous) head = currentNode } } } extension LinkedList: CustomStringConvertible { public var description: String { var s = "[" var node = head while node != nil { s += "\(node!.value)" node = node!.next if node != nil { s += ", " } } return s + "]" } }
mit
b139961327524a51fb2a5a1a70e76fd0
21.006289
58
0.464704
4.677807
false
false
false
false
Queuely/queuely
ProximityContent/MainViewController.swift
1
8360
// // MainViewController.swift // ProximityContent // // Created by avnt on 2016/11/12. // Copyright © 2016 Estimote, Inc. All rights reserved. // import UIKit class MainViewController: UIViewController, ESTBeaconManagerDelegate { @IBOutlet weak var karmaLabel: UILabel! @IBOutlet weak var queuePosLabel: UILabel! @IBOutlet weak var queueEstimateLabel: UILabel! @IBOutlet weak var queueButton: UIButton! @IBOutlet weak var urgentButton: UIButton! @IBOutlet weak var centerImage: UIImageView! var inQueue = false var pending = false var active = false var aheadOfYou = 3 var queueSize = 3 var karmaPoints = 85 var countdownTimer: Timer! var countdownTime = 0 var timePad = "" override func viewDidLoad() { super.viewDidLoad() // 3. Set the beacon manager's delegate self.beaconManager.delegate = self // 4. We need to request this authorization for every beacon manager self.beaconManager.requestWhenInUseAuthorization() renderUI() // Do any additional setup after loading the view. countdownTime = aheadOfYou * 3 * 60 urgentButton.isHidden = true queuePosLabel.text = "\(aheadOfYou)" if countdownTime % 60 < 10 { timePad = "0" } else { timePad = "" } queueEstimateLabel.text = "\(countdownTime / 60):\(timePad)\(countdownTime % 60)" karmaLabel.text = "\(karmaPoints)" countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func runTimedCode() { countdownTime -= 1 if countdownTime < 0 { countdownTime = 0 } if countdownTime % 60 < 10 { timePad = "0" } else { timePad = "" } queueEstimateLabel.text = "\(countdownTime / 60):\(timePad)\(countdownTime % 60)" // Update Queue Pos if ((aheadOfYou - 1) * 3 * 60) >= countdownTime { aheadOfYou -= 1 queuePosLabel.text = "\(aheadOfYou)" } if aheadOfYou == 0 && !pending && !active { setPending() } if pending && countdownTime == 0 { setInActive() } // mock data // if countdownTime == 118 { // getIn() // } // // if countdownTime == 115 { // getOut() // } } func setPending() { pending = true active = false queueEstimateLabel.isHidden = false queuePosLabel.isHidden = true urgentButton.isHidden = true centerImage.image = UIImage(named: "center_pending") countdownTime = 2 * 60 queueEstimateLabel.textColor = UIColor(red: 98.0/255.0, green: 98.0/255.0, blue: 98.0/255.0, alpha: 1.0) } func setActive() { active = true pending = false queueEstimateLabel.isHidden = true queuePosLabel.isHidden = true centerImage.image = UIImage(named: "center_in") } func setInActive() { pending = false active = false centerImage.image = UIImage(named: "center") queueEstimateLabel.isHidden = false queuePosLabel.isHidden = false queueButton.setTitle("Enter Queue", for: .normal) queuePosLabel.textColor = UIColor.darkGray urgentButton.isHidden = true queueEstimateLabel.textColor = UIColor.white // Reset Queue aheadOfYou = 3 queuePosLabel.text = "\(aheadOfYou)" countdownTime = aheadOfYou * 3 * 60 } func setQueued() { pending = false active = false centerImage.image = UIImage(named: "center") queueEstimateLabel.isHidden = false queuePosLabel.isHidden = false queueButton.setTitle("Leave Queue", for: .normal) queuePosLabel.textColor = UIColor(red: 131.0/255.0, green: 207.0/255.0, blue: 242.0/255.0, alpha: 1.0) urgentButton.isHidden = false queueEstimateLabel.textColor = UIColor.white if karmaPoints <= (queueSize - aheadOfYou) { urgentButton.isHidden = true } } @IBAction func queueAction(_ sender: UIButton) { inQueue = !inQueue renderUI() } @IBAction func urgentAction(_ sender: UIButton) { if aheadOfYou > 0 { aheadOfYou -= 1 karmaPoints -= queueSize - aheadOfYou queuePosLabel.text = "\(aheadOfYou)" countdownTime = aheadOfYou * 3 * 60 karmaLabel.text = "\(karmaPoints)" } if aheadOfYou == 1 { countdownTime = aheadOfYou * 5 } if aheadOfYou == 0 || karmaPoints < (queueSize - aheadOfYou) { urgentButton.isHidden = true } if aheadOfYou == 0 { setPending() } renderUI() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ private func renderUI(){ if !inQueue { setInActive() } else { setQueued() } if aheadOfYou == 0 { setPending() // queuePosLabel.text = "It's your turn" // urgentButton.isHidden = true } } let beaconManager = ESTBeaconManager() let beaconRegion = CLBeaconRegion( proximityUUID: NSUUID(uuidString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")! as UUID, // major: 59823, minor: 46734, identifier: "ranged region") //8492E75F-4FD6-469D-B132-043FE94921D8 /*let arianRegion = CLBeaconRegion( proximityUUID: NSUUID(uuidString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")! as UUID, major: 10773, minor: 19987, identifier: "ranged region") let sinhRegion = CLBeaconRegion( proximityUUID: NSUUID(uuidString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D")! as UUID, major: 8911, minor: 253, identifier: "ranged region") */ var proximityContentManager: ProximityContentManager! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.beaconManager.startRangingBeacons(in: self.beaconRegion) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.beaconManager.startRangingBeacons(in: self.beaconRegion) } var current: String = "" var prev1: String = "" var prev2: String = "" func beaconManager(_ manager: Any, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) { for item in beacons { print("dis con meeee", item.major, item.proximity.rawValue, item.accuracy) switch item.proximity { case .immediate, .near: prev2 = prev1 prev1 = current current = "in" if (prev2 == "in" && prev1 == "in" && current == "in" ){ getIn() } getIn() return case .unknown: print("unknown") default: print("default") } } prev2 = prev1 prev1 = current current = "out" if (prev2 == "out" && prev1 == "out" && current == "out" ) { getOut() } } func getIn() { if pending { setActive() } } func getOut() { if active { setInActive() } } }
mit
51f349eccdd0a4057b1bfc82adee47d0
26.678808
141
0.543845
4.934475
false
false
false
false
thunderousNinja/ReduxSwift
ReduxSwift/Utils.swift
1
811
// // Utils.swift // ReduxSwift // // Created by Jonathan Garcia on 12/2/15. // Copyright © 2015 wasbee. All rights reserved. // import Foundation typealias AppState = [String: Any] typealias State = Any typealias EmptyFunction = () -> Void /** * Composes single-argument functions from right to left. * * - Parameter funks: functions to compose. * * - Returns: A function obtained by composing functions from right to * left. For example, compose(f, g, h) is identical to arg => f(g(h(arg))). */ public func compose<G>(funks: [(G) -> G]) -> (G) -> G { let reversed = funks.reverse() // no reduceRight in STL :[ func compose(arg: G) -> G { return reversed.reduce(arg) { (composed: G, funk: (G) -> G) -> G in return funk(composed) } } return compose }
mit
16680eb83d49cf228d6236da15fb7ad6
25.16129
75
0.624691
3.432203
false
false
false
false
dreymonde/SwiftyNURE
Tests/GroupsProviderTests.swift
1
1503
// // GroupsProviderTests.swift // NUREAPI // // Created by Oleg Dreyman on 19.02.16. // Copyright © 2016 Oleg Dreyman. All rights reserved. // import XCTest @testable import SwiftyNURE class GroupsProviderTests: NURETests { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGroups() { let expectation = expectationWithDescription("Async group task") let provider = GroupsProvider.Remote() { groups in XCTAssertGreaterThan(groups.count, 1000) expectation.fulfill() } provider.error = defaultError provider.execute() waitForExpectationsWithTimeout(timeout, handler: nil) } func testPartGroups() { let expectation = expectationWithDescription("Async group task") let _ = GroupsProvider.Remote(matching: "14-1") { groups in groups.forEach { group in print(group.name) if !group.name.containsString("14-1") { XCTFail("It needs to contain 14-1") return } } expectation.fulfill() }.execute() waitForExpectationsWithTimeout(timeout, handler: nil) } }
mit
77b9d8343b153a2c3161e064384cf92e
29.04
111
0.609854
4.892508
false
true
false
false
KarlWarfel/nutshell-ios
Nutshell/GraphView/Tidepool Graph/SmbgGraphData.swift
1
4434
/* * Copyright (c) 2015, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * 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 License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import UIKit class SmbgGraphDataType: GraphDataType { override func typeString() -> String { return "smbg" } } class SmbgGraphDataLayer: TidepoolGraphDataLayer { // vars for drawing datapoints of this type var pixelsPerValue: CGFloat = 0.0 let circleRadius: CGFloat = 9.0 var lastCircleDrawn = CGRectNull var context: CGContext? override func typeString() -> String { return "smbg" } private let kGlucoseConversionToMgDl: CGFloat = 18.0 // // MARK: - Loading data // override func nominalPixelWidth() -> CGFloat { return circleRadius * 2 } override func loadEvent(event: CommonData, timeOffset: NSTimeInterval) { if let smbgEvent = event as? SelfMonitoringGlucose { //NSLog("Adding smbg event: \(event)") if let value = smbgEvent.value { let convertedValue = round(CGFloat(value) * kGlucoseConversionToMgDl) dataArray.append(CbgGraphDataType(value: convertedValue, timeOffset: timeOffset)) } else { NSLog("ignoring smbg event with nil value") } } } // // MARK: - Drawing data points // // override for any draw setup override func configureForDrawing() { self.pixelsPerValue = layout.yPixelsGlucose/layout.kGlucoseRange context = UIGraphicsGetCurrentContext() } // override! override func drawDataPointAtXOffset(xOffset: CGFloat, dataPoint: GraphDataType) { let centerX = xOffset var value = round(dataPoint.value) let valueForLabel = value if value > layout.kGlucoseMaxValue { value = layout.kGlucoseMaxValue } // flip the Y to compensate for origin! let centerY: CGFloat = layout.yTopOfGlucose + layout.yPixelsGlucose - floor(value * pixelsPerValue) let circleColor = value < layout.lowBoundary ? layout.lowColor : value < layout.highBoundary ? layout.targetColor : layout.highColor let largeCirclePath = UIBezierPath(ovalInRect: CGRectMake(centerX-circleRadius, centerY-circleRadius, circleRadius*2, circleRadius*2)) circleColor.setFill() largeCirclePath.fill() layout.backgroundColor.setStroke() largeCirclePath.lineWidth = 1.5 largeCirclePath.stroke() let intValue = Int(valueForLabel) let readingLabelTextContent = String(intValue) let readingLabelStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle readingLabelStyle.alignment = .Center let readingLabelFontAttributes = [NSFontAttributeName: Styles.smallSemiboldFont, NSForegroundColorAttributeName: circleColor, NSParagraphStyleAttributeName: readingLabelStyle] var readingLabelTextSize = readingLabelTextContent.boundingRectWithSize(CGSizeMake(CGFloat.infinity, CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: readingLabelFontAttributes, context: nil).size readingLabelTextSize = CGSize(width: ceil(readingLabelTextSize.width), height: ceil(readingLabelTextSize.height)) let readingLabelRect = CGRectMake(centerX-(readingLabelTextSize.width/2), centerY+circleRadius, readingLabelTextSize.width, readingLabelTextSize.height) let readingLabelPath = UIBezierPath(rect: readingLabelRect.insetBy(dx: 1.0, dy: 2.5)) layout.backgroundColor.setFill() readingLabelPath.fill() CGContextSaveGState(context!) CGContextClipToRect(context!, readingLabelRect); readingLabelTextContent.drawInRect(readingLabelRect, withAttributes: readingLabelFontAttributes) CGContextRestoreGState(context!) } }
bsd-2-clause
90a2d49999b694a05681e62a8d7f7b8b
40.055556
242
0.702977
5.114187
false
false
false
false
tikhop/TPKit
Pod/Sources/UITextView+TPExtension.swift
1
655
// // UITextView+TPExtension.swift // Pods // // Created by Pavel Tikhonenko on 10/09/16. // // import UIKit extension UITextView { func finalString(range: NSRange, replacementString string: String) -> String { let addingCharacter = range.length == 0 var currentText = text != nil ? text! : "" if addingCharacter { return currentText + string }else{ let start = currentText.index(currentText.startIndex, offsetBy: range.location) currentText.replaceSubrange(start...currentText.index(after: start), with: "") return currentText } } }
mit
9b17e5aa914ce366dc33857db28a0079
24.192308
91
0.606107
4.486301
false
false
false
false
natecook1000/swift
test/SILGen/default_constructor.swift
1
6303
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -enable-sil-ownership -primary-file %s | %FileCheck %s struct B { var i : Int, j : Float var c : C } struct C { var x : Int init() { x = 17 } } struct D { var (i, j) : (Int, Double) = (2, 3.5) } // CHECK-LABEL: sil hidden [transparent] @$S19default_constructor1DV1iSivpfi : $@convention(thin) () -> (Int, Double) // CHECK: [[METATYPE:%.*]] = metatype $@thin Int.Type // CHECK-NEXT: [[VALUE:%.*]] = integer_literal $Builtin.Int2048, 2 // CHECK: [[FN:%.*]] = function_ref @$SSi22_builtinIntegerLiteralSiBi2048__tcfC : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK-NEXT: [[LEFT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Double.Type // CHECK-NEXT: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x400C000000000000|0x4000E000000000000000}} // CHECK: [[FN:%.*]] = function_ref @$SSd20_builtinFloatLiteralSdBf{{64|80}}__tcfC : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double // CHECK-NEXT: [[RIGHT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Double) // CHECK-NEXT: return [[RESULT]] : $(Int, Double) // CHECK-LABEL: sil hidden @$S19default_constructor1DV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin D.Type) -> D // CHECK: [[THISBOX:%[0-9]+]] = alloc_box ${ var D } // CHECK: [[THIS:%[0-9]+]] = mark_uninit // CHECK: [[PB_THIS:%.*]] = project_box [[THIS]] // CHECK: [[INIT:%[0-9]+]] = function_ref @$S19default_constructor1DV1iSivpfi // CHECK: [[RESULT:%[0-9]+]] = apply [[INIT]]() // CHECK: ([[INTVAL:%[0-9]+]], [[FLOATVAL:%[0-9]+]]) = destructure_tuple [[RESULT]] // CHECK: [[IADDR:%[0-9]+]] = struct_element_addr [[PB_THIS]] : $*D, #D.i // CHECK: assign [[INTVAL]] to [[IADDR]] // CHECK: [[JADDR:%[0-9]+]] = struct_element_addr [[PB_THIS]] : $*D, #D.j // CHECK: assign [[FLOATVAL]] to [[JADDR]] class E { var i = Int64() } // FIXME(integers): the following checks should be updated for the new way + // gets invoked. <rdar://problem/29939484> // XCHECK-LABEL: sil hidden [transparent] @$S19default_constructor1EC1is5Int64Vvfi : $@convention(thin) () -> Int64 // XCHECK: [[FN:%.*]] = function_ref @$Ss5Int64VABycfC : $@convention(method) (@thin Int64.Type) -> Int64 // XCHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int64.Type // XCHECK-NEXT: [[VALUE:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thin Int64.Type) -> Int64 // XCHECK-NEXT: return [[VALUE]] : $Int64 // CHECK-LABEL: sil hidden @$S19default_constructor1EC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned E) -> @owned E // CHECK: bb0([[SELFIN:%[0-9]+]] : @owned $E) // CHECK: [[SELF:%[0-9]+]] = mark_uninitialized // CHECK: [[INIT:%[0-9]+]] = function_ref @$S19default_constructor1EC1is5Int64Vvpfi : $@convention(thin) () -> Int64 // CHECK-NEXT: [[VALUE:%[0-9]+]] = apply [[INIT]]() : $@convention(thin) () -> Int64 // CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[IREF:%[0-9]+]] = ref_element_addr [[BORROWED_SELF]] : $E, #E.i // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[IREF]] : $*Int64 // CHECK-NEXT: assign [[VALUE]] to [[WRITE]] : $*Int64 // CHECK-NEXT: end_access [[WRITE]] : $*Int64 // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: destroy_value [[SELF]] // CHECK-NEXT: return [[SELF_COPY]] : $E class F : E { } // CHECK-LABEL: sil hidden @$S19default_constructor1FCACycfc : $@convention(method) (@owned F) -> @owned F // CHECK: bb0([[ORIGSELF:%[0-9]+]] : @owned $F) // CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var F } // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[SELF]] // CHECK-NEXT: store [[ORIGSELF]] to [init] [[PB]] : $*F // CHECK-NEXT: [[SELFP:%[0-9]+]] = load [take] [[PB]] : $*F // CHECK-NEXT: [[E:%[0-9]]] = upcast [[SELFP]] : $F to $E // CHECK: [[E_CTOR:%[0-9]+]] = function_ref @$S19default_constructor1ECACycfc : $@convention(method) (@owned E) -> @owned E // CHECK-NEXT: [[ESELF:%[0-9]]] = apply [[E_CTOR]]([[E]]) : $@convention(method) (@owned E) -> @owned E // CHECK-NEXT: [[ESELFW:%[0-9]+]] = unchecked_ref_cast [[ESELF]] : $E to $F // CHECK-NEXT: store [[ESELFW]] to [init] [[PB]] : $*F // CHECK-NEXT: [[SELFP:%[0-9]+]] = load [copy] [[PB]] : $*F // CHECK-NEXT: destroy_value [[SELF]] : ${ var F } // CHECK-NEXT: return [[SELFP]] : $F // <rdar://problem/19780343> Default constructor for a struct with optional doesn't compile // This shouldn't get a default init, since it would be pointless (bar can never // be reassigned). It should get a memberwise init though. struct G { let bar: Int32? } // CHECK-NOT: default_constructor.G.init() // CHECK-LABEL: default_constructor.G.init(bar: Swift.Optional<Swift.Int32>) // CHECK-NEXT: sil hidden @$S19default_constructor1GV{{[_0-9a-zA-Z]*}}fC // CHECK-NOT: default_constructor.G.init() struct H<T> { var opt: T? // CHECK-LABEL: sil hidden @$S19default_constructor1HVyACyxGqd__clufC : $@convention(method) <T><U> (@in U, @thin H<T>.Type) -> @out H<T> { // CHECK: [[INIT_FN:%[0-9]+]] = function_ref @$S19default_constructor1HV3optxSgvpfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK-NEXT: [[OPT_T:%[0-9]+]] = alloc_stack $Optional<T> // CHECK-NEXT: apply [[INIT_FN]]<T>([[OPT_T]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> init<U>(_: U) { } } // <rdar://problem/29605388> Member initializer for non-generic type with generic constructor doesn't compile struct I { var x: Int = 0 // CHECK-LABEL: sil hidden @$S19default_constructor1IVyACxclufC : $@convention(method) <T> (@in T, @thin I.Type) -> I { // CHECK: [[INIT_FN:%[0-9]+]] = function_ref @$S19default_constructor1IV1xSivpfi : $@convention(thin) () -> Int // CHECK: [[RESULT:%[0-9]+]] = apply [[INIT_FN]]() : $@convention(thin) () -> Int // CHECK: [[X_ADDR:%[0-9]+]] = struct_element_addr {{.*}} : $*I, #I.x // CHECK: assign [[RESULT]] to [[X_ADDR]] : $*Int init<T>(_: T) {} }
apache-2.0
a3b248b70f5e4db94d0b6d404463917f
50.631148
165
0.606287
2.978251
false
false
false
false
long3zhuang/DYZB_ZQL
DouYuZB/DouYuZB/Classes/Tools/Extension/UIBarButtonItem-Extension.swift
1
1424
// // UIBarButtonItem-Extension.swift // DouYuZB // // Created by 周泉龙 on 17/2/5. // Copyright © 2017年 love阿木蛋花. All rights reserved. // import UIKit extension UIBarButtonItem { // 扩展一个类方法 class func creatItem(imgaeName :String ,highImageName : String, size : CGSize) ->UIBarButtonItem { let btn = UIButton() btn.setImage(UIImage(named:imgaeName), for: .normal) btn.setImage(UIImage(named:highImageName), for: .highlighted) btn.frame = CGRect(origin: CGPoint.zero, size: size) return UIBarButtonItem(customView: btn) } // 扩展一个构造方法 需要两个条件1.只能在extention中构造便利构造函数,以convenience开头 // 2.在构造函数中必须明确调用一个设计的构造函数(self) convenience init(imgaeName :String ,highImageName: String = "", size: CGSize = CGSize.zero) { let btn = UIButton() // 设置button图片 btn.setImage(UIImage(named:imgaeName), for: .normal) if highImageName != "" { btn.setImage(UIImage(named:highImageName), for: .highlighted) } // 设置button尺寸 if size == CGSize.zero { btn.sizeToFit() }else { btn.frame = CGRect(origin: CGPoint.zero, size: size) } self.init(customView : btn) } }
mit
b49681501dab595480f4b14be93eecba
29.404762
102
0.600626
3.95356
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/DataZoom/InsideDataZoom.swift
1
14820
// // InsideDataZoom.swift // SwiftyEcharts // // Created by Pluto-Y on 17/01/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 内置型数据区域缩放组件(dataZoomInside) /// /// 所谓『内置』,即内置在坐标系中。 /// /// - 平移:在坐标系中滑动拖拽进行数据区域平移。 /// - 缩放: /// - PC端:鼠标在坐标系范围内滚轮滚动(MAC触控板类同) /// - 移动端:在移动端触屏上,支持两指滑动缩放。 public final class InsideDataZoom: DataZoom { /// 类型 public var type: String { return "inside" } /// 是否停止组件的功能。 public var disabled: Bool? /// 设置 dataZoom-inside 组件控制的 x轴(即xAxis,是直角坐标系中的概念,参见 grid)。 /// 不指定时,当 dataZoom-inside.orient 为 'horizontal'时,默认控制和 dataZoom 平行的第一个 xAxis。但是不建议使用默认值,建议显式指定。 /// 如果是 number 表示控制一个轴,如果是 Array 表示控制多个轴。 /// 例如有如下 ECharts option: /// /// option: { /// xAxis: [ /// {...}, // 第一个 xAxis /// {...}, // 第二个 xAxis /// {...}, // 第三个 xAxis /// {...} // 第四个 xAxis /// ], /// dataZoom: [ /// { // 第一个 dataZoom 组件 /// xAxisIndex: [0, 2] // 表示这个 dataZoom 组件控制 第一个 和 第三个 xAxis /// }, /// { // 第二个 dataZoom 组件 /// xAxisIndex: 3 // 表示这个 dataZoom 组件控制 第四个 xAxis /// } //// ] /// } public var xAxisIndex: OneOrMore<UInt8>? /// 设置 dataZoom-inside 组件控制的 x轴(即yAxis,是直角坐标系中的概念,参见 grid)。 /// 不指定时,当 dataZoom-inside.orient 为 'vertical'时,默认控制和 dataZoom 平行的第一个 yAxis。但是不建议使用默认值,建议显式指定。 /// 如果是 number 表示控制一个轴,如果是 Array 表示控制多个轴。 /// 例如有如下 ECharts option: /// /// option: { /// yAxis: [ /// {...}, // 第一个 yAxis /// {...}, // 第二个 yAxis /// {...}, // 第三个 yAxis /// {...} // 第四个 yAxis /// ], /// dataZoom: [ /// { // 第一个 dataZoom 组件 /// yAxisIndex: [0, 2] // 表示这个 dataZoom 组件控制 第一个 和 第三个 yAxis /// }, /// { // 第二个 dataZoom 组件 /// yAxisIndex: 3 // 表示这个 dataZoom 组件控制 第四个 yAxis /// } //// ] /// } public var yAxisIndex: OneOrMore<UInt8>? /// 设置 dataZoom-inside 组件控制的 radius 轴(即radiusAxis,是直角坐标系中的概念,参见 polar)。 /// 如果是 number 表示控制一个轴,如果是 Array 表示控制多个轴。 /// 例如有如下 ECharts option: /// /// option: { /// radiusAxis: [ /// {...}, // 第一个 radiusAxis /// {...}, // 第二个 radiusAxis /// {...}, // 第三个 radiusAxis /// {...} // 第四个 radiusAxis /// ], /// dataZoom: [ /// { // 第一个 dataZoom 组件 /// radiusAxisIndex: [0, 2] // 表示这个 dataZoom 组件控制 第一个 和 第三个 radiusAxis /// }, /// { // 第二个 dataZoom 组件 /// radiusAxisIndex: 3 // 表示这个 dataZoom 组件控制 第四个 radiusAxis /// } /// ] /// } public var radiusAxisIndex: OneOrMore<UInt8>? /// 设置 dataZoom-inside 组件控制的 angle 轴(即angleAxis,是直角坐标系中的概念,参见 polar)。 /// 如果是 number 表示控制一个轴,如果是 Array 表示控制多个轴。 /// 例如有如下 ECharts option: /// /// option: { /// angleAxis: [ /// {...}, // 第一个 angleAxis /// {...}, // 第二个 angleAxis /// {...}, // 第三个 angleAxis /// {...} // 第四个 angleAxis /// ], /// dataZoom: [ /// { // 第一个 dataZoom 组件 /// angleAxisIndex: [0, 2] // 表示这个 dataZoom 组件控制 第一个 和 第三个 angleAxis /// }, /// { // 第二个 dataZoom 组件 /// angleAxisIndex: 3 // 表示这个 dataZoom 组件控制 第四个 angleAxis /// } /// ] /// } public var angleAxisIndex: OneOrMore<UInt8>? /// dataZoom 的运行原理是通过 数据过滤 来达到 数据窗口缩放 的效果。数据过滤模式的设置不同,效果也不同。 /// 可选值为: /// - 'filter':当前数据窗口外的数据,被 过滤掉。即会影响其他轴的数据范围。 /// - 'empty':当前数据窗口外的数据,被 设置为空。即不会影响其他轴的数据范围。 /// 如何设置,由用户根据场景和需求自己决定。经验来说: /// - 当『只有 X 轴 或 只有 Y 轴受 dataZoom 组件控制』时,常使用 filterMode: 'filter',这样能使另一个轴自适应过滤后的数值范围。 /// - 当『X 轴 Y 轴分别受 dataZoom 组件控制』时: /// - 如果 X 轴和 Y 轴是『同等地位的、不应互相影响的』,比如在『双数值轴散点图』中,那么两个轴可都设为 fiterMode: 'empty'。 /// - 如果 X 轴为主,Y 轴为辅,比如在『柱状图』中,需要『拖动 dataZoomX 改变 X 轴过滤柱子时,Y 轴的范围也自适应剩余柱子的高度』,『拖动 dataZoomY 改变 Y 轴过滤柱子时,X 轴范围不受影响』,那么就 X轴设为 fiterMode: 'filter',Y 轴设为 fiterMode: 'empty',即主轴 'filter',辅轴 'empty'。 /// 下面是个具体例子: /// /// option = { /// dataZoom: [ /// { /// id: 'dataZoomX', /// type: 'slider', /// xAxisIndex: [0], /// filterMode: 'filter' /// }, /// { /// id: 'dataZoomY', /// type: 'slider', /// yAxisIndex: [0], /// filterMode: 'empty' /// } /// ], /// xAxis: {type: 'value'}, /// yAxis: {type: 'value'}, /// series{ /// type: 'bar', /// data: [ /// // 第一列对应 X 轴,第二列对应 Y 轴。 /// [12, 24, 36], /// [90, 80, 70], /// [3, 9, 27], /// [1, 11, 111] /// ] /// } /// } /// /// 上例中,dataZoomX 的 filterMode 设置为 'filter'。于是,假设当用户拖拽 dataZoomX(不去动 dataZoomY)导致其 valueWindow 变为 [2, 50] 时,dataZoomX 对 series.data 的第一列进行遍历,窗口外的整项去掉,最终得到的 series.data 为: /// /// [ /// // 第一列对应 X 轴,第二列对应 Y 轴。 /// [12, 24, 36], /// // [90, 80, 70] 整项被过滤掉,因为 90 在 dataWindow 之外。 /// [3, 9, 27] /// // [1, 11, 111] 整项被过滤掉,因为 1 在 dataWindow 之外。 /// ] /// /// 过滤前,series.data 中对应 Y 轴的值有 24、80、9、11,过滤后,只剩下 24 和 9,那么 Y 轴的显示范围就会自动改变以适应剩下的这两个值的显示(如果 Y 轴没有被设置 min、max 固定其显示范围的话)。 /// 所以,filterMode: 'filter' 的效果是:过滤数据后使另外的轴也能自动适应当前数据的范围。 /// 再从头来,上例中 dataZoomY 的 filterMode 设置为 'empty'。于是,假设当用户拖拽 dataZoomY(不去动 dataZoomX)导致其 dataWindow 变为 [10, 60] 时,dataZoomY 对 series.data 的第二列进行遍历,窗口外的值被设置为 empty (即替换为 NaN,这样设置为空的项,其所对应柱形,在 X 轴还有占位,只是不显示出来)。最终得到的 series.data 为: /// /// [ /// // 第一列对应 X 轴,第二列对应 Y 轴。 /// [12, 24, 36], /// [90, NaN, 70], // 设置为 empty (NaN) /// [3, NaN, 27], // 设置为 empty (NaN) /// [1, 11, 111] /// ] /// /// 这时,series.data 中对应于 X 轴的值仍然全部保留不受影响,为 12、90、3、1。那么用户对 dataZoomY 的拖拽操作不会影响到 X 轴的范围。这样的效果,对于离群点(outlier)过滤功能,比较清晰。 /// 如地址的例子: public var filterMode: FilterMode? /// 数据窗口范围的起始百分比。范围是:0 ~ 100。表示 0% ~ 100%。 public var start: Float? /// 数据窗口范围的结束百分比。范围是:0 ~ 100。 public var end: Float? /// 数据窗口范围的起始数值。如果设置了 dataZoom-inside.start 则 startValue 失效。 /// dataZoom-inside.startValue 和 dataZoom-inside.endValue 共同用 绝对数值 的形式定义了数据窗口范围。 /// 注意,如果轴的类型为 category,则 startValue 既可以设置为 axis.data 数组的 index,也可以设置为数组值本身。 但是如果设置为数组值本身,会在内部自动转化为数组的 index。 public var startValue: Float? /// 数据窗口范围的结束数值。如果设置了 dataZoom-inside.end 则 endValue 失效。 /// dataZoom-inside.startValue 和 dataZoom-inside.endValue 共同用 绝对数值 的形式定义了数据窗口范围。 /// 注意,如果轴的类型为 category,则 endValue 即可以设置为 axis.data 数组的 index,也可以设置为数组值本身。 但是如果设置为数组值本身,会在内部自动转化为数组的 index。 public var endValue: Float? /// 布局方式是横还是竖。不仅是布局方式,对于直角坐标系而言,也决定了,缺省情况控制横向数轴还是纵向数轴。 public var orient: Orient? /// 是否锁定选择区域(或叫做数据窗口)的大小。 /// 如果设置为 true 则锁定选择区域的大小,也就是说,只能平移,不能缩放。 public var zoomLock: Bool? /// 设置触发视图刷新的频率。单位为毫秒(ms)。 /// 如果 animation 设为 true 且 animationDurationUpdate 大于 0,可以保持 throttle 为默认值 100(或者设置为大于 0 的值),否则拖拽时有可能画面感觉卡顿。 /// 如果 animation 设为 false 或者 animationDurationUpdate 设为 0,且在数据量不大时,拖拽时画面感觉卡顿,可以把尝试把 throttle 设为 0 来改善。 public var throttle: Float? public init() {} } extension InsideDataZoom: Enumable { public enum Enums { case disabled(Bool), xAxisIndex(UInt8), xAxisIndexes([UInt8]), yAxisIndex(UInt8), yAxisIndexes([UInt8]), radiusAxisIndex(UInt8), radiusAxisIndexes([UInt8]), angleAxisIndex(UInt8), angleAxisIndexes([UInt8]), filterMode(FilterMode), start(Float), end(Float), startValue(Float), endValue(Float), orient(Orient), zoomLock(Bool), throttle(Float) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .disabled(disabled): self.disabled = disabled case let .xAxisIndex(xAxisIndex): self.xAxisIndex = OneOrMore(one: xAxisIndex) case let .xAxisIndexes(xAxisIndexes): self.xAxisIndex = OneOrMore(more: xAxisIndexes) case let .yAxisIndex(yAxisIndex): self.yAxisIndex = OneOrMore(one: yAxisIndex) case let .yAxisIndexes(yAxisIndexes): self.yAxisIndex = OneOrMore(more: yAxisIndexes) case let .radiusAxisIndex(radiusAxisIndex): self.radiusAxisIndex = OneOrMore(one: radiusAxisIndex) case let .radiusAxisIndexes(radiusAxisIndexes): self.radiusAxisIndex = OneOrMore(more: radiusAxisIndexes) case let .angleAxisIndex(angleAxisIndex): self.angleAxisIndex = OneOrMore(one: angleAxisIndex) case let .angleAxisIndexes(angleAxisIndexes): self.angleAxisIndex = OneOrMore(more: angleAxisIndexes) case let .filterMode(filterMode): self.filterMode = filterMode case let .start(start): self.start = start case let .end(end): self.end = end case let .startValue(startValue): self.startValue = startValue case let .endValue(endValue): self.endValue = endValue case let .orient(orient): self.orient = orient case let .zoomLock(zoomLock): self.zoomLock = zoomLock case let .throttle(throttle): self.throttle = throttle } } } } extension InsideDataZoom: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["disabled"] = disabled map["xAxisIndex"] = xAxisIndex map["yAxisIndex"] = yAxisIndex map["radiusAxisIndex"] = radiusAxisIndex map["angleAxisIndex"] = angleAxisIndex map["filterMode"] = filterMode map["start"] = start map["end"] = end map["startValue"] = startValue map["endValue"] = endValue map["orient"] = orient map["zoomLock"] = zoomLock map["throttle"] = throttle } }
mit
153afc30c4839b1d51d1e0937c5cb0dd
40.958955
348
0.497999
3.770959
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Mark/MarkPoint.swift
1
6569
// // MarkPoint.swift // SwiftyEcharts // // Created by Pluto-Y on 16/01/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // public final class MarkPoint: Symbolized, Animatable { /// 标记的图形。 public var symbol: OneOrMore<Symbol>? /// 标记的大小 public var symbolSize: FunctionOrFloatOrPair? /// 标记的旋转角度。注意在 markLine 中当 symbol 为 'arrow' 时会忽略 symbolRotate 强制设置为切线的角度。 public var symbolRotate: Float? /// 标记相对于原本位置的偏移。默认情况下,标记会居中置放在数据对应的位置,但是如果 symbol 是自定义的矢量路径或者图片,就有可能不希望 symbol 居中。这时候可以使用该配置项配置 symbol 相对于原本居中的偏移,可以是绝对的像素值,也可以是相对的百分比。 /// 例如 [0, '50%'] 就是把自己向上移动了一半的位置,在 symbol 图形是气泡的时候可以让图形下端的箭头对准数据点。 public var symbolOffset: Point? /// 图形是否不响应和触发鼠标事件,默认为 false,即响应和触发鼠标事件。 public var silent: Bool? /// 标注的文本。 public var label: EmphasisLabel? /// 标注的样式。 public var itemStyle: ItemStyle? /// 标注的数据数组 public var data: [Jsonable]? /// 是否开启动画。 public var animation: Bool? /// 是否开启动画的阈值,当单个系列显示的图形数量大于这个阈值时会关闭动画。 public var animationThreshold: Float? /// 初始动画的时长,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的初始动画效果: /// /// animationDuration: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDuration: Time? /// 初始动画的缓动效果。不同的缓动效果可以参考 public var animationEasing: EasingFunction? /// 初始动画的延迟,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的初始动画效果。 /// /// 如下示例: /// /// animationDuration: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDelay: Time? /// 数据更新动画的时长。 /// 支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的更新动画效果: /// animationDurationUpdate: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDurationUpdate: Time? /// 数据更新动画的缓动效果。 public var animationEasingUpdate: EasingFunction? /// 数据更新动画的延迟,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的更新动画效果。 /// 如下示例: /// /// animationDelayUpdate: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDelayUpdate: Time? public var tooltip: Tooltip? public init() { } } extension MarkPoint: Enumable { public enum Enums { case symbol(Symbol), symbolSize(FunctionOrFloatOrPair), symbolRotate(Float), symbolOffset(Point), silent(Bool), label(EmphasisLabel), itemStyle(ItemStyle), data([Jsonable]), animation(Bool), animationThreshold(Float), animationDuration(Time), animationEasing(EasingFunction), animationDelay(Time), animationDurationUpdate(Time), animationEasingUpdate(EasingFunction), animationDelayUpdate(Time), tooltip(Tooltip) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .symbol(symbol): self.symbol = OneOrMore(one: symbol) case let .symbolSize(symbolSize): self.symbolSize = symbolSize case let .symbolRotate(symbolRotate): self.symbolRotate = symbolRotate case let .symbolOffset(symbolOffset): self.symbolOffset = symbolOffset case let .silent(silent): self.silent = silent case let .label(label): self.label = label case let .itemStyle(itemStyle): self.itemStyle = itemStyle case let .data(data): self.data = data case let .animation(animation): self.animation = animation case let .animationThreshold(animationThreshold): self.animationThreshold = animationThreshold case let .animationDuration(animationDuration): self.animationDuration = animationDuration case let .animationEasing(animationEasing): self.animationEasing = animationEasing case let .animationDelay(animationDelay): self.animationDelay = animationDelay case let .animationDurationUpdate(animationDurationUpdate): self.animationDurationUpdate = animationDurationUpdate case let .animationEasingUpdate(animationEasingUpdate): self.animationEasingUpdate = animationEasingUpdate case let .animationDelayUpdate(animationDelayUpdate): self.animationDelayUpdate = animationDelayUpdate case let .tooltip(tooltip): self.tooltip = tooltip } } } } extension MarkPoint: Mappable { public func mapping(_ map: Mapper) { map["symbol"] = symbol map["symbolSize"] = symbolSize map["symbolRotate"] = symbolRotate map["symbolOffset"] = symbolOffset map["silent"] = silent map["label"] = label map["itemStyle"] = itemStyle map["data"] = data map["animation"] = animation map["animationThreshold"] = animationThreshold map["animationDuration"] = animationDuration map["animationEasing"] = animationEasing map["animationDelay"] = animationDelay map["animationDurationUpdate"] = animationDurationUpdate map["animationEasingUpdate"] = animationEasingUpdate map["animationDelayUpdate"] = animationDelayUpdate map["tooltip"] = tooltip } }
mit
62262ff2fe558f435d992115cf2dceb6
37.363636
421
0.626139
5.093779
false
false
false
false
smoope/swift-client-conversation
Framework/Pods/SwiftyTraverson/Pod/Classes/Traverson.swift
2
14936
/* * Copyright 2016 smoope GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import Alamofire import URITemplate import SwiftyJSON /** Swift implementation of a Hypermedia API/HATEOAS client */ open class Traverson { fileprivate var client: Alamofire.SessionManager fileprivate var authenticator: TraversonAuthenticator? fileprivate var preemptive: Bool fileprivate var dispatchQueue: DispatchQueue? fileprivate var current: Traversing? /** Constructor with parameters - Parameters: - configuration: Configuration - authenticator: Authenticator */ fileprivate init(configuration: URLSessionConfiguration, authenticator: TraversonAuthenticator? = nil, preemptive: Bool, dispatchQueue: DispatchQueue? = nil) { self.client = Alamofire.SessionManager(configuration: configuration) self.authenticator = authenticator self.preemptive = preemptive self.dispatchQueue = dispatchQueue } /** Constructor with parameters */ public convenience init() { self.init(configuration: URLSessionConfiguration.default, preemptive: false) } /** Sets the base URL - Parameter baseUri: URL to start with - Returns: Traversing object */ open func from(_ baseUri: String) -> Traversing { current = Traversing(baseUri: baseUri, client: client, authenticator: authenticator, preemptive: preemptive, dispatchQueue: dispatchQueue) return current! } /** Creates a new request based on exsiting one, allowing multiple usage of the same `Traverson` instance - Returns: Traversing object */ open func newRequest() -> Traversing { return current! } /** Result callback object */ public typealias TraversonResultHandler = (_ result: TraversonResult?, _ error: Error?) -> Void /** Traverson builder */ open class Builder { fileprivate var configuration: URLSessionConfiguration fileprivate var defaultHeaders: [AnyHashable: Any] fileprivate var useCache: Bool fileprivate var requestTimeout: TimeInterval fileprivate var responseTimeout: TimeInterval fileprivate var authenticator: TraversonAuthenticator? fileprivate var dispatchQueue: DispatchQueue? = nil fileprivate var preemptive: Bool public init() { self.configuration = URLSessionConfiguration.default self.defaultHeaders = self.configuration.httpAdditionalHeaders ?? [:] self.useCache = true self.requestTimeout = self.configuration.timeoutIntervalForRequest self.responseTimeout = self.configuration.timeoutIntervalForResource self.preemptive = false } /** Adds default headers collection - Parameters defaultHeaders: Collection of default headers to use */ @discardableResult open func defaultHeaders(_ defaultHeaders: [String: String]) -> Builder { self.defaultHeaders = defaultHeaders return self } /** Adds default header - Parameters: - name: Header's name - value: Header's value */ @discardableResult open func defaultHeader(_ name: String, value: String) -> Builder { defaultHeaders[name] = value return self } /** Disables cache */ @discardableResult open func disableCache() -> Builder { useCache = false return self } /** Sets read timeout - Parameter timout: Request timeout */ @discardableResult open func requestTimeout(_ timeout: TimeInterval) -> Builder { requestTimeout = timeout return self } /** Sets read timeout - Parameter timout: Response timeout */ @discardableResult open func responseTimeout(_ timeout: TimeInterval) -> Builder { responseTimeout = timeout return self } /** Sets authenticator object - Parameter authenticator: Authenticator */ @discardableResult open func authenticator(_ authenticator: TraversonAuthenticator) -> Builder { return self.authenticator(authenticator, preemptive: false) } /** Sets authenticator object - Parameter authenticator: Authenticator - Parameter preemptive: Pre-authenticate requests */ @discardableResult open func authenticator(_ authenticator: TraversonAuthenticator, preemptive: Bool) -> Builder { self.authenticator = authenticator self.preemptive = preemptive return self } /** Sets queue - Parameter queue: Queue on which the result handler get called */ @discardableResult open func dispatchQueue(_ queue: DispatchQueue) -> Builder { self.dispatchQueue = queue return self } /** Builds the Traverson object with custom configuration */ open func build() -> Traverson { configuration.httpAdditionalHeaders = defaultHeaders configuration.timeoutIntervalForRequest = requestTimeout configuration.timeoutIntervalForResource = responseTimeout if !useCache { configuration.requestCachePolicy = .reloadIgnoringLocalCacheData } return Traverson(configuration: configuration, authenticator: authenticator, preemptive: preemptive, dispatchQueue: dispatchQueue) } } open class Traversing { fileprivate var baseUri: String fileprivate var client: Alamofire.SessionManager fileprivate var rels: [String] fileprivate var headers: [String: String] fileprivate var templateParameters: [String: String] fileprivate var dispatchQueue: DispatchQueue? = nil fileprivate var follow201Location:Bool = false fileprivate var traverse:Bool = true fileprivate var linkResolver: TraversonLinkResolver = TraversonJsonHalLinkResolver() fileprivate var authenticator: TraversonAuthenticator? fileprivate var preemptive: Bool fileprivate typealias ResolveUrlHandler = (_ url: String?, _ error: Error?) -> Void fileprivate init(baseUri: String, client: Alamofire.SessionManager, authenticator: TraversonAuthenticator? = nil, preemptive: Bool, dispatchQueue: DispatchQueue? = nil) { self.baseUri = baseUri self.client = client self.rels = Array() self.headers = Dictionary() self.templateParameters = Dictionary() self.authenticator = authenticator self.preemptive = preemptive self.dispatchQueue = dispatchQueue } fileprivate func prepareRequest(_ url: String, method: TraversonRequestMethod, object: [String: AnyObject]? = nil) -> DataRequest { switch method { case .get: return client.request(url, method: .get, headers: headers) case .post: return client.request(url, method: .post, parameters: object, encoding: JSONEncoding.default, headers: headers) case .put: return client.request(url, method: .put, parameters: object, encoding: JSONEncoding.default, headers: headers) case .delete: return client.request(url, method: .delete, headers: headers) } } fileprivate func prepareResponse(_ response: Data) -> JSON { return JSON(data: response as Data); } fileprivate func call(_ url: String? = nil, method: TraversonRequestMethod, object: [String: AnyObject]? = nil, retries: Int = 0, callback: @escaping TraversonResultHandler) { resolveUrl(url, success: { resolvedUrl, error in if let resolvedUrl = resolvedUrl { self.prepareRequest( resolvedUrl, method: method, object: object ) .response(queue: self.dispatchQueue) { result in if let response = result.response, response.statusCode == 401 { if let authenticator = self.authenticator { if retries < authenticator.retries { authenticator.authenticate { authenticatorResult in if let authorization = authenticatorResult { self.headers["Authorization"] = authorization self.call(resolvedUrl, method: method, object: object, retries: retries + 1, callback: callback) } else { callback(nil, TraversonError.authenticatorError()) } } } else { callback(nil, TraversonError.accessDenied()) } } else { callback(nil, TraversonError.accessDenied()) } } else { if result.response?.statusCode == 201, self.follow201Location { if let location = result.response?.allHeaderFields["Location"] as? String { self.call(location, method: .get, callback: callback) } else { callback(nil, TraversonError.httpException(code: 201, message: "No Location Header found")) } } else if let data = result.data, data.count > 0 { callback(TraversonResult(data: self.prepareResponse(data)), nil) } else { callback(nil, TraversonError.unknown()) } } } } else { callback(nil, error) } }) } /* Follows specified endpoints - Parameter rels: Collection of endpoints to follow - Returns: Traversing object */ @discardableResult open func follow(_ rels: String...) -> Traversing { for rel in rels { self.rels.append(rel) } self.traverse = true return self } fileprivate func traverseToFinalUrl(_ success: @escaping ResolveUrlHandler) { do { try getAndFindLinkWithRel(baseUri, rels: rels.makeIterator(), success: success) } catch let error { success(nil, error) } } fileprivate func authenticate(_ success: @escaping ResolveUrlHandler) { if let authenticator = self.authenticator { authenticator.authenticate { authenticatorResult in if let authorization = authenticatorResult { self.headers["Authorization"] = authorization self.traverseUrl(success) } else { success(nil, TraversonError.authenticatorError()) } } } else { traverseUrl(success) } } fileprivate func resolveUrl(_ url: String? = nil, success: @escaping ResolveUrlHandler) { if url == nil { if (self.preemptive && self.headers["Authorization"] == nil) { authenticate(success) } else { traverseUrl(success) } } else { success(url!, nil) } } fileprivate func traverseUrl(_ success: @escaping ResolveUrlHandler) { if self.traverse { traverseToFinalUrl(success) } else { success(URITemplate(template: rels.first!).expand(templateParameters), nil) } } private func getAndFindLinkWithRel(_ url: String, rels: IndexingIterator<[String]>, success: @escaping ResolveUrlHandler) throws { var rels = rels let next = rels.next() if (next == nil) { success(url, nil) } else { call(url, method: TraversonRequestMethod.get, callback: { data, error in if let e = error { success(nil, e) } else { do { if let json = data!.data { let link = try self.linkResolver.findNext(next!, data: json) try self.getAndFindLinkWithRel( URITemplate(template: link).expand(self.templateParameters), rels: rels, success: success ) } else { throw TraversonError.unknown() } } catch let error { success(nil, error) } } }) } } /* Follows specified endpoints - Parameter link: Endpoint to follow - Returns: Traversing object */ @discardableResult open func followUri(_ link: String) -> Traversing { self.rels.append(link) self.traverse = false return self } @discardableResult open func follow201Location(_ follow: Bool) -> Traversing { self.follow201Location = follow return self } @discardableResult open func json() -> Traversing { self.linkResolver = TraversonJsonLinkResolver() return self } @discardableResult open func jsonHal() -> Traversing { self.linkResolver = TraversonJsonHalLinkResolver() return self } @discardableResult open func withHeaders(_ headers: [String: String]) -> Traversing { for (k, v) in headers { self.headers[k] = v } return self } @discardableResult open func withHeader(_ name: String, value: String) -> Traversing { self.headers[name] = value return self } @discardableResult open func withTemplateParameter(_ name: String, value: String) -> Traversing { self.templateParameters[name] = value return self } @discardableResult open func withTemplateParameters(_ parameters: [String: String]) -> Traversing { for (k, v) in parameters { self.templateParameters[k] = v } return self } open func get(_ result: @escaping TraversonResultHandler) { call(method: TraversonRequestMethod.get, callback: result) } open func post(_ object: [String: AnyObject], result: @escaping TraversonResultHandler) { call(method: TraversonRequestMethod.post, object: object, callback: result) } open func put(_ object: [String: AnyObject], result: @escaping TraversonResultHandler) { call(method: TraversonRequestMethod.put, object: object, callback: result) } open func delete(_ result: @escaping TraversonResultHandler) { call(method: TraversonRequestMethod.delete, callback: result) } } }
apache-2.0
20198c47316a9021f99883304515b6d8
28.872
179
0.622657
5.405718
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Site Creation/DesignSelection/SiteDesignContentCollectionViewController.swift
1
8937
import UIKit import WordPressKit extension RemoteSiteDesign: Thumbnail { var urlDesktop: String? { screenshot } var urlTablet: String? { tabletScreenshot } var urlMobile: String? { mobileScreenshot} } class SiteDesignSection: CategorySection { var category: RemoteSiteDesignCategory var designs: [RemoteSiteDesign] var categorySlug: String { category.slug } var title: String { category.title } var emoji: String? { category.emoji } var description: String? { category.description } var thumbnails: [Thumbnail] { designs } var scrollOffset: CGPoint init(category: RemoteSiteDesignCategory, designs: [RemoteSiteDesign]) { self.category = category self.designs = designs self.scrollOffset = .zero } } class SiteDesignContentCollectionViewController: FilterableCategoriesViewController, UIPopoverPresentationControllerDelegate { typealias TemplateGroup = SiteDesignRequest.TemplateGroup private let templateGroups: [TemplateGroup] = [.stable, .singlePage] let completion: SiteDesignStep.SiteDesignSelection let restAPI = WordPressComRestApi.anonymousApi(userAgent: WPUserAgent.wordPress(), localeKey: WordPressComRestApi.LocaleKeyV2) var selectedIndexPath: IndexPath? = nil private var sections: [SiteDesignSection] = [] internal override var categorySections: [CategorySection] { get { sections }} var siteDesigns = RemoteSiteDesigns() { didSet { if oldValue.categories.count == 0 { scrollableView.setContentOffset(.zero, animated: false) } sections = siteDesigns.categories.map { category in SiteDesignSection(category: category, designs: siteDesigns.designs.filter { design in design.categories.map({$0.slug}).contains(category.slug) }) } NSLog("sections: %@", String(describing: sections)) contentSizeWillChange() tableView.reloadData() } } var previewDeviceButtonItem: UIBarButtonItem? var selectedDesign: RemoteSiteDesign? { guard let sectionIndex = selectedItem?.section, let position = selectedItem?.item else { return nil } return sections[sectionIndex].designs[position] } init(_ completion: @escaping SiteDesignStep.SiteDesignSelection) { self.completion = completion super.init( analyticsLocation: "site_creation", mainTitle: NSLocalizedString("Choose a design", comment: "Title for the screen to pick a design and homepage for a site."), prompt: NSLocalizedString("Pick your favorite homepage layout. You can edit and customize it later.", comment: "Prompt for the screen to pick a design and homepage for a site."), primaryActionTitle: NSLocalizedString("Choose", comment: "Title for the button to progress with the selected site homepage design"), secondaryActionTitle: NSLocalizedString("Preview", comment: "Title for button to preview a selected homepage design") ) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.backButtonTitle = NSLocalizedString("Design", comment: "Shortened version of the main title to be used in back navigation") fetchSiteDesigns() configureCloseButton() configureSkipButton() configurePreviewDeviceButton() SiteCreationAnalyticsHelper.trackSiteDesignViewed(previewMode: selectedPreviewDevice) } private func fetchSiteDesigns() { isLoading = true let thumbnailSize = CategorySectionTableViewCell.expectedThumbnailSize let request = SiteDesignRequest(withThumbnailSize: thumbnailSize, withGroups: templateGroups) SiteDesignServiceRemote.fetchSiteDesigns(restAPI, request: request) { [weak self] (response) in DispatchQueue.main.async { switch response { case .success(let result): self?.dismissNoResultsController() self?.siteDesigns = result case .failure(let error): self?.handleError(error) } self?.isLoading = false } } } private func configureSkipButton() { let skip = UIBarButtonItem(title: NSLocalizedString("Skip", comment: "Continue without making a selection"), style: .done, target: self, action: #selector(skipButtonTapped)) navigationItem.rightBarButtonItem = skip } private func configurePreviewDeviceButton() { let button = UIBarButtonItem(image: UIImage(named: "icon-devices"), style: .plain, target: self, action: #selector(previewDeviceButtonTapped)) previewDeviceButtonItem = button navigationItem.rightBarButtonItems?.append(button) } private func configureCloseButton() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: "Cancel site creation"), style: .done, target: self, action: #selector(closeButtonTapped)) } @objc func skipButtonTapped(_ sender: Any) { SiteCreationAnalyticsHelper.trackSiteDesignSkipped() completion(nil) } @objc private func previewDeviceButtonTapped() { SiteCreationAnalyticsHelper.trackSiteDesignThumbnailModeButtonTapped(selectedPreviewDevice) let popoverContentController = PreviewDeviceSelectionViewController() popoverContentController.selectedOption = selectedPreviewDevice popoverContentController.onDeviceChange = { [weak self] device in guard let self = self else { return } SiteCreationAnalyticsHelper.trackSiteDesignPreviewModeChanged(device) self.selectedPreviewDevice = device } popoverContentController.modalPresentationStyle = .popover popoverContentController.popoverPresentationController?.delegate = self self.present(popoverContentController, animated: true, completion: nil) } override func primaryActionSelected(_ sender: Any) { guard let design = selectedDesign else { completion(nil) return } SiteCreationAnalyticsHelper.trackSiteDesignSelected(design) completion(design) } override func secondaryActionSelected(_ sender: Any) { guard let design = selectedDesign else { return } let previewVC = SiteDesignPreviewViewController(siteDesign: design, selectedPreviewDevice: selectedPreviewDevice, onDismissWithDeviceSelected: { [weak self] device in self?.selectedPreviewDevice = device }, completion: completion) let navController = GutenbergLightNavigationController(rootViewController: previewVC) navController.modalPresentationStyle = .pageSheet navigationController?.present(navController, animated: true) } private func handleError(_ error: Error) { SiteCreationAnalyticsHelper.trackError(error) let titleText = NSLocalizedString("Unable to load this content right now.", comment: "Informing the user that a network request failed becuase the device wasn't able to establish a network connection.") let subtitleText = NSLocalizedString("Check your network connection and try again.", comment: "Default subtitle for no-results when there is no connection.") displayNoResultsController(title: titleText, subtitle: subtitleText, resultsDelegate: self) } } // MARK: - NoResultsViewControllerDelegate extension SiteDesignContentCollectionViewController: NoResultsViewControllerDelegate { func actionButtonPressed() { fetchSiteDesigns() } } // MARK: UIPopoverPresentationDelegate extension SiteDesignContentCollectionViewController { func prepareForPopoverPresentation(_ popoverPresentationController: UIPopoverPresentationController) { guard popoverPresentationController.presentedViewController is PreviewDeviceSelectionViewController else { return } popoverPresentationController.permittedArrowDirections = .up popoverPresentationController.barButtonItem = previewDeviceButtonItem } func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // Reset our source rect and view for a transition to a new size guard let popoverPresentationController = presentedViewController?.presentationController as? UIPopoverPresentationController else { return } prepareForPopoverPresentation(popoverPresentationController) } }
gpl-2.0
27d6665d60b5fc9a4a89983d9f9d8be1
44.136364
210
0.712767
5.938206
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/Pods/Charts/Charts/Classes/Data/Implementations/Standard/BarChartDataSet.swift
6
5624
// // BarChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics public class BarChartDataSet: BarLineScatterCandleBubbleChartDataSet, IBarChartDataSet { private func initialize() { self.highlightColor = NSUIColor.blackColor() self.calcStackSize(yVals as! [BarChartDataEntry]) self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry]) } public required init() { super.init() initialize() } public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) initialize() } // MARK: - Data functions and accessors /// the maximum number of bars that are stacked upon each other, this value /// is calculated from the Entries that are added to the DataSet private var _stackSize = 1 /// the overall entry count, including counting each stack-value individually private var _entryCountStacks = 0 /// Calculates the total number of entries this DataSet represents, including /// stacks. All values belonging to a stack are calculated separately. private func calcEntryCountIncludingStacks(yVals: [BarChartDataEntry]!) { _entryCountStacks = 0 for i in 0 ..< yVals.count { let vals = yVals[i].values if (vals == nil) { _entryCountStacks += 1 } else { _entryCountStacks += vals!.count } } } /// calculates the maximum stacksize that occurs in the Entries array of this DataSet private func calcStackSize(yVals: [BarChartDataEntry]!) { for i in 0 ..< yVals.count { if let vals = yVals[i].values { if vals.count > _stackSize { _stackSize = vals.count } } } } public override func calcMinMax(start start : Int, end: Int) { let yValCount = _yVals.count if yValCount == 0 { return } var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } _lastStart = start _lastEnd = endValue _yMin = DBL_MAX _yMax = -DBL_MAX for i in start ... endValue { if let e = _yVals[i] as? BarChartDataEntry { if !e.value.isNaN { if e.values == nil { if e.value < _yMin { _yMin = e.value } if e.value > _yMax { _yMax = e.value } } else { if -e.negativeSum < _yMin { _yMin = -e.negativeSum } if e.positiveSum > _yMax { _yMax = e.positiveSum } } } } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } } /// - returns: the maximum number of bars that can be stacked upon another in this DataSet. public var stackSize: Int { return _stackSize } /// - returns: true if this DataSet is stacked (stacksize > 1) or not. public var isStacked: Bool { return _stackSize > 1 ? true : false } /// - returns: the overall entry count, including counting each stack-value individually public var entryCountStacks: Int { return _entryCountStacks } /// array of labels used to describe the different values of the stacked bars public var stackLabels: [String] = ["Stack"] // MARK: - Styling functions and accessors /// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width) public var barSpace: CGFloat = 0.15 /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value public var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) public var highlightAlpha = CGFloat(120.0 / 255.0) // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! BarChartDataSet copy._stackSize = _stackSize copy._entryCountStacks = _entryCountStacks copy.stackLabels = stackLabels copy.barSpace = barSpace copy.barShadowColor = barShadowColor copy.highlightAlpha = highlightAlpha return copy } }
apache-2.0
cdd570f8e8e2ff0946fa608c28dffca1
27.553299
148
0.511558
5.30566
false
false
false
false
hqy825334067/DouYuZB
DouYuZB/DouYuZB/Classes/Main/View/PageContentView.swift
1
5445
// // PageContentView.swift // DouYuZB // // Created by 20160713 on 2017/2/17. // Copyright © 2017年 胡清雨. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } private let ContentCellID = "ContentCellID" class PageContentView: UIView { //MARK:- 定义属性 fileprivate var childVcs : [UIViewController] fileprivate weak var parentViewController : UIViewController? fileprivate var startOffsetX : CGFloat = 0 weak var delegate : PageContentViewDelegate? //MARK:- 懒加载属性 fileprivate lazy var collectionView : UICollectionView = {[weak self] in //1.创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //2.创建UICollectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() //MARK:- 自定义构造函数 init(frame: CGRect, childVcs : [UIViewController], parentViewController : UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) //设置UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:- 设置UI界面 extension PageContentView { fileprivate func setupUI() { // 1.将所有的子控制器添加到父控制器中 for childVcs in childVcs { parentViewController?.addChildViewController(childVcs) } // 2.添加UICollectionView,用于在Cell中存放控制器的View addSubview(collectionView) collectionView.frame = bounds } } //MARK:- 遵守UICollectionViewDataSource extension PageContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //1.创建Cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) //2.给Cell设置内容 for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } //MARK:- 遵守UICollectionViewDelegate extension PageContentView : UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 1.定义获取需要的数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 左滑 // 1.计算progress progress = currentOffsetX.truncatingRemainder(dividingBy: scollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } // 4.如果完全划过去 if currentOffsetX - startOffsetX == scollViewW { progress = 1 targetIndex = sourceIndex } } else {// 右滑 // 1.计算progress progress = 1 - currentOffsetX.truncatingRemainder(dividingBy: scollViewW) // 2.计算targetIndex targetIndex = Int(currentOffsetX / scollViewW) // 3.计算sourceIndex sourceIndex = targetIndex + 1 if targetIndex <= childVcs.count { targetIndex = childVcs.count + 1 } } // 3.将progress/targetIndex/sourceIndex传递给titleView delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //MAKE:- 对外暴露的方法 extension PageContentView { func setCurrentIndex(currentIndex : Int) { let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
mit
128d80b2b3efec636196bf601330972c
29.588235
124
0.634615
5.882353
false
false
false
false
mxcl/swift-package-manager
Sources/SourceControl/GitRepository.swift
1
16821
/* This source file is part of the Swift.org open source project Copyright 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import Utility import func POSIX.getenv import enum POSIX.Error import class Foundation.ProcessInfo enum GitRepositoryProviderError: Swift.Error { case gitCloneFailure(url: String, path: AbsolutePath) } extension GitRepositoryProviderError: CustomStringConvertible { var description: String { switch self { case .gitCloneFailure(let url, let path): return "Failed to clone \(url) to \(path)" } } } /// A `git` repository provider. public class GitRepositoryProvider: RepositoryProvider { public init() { } public func fetch(repository: RepositorySpecifier, to path: AbsolutePath) throws { // Perform a bare clone. // // NOTE: We intentionally do not create a shallow clone here; the // expected cost of iterative updates on a full clone is less than on a // shallow clone. // FIXME: We need to define if this is only for the initial clone, or // also for the update, and if for the update then we need to handle it // here. // FIXME: Need to think about & handle submodules. precondition(!exists(path)) do { // FIXME: We need infrastructure in this subsystem for reporting // status information. let env = ProcessInfo.processInfo.environment try system( Git.tool, "clone", "--bare", repository.url, path.asString, environment: env, message: "Cloning \(repository.url)") } catch POSIX.Error.exitStatus { // Git 2.0 or higher is required if let majorVersion = Git.majorVersionNumber, majorVersion < 2 { throw Utility.Error.obsoleteGitVersion } else { throw GitRepositoryProviderError.gitCloneFailure(url: repository.url, path: path) } } } public func open(repository: RepositorySpecifier, at path: AbsolutePath) -> Repository { return GitRepository(path: path) } public func cloneCheckout( repository: RepositorySpecifier, at sourcePath: AbsolutePath, to destinationPath: AbsolutePath ) throws { // Clone using a shared object store with the canonical copy. // // We currently expect using shared storage here to be safe because we // only ever expect to attempt to use the working copy to materialize a // revision we selected in response to dependency resolution, and if we // re-resolve such that the objects in this repository changed, we would // only ever expect to get back a revision that remains present in the // object storage. // // NOTE: The above assumption may become violated once we have support // for editable packages, if we are also using this method to get that // copy. At that point we may need to expose control over this. // // FIXME: Need to think about & handle submodules. try Git.runCommandQuietly([ Git.tool, "clone", "--shared", sourcePath.asString, destinationPath.asString]) } public func openCheckout(at path: AbsolutePath) throws -> WorkingCheckout { return GitRepository(path: path) } } enum GitInterfaceError: Swift.Error { /// This indicates a problem communicating with the `git` tool. case malformedResponse(String) } /// A basic `git` repository. // // FIXME: Currently, this class is serving two goals, it is the Repository // interface used by `RepositoryProvider`, but is also a class which can be // instantiated directly against non-RepositoryProvider controlled // repositories. This may prove inconvenient if what is currently `Repository` // becomes inconvenient or incompatible with the ideal interface for this // class. It is possible we should rename `Repository` to something more // abstract, and change the provider to just return an adaptor around this // class. public class GitRepository: Repository, WorkingCheckout { /// A hash object. struct Hash: Equatable, Hashable { // FIXME: We should optimize this representation. let bytes: ByteString /// Create a hash from the given hexadecimal representation. /// /// - Returns; The hash, or nil if the identifier is invalid. init?(_ identifier: String) { self.init(asciiBytes: ByteString(encodingAsUTF8: identifier).contents) } /// Create a hash from the given ASCII bytes. /// /// - Returns; The hash, or nil if the identifier is invalid. init?<C: Collection>(asciiBytes bytes: C) where C.Iterator.Element == UInt8 { if bytes.count != 40 { return nil } for byte in bytes { switch byte { case UInt8(ascii: "0")...UInt8(ascii: "9"), UInt8(ascii: "a")...UInt8(ascii: "z"): continue default: return nil } } self.bytes = ByteString(bytes) } public var hashValue: Int { return bytes.hashValue } } /// A commit object. struct Commit: Equatable { /// The object hash. let hash: Hash /// The tree contained in the commit. let tree: Hash } /// A tree object. struct Tree { struct Entry { enum EntryType { case blob case executableBlob case symlink case tree init?(mode: Int) { // Although the mode is a full UNIX mode mask, there are // only a limited set of allowed values. switch mode { case 0o040000: self = .tree case 0o100644: self = .blob case 0o100755: self = .executableBlob case 0o120000: self = .symlink default: return nil } } } /// The hash of the object. let hash: Hash /// The type of object referenced. let type: EntryType /// The name of the object. let name: String } /// The object hash. let hash: Hash /// The list of contents. let contents: [Entry] } /// The path of the repository on disk. public let path: AbsolutePath public init(path: AbsolutePath) { self.path = path } // MARK: Repository Interface public var tags: [String] { return tagsCache.getValue(self) } private var tagsCache = LazyCache(getTags) private func getTags() -> [String] { // FIXME: Error handling. let tagList = try! Git.runPopen([Git.tool, "-C", path.asString, "tag", "-l"]) return tagList.characters.split(separator: "\n").map(String.init) } public func resolveRevision(tag: String) throws -> Revision { return try Revision(identifier: resolveHash(treeish: tag, type: "commit").bytes.asString!) } public func openFileView(revision: Revision) throws -> FileSystem { return try GitFileSystemView(repository: self, revision: revision) } // MARK: Working Checkout Interface public func getCurrentRevision() throws -> Revision { return Revision(identifier: try Git.runPopen([Git.tool, "-C", path.asString, "rev-parse", "--verify", "HEAD"]).chomp()) } public func checkout(tag: String) throws { // FIXME: Audit behavior with off-branch tags in remote repositories, we // may need to take a little more care here. try Git.runCommandQuietly([Git.tool, "-C", path.asString, "reset", "--hard", tag]) } public func checkout(revision: Revision) throws { // FIXME: Audit behavior with off-branch tags in remote repositories, we // may need to take a little more care here. try Git.runCommandQuietly([Git.tool, "-C", path.asString, "reset", "--hard", revision.identifier]) } // MARK: Git Operations /// Resolve a "treeish" to a concrete hash. /// /// Technically this method can accept much more than a "treeish", it maps /// to the syntax accepted by `git rev-parse`. func resolveHash(treeish: String, type: String? = nil) throws -> Hash { let specifier: String if let type = type { specifier = treeish + "^{\(type)}" } else { specifier = treeish } let response = try Git.runPopen([Git.tool, "-C", path.asString, "rev-parse", "--verify", specifier]).chomp() if let hash = Hash(response) { return hash } else { throw GitInterfaceError.malformedResponse("expected an object hash in \(response)") } } /// Read the commit referenced by `hash`. func read(commit hash: Hash) throws -> Commit { // Currently, we just load the tree, using the typed `rev-parse` syntax. let treeHash = try resolveHash(treeish: hash.bytes.asString!, type: "tree") return Commit(hash: hash, tree: treeHash) } /// Read a tree object. func read(tree hash: Hash) throws -> Tree { // Get the contents using `ls-tree`. let treeInfo = try Git.runPopen([Git.tool, "-C", path.asString, "ls-tree", hash.bytes.asString!]) var contents: [Tree.Entry] = [] for line in treeInfo.components(separatedBy: "\n") { // Ignore empty lines. if line == "" { continue } // Each line in the response should match: // // `mode type hash\tname` // // where `mode` is the 6-byte octal file mode, `type` is a 4-byte // type ("blob" or "tree"), `hash` is the hash, and the remainder of // the line is the file name. let bytes = ByteString(encodingAsUTF8: line) guard bytes.count > 6 + 1 + 4 + 1 + 40 + 1, bytes.contents[6] == UInt8(ascii: " "), bytes.contents[6 + 1 + 4] == UInt8(ascii: " "), bytes.contents[6 + 1 + 4 + 1 + 40] == UInt8(ascii: "\t") else { throw GitInterfaceError.malformedResponse("unexpected tree entry '\(line)' in '\(treeInfo)'") } // Compute the mode. let mode = bytes.contents[0..<6].reduce(0) { (acc: Int, char: UInt8) in (acc << 3) | (Int(char) - Int(UInt8(ascii: "0"))) } guard let type = Tree.Entry.EntryType(mode: mode), let hash = Hash(asciiBytes: bytes.contents[(6 + 1 + 4 + 1)..<(6 + 1 + 4 + 1 + 40)]), let name = ByteString(bytes.contents[(6 + 1 + 4 + 1 + 40 + 1)..<bytes.count]).asString else { throw GitInterfaceError.malformedResponse("unexpected tree entry '\(line)' in '\(treeInfo)'") } // FIXME: We do not handle de-quoting of names, currently. if name.hasPrefix("\"") { throw GitInterfaceError.malformedResponse("unexpected tree entry '\(line)' in '\(treeInfo)'") } contents.append(Tree.Entry(hash: hash, type: type, name: name)) } return Tree(hash: hash, contents: contents) } /// Read a blob object. func read(blob hash: Hash) throws -> ByteString { // Get the contents using `cat-file`. // // FIXME: We need to get the raw bytes back, not a String. let output = try Git.runPopen([Git.tool, "-C", path.asString, "cat-file", "-p", hash.bytes.asString!]) return ByteString(encodingAsUTF8: output) } } func ==(_ lhs: GitRepository.Commit, _ rhs: GitRepository.Commit) -> Bool { return lhs.hash == rhs.hash && lhs.tree == rhs.tree } func ==(_ lhs: GitRepository.Hash, _ rhs: GitRepository.Hash) -> Bool { return lhs.bytes == rhs.bytes } /// A `git` file system view. /// /// The current implementation is based on lazily caching data with no eviction /// policy, and is very unoptimized. private class GitFileSystemView: FileSystem { typealias Hash = GitRepository.Hash typealias Tree = GitRepository.Tree // MARK: Git Object Model // The map of loaded trees. var trees: [Hash: Tree] = [:] /// The underlying repository. let repository: GitRepository /// The revision this is a view on. let revision: Revision /// The root tree hash. let root: GitRepository.Hash init(repository: GitRepository, revision: Revision) throws { self.repository = repository self.revision = revision self.root = try repository.read(commit: Hash(revision.identifier)!).tree } // MARK: FileSystem Implementation private func getEntry(_ path: AbsolutePath) throws -> Tree.Entry? { // Walk the components resolving the tree (starting with a synthetic // root entry). var current: Tree.Entry = Tree.Entry(hash: root, type: .tree, name: "/") for component in path.components.dropFirst(1) { // Skip the root pseudo-component. if component == "/" { continue } // We have a component to resolve, so the current entry must be a tree. guard current.type == .tree else { throw FileSystemError.notDirectory } // Fetch the tree. let tree = try getTree(current.hash) // Search the tree for the component. // // FIXME: This needs to be optimized, somewhere. guard let index = tree.contents.index(where: { $0.name == component }) else { return nil } current = tree.contents[index] } return current } private func getTree(_ hash: Hash) throws -> Tree { // Check the cache. if let tree = trees[hash] { return tree } // Otherwise, load it. let tree = try repository.read(tree: hash) trees[hash] = tree return tree } func exists(_ path: AbsolutePath) -> Bool { do { return try getEntry(path) != nil } catch { return false } } func isFile(_ path: AbsolutePath) -> Bool { do { if let entry = try getEntry(path), entry.type != .tree { return true } return false } catch { return false } } func isDirectory(_ path: AbsolutePath) -> Bool { do { if let entry = try getEntry(path), entry.type == .tree { return true } return false } catch { return false } } func isSymlink(_ path: AbsolutePath) -> Bool { do { if let entry = try getEntry(path), entry.type == .symlink { return true } return false } catch { return false } } func getDirectoryContents(_ path: AbsolutePath) throws -> [String] { guard let entry = try getEntry(path) else { throw FileSystemError.noEntry } guard entry.type == .tree else { throw FileSystemError.notDirectory } return try getTree(entry.hash).contents.map{ $0.name } } func readFileContents(_ path: AbsolutePath) throws -> ByteString { guard let entry = try getEntry(path) else { throw FileSystemError.noEntry } guard entry.type != .tree else { throw FileSystemError.isDirectory } guard entry.type != .symlink else { fatalError("FIXME: not implemented") } return try repository.read(blob: entry.hash) } // MARK: Unsupported methods. func createDirectory(_ path: AbsolutePath) throws { throw FileSystemError.unsupported } func createDirectory(_ path: AbsolutePath, recursive: Bool) throws { throw FileSystemError.unsupported } func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws { throw FileSystemError.unsupported } }
apache-2.0
a3a17770d4e8dd278249a3afdf993b36
33.469262
127
0.576363
4.722347
false
false
false
false
ultimecia7/BestGameEver
Stick-Hero/LoginViewController.swift
1
3596
// // LoginViewController.swift // Stick-Hero // // Created by YIZHONGQI on 11/5/15. // Copyright © 2015 koofrank. All rights reserved. // import UIKit import SpriteKit import AVFoundation import SwiftHTTP import JSONJoy class LoginViewController: UIViewController { @IBOutlet weak var billboard: UILabel! @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! @IBAction func login(sender: AnyObject) { struct Response: JSONJoy { let status: String? let highscore: String? let speedhighscore: String? init(_ decoder: JSONDecoder) { status = decoder["status"].string highscore = decoder["highscore"].string speedhighscore = decoder["speedhighscore"].string } } let params = ["username":"\(username.text!)", "password":"\(password.text!)"] do { let opt = try HTTP.POST("http://192.168.1.107/login.php", parameters: params, requestSerializer: JSONParameterSerializer()) opt.start { response in print(response.description) if let error = response.error { self.billboard.text = "please check your network" print("got an error: \(error)") return } let resp = Response(JSONDecoder(response.data)) if (resp.status=="true") { let StoreScoreName = "com.stickHero.score" let StoreSpeedScoreName = "com.stickHero.speedscore" let StoreLoginUser = "com.stickHero.user" let hsVar1 : String = resp.highscore! let user_highscore:Int? = Int(hsVar1) NSUserDefaults.standardUserDefaults().setInteger(user_highscore!, forKey: StoreScoreName) NSUserDefaults.standardUserDefaults().synchronize() let hsVar2 : String = resp.speedhighscore! let user_speedhighscore:Int? = Int(hsVar2) NSUserDefaults.standardUserDefaults().setInteger(user_speedhighscore!, forKey: StoreSpeedScoreName) NSUserDefaults.standardUserDefaults().synchronize() let userVar : String = self.username.text! NSUserDefaults.standardUserDefaults().setValue(userVar, forKey: StoreLoginUser) NSUserDefaults.standardUserDefaults().synchronize() let userName = NSUserDefaults.standardUserDefaults().valueForKey(StoreLoginUser) print(userName!) print(userVar) print("status: \(resp.status!)") print("highscore: \(resp.highscore!)") dispatch_async(dispatch_get_main_queue()) { self.performSegueWithIdentifier("logintab", sender: self) } } else{ self.billboard.text = "invalid password or username" print("status: \(resp.status!)") print("wrong") } } } catch let error { self.billboard.text = "please try again." print("got an error creating the request: \(error)") } } }
mit
5e644d4535030b6891f7353abb5dccad
36.447917
135
0.523227
5.752
false
false
false
false
crazypoo/PTools
Pods/KakaJSON/Sources/KakaJSON/Extension/String+KJ.swift
1
2501
// // String+KJ.swift // KakaJSON // // Created by MJ Lee on 2019/8/5. // Copyright © 2019 MJ Lee. All rights reserved. // import Foundation extension String: KJCompatible {} extension NSString: KJCompatible {} public extension KJ where Base: ExpressibleByStringLiteral { /// from underline-cased to camel-cased /// /// e.g. from `my_test_name` to `myTestName` func camelCased() -> String { guard let str = base as? String else { return "" } var newStr = "" var upper = false for c in str { if c == "_" { upper = true continue } if upper, newStr.count > 0 { newStr += c.uppercased() } else { newStr.append(c) } upper = false } return newStr } /// from camel-cased to underline-cased /// /// e.g. from `myTestName` to `my_test_name` func underlineCased() -> String { guard let str = base as? String else { return "" } var newStr = "" for c in str { if c.isUppercase { newStr += "_" newStr += c.lowercased() } else { newStr.append(c) } } return newStr } /// JSONObject -> Model func model<M: Convertible>(_ type: M.Type) -> M? { return model(type: type) as? M } /// JSONObject -> Model func model(type: Convertible.Type) -> Convertible? { guard let string = base as? String else { return nil } return string.kj_fastModel(type) } /// JSONObjectArray -> ModelArray func modelArray<M: Convertible>(_ type: M.Type) -> [M] { return modelArray(type: type) as! [M] } /// JSONObjectArray -> ModelArray func modelArray(type: Convertible.Type) -> [Convertible] { guard let string = base as? String else { return [] } if let json = JSONSerialization.kj_JSON(string, [Any].self) { return json.kj.modelArray(type: type) } Logger.error("Failed to get JSON from JSONString.") return [] } } extension String { func kj_fastModel(_ type: Convertible.Type) -> Convertible? { if let json = JSONSerialization.kj_JSON(self, [String: Any].self) { return json.kj_fastModel(type) } Logger.error("Failed to get JSON from JSONString.") return nil } }
mit
ac25017aa0c84f1abf4060e1d9c8d6e5
26.777778
75
0.5292
4.266212
false
false
false
false
iOSDevLog/iOSDevLog
101. Psychologist/Psychologist/PsychologistViewController.swift
1
1289
// // ViewController.swift // Psychologist // // Created by jiaxianhua on 15/9/23. // Copyright © 2015年 com.jiaxh. All rights reserved. // import UIKit class PsychologistViewController : UIViewController { @IBAction func nothing(sender: UIButton) {performSegueWithIdentifier("nothing", sender: nil) } // prepare for segues // the only segue we currently have is to the HappinessViewController // to show the Psychologist's diagnosis override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var destination = segue.destinationViewController // this next if-statement makes sure the segue prepares properly even // if the MVC we're seguing to is wrapped in a UINavigationController if let navCon = destination as? UINavigationController { destination = navCon.visibleViewController! } if let hvc = destination as? HappinessViewController { if let identifier = segue.identifier { switch identifier { case "sad": hvc.happiness = 0 case "happy": hvc.happiness = 100 case "nothing": hvc.happiness = 25 default: hvc.happiness = 50 } } } } }
mit
a3faf83f044d2ee48ac81700feea57bd
31.974359
96
0.634526
5.185484
false
false
false
false
johnno1962d/swift
test/1_stdlib/CGGeometry.swift
3
7497
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import CoreGraphics func print_(_ r: CGPoint, _ prefix: String) { print("\(prefix) \(r.x) \(r.y)") } func print_(_ r: CGSize, _ prefix: String) { print("\(prefix) \(r.width) \(r.height)") } func print_(_ r: CGVector, _ prefix: String) { print("\(prefix) \(r.dx) \(r.dy)") } func print_(_ r: CGRect, _ prefix: String) { print("\(prefix) \(r.origin.x) \(r.origin.y) \(r.size.width) \(r.size.height)") } let int1: Int = 1 let int2: Int = 2 let int3: Int = 3 let int4: Int = 4 let cgfloat1: CGFloat = 1 let cgfloat2: CGFloat = 2 let cgfloat3: CGFloat = 3 let cgfloat4: CGFloat = 4 let double1: Double = 1 let double2: Double = 2 let double3: Double = 3 let double4: Double = 4 print("You may begin.") // CHECK: You may begin. var pt: CGPoint pt = CGPoint(x: 1.25, y: 2.25) print_(pt, "named float literals") pt = CGPoint(x: 1, y: 2) print_(pt, "named int literals") pt = CGPoint(x: cgfloat1, y: cgfloat2) print_(pt, "named cgfloats") pt = CGPoint(x: double1, y: double2) print_(pt, "named doubles") pt = CGPoint(x: int1, y: int2) print_(pt, "named ints") // CHECK-NEXT: named float literals 1.25 2.25 // CHECK-NEXT: named int literals 1.0 2.0 // CHECK-NEXT: named cgfloats 1.0 2.0 // CHECK-NEXT: named doubles 1.0 2.0 // CHECK-NEXT: named ints 1.0 2.0 assert(pt != CGPoint.zero) var size: CGSize size = CGSize(width:-1.25, height:-2.25) print_(size, "named float literals") size = CGSize(width:-1, height:-2) print_(size, "named int literals") size = CGSize(width:cgfloat1, height:cgfloat2) print_(size, "named cgfloats") size = CGSize(width:double1, height:double2) print_(size, "named doubles") size = CGSize(width: int1, height: int2) print_(size, "named ints") // CHECK-NEXT: named float literals -1.25 -2.25 // CHECK-NEXT: named int literals -1.0 -2.0 // CHECK-NEXT: named cgfloats 1.0 2.0 // CHECK-NEXT: named doubles 1.0 2.0 // CHECK-NEXT: named ints 1.0 2.0 assert(size != CGSize.zero) var vector: CGVector vector = CGVector(dx: -111.25, dy: -222.25) print_(vector, "named float literals") vector = CGVector(dx: -111, dy: -222) print_(vector, "named int literals") vector = CGVector(dx: cgfloat1, dy: cgfloat2) print_(vector, "named cgfloats") vector = CGVector(dx: double1, dy: double2) print_(vector, "named doubles") vector = CGVector(dx: int1, dy: int2) print_(vector, "named ints") // CHECK-NEXT: named float literals -111.25 -222.25 // CHECK-NEXT: named int literals -111.0 -222.0 // CHECK-NEXT: named cgfloats 1.0 2.0 // CHECK-NEXT: named doubles 1.0 2.0 // CHECK-NEXT: named ints 1.0 2.0 assert(vector != CGVector.zero) var rect: CGRect pt = CGPoint(x: 10.25, y: 20.25) size = CGSize(width: 30.25, height: 40.25) rect = CGRect(origin: pt, size: size) print_(rect, "point+size") rect = CGRect(origin:pt, size:size) print_(rect, "named point+size") // CHECK-NEXT: point+size 10.25 20.25 30.25 40.25 // CHECK-NEXT: named point+size 10.25 20.25 30.25 40.25 rect = CGRect(x:10.25, y:20.25, width:30.25, height:40.25) print_(rect, "named float literals") rect = CGRect(x:10, y:20, width:30, height:40) print_(rect, "named int literals") rect = CGRect(x:cgfloat1, y:cgfloat2, width:cgfloat3, height:cgfloat4) print_(rect, "named cgfloats") rect = CGRect(x:double1, y:double2, width:double3, height:double4) print_(rect, "named doubles") rect = CGRect(x:int1, y:int2, width:int3, height:int4) print_(rect, "named ints") // CHECK-NEXT: named float literals 10.25 20.25 30.25 40.25 // CHECK-NEXT: named int literals 10.0 20.0 30.0 40.0 // CHECK-NEXT: named cgfloats 1.0 2.0 3.0 4.0 // CHECK-NEXT: named doubles 1.0 2.0 3.0 4.0 // CHECK-NEXT: named ints 1.0 2.0 3.0 4.0 assert(rect == rect) assert(rect != CGRect.zero) assert(!rect.isNull) assert(!rect.isEmpty) assert(!rect.isInfinite) assert(CGRect.null.isNull) assert(CGRect.zero.isEmpty) assert(CGRect.infinite.isInfinite) var unstandard = CGRect(x: 10, y: 20, width: -30, height: -50) var standard = unstandard.standardized print_(unstandard, "unstandard") print_(standard, "standard") // CHECK-NEXT: unstandard 10.0 20.0 -30.0 -50.0 // CHECK-NEXT: standard -20.0 -30.0 30.0 50.0 assert(unstandard.width == 30) assert(unstandard.size.width == -30) assert(standard.width == 30) assert(standard.size.width == 30) assert(unstandard.height == 50) assert(unstandard.size.height == -50) assert(standard.height == 50) assert(standard.size.height == 50) assert(unstandard.minX == -20) assert(unstandard.midX == -5) assert(unstandard.maxX == 10) assert(unstandard.minY == -30) assert(unstandard.midY == -5) assert(unstandard.maxY == 20) assert(unstandard == standard) assert(unstandard.standardized == standard) unstandard.standardizeInPlace() print_(unstandard, "standardized unstandard") // CHECK-NEXT: standardized unstandard -20.0 -30.0 30.0 50.0 rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.insetBy(dx: 1, dy: -2), "insetBy") // CHECK-NEXT: insetBy 12.25 20.25 31.25 48.25 rect.insetInPlace(dx: 1, dy: -2) print_(rect, "insetInPlace") // CHECK-NEXT: insetInPlace 12.25 20.25 31.25 48.25 rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.offsetBy(dx: 3, dy: -4), "offsetBy") // CHECK-NEXT: offsetBy 14.25 18.25 33.25 44.25 rect.offsetInPlace(dx: 3, dy: -4) print_(rect, "offsetInPlace") // CHECK-NEXT: offsetInPlace 14.25 18.25 33.25 44.25 rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.integral, "integral") // CHECK-NEXT: integral 11.0 22.0 34.0 45.0 rect.makeIntegralInPlace() print_(rect, "makeIntegralInPlace") // CHECK-NEXT: makeIntegralInPlace 11.0 22.0 34.0 45.0 let smallRect = CGRect(x: 10, y: 25, width: 5, height: -5) let bigRect = CGRect(x: 1, y: 2, width: 101, height: 102) let distantRect = CGRect(x: 1000, y: 2000, width: 1, height: 1) rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.union(smallRect), "union small") print_(rect.union(bigRect), "union big") print_(rect.union(distantRect), "union distant") // CHECK-NEXT: union small 10.0 20.0 34.5 46.5 // CHECK-NEXT: union big 1.0 2.0 101.0 102.0 // CHECK-NEXT: union distant 11.25 22.25 989.75 1978.75 rect.unionInPlace(smallRect) rect.unionInPlace(bigRect) rect.unionInPlace(distantRect) print_(rect, "unionInPlace") // CHECK-NEXT: unionInPlace 1.0 2.0 1000.0 1999.0 rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.intersect(smallRect), "intersect small") print_(rect.intersect(bigRect), "intersect big") print_(rect.intersect(distantRect), "intersect distant") // CHECK-NEXT: intersect small 11.25 22.25 3.75 2.75 // CHECK-NEXT: intersect big 11.25 22.25 33.25 44.25 // CHECK-NEXT: intersect distant inf inf 0.0 0.0 assert(rect.intersects(smallRect)) rect.intersectInPlace(smallRect) assert(!rect.isEmpty) assert(rect.intersects(bigRect)) rect.intersectInPlace(bigRect) assert(!rect.isEmpty) assert(!rect.intersects(distantRect)) rect.intersectInPlace(distantRect) assert(rect.isEmpty) rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) assert(rect.contains(CGPoint(x: 15, y: 25))) assert(!rect.contains(CGPoint(x: -15, y: 25))) assert(bigRect.contains(rect)) assert(!rect.contains(bigRect)) rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) var (slice, remainder) = rect.divide(5, fromEdge:CGRectEdge.minXEdge) print_(slice, "slice") print_(remainder, "remainder") // CHECK-NEXT: slice 11.25 22.25 5.0 44.25 // CHECK-NEXT: remainder 16.25 22.25 28.25 44.25
apache-2.0
badb4ed70d9d204b378f573a9732f8af
29.979339
81
0.695612
2.826923
false
false
false
false
MaTriXy/androidtool-mac
AndroidTool/DeviceViewController.swift
1
24175
// // DeviceViewController.swift // AndroidTool // // Created by Morten Just Petersen on 4/22/15. // Copyright (c) 2015 Morten Just Petersen. All rights reserved. // import Cocoa import AVFoundation class DeviceViewController: NSViewController, NSPopoverDelegate, UserScriptDelegate, IOSRecorderDelegate, DropDelegate, ApkHandlerDelegate, ZipHandlerDelegate, ObbHandlerDelegate { var device : Device! @IBOutlet weak var deviceNameField: NSTextField! @IBOutlet var cameraButton: NSButton! @IBOutlet weak var deviceImage: NSImageView! @IBOutlet weak var progressBar: NSProgressIndicator! @IBOutlet weak var videoButton: MovableButton! @IBOutlet weak var moreButton: MovableButton! @IBOutlet weak var loaderButton: LoaderView! @IBOutlet weak var statusLabel: StatusTextField! var restingButton : NSImage! @IBOutlet var scriptsPopover: NSPopover! @IBOutlet var previewPopover: NSPopover! @IBOutlet var previewView: NSView! @IBOutlet weak var uninstallButton: MovableButton! // install invite @IBOutlet var installInviteView: NSView! @IBOutlet weak var inviteAppName: NSTextField! @IBOutlet weak var inviteVersions: NSTextField! @IBOutlet weak var invitePackageName: NSTextField! @IBOutlet weak var inviteIcon: NSImageView! var iosHelper : IOSDeviceHelper! var shellTasker : ShellTasker! var isRecording = false var moreOpen = false var moreShouldClose = false var uiTweaker : UITweaker! var dropView : DropReceiverView! var apkToUninstall : Apk! func shouldChangeStatusBar() -> Bool { if device.type == .Watch { return false } return NSUserDefaults.standardUserDefaults().boolForKey("changeAndroidStatusBar") } func setStatus(text:String, shouldFadeOut:Bool = true){ statusLabel.setText(text, shouldFadeOut: shouldFadeOut) } func maybeChangeStatusBar(should:Bool, completion:()->Void){ if should { setStatus("Changing status bar") uiTweaker.start({ () -> Void in completion() }) } else { completion() } } func maybeUseActivityFilename(should:Bool, completion:()->Void){ if should{ setStatus("Using activity as filename") device.getCurrentActivity({ (activityName) -> Void in completion() }) } else { completion() } } func takeScreenshot(){ setStatus("Taking screenshot...") self.startProgressIndication() if device.deviceOS == DeviceOS.Android { maybeChangeStatusBar(self.shouldChangeStatusBar(), completion: { () -> Void in self.maybeUseActivityFilename(self.shouldUseActivityInFilename(), completion: { () -> Void in self.takeAndroidScreenshot() }) }) } if device.deviceOS == DeviceOS.Ios { print("IOS screenshot") let args = [device.uuid!, getFolderForScreenshots()] ShellTasker(scriptFile: "takeScreenshotOfDeviceWithUUID").run(arguments: args, isUserScript: false, isIOS: true, complete: { (output) -> Void in self.setStatus("Screenshot ready") self.stopProgressIndication() Util().showNotification("Screenshot ready", moreInfo: "", sound: true) self.setStatus("Screenshot ready") }) } } func getFolderForScreenshots() -> String { return NSUserDefaults.standardUserDefaults().stringForKey(C.PREF_SCREENSHOTFOLDER)! } func getFolderForScreenRecordings() -> String { return NSUserDefaults.standardUserDefaults().stringForKey(C.PREF_SCREENRECORDINGSFOLDER)! } func cleanActivityName(a:String) -> String { // let trimmed = a.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).stringByTrimmingCharactersInSet(NSCharacterSet.URLPathAllowedCharacterSet()) var trimmed = a.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) trimmed = trimmed.stringByReplacingOccurrencesOfString("/", withString: "") let components = trimmed.componentsSeparatedByString(".") var cleanName="" if components.count > 1 { cleanName = "\(components[components.count-2])-\(components[components.count-1])" } return cleanName } func shouldUseActivityInFilename() -> Bool { let should = NSUserDefaults.standardUserDefaults().boolForKey(C.PREF_USEACTIVITYINFILENAME) if !should { device.currentActivity = "" } return should } func takeAndroidScreenshot(){ setStatus("Taking screenshot") let activity = self.cleanActivityName(device.currentActivity) let args = [self.device.adbIdentifier!, getFolderForScreenshots(), activity ] ShellTasker(scriptFile: "takeScreenshotOfDeviceWithSerial").run(arguments: args) { (output) -> Void in Util().showNotification("Screenshot ready", moreInfo: "", sound: true) self.exitDemoModeIfNeeded() self.stopProgressIndication() self.setStatus("Screenshot ready") } } func exitDemoModeIfNeeded(){ if self.shouldChangeStatusBar() { self.setStatus("Changing status bar back to normal") ShellTasker(scriptFile: "exitDemoMode").run(arguments: [self.device.adbIdentifier!], isUserScript: false, isIOS: false, complete: { (output) -> Void in // done, back to normal }) } } @IBAction func cameraClicked(sender: NSButton) { takeScreenshot() } func userScriptEnded() { setStatus("Script finished") stopProgressIndication() Util().restartRefreshingDeviceList() } func userScriptStarted() { setStatus("Script running") startProgressIndication() Util().stopRefreshingDeviceList() } func userScriptWantsSerial() -> String { return device.adbIdentifier! } func popoverDidClose(notification: NSNotification) { Util().restartRefreshingDeviceList() moreOpen = false } @IBAction func moreClicked(sender: NSButton) { Util().stopRefreshingDeviceList() if !moreOpen{ moreOpen = true scriptsPopover.showRelativeToRect(sender.bounds, ofView: sender, preferredEdge: NSRectEdge(rawValue: 2)!) } } func openPreviewPopover(){ // previewPopover.showRelativeToRect(videoButton.bounds, ofView: videoButton, preferredEdge: 2) } func closePreviewPopover(){ previewPopover.close() } func iosRecorderFailed(title: String, message: String?) { let alert = NSAlert() alert.messageText = title alert.runModal() cameraButton.enabled = true videoButton.enabled = true isRecording = false self.videoButton.image = NSImage(named: "recordButtonWhite") } func iosRecorderDidEndPreparing() { videoButton.alphaValue = 1 print("recorder did end preparing") self.videoButton.image = NSImage(named: "stopButton") self.videoButton.enabled = true } func iosRecorderDidStartPreparing(device: AVCaptureDevice) { print("recorder did start preparing") } func startRecording(){ setStatus("Starting screen recording") Util().stopRefreshingDeviceList() isRecording = true self.restingButton = self.videoButton.image // restingbutton is "recordButtonWhite" videoButton.image = NSImage(named: "stopButton") videoButton.enabled = false cameraButton.enabled = false moreButton.enabled = false switch device.deviceOS! { case .Android: if shouldChangeStatusBar() { setStatus("Changing status bar") uiTweaker.start({ () -> Void in self.videoButton.enabled = true self.startRecordingOnAndroidDevice(self.restingButton!) }) } else { self.videoButton.enabled = true startRecordingOnAndroidDevice(restingButton!) } case .Ios: // iOS starts recording 1 second delayed, so delaying the STOP button to signal this to the user videoButton.enabled = true openPreviewPopover() videoButton.alphaValue = 0.5 startRecordingOnIOSDevice() } } func startRecordingOnIOSDevice(){ iosHelper.toggleRecording(device.avDevice) } func startRecordingOnAndroidDevice(restingButton:NSImage){ shellTasker = ShellTasker(scriptFile: "startRecordingForSerial") let scalePref = NSUserDefaults.standardUserDefaults().doubleForKey("scalePref") let bitratePref = Int(NSUserDefaults.standardUserDefaults().doubleForKey("bitratePref")) // get phone's resolution, multiply with user preference for screencap size (either 1 or lower) var res = device.resolution! if device.type == DeviceType.Phone { res = (device.resolution!.width*scalePref, device.resolution!.height*scalePref) } let args:[String] = [device.adbIdentifier!, "\(Int(res.width))", "\(Int(res.height))", "\(bitratePref)", getFolderForScreenRecordings(), "\(NSUserDefaults.standardUserDefaults().boolForKey(C.PREF_GENERATEGIF))" ] setStatus("Recording screen") shellTasker.run(arguments: args) { (output) -> Void in self.setStatus("Fetching screen recording") print("-----") print(output) print("-----") self.startProgressIndication() self.cameraButton.enabled = true self.moreButton.enabled = true self.videoButton.image = restingButton let postProcessTask = ShellTasker(scriptFile: "postProcessMovieForSerial") postProcessTask.run(arguments: args, complete: { (output) -> Void in Util().showNotification("Your recording is ready", moreInfo: "", sound: true) self.exitDemoModeIfNeeded() self.setStatus("Recording finished") self.stopProgressIndication() }) } } func iosRecorderDidFinish(outputFileURL: NSURL!) { NSWorkspace.sharedWorkspace().openFile(outputFileURL.path!) self.videoButton.image = restingButton Util().showNotification("Your recording is ready", moreInfo: "", sound: true) cameraButton.enabled = true let movPath = outputFileURL.path! let gifUrl = outputFileURL.URLByDeletingPathExtension! let gifPath = "\(gifUrl.path!).gif" let ffmpegPath = NSBundle.mainBundle().pathForResource("ffmpeg", ofType: "")! let scalePref = NSUserDefaults.standardUserDefaults().doubleForKey("scalePref") let args = [ffmpegPath, movPath, gifPath, "\(scalePref)", getFolderForScreenRecordings()] ShellTasker(scriptFile: "convertMovieFiletoGif").run(arguments: args, isUserScript: false, isIOS: false) { (output) -> Void in print("done converting to gif") self.stopProgressIndication() } // convert to gif shell args // $ffmpeg = $1 // $inputFile = $2 // $outputFile = $3 } func stopRecording(){ Util().restartRefreshingDeviceList() isRecording = false videoButton.alphaValue = 1 switch device.deviceOS! { case .Android: shellTasker.stop() // terminates script and fires the closure in startRecordingForSerial case .Ios: iosHelper.toggleRecording(device.avDevice) // stops recording and fires delegate: } } @IBAction func videoClicked(sender: NSButton) { if isRecording { stopRecording() } else { startRecording() } } init?(device _device:Device){ device = _device super.init(nibName: "DeviceViewController", bundle: nil) setup() } override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup(){ if device.deviceOS == .Android { uiTweaker = UITweaker(adbIdentifier: device.adbIdentifier!) } dropView = self.view as! DropReceiverView dropView.delegate = self // let apk = Apk(rawAaptBadgingData: "hej") // showUninstallButton(apk) } func startProgressIndication(){ Util().stopRefreshingDeviceList() dispatch_after(1, dispatch_get_main_queue()) { () -> Void in self.loaderButton.startRotating() } } func stopProgressIndication(){ Util().restartRefreshingDeviceList() // progressBar.stopAnimation(nil) loaderButton.stopRotatingAndReset() } override func awakeFromNib() { if let model = device.model { deviceNameField.stringValue = model } let brandName = device.brand!.lowercaseString let imageName = "logo\(brandName)" print("imageName: \(imageName)") var image = NSImage(named: imageName) if image == nil { image = NSImage(named: "androidlogo") } deviceImage.image = image if device.isEmulator { // cameraButton.enabled = false videoButton.enabled = false deviceNameField.stringValue = "Emulator" } // only enable video recording if we have resolution, which is a bit slow because it comes from a big call videoButton.enabled = false enableVideoButtonWhenReady() if device.deviceOS == DeviceOS.Ios { iosHelper = IOSDeviceHelper(recorderDelegate: self, forDevice:device.avDevice) moreButton.hidden = true } } func startWaitingForAndroidVideoReady(){ if device.resolution != nil { print("resolution not nil") videoButton.enabled = true } else { print("resolution is nil") NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "enableVideoButtonWhenReady", userInfo: nil, repeats: false) } } func enableVideoButtonWhenReady(){ switch device.deviceOS! { case .Android: startWaitingForAndroidVideoReady() case .Ios: // videoButton.hidden = false print("showing video button for iOS") videoButton.enabled = true } } override func viewDidLoad() { if #available(OSX 10.10, *) { super.viewDidLoad() } else { // Fallback on earlier versions } setStatus("") } func hideButtons(){ Util().fadeViewsOutStaggered([moreButton, cameraButton, videoButton]) uninstallButton.alphaValue = 0 } func showButtons(){ Util().fadeViewsInStaggered([moreButton, cameraButton, videoButton]) uninstallButton.alphaValue = 1 } func transitionInstallInvite(moveIn:Bool=true, completion:()->Void){ let move = CABasicAnimation(keyPath: "position.y") move.duration = 0.3 if moveIn { move.toValue = 30 move.fromValue = 20 } else { move.toValue = 20 move.fromValue = 30 } move.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) installInviteView.wantsLayer = true let fade = CABasicAnimation(keyPath: "opacity") fade.duration = 0.3 if moveIn { fade.toValue = 1 fade.fromValue = 0 } else { fade.toValue = 0 fade.fromValue = 1 } fade.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) CATransaction.begin() CATransaction.setCompletionBlock { () -> Void in completion() } installInviteView.layer?.addAnimation(fade, forKey: "fader") installInviteView.layer?.addAnimation(move, forKey: "mover") CATransaction.commit() } func showInstallInvite(forApk apk:Apk){ installInviteView.frame.origin = NSMakePoint(120, 30) view.addSubview(installInviteView) transitionInstallInvite(true) { () -> Void in } inviteAppName.stringValue = apk.appName if let versionName = apk.versionName { inviteVersions.stringValue = versionName } if let versionCode = apk.versionCode { inviteVersions.stringValue = "\(inviteVersions.stringValue) (\(versionCode))" } if let packageName = apk.packageName { invitePackageName.stringValue = packageName } if let localIcon = apk.localIconPath { print("icon is: \(localIcon)") let i = NSImage(byReferencingFile: localIcon) inviteIcon.image = i } } func hideInstallInviteView(){ transitionInstallInvite(false) { () -> Void in self.installInviteView.removeFromSuperview() } } func dropDragEntered(filePath: String) { print("vc:dropDragEntered") if let fileExt = NSURL(fileURLWithPath: filePath).pathExtension { switch fileExt { case "apk": hideButtons() let a = ApkHandler(filepath: filePath, device: self.device) a.getInfoFromApk { (apk) -> Void in self.setStatus("Drop to install") self.showInstallInvite(forApk: apk) } case "zip": if NSUserDefaults.standardUserDefaults().boolForKey(C.PREF_FLASHIMAGESINZIPFILES){ setStatus("Drop to flash image with Fastboot") } else { setStatus("Enable flashing in Prefs first") } case "obb": setStatus("Drop to copy OBB") default: setStatus("Whaaaaat, what is this file?") } } } func dropDragExited() { print("vc:dropDragExited") stopProgressIndication() hideInstallInviteView() showButtons() setStatus(" ") } func dropDragPerformed(filePath: String) { if device.deviceOS != .Android {return} startProgressIndication() print("vc:dropDragPerformed") if let fileExt = NSURL(fileURLWithPath: filePath).pathExtension { switch fileExt { case "apk": installApk(filePath) hideInstallInviteView() showButtons() case "zip": if NSUserDefaults.standardUserDefaults().boolForKey(C.PREF_FLASHIMAGESINZIPFILES){ flashZip(filePath) } else { stopProgressIndication() self.setStatus("Enable flashing in Prefs") } case "obb": installObb(filePath) default: stopProgressIndication() setStatus("Wait, what?") } } } func dropUpdated(mouseAt: NSPoint) { // print("vc:dropUpdated") } func installObb(filePath:String){ print("installObb") startProgressIndication() let obbHandler = ObbHandler(filePath: filePath, device: self.device) obbHandler.delegate = self obbHandler.pushToDevice() } func obbHandlerDidFinish() { setStatus("Finished copying OBB file") stopProgressIndication() } func obbHandlerDidStart(bytes:String) { setStatus("Copying \(bytes) OBB file", shouldFadeOut: false) startProgressIndication() } func flashZip(filePath:String){ print("flashZip") startProgressIndication() let handler = ZipHandler(filepath: filePath, device: self.device) handler.delegate = self handler.flash() } func zipHandlerDidFinish() { setStatus("Finished flashing image") stopProgressIndication() } func zipHandlerDidStart() { setStatus("Flashing image") startProgressIndication() } func installApk(apkPath:String){ let apkHandler = ApkHandler(filepath: apkPath, device: self.device) apkHandler.delegate = self var apk:Apk! apkHandler.getInfoFromApk { (apkInfo) -> Void in apk = apkInfo } self.startProgressIndication() if NSUserDefaults.standardUserDefaults().boolForKey(C.PREF_LAUNCHINSTALLEDAPP) { apkHandler.installAndLaunch({ () -> Void in print("installed and launched") self.stopProgressIndication() self.showUninstallButton(apk) }) } else { apkHandler.install({ () -> Void in print("installed but not launched") self.stopProgressIndication() self.showUninstallButton(apk) }) } } func showUninstallButton(apk:Apk){ uninstallButton.title = "Uninstall \(apk.appName)" apkToUninstall = apk uninstallButton.hidden = false uninstallButton.fadeIn() uninstallButton.moveUpForUninstallButton(0.5) moreButton.moveUpForUninstallButton(0.6) videoButton.moveUpForUninstallButton(0.6) } func hideUninstallButton(){ uninstallButton.fadeOut({ () -> Void in }) uninstallButton.moveDownForUninstallButton(0.5) moreButton.moveDownForUninstallButton(0.6) videoButton.moveDownForUninstallButton(0.6) } @IBAction func uninstallPackageClicked(sender: AnyObject) { startProgressIndication() setStatus("Removing \(apkToUninstall.appName)...") let handler = ApkHandler(device: self.device) self.moreButton.moveDownForUninstallButton() self.videoButton.moveDownForUninstallButton() self.hideUninstallButton() if let packageName = apkToUninstall.packageName { handler.uninstallPackageWithName(packageName) { () -> Void in self.stopProgressIndication() self.setStatus("\(self.apkToUninstall.appName) removed") } } } func apkHandlerDidFinish() { print("apkHandlerDidFinish") } func apkHandlerDidGetInfo(apk: Apk) { print("apkHandlerDidGetInfo") } func apkHandlerDidStart() { print("apkHandlerDidStart") } func apkHandlerDidUpdate(update: String) { setStatus(update) print("apkHandlerDidUpdate: \(update)") } }
apache-2.0
d121e7102c8832e5f4dde4e79ab41d98
31.846467
185
0.58908
5.540912
false
false
false
false
Bijiabo/F-Client-iOS
F/Library/FStatus.swift
1
4970
// // FStatus.swift // F // // Created by huchunbo on 15/11/10. // Copyright © 2015年 TIDELAB. All rights reserved. // import Foundation class FStatus: NSObject { var observers: [String: [FStatusObserver]] = [String: [FStatusObserver]]() override init() { super.init() _addObservers() _setupLoginStatus() } deinit { _removeObservers() } // MARK: - add observers private func _addObservers () { NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("addObserver:"), name: FConstant.Notification.FStatus.addObserver, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("removeObserver:"), name: FConstant.Notification.FStatus.removeObserver, object: nil) } private func _removeObservers () { NSNotificationCenter.defaultCenter().removeObserver(self, name: FConstant.Notification.FStatus.addObserver, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: FConstant.Notification.FStatus.removeObserver, object: nil) } func addObserver (notification: NSNotification) { guard let object = _convertNotificationObject(notificationObject: notification.object) else {return} if let targetObserverGroup = observers[object.name]{ for (_,item) in targetObserverGroup.enumerate() { if item === object.observer {return} } observers[object.name]?.append(object.observer) } else { observers[object.name] = [object.observer] } _afterActionForAddObservers(object) } func removeObserver (notification: NSNotification) { guard let object = _convertNotificationObject(notificationObject: notification.object) else {return} guard let targetObserverGroup = observers[object.name] else {return} for (index,item) in targetObserverGroup.enumerate() { if item === object.observer { observers[object.name]?.removeAtIndex(index) return } } } private func _convertNotificationObject(notificationObject notificationObject: AnyObject?) -> (name: String, observer: FStatusObserver)? { guard let n_object = notificationObject else {return nil} guard let object = n_object as? [String: AnyObject] else {return nil} if let name = object["name"] as? String, let observer = object["observer"] as? FStatusObserver { return (name: name, observer: observer) } return nil } func runStatementForTargetObservers(observerGroupName observerGroupName: String, statement : (observer : FStatusObserver) -> Void ) { guard let targetObserverGroup = observers[observerGroupName] else {return} for (_,observer) in targetObserverGroup.enumerate() { statement(observer: observer) } } private func _afterActionForAddObservers (object: (name: String, observer: FStatusObserver)) { //do things after add observers each time } // MARK: - class functions class func addFStatusObserver(name name: String, observer: FStatusObserver) { NSNotificationCenter.defaultCenter().postNotificationName(FConstant.Notification.FStatus.addObserver, object: ["name": name, "observer": observer] as NSDictionary) } class func removeFStatusObserver(name name: String, observer: FStatusObserver) { NSNotificationCenter.defaultCenter().postNotificationName(FConstant.Notification.FStatus.removeObserver, object: ["name": name, "observer": observer] as NSDictionary) } // MARK: - login status private func _setupLoginStatus () { let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setBool(false, forKey: FConstant.UserDefaults.FStatus.logged_in) userDefaults.synchronize() _checkLoginStatus() } private func _checkLoginStatus () { //TODO: check logged in status var logged_in: Bool = false FAction.checkLogin { (success, description) -> Void in logged_in = success let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setBool(logged_in, forKey: FConstant.UserDefaults.FStatus.logged_in) userDefaults.synchronize() self.runStatementForTargetObservers(observerGroupName: FConstant.String.FStatus.loginStatus) { (observer) -> Void in if let observer = observer as? FStatus_LoginObserver { if logged_in { observer.FStatus_didLogIn?() } else { observer.FStatus_didLogOut?() } } } } } }
gpl-2.0
e596e6ea65e59bf903dc3b2532cd0e8f
36.923664
174
0.635394
5.250529
false
false
false
false
mperovic/my41
my41/Classes/CPU_Class0.swift
1
94285
// // CPU_Class0.swift // my41 // // Created by Miroslav Perovic on 12/20/14. // Copyright (c) 2014 iPera. All rights reserved. // import Foundation let opcodeDecrementPointer = 0x3d4 let opcodeIncrementPointer = 0x3dc let opcodePtEq13 = 0x2dc let oldOpcodePtEq13 = 0x2d4 // MARK: - Subclass 0 func op_NOP() -> Bit // NOP { /* NOP No Operation ========================================================================================= NOP operand: none Operation: None ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- NOP 0000_0000_00 1 ========================================================================================= */ return 0 } func op_WROM() -> Bit // WROM { /* WROM Write ROM ========================================================================================= WROM operand: none Operation: No operation ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- WROM 0001_0000_00 1 ========================================================================================= Note: This instruction is a NOP as far as the processor is concerned, but is used in legacy software to write to the program address space, similar to the WCMD Write to Logical Address. The contents of the C register are used as follows: digits 6-3 are the logical address and digits 2-0 are the data. The write is performed to the currently active bank in the logical address page. This is different from the WCMD case, where the bank must be explicitly specified. Only twelve bits of data are available to be written to the memory. The other four bits are always zero. This means that there is no way to control the Turbo mode tag bits in memory when using this write. ----------------------------------------------------------------------- nibble | 13 | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | ----------------------------------------------------------------------- ----------------------------------------------------------------------- write ROM | | logical address | data | ----------------------------------------------------------------------- */ let slot = cpu.reg.C[6] if let rom = bus.romChipInSlot(Bits4(slot)) { if rom.writable == false { return 0 } let addr = (cpu.reg.C[5] << 8) | (cpu.reg.C[4] << 4) | cpu.reg.C[3] let toSave = ((cpu.reg.C[2] & 0x03) << 8) | (cpu.reg.C[1] << 4) | cpu.reg.C[0] rom[Int(addr)] = UInt16(toSave) } return 0 } func op_ENROM() -> Bit // ENROMx { /* ENROMx Enable ROM bank x ========================================================================================= ENROMx operand: none Operation: No operation ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ENROM1 0100_0000_00 1 ENROM2 0110_0000_00 1 ENROM3 0101_0000_00 1 ENROM4 0111_0000_00 1 ========================================================================================= Note: This instruction is a NOP for the processor, but is interpreted by either the on-chip memory controller (if the current page is in system memory) or an external ROM module (if the current page is in an external ROM module). For the on-chip memory controller, the actual bank select changes at the end of the current machine cycle. This means that the instruction following the ENROMx and all subsequent instructions are fetched from the new bank. This operation in the original NUT is not specified, but the usual code to execute a bank change is duplicated in all of the banks that are physically present. This makes the operation independent of the actual timing. The HP documentation for the 12K ROM chip specifies that the bank changes at the end of the current machine cycle. */ if cpu.opcode.row == 0x4 { enableBank(1) } else if cpu.opcode.row == 0x6 { enableBank(2) } else if cpu.opcode.row == 0x5 { enableBank(3) } else if cpu.opcode.row == 0x7 { enableBank(4) } return 0 } func enableBank(_ bankSet: Bits4) { if cpu.currentRomChip == nil || cpu.currentRomChip?.actualBankGroup == 0 { return } // search for banks that match ActualBankGroup for slot in 0...0xf { for bank in 1...4 { if let rom1 = bus.romChips[slot][bank - 1], let _ = bus.romChips[slot][Int(bankSet) - 1] { if let currentROM = cpu.currentRomChip { if currentROM.actualBankGroup == rom1.actualBankGroup { bus.activeBank[slot] = Int(bankSet) } } } } } } // MARK: - Subclass 1 func op_SDeq0(_ param: Int) -> Bit // SD=0 { /* ST=0 Clear Status bit ========================================================================================= ST=0 operand: none Operation: ST[7:0] <= 0 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ST=0 d dddd_0001_00 1 ========================================================================================= Note: In the original NUT implementation this instruction cannot immediately follow an arithmetic (type 10) instruction. This restriction is not present in the NEWT implementation. */ if param <= 7 { cpu.reg.ST &= ~Bits8(1 << param) } else { cpu.reg.XST &= ~Bits8(1 << (param - 8)) } return 0 } func op_CLRST() -> Bit // CLRST { /* CLRST Clear ST ========================================================================================= CLRST operand: none Operation: ST[7:0] <= 0 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CLRST 1111_0001_00 1 ========================================================================================= */ cpu.reg.ST = 0 return 0 } // MARK: - Subclass 2 func op_STeq1(_ param: Int) -> Bit // SD=1 { /* ST=1 Set Status bit ========================================================================================= ST=1 operand: Digit Number Operation: ST[digit] <= 1 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ST=1 d dddd_0010_00 1 ========================================================================================= Note: In the original NUT implementation this instruction cannot immediately follow an arithmetic (type 10) instruction. */ if param <= 7 { cpu.reg.ST |= Bits8(1 << param) } else { cpu.reg.XST |= Bits8(1 << (param - 8)) } return 0 } func op_RSTKB() -> Bit // RSTKB { /* RST KB Reset Keyboard ========================================================================================= RST KB operand: none Operation: KYF <= 0 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- RSTKB 1111_0010_00 1 ========================================================================================= Note: The keyboard flag is only cleared if the key has been released before this instruction is executed. If the key is still down while this instruction is executed the flag will remain set. */ if cpu.reg.keyDown == 0 { if cpu.keyReleaseDelay != 0 { // See comment in reset: cpu.keyReleaseDelay -= 1 } else { cpu.reg.KY = 0 cpu.reg.keyDown = 0 } } return 0 } // MARK: - Subclass 3 func op_ifSTeq1(_ param: Int) -> Bit // ?SD=1 { /* ST=1? Test Status Equal To One ========================================================================================= ST=1? operand: Digit Number Operation: CY <= Status<digit> ========================================================================================= Flag: Set/Cleared as a the result of the test ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ST=1? d dddd_0011_00 1 ========================================================================================= Note: In the original NUT implementation this instruction cannot immediately follow an arithmetic (type 10) instruction. */ if param <= 7 { return (cpu.reg.ST & Bits8(1 << param)) != 0 ? 1 : 0 } else { return (cpu.reg.XST & Bits6(1 << (param - 8))) != 0 ? 1 : 0 } } func op_CHKBK() -> Bit // CHKKB { /* CHKKB Check Keyboard ========================================================================================= CHKKB operand: none Operation: CY <= KYF ========================================================================================= Flag: Set/Cleared according to the state of the keyboard flag ========================================================================================= Dec/Hex: Independent Turbo: Automatically executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CHKKB 1111_0011_00 1 ========================================================================================= */ return cpu.reg.KY != Bits8(0) ? 1 : 0 } // MARK: - Subclass 4 func op_LC(_ param: Int) -> Bit // LC { /* LC Load Constant ========================================================================================= LC operand: immediate nibble Operation: C<ptr> <= nnnn ptr <= ptr- ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- LC n nnnn_0100_00 1 ========================================================================================= Note: The pointer decrements to the next lower digit position. =========================================================== | current ptr | next ptr | current digit -> next digit | =========================================================== | 0000 | 1000 | 3 (Mantissa digit 0) -> 2 | | 0001 | 0000 | 4 (Mantissa digit 1) -> 3 | | 0010 | 0001 | 5 (Mantissa digit 2) -> 4 | | 0011 | 1001 | 10 (Mantissa digit 7) -> 9 | | 0100 | 1010 | 8 (mantissa digit 5) -> 7 | | 0101 | 0010 | 6 (Mantissa digit 3) -> 5 | | 0110 | 0011 | 11 (Mantissa digit 8) -> 10 | | 1000 | 1100 | 2 (Exponent Sign digit) -> 1 | | 1001 | 0100 | 9 (Mantissa digit 6) -> 8 | | 1010 | 0101 | 7 (Mantissa digit 4) -> 6 | | 1011 | 1101 | 13 (Mantissa sign digit) -> 12 | | 1100 | 1110 | 1 (Exponent digit 1) -> 0 | | 1101 | 0110 | 12 (Mantissa digit 9) -> 11 | | 1110 | 1011 | 0 (Exponent digit 0) -> 13 | =========================================================== */ cpu.reg.C[Int(cpu.regR())] = Digit(param) cpu.decrementPointer() return 0 } // MARK: - Subclass 5 func op_ifPTeqD(_ param: Int) -> Bit // ?PT=D { /* ?PT= Test Pointer Equal To ========================================================================================= ?PT= operand: Digit Number Operation: CY <= (PT == digit) ========================================================================================= Flag: Set if the pointer is equal to the dddd field in the instruction; cleared otherwise ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ?PT= d dddd_0101_00 1 ========================================================================================= Note: In the original NUT implementation this instruction cannot immediately follow an arithmetic (type 10) instruction. */ return cpu.regR() == Digit(param) ? 1 : 0 } func op_DECPT() -> Bit // DECPT { /* DECPT Decrement Pointer ========================================================================================= DECPT operand: none Operation: ptr <= ptr- ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- DECPT 1111_0101_00 1 ========================================================================================= Note: This is not a binary or decimal decrement. The pointer decrements to the next lower digit position. =========================================================== | current ptr | next ptr | current digit -> next digit | =========================================================== | 0000 | 1000 | 3 (Mantissa digit 0) -> 2 | | 0001 | 0000 | 4 (Mantissa digit 1) -> 3 | | 0010 | 0001 | 5 (Mantissa digit 2) -> 4 | | 0011 | 1001 | 10 (Mantissa digit 7) -> 9 | | 0100 | 1010 | 8 (Mantissa digit 5) -> 7 | | 0101 | 0010 | 6 (Mantissa digit 3) -> 5 | | 0110 | 0011 | 11 (Mantissa digit 8) -> 10 | | 1000 | 1100 | 2 (Exponent Sign digit) -> 1 | | 1001 | 0100 | 9 (Mantissa digit 6) -> 8 | | 1010 | 0101 | 7 (Mantissa digit 4) -> 6 | | 1011 | 1101 | 13 (Mantissa sign digit) -> 12 | | 1100 | 1110 | 1 (Exponent digit 1) -> 0 | | 1101 | 0110 | 12 (Mantissa digit 9) -> 11 | | 1110 | 1011 | 0 (Exponent digit 0) -> 13 | =========================================================== */ cpu.decrementPointer() return 0 } // MARK: - Subclass 6 func swapRegisterG() { let temp = cpu.reg.G[1] cpu.reg.G[1] = cpu.reg.G[0] cpu.reg.G[0] = temp } func op_GeqC() -> Bit // G=C { /* G=C Load G From C ========================================================================================= G=C operand: none Operation: G <= C<ptr+:ptr> ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- G=C 0001_0110_00 1 ========================================================================================= Note: There are several boundary conditions that can occur when the pointer is pointing at the most significant nibble. These are detailed below: 1. If the active pointer was not changed to point at the most significant nibble immediately prior to this instruction, then: G <= {C<13>, C<0>} 2. If the active pointer was changed to point at the most significant nibble (using PT=13, INC PT or DEC PT) immediately prior to this instruction, then: G <= {C<13>, G<1>} 3. If the active pointer was changed from pointing at the most significant nibble (using DEC PT only) immediately prior to this instruction, then: G <= C<13:12> which is normal operation */ if (cpu.regR() == 13) { // PT == 13 if cpu.prevPT == 13 { /* 1. active pointer wan not changed to point at the most significant nible immediately prior to this instruction */ cpu.reg.G[1] = cpu.reg.C[13] cpu.reg.G[0] = cpu.reg.C[0] } else { /* 3. If the active pointer was changed to point at the most significant nibble (using PT=13, INC PT or DEC PT) immediately prior to this instruction */ cpu.reg.G[0] = cpu.reg.G[1] cpu.reg.G[1] = cpu.reg.C[13] } } else if cpu.prevPT == 13 && (cpu.lastOpCode.opcode == opcodeDecrementPointer) { /* 3. If the active pointer was changed from pointing at the most significant nibble (using DEC PT only) immediately prior to this instruction */ cpu.reg.G[1] = cpu.reg.C[13] cpu.reg.G[0] = cpu.reg.C[12] } else { // normal case cpu.reg.G[1] = cpu.reg.C[Int(cpu.regR()) + 1] cpu.reg.G[0] = cpu.reg.C[Int(cpu.regR())] } return 0 } func op_CeqG() -> Bit // C=G { /* C=G Load C From G ========================================================================================= C=G operand: none Operation: C<ptr+:ptr> <= G ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=G 0010_0110_00 1 ========================================================================================= Note: There are several boundary conditions that can occur when the pointer is pointing at the most significant nibble. These are detailed below: 1. If the active pointer was not changed to point at the most significant nibble immediately prior to this instruction, then: C<13> <= G<1> C<0> <= G<0> 2. If the active pointer was changed to point at the most significant nibble (using PT=13, INC PT or DEC PT) immediately prior to this instruction, then: fork C<13> <= G<0> G <= {G<0>, G<1>} join 3. If the active pointer was changed from pointing at the most significant nibble (using DEC PT only) immediately prior to this instruction, then: fork C<13:12> <= {G<0>, G<1>} C<0> <= G<0> G <= {G<0>, G<1>} join 4. If the active pointer was changed from pointing at the most significant nibble (using PT=d only) immediately prior to this instruction, then: fork C<ptr+:ptr> <= {G<0>, G<1>} C<0> <= G<0> G <= {G<0>, G<1>} join */ let opcode01c = cpu.lastOpCode.opcode & 0x01c != 0 let opcode05c = cpu.lastOpCode.opcode & 0x05c != 0 let opcode09c = cpu.lastOpCode.opcode & 0x09c != 0 let opcode0dc = cpu.lastOpCode.opcode & 0x0dc != 0 let opcode11c = cpu.lastOpCode.opcode & 0x11c != 0 let opcode15c = cpu.lastOpCode.opcode & 0x15c != 0 let opcode19c = cpu.lastOpCode.opcode & 0x19c != 0 let opcode21c = cpu.lastOpCode.opcode & 0x21c != 0 let opcode25c = cpu.lastOpCode.opcode & 0x25c != 0 let opcode29c = cpu.lastOpCode.opcode & 0x29c != 0 let opcode31c = cpu.lastOpCode.opcode & 0x31c != 0 let opcode35c = cpu.lastOpCode.opcode & 0x35c != 0 let opcode39c = cpu.lastOpCode.opcode & 0x39c != 0 let additionalPTAsignments = opcode01c || opcode05c || opcode09c || opcode0dc || opcode11c || opcode15c || opcode19c || opcode21c || opcode25c || opcode29c || opcode31c || opcode35c || opcode39c if cpu.regR() == 13 { if cpu.prevPT == 13 { /* 1. If the active pointer was not changed to point at the most significant nibble immediately prior to this instruction */ cpu.reg.C[13] = cpu.reg.G[1] cpu.reg.C[0] = cpu.reg.G[0] } else { /* 2. If the active pointer was changed to point at the most significant nibble (using PT=13, INC PT or DEC PT) immediately prior to this instruction */ cpu.reg.C[13] = cpu.reg.G[0] swapRegisterG() } } else if cpu.prevPT == 13 && (cpu.lastOpCode.opcode == opcodeDecrementPointer) { /* 3. If the active pointer was changed from pointing at the most significant nibble (using DEC PT only) immediately prior to this instruction */ cpu.reg.C[13] = cpu.reg.G[0] cpu.reg.C[12] = cpu.reg.G[1] cpu.reg.C[0] = cpu.reg.G[0] swapRegisterG() } else if cpu.prevPT == 13 && (cpu.lastOpCode.opcode == opcodePtEq13 || additionalPTAsignments) { /* 4. If the active pointer was changed from pointing at the most significant nibble (using PT=d only) immediately prior to this instruction */ cpu.reg.C[Int(cpu.regR()) + 1] = cpu.reg.G[0] cpu.reg.C[Int(cpu.regR())] = cpu.reg.G[1] cpu.reg.C[0] = cpu.reg.G[0] swapRegisterG() } else { // normal case cpu.reg.C[Int(cpu.regR()) + 1] = cpu.reg.G[1] cpu.reg.C[Int(cpu.regR())] = cpu.reg.G[0] } return 0 } func op_CGEX() -> Bit // CGEX { /* CGEX Exchange C and G ========================================================================================= CGEX operand: none Operation: fork C<ptr+:ptr> <= G G <= C<ptr+,ptr> join ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CGEX 0011_0110_00 1 ========================================================================================= Note: There are several boundary conditions that can occur when the pointer is pointing at the most significant nibble. These are detailed below: 1. If the active pointer was not changed to point at the most significant nibble immediately prior to this instruction, then: fork C<13> <= G<1> C<0> <= G<0> G <= {C<13>, C<0>} join 2. If the active pointer was changed to point at the most significant nibble (using PT=13, INC PT or DEC PT) immediately prior to this instruction, then: fork C<13> <= G<0> G <= {C<13>, G<1>} join 3. If the active pointer was changed from pointing at the most significant nibble (using DEC PT only) immediately prior to this instruction, then: fork C<13:12> <= {C<0>, G<1>} C<0> <= G<0> G <= C<13:12> join 4. If the active pointer was changed from pointing at the most significant nibble (using PT=d only) immediately prior to this instruction, then: fork C<ptr+:ptr> <= {C<0>, G<1>} C<0> <= G<0> G <= C<ptr+:ptr> join */ let tempG = cpu.reg.G let opcode01c = cpu.lastOpCode.opcode & 0x01c != 0 let opcode05c = cpu.lastOpCode.opcode & 0x05c != 0 let opcode09c = cpu.lastOpCode.opcode & 0x09c != 0 let opcode0dc = cpu.lastOpCode.opcode & 0x0dc != 0 let opcode11c = cpu.lastOpCode.opcode & 0x11c != 0 let opcode15c = cpu.lastOpCode.opcode & 0x15c != 0 let opcode19c = cpu.lastOpCode.opcode & 0x19c != 0 let opcode21c = cpu.lastOpCode.opcode & 0x21c != 0 let opcode25c = cpu.lastOpCode.opcode & 0x25c != 0 let opcode29c = cpu.lastOpCode.opcode & 0x29c != 0 let opcode31c = cpu.lastOpCode.opcode & 0x31c != 0 let opcode35c = cpu.lastOpCode.opcode & 0x35c != 0 let opcode39c = cpu.lastOpCode.opcode & 0x39c != 0 let additionalPTAsignments = opcode01c || opcode05c || opcode09c || opcode0dc || opcode11c || opcode15c || opcode19c || opcode21c || opcode25c || opcode29c || opcode31c || opcode35c || opcode39c if cpu.regR() == 13 { if cpu.prevPT == 13 { /* 1. If the active pointer was not changed to point at the most significant nibble immediately prior to this instruction */ cpu.reg.G[1] = cpu.reg.C[13] cpu.reg.G[0] = cpu.reg.G[0] cpu.reg.C[13] = tempG[1] cpu.reg.C[0] = tempG[0] } else { /* 2. If the active pointer was changed to point at the most significant nibble (using PT=13, INC PT or DEC PT) immediately prior to this instruction */ cpu.reg.G[1] = cpu.reg.C[13] cpu.reg.G[0] = tempG[1] cpu.reg.C[13] = tempG[0] } } else if cpu.prevPT == 13 && (cpu.lastOpCode.opcode == opcodeDecrementPointer) { /* 3. If the active pointer was changed from pointing at the most significant nibble (using DEC PT only) immediately prior to this instruction */ cpu.reg.G[1] = cpu.reg.C[13] cpu.reg.G[0] = cpu.reg.C[12] cpu.reg.C[13] = cpu.reg.C[0] cpu.reg.C[12] = tempG[1] cpu.reg.C[0] = tempG[0] } else if cpu.prevPT == 13 && (cpu.lastOpCode.opcode == opcodePtEq13 || additionalPTAsignments) { /* 4. If the active pointer was changed from pointing at the most significant nibble (using PT=d only) immediately prior to this instruction */ cpu.reg.G[1] = cpu.reg.C[Int(cpu.regR()) + 1] cpu.reg.G[0] = cpu.reg.C[Int(cpu.regR())] cpu.reg.C[Int(cpu.regR()) + 1] = cpu.reg.C[0] cpu.reg.C[Int(cpu.regR())] = tempG[1] cpu.reg.C[0] = tempG[0] } else { // normal case cpu.reg.G[1] = cpu.reg.C[Int(cpu.regR()) + 1] cpu.reg.G[0] = cpu.reg.C[Int(cpu.regR())] cpu.reg.C[Int(cpu.regR()) + 1] = tempG[1] cpu.reg.C[Int(cpu.regR())] = tempG[0] } return 0 } func op_MeqC() -> Bit // M=C { /* M=C Load M from C ========================================================================================= M=C operand: none Operation: M <= C ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- M=C 0101_0110_00 1 ========================================================================================= */ cpu.reg.M = cpu.reg.C return 0 } func op_CeqM() -> Bit // C=M { /* C=M Load C From M ========================================================================================= C=M operand: none Operation: C <= M ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=M 0110_0110_00 1 ========================================================================================= */ cpu.reg.C = cpu.reg.M return 0 } func op_CMEX() -> Bit // CMEX { /* CMEX Exchange C and M ========================================================================================= CMEX operand: none Operation: fork C <= M M <= C join ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CMEX 0111_0110_00 1 ========================================================================================= */ // let temp = cpu.reg.M // cpu.reg.M = cpu.reg.C // cpu.reg.C = temp var x = cpu.reg.C var y = cpu.reg.M exchangeDigits( X: &x, Y: &y, startPos: 0, count: 14 ) cpu.reg.C = x cpu.reg.M = y return 0 } func op_FeqSB() -> Bit // F=SB { /* F=SB Load Flag Out from Status Byte ========================================================================================= F=SB operand: none Operation: FO<7:0> <= ST[7:0] ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically executed a bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- F=SB 1001_0110_00 1 ========================================================================================= Note: The fo_bus output timing is not independent of the Turbo mode, so the timing is identical to normal operation only during the execution of this instruction. Thus a timing loop that times the duration of the fo_bus output should be tagged to execute at normal bus speed. */ cpu.reg.T = cpu.reg.ST return 0 } func op_SBeqF() -> Bit // SB=F { /* SB=F Load Status Byte from Flag Out ========================================================================================= SB=F operand: none Operation: ST[7:0] <= FO[7:0] ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically executed a bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- SB=F 1010_0110_00 1 ========================================================================================= */ cpu.reg.ST = cpu.reg.T return 0 } func op_FEXSB() -> Bit // FEXSB { /* FEXSB Load Status Byte from Flag Out ========================================================================================= FEXSB operand: none Operation: fork FO<7:0> <= ST[7:0] ST[7:0] <= FO<7:0> join ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- FEXSB 1011_0110_00 1 ========================================================================================= Note: The fo_bus output timing is not independent of the Turbo mode, so the timing is identical to normal operation only during the execution of this instruction. Thus a timing loop that times the duration of the fo_bus output should be tagged to execute at normal bus speed */ // this is used to create tones. Normally FF and 00 are switched back and forth. // one machine cycle is about 158 microseconds. // frequency = 1/((number of FFh cycles + number of 00h cycles)x 158 10E-6 // Hepax Vol II pg 111,131, Zenrom Manual pg. 81, HP41 Schematic swap(&cpu.reg.ST, &cpu.reg.T) // let temp = cpu.reg.ST // cpu.reg.ST = cpu.reg.T // cpu.reg.T = temp if cpu.soundOutput.soundMode == .speaker { // Speaker(F_REG, 1) } return 0 } func op_STeqC() -> Bit // ST=C { /* ST=C Load Status from C ========================================================================================= ST=C operand: none Operation: ST[7:0] <= C<1:0> ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ST=C 1101_0110_00 1 ========================================================================================= */ cpu.reg.ST = cpu.reg.C[1] << 4 | cpu.reg.C[0] return 0 } func op_CeqST() -> Bit // C=ST { /* C=ST Load C From ST ========================================================================================= C=ST operand: none Operation: C<1:0> <= ST[7:0] ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=ST 1110_0110_00 1 ========================================================================================= */ cpu.reg.C[1] = (cpu.reg.ST & 0xf0) >> 4 cpu.reg.C[0] = cpu.reg.ST & 0xf return 0 } func op_CSTEX() -> Bit // CSTEX { /* CSTEX Exchange C and M ========================================================================================= CSTEX operand: none Operation: fork C<1:0> <= ST[7:0] ST[7:0] <= C<1:0> join ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CSTEX 1111_0110_00 1 ========================================================================================= Note: In the original NUT implementation this instruction cannot immediately follow an arithmetic (type 10) instruction. */ let temp1 = cpu.reg.C[1] let temp0 = cpu.reg.C[0] cpu.reg.C[1] = (cpu.reg.ST & 0xf0) >> 4 cpu.reg.C[0] = cpu.reg.ST & 0xf cpu.reg.ST = (temp1 << 4) | temp0 return 0 } // MARK: - Subclass 7 func op_INCPT() -> Bit // INCPT { /* INCPT Increment Pointer ========================================================================================= INCPT operand: none Operation: ptr <= ptr+ ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- INCPT 1111_0111_00 1 ========================================================================================= Note: This is not a binary or decimal increment. The pointer increments to the next higher digit position. =========================================================== | current ptr | next ptr | current digit -> next digit | =========================================================== | 0000 | 0001 | 3 (Mantissa digit 0) -> 4 | | 0001 | 0010 | 4 (Mantissa digit 1) -> 5 | | 0010 | 0101 | 5 (Mantissa digit 2) -> 6 | | 0011 | 0110 | 10 (Mantissa digit 7) -> 11 | | 0100 | 1001 | 8 (Mantissa digit 5) -> 9 | | 0101 | 1010 | 6 (Mantissa digit 3) -> 7 | | 0110 | 1101 | 11 (Mantissa digit 8) -> 12 | | 1000 | 0000 | 2 (Exponent Sign digit) -> 3 | | 1001 | 0011 | 9 (Mantissa digit 6) -> 10 | | 1010 | 0100 | 7 (Mantissa digit 4) -> 8 | | 1011 | 1110 | 13 (Mantissa sign digit) -> 0 | | 1100 | 1000 | 1 (Exponent digit 1) -> 2 | | 1101 | 1011 | 12 (Mantissa digit 9) -> 13 | | 1110 | 1100 | 0 (Exponent digit 0) -> 1 | =========================================================== */ cpu.incrementPointer() return 0 } func op_PTeqD(_ param: Int) -> Bit // PT=D { /* PT= Load Pointer immediate ========================================================================================= PT= operand: digit Operation: ptr <= digit ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- PT=D dddd_0111_00 1 ========================================================================================= */ cpu.setR(Digit(param)) return 0 } // MARK: - Subclass 8 func op_SPOPND() -> Bit // SPOPND { /* SPOPND Pop Stack ========================================================================================= SPOPND operand: none Operation: STK0 <= STK1 STK1 <= STK2 STK2 <= STK3 STK3 <= 0000 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- SPOPND 0000_1000_00 1 ========================================================================================= */ cpu.popReturnStack() return 0 } func op_POWOFF() -> Bit // POWOFF { /* POWOFF Power Down ========================================================================================= POWOFF operand: none Operation: Power Down ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- POWOFF 0001_1000_00 2 0000_0000_00 ========================================================================================= */ for page in 0...0xf { bus.activeBank[page] = 1 } cpu.reg.PC = 0 enableBank(1) let regN = cpu.reg.N if regN[11] == 11 && regN[12] == 0 && regN[13] == 3 { // Check if exiting ED mode cpu.powerOffFlag = false cpu.setPowerMode(.lightSleep) return 0 } else { if cpu.powerOffFlag { cpu.setPowerMode(.deepSleep) cpu.powerOffFlag = false return 1 } else { cpu.setPowerMode(.lightSleep) return 0 } } } func op_SELP() -> Bit // SELP { /* SELP Select Pointer P ========================================================================================= SELP operand: none Operation: ptr = P ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- SELP 0010_1000_00 1 ========================================================================================= */ cpu.reg.R = 0 return 0 } func op_SELQ() -> Bit // SELQ { /* SELQ Select Pointer Q ========================================================================================= SELQ operand: none Operation: ptr = Q ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- SELQ 0011_1000_00 1 ========================================================================================= */ cpu.reg.R = 1 return 0 } func op_ifPeqQ() -> Bit // ?P=Q { /* ?P=Q Test P Equal To Q ========================================================================================= ?P=Q operand: none Operation: CY <= (P == Q) ========================================================================================= Flag: Set if P equals Q; cleared otherwise. ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ?P=Q 0100_1000_00 1 ========================================================================================= */ return cpu.reg.P == cpu.reg.Q ? 1 : 0 } func op_ifLLD() -> Bit // ?LLD { /* ?LLD Low Level Detect ========================================================================================= ?LLD operand: none Operation: CY <= low_battery_status ========================================================================================= Flag: Set if the lld input is Low, signaling a Low Battery; cleared otherwise. ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ?LLD 0101_1000_00 1 ========================================================================================= Note: Our batteries NEVER go flat! Or your money back! */ return 0 } func op_CLRABC() -> Bit // CLRABC { /* CLRABC Clear A, B and C ========================================================================================= CLRABC operand: none Operation: A <= 0 B <= 0 C <= 0 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CLRABC 0110_1000_00 1 ========================================================================================= */ cpu.reg.A = Digits14() cpu.reg.B = Digits14() cpu.reg.C = Digits14() return 0 } func op_GOTOC() -> Bit // GOTOC { /* GOTOC Branch using C register ========================================================================================= GOTOC operand: none Operation: PC <= C<6:3> ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- GOTOC 0111_1000_00 1 ========================================================================================= */ var digits = Digits14() var pos = 0 for idx in 3...6 { digits[pos] = cpu.reg.C[idx] pos += 1 } cpu.reg.PC = digitsToBits( digits: digits, nbits: 16 ) return 0 } func op_CeqKEYS() -> Bit // C=KEYS { /* C=KEYS Load C From KEYS ========================================================================================= C=KEYS operand: none Operation: C<4:3> <= KEYS ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=KEYS 1000_1000_00 1 ========================================================================================= */ bitsToDigits( bits: Int(cpu.reg.KY), destination: &cpu.reg.C, start: 3, count: 2 ) return 0 } func op_SETHEX() -> Bit // SETHEX { /* SETHEX Set Hex Mode ========================================================================================= SETHEX operand: none Operation: hex_mode = 1 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- SETHEX 1001_1000_00 1 ========================================================================================= */ cpu.reg.mode = .hex_mode return 0 } func op_SETDEC() -> Bit // SETDEC { /* SETDEC Set Decimal Mode ========================================================================================= SETDEC operand: none Operation: hex_mode = 0 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- SETDEC 1010_1000_00 1 ========================================================================================= */ cpu.reg.mode = .dec_mode return 0 } func op_DISOFF() -> Bit // DISOFF { /* DISOFF Display off ========================================================================================= DISOFF operand: none Operation: No operation ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- DISOFF 1011_1000_00 1 ========================================================================================= Note: This instruction is a NOP for the processor, but is interpreted by the (off-chip) LCD display controller, which turns off the display. */ NotificationCenter.default.post(name: Notification.Name(rawValue: "displayOff"), object: nil) return 0 } func op_DISTOG() -> Bit // DISTOG { /* DISTOG Display Toggle ========================================================================================= DISTOG operand: none Operation: No operation ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- DISTOG 1100_1000_00 1 ========================================================================================= Note: This instruction is a NOP for the processor, but is interpreted by the (off-chip) LCD display controller, which toggles the display. */ NotificationCenter.default.post(name: Notification.Name(rawValue: "displayToggle"), object: nil) return 0 } func op_RTNC() -> Bit // RTNC { /* RTNC Return from subroutine on Carry ========================================================================================= RTNC operand: none Operation: if (CY) begin PC <= STK0 STK0 <= STK1 STK1 <= STK2 STK2 <= STK3 STK3 <= 0000 end ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- RTNC 1101_1000_00 1 ========================================================================================= */ if cpu.reg.carry != 0 { cpu.reg.PC = cpu.popReturnStack() } return 0 } func op_RTNNC() -> Bit // RTNNC { /* RTNNC Return from subroutine on No Carry ========================================================================================= RTNNC operand: none Operation: if (!CY) begin PC <= STK0 STK0 <= STK1 STK1 <= STK2 STK2 <= STK3 STK3 <= 0000 end ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- RTNNC 1110_1000_00 1 ========================================================================================= */ if cpu.reg.carry == 0 { cpu.reg.PC = cpu.popReturnStack() } return 0 } func op_RTN() -> Bit // RTN { /* RTN Return from subroutine ========================================================================================= RTN operand: none Operation: PC <= STK0 STK0 <= STK1 STK1 <= STK2 STK2 <= STK3 STK3 <= 0000 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- RTN 1111_1000_00 1 ========================================================================================= */ cpu.reg.PC = cpu.popReturnStack() return 0 } // MARK: - Subclass 9 func op_SELPF(_ param: Int) -> Bit // SELPF { /* SELPF Select Peripheral ========================================================================================= SELPF operand: peripheral number Operation: transfer control to peripheral n ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- SELPF n nnnn_1001_00 2 or more ========================================================================================= Note: This instruction transfers control from the CPU to an intelligent peripheral. The CPU continues to fetch instructions, incrementing the PC with each fetch, but in general ignores the instructions fetched from the isa_bus. Control is returned to the CPU when the instruction fetched has the LSB set to one. All of these fetches are executed at normal bus speed, including the first fetch after control is returned to the CPU. Two instructions are available to transfer information from the peripheral back to the CPU: First, the ?PFLGn=1 instruction transfers the contents of one of sixteen flags internal to the peripheral back to the CY flag during the first clock cycle of the following instruction (which is executed by the CPU). Second, the C=DATAPn instruction sets the data_bus as an input and the contents of the data_bus during the execution of this instruction is loaded into the C register. With these two instructions, either status information or data may be communicated from the peripheral to the CPU. */ switch param { case 0xE, 0x9: // Printer ROM is loaded? if let _ = bus.romChipInSlot(6) { cpu.reg.peripheral = 1 } default: break } return 0 } // MARK: - Subclass A func op_REGNeqC(_ param: Int) -> Bit // REGN=C { /* REGN=C Load Register from C ========================================================================================= REGN=C operand: register number Operation: reg_addr <= {reg_addr[11:4], nnnn} REG[reg_addr] <= C ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent for valid register address; fetched and executed at bus speed for an unimplemented register or a peripheral register. ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- REGN=C n nnnn_1010_00 1 ========================================================================================= Note: Bits 11-4 of the register address must have been previously loaded into reg_addr by a DADD=C instruction. The data is actually written to the parallel memory bus using the RAM chip select. The value nnnn replaces the least significant four bits of the current value in the latched register address reg_addr. */ if cpu.reg.peripheral == 0 || cpu.reg.ramAddress <= 0x00F || cpu.reg.ramAddress >= 0x020 { // RAM is currently selected peripheral cpu.reg.ramAddress = (cpu.reg.ramAddress & 0x0FF0) | Bits12(param) do { try bus.writeRamAddress(cpu.reg.ramAddress, from: cpu.reg.C) } catch _ { // displayAlert("error writing ram at address: \(cpu.reg.ramAddress)") } } else { switch (cpu.reg.peripheral) { case 0x10: // Halfnut display if let display = bus.display { display.halfnutWrite() } case 0xfb: // Timer write bus.writeToRegister( Bits4(param), ofPeripheral: cpu.reg.peripheral ) case 0xfc: // Card reader break case 0xfd: // LCD display if let display = bus.display { display.displayWrite() } // bus.writeToRegister( // Bits4(param), // ofPeripheral: cpu.reg.peripheral, // from: &cpu.reg.C // ) case 0xfe: // Wand break default: break } } return 0 } // MARK: - Subclass B func op_FDeq1(_ param: Int) -> Bit // ?Fd=1 { /* ?Fd=1 Test Flag Input Equal to One ========================================================================================= ?Fd=1 operand: Digit Number Operation: CY <= FI<digit> ========================================================================================= Flag: Set/Cleared to match the selected Flag Input ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at normal bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- ?Fd=1 dddd_1011_00 1 ========================================================================================= Note: The flag input, fi_bus, is sampled near the middle of the appropriate digit time (on the falling edge of the second ph1 clock) during the execution phase of this instruction. The following flags are currently used in an HP-41 system: ================================================================ | flag number | device | Mnemonic | Used for | ================================================================ | 0 | 82143A | ?PBSY | Printer Busy | | | 82242A | | | | 1 | 82104A | ?CRDR | Card Reader | | 2 | 82153A | ?WNDB | Wand Byte Available | | 5 | 82242A | ?EDAV | Emitter Diode Available | | 6 | 82160A | ?IFCR | Interface Clear Received | | 7 | 82160A | ?SRQR | Service Request Received | | 8 | 82160A | ?FRAV | Frame Available | | 9 | 82160A | ?FRNS | Frame Received Not As Sent | | 10 | 82160A | ?ORAV | Output Register Available | | 12 | 82182A | ?ALM | Alarm | | 13 | all | ?SER | Service Request | ================================================================ */ if param == 0x7 || param == 0xf { return 0 } else { return (cpu.reg.FI & Bits14(1 << param)) != 0 ? 1 : 0 } } // MARK: - Subclass C func op_ROMBLK() -> Bit // ROMBLK { //TODO: HEPAX Support /* ROMBLK - Eramco pg. 125 Moves Hepax ROM to page specified in C[0]- only known to work with HEPAX module HEPAX may be on top of a RAM page and when it moves the RAM (alternate) becomes visible */ //TODO: CHECK!!!! let destination = cpu.reg.C[0] - 1 for slot in 0x5..<0xf { for bank in 1..<4 { guard (bus.romChips[slot][bank - 1] != nil) else { continue } if let rom = bus.romChips[slot][bank - 1] { if rom.HEPAX == 0 || rom.RAM != 0 { // only move hepax ROM and not RAM continue } } let altRom = bus.romChips[Int(destination)][bank - 1] // if there is something at the dest page, save it as the dest alt page (does not normally happen) bus.romChips[Int(destination)][bank - 1] = bus.romChips[slot][bank - 1] if let modulePage = bus.romChips[slot][bank - 1]?.altPage { bus.romChips[slot][bank - 1] = RomChip(fromBIN: modulePage.image, actualBankGroup: modulePage.actualBankGroup) // move src alt page to primary now that hepax is moved off it bus.romChips[Int(destination)][bank - 1] = altRom } } } return 0 } func op_NeqC() -> Bit // N=C { /* N=C Load N from C ========================================================================================= N=C operand: none Operation: N <= C ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- N=C 0001_1100_00 1 ========================================================================================= */ cpu.reg.N = cpu.reg.C return 0 } func op_CeqN() -> Bit // C=N { /* C=N Load C from N ========================================================================================= C=N operand: none Operation: C <= N ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=N 0010_1100_00 1 ========================================================================================= */ cpu.reg.C = cpu.reg.N return 0 } func op_CNEX() -> Bit // CNEX { /* CNEX Exchange C and N ========================================================================================= CNEX operand: none Operation: fork C <= N N <= C join ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CNEX 0011_1100_00 1 ========================================================================================= */ var x = cpu.reg.C var y = cpu.reg.N exchangeDigits( X: &x, Y: &y, startPos: 0, count: 14 ) cpu.reg.C = x cpu.reg.N = y return 0 } func op_LDI() -> Bit // LDI { /* LDI Load Immediate ========================================================================================= LDI operand: immediate 10-bit value Operation: C<2:0> <= {2’b00, const} ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- LDI const 0100_1100_00 2 const ========================================================================================= Note: When executed at bus speed the sync signal is suppressed during the fetch of the second word of the instruction to prevent external devices from incorrectly interpreting the contents of the isa_bus during the second machine cycle as an instruction. */ var value: Int do { value = try cpu.fetch() } catch { value = 0 } bitsToDigits( bits: value, destination: &cpu.reg.C, start: 0, count: 3 ) return 0 } func op_STKeqC() -> Bit // STK=C { /* STK=C Push C ========================================================================================= STK=C operand: none Operation: STK3 <= STK2 STK2 <= STK1 STK1 <= STK0 STK0 <= C<6:3> ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- STK=C 0101_1100_00 1 ========================================================================================= */ // var word: UInt16 = 0 var digits = Digits14() var pos = 0 for idx in 3...6 { digits[pos] = cpu.reg.C[idx] pos += 1 } let word: UInt16 = digitsToBits( digits: digits, nbits: 16 ) cpu.pushReturnStack(Bits16(word)) return 0 } func op_CeqSTK() -> Bit // C=STK { /* C=STK Load C From STK ========================================================================================= C=STK operand: none Operation: C<6:3> <= STK0 STK0 <= STK1 STK1 <= STK2 STK2 <= STK3 STK3 <= 0000 ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=STK 0110_1100_00 1 ========================================================================================= */ let word = cpu.popReturnStack() bitsToDigits( bits: Int(word), destination: &cpu.reg.C, start: 3, count: 4 ) return 0 } func op_WPTOG() -> Bit { /* WPTOG - Toggles write protection on HEPAX RAM at page C[0] */ let page = cpu.reg.C[0] - 1 if let romChip = bus.romChipInSlot(Bits4(page), bank: Bits4(1)) { if romChip.HEPAX != 0 || romChip.RAM != 0 { romChip.writable = !romChip.writable } } return 0 } func op_GOKEYS() -> Bit // GOKEYS { /* GOKEYS Branch to Keys ========================================================================================= GOKEYS operand: none Operation: PC <= {PC[15:8], KEYS} ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- GOKEYS 1000_1100_00 1 ========================================================================================= */ cpu.reg.PC = (cpu.reg.PC & 0xff00) | Bits16(cpu.reg.KY) return 0 } func op_DADDeqC() -> Bit // DADD=C { /* DADD=C Load Register address from C ========================================================================================= DADD=C operand: none Operation: reg_addr <= C<2:0> ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- DADD=C 1001_1100_00 1 ========================================================================================= Note: The register address is loaded into reg_addr (at memory location 0x804000) by the DADD=C instruction. */ cpu.reg.ramAddress = digitsToBits( digits: cpu.reg.C, nbits: 12 ) return 0 } func op_CLRDATA() -> Bit // CLRDATA { /* CLRDATA Clear Registers ========================================================================================= CLRDATA operand: none Operation: No operation ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CLRDATA 1010_1100_00 1 ========================================================================================= Note: This instruction is a NOP for the processor. The original data storage chips used in the HP-41 series cleared all 16 registers on the selected data storage chip as a result of this instruction. */ // cpu.clearRegisters() return 0 } func op_DATAeqC() -> Bit // DATA=C { /* DATA=C Load Register from C ========================================================================================= DATA=C operand: none Operation: REG[reg_addr] <= C ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent for valid register address; fetched and executed at bus speed for an unimplemented register or a peripheral register. ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- DATA=C 1011_1100_00 1 ========================================================================================= Note: The register address must have been previously loaded into reg_addr by a DADD=C instruction. The data is actually written to the parallel memory bus using the RAM chip select. */ if cpu.reg.peripheral == 0 || cpu.reg.peripheral == 0xFB { do { try bus.writeRamAddress(cpu.reg.ramAddress, from: cpu.reg.C) } catch _ { if TRACE != 0 { print("error writing ram at address: \(cpu.reg.ramAddress)") } } } else { bus.writeDataToPeripheral( slot: cpu.reg.peripheral, from: cpu.reg.C ) } return 0 } func op_CXISA() -> Bit // CXISA { /* CXISA Exchange C and ISA ========================================================================================= CXISA operand: none Operation: mem_addr <= C<6:3> C<2:0> <= ISA[mem_addr] ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- CXISA 1100_1100_00 2 ========================================================================================= Note: During the second machine cycle of this instruction the contents of C<6:3> are used as a program memory address on isa_bus. The contents of this program memory location are then loaded into C<2:0>, right-justified, with the two most significant bits set to 0. */ let page = Int(cpu.reg.C[6]) let addr = (Int(cpu.reg.C[5]) << 8) | (Int(cpu.reg.C[4]) << 4) | Int(cpu.reg.C[3]) var opcode: Int if let rom = bus.romChips[page][bus.activeBank[page] - 1] { opcode = Int(rom.words[addr]) } else { opcode = 0 } cpu.reg.C[2] = Digit(((opcode & 0x0300) >> 8)) cpu.reg.C[1] = Digit(((opcode & 0x00f0) >> 4)) cpu.reg.C[0] = Digit(opcode & 0x000f) return 0 } func op_CeqCorA() -> Bit // C=CORA { /* C=CORA Load C With C OR A ========================================================================================= C=CORA operand: none Operation: C <= C | A ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=CORA 1101_1100_00 1 ========================================================================================= Note: In the original NUT implementation this instruction cannot immediately follow an arithmetic (type 10) instruction. */ cpu.reg.C = orDigits( X: cpu.reg.C, Y: cpu.reg.A, start: 0, count: 14 ) //TODO: David Assembler pg 60 CPU errors return 0 } func op_CeqCandA() -> Bit // C=C&A { /* C=C&A Load C With C AND A ========================================================================================= C=C&A operand: none Operation: C <= C & A ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=C&A 1110_1100_00 1 ========================================================================================= Note: In the original NUT implementation this instruction cannot immediately follow an arithmetic (type 10) instruction. */ cpu.reg.C = andDigits( X: cpu.reg.C, Y: cpu.reg.A, start: 0, count: 14 ) //TODO: David Assembler pg 60 CPU errors return 0 } func op_PFADeqC() -> Bit // PFAD=C { /* PFAD=C Load Peripheral Address from C ========================================================================================= PFAD=C operand: none Operation: No operation ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- PFAD=C 1111_1100_00 1 ========================================================================================= Note: This instruction is a NOP for the processor, but is interpreted by peripheral devices to perform the chip select function. The peripheral chip select remains active until another PFAD=C instruction selects a different peripheral. Peripheral devices decode the least-significant byte on the data_bus according to the following table: =============================== | c<1:0> | Peripheral Device | =============================== | 0xF0 | NEWT On-chip Port | | 0xFB | Timer | | 0xFC | Card Reader | | 0xFD | LCD Display Driver | | 0xFE | Wand | =============================== */ var digits = Digits14() for idx in 0...1 { digits[idx] = cpu.reg.C[idx] } let temp = digitsToBits( digits: digits, nbits: 8 ) cpu.reg.peripheral = Bits8(temp) return 0 } // MARK: - Subclass E func op_CeqDATA(_ param: Int) -> Bit // C=DATA { /* C=DATA Load C From Register (Indirect) ========================================================================================= C=DATA operand: none Operation: C <= REG[reg_addr] ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent for valid register address; fetched and executed at bus speed for an unimplemented register or a peripheral register. ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=DATA 0000_1110_00 1 ========================================================================================= Note: The register address must have been previously loaded into reg_addr by a DADD=C instruction. The data is actually loaded from the parallel memory bus using the RAM chip select. There are unimplemented areas in the register map in 41C mode. Accessing an unimplemented register causes the data_bus to remain floating, allowing an external device to drive the data_bus. */ if (cpu.reg.peripheral == 0 || (cpu.reg.ramAddress <= 0x000F) || (cpu.reg.ramAddress >= 0x0020)) { do { cpu.reg.C = try bus.readRamAddress(cpu.reg.ramAddress) } catch { if TRACE != 0 { print("error RAM address: \(cpu.reg.ramAddress)") } } } else { bus.readFromRegister( register: Bits4(param), ofPeripheral: cpu.reg.peripheral ) } return 0 } func op_CeqREGN(_ param: Int) -> Bit // C=REGN { /* C=REGN Load C From Register ========================================================================================= C=REGN operand: register number Operation: reg_addr <= {reg_addr[11:4], nnnn} C <= REG[reg_addr] ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent for valid register address; fetched and executed at bus speed for an unimplemented register or a peripheral register. ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- C=REGN n nnnn_1110_00 1 ========================================================================================= Note: Bits 11-4 of the register address must have been previously loaded into reg_addr by a DADD=C instruction. The data is actually loaded from the parallel memory bus using the RAM chip select. As discussed in the Memory Organization chapter, there are unimplemented areas in the register map in 41C mode. Accessing an unimplemented register causes the data_bus to remain floating, allowing an external device to drive the data_bus. Only fifteen encodings are valid for nnnn. The all zeros case is the C=DATA instruction, with indirect register addressing. */ if (cpu.reg.peripheral == 0 || (cpu.reg.ramAddress <= 0x000F) || (cpu.reg.ramAddress >= 0x0020)) { cpu.reg.ramAddress = Bits12(cpu.reg.ramAddress & 0x03F0) | Bits12(param) do { cpu.reg.C = try bus.readRamAddress(cpu.reg.ramAddress) } catch { if TRACE != 0 { print("error RAM address: \(cpu.reg.ramAddress)") } } } else { bus.readFromRegister( register: Bits4(param), ofPeripheral: cpu.reg.peripheral ) } return 0 } // MARK: - Subclass F func op_WCMD() -> Bit // WCMD { /* WCMD Write Command ========================================================================================= WCMD operand: none Operation: No operation ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Automatically fetched and executed at bus speed ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- WCMD 0111_1111_00 1 ========================================================================================= Note: This instruction is a NOP as far as the processor is concerned, but is interpreted by the Memory Management Unit or Turbo Control Unit. Writes automatically transfer the contents of the C register to the destination. Reads latch the relevant data, which can then be accessed via the on-chip I/O Port. The contents of digit 4 are interpreted as a command, and some of the remaining digit contents are used for data. The write commands are: ==================================== | Command | Meaning | |==================================| | 0 | Write MMU (per bank) | |----------------------------------| | 2 | Write Logical Address | |----------------------------------| | 4 | Write Physical Address | |----------------------------------| | 6 | Global MMU Disable | |----------------------------------| | 7 | Global MMU Enable | |----------------------------------| | 8 | Disable Turbo Mode | |----------------------------------| | 9 | Enable 2X Turbo Mode | |----------------------------------| | A | Enable 5X Turbo Mode | |----------------------------------| | B | Enable 10X Turbo Mode | |----------------------------------| | C | Enable 20X Turbo Mode | |----------------------------------| | D | Enable 50X Turbo Mode | |----------------------------------| | E | Special MMU Disable | |----------------------------------| | F | Special MMU Enable | ==================================== The read commands are: ======================================== | Command | Meaning | |======================================| | 1 | Read MMU (per bank) | |--------------------------------------| | 3 | Read from Logical Address | |--------------------------------------| | 5 | Read from Physical Address | ======================================== The table below shows the format of the data used by these commands. Refer to the Memory Organization, Turbo Mode or I/O Port chapter for more details. ----------------------------------------------------------------------- nibble | 13 | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | ----------------------------------------------------------------------- ----------------------------------------------------------------------- Write MMU | |page| |bank| 0 | en | ph addr | |---------------------------------------------------------------------| Read MMU | |page| |bank| 1 | | |---------------------------------------------------------------------| Write Logical Address | | logical address |bank| 2 | write data | |---------------------------------------------------------------------| Read Logical Address | | logical address |bank| 3 | | |---------------------------------------------------------------------| Write Physical Address | | physical address | | 4 | write data | |---------------------------------------------------------------------| Read Physical Address | | physical address | | 5 | | |---------------------------------------------------------------------| Global MMU Disable | | 6 | | |---------------------------------------------------------------------| Global MMU Enable | | 7 | | |---------------------------------------------------------------------| Disable Turbo Mode | | 8 | | |---------------------------------------------------------------------| Enable 2x Turbo Mode | | 9 | | |---------------------------------------------------------------------| Enable 5x Turbo Mode | | A | | |---------------------------------------------------------------------| Enable 10x Turbo Mode | | B | | |---------------------------------------------------------------------| Enable 20x Turbo Mode | | C | | |---------------------------------------------------------------------| Enable 50x Turbo Mode | | D | | |---------------------------------------------------------------------| Special MMU Disable | | E | | |---------------------------------------------------------------------| Special MMU Enable | | F | | ----------------------------------------------------------------------- */ return 0 } func op_RCR(_ param: Int) -> Bit // RCR { /* RCR Rotate C right by digits ========================================================================================= RCR operand: none Operation: for (i=0; i<d; i++) begin C <= {C<0>, C<13:1>} end ========================================================================================= Flag: Cleared ========================================================================================= Dec/Hex: Independent Turbo: Independent ========================================================================================= Assembly Syntax Encoding Machine Cycles ----------------------------------------------------------------------------------------- RCR d dddd_1111_00 1 ========================================================================================= */ var temp = Digits14() var tempC = cpu.reg.C copyDigits( cpu.reg.C, sourceStartAt: 0, destination: &temp, destinationStartAt: 0, count: param ) copyDigits( cpu.reg.C, sourceStartAt: param, destination: &tempC, destinationStartAt: 0, count: 14-param ) copyDigits( temp, sourceStartAt: 0, destination: &tempC, destinationStartAt: 14-param, count: param ) cpu.reg.C = tempC return 0 }
bsd-3-clause
82f8903c439e44648567aa2217877401
35.685992
195
0.355345
4.882853
false
false
false
false
PatrickChow/ForOneNight
NightDriver/Source/UIKit/UISearchBar+Nv.swift
1
2280
// // Created by Patrick Chow on 2017/5/9. // Copyright (c) 2017 Jiemian Technology. All rights reserved. import UIKit.UISearchBar extension Reactive where Base: UISearchBar { @discardableResult public func barTintColor(_ day: RenderPropertyType?, night: RenderPropertyType?) -> Self { base?.barTintColor = renderProperty(day,night) as? UIColor propertiesObserved.append { [weak self] in self?.base?.barTintColor = self?.renderProperty(day,night) as? UIColor } return self } @discardableResult public func backgroundImage(_ day: RenderPropertyType?, night: RenderPropertyType?, for position: UIBarPosition = .any, barMetrics: UIBarMetrics) -> Self { base?.setBackgroundImage(renderProperty(day,night) as? UIImage, for: position, barMetrics: barMetrics) propertiesObserved.append { [weak self] in self?.base?.setBackgroundImage(self?.renderProperty(day,night) as? UIImage, for: position, barMetrics: barMetrics) } return self } @discardableResult public func searchFieldBackgroundImage(_ day: RenderPropertyType?, night: RenderPropertyType?, for state: UIControlState = .normal) -> Self { base?.setSearchFieldBackgroundImage(renderProperty(day,night) as? UIImage, for: state) propertiesObserved.append { [weak self] in self?.base?.setSearchFieldBackgroundImage(self?.renderProperty(day,night) as? UIImage, for: state) } return self } @discardableResult public func image(_ day: RenderPropertyType?, night: RenderPropertyType?, for icon: UISearchBarIcon = .search, state: UIControlState = .normal) -> Self { base?.setImage(renderProperty(day,night) as? UIImage, for: icon, state: state) propertiesObserved.append { [weak self] in self?.base?.setImage(self?.renderProperty(day,night) as? UIImage, for: icon, state: state) } return self } }
mit
050953e13bd008ac6d5016dce3369b7a
39.714286
110
0.595175
5.364706
false
false
false
false
zvonler/PasswordElephant
external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/TextFormatScanner.swift
4
35930
// Sources/SwiftProtobuf/TextFormatScanner.swift - Text format decoding // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Test format decoding engine. /// // ----------------------------------------------------------------------------- import Foundation private let asciiBell = UInt8(7) private let asciiBackspace = UInt8(8) private let asciiTab = UInt8(9) private let asciiNewLine = UInt8(10) private let asciiVerticalTab = UInt8(11) private let asciiFormFeed = UInt8(12) private let asciiCarriageReturn = UInt8(13) private let asciiZero = UInt8(ascii: "0") private let asciiOne = UInt8(ascii: "1") private let asciiThree = UInt8(ascii: "3") private let asciiSeven = UInt8(ascii: "7") private let asciiNine = UInt8(ascii: "9") private let asciiColon = UInt8(ascii: ":") private let asciiPeriod = UInt8(ascii: ".") private let asciiPlus = UInt8(ascii: "+") private let asciiComma = UInt8(ascii: ",") private let asciiSemicolon = UInt8(ascii: ";") private let asciiDoubleQuote = UInt8(ascii: "\"") private let asciiSingleQuote = UInt8(ascii: "\'") private let asciiBackslash = UInt8(ascii: "\\") private let asciiForwardSlash = UInt8(ascii: "/") private let asciiHash = UInt8(ascii: "#") private let asciiUnderscore = UInt8(ascii: "_") private let asciiQuestionMark = UInt8(ascii: "?") private let asciiSpace = UInt8(ascii: " ") private let asciiOpenSquareBracket = UInt8(ascii: "[") private let asciiCloseSquareBracket = UInt8(ascii: "]") private let asciiOpenCurlyBracket = UInt8(ascii: "{") private let asciiCloseCurlyBracket = UInt8(ascii: "}") private let asciiOpenAngleBracket = UInt8(ascii: "<") private let asciiCloseAngleBracket = UInt8(ascii: ">") private let asciiMinus = UInt8(ascii: "-") private let asciiLowerA = UInt8(ascii: "a") private let asciiUpperA = UInt8(ascii: "A") private let asciiLowerB = UInt8(ascii: "b") private let asciiLowerE = UInt8(ascii: "e") private let asciiUpperE = UInt8(ascii: "E") private let asciiLowerF = UInt8(ascii: "f") private let asciiUpperF = UInt8(ascii: "F") private let asciiLowerI = UInt8(ascii: "i") private let asciiLowerL = UInt8(ascii: "l") private let asciiLowerN = UInt8(ascii: "n") private let asciiLowerR = UInt8(ascii: "r") private let asciiLowerS = UInt8(ascii: "s") private let asciiLowerT = UInt8(ascii: "t") private let asciiUpperT = UInt8(ascii: "T") private let asciiLowerU = UInt8(ascii: "u") private let asciiLowerV = UInt8(ascii: "v") private let asciiLowerX = UInt8(ascii: "x") private let asciiLowerY = UInt8(ascii: "y") private let asciiLowerZ = UInt8(ascii: "z") private let asciiUpperZ = UInt8(ascii: "Z") private func fromHexDigit(_ c: UInt8) -> UInt8? { if c >= asciiZero && c <= asciiNine { return c - asciiZero } if c >= asciiUpperA && c <= asciiUpperF { return c - asciiUpperA + UInt8(10) } if c >= asciiLowerA && c <= asciiLowerF { return c - asciiLowerA + UInt8(10) } return nil } // Protobuf Text encoding assumes that you're working directly // in UTF-8. So this implementation converts the string to UTF8, // then decodes it into a sequence of bytes, then converts // it back into a string. private func decodeString(_ s: String) -> String? { var out = [UInt8]() var bytes = s.utf8.makeIterator() while let byte = bytes.next() { switch byte { case asciiBackslash: // backslash if let escaped = bytes.next() { switch escaped { case asciiZero...asciiSeven: // 0...7 // C standard allows 1, 2, or 3 octal digits. let savedPosition = bytes let digit1 = escaped let digit1Value = digit1 - asciiZero if let digit2 = bytes.next(), digit2 >= asciiZero && digit2 <= asciiSeven { let digit2Value = digit2 - asciiZero let innerSavedPosition = bytes if let digit3 = bytes.next(), digit3 >= asciiZero && digit3 <= asciiSeven { let digit3Value = digit3 - asciiZero let n = digit1Value * 64 + digit2Value * 8 + digit3Value out.append(n) } else { let n = digit1Value * 8 + digit2Value out.append(n) bytes = innerSavedPosition } } else { let n = digit1Value out.append(n) bytes = savedPosition } case asciiLowerX: // "x" // Unlike C/C++, protobuf only allows 1 or 2 digits here: if let byte = bytes.next(), let digit = fromHexDigit(byte) { var n = digit let savedPosition = bytes if let byte = bytes.next(), let digit = fromHexDigit(byte) { n = n &* 16 + digit } else { // No second digit; reset the iterator bytes = savedPosition } out.append(n) } else { return nil // Hex escape must have at least 1 digit } case asciiLowerA: // \a out.append(asciiBell) case asciiLowerB: // \b out.append(asciiBackspace) case asciiLowerF: // \f out.append(asciiFormFeed) case asciiLowerN: // \n out.append(asciiNewLine) case asciiLowerR: // \r out.append(asciiCarriageReturn) case asciiLowerT: // \t out.append(asciiTab) case asciiLowerV: // \v out.append(asciiVerticalTab) case asciiDoubleQuote, asciiSingleQuote, asciiQuestionMark, asciiBackslash: // " ' ? \ out.append(escaped) default: return nil // Unrecognized escape } } else { return nil // Input ends with backslash } default: out.append(byte) } } // There has got to be an easier way to convert a [UInt8] into a String. return out.withUnsafeBufferPointer { ptr in if let addr = ptr.baseAddress { return utf8ToString(bytes: addr, count: ptr.count) } else { return String() } } } /// /// TextFormatScanner has no public members. /// internal struct TextFormatScanner { internal var extensions: ExtensionMap? private var p: UnsafePointer<UInt8> private var end: UnsafePointer<UInt8> private var doubleFormatter = DoubleFormatter() internal var complete: Bool { mutating get { return p == end } } internal init(utf8Pointer: UnsafePointer<UInt8>, count: Int, extensions: ExtensionMap? = nil) { p = utf8Pointer end = p + count self.extensions = extensions skipWhitespace() } /// Skip whitespace private mutating func skipWhitespace() { while p != end { let u = p[0] switch u { case asciiSpace, asciiTab, asciiNewLine, asciiCarriageReturn: // space, tab, NL, CR p += 1 case asciiHash: // # comment p += 1 while p != end { // Skip until end of line let c = p[0] p += 1 if c == asciiNewLine || c == asciiCarriageReturn { break } } default: return } } } /// Return a buffer containing the raw UTF8 for an identifier. /// Assumes that you already know the current byte is a valid /// start of identifier. private mutating func parseUTF8Identifier() -> UnsafeBufferPointer<UInt8> { let start = p loop: while p != end { let c = p[0] switch c { case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ, asciiZero...asciiNine, asciiUnderscore: p += 1 default: break loop } } let s = UnsafeBufferPointer(start: start, count: p - start) skipWhitespace() return s } /// Return a String containing the next identifier. private mutating func parseIdentifier() -> String { let buff = parseUTF8Identifier() let s = utf8ToString(bytes: buff.baseAddress!, count: buff.count) // Force-unwrap is OK: we never have invalid UTF8 at this point. return s! } /// Parse the rest of an [extension_field_name] in the input, assuming the /// initial "[" character has already been read (and is in the prefix) /// This is also used for AnyURL, so we include "/", "." private mutating func parseExtensionKey() -> String? { let start = p if p == end { return nil } let c = p[0] switch c { case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ: p += 1 default: return nil } while p != end { let c = p[0] switch c { case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ, asciiZero...asciiNine, asciiUnderscore, asciiPeriod, asciiForwardSlash: p += 1 case asciiCloseSquareBracket: // ] return utf8ToString(bytes: start, count: p - start) default: return nil } } return nil } /// Scan a string that encodes a byte field, return a count of /// the number of bytes that should be decoded from it private mutating func validateAndCountBytesFromString(terminator: UInt8, sawBackslash: inout Bool) throws -> Int { var count = 0 let start = p sawBackslash = false while p != end { let byte = p[0] p += 1 if byte == terminator { p = start return count } switch byte { case asciiBackslash: // "\\" sawBackslash = true if p != end { let escaped = p[0] p += 1 switch escaped { case asciiZero...asciiSeven: // '0'...'7' // C standard allows 1, 2, or 3 octal digits. if p != end, p[0] >= asciiZero, p[0] <= asciiSeven { p += 1 if p != end, p[0] >= asciiZero, p[0] <= asciiSeven { if escaped > asciiThree { // Out of range octal: three digits and first digit is greater than 3 throw TextFormatDecodingError.malformedText } p += 1 } } count += 1 case asciiLowerX: // 'x' hexadecimal escape if p != end && fromHexDigit(p[0]) != nil { p += 1 if p != end && fromHexDigit(p[0]) != nil { p += 1 } } else { throw TextFormatDecodingError.malformedText // Hex escape must have at least 1 digit } count += 1 case asciiLowerA, // \a ("alert") asciiLowerB, // \b asciiLowerF, // \f asciiLowerN, // \n asciiLowerR, // \r asciiLowerT, // \t asciiLowerV, // \v asciiSingleQuote, // \' asciiDoubleQuote, // \" asciiQuestionMark, // \? asciiBackslash: // \\ count += 1 default: throw TextFormatDecodingError.malformedText // Unrecognized escape } } default: count += 1 } } throw TextFormatDecodingError.malformedText } /// Protobuf Text format uses C ASCII conventions for /// encoding byte sequences, including the use of octal /// and hexadecimal escapes. /// /// Assumes that validateAndCountBytesFromString() has already /// verified the correctness. So we get to avoid error checks here. private mutating func parseBytesFromString(terminator: UInt8, into data: inout Data) { data.withUnsafeMutableBytes { (dataPointer: UnsafeMutablePointer<UInt8>) in var out = dataPointer while p[0] != terminator { let byte = p[0] p += 1 switch byte { case asciiBackslash: // "\\" let escaped = p[0] p += 1 switch escaped { case asciiZero...asciiSeven: // '0'...'7' // C standard allows 1, 2, or 3 octal digits. let digit1Value = escaped - asciiZero let digit2 = p[0] if digit2 >= asciiZero, digit2 <= asciiSeven { p += 1 let digit2Value = digit2 - asciiZero let digit3 = p[0] if digit3 >= asciiZero, digit3 <= asciiSeven { p += 1 let digit3Value = digit3 - asciiZero out[0] = digit1Value &* 64 + digit2Value * 8 + digit3Value out += 1 } else { out[0] = digit1Value * 8 + digit2Value out += 1 } } else { out[0] = digit1Value out += 1 } case asciiLowerX: // 'x' hexadecimal escape // We already validated, so we know there's at least one digit: var n = fromHexDigit(p[0])! p += 1 if let digit = fromHexDigit(p[0]) { n = n &* 16 &+ digit p += 1 } out[0] = n out += 1 case asciiLowerA: // \a ("alert") out[0] = asciiBell out += 1 case asciiLowerB: // \b out[0] = asciiBackspace out += 1 case asciiLowerF: // \f out[0] = asciiFormFeed out += 1 case asciiLowerN: // \n out[0] = asciiNewLine out += 1 case asciiLowerR: // \r out[0] = asciiCarriageReturn out += 1 case asciiLowerT: // \t out[0] = asciiTab out += 1 case asciiLowerV: // \v out[0] = asciiVerticalTab out += 1 default: out[0] = escaped out += 1 } default: out[0] = byte out += 1 } } p += 1 // Consume terminator } } /// Assumes the leading quote has already been consumed private mutating func parseStringSegment(terminator: UInt8) -> String? { let start = p var sawBackslash = false while p != end { let c = p[0] if c == terminator { let s = utf8ToString(bytes: start, count: p - start) p += 1 skipWhitespace() if let s = s, sawBackslash { return decodeString(s) } else { return s } } p += 1 if c == asciiBackslash { // \ if p == end { return nil } sawBackslash = true p += 1 } } return nil // Unterminated quoted string } internal mutating func nextUInt() throws -> UInt64 { if p == end { throw TextFormatDecodingError.malformedNumber } let c = p[0] p += 1 if c == asciiZero { // leading '0' precedes octal or hex if p[0] == asciiLowerX { // 'x' => hex p += 1 var n: UInt64 = 0 while p != end { let digit = p[0] let val: UInt64 switch digit { case asciiZero...asciiNine: // 0...9 val = UInt64(digit - asciiZero) case asciiLowerA...asciiLowerF: // a...f val = UInt64(digit - asciiLowerA + 10) case asciiUpperA...asciiUpperF: val = UInt64(digit - asciiUpperA + 10) case asciiLowerU: // trailing 'u' p += 1 skipWhitespace() return n default: skipWhitespace() return n } if n > UInt64.max / 16 { throw TextFormatDecodingError.malformedNumber } p += 1 n = n * 16 + val } skipWhitespace() return n } else { // octal var n: UInt64 = 0 while p != end { let digit = p[0] if digit == asciiLowerU { // trailing 'u' p += 1 skipWhitespace() return n } if digit < asciiZero || digit > asciiSeven { skipWhitespace() return n // not octal digit } let val = UInt64(digit - asciiZero) if n > UInt64.max / 8 { throw TextFormatDecodingError.malformedNumber } p += 1 n = n * 8 + val } skipWhitespace() return n } } else if c > asciiZero && c <= asciiNine { // 1...9 var n = UInt64(c - asciiZero) while p != end { let digit = p[0] if digit == asciiLowerU { // trailing 'u' p += 1 skipWhitespace() return n } if digit < asciiZero || digit > asciiNine { skipWhitespace() return n // not a digit } let val = UInt64(digit - asciiZero) if n > UInt64.max / 10 || n * 10 > UInt64.max - val { throw TextFormatDecodingError.malformedNumber } p += 1 n = n * 10 + val } skipWhitespace() return n } throw TextFormatDecodingError.malformedNumber } internal mutating func nextSInt() throws -> Int64 { if p == end { throw TextFormatDecodingError.malformedNumber } let c = p[0] if c == asciiMinus { // - p += 1 // character after '-' must be digit let digit = p[0] if digit < asciiZero || digit > asciiNine { throw TextFormatDecodingError.malformedNumber } let n = try nextUInt() let limit: UInt64 = 0x8000000000000000 // -Int64.min if n >= limit { if n > limit { // Too large negative number throw TextFormatDecodingError.malformedNumber } else { return Int64.min // Special case for Int64.min } } return -Int64(bitPattern: n) } else { let n = try nextUInt() if n > UInt64(bitPattern: Int64.max) { throw TextFormatDecodingError.malformedNumber } return Int64(bitPattern: n) } } internal mutating func nextStringValue() throws -> String { var result: String skipWhitespace() if p == end { throw TextFormatDecodingError.malformedText } let c = p[0] if c != asciiSingleQuote && c != asciiDoubleQuote { throw TextFormatDecodingError.malformedText } p += 1 if let s = parseStringSegment(terminator: c) { result = s } else { throw TextFormatDecodingError.malformedText } while true { if p == end { return result } let c = p[0] if c != asciiSingleQuote && c != asciiDoubleQuote { return result } p += 1 if let s = parseStringSegment(terminator: c) { result.append(s) } else { throw TextFormatDecodingError.malformedText } } } /// Protobuf Text Format allows a single bytes field to /// contain multiple quoted strings. The values /// are separately decoded and then concatenated: /// field1: "bytes" 'more bytes' /// "and even more bytes" internal mutating func nextBytesValue() throws -> Data { // Get the first string's contents var result: Data skipWhitespace() if p == end { throw TextFormatDecodingError.malformedText } let c = p[0] if c != asciiSingleQuote && c != asciiDoubleQuote { throw TextFormatDecodingError.malformedText } p += 1 var sawBackslash = false let n = try validateAndCountBytesFromString(terminator: c, sawBackslash: &sawBackslash) if sawBackslash { result = Data(count: n) parseBytesFromString(terminator: c, into: &result) } else { result = Data(bytes: p, count: n) p += n + 1 // Skip string body + close quote } // If there are more strings, decode them // and append to the result: while true { skipWhitespace() if p == end { return result } let c = p[0] if c != asciiSingleQuote && c != asciiDoubleQuote { return result } p += 1 var sawBackslash = false let n = try validateAndCountBytesFromString(terminator: c, sawBackslash: &sawBackslash) if sawBackslash { var b = Data(count: n) parseBytesFromString(terminator: c, into: &b) result.append(b) } else { result.append(p, count: n) p += n + 1 // Skip string body + close quote } } } // Tries to identify a sequence of UTF8 characters // that represent a numeric floating-point value. private mutating func tryParseFloatString() -> Double? { guard p != end else {return nil} let start = p var c = p[0] if c == asciiMinus { p += 1 guard p != end else {p = start; return nil} c = p[0] } switch c { case asciiZero: // '0' as first character only if followed by '.' p += 1 guard p != end else {p = start; return nil} c = p[0] if c != asciiPeriod { p = start return nil } case asciiPeriod: // '.' as first char only if followed by digit p += 1 guard p != end else {p = start; return nil} c = p[0] if c < asciiZero || c > asciiNine { p = start return nil } case asciiOne...asciiNine: break default: p = start return nil } loop: while p != end { let c = p[0] switch c { case asciiZero...asciiNine, asciiPeriod, asciiPlus, asciiMinus, asciiLowerE, asciiUpperE: // 0...9, ., +, -, e, E p += 1 case asciiLowerF: // f // proto1 allowed floats to be suffixed with 'f' let d = doubleFormatter.utf8ToDouble(bytes: start, count: p - start) // Just skip the 'f' p += 1 skipWhitespace() return d default: break loop } } let d = doubleFormatter.utf8ToDouble(bytes: start, count: p - start) skipWhitespace() return d } // Skip specified characters if they all match private mutating func skipOptionalCharacters(bytes: [UInt8]) { let start = p for b in bytes { if p == end || p[0] != b { p = start return } p += 1 } } // Skip following keyword if it matches (case-insensitively) // the given keyword (specified as a series of bytes). private mutating func skipOptionalKeyword(bytes: [UInt8]) -> Bool { let start = p for b in bytes { if p == end { p = start return false } var c = p[0] if c >= asciiUpperA && c <= asciiUpperZ { // Convert to lower case // (Protobuf text keywords are case insensitive) c += asciiLowerA - asciiUpperA } if c != b { p = start return false } p += 1 } if p == end { return true } let c = p[0] if ((c >= asciiUpperA && c <= asciiUpperZ) || (c >= asciiLowerA && c <= asciiLowerZ)) { p = start return false } skipWhitespace() return true } // If the next token is the identifier "nan", return true. private mutating func skipOptionalNaN() -> Bool { return skipOptionalKeyword(bytes: [asciiLowerN, asciiLowerA, asciiLowerN]) } // If the next token is a recognized spelling of "infinity", // return Float.infinity or -Float.infinity private mutating func skipOptionalInfinity() -> Float? { if p == end { return nil } let c = p[0] let negated: Bool if c == asciiMinus { negated = true p += 1 } else { negated = false } let inf = [asciiLowerI, asciiLowerN, asciiLowerF] let infinity = [asciiLowerI, asciiLowerN, asciiLowerF, asciiLowerI, asciiLowerN, asciiLowerI, asciiLowerT, asciiLowerY] if (skipOptionalKeyword(bytes: inf) || skipOptionalKeyword(bytes: infinity)) { return negated ? -Float.infinity : Float.infinity } return nil } internal mutating func nextFloat() throws -> Float { if let d = tryParseFloatString() { let n = Float(d) if n.isFinite { return n } } if skipOptionalNaN() { return Float.nan } if let inf = skipOptionalInfinity() { return inf } throw TextFormatDecodingError.malformedNumber } internal mutating func nextDouble() throws -> Double { if let d = tryParseFloatString() { return d } if skipOptionalNaN() { return Double.nan } if let inf = skipOptionalInfinity() { return Double(inf) } throw TextFormatDecodingError.malformedNumber } internal mutating func nextBool() throws -> Bool { skipWhitespace() if p == end { throw TextFormatDecodingError.malformedText } let c = p[0] p += 1 let result: Bool switch c { case asciiZero: result = false case asciiOne: result = true case asciiLowerF, asciiUpperF: if p != end { let alse = [asciiLowerA, asciiLowerL, asciiLowerS, asciiLowerE] skipOptionalCharacters(bytes: alse) } result = false case asciiLowerT, asciiUpperT: if p != end { let rue = [asciiLowerR, asciiLowerU, asciiLowerE] skipOptionalCharacters(bytes: rue) } result = true default: throw TextFormatDecodingError.malformedText } if p == end { return result } switch p[0] { case asciiSpace, asciiTab, asciiNewLine, asciiCarriageReturn, asciiHash, asciiComma, asciiSemicolon, asciiCloseSquareBracket, asciiCloseCurlyBracket, asciiCloseAngleBracket: skipWhitespace() return result default: throw TextFormatDecodingError.malformedText } } internal mutating func nextOptionalEnumName() throws -> UnsafeBufferPointer<UInt8>? { skipWhitespace() if p == end { throw TextFormatDecodingError.malformedText } switch p[0] { case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ: return parseUTF8Identifier() default: return nil } } /// Any URLs are syntactically (almost) identical to extension /// keys, so we share the code for those. internal mutating func nextOptionalAnyURL() throws -> String? { return try nextOptionalExtensionKey() } /// Returns next extension key or nil if end-of-input or /// if next token is not an extension key. /// /// Throws an error if the next token starts with '[' but /// cannot be parsed as an extension key. /// /// Note: This accepts / characters to support Any URL parsing. /// Technically, Any URLs can contain / characters and extension /// key names cannot. But in practice, accepting / chracters for /// extension keys works fine, since the result just gets rejected /// when the key is looked up. internal mutating func nextOptionalExtensionKey() throws -> String? { skipWhitespace() if p == end { return nil } if p[0] == asciiOpenSquareBracket { // [ p += 1 if let s = parseExtensionKey() { if p == end || p[0] != asciiCloseSquareBracket { throw TextFormatDecodingError.malformedText } // Skip ] p += 1 skipWhitespace() return s } else { throw TextFormatDecodingError.malformedText } } return nil } /// Returns text of next regular key or nil if end-of-input. /// This considers an extension key [keyname] to be an /// error, so call nextOptionalExtensionKey first if you /// want to handle extension keys. /// /// This is only used by map parsing; we should be able to /// rework that to use nextFieldNumber instead. internal mutating func nextKey() throws -> String? { skipWhitespace() if p == end { return nil } let c = p[0] switch c { case asciiOpenSquareBracket: // [ throw TextFormatDecodingError.malformedText case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ, asciiOne...asciiNine: // a...z, A...Z, 1...9 return parseIdentifier() default: throw TextFormatDecodingError.malformedText } } /// Parse a field name, look it up, and return the corresponding /// field number. /// /// returns nil at end-of-input /// /// Throws if field name cannot be parsed or if field name is /// unknown. /// /// This function accounts for as much as 2/3 of the total run /// time of the entire parse. internal mutating func nextFieldNumber(names: _NameMap) throws -> Int? { if p == end { return nil } let c = p[0] switch c { case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ: // a...z, A...Z let key = parseUTF8Identifier() if let fieldNumber = names.number(forProtoName: key) { return fieldNumber } else { throw TextFormatDecodingError.unknownField } case asciiOne...asciiNine: // 1-9 (field numbers are 123, not 0123) var fieldNum = Int(c) - Int(asciiZero) p += 1 while p != end { let c = p[0] if c >= asciiZero && c <= asciiNine { fieldNum = fieldNum &* 10 &+ (Int(c) - Int(asciiZero)) } else { break } p += 1 } skipWhitespace() if names.names(for: fieldNum) != nil { return fieldNum } else { // It was a number that isn't a known field. // The C++ version (TextFormat::Parser::ParserImpl::ConsumeField()), // supports an option to file or skip the field's value (this is true // of unknown names or numbers). throw TextFormatDecodingError.unknownField } default: break } throw TextFormatDecodingError.malformedText } private mutating func skipRequiredCharacter(_ c: UInt8) throws { skipWhitespace() if p != end && p[0] == c { p += 1 skipWhitespace() } else { throw TextFormatDecodingError.malformedText } } internal mutating func skipRequiredComma() throws { try skipRequiredCharacter(asciiComma) } internal mutating func skipRequiredColon() throws { try skipRequiredCharacter(asciiColon) } private mutating func skipOptionalCharacter(_ c: UInt8) -> Bool { if p != end && p[0] == c { p += 1 skipWhitespace() return true } return false } internal mutating func skipOptionalColon() -> Bool { return skipOptionalCharacter(asciiColon) } internal mutating func skipOptionalEndArray() -> Bool { return skipOptionalCharacter(asciiCloseSquareBracket) } internal mutating func skipOptionalBeginArray() -> Bool { return skipOptionalCharacter(asciiOpenSquareBracket) } internal mutating func skipOptionalObjectEnd(_ c: UInt8) -> Bool { return skipOptionalCharacter(c) } internal mutating func skipOptionalSeparator() { if p != end { let c = p[0] if c == asciiComma || c == asciiSemicolon { // comma or semicolon p += 1 skipWhitespace() } } } /// Returns the character that should end this field. /// E.g., if object starts with "{", returns "}" internal mutating func skipObjectStart() throws -> UInt8 { if p != end { let c = p[0] p += 1 skipWhitespace() switch c { case asciiOpenCurlyBracket: // { return asciiCloseCurlyBracket // } case asciiOpenAngleBracket: // < return asciiCloseAngleBracket // > default: break } } throw TextFormatDecodingError.malformedText } }
gpl-3.0
3ba46dd27a48f00b59df78985b376b98
32.299351
118
0.501614
5.195951
false
false
false
false
malcommac/SwiftMsgPack
Sources/SwiftMsgPack/Commons.swift
2
7349
/* * SwiftMsgPack * Lightweight MsgPack for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * 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 /// Error MsgPack encoder/decoder may generate during the elaboration of the data /// /// - invalidEncoding: invalid encoding. string cannot be encoded correctly in UTF-8 /// - unexpectedData: missing data /// - dataIsTooBig: data is too large to be contained in a MsgPack data (see https://github.com/msgpack/msgpack/blob/master/spec.md#types-limitation) /// - unsupportedValue: unsupported value public enum MsgPackError: Error { case invalidEncoding case unexpectedData case dataIsTooBig(_: String) case unsupportedValue(_: Any) } // This enum defines the prefix header bytes to write // according to the MsgPack specs // https://github.com/msgpack/msgpack/blob/master/spec.md#formats-bool public enum MsgPackType: CustomStringConvertible { // numeric vlues case uInt64 case int64 case uInt32 case int32 case uInt16 case int16 case uInt8 case pFixInt8(value: Int) case nFixInt(value: Int) case nInt8 case nInt16 case nInt32 case nInt64 case float case double case fixstr // string case str(length: Int) // binary data case bin8 case bin16 case bin32 // array case array(items: Int) case fixarray(items: Int) case array16 case array32 // dictionary case dict(items: Int) case fixdict(items: Int) case dict16 case dict32 // nil case `nil` // bool case boolean(_: Bool) /// The `UInt8` which represent the type of data public func value() throws -> UInt8 { switch self { // numeric values case .uInt64: return UInt8(0xcf) // uint 64 11001111 0xcf case .int64: return UInt8(0xd3) // int 64 11010011 0xd3 case .uInt32: return UInt8(0xce) // uint 32 11001110 0xce case .int32: return UInt8(0xd2) // int 32 11010010 0xd2 case .uInt16: return UInt8(0xcd) // uint 16 11001101 0xcd case .int16: return UInt8(0xd1) // int 16 11010001 0xd1 case .uInt8: return UInt8(0xcc) // uint 8 11001100 0xcc case .pFixInt8(let value): return UInt8(value & 0x7f) // positive fixint 0xxxxxxx 0x00 - 0x7f case .nFixInt(let value): return UInt8(value & 0xff) // negative fixint 111xxxxx 0xe0 - 0xff case .nInt8: return UInt8(0xd0) // int 8 11010000 0xd0 case .nInt16: return UInt8(0xd1) // int 16 11010001 0xd1 case .nInt32: return UInt8(0xd2) // int 32 11010010 0xd2 case .nInt64: return UInt8(0xd3) // int 64 11010011 0xd3 case .float: return UInt8(0xca) // float 32 11001010 0xca case .double: return UInt8(0xcb) // float 64 11001011 // binary data case .bin8: return UInt8(0xc4) // bin 8 11000100 0xc4 case .bin16: return UInt8(0xc5) // bin 16 11000101 0xc5 case .bin32: return UInt8(0xc6) // bin 32 11000110 0xc6 // array case .fixarray(let count): return UInt8(0x90 + count) // fixarray 1001xxxx 0x90 - 0x9f case .array16: return UInt8(0xdc) // array 16 11011100 0xdc case .array32: return UInt8(0xdd) // array 32 11011101 0xdd case .array(let count): if count < 16 { // less than 16 bit length return try MsgPackType.fixarray(items: count).value() } else if count < Int(UInt16.max) { // 16 bit length return try MsgPackType.array16.value() } else { //if count < Int(UInt32.max) { // 32 bit length return try MsgPackType.array32.value() } //throw MsgPackError.dataIsTooBig("Array is too big: \(count) items") // string case .fixstr: return UInt8(0xa0) // fixstr 101xxxxx 0xa0 - 0xbf case .str(let length): if length < 32 { // 0xa0 + length of the string return UInt8(try MsgPackType.fixstr.value() + UInt8(length)) } else if length < Int(UInt8.max) { // str 8 11011001 0xd9 return UInt8(0xd9) } else if length < Int(UInt16.max) { // str 16 11011010 0xda return UInt8(0xda) } else { //if length < Int(UInt32.max) { // str 32 11011011 0xdb return UInt8(0xdb) } //throw MsgPackError.dataIsTooBig("String is too long: \(length) chars") // dictionaries case .fixdict(let count): return UInt8(0x80 + count) // fixmap 1000xxxx 0x80 - 0x8f case .dict16: return UInt8(0xde) // map 16 11011110 0xde case .dict32: return UInt8(0xdf) // map 32 11011111 0xdf case .dict(let count): if count < 16 { // less than 16 bit return try MsgPackType.fixdict(items: count).value() } else if count < Int(UInt16.max) { // 16 bit return try MsgPackType.dict16.value() } else { //if count < Int(UInt32.max) { // 32 bit return try MsgPackType.dict32.value() } //throw MsgPackError.dataIsTooBig("Dictionary is too big: \(count) keys") // nil values case .nil: return UInt8(0xc0) // boolean values case .boolean(let v): return UInt8(v ? 0xc3 : 0xc2) } } /// String representation public var description: String { switch self { case .uInt64: return "uInt64" case .int64: return "int64" case .uInt32: return "uInt32" case .int32: return "int32" case .uInt16: return "uInt16" case .int16: return "int16" case .uInt8: return "uInt8" case .pFixInt8(let value): return "pFixInt8 (val= \(value))" case .nFixInt(let value): return "pFixInt8 (val= \(value))" case .nInt8: return "nInt8" case .nInt16: return "nInt16" case .nInt32: return "nInt32" case .nInt64: return "nInt64" case .float: return "float" case .double: return "double" case .fixstr: return "fixstr" case .str(let len): return "str (len= \(len))" case .bin8: return "bin8" case .bin16: return "bin16" case .bin32: return "bin32" case .array(let count): return "array (count= \(count))" case .fixarray(let count): return "fixarray (count= \(count))" case .array16: return "array16" case .array32: return "array32" case .dict(let count): return "dict (keys= \(count))" case .fixdict(let count): return "fixdict (keys= \(count))" case .dict16: return "dict16" case .dict32: return "dict32" case .`nil`: return "nil" case .boolean(let val): return "bool (is true=\(val))" } } }
mit
5b3657e18b79faf375d404a2f478049c
33.336449
149
0.680321
2.966492
false
false
false
false
sonsongithub/numsw
Sources/numsw/NDArray/NDArray.swift
1
475
public struct NDArray<T> { private var _shape: [Int] public var shape: [Int] { get { return _shape } set { self = reshaped(newValue) } } public internal(set) var elements: [T] public init(shape: [Int], elements: [T]) { precondition(shape.reduce(1, *) == elements.count, "Shape and elements are not compatible.") self._shape = shape self.elements = elements } }
mit
91b4b8e560bf8a1405b590a7baf46bbc
24
100
0.528421
4.130435
false
false
false
false
shanyazhou/XMG_DouYuTV
DouYuTV/DouYuTV/Classes/Home/Controller/HomeViewController.swift
1
1231
// // HomeViewController.swift // DouYuTV // // Created by shanyazhou on 2017/4/25. // Copyright © 2017年 SYZ. All rights reserved. // import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //设置UI界面 setupUI() } } // MARK: - 设置UI界面 extension HomeViewController { fileprivate func setupUI() { //1.设置导航栏 setupNavigationBar() } //设置导航栏 private func setupNavigationBar() { //1.设置左侧的item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") //2.设置右侧的item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "Image_my_history", highImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_click", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem] } }
mit
fa8e47098f809705641001a4531aeb26
23.93617
125
0.627986
4.669323
false
false
false
false
PlutoMa/SwiftProjects
021.CoreDataApp/CoreDataApp/CoreDataApp/ViewController.swift
1
3528
// // ViewController.swift // CoreDataApp // // Created by Dareway on 2017/11/3. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { let tableView = UITableView(frame: CGRect.zero, style: .plain) let entityName = "TodoList" var dataSource = [TodoList]() override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Todo List" let rightBarItem = UIBarButtonItem(title: "+", style: .plain, target: self, action: #selector(rightBarItemAction)) navigationItem.rightBarButtonItem = rightBarItem tableView.frame = view.bounds tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "reuseCell") view.addSubview(tableView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateDataSource() tableView.reloadData() } @objc func rightBarItemAction() -> Void { let alert = UIAlertController(title: "Add New Todo Item", message: "", preferredStyle: .alert) let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in if let field = alert.textFields?[0] { self.saveContent(content: field.text!) self.updateDataSource() self.tableView.reloadData() } } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addTextField { (textField) in textField.placeholder = "Please input the todo Item" } alert.addAction(confirmAction) alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) } func updateDataSource() -> Void { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) do { let searchResults = try getContext().fetch(fetchRequest) dataSource = searchResults as! [TodoList] } catch { print(error) } } } // MARK: - UITableViewDelegate & UITableViewDataSource extension ViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath) let content = dataSource[indexPath.row].content cell.textLabel?.text = content return cell } } // MARK: - CoreData extension ViewController { func getContext() -> NSManagedObjectContext { let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.persistentContainer.viewContext } func saveContent(content: String) -> Void { let context = getContext() let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) let todoList = NSManagedObject(entity: entity!, insertInto: context) todoList.setValue(content, forKey: "content") do { try context.save() } catch { print(error) } } }
mit
1526decac7b4fce40bfc8af16ab940e4
31.638889
122
0.639149
5.199115
false
false
false
false
colemancda/Pedido
CorePedidoClient/CorePedidoClient/AuthenticationManager.swift
1
1540
// // AuthenticationManager.swift // CorePedidoClient // // Created by Alsey Coleman Miller on 12/6/14. // Copyright (c) 2014 ColemanCDA. All rights reserved. // import Foundation public class AuthenticationManager: StoreDelegate { // MARK: - Private Properties private let accessOperationQueue: NSOperationQueue = { let operationQueue = NSOperationQueue() operationQueue.name = "AuthenticationManager Private Variables Access Operation Queue" operationQueue.maxConcurrentOperationCount = 1 return operationQueue }() private var token: String? private var username: String? private var password: String? // MARK: - Initialization public init() { } // MARK: - StoreDelegate public func tokenForStore(store: Store) -> String? { var token: String? self.accessOperationQueue.addOperations([NSBlockOperation(block: { () -> Void in token = self.token })], waitUntilFinished: true) return token } public func store(store: Store, didLoginWithUsername username: String, password: String, token: String) { self.accessOperationQueue.addOperationWithBlock { () -> Void in self.token = token self.username = username self.password = password } } }
mit
6878500cf14a146b52947ab648bdee2c
21.985075
109
0.572078
5.877863
false
false
false
false
typelift/Basis
Basis/Function.swift
2
3691
// // Function.swift // Basis // // Created by Robert Widmann on 9/7/14. // Copyright (c) 2014 TypeLift. All rights reserved. // Released under the MIT license. // /// The type of a function from T -> U. public struct Function<T, U> { typealias A = T typealias B = U typealias C = Any let ap : T -> U public init(_ apply : T -> U) { self.ap = apply } public func apply(x : T) -> U { return self.ap(x) } } extension Function : Category { typealias CAA = Function<A, A> typealias CBC = Function<B, C> typealias CAC = Function<A, C> public static func id() -> Function<T, T> { return Function<T, T>({ $0 }) } } public func • <A, B, C>(c : Function<B, C>, c2 : Function<A, B>) -> Function<A, C> { return ^{ c.apply(c2.apply($0)) } } public func <<< <A, B, C>(c1 : Function<B, C>, c2 : Function<A, B>) -> Function<A, C> { return c1 • c2 } public func >>> <A, B, C>(c1 : Function<A, B>, c2 : Function<B, C>) -> Function<A, C> { return c2 • c1 } extension Function : Arrow { typealias D = T typealias E = Swift.Any typealias FIRST = Function<(A, D), (B, D)> typealias SECOND = Function<(D, A), (D, B)> typealias ADE = Function<D, E> typealias SPLIT = Function<(A, D), (B, E)> typealias ABD = Function<A, D> typealias FANOUT = Function<A, (B, D)> public static func arr(f : T -> U) -> Function<A, B> { return Function<A, B>(f) } public func first() -> Function<(T, T), (U, T)> { return self *** Function.id() } public func second() -> Function<(T, T), (T, U)> { return Function.id() *** self } } public func *** <B, C, D, E>(f : Function<B, C>, g : Function<D, E>) -> Function<(B, D), (C, E)> { return ^{ (x, y) in (f.apply(x), g.apply(y)) } } public func &&& <A, B, C>(f : Function<A, B>, g : Function<A, C>) -> Function<A, (B, C)> { return ^{ b in (b, b) } >>> f *** g } extension Function : ArrowChoice { typealias LEFT = Function<Either<A, D>, Either<B, D>> typealias RIGHT = Function<Either<D, A>, Either<D, B>> typealias SPLAT = Function<Either<A, D>, Either<B, E>> typealias ACD = Function<B, D> typealias FANIN = Function<Either<A, B>, D> public static func left(f : Function<A, B>) -> Function<Either<A, D>, Either<B, D>> { return f +++ Function.id() } public static func right(f : Function<A, B>) -> Function<Either<D, A>, Either<D, B>> { return Function.id() +++ f } } public func +++ <B, C, D, E>(f : Function<B, C>, g : Function<D, E>) -> Function<Either<B, D>, Either<C, E>> { return ^Either.left • f ||| ^Either.right • g } public func ||| <B, C, D>(f : Function<B, D>, g : Function<C, D>) -> Function<Either<B, C>, D> { return ^either(f^)(g^) } extension Function : ArrowApply { typealias APP = Function<(Function<A, B>, A), B> public static func app() -> Function<(Function<T, U>, A), B> { return Function<(Function<T, U>, A), B>({ (f, x) in f.apply(x) }) } public static func leftApp<C>(f : Function<A, B>) -> Function<Either<A, C>, Either<B, C>> { let l : Function<A, (Function<Void, Either<B, C>>, Void)> = ^{ (let a : A) -> (Function<Void, Either<B, C>>, Void) in (Function<Void, A>.arr({ _ in a }) >>> f >>> Function<B, Either<B, C>>.arr(Either.left), Void()) } let r : Function<C, (Function<Void, Either<B, C>>, Void)> = ^{ (let c : C) -> (Function<Void, Either<B, C>>, Void) in (Function<Void, C>.arr({ _ in c }) >>> Function<C, Either<B, C>>.arr(Either.right), Void()) } return (l ||| r) >>> Function<Void, Either<B, C>>.app() } } extension Function : ArrowLoop { typealias LOOP = Function<(A, D), (B, D)> public static func loop<B, C>(f : Function<(B, D), (C, D)>) -> Function<B, C> { return ^({ k in Function.loop(f).apply(k) }) } }
mit
3cfa32c9f91ea425b96c3da00ae05c8f
27.315385
218
0.580277
2.66546
false
false
false
false
webim/webim-client-sdk-ios
Example/Localizer/ShellWrapper.swift
1
1281
// // ShellWrapper.swift // localizer2 // // Created by EVGENII Loshchenko on 22.03.2021. // import Cocoa import Foundation class ShellWrapper: NSObject { static let tempStringsFileName = "temp_strings_file.strings" static func shell(_ args: [String]) { let task = Process() task.launchPath = "/usr/bin/env" task.arguments = args task.launch() task.waitUntilExit() } static func readUTF8File(_ filePath: String) -> String { var text = "" do { text = try String(contentsOfFile: filePath, encoding: .utf8) } catch { print("readUTF8File error \(filePath)") } return text } static func readUTF16File(_ filePath: String) -> String { var text = "" do { text = try String(contentsOfFile: filePath, encoding: .utf16) } catch { print("readUTF16File error \(filePath)") } return text } static func generateStringsFileForXib(_ filePath: String) -> String { var text = "" shell(["ibtool", filePath, "--generate-strings-file", tempStringsFileName]) text = readUTF16File(tempStringsFileName) shell(["rm", tempStringsFileName]) return text } }
mit
a3a72acbbd89314068c088f515783ec1
25.6875
83
0.586261
4.313131
false
false
false
false
vrasneur/RandomBag
RandomBagTests/TestUtils.swift
1
849
// // TestUtils.swift // Random // // Created by Vincent on 28/09/2015. // Copyright © 2015 Mirandolabs. All rights reserved. // import Foundation class StringBitSequence: SequenceType { let bits: String init(bits: String) { self.bits = bits } func generate() -> AnyGenerator<Bit> { var idx: String.Index = self.bits.startIndex return anyGenerator { var bit: Bit? while (idx != self.bits.endIndex) && (bit == nil) { switch self.bits[idx] { case "0": bit = Bit.Zero case "1": bit = Bit.One default: bit = nil } idx = idx.advancedBy(1) } return bit } } }
gpl-3.0
255a8f58189caa1e5614ed15ef38377c
20.225
63
0.448113
4.510638
false
false
false
false
mcudich/TemplateKit
Source/Core/Properties/GestureProperties.swift
1
797
// // GestureProperties.swift // TemplateKit // // Created by Matias Cudich on 10/5/16. // Copyright © 2016 Matias Cudich. All rights reserved. // import Foundation public struct GestureProperties: RawProperties, Model, Equatable { var onTap: Selector? var onPress: Selector? var onDoubleTap: Selector? public init() {} public init(_ properties: [String : Any]) { onTap = properties.cast("onTap") onPress = properties.cast("onPress") onDoubleTap = properties.cast("onDoubleTap") } public mutating func merge(_ other: GestureProperties) { merge(&onTap, other.onTap) merge(&onPress, other.onPress) merge(&onDoubleTap, other.onDoubleTap) } } public func ==(lhs: GestureProperties, rhs: GestureProperties) -> Bool { return lhs.onTap == rhs.onTap }
mit
9f626bafcc4ad82721db0b00d8e7daca
23.121212
72
0.697236
3.921182
false
false
false
false
Mobilette/AniMee
Pods/p2.OAuth2/Sources/Base/OAuth2Error.swift
1
7369
// // OAuth2Error.swift // OAuth2 // // Created by Pascal Pfiffner on 16/11/15. // Copyright © 2015 Pascal Pfiffner. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /** All errors that might occur. The response errors return a description as defined in the spec: http://tools.ietf.org/html/rfc6749#section-4.1.2.1 */ public enum OAuth2Error: ErrorType, CustomStringConvertible, Equatable { case Generic(String) case NSError(Foundation.NSError) // Client errors case NoClientId case NoClientSecret case NoRedirectURL case NoUsername case NoPassword case NoAuthorizationContext case InvalidAuthorizationContext case InvalidRedirectURL(String) case NoRefreshToken case NoRegistrationURL // Request errors case NotUsingTLS case UnableToOpenAuthorizeURL case InvalidRequest case RequestCancelled case NoTokenType case UnsupportedTokenType(String) case NoDataInResponse case PrerequisiteFailed(String) case InvalidState case JSONParserError case UTF8EncodeError case UTF8DecodeError // OAuth2 errors case UnauthorizedClient case AccessDenied case UnsupportedResponseType case InvalidScope case ServerError case TemporarilyUnavailable case ResponseError(String) public static func fromResponseError(code: String, fallback: String? = nil) -> OAuth2Error { switch code { case "invalid_request": return .InvalidRequest case "unauthorized_client": return .UnauthorizedClient case "access_denied": return .AccessDenied case "unsupported_response_type": return .UnsupportedResponseType case "invalid_scope": return .InvalidScope case "server_error": return .ServerError case "temporarily_unavailable": return .TemporarilyUnavailable default: return .ResponseError(fallback ?? "Authorization error: \(code)") } } public var description: String { switch self { case .Generic(let message): return message case .NSError(let error): return error.localizedDescription case NoClientId: return "Client id not set" case NoClientSecret: return "Client secret not set" case NoRedirectURL: return "Redirect URL not set" case NoUsername: return "No username" case NoPassword: return "No password" case NoAuthorizationContext: return "No authorization context present" case InvalidAuthorizationContext: return "Invalid authorization context" case InvalidRedirectURL(let url): return "Invalid redirect URL: \(url)" case .NoRefreshToken: return "I don't have a refresh token, not trying to refresh" case .NoRegistrationURL: return "No registration URL defined" case .NotUsingTLS: return "You MUST use HTTPS/SSL/TLS" case .UnableToOpenAuthorizeURL: return "Cannot open authorize URL" case .InvalidRequest: return "The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed." case .RequestCancelled: return "The request has been cancelled" case NoTokenType: return "No token type received, will not use the token" case UnsupportedTokenType(let message): return message case NoDataInResponse: return "No data in the response" case PrerequisiteFailed(let message): return message case InvalidState: return "The state was either empty or did not check out" case JSONParserError: return "Error parsing JSON" case UTF8EncodeError: return "Failed to UTF-8 encode the given string" case UTF8DecodeError: return "Failed to decode given data as a UTF-8 string" case .UnauthorizedClient: return "The client is not authorized to request an access token using this method." case .AccessDenied: return "The resource owner or authorization server denied the request." case .UnsupportedResponseType: return "The authorization server does not support obtaining an access token using this method." case .InvalidScope: return "The requested scope is invalid, unknown, or malformed." case .ServerError: return "The authorization server encountered an unexpected condition that prevented it from fulfilling the request." case .TemporarilyUnavailable: return "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server." case .ResponseError(let message): return message } } } public func ==(lhs: OAuth2Error, rhs: OAuth2Error) -> Bool { switch (lhs, rhs) { case (.Generic(let lhm), .Generic(let rhm)): return lhm == rhm case (.NSError(let lhe), .NSError(let rhe)): return lhe.isEqual(rhe) case (.NoClientId, .NoClientId): return true case (.NoClientSecret, .NoClientSecret): return true case (.NoRedirectURL, .NoRedirectURL): return true case (.NoUsername, .NoUsername): return true case (.NoPassword, .NoPassword): return true case (.NoAuthorizationContext, .NoAuthorizationContext): return true case (.InvalidAuthorizationContext, .InvalidAuthorizationContext): return true case (.InvalidRedirectURL(let lhu), .InvalidRedirectURL(let rhu)): return lhu == rhu case (.NoRefreshToken, .NoRefreshToken): return true case (.NotUsingTLS, .NotUsingTLS): return true case (.UnableToOpenAuthorizeURL, .UnableToOpenAuthorizeURL): return true case (.InvalidRequest, .InvalidRequest): return true case (.RequestCancelled, .RequestCancelled): return true case (.NoTokenType, .NoTokenType): return true case (.UnsupportedTokenType(let lhm), .UnsupportedTokenType(let rhm)): return lhm == rhm case (.NoDataInResponse, .NoDataInResponse): return true case (.PrerequisiteFailed(let lhm), .PrerequisiteFailed(let rhm)): return lhm == rhm case (.InvalidState, .InvalidState): return true case (.JSONParserError, .JSONParserError): return true case (.UTF8EncodeError, .UTF8EncodeError): return true case (.UTF8DecodeError, .UTF8DecodeError): return true case (.UnauthorizedClient, .UnauthorizedClient): return true case (.AccessDenied, .AccessDenied): return true case (.UnsupportedResponseType, .UnsupportedResponseType): return true case (.InvalidScope, .InvalidScope): return true case (.ServerError, .ServerError): return true case (.TemporarilyUnavailable, .TemporarilyUnavailable): return true case (.ResponseError(let lhm), .ResponseError(let rhm)): return lhm == rhm default: return false } }
mit
be9e29d09eb3b08c87771736c48046aa
35.656716
157
0.70874
4.367516
false
false
false
false
micchyboy1023/Today
Today iOS App/Today iOS App/IAPManager.swift
1
3587
// // IAPManager.swift // Today // // Created by UetaMasamichi on 9/11/16. // Copyright © 2016 Masamichi Ueta. All rights reserved. // import Foundation import StoreKit public typealias ProductIdentifier = String public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> () public typealias ProductPaymentHandler = (_ state: SKPaymentTransactionState, _ error: Error?) -> () public final class IAPManager : NSObject { fileprivate let productIdentifiers: Set<ProductIdentifier> fileprivate var purchasedProductIdentifiers = Set<ProductIdentifier>() fileprivate var productsRequest: SKProductsRequest? fileprivate var productsRequestCompletionHandler: ProductsRequestCompletionHandler? fileprivate var productPaymentHandler: ProductPaymentHandler? static let IAPHelperPurchaseNotification = "IAPHelperPurchaseNotification" public init(productIds: Set<ProductIdentifier>) { self.productIdentifiers = productIds super.init() SKPaymentQueue.default().add(self) } } // MARK: - StoreKit API extension IAPManager { public func requestProducts(completionHandler: ProductsRequestCompletionHandler?) { productsRequest?.cancel() productsRequestCompletionHandler = completionHandler productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers) productsRequest!.delegate = self productsRequest!.start() } public func buyProduct(_ product: SKProduct, productPaymentHandler: ProductPaymentHandler?) { print("Buying \(product.productIdentifier)...") let payment = SKPayment(product: product) self.productPaymentHandler = productPaymentHandler SKPaymentQueue.default().add(payment) } public class func canMakePayments() -> Bool { return SKPaymentQueue.canMakePayments() } } extension IAPManager: SKProductsRequestDelegate { public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { print("load list of products") let products = response.products productsRequestCompletionHandler?(true, products) clearRequestAndHandler() for p in products { print("Found product: \(p.productIdentifier) \(p.localizedTitle) \(p.price.floatValue)") } } public func request(_ request: SKRequest, didFailWithError error: Error) { productsRequestCompletionHandler!(false, nil) clearRequestAndHandler() } fileprivate func clearRequestAndHandler() { productsRequest = nil productsRequestCompletionHandler = nil } } extension IAPManager: SKPaymentTransactionObserver { public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions { switch transaction.transactionState { case .purchased: self.productPaymentHandler?(.purchased, nil) SKPaymentQueue.default().finishTransaction(transaction) case .purchasing: self.productPaymentHandler?(.purchasing, nil) break case .failed: self.productPaymentHandler?(.failed, transaction.error) SKPaymentQueue.default().finishTransaction(transaction) case .restored, .deferred: break } } } }
mit
132fa6f4c478e62a0859855665699618
31.899083
113
0.675404
5.986644
false
false
false
false
artsy/eigen
ios/Artsy/View_Controllers/Live_Auctions/LiveAuctionStaticDataFetcher+Stubs.swift
1
1692
import Interstellar import SwiftyJSON // swiftlint:disable force_unwrapping /// Used to stub data from a JSON file stored in the app bundle, in lieu of fetching data from the server. /// Userful for offline development, debugging, and testing. class Stubbed_StaticDataFetcher: LiveAuctionStaticDataFetcherType { var bidders: [Bidder] = [] var paddleNumber: String = "123456" var userID: String = "abcd" init() { if let bidder = try? Bidder(dictionary: ["qualifiedForBidding": true, "bidderID": "123456"], error: Void()) { bidders = [bidder] } } func fetchStaticData() -> Observable<StaticSaleResult> { let signal = Observable<StaticSaleResult>() let json = loadJSON("live_auctions_static") let sale = self.parseSale(JSON(json))! let bidderCredentials = BiddingCredentials(bidders: bidders, paddleNumber: paddleNumber, userID: userID) let stubbedJWT = JWT(jwtString: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhdWN0aW9ucyIsInJvbGUiOiJvYnNlcnZlciIsInVzZXJJZCI6bnVsbCwic2FsZUlkIjoiNTRjN2U4ZmE3MjYxNjkyYjVhY2QwNjAwIiwiYmlkZGVySWQiOm51bGwsImlhdCI6MTQ2NTIzNDI2NDI2N30.2q3bh1E897walHdSXIocGKElbxOhCGmCCsL8Bf-UWNA")! let s = (sale: sale, jwt: stubbedJWT, bidderCredentials: bidderCredentials) signal.update(Result.success(s)) return signal } } func loadJSON(_ filename: String) -> AnyObject { let jsonPath = Bundle.main.path(forResource: filename, ofType: "json") let jsonData = try! Data(contentsOf: URL(fileURLWithPath: jsonPath!)) let json = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) return json as AnyObject }
mit
cdf4dcdc8ca31b1a8ace8330cec5d83a
40.268293
288
0.729314
3.562105
false
false
false
false
mitchellallison/nifty
nifty/parser.swift
1
41721
// // parser.swift // nifty // // Created by Mitchell Allison on 04/11/2014. // Copyright (c) 2014 mitchellallison. All rights reserved. // import Foundation //MARK: Equatable protocol conformance public func ==(lhs: SwiftAST, rhs: SwiftAST) -> Bool { return false } public func ==(lhs: SwiftType, rhs: SwiftType) -> Bool { switch (lhs, rhs) { case let (l as SwiftTypeIdentifier, r as SwiftTypeIdentifier): return l.identifier == r.identifier case let (l as SwiftTupleType, r as SwiftTupleType): return l.types == r.types case let (l as SwiftFunctionType, r as SwiftFunctionType): return l.parameterType == r.parameterType && l.returnType == r.returnType default: return false } } public func ==(lhs: SwiftExpr, rhs: SwiftExpr) -> Bool { switch (lhs, rhs) { case let (l as SwiftSignedIntegerLiteral, r as SwiftSignedIntegerLiteral): return l.val == r.val case let (l as SwiftDoubleLiteral, r as SwiftDoubleLiteral): return l.val == r.val case let (l as SwiftIdentifierString, r as SwiftIdentifierString): return l.name == r.name case let (l as SwiftBinaryExpression, r as SwiftBinaryExpression): return l.op == r.op && l.lhs == r.lhs && l.rhs == r.rhs case let (l as SwiftBooleanLiteral, r as SwiftBooleanLiteral): return l.val == r.val default: return false } } public func ==(lhs: SwiftDeclaration, rhs: SwiftDeclaration) -> Bool { switch (lhs, rhs) { case let (l, r): return l.identifier == r.identifier && l.isConstant == r.isConstant && l.assignment == r.assignment && l.type == r.type default: return false } } //MARK: - //MARK: Types // Abstract class representing a node in a Swift Abstract Syntax Tree. public class SwiftAST : Equatable, Printable { var children: [SwiftAST] = [] /** Initialises a SwiftAST node. Designated initialiser for subclasses, should not be called otherwise. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftAST. **/ init(lineContext: LineContext?) { self.lineContext = lineContext } private var explicitLineContext: LineContext? var lineContext: LineContext? { get { return explicitLineContext ?? children.first?.lineContext } set (explicitLineContext) { self.explicitLineContext = explicitLineContext } } // Returns a description of all child nodes, indented appropriately. private var childDescriptions: String { // For every child, replace all instances of "\n" in their descriptions with "\n\t" to indent appropriately let indentedDescriptions = self.children.map({ return reduce(split($0.description, isSeparator: { $0 == "\n" }), "") { return $0 + "\n\t" + $1 } }) // Then, concatenate all the descriptions return reduce(indentedDescriptions, "", +) } public var description: String { return "SwiftAST" + self.childDescriptions } } // A Swift program/closure body node in the AST. public class SwiftBody: SwiftAST { override public var description: String { return "SwiftBody" + self.childDescriptions } } // A constant or variable declaration node in the AST. public class SwiftDeclaration: SwiftAST, Equatable { var identifier: String var isConstant: Bool var type: SwiftType? var assignment: SwiftExpr? { didSet { self.children.append(assignment!) } } /** Initialises a SwiftDeclaration node. :param: id The identifier of the binding. :param: type The optional type of the binding. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftDeclaration. **/ init(id: String, type: SwiftType?, lineContext: LineContext?) { identifier = id isConstant = true self.type = type super.init(lineContext: lineContext) if let type = type { self.children.append(type) } } /** Initialises a SwiftDeclaration node without a type. :param: id The identifier of the binding. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftDeclaration. **/ convenience init(id: String, lineContext: LineContext?) { self.init(id: id, type: nil, lineContext: lineContext) } override public var description: String { return "SwiftDeclaration: - identifier:\(identifier), isConstant:\(isConstant)" + self.childDescriptions } } public class SwiftFunctionParameter: SwiftDeclaration { } // The prototype for a function, consisting of its parameters, their types and the return type. public class SwiftFunctionPrototype: SwiftDeclaration { var parameters: [SwiftDeclaration] /** Initialises a SwiftFunctionPrototype. :param: id The identifier of the function prototype. :param: parameters An array of SwiftDeclaration nodes, corresponding to the parameters of a function. :param: returnType The return type of the function. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftFunctionPrototype. **/ init(id: String, parameters: [SwiftDeclaration], returnType: SwiftType, lineContext: LineContext?) { self.parameters = parameters super.init(id: id, type: returnType, lineContext: lineContext) } } // The body of a function. public class SwiftFunctionBody: SwiftBody { /** Initialises a SwiftFunctionPrototype. :param: _ A SwiftBody representing the body of a function. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftFunctionPrototype. **/ init(_ body: SwiftBody, lineContext: LineContext?) { super.init(lineContext: lineContext) self.children = body.children self.lineContext = body.lineContext } } // The declaration of a function, consisting of its prototype and body. public class SwiftFunctionDeclaration: SwiftAST { var prototype: SwiftFunctionPrototype var body: SwiftFunctionBody? /** Initialises a SwiftFunctionDeclaration. :param: id The identifier of the function. :param: parameters An array of SwiftDeclaration nodes, corresponding to the parameters of a function. :param: returnType The return type of the function. :param: body A SwiftBody representing the body of a function. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftFunctionPrototype. **/ init(id: String, parameters: [SwiftDeclaration], returnType: SwiftType, body: SwiftFunctionBody?, lineContext: LineContext?) { self.prototype = SwiftFunctionPrototype(id: id, parameters: parameters, returnType: returnType, lineContext: lineContext) self.body = body super.init(lineContext: lineContext) self.children.append(self.prototype) if let body = self.body { self.children.append(body) } } } // A function call public class SwiftCall: SwiftExpr { let identifier: SwiftIdentifierString /** Initialises a SwiftCall node. :param: id The function identifier. :param: arguments An array of SwiftExpr nodes, corresponding to the arguments of the function. **/ init(identifier: SwiftIdentifierString, arguments: [SwiftExpr]) { self.identifier = identifier super.init(lineContext: nil) let args = arguments as [SwiftAST] self.children.extend(args) } } // An assignment to a constant or variable. public class SwiftAssignment: SwiftAST { var storage: SwiftExpr var expression: SwiftExpr init(storage: SwiftExpr, expression: SwiftExpr) { self.storage = storage self.expression = expression super.init(lineContext: nil) self.children = [self.storage, self.expression] } } public class SwiftConditionalStatement: SwiftAST { let cond: SwiftExpr let body: SwiftBody init(condition: SwiftExpr, body: SwiftBody, lineContext: LineContext?) { self.cond = condition self.body = body super.init(lineContext: lineContext) self.lineContext = lineContext } } // A while statement. public class SwiftWhileStatement: SwiftConditionalStatement {} // An if statement. public class SwiftIfStatement: SwiftConditionalStatement {} //MARK: SwiftExpr // An abstract class representing a Swift expression in the AST. public class SwiftExpr: SwiftAST, Equatable { let isAssignable: Bool /** Initialises a SwiftExpr node. Designated initialiser for subclasses, should not be called otherwise. :param: assignable Boolean value representing if the expression can be assigned to (i.e, identifiers, tuples). :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftExpr. **/ init(assignable: Bool = false, lineContext: LineContext?) { self.isAssignable = assignable super.init(lineContext: lineContext) } } // An 'Int' node in the AST. public class SwiftSignedIntegerLiteral: SwiftExpr { let val: Int /** Initialises a SwiftSignedIntegerLiteral node. :param: val The value represented by the integer literal. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftSignedIntegerLiteral. **/ init(val: Int, lineContext: LineContext?) { self.val = val super.init(lineContext: lineContext) } override public var description: String { return "SwiftSignedIntegerLiteral - val:\(val)" } } // A 'Double' node in the AST. public class SwiftDoubleLiteral: SwiftExpr { let val: Double /** Initialises a SwiftDoubleLiteral node. :param: val The value represented by the double literal. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftSignedDoubleLiteral. **/ init(val: Double, lineContext: LineContext?) { self.val = val super.init(lineContext: lineContext) } override public var description: String { return "SwiftSignedDoubleLiteral - val:\(val)" } } // A boolean literal node in the AST. public class SwiftBooleanLiteral: SwiftExpr { let val: Bool init(val: Bool, lineContext: LineContext?) { self.val = val super.init(assignable: false, lineContext: lineContext) } } // An identifier expression node in the AST. public class SwiftIdentifierString: SwiftExpr { var name: String /** Initialises a SwiftIdentifierString node. :param: id The identifier string. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftIdentifierString. **/ init(name: String, lineContext: LineContext?) { self.name = name super.init(assignable: true, lineContext: lineContext) } } // A binary expression node in the AST. public class SwiftBinaryExpression: SwiftExpr { let op: String let lhs: SwiftExpr let rhs: SwiftExpr /** Initialises a SwiftBinaryExpression node. :param: op The binary operator. :param: lhs The left hand side of the binary expression. :param: rhs The left hand side of the binary expression. :returns: An initialised SwiftBinaryExpression node **/ init(op: String, lhs: SwiftExpr, rhs:SwiftExpr) { self.op = op self.lhs = lhs self.rhs = rhs super.init(assignable: false, lineContext: nil) switch lhs { case let l as SwiftBinaryExpression: self.children.extend(l.children) default: self.children.append(lhs) } switch rhs { case let r as SwiftBinaryExpression: self.children.extend(r.children) default: self.children.append(rhs) } } } public class SwiftPostfixExpression: SwiftExpr { let expr: SwiftExpr let op: String init(op: String, expr: SwiftExpr, lineContext: LineContext?) { self.op = op self.expr = expr super.init(assignable: false, lineContext: lineContext) self.lineContext = lineContext } } public class SwiftPrefixExpression: SwiftExpr { let expr: SwiftExpr let op: String init(op: String, expr: SwiftExpr, lineContext: LineContext?) { self.op = op self.expr = expr super.init(assignable: false, lineContext: lineContext) self.lineContext = lineContext } } //MARK: SwiftType // An abstract class representing a type in the AST. public class SwiftType: SwiftAST, Equatable {} // A type identifier node in the AST. public class SwiftTypeIdentifier: SwiftType { var identifier: String /** Initialises a SwiftTypeIdentifier node. :param: identifier The type identifier string. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftTypeIdentifier. **/ init(identifier: String, lineContext: LineContext?) { self.identifier = identifier super.init(lineContext: lineContext) } /** Convinience initialiser to initialise a SwiftTypeIdentifier node without LineContext. :param: identifier The type identifier string. :returns: An initialised SwiftTypeIdentifier. **/ convenience init(identifier: String) { self.init(identifier: identifier, lineContext: nil) } override public var description: String { return self.identifier } } // A parameter list type, used for multiple return values and parameter lists in function types. public class SwiftTupleType: SwiftType { var types: [SwiftType] /** Initialises a SwiftTupleType node. :param: types A list of SwiftType objects. :param: lineContext An optional LineContext relating to the node. :returns: An initialised SwiftTupleType. **/ init (types: [SwiftType], lineContext: LineContext?) { self.types = types super.init(lineContext: lineContext) } override public var description: String { if types.count == 0 { return "Void" } var desc = "(" for (i, t) in enumerate(types) { desc += t.description if (i != types.count - 1) { desc += ", " } } desc += ")" return desc } } // A function type. public class SwiftFunctionType: SwiftType { var parameterType: SwiftType var returnType: SwiftType /** Initialises a SwiftFunctionType node. :param: parameterType The parameter type. :param: returnType The returnType type. :param: lineContext An LineContext relating to the node. :returns: An initialised SwiftFunctionType. **/ init(parameterType: SwiftType, returnType: SwiftType, lineContext: LineContext? = nil) { self.parameterType = parameterType self.returnType = returnType super.init(lineContext: lineContext) } override public var description: String { var description = "(" description += parameterType.description description += " -> " description += returnType.description description += ")" return description } } //MARK: - //MARK: Parser // A class used to parse a [SwiftToken], accompanied by [LineContext]. public class SwiftParser { var tokens: [SwiftToken] var lineContext: [LineContext] lazy public private(set) var errors = [SCError]() var binaryOperatorPrecedence: Dictionary<String, Int> = [ "<<": 160, ">>": 160, "*": 150, "/": 150, "%": 150, "&*": 150, "&/": 150, "&%": 150, "&": 150, "+": 140, "-": 140, "&+": 140, "&-": 140, "|": 140, "^": 140, "..": 135, "...": 135, "is": 132, "as": 132, "<": 130, "<=": 130, ">": 130, ">=": 130, "==": 130, "!=": 130, "===": 130, "!==": 130, "~=": 130, "&&": 120, "||": 110, "?": 100, "=": 90, "*=": 90, "/=": 90, "%=": 90, "+=": 90, "-=": 90, "<<=": 90, ">>=": 90, "&=": 90, "^=": 90, "|=": 90, "&&=": 90, "||=": 90, ] /** Gets the operator precedence for a specified operator. :param: op An operator. :returns: The precedence of the operator. Nil if the operator does not exist. **/ func getOperatorPrecedence(op: String) -> Int { if let precedence = binaryOperatorPrecedence[op] { return precedence } else { return -1 } } /** Initialises a SwiftParser. :param: tokens An array of SwiftToken values to parse. :param: lineContext An array of LineContext values corresponding to the tokens. :returns: An initialised SwiftIdentifierString. **/ init(tokens: [SwiftToken], lineContext: [LineContext] = []) { self.tokens = tokens self.lineContext = lineContext } /** Generates an AST from the tokens and lineContext provided. :returns: A SwiftBody if no errors occured, nil otherwise. **/ func generateAST() -> SwiftBody? { return parseBody() } // Removes the first value from tokens and lineContext respectively. private func consumeToken() { tokens.removeAtIndex(0) lineContext.removeAtIndex(0) } /** Parses a program or closure body. :param: bracesRequired If true, will validate presence of braces, otherwise will not. :returns: A SwiftBody if no errors occured, nil otherwise. **/ private func parseBody(bracesRequired: Bool = false) -> SwiftBody? { if bracesRequired { switch tokens[0] { case .LeftBrace: consumeToken() default: errors.append(SCError(message: "Missing expected brace.", lineContext: self.lineContext[0])) return nil } } var body = SwiftBody(lineContext: self.lineContext[0]) while !tokens.isEmpty { // If braces are required, check for them and return if encountered if bracesRequired { switch tokens[0] { case .RightBrace: consumeToken() return body default: break } } // Otherwise, parse statement as normal, adding the statement as a child of the body if let statement = parseStatement() { body.children.append(statement) } else if errors.count > 0 { return nil } } return body } /** Parses a statement :returns: A SwiftAST subclass if no errors occured, nil otherwise. **/ private func parseStatement() -> SwiftAST? { switch tokens[0] { case .VariableDeclaration: fallthrough case .ConstantDeclaration: return parseDeclarationStatement() case .IntegerLiteral(_): fallthrough case .DoubleLiteral(_): fallthrough case .LeftBracket: fallthrough case .Identifier(_): if let lhs = parsePrimary() { if tokens.count == 0 { return lhs } switch tokens[0] { case .InfixOperator("=") where lhs.isAssignable: return parseAssignment(lhs) default: return parseOperationRHS(precedence: 0, lhs: lhs) } } else { return nil } case .While: fallthrough case .If: return parseConditionalStatement() case .Function: return parseFunctionDeclaration() case .SemiColon: fallthrough case .NewLine: consumeToken() return nil default: errors.append(SCError(message: "Unexpected token \(tokens[0]) encountered.", lineContext: lineContext[0])) return nil } } /** Parses the right hand side of a binary expression. :param: precedence The current precedence to consider when parsing. :param: lhs The current left hand side of the expression being parsed. :returns: An optional SwiftExpr. **/ func parseOperationRHS(#precedence: Int, var lhs: SwiftExpr) -> SwiftExpr? { // If there are no more tokens, return the lhs if tokens.count == 0 { return lhs } // Otherwise, switch on the first token switch tokens[0] { case .InfixOperator(let op): let tokenPrecedence = getOperatorPrecedence(op) // If the token we have encountered does not bind as tightly as the current precedence, return the current expression if tokenPrecedence < precedence { return lhs } // Get next operand consumeToken() // Error handling if let rhs = parsePrimary() { // No further tokens if tokens.count == 0 { return SwiftBinaryExpression(op: op, lhs: lhs, rhs: rhs) } // Get next operator switch tokens[0] { case .InfixOperator(let nextOp): let nextTokenPrecedence = getOperatorPrecedence(nextOp) // The next token has higher precedence, parse from the rhs onwards. if tokenPrecedence < nextTokenPrecedence { if let newRhs = parseOperationRHS(precedence: tokenPrecedence, lhs: rhs) { return parseOperationRHS(precedence: precedence + 1, lhs: SwiftBinaryExpression(op: op, lhs: lhs, rhs: newRhs)) } else { return nil } } return parseOperationRHS(precedence: precedence + 1, lhs: SwiftBinaryExpression(op: op, lhs: lhs, rhs: rhs)) // Encountered a different token, return the intermediate result. default: return SwiftBinaryExpression(op: op, lhs: lhs, rhs: rhs) } } else { return nil } // Collapse the postfix operator and continue parsing case .PostfixOperator(let op): let context = self.lineContext[0] consumeToken() let newLHS = SwiftPostfixExpression(op: op, expr: lhs, lineContext: context) return parseOperationRHS(precedence: precedence, lhs: newLHS) // Collapse the prefix operator and continue parsing case .PrefixOperator(let op): let context = self.lineContext[0] consumeToken() let newLHS = SwiftPrefixExpression(op: op, expr: lhs, lineContext: context) return parseOperationRHS(precedence: precedence, lhs: newLHS) // Encountered a different token, return the lhs. default: return lhs } } /** Parses an assignment. :param: store The variable or constant where the assignment should be stored. :return: An optional SwiftAssignment node. **/ func parseAssignment(store: SwiftExpr) -> SwiftAssignment? { switch tokens[0] { case .InfixOperator("="): consumeToken() if let rhs = parseExpression() { return SwiftAssignment(storage: store, expression: rhs) } else { return nil } default: errors.append(SCError(message: "Missing expected '='.", lineContext: self.lineContext[0])) return nil } } /** Parses a while statement. :return: A SwiftWhileStatement if no errors occured, nil otherwise. **/ func parseConditionalStatement() -> SwiftConditionalStatement? { let context = self.lineContext[0] var token: SwiftToken switch tokens[0] { case .If: fallthrough case .While: token = tokens[0] consumeToken() default: errors.append(SCError(message: "Missing expected 'while'.", lineContext: self.lineContext[0])) return nil } if let cond = parseExpression(), let body = parseBody(bracesRequired: true) { switch token { case .While: return SwiftWhileStatement(condition: cond, body: body, lineContext: context) case .If: return SwiftIfStatement(condition: cond, body: body, lineContext: context) default: return nil } } // In the presence of an error, return nil return nil } /** Parses a declaration. :returns: A SwiftAST subclass if no errors occured, nil otherwise. **/ private func parseDeclarationStatement() -> SwiftAST? { var isConstant = true switch tokens[0] { case .ConstantDeclaration: consumeToken() case .VariableDeclaration: consumeToken() isConstant = false default: errors.append(SCError(message: "Missing expected 'let' or 'var'.", lineContext: self.lineContext[0])) return nil } if let declaration = parseStorageDeclaration() { declaration.isConstant = isConstant return declaration } return nil } /** Parses a pattern consisting of an assignment. :returns: A SwiftDeclaration if no errors occured, nil otherwise. **/ private func parseStorageDeclaration(isFunctionParameter: Bool = false) -> SwiftDeclaration? { var type: SwiftType? let context = self.lineContext[0] if let declarationIdentifier = parseIdentifierDeclaration() { let declarationNode = isFunctionParameter ? SwiftFunctionParameter(id: declarationIdentifier, lineContext: context) : SwiftDeclaration(id: declarationIdentifier, lineContext: context) if tokens.count > 0 { switch tokens[0] { case .Colon: consumeToken() type = parseType() if type == nil { errors.append(SCError(message: "Could not parse type.", lineContext: self.lineContext[0])) return nil } declarationNode.type = type default: break } } if tokens.count > 0 { // Check for optional assignment switch tokens[0] { case .InfixOperator("="): consumeToken() if let assignment = parseExpression() { declarationNode.assignment = assignment } else { return nil } default: break; } } return declarationNode } else { return nil } } /** Parses an identifier used in a declaration. :returns: A String if no errors occured, nil otherwise. **/ private func parseIdentifierDeclaration() -> String? { switch tokens[0] { case .Identifier(let string): consumeToken() return string default: errors.append(SCError(message: "Missing expected identifier.", lineContext: self.lineContext[0])) return nil } } //MARK: Type parsing /** Parses a type. :returns: A SwiftType if no errors occured, nil otherwise. **/ func parseType() -> SwiftType? { switch tokens[0] { case .Identifier(let t): let context = self.lineContext[0] consumeToken() return parseTypeRHS(lhs: SwiftTypeIdentifier(identifier: t, lineContext: context), isBracketed: false) case .Void: let context = self.lineContext[0] consumeToken() // Void is equivalent to the empty tuple (). return parseTypeRHS(lhs: SwiftTupleType(types: [], lineContext: context), isBracketed: false) case .LeftBracket: let typeContext = self.lineContext[0] consumeToken() let t = parseType() ?? SwiftTupleType(types: [], lineContext: typeContext) if let type = parseTypeRHS(lhs: t, isBracketed: true) { return parseTypeRHS(lhs: type) } else { return nil } default: return nil } } /** Parses the right hand side of a type. :param: lhs The left hand side of the type. :param: isBracketed Causes the type to be parsed differently if the left hand side includes a bracket. :returns: A SwiftType if no errors occured, nil otherwise. **/ func parseTypeRHS(#lhs: SwiftType, isBracketed bracketed: Bool = false) -> SwiftType? { if !tokens.isEmpty { switch tokens[0] { // Close a tuple. case .RightBracket where bracketed: consumeToken() return lhs // Parse the list of types in a TupleType. case .Comma where bracketed: if let type = parseTupleTypeRHS(lhs) { return parseTypeRHS(lhs: type, isBracketed: bracketed) } else { return nil } case .Returns: if let type = parseFunctionTypeRHS(parameterType: lhs, isBracketed: bracketed) { return parseTypeRHS(lhs: type) } else { return nil } default: if bracketed { errors.append(SCError(message: "Missing expected ')'.", lineContext: self.lineContext[0])) return nil } else { return lhs } } } return lhs } /** Parses the right hand side of a SwiftTupleType. :param: lhs The left hand side of the SwiftTupleType. :returns: A SwiftTupleType if no errors occured, nil otherwise. **/ func parseTupleTypeRHS(lhs: SwiftType) -> SwiftTupleType? { var types: [SwiftType] = [lhs] let typeContext = self.lineContext[0] while true { switch tokens[0] { case .Comma: consumeToken() case .RightBracket: return SwiftTupleType(types: types, lineContext: typeContext) default: if let type = parseType() { types.append(type) } else { return nil } } } } /** Parses the right hand side of a SwiftFunctionType. :param: parameterType The parameter type of the function. :param: isBracketed Causes the type to be parsed differently if the left hand side includes a bracket. :returns: A SwiftFunctionType if no errors occured, nil otherwise. **/ func parseFunctionTypeRHS(#parameterType: SwiftType, isBracketed bracketed: Bool = false) -> SwiftType? { var type: SwiftFunctionType! while true { if tokens.isEmpty { return type } switch tokens[0] { case .Returns: consumeToken() case .RightBracket: return type default: let lineContext = self.lineContext[0] if let t = parseType() { type = SwiftFunctionType(parameterType: parameterType, returnType: t, lineContext: lineContext) } else { return nil } } } } // MARK: Expression parsing /** Parses a Swift expression. :returns: A SwiftExpr if no errors occured, nil otherwise. **/ private func parseExpression() -> SwiftExpr? { if let primary = parsePrimary() { return parseOperationRHS(precedence: 0, lhs: primary) } else { return nil } } /** Parses the first part of a SwiftExpr. :returns: A SwiftExpr if no errors occured, nil otherwise. **/ private func parsePrimary() -> SwiftExpr? { let context = self.lineContext[0] switch tokens[0] { case .Identifier(let string): return parseIdentifierExpression() case .PrefixOperator(let op): consumeToken() if let expr = parsePrimary() { return SwiftPrefixExpression(op: op, expr: expr, lineContext: context) } else { return nil } case .IntegerLiteral(_): fallthrough case .DoubleLiteral(_): return parseNumberExpression() case .True: consumeToken() return SwiftBooleanLiteral(val: true, lineContext: context) case .False: consumeToken() return SwiftBooleanLiteral(val: false, lineContext: context) case .LeftBracket: return parseParenthesesExpression() default: errors.append(SCError(message: "\(tokens[0]) is not a Swift expression.", lineContext: self.lineContext[0])) return nil } } /** Parses an identifier within an expression. :returns: A SwiftExpr if no errors occured, nil otherwise. **/ private func parseIdentifierExpression() -> SwiftExpr? { // Get identifier let context = self.lineContext[0] var identifier: SwiftIdentifierString! switch tokens[0] { case .Identifier(let id): consumeToken() identifier = SwiftIdentifierString(name: id, lineContext: context) default: errors.append(SCError(message: "Missing expected identifier.", lineContext: self.lineContext[0])) return nil } // Check if it's a function call if tokens.count == 0 { return identifier } switch tokens[0] { case .LeftBracket: consumeToken() var args = [SwiftExpr]() while true { if tokens.count == 0 { errors.append(SCError(message: "Missing expected ')' in function argument list.", lineContext: self.lineContext[0])) return nil } switch tokens[0] { case .RightBracket: consumeToken() return SwiftCall(identifier: identifier, arguments: args) case .Comma: consumeToken() default: if let exp = parseExpression() { args.append(exp) } else { return nil } } } default: return identifier } } /** Parses a numerical literal. :returns: A SwiftExpr if no errors occured, nil otherwise. **/ private func parseNumberExpression() -> SwiftExpr? { let context = self.lineContext[0] switch tokens[0] { case .IntegerLiteral(let int): consumeToken() return SwiftSignedIntegerLiteral(val: int, lineContext: context) case .DoubleLiteral(let double): consumeToken() return SwiftDoubleLiteral(val: double, lineContext: context) default: errors.append(SCError(message: "Missing expected Int or Double literal.", lineContext: self.lineContext[0])) return nil } } /** Parses an expression enclosed in parentheses. :returns: A SwiftExpr if no errors occured, nil otherwise. **/ private func parseParenthesesExpression() -> SwiftExpr? { let context = self.lineContext[0] switch tokens[0] { case .LeftBracket: consumeToken() default: errors.append(SCError(message: "Missing expected '('.", lineContext: self.lineContext[0])) return nil } if let expr = parseExpression() { switch tokens[0] { case .RightBracket: consumeToken() return expr default: errors.append(SCError(message: "Missing expected ')'.", lineContext: self.lineContext[0])) return nil } } else { return nil } } /** Parses a function declaration. :returns: A SwiftFunctionDeclaration if no errors occured, nil otherwise **/ func parseFunctionDeclaration() -> SwiftFunctionDeclaration? { let context = self.lineContext[0] switch tokens[0] { case .Function: consumeToken() default: errors.append(SCError(message: "Missing expected 'func'.", lineContext: self.lineContext[0])) return nil } let functionIdentifier: String switch tokens[0] { case .Identifier(let string): functionIdentifier = string consumeToken() default: errors.append(SCError(message: "Missing expected function identifier.", lineContext: self.lineContext[0])) return nil } let functionParameters: [SwiftFunctionParameter] if let params = parseFunctionParameters() { functionParameters = params } else { return nil } let returnType: SwiftType let returnTypeContext = self.lineContext[0] switch tokens[0] { case .Returns: consumeToken() if let type = parseType() { returnType = type } else { return nil } default: // If not specified, function type is Void returnType = SwiftTypeIdentifier(identifier: "Void", lineContext: context) } var body: SwiftFunctionBody? if (tokens.isEmpty) { errors.append(SCError(message: "Function body not specified.", lineContext: returnTypeContext)) return nil } let bodyContext = self.lineContext[0] switch tokens[0] { case .LeftBrace: if let closure = parseBody(bracesRequired: true) { body = SwiftFunctionBody(closure, lineContext: bodyContext) fallthrough } else { return nil } default: return SwiftFunctionDeclaration(id: functionIdentifier, parameters: functionParameters, returnType: returnType, body: body, lineContext: context) } } func parseFunctionParameters() -> [SwiftFunctionParameter]? { switch tokens[0] { case .LeftBracket: consumeToken() default: errors.append(SCError(message: "Missing expected '('.", lineContext: self.lineContext[0])) return nil } func parseParams() -> [SwiftFunctionParameter]? { var functionParameters: [SwiftFunctionParameter] = [SwiftFunctionParameter]() while true { switch tokens[0] { case .RightBracket: return functionParameters case .Comma: consumeToken() default: if let arg = parseStorageDeclaration(isFunctionParameter: true) as? SwiftFunctionParameter { functionParameters.append(arg) } else { return nil } } } } if let params = parseParams() { switch tokens[0] { case .RightBracket: consumeToken() return params default: errors.append(SCError(message: "Missing expected ')'.", lineContext: self.lineContext[0])) return nil } } else { return nil } } }
mit
9c30fe78e97275002faf46e19c1072e3
30.299325
195
0.572254
5.276464
false
false
false
false
radazzouz/firefox-ios
Client/Frontend/Widgets/TabsButton.swift
2
10991
/* 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 SnapKit import Shared import XCGLogger private let log = Logger.browserLogger struct TabsButtonUX { static let TitleColor: UIColor = UIColor.black static let TitleBackgroundColor: UIColor = UIColor.white static let CornerRadius: CGFloat = 2 static let TitleFont: UIFont = UIConstants.DefaultChromeSmallFontBold static let BorderStrokeWidth: CGFloat = 1 static let BorderColor: UIColor = UIColor.clear static let TitleInsets = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.borderColor = UIConstants.PrivateModePurple theme.borderWidth = BorderStrokeWidth theme.font = UIConstants.DefaultChromeBoldFont theme.backgroundColor = UIConstants.AppBackgroundColor theme.textColor = UIConstants.PrivateModePurple theme.insets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) theme.highlightButtonColor = UIConstants.PrivateModePurple theme.highlightTextColor = TabsButtonUX.TitleColor theme.highlightBorderColor = UIConstants.PrivateModePurple themes[Theme.PrivateMode] = theme theme = Theme() theme.borderColor = BorderColor theme.borderWidth = BorderStrokeWidth theme.font = TitleFont theme.backgroundColor = TitleBackgroundColor theme.textColor = TitleColor theme.insets = TitleInsets theme.highlightButtonColor = TabsButtonUX.TitleColor theme.highlightTextColor = TabsButtonUX.TitleBackgroundColor theme.highlightBorderColor = TabsButtonUX.TitleBackgroundColor themes[Theme.NormalMode] = theme return themes }() } class TabsButton: UIControl { fileprivate var theme: Theme = TabsButtonUX.Themes[Theme.NormalMode]! override var isHighlighted: Bool { didSet { if isHighlighted { borderColor = theme.highlightBorderColor! titleBackgroundColor = theme.highlightButtonColor textColor = theme.highlightTextColor } else { borderColor = theme.borderColor! titleBackgroundColor = theme.backgroundColor textColor = theme.textColor } } } override var transform: CGAffineTransform { didSet { clonedTabsButton?.transform = transform } } lazy var titleLabel: UILabel = { let label = UILabel() label.font = TabsButtonUX.TitleFont label.layer.cornerRadius = TabsButtonUX.CornerRadius label.textAlignment = NSTextAlignment.center label.isUserInteractionEnabled = false return label }() lazy var insideButton: UIView = { let view = UIView() view.clipsToBounds = false view.isUserInteractionEnabled = false return view }() fileprivate lazy var labelBackground: UIView = { let background = UIView() background.layer.cornerRadius = TabsButtonUX.CornerRadius background.isUserInteractionEnabled = false return background }() fileprivate lazy var borderView: InnerStrokedView = { let border = InnerStrokedView() border.strokeWidth = TabsButtonUX.BorderStrokeWidth border.cornerRadius = TabsButtonUX.CornerRadius border.isUserInteractionEnabled = false return border }() fileprivate var buttonInsets: UIEdgeInsets = TabsButtonUX.TitleInsets // Used to temporarily store the cloned button so we can respond to layout changes during animation fileprivate weak var clonedTabsButton: TabsButton? override init(frame: CGRect) { super.init(frame: frame) insideButton.addSubview(labelBackground) insideButton.addSubview(borderView) insideButton.addSubview(titleLabel) addSubview(insideButton) isAccessibilityElement = true accessibilityTraits |= UIAccessibilityTraitButton } override func updateConstraints() { super.updateConstraints() labelBackground.snp.remakeConstraints { (make) -> Void in make.edges.equalTo(insideButton) } borderView.snp.remakeConstraints { (make) -> Void in make.edges.equalTo(insideButton) } titleLabel.snp.remakeConstraints { (make) -> Void in make.edges.equalTo(insideButton) } insideButton.snp.remakeConstraints { (make) -> Void in make.edges.equalTo(self).inset(insets) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func clone() -> UIView { let button = TabsButton() button.accessibilityLabel = accessibilityLabel button.titleLabel.text = titleLabel.text button.theme = theme // Copy all of the styable properties over to the new TabsButton button.titleLabel.font = titleLabel.font button.titleLabel.textColor = titleLabel.textColor button.titleLabel.layer.cornerRadius = titleLabel.layer.cornerRadius button.labelBackground.backgroundColor = labelBackground.backgroundColor button.labelBackground.layer.cornerRadius = labelBackground.layer.cornerRadius button.borderView.strokeWidth = borderView.strokeWidth button.borderView.color = borderView.color button.borderView.cornerRadius = borderView.cornerRadius return button } func updateTabCount(_ count: Int, animated: Bool = true) { let currentCount = self.titleLabel.text let infinity = "\u{221E}" let countToBe = (count < 100) ? count.description : infinity // only animate a tab count change if the tab count has actually changed if currentCount != count.description || (clonedTabsButton?.titleLabel.text ?? count.description) != count.description { if let _ = self.clonedTabsButton { self.clonedTabsButton?.layer.removeAllAnimations() self.clonedTabsButton?.removeFromSuperview() insideButton.layer.removeAllAnimations() } // make a 'clone' of the tabs button let newTabsButton = clone() as! TabsButton self.clonedTabsButton = newTabsButton newTabsButton.addTarget(self, action: #selector(TabsButton.cloneDidClickTabs), for: UIControlEvents.touchUpInside) newTabsButton.titleLabel.text = countToBe newTabsButton.accessibilityValue = countToBe superview?.addSubview(newTabsButton) newTabsButton.snp.makeConstraints { make in make.centerY.equalTo(self) make.trailing.equalTo(self) make.size.equalTo(UIConstants.ToolbarHeight) } newTabsButton.frame = self.frame newTabsButton.insets = insets // Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be // a rotation around a non-origin point let frame = self.insideButton.frame let halfTitleHeight = frame.height / 2 var newFlipTransform = CATransform3DIdentity newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0) newFlipTransform.m34 = -1.0 / 200.0 // add some perspective newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0) newTabsButton.insideButton.layer.transform = newFlipTransform var oldFlipTransform = CATransform3DIdentity oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0) oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0) let animate = { newTabsButton.insideButton.layer.transform = CATransform3DIdentity self.insideButton.layer.transform = oldFlipTransform self.insideButton.layer.opacity = 0 } let completion: (Bool) -> Void = { _ in // Remove the clone and setup the actual tab button newTabsButton.removeFromSuperview() self.insideButton.layer.opacity = 1 self.insideButton.layer.transform = CATransform3DIdentity self.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) tab toolbar") self.titleLabel.text = countToBe self.accessibilityValue = countToBe } if animated { UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions(), animations: animate, completion: completion) } else { completion(true) } } } func cloneDidClickTabs() { sendActions(for: UIControlEvents.touchUpInside) } } extension TabsButton: Themeable { func applyTheme(_ themeName: String) { guard let theme = TabsButtonUX.Themes[themeName] else { log.error("Unable to apply unknown theme \(themeName)") return } borderColor = theme.borderColor! borderWidth = theme.borderWidth! titleFont = theme.font titleBackgroundColor = theme.backgroundColor textColor = theme.textColor insets = theme.insets! self.theme = theme } } // MARK: UIAppearance extension TabsButton { dynamic var borderColor: UIColor { get { return borderView.color } set { borderView.color = newValue } } dynamic var borderWidth: CGFloat { get { return borderView.strokeWidth } set { borderView.strokeWidth = newValue } } dynamic var textColor: UIColor? { get { return titleLabel.textColor } set { titleLabel.textColor = newValue } } dynamic var titleFont: UIFont? { get { return titleLabel.font } set { titleLabel.font = newValue } } dynamic var titleBackgroundColor: UIColor? { get { return labelBackground.backgroundColor } set { labelBackground.backgroundColor = newValue } } dynamic var insets: UIEdgeInsets { get { return buttonInsets } set { buttonInsets = newValue setNeedsUpdateConstraints() } } }
mpl-2.0
31adf1480b77bdb40a04646d3b97f875
37.031142
196
0.647166
5.639302
false
false
false
false
dobaduc/segmentedcontroller
SegmentedController/SegmentedViewController.swift
1
2285
// // SegmentedViewController.swift // SegmentedController // // Created by Duc DoBa on 8/26/15. // Copyright (c) 2015 Duc Doba. All rights reserved. // import UIKit public class SegmentedViewController: UIViewController { @IBOutlet public weak var segmentedControl: SegmentedControl! public var viewControllers: [UIViewController] = [] { didSet { segmentedControl.segments = viewControllers.map( { $0.title ?? "" } ) } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init() { super.init(nibName: "SegmentedViewController", bundle: NSBundle(forClass: SegmentedViewController.self)) } public override func viewDidLoad() { super.viewDidLoad() configure() } public func didChangeSelectedIndex(sender: SegmentedControl) { showChildViewController(viewControllers[segmentedControl.selectedIndex]) } func configure() { segmentedControl.addTarget(self, action: "didChangeSelectedIndex:", forControlEvents: .ValueChanged) } } public extension SegmentedViewController { public func showChildViewController(viewController: UIViewController) { addChildViewController(viewController) view.addSubview(viewController.view) viewController.didMoveToParentViewController(self) } public func hideChildViewController(viewController: UIViewController) { viewController.willMoveToParentViewController(self) viewController.view.removeFromSuperview() viewController.removeFromParentViewController() } public func switchViewControllers(from: UIViewController, to: UIViewController) { from.willMoveToParentViewController(self) // Alpha only by default addChildViewController(to) to.view.alpha = 0 transitionFromViewController( from, toViewController: to, duration: 0.3, options: .CurveEaseOut, animations: { to.view.alpha = 1 from.view.alpha = 0 }) { finished in from.removeFromParentViewController() to.didMoveToParentViewController(self) } } }
mit
e9a93b120e80e3ff80e2173d4c7fdf95
29.466667
112
0.660832
5.655941
false
false
false
false
snepo/ios-networking
ios-BLE/BLEManager/WXPeripheral.swift
1
826
// // WXPeripheral.swift // BLEManager // // Created by Christos Bimpas on 26/09/2016. // Copyright © 2016 Snepo. All rights reserved. // import Foundation import CoreBluetooth public class WXPeripheral: NSObject { public let peripheral: CBPeripheral public let name: String public let uuid: String public var RSSI: Int public var connected: Bool = false public var isClosest: Bool = true public var receiveCharacteristic: CBCharacteristic? = nil public var sendCharacteristic: CBCharacteristic? = nil public var dataToWrite: [NSData] = [] public var canWrite: Bool = false init(peripheral: CBPeripheral,name: String, uuid: String, RSSI: Int) { self.peripheral = peripheral self.name = name self.uuid = uuid self.RSSI = RSSI } }
mit
a8d65c731b429ad7a3ce7581889d6eeb
25.612903
74
0.677576
4.319372
false
false
false
false
naokits/my-programming-marathon
RxSwiftDemo/Carthage/Checkouts/RxSwift/Rx.playground/Pages/Subjects.xcplaygroundpage/Contents.swift
6
3736
//: [<< Previous](@previous) - [Index](Index) import RxSwift /*: A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items. */ func writeSequenceToConsole<O: ObservableType>(name: String, sequence: O) -> Disposable { return sequence .subscribe { e in print("Subscription: \(name), event: \(e)") } } /*: ## PublishSubject `PublishSubject` emits to an observer only those items that are emitted by the source Observable(s) subsequent to the time of the subscription. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject.png) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject_error.png) */ example("PublishSubject") { let disposeBag = DisposeBag() let subject = PublishSubject<String>() writeSequenceToConsole("1", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("c")) subject.on(.Next("d")) } /*: ## ReplaySubject `ReplaySubject` emits to any observer all of the items that were emitted by the source Observable(s), regardless of when the observer subscribes. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/replaysubject.png) */ example("ReplaySubject") { let disposeBag = DisposeBag() let subject = ReplaySubject<String>.create(bufferSize: 1) writeSequenceToConsole("1", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("c")) subject.on(.Next("d")) } /*: ## BehaviorSubject When an observer subscribes to a `BehaviorSubject`, it begins by emitting the item most recently emitted by the source Observable (or a seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s). ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject.png) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject_error.png) */ example("BehaviorSubject") { let disposeBag = DisposeBag() let subject = BehaviorSubject(value: "z") writeSequenceToConsole("1", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("c")) subject.on(.Next("d")) subject.on(.Completed) } /*: ## Variable `Variable` wraps `BehaviorSubject`. Advantage of using variable over `BehaviorSubject` is that variable can never explicitly complete or error out, and `BehaviorSubject` can in case `Error` or `Completed` message is send to it. `Variable` will also automatically complete in case it's being deallocated. */ example("Variable") { let disposeBag = DisposeBag() let variable = Variable("z") writeSequenceToConsole("1", sequence: variable.asObservable()).addDisposableTo(disposeBag) variable.value = "a" variable.value = "b" writeSequenceToConsole("2", sequence: variable.asObservable()).addDisposableTo(disposeBag) variable.value = "c" variable.value = "d" } //: [Index](Index) - [Next >>](@next)
mit
5f76ab741f6bde99bde0b3078b5d87e5
34.923077
344
0.728319
4.319075
false
false
false
false
kellanburket/franz
Sources/Franz/KafkaProtocol.swift
1
4417
// // KafkaProtocol.swift // Franz // // Created by Kellan Cummings on 1/14/16. // Copyright © 2016 Kellan Cummings. All rights reserved. // import Foundation protocol KafkaType { init(data: inout Data) var data: Data { get } var dataLength: Int { get } } protocol CompoundKafkaType: KafkaType { var values: [KafkaType] { get } } extension CompoundKafkaType { var data: Data { return values.map { $0.data }.reduce(Data(), +) } var dataLength: Int { return values.map { $0.dataLength }.reduce(0, +) } } extension Data { mutating func take(first: Int) -> Data { let start = prefix(upTo: startIndex + first) removeFirst(first) return start } } extension KafkaType where Self: FixedWidthInteger { init(data: inout Data) { let dataLength = MemoryLayout<Self>.size self.init(bigEndian: data.take(first: dataLength).withUnsafeBytes { $0.pointee }) } var dataLength: Int { return MemoryLayout<Self>.size } var data: Data { var bytes = Self(self.bigEndian) return Data(bytes: &bytes, count: MemoryLayout<Self>.size) } } extension UInt: KafkaType {} extension UInt8: KafkaType {} extension UInt16: KafkaType {} extension UInt32: KafkaType {} extension UInt64: KafkaType {} extension Int: KafkaType {} extension Int8: KafkaType {} extension Int16: KafkaType {} extension Int32: KafkaType {} extension Int64: KafkaType {} extension Bool: KafkaType { init(data: inout Data) { self = Int8(data: &data) == 0 } private var representation: Int8 { return Int8(self ? 1 : 0) } var data: Data { return representation.data } var dataLength: Int { return representation.dataLength } } protocol KafkaVariableLengthType: KafkaType { associatedtype Length: FixedWidthInteger where Length: KafkaType var variableLengthData: Data { get } init(variableLengthData: Data) } extension KafkaVariableLengthType { init(data: inout Data) { let length = Int(Length(data: &data)) if length == -1 { self.init(variableLengthData: Data()) return } self.init(variableLengthData: data.take(first: length)) } var lengthSize: Int { return MemoryLayout<Length>.size } var dataLength: Int { return variableLengthData.count + lengthSize } var data: Data { var finalData = Data(capacity: self.dataLength) finalData += Length(self.variableLengthData.count).data finalData += variableLengthData return finalData } } extension String: KafkaVariableLengthType { typealias Length = Int16 init(variableLengthData: Data) { self.init(data: variableLengthData, encoding: .utf8)! } var variableLengthData: Data { return data(using: .utf8)! } } extension Optional: KafkaType where Wrapped == String { init(data: inout Data) { var peekData = data let length = Int16(data: &peekData) if length == -1 { self = .none } else { self = .some(String(data: &data)) } } var dataLength: Int { switch self { case .none: return Int16(-1).dataLength case .some(let wrapped): return wrapped.dataLength } } var data: Data { switch self { case .none: return Int16(-1).data case .some(let wrapped): return wrapped.data } } } extension Data: KafkaVariableLengthType { typealias Length = Int32 init(variableLengthData: Data) { self = variableLengthData } var variableLengthData: Data { return self } } extension Optional where Wrapped == Data { var dataLength: Int { switch self { case .none: return Data().dataLength case .some(let wrapped): return wrapped.dataLength } } var data: Data { switch self { case .none: return Data().data case .some(let wrapped): return wrapped.data } } } extension Array: KafkaType where Element: KafkaType { init(data: inout Data) { let count = Int32(data: &data) var temp: [Element] = [] for _ in 0..<count { temp.append(Element(data: &data)) } self = temp } var data: Data { var finalData = Data(capacity: dataLength) let sizeData = Int32(count).data finalData.append(sizeData) finalData.append(valuesData) return finalData } var dataLength: Int { // Value length + size length return valuesDataLength + 4 } private var valuesDataLength: Int { return map { $0.dataLength }.reduce(0, +) } private var valuesData: Data { return map { $0.data }.reduce(Data(), +) } } protocol KafkaMetadata: KafkaType { static var protocolType: GroupProtocol { get } }
mit
08bcf52113e52cc0135c9bcaeaf98012
18.116883
83
0.687274
3.36329
false
false
false
false
AaoIi/FMPhoneTextField
FMPhoneTextField/FMPhoneTextField/Countries/Models/Country.swift
1
1036
// // Country.swift // FMPhoneTextField // // Created by Mobile build server on 8/28/19. // Copyright © 2019 Saad Basha. All rights reserved. // import Foundation // MARK: - Country public struct Country: Codable { let countries: [CountryElement]? } // MARK: - CountryElement public struct CountryElement: Codable { public let isoCode: String? public let isoShortCode: String? public let nameAr, nameEn, countryInternationlKey: String? public let phoneRegex: String? public enum CodingKeys: String, CodingKey { case isoCode, isoShortCode, nameAr, nameEn, countryInternationlKey, phoneRegex } public init(isoCode: String?, isoShortCode: String?, nameAr: String?, nameEn: String?, countryInternationlKey: String?,phoneRegex: String?) { self.isoCode = isoCode self.isoShortCode = isoShortCode self.nameAr = nameAr self.nameEn = nameEn self.countryInternationlKey = countryInternationlKey self.phoneRegex = phoneRegex } }
mit
509090ba49a5ebcf0b404b9c2f3ffad0
27.75
145
0.689855
4.259259
false
false
false
false
multinerd/Mia
Mia/Sugar/On/Notification.swift
1
990
import Foundation public extension Container where Host: NSObject { func observe(notification name: Notification.Name, _ action: @escaping NotificationAction) { let observer = NotificationCenter.default.addObserver(forName: name, object: nil, queue: OperationQueue.main, using: { action($0) }) notificationTarget.mapping[name] = observer } func unobserve(notification name: Notification.Name) { let observer = notificationTarget.mapping.removeValue(forKey: name) if let observer = observer { NotificationCenter.default.removeObserver(observer as Any) notificationTarget.mapping.removeValue(forKey: name) } } } class NotificationTarget: NSObject { var mapping: [Notification.Name: NSObjectProtocol] = [:] deinit { mapping.forEach({ (key, value) in NotificationCenter.default.removeObserver(value as Any) }) mapping.removeAll() } }
mit
708be657878a1066a9ba658b73a7af39
25.756757
126
0.666667
5
false
false
false
false
hengZhuo/DouYuZhiBo
swift-DYZB/swift-DYZB/Classes/Main/Model/AnchorModel.swift
1
749
// // AnchorModel.swift // swift-DYZB // // Created by chenrin on 2016/11/16. // Copyright © 2016年 zhuoheng. All rights reserved. // import UIKit class AnchorModel: NSObject { //房间号 var room_id : Int = 0 //房间图片 var vertical_src = "" //判断是手机还是电脑直播 0:手机 1:电脑 var isVertical : Int = 0 //房间名字 var room_name = "" //主播昵称 var nickname = "" //观看人数 var online : Int = 0 //所在城市 var anchor_city = "" init(dict:[String : NSObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
mit
514d5d7e245f6c2a7d1fc5ccadc12f5b
16.076923
72
0.540541
3.659341
false
false
false
false
DanteEvil/MadPuzzle
MadPuzzle/MadPuzzle/Viewcontrollers/PrepareGame/MPPrepareGameViewController.swift
1
2392
// // MPPrepareGameViewController.swift // MadPuzzle // // Created by Truong Le on 6/12/17. // Copyright © 2017 Truong Le. All rights reserved. // import UIKit class MPPrepareGameViewController: MPBaseViewController { @IBOutlet weak var imageListCollectionView: UICollectionView! @IBOutlet weak var presentSelectedImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() imageListCollectionView.register(UINib(nibName: "ImageCollectionViewCell", bundle: Bundle.main), forCellWithReuseIdentifier: "ImageCollectionViewCell") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) imageListCollectionView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK: UIImagePickerControllerDelegate extension MPPrepareGameViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { } //MARK: Actions extension MPPrepareGameViewController { fileprivate func presentPhotosPicker() { let imagePicker:UIImagePickerController = UIImagePickerController() imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary imagePicker.delegate = self present(imagePicker, animated: true, completion: nil) } } //MARK: UICollectionViewDelegate extension MPPrepareGameViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 8 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell cell.populate(image: UIImage(named:String(indexPath.row+1))!) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = collectionView.bounds.height return CGSize(width: 2/3*height, height: height) } }
apache-2.0
69b7703917b8555f867d88e812e7cff7
36.359375
160
0.73693
6.11509
false
false
false
false
stephentyrone/swift
test/Sema/diag_mismatched_magic_literals.swift
4
6781
// RUN: %target-typecheck-verify-swift func callee(file: String = #file) {} // expected-note {{'file' declared here}} func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}} func callee(arbitrary: String) {} class SomeClass { static func callee(file: String = #file) {} // expected-note 2{{'file' declared here}} static func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}} static func callee(arbitrary: String) {} func callee(file: String = #file) {} // expected-note 2{{'file' declared here}} func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}} func callee(arbitrary: String) {} } // // Basic functionality // // We should warn when we we pass a `#function`-defaulted argument to a // `#file`-defaulted argument. func bad(function: String = #function) { // expected-note@-1 3{{did you mean for parameter 'function' to default to '#file'?}} {{29-38=#file}} callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{16-16=(}} {{24-24=)}} SomeClass.callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{26-26=(}} {{34-34=)}} SomeClass().callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{28-28=(}} {{36-36=)}} } // We should not warn when we pass a `#file`-defaulted argument to a // `#file`-defaulted argument. func good(file: String = #file) { callee(file: file) SomeClass.callee(file: file) SomeClass().callee(file: file) } // We should not warn when we surround the `#function`-defaulted argument // with parentheses, which explicitly silences the warning. func disabled(function: String = #function) { callee(file: (function)) SomeClass.callee(file: (function)) SomeClass().callee(file: (function)) } // // With implicit instance `self` // extension SomeClass { // We should warn when we we pass a `#function`-defaulted argument to a // `#file`-defaulted argument. func bad(function: String = #function) { // expected-note@-1 1{{did you mean for parameter 'function' to default to '#file'?}} {{31-40=#file}} callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{18-18=(}} {{26-26=)}} } // We should not warn when we pass a `#file`-defaulted argument to a // `#file`-defaulted argument. func good(file: String = #file) { callee(file: file) } // We should not warn when we surround the `#function`-defaulted argument // with parentheses, which explicitly silences the warning. func disabled(function: String = #function) { callee(file: (function)) } } // // With implicit type `self` // extension SomeClass { // We should warn when we we pass a `#function`-defaulted argument to a // `#file`-defaulted argument. static func bad(function: String = #function) { // expected-note@-1 1{{did you mean for parameter 'function' to default to '#file'?}} {{38-47=#file}} callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{18-18=(}} {{26-26=)}} } // We should not warn when we pass a `#file`-defaulted argument to a // `#file`-defaulted argument. static func good(file: String = #file) { callee(file: file) } // We should not warn when we surround the `#function`-defaulted argument // with parentheses, which explicitly silences the warning. static func disabled(function: String = #function) { callee(file: (function)) } } // // Looking through implicit conversions // // Same as above, but these lift the argument from `String` to `String?`, so // the compiler has to look through the implicit conversion. // // We should warn when we we pass a `#function`-defaulted argument to a // `#file`-defaulted argument. func optionalBad(function: String = #function) { // expected-note@-1 3{{did you mean for parameter 'function' to default to '#file'?}} {{37-46=#file}} callee(optFile: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{19-19=(}} {{27-27=)}} SomeClass.callee(optFile: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{37-37=)}} SomeClass().callee(optFile: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{31-31=(}} {{39-39=)}} } // We should not warn when we pass a `#file`-defaulted argument to a // `#file`-defaulted argument. func optionalGood(file: String = #file) { callee(optFile: file) SomeClass.callee(optFile: file) SomeClass().callee(optFile: file) } // We should not warn when we surround the `#function`-defaulted argument // with parentheses, which explicitly silences the warning. func optionalDisabled(function: String = #function) { callee(optFile: (function)) SomeClass.callee(optFile: (function)) SomeClass().callee(optFile: (function)) } // // More negative cases // // We should not warn if the caller's parameter has no default. func explicit(arbitrary: String) { callee(file: arbitrary) SomeClass.callee(file: arbitrary) SomeClass().callee(file: arbitrary) } // We should not warn if the caller's parameter has a non-magic-identifier // default. func empty(arbitrary: String = "") { callee(file: arbitrary) SomeClass.callee(file: arbitrary) SomeClass().callee(file: arbitrary) } // We should not warn if the callee's parameter has no default. func ineligible(function: String = #function) { callee(arbitrary: function) SomeClass.callee(arbitrary: function) SomeClass().callee(arbitrary: function) }
apache-2.0
6c797431ced59020879ac0d43c88f41c
35.456989
148
0.692081
3.953936
false
false
false
false
zhugejunwei/Algorithms-in-Java-Swift-CPP
Isomorphism & Girth/sourceCode/GirthofG/GirthofG/Girth Algorithm.swift
1
1992
// // Girth Algorithm.swift // Girth // // Created by 诸葛俊伟 on 10/23/16. // Copyright © 2016 University of Pittsburgh. All rights reserved. // import Foundation public class Node { public var vertex: Int public var depth: Int init(_ vertex: Int, _ depth: Int) { self.vertex = vertex self.depth = depth } } func FindGirth(_ graph: [[Int]]) { let n = graph.count // shortest cycle length var short = n - 1 var queue = [Node]() var root = 0 while (root < n - 2 && short > 3) { var label = Array(repeating: -1, count: n) label[root] = 0 queue.append(Node(root, 0)) var node = queue.removeFirst() while (!queue.isEmpty && short > 3 && (node.depth + 1) * 2 - 1 < short) { let depth = node.depth + 1 // check all neighbours for neighbour in getNeighbours(graph, node.vertex) { // haven't seen this neighbour before if label[neighbour] < 0 { queue.append(Node(neighbour, depth)) label[neighbour] = depth } else if label[neighbour] == depth - 1 { // odd number of edges if depth * 2 - 1 < short { short = depth * 2 - 1 } } else if label[neighbour] == depth { // even number of edges if (depth * 2 < short) { short = depth * 2 } } } node = queue.removeFirst() } queue.removeAll() root += 1 } // return short > 0 ? short : 1 } func getNeighbours(_ graph: [[Int]], _ vertex: Int) -> [Int] { var res = [Int]() for i in 0..<graph.count { if graph[vertex][i] != 0 { res.append(i) } } return res }
mit
fc6f6d4b3f4e0cc260151fc1cd8fdd24
24.101266
79
0.452345
4.183544
false
false
false
false
shu223/ARKit-Sampler
ARKit-Sampler/Samples/ARFaceSimple/ARFaceSimpleViewController.swift
1
3236
// // ARFaceSimpleViewController.swift // ARKit-Sampler // // Created by Shuichi Tsutsumi on 2017/12/25. // Copyright © 2017 Shuichi Tsutsumi. All rights reserved. // import ARKit class ARFaceSimpleViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! @IBOutlet var trackingStateLabel: UILabel! private var faceNode: ARFaceNode! override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self sceneView.scene = SCNScene() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard ARFaceTrackingConfiguration.isSupported, let device = sceneView.device else { print("ARFaceTrackingConfiguration is not supported on this device!") navigationController?.popViewController(animated: true) return; } faceNode = ARFaceNode(device: device) sceneView.session.run(ARFaceTrackingConfiguration(), options: [.resetTracking, .removeExistingAnchors]) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) sceneView.session.pause() } private func updateTime(_ time: TimeInterval, for material: SCNMaterial) { var floatTime = Float(time) let timeData = Data(bytes: &floatTime, count: MemoryLayout<Float>.size) material.setValue(timeData, forKey: "time") } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { guard let currentFrame = sceneView.session.currentFrame else { return } for anchor in currentFrame.anchors { // update time for ARFaceNode object guard let faceAnchor = anchor as? ARFaceAnchor else { continue } guard let node = sceneView.node(for: faceAnchor) else { continue } guard let faceNode = node.findFaceNode() else { continue } guard let material = faceNode.geometry?.firstMaterial else { return } self.updateTime(time, for: material) } } func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { print("\(self.classForCoder)/" + #function) guard let faceAnchor = anchor as? ARFaceAnchor else {fatalError()} faceNode.removeFromParentNode() node.addChildNode(faceNode) faceNode.update(with: faceAnchor) } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { guard let faceAnchor = anchor as? ARFaceAnchor else {fatalError()} faceNode.update(with: faceAnchor) } func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) { print("\(self.classForCoder)/" + #function) faceNode.removeFromParentNode() } // MARK: - ARSessionObserver func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) { print("trackingState: \(camera.trackingState)") trackingStateLabel.text = camera.trackingState.description } }
mit
ca789d0f8ddc0ff6a077a163f047e12f
33.784946
111
0.656569
5.26873
false
false
false
false
libiao88/APNGKit
APNGKit/Disassembler.swift
4
12623
// // Disassembler.swift // APNGKit // // Created by Wei Wang on 15/8/27. // // Copyright (c) 2015 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit let signatureOfPNGLength = 8 let kMaxPNGSize: UInt32 = 1000000; // Reading callback for libpng func readData(pngPointer: png_structp, outBytes: png_bytep, byteCountToRead: png_size_t) { let ioPointer = png_get_io_ptr(pngPointer) var reader = UnsafePointer<Reader>(ioPointer).memory reader.read(outBytes, bytesCount: byteCountToRead) } /** Disassembler Errors. An error will be thrown if the disassembler encounters unexpected error. - InvalidFormat: The file is not a PNG format. - PNGStructureFailure: Fail on creating a PNG structure. It might due to out of memory. - PNGInternalError: Internal error when decoding a PNG image. - FileSizeExceeded: The file is too large. There is a limitation of APNGKit that the max width and height is 1M pixel. */ public enum DisassemblerError: ErrorType { case InvalidFormat case PNGStructureFailure case PNGInternalError case FileSizeExceeded } /** * Disassemble APNG data. * See APNG Specification: https://wiki.mozilla.org/APNG_Specification for defination of APNG. * This Disassembler is using a patched libpng with supporting of apng to read APNG data. * See https://github.com/onevcat/libpng for more. */ public struct Disassembler { private(set) var reader: Reader let originalData: NSData /** Init a disassembler with APNG data. - parameter data: Data object of an APNG file. - returns: The disassembler ready to use. */ public init(data: NSData) { reader = Reader(data: data) originalData = data } /** Decode the data to a high level `APNGImage` object. - parameter scale: The screen scale should be used when decoding. You should pass 1 if you want to use the dosassembler separately. If you need to display the image on the screen later, use `UIScreen.mainScreen().scale`. Default is 1.0. - throws: A `DisassemblerError` when error happens. - returns: A decoded `APNGImage` object at given scale. */ public mutating func decode(scale: CGFloat = 1) throws -> APNGImage { let (frames, size, repeatCount, bitDepth, firstFrameHidden) = try decodeToElements(scale) // Setup apng properties let apng = APNGImage(frames: frames, size: size, scale: scale, bitDepth: bitDepth, repeatCount: repeatCount, firstFrameHidden: firstFrameHidden) return apng } mutating func decodeToElements(scale: CGFloat = 1) throws -> (frames: [Frame], size: CGSize, repeatCount: Int, bitDepth: Int, firstFrameHidden: Bool) { reader.beginReading() defer { reader.endReading() } try checkFormat() var pngPointer = png_create_read_struct(PNG_LIBPNG_VER_STRING, nil, nil, nil) if pngPointer == nil { throw DisassemblerError.PNGStructureFailure } var infoPointer = png_create_info_struct(pngPointer) defer { png_destroy_read_struct(&pngPointer, &infoPointer, nil) } if infoPointer == nil { throw DisassemblerError.PNGStructureFailure } if setjmp(png_jmpbuf(pngPointer)) != 0 { throw DisassemblerError.PNGInternalError } png_set_read_fn(pngPointer, &reader, readData) png_read_info(pngPointer, infoPointer) var width: UInt32 = 0, height: UInt32 = 0, bitDepth: Int32 = 0, colorType: Int32 = 0 // Decode IHDR png_get_IHDR(pngPointer, infoPointer, &width, &height, &bitDepth, &colorType, nil, nil, nil) if width > kMaxPNGSize || height > kMaxPNGSize { throw DisassemblerError.FileSizeExceeded } // Transforms. We only handle 8-bit RGBA images. png_set_expand(pngPointer) if bitDepth == 16 { png_set_strip_16(pngPointer) } if colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA { png_set_gray_to_rgb(pngPointer); } if colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_GRAY { png_set_add_alpha(pngPointer, 0xff, PNG_FILLER_AFTER); } png_set_interlace_handling(pngPointer); png_read_update_info(pngPointer, infoPointer); // Update information from updated info pointer width = png_get_image_width(pngPointer, infoPointer) height = png_get_image_height(pngPointer, infoPointer) let rowBytes = UInt32(png_get_rowbytes(pngPointer, infoPointer)) let length = height * rowBytes // Decode acTL var frameCount: UInt32 = 0, playCount: UInt32 = 0 png_get_acTL(pngPointer, infoPointer, &frameCount, &playCount) if frameCount == 0 { // Fallback to regular PNG var currentFrame = Frame(length: length, bytesInRow: rowBytes) currentFrame.duration = Double.infinity currentFrame.updateCGImageRef(Int(width), height: Int(height), bits: Int(bitDepth), scale: scale) png_read_image(pngPointer, &currentFrame.byteRows) png_read_end(pngPointer, infoPointer) return ([currentFrame], CGSize(width: CGFloat(width), height: CGFloat(height)), Int(playCount) - 1, Int(bitDepth), false) } var bufferFrame = Frame(length: length, bytesInRow: rowBytes) var currentFrame = Frame(length: length, bytesInRow: rowBytes) var nextFrame: Frame! // Setup values for reading frames var frameWidth: UInt32 = 0, frameHeight: UInt32 = 0, offsetX: UInt32 = 0, offsetY: UInt32 = 0, delayNum: UInt16 = 0, delayDen: UInt16 = 0, disposeOP: UInt8 = 0, blendOP: UInt8 = 0 let firstImageIndex: Int let firstFrameHidden = png_get_first_frame_is_hidden(pngPointer, infoPointer) != 0 firstImageIndex = firstFrameHidden ? 1 : 0 var frames = [Frame]() // Decode frames for i in 0 ..< frameCount { let currentIndex = Int(i) // Read header png_read_frame_head(pngPointer, infoPointer) // Decode fcTL png_get_next_frame_fcTL(pngPointer, infoPointer, &frameWidth, &frameHeight, &offsetX, &offsetY, &delayNum, &delayDen, &disposeOP, &blendOP) // Update disposeOP for first visable frame if currentIndex == firstImageIndex { blendOP = UInt8(PNG_BLEND_OP_SOURCE) if disposeOP == UInt8(PNG_DISPOSE_OP_PREVIOUS) { disposeOP = UInt8(PNG_DISPOSE_OP_BACKGROUND) } } nextFrame = Frame(length: length, bytesInRow: rowBytes) if (disposeOP == UInt8(PNG_DISPOSE_OP_PREVIOUS)) { // For the first frame, currentFrame is not inited yet. // But we can ensure the disposeOP is not PNG_DISPOSE_OP_PREVIOUS for the 1st frame memcpy(nextFrame.bytes, currentFrame.bytes, Int(length)); } // Decode fdATs png_read_image(pngPointer, &bufferFrame.byteRows) blendFrameDstBytes(currentFrame.byteRows, srcBytes: bufferFrame.byteRows, blendOP: blendOP, offsetX: offsetX, offsetY: offsetY, width: frameWidth, height: frameHeight) // Calculating delay (duration) if delayDen == 0 { delayDen = 100 } let duration = Double(delayNum) / Double(delayDen) currentFrame.duration = duration currentFrame.updateCGImageRef(Int(width), height: Int(height), bits: Int(bitDepth), scale: scale) frames.append(currentFrame) if disposeOP != UInt8(PNG_DISPOSE_OP_PREVIOUS) { memcpy(nextFrame.bytes, currentFrame.bytes, Int(length)) if disposeOP == UInt8(PNG_DISPOSE_OP_BACKGROUND) { for j in 0 ..< frameHeight { let tarPointer = nextFrame.byteRows[Int(offsetY + j)].advancedBy(Int(offsetX) * 4) memset(tarPointer, 0, Int(frameWidth) * 4) } } } currentFrame.bytes = nextFrame.bytes currentFrame.byteRows = nextFrame.byteRows } // End png_read_end(pngPointer, infoPointer) bufferFrame.clean() currentFrame.clean() return (frames, CGSize(width: CGFloat(width), height: CGFloat(height)), Int(playCount) - 1, Int(bitDepth), firstFrameHidden) } func blendFrameDstBytes(dstBytes: Array<UnsafeMutablePointer<UInt8>>, srcBytes: Array<UnsafeMutablePointer<UInt8>>, blendOP: UInt8, offsetX: UInt32, offsetY: UInt32, width: UInt32, height: UInt32) { var u: Int = 0, v: Int = 0, al: Int = 0 for j in 0 ..< Int(height) { var sp = srcBytes[j] var dp = (dstBytes[j + Int(offsetY)]).advancedBy(Int(offsetX) * 4) //We will always handle 4 channels and 8-bits if blendOP == UInt8(PNG_BLEND_OP_SOURCE) { memcpy(dp, sp, Int(width) * 4) } else { // APNG_BLEND_OP_OVER for var i = 0; i < Int(width); i++, sp = sp.advancedBy(4), dp = dp.advancedBy(4) { let srcAlpha = Int(sp.advancedBy(3).memory) // Blend alpha to dst if srcAlpha == 0xff { memcpy(dp, sp, 4) } else if srcAlpha != 0 { let dstAlpha = Int(dp.advancedBy(3).memory) if dstAlpha != 0 { u = srcAlpha * 255 v = (255 - srcAlpha) * dstAlpha al = u + v for bit in 0 ..< 3 { dp.advancedBy(bit).memory = UInt8( (Int(sp.advancedBy(bit).memory) * u + Int(dp.advancedBy(bit).memory) * v) / al ) } dp.advancedBy(4).memory = UInt8(al / 255) } else { memcpy(dp, sp, 4) } } } } } } func checkFormat() throws { guard originalData.length > 8 else { throw DisassemblerError.InvalidFormat } var sig = [UInt8](count: signatureOfPNGLength, repeatedValue: 0) originalData.getBytes(&sig, length: signatureOfPNGLength) guard png_sig_cmp(&sig, 0, signatureOfPNGLength) == 0 else { throw DisassemblerError.InvalidFormat } } }
mit
1f3b76980083a2f7d6eb5e7eb6f9a8f2
37.962963
133
0.572447
4.657934
false
false
false
false
colemancda/Seam
Seam/Seam/NSEntityDescription+Helpers.swift
1
2450
// NSEntityDescription+Helpers.swift // // The MIT License (MIT) // // Copyright (c) 2015 Nofel Mahmood ( https://twitter.com/NofelMahmood ) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import CoreData extension NSEntityDescription { func attributesByNameByRemovingBackingStoreAttributes() -> [String:NSAttributeDescription] { var attributesByName = self.attributesByName attributesByName.removeValueForKey(SMLocalStoreRecordIDAttributeName) attributesByName.removeValueForKey(SMLocalStoreRecordEncodedValuesAttributeName) return attributesByName } func toOneRelationships() -> [NSRelationshipDescription] { return Array(self.relationshipsByName.values).filter({ (relationshipDescription) -> Bool in return relationshipDescription.toMany == false }) } func toOneRelationshipsByName() -> [String:NSRelationshipDescription] { var relationshipsByNameDictionary: Dictionary<String,NSRelationshipDescription> = Dictionary<String,NSRelationshipDescription>() for (key,value) in self.relationshipsByName { if value.toMany == true { continue } relationshipsByNameDictionary[key] = value } return relationshipsByNameDictionary } }
mit
3f7becff8a7736f232630a0ad212ba77
39.833333
136
0.708571
5.125523
false
false
false
false
tiggleric/CVCalendar
Pod/Classes/CVCalendarMonthView.swift
1
3272
// // CVCalendarMonthView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit class CVCalendarMonthView: UIView { // MARK: - Public properties var calendarView: CVCalendarView? var date: NSDate? var numberOfWeeks: Int? var weekViews: [CVCalendarWeekView]? var weeksIn: [[Int : [Int]]]? var weeksOut: [[Int : [Int]]]? var currentDay: Int? // MARK: - Initialization init(calendarView: CVCalendarView, date: NSDate) { super.init(frame: CGRectZero) self.calendarView = calendarView self.date = date self.commonInit() } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func commonInit() { let calendarManager = CVCalendarManager.sharedManager self.numberOfWeeks = calendarManager.monthDateRange(self.date!).countOfWeeks self.weeksIn = calendarManager.weeksWithWeekdaysForMonthDate(self.date!).weeksIn self.weeksOut = calendarManager.weeksWithWeekdaysForMonthDate(self.date!).weeksOut self.currentDay = calendarManager.dateRange(NSDate()).day } // MARK: - Content filling func updateAppearance(frame: CGRect) { self.frame = frame self.createWeekViews() } func createWeekViews() { let renderer = CVCalendarRenderer.sharedRenderer() self.weekViews = [CVCalendarWeekView]() for i in 0..<self.numberOfWeeks! { let frame = renderer.renderWeekFrameForMonthView(self, weekIndex: i) let weekView = CVCalendarWeekView(monthView: self, frame: frame, index: i) self.weekViews?.append(weekView) self.addSubview(weekView) } } // MARK: - Events receiving func receiveDayViewTouch(dayView: CVCalendarDayView) { let controlCoordinator = CVCalendarDayViewControlCoordinator.sharedControlCoordinator controlCoordinator.performDayViewSelection(dayView) self.calendarView!.didSelectDayView(dayView) } // MARK: - View Destruction func destroy() { let coordinator = CVCalendarDayViewControlCoordinator.sharedControlCoordinator if self.weekViews != nil { for weekView in self.weekViews! { for dayView in weekView.dayViews! { if dayView == coordinator.selectedDayView { coordinator.selectedDayView = nil } } weekView.destroy() } self.weekViews = nil } } // MARK: Content reload func reloadWeekViewsWithMonthFrame(frame: CGRect) { self.frame = frame for i in 0..<self.weekViews!.count { let frame = CVCalendarRenderer.sharedRenderer().renderWeekFrameForMonthView(self, weekIndex: i) let weekView = self.weekViews![i] weekView.frame = frame weekView.reloadDayViews() } } }
mit
bad160161bd97b3faf53a2ddb97fb89f
28.214286
107
0.60544
5.277419
false
false
false
false
mindbody/Conduit
Sources/Conduit/Auth/AuthorizationCodeGrant/OAuth2AuthorizationError.swift
1
1890
// // OAuth2AuthorizationError.swift // Conduit // // Created by John Hammerlund on 6/28/17. // Copyright © 2017 MINDBODY. All rights reserved. // import Foundation /// An error that occured during a request for authorization, as /// defined by RFC6749 4.1.2.1 public enum OAuth2AuthorizationError: Error { /// The request has invalid/missing parameters or is otherwise malformed case invalidRequest /// The client is not authorized for this request case unauthorizedClient /// The resource owner or authorization server denied the request case accessDenied /// The authorization server does not support this request case unsupportedResponseType /// The requested scope is invalid, unknown, or malformed case invalidScope /// The server encountered an unexpected server error (HTTP redirects are not /// allowed when the HTTP status code falls in the 500 range) case serverError /// The authorization server is temporarily unable to handle requests (HTTP redirects /// are not allowed when the HTTP status code falls in the 500 range) case temporarilyUnavailable /// The user cancelled the request case cancelled /// An unknown error occurred during or after the request case unknown init(errorCode: String) { switch errorCode { case "invalid_request": self = .invalidRequest case "unauthorized_client": self = .unauthorizedClient case "access_denied": self = .accessDenied case "unsupported_response_type": self = .unsupportedResponseType case "invalid_scope": self = .invalidScope case "server_error": self = .serverError case "temporarily_unavailable": self = .temporarilyUnavailable default: self = .unknown } } }
apache-2.0
31ba046db84be86a0a992b6acb67efe3
33.345455
89
0.670725
5.218232
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Commons/Extensions/FileManager+DirectoryUrl.swift
1
1337
// // FileManager+DirectoryUrl.swift // NearbyWeather // // Created by Erik Maximilian Martens on 28.04.20. // Copyright © 2020 Erik Maximilian Martens. All rights reserved. // import Foundation enum FileManagerError: String, Error { var domain: String { "FileManager" } case directoryUrlDeterminationError = "Could not determine the specified directory within the SearchPathDirectory" } extension FileManager { enum StorageLocationType { case bundle case documents case applicationSupport } func directoryUrl(for location: StorageLocationType, fileName: String? = nil, fileExtension: String? = nil) throws -> URL { var url: URL? switch location { case .bundle: url = Bundle.main.bundleURL case .documents: url = urls(for: .documentDirectory, in: .userDomainMask).first case .applicationSupport: url = urls(for: .applicationSupportDirectory, in: .userDomainMask).first } guard let result = url else { throw FileManagerError.directoryUrlDeterminationError } return result } func createBaseDirectoryIfNeeded(for filePath: String) throws { if fileExists(atPath: filePath, isDirectory: nil) { return } try createDirectory(atPath: filePath, withIntermediateDirectories: true, attributes: nil) } }
mit
e3752cd1b972b1299e8ca8aa01d5783f
24.692308
125
0.704341
4.737589
false
false
false
false
feistydog/FeistyDB
Sources/FeistyDB/Database+SQLFunctions.swift
1
13714
// // Copyright (c) 2015 - 2021 Feisty Dog, LLC // // See https://github.com/feistydog/FeistyDB/blob/master/LICENSE.txt for license information // import Foundation import CSQLite extension Database { /// A custom SQL function. /// /// - parameter values: The SQL function parameters /// /// - throws: `Error` /// /// - returns: The result of applying the function to `values` public typealias SQLFunction = (_ values: [DatabaseValue]) throws -> DatabaseValue /// Custom SQL function flags /// /// - seealso: [Function Flags](https://www.sqlite.org/c3ref/c_deterministic.html) public struct SQLFunctionFlags: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// The function gives the same output when the input parameters are the same public static let deterministic = SQLFunctionFlags(rawValue: 1 << 0) /// The function may only be invoked from top-level SQL, and cannot be used in views or triggers /// nor in schema structures such as `CHECK` constraints, `DEFAULT` clauses, expression indexes, partial indexes, or generated columns public static let directOnly = SQLFunctionFlags(rawValue: 1 << 1) /// Indicates to SQLite that a function may call `sqlite3_value_subtype() `to inspect the sub-types of its arguments public static let subtype = SQLFunctionFlags(rawValue: 1 << 2) /// The function is unlikely to cause problems even if misused. /// An innocuous function should have no side effects and should not depend on any values other than its input parameters. public static let innocuous = SQLFunctionFlags(rawValue: 1 << 3) } } extension Database.SQLFunctionFlags { /// Returns the value of `self` using SQLite's flag values func asSQLiteFlags() -> Int32 { var flags: Int32 = 0 if contains(.deterministic) { flags |= SQLITE_DETERMINISTIC } if contains(.directOnly) { flags |= SQLITE_DIRECTONLY } if contains(.subtype) { flags |= SQLITE_SUBTYPE } if contains(.innocuous) { flags |= SQLITE_INNOCUOUS } return flags } } /// A custom SQL aggregate function. public protocol SQLAggregateFunction { /// Invokes the aggregate function for one or more values in a row. /// /// - parameter values: The SQL function parameters /// /// - throws: `Error` func step(_ values: [DatabaseValue]) throws /// Returns the current value of the aggregate function. /// /// - note: This should also reset any function context to defaults. /// /// - throws: `Error` /// /// - returns: The current value of the aggregate function. func final() throws -> DatabaseValue } /// A custom SQL aggregate window function. public protocol SQLAggregateWindowFunction: SQLAggregateFunction { /// Invokes the inverse aggregate function for one or more values in a row. /// /// - parameter values: The SQL function parameters /// /// - throws: `Error` func inverse(_ values: [DatabaseValue]) throws /// Returns the current value of the aggregate window function. /// /// - throws: `Error` /// /// - returns: The current value of the aggregate window function. func value() throws -> DatabaseValue } extension Database { /// Adds a custom SQL scalar function. /// /// For example, a localized uppercase scalar function could be implemented as: /// ```swift /// try db.addFunction("localizedUppercase", arity: 1) { values in /// let value = values.first.unsafelyUnwrapped /// switch value { /// case .text(let s): /// return .text(s.localizedUppercase()) /// default: /// return value /// } /// } /// ``` /// /// - parameter name: The name of the function /// - parameter arity: The number of arguments the function accepts /// - parameter flags: Flags affecting the function's use by SQLite /// - parameter block: A closure that returns the result of applying the function to the supplied arguments /// /// - throws: An error if the SQL scalar function couldn't be added /// /// - seealso: [Create Or Redefine SQL Functions](https://sqlite.org/c3ref/create_function.html) public func addFunction(_ name: String, arity: Int = -1, flags: SQLFunctionFlags = [.deterministic, .directOnly], _ block: @escaping SQLFunction) throws { let function_ptr = UnsafeMutablePointer<SQLFunction>.allocate(capacity: 1) function_ptr.initialize(to: block) let function_flags = SQLITE_UTF8 | flags.asSQLiteFlags() guard sqlite3_create_function_v2(db, name, Int32(arity), function_flags, function_ptr, { sqlite_context, argc, argv in let context = sqlite3_user_data(sqlite_context) let function_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLFunction.self) let args = UnsafeBufferPointer(start: argv, count: Int(argc)) let arguments = args.map { DatabaseValue($0.unsafelyUnwrapped) } do { set_sqlite3_result(sqlite_context, value: try function_ptr.pointee(arguments)) } catch let error { sqlite3_result_error(sqlite_context, "\(error)", -1) } }, nil, nil, { context in let function_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLFunction.self) function_ptr.deinitialize(count: 1) function_ptr.deallocate() }) == SQLITE_OK else { throw SQLiteError("Error adding SQL scalar function \"\(name)\"", takingDescriptionFromDatabase: db) } } /// Adds a custom SQL aggregate function. /// /// For example, an integer sum aggregate function could be implemented as: /// ```swift /// class IntegerSumAggregateFunction: SQLAggregateFunction { /// func step(_ values: [DatabaseValue]) throws { /// let value = values.first.unsafelyUnwrapped /// switch value { /// case .integer(let i): /// sum += i /// default: /// throw DatabaseError("Only integer values supported") /// } /// } /// /// func final() throws -> DatabaseValue { /// defer { /// sum = 0 /// } /// return DatabaseValue(sum) /// } /// /// var sum: Int64 = 0 /// } /// ``` /// /// - parameter name: The name of the aggregate function /// - parameter arity: The number of arguments the function accepts /// - parameter flags: Flags affecting the function's use by SQLite /// - parameter aggregateFunction: An object defining the aggregate function /// /// - throws: An error if the SQL aggregate function can't be added /// /// - seealso: [Create Or Redefine SQL Functions](https://sqlite.org/c3ref/create_function.html) public func addAggregateFunction(_ name: String, arity: Int = -1, flags: SQLFunctionFlags = [.deterministic, .directOnly], _ function: SQLAggregateFunction) throws { // function must live until the xDelete function is invoked let context_ptr = UnsafeMutablePointer<SQLAggregateFunction>.allocate(capacity: 1) context_ptr.initialize(to: function) let function_flags = SQLITE_UTF8 | flags.asSQLiteFlags() guard sqlite3_create_function_v2(db, name, Int32(arity), function_flags, context_ptr, nil, { sqlite_context, argc, argv in let context = sqlite3_user_data(sqlite_context) let context_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLAggregateFunction.self) let function = context_ptr.pointee let args = UnsafeBufferPointer(start: argv, count: Int(argc)) let arguments = args.map { DatabaseValue($0.unsafelyUnwrapped) } do { try function.step(arguments) } catch let error { sqlite3_result_error(sqlite_context, "\(error)", -1) } }, { sqlite_context in let context = sqlite3_user_data(sqlite_context) let context_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLAggregateFunction.self) let function = context_ptr.pointee do { set_sqlite3_result(sqlite_context, value: try function.final()) } catch let error { sqlite3_result_error(sqlite_context, "\(error)", -1) } }, { context in let context_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLAggregateFunction.self) context_ptr.deinitialize(count: 1) context_ptr.deallocate() }) == SQLITE_OK else { throw SQLiteError("Error adding SQL aggregate function \"\(name)\"", takingDescriptionFromDatabase: db) } } /// Adds a custom SQL aggregate window function. /// /// For example, an integer sum aggregate window function could be implemented as: /// ```swift /// class IntegerSumAggregateWindowFunction: SQLAggregateWindowFunction { /// func step(_ values: [DatabaseValue]) throws { /// let value = values.first.unsafelyUnwrapped /// switch value { /// case .integer(let i): /// sum += i /// default: /// throw DatabaseError("Only integer values supported") /// } /// } /// /// func inverse(_ values: [DatabaseValue]) throws { /// let value = values.first.unsafelyUnwrapped /// switch value { /// case .integer(let i): /// sum -= i /// default: /// throw DatabaseError("Only integer values supported") /// } /// } /// /// func value() throws -> DatabaseValue { /// return DatabaseValue(sum) /// } /// /// func final() throws -> DatabaseValue { /// defer { /// sum = 0 /// } /// return DatabaseValue(sum) /// } /// /// var sum: Int64 = 0 /// } /// ``` /// /// - parameter name: The name of the aggregate window function /// - parameter arity: The number of arguments the function accepts /// - parameter flags: Flags affecting the function's use by SQLite /// - parameter aggregateWindowFunction: An object defining the aggregate window function /// /// - throws: An error if the SQL aggregate window function can't be added /// /// - seealso: [User-Defined Aggregate Window Functions](https://sqlite.org/windowfunctions.html#udfwinfunc) public func addAggregateWindowFunction(_ name: String, arity: Int = -1, flags: SQLFunctionFlags = [.deterministic, .directOnly], _ function: SQLAggregateWindowFunction) throws { let context_ptr = UnsafeMutablePointer<SQLAggregateWindowFunction>.allocate(capacity: 1) context_ptr.initialize(to: function) let function_flags = SQLITE_UTF8 | flags.asSQLiteFlags() guard sqlite3_create_window_function(db, name, Int32(arity), function_flags, context_ptr, { sqlite_context, argc, argv in let context = sqlite3_user_data(sqlite_context) let context_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLAggregateWindowFunction.self) let function = context_ptr.pointee let args = UnsafeBufferPointer(start: argv, count: Int(argc)) let arguments = args.map { DatabaseValue($0.unsafelyUnwrapped) } do { try function.step(arguments) } catch let error { sqlite3_result_error(sqlite_context, "\(error)", -1) } }, { sqlite_context in let context = sqlite3_user_data(sqlite_context) let context_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLAggregateWindowFunction.self) let function = context_ptr.pointee do { set_sqlite3_result(sqlite_context, value: try function.final()) } catch let error { sqlite3_result_error(sqlite_context, "\(error)", -1) } }, { sqlite_context in let context = sqlite3_user_data(sqlite_context) let context_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLAggregateWindowFunction.self) let function = context_ptr.pointee do { set_sqlite3_result(sqlite_context, value: try function.value()) } catch let error { sqlite3_result_error(sqlite_context, "\(error)", -1) } }, { sqlite_context, argc, argv in let context = sqlite3_user_data(sqlite_context) let context_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLAggregateWindowFunction.self) let function = context_ptr.pointee let args = UnsafeBufferPointer(start: argv, count: Int(argc)) let arguments = args.map { DatabaseValue($0.unsafelyUnwrapped) } do { try function.inverse(arguments) } catch let error { sqlite3_result_error(sqlite_context, "\(error)", -1) } }, { context in let context_ptr = context.unsafelyUnwrapped.assumingMemoryBound(to: SQLAggregateWindowFunction.self) context_ptr.deinitialize(count: 1) context_ptr.deallocate() }) == SQLITE_OK else { throw SQLiteError("Error adding SQL aggregate window function \"\(name)\"", takingDescriptionFromDatabase: db) } } /// Removes a custom SQL scalar, aggregate, or window function. /// /// - parameter name: The name of the custom SQL function /// - parameter arity: The number of arguments the custom SQL function accepts /// /// - throws: An error if the SQL function couldn't be removed public func removeFunction(_ name: String, arity: Int = -1) throws { guard sqlite3_create_function_v2(db, name, Int32(arity), SQLITE_UTF8, nil, nil, nil, nil, nil) == SQLITE_OK else { throw SQLiteError("Error removing SQL function \"\(name)\"", takingDescriptionFromDatabase: db) } } } /// Passes `value` to the appropriate `sqlite3_result` function /// /// - parameter sqlite_context: An `sqlite3_context *` object /// - parameter value: The value to pass func set_sqlite3_result(_ sqlite_context: OpaquePointer!, value: DatabaseValue) { switch value { case .integer(let i): sqlite3_result_int64(sqlite_context, i) case .float(let f): sqlite3_result_double(sqlite_context, f) case .text(let t): sqlite3_result_text(sqlite_context, t, -1, SQLITE_TRANSIENT) case .blob(let b): b.withUnsafeBytes { bytes in sqlite3_result_blob(sqlite_context, bytes.baseAddress, Int32(b.count), SQLITE_TRANSIENT) } case .null: sqlite3_result_null(sqlite_context) } }
mit
dd211653734dc0620649af739d3814b9
35.376658
178
0.682223
3.806273
false
false
false
false
Mosquito1123/WTPhotoBrowser
Example/Pods/ZWTPhotoBrowser/PhotoBrowser/WTPhotoTransition.swift
1
4373
// // PhotoTransition.swift // PhotoBrowser-swift // // Created by zhangwentong on 2017/5/30. // Copyright © 2017年 YiXue. All rights reserved. // import UIKit enum WTPhotoTransitionStyle { case present case dismiss } class WTPhotoTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning { var style: WTPhotoTransitionStyle var animationDuration: TimeInterval = 0.5 init(style: WTPhotoTransitionStyle) { self.style = style super.init() } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return animationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView switch style { case .present: let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! WTPhotoBrowser containerView.addSubview(toVC.view) toVC.view.alpha = 0 if let sourceImageView = toVC.sourceImageView, let sourceImage = sourceImageView.image { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.image = sourceImage imageView.frame = sourceImageView.superview?.convert(sourceImageView.frame, to: toVC.view) ?? CGRect.zero toVC.view.insertSubview(imageView, at: 1) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: { toVC.view.alpha = 1 imageView.frame = sourceImage.frameWithScreenWidth }, completion: { (_) in imageView.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) }else { UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { toVC.view.alpha = 1 }, completion: { (_) in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } case .dismiss: let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! WTPhotoBrowser if let sourceImageView = fromVC.sourceImageView, let displayImageView = fromVC.displayImageView { displayImageView.frame = displayImageView.superview?.convert(displayImageView.frame, to: containerView) ?? CGRect.zero containerView.addSubview(displayImageView) UIView.animate(withDuration: transitionDuration(using: transitionContext) * 0.5, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { fromVC.view.alpha = 0 displayImageView.frame = sourceImageView.superview?.convert(sourceImageView.frame, to: containerView) ?? CGRect.zero }, completion: { (_) in displayImageView.removeFromSuperview() transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) }else { UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { fromVC.view.alpha = 0 }, completion: { (_) in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } break } } }
mit
06094646363499996f2b19ccaa727da0
36.672414
198
0.5627
7.094156
false
false
false
false
urbn/URBNValidator
Pod/Classes/URBNValidator.swift
1
10275
// // URBNValidator.swift // URBNValidator // // Created by Joseph Ridenour on 11/17/15. // Copyright © 2015 URBN. All rights reserved. // import Foundation /** Validateable objects are meant to allow direct validation of keys/values of a given model by defining a validationMap which contains a map of keys -> ValidatingValue's */ public protocol Validateable { associatedtype V func validationMap() -> [String: ValidatingValue<V>] } /** This wraps up a value with it's list of rules to validate against. */ public struct ValidatingValue<V> { public var value: V? public var rules: [ValidationRule] public init(_ value: V?, rules: [ValidationRule]) { self.value = value self.rules = rules } public init(value: V?, rules: ValidationRule...) { self.init(value, rules: rules) } } /** # Validator This is our main validation protocol. Any object that you want to be a validator, you can simply conform to this protocol and implement the initializer. By default we provide implementations for all of the properties and functions listed here. */ public protocol Validator { /** This is used for building the localization key strings. Takes the rule and the field currently being localized. By default this generates `ls_URBNValidator_URBNValidator.{rule.localizationKey}` */ var localizationKeyBuilder: (ValidationRule, String) -> String { get } /** You'll probably never need to override this unless you're using a specific bundle other than the bundle of this class. - note: We'll handle falling back to the mainBundle for any localizations for free, so you don't have to override this if you're just trying to localize with the main bundle */ var localizationBundle: Bundle { get } // You'll probably never use this. But just incase here's a prop for it var localizationTable: String? { get } /** Designated initializer for validators. - parameter bundle: Optional `NSBundle` to use for localizations */ init(bundle: Bundle?) /** This validates a single value with a single rule. The key is only used for display purposes. It will be used to replace {{field}} in the localization. - parameters: - key: The key used to replace {{field}} in the localization - value: The value to validate with - rule: The rule to run the validation against - throws: An instance of NSError with the localized data */ func validate<V>(_ key: String, value: V?, rule: ValidationRule) throws /** The purpose of this method is to validate the given model. This will run through the model.validationMap and run validations on each one of the key -> Rules pairs. - parameters: - item: a validateable item to be used for validation - stopOnFirstError: indicates that you only care about the first error - throws: An instance of NSError representing the invalid data */ func validate<V: Validateable>(_ item: V , stopOnFirstError: Bool) throws /** The purpose of this method is to validate the given model. This will run through the model.validationMap and run validations on each one of the key -> Rules pairs. - parameters: - item: a validateable item to be used for validation - ignoreList: List of keys that should not be validated - stopOnFirstError: indicates that you only care about the first error - throws: An instance of NSError representing the invalid data */ func validate<V: Validateable>(_ item: V, ignoreList: [String], stopOnFirstError: Bool) throws /** The purpose of this function is to wrap up our localization fallback logic, and handle replacing any values necessary in the result of the localized string - parameters: - rule: The validation rule to localize against - key: The key to inject into the localization (if applicable). Replaces the {{field}} - value: The value to inject into the localization (if applicable). Replaces the {{value}} */ func localizeableString(_ rule: ValidationRule, key: String, value: Any?) -> String } private let DefaultBundle = Bundle(identifier: "org.cocoapods.URBNValidator") ?? Bundle.main private let DefaultLocalizationKeyBuilder: (ValidationRule, String) -> String = { rule, key in "ls_URBNValidator_URBNValidator.\(rule.localizationKey)" } // MARK: - Default Implementations extension Validator { public var localizationBundle: Bundle { return DefaultBundle } public var localizationTable: String? { return nil } public var localizationKeyBuilder: (ValidationRule, String) -> String { return DefaultLocalizationKeyBuilder } public func validate<V>(_ key: String, value: V?, rule: ValidationRule) throws { if rule.validateValue(value) { return } throw NSError.fieldError(key, description: localizeableString(rule, key: key, value: value)) } public func validate<V: Validateable>(_ item: V, stopOnFirstError: Bool = false) throws { do { try self.validate(item, ignoreList: [], stopOnFirstError: stopOnFirstError) } catch let e { throw e } } public func validate<V: Validateable>(_ item: V, ignoreList: [String], stopOnFirstError: Bool = false) throws { /// Nothing to validate here. We're all good if item.validationMap().length == 0 { return } // We want to get our validationMap minus the items in the ignoreList let vdMap = item.validationMap().filter { !ignoreList.contains($0.0) } let errs = try vdMap.flatMap({ (key, value) -> [NSError]? in let rules = implicitelyRequiredRules(value.rules) return try rules.flatMap({ (rule) throws -> NSError? in do { try validate(key, value: value.value, rule: rule) return nil } catch let err as NSError { if stopOnFirstError { throw err } return err } }) }).flatMap { $0 } if errs.count > 0 { throw NSError.multiErrorWithErrors(errs) } } public func localizeableString(_ rule: ValidationRule, key: String, value: Any?) -> String { let ruleKey = localizationKeyBuilder(rule, key) // First we try to localize against the mainBundle. let mainBundleStr = NSLocalizedString(ruleKey, tableName: self.localizationTable, comment: "") let str = NSLocalizedString(mainBundleStr, tableName: self.localizationTable, bundle: self.localizationBundle, comment: "") // Now we're going to regex the resulting string and replace {{field}}, {{value}} var replacementValue: String = "" if let repValue = value as? CustomStringConvertible { replacementValue = repValue.description } let options: NSRegularExpression.Options = [NSRegularExpression.Options.caseInsensitive] return [ // Considering the try! fine here because this is a dev issue. If you write an invalid // regex, then that's your own fault. Once it's written properly it's guaranteed to not crash key: try! NSRegularExpression(pattern: "\\{\\{field\\}\\}", options: options), replacementValue: try! NSRegularExpression(pattern: "\\{\\{value\\}\\}", options: options), ].reduce(str) { (s, replacement: (key: String, pattern: NSRegularExpression)) -> String in return replacement.pattern.stringByReplacingMatches(in: s, options: .reportCompletion, range: NSMakeRange(0, (s as NSString).length), withTemplate: replacement.key ) } } // MARK: - Internal - /** This takes an array of `ValidationRule` and inserts an URBNRequiredRule if necessary. If the list already contains a requirement rule (`URBNRequiredRule` or `URBNNotRequiredRule`), then we'll return the original list. Otherwise, we'll add a requirement at the beginning of the list - parameter rules: The rules to do this implicit orchestration with - returns: The resulting rules to use for validation */ internal func implicitelyRequiredRules(_ rules: [ValidationRule]) -> [ValidationRule] { // Sanity if rules.count == 0 { return rules } // If our rules do not contain any URBNRequirement rules, then // we can safely skip the next part if !rules.contains(where: { $0 is URBNRequirement}) { return rules } let isRequired = rules.contains(where: { $0 is URBNNotRequiredRule }) == false let hasRequirement = rules.contains(where: { $0 is URBNRequiredRule || $0 is URBNNotRequiredRule }) let updatedRules = hasRequirement ? rules : ([URBNRequiredRule()] + rules) return updatedRules.map({ (r) -> ValidationRule in if var rr = r as? URBNRequirement { rr.isRequired = isRequired } return r }) } } /** This is the main URBNValidator object. Used to validate objects and localize the results in a nice way. */ // MARK: - URBNValidator - public struct URBNValidator: Validator { public var localizationBundle: Bundle = DefaultBundle public var localizationTable: String? = nil public var localizationKeyBuilder: (ValidationRule, String) -> String = DefaultLocalizationKeyBuilder public init(bundle: Bundle? = nil) { if let bundle = bundle { localizationBundle = bundle } } }
mit
78bae8bb44337b044941deff79996963
36.090253
153
0.624586
5.053615
false
false
false
false
BitBaum/Swift-Big-Integer
Sources/Swift-Big-Number-Core.swift
1
98471
// // ———————————————————————————————————————————————————————————————————————————————————————————— // ||||||||| Swift-Big-Number-Core.swift |||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // Created by Marcel Kröker on 30.09.16. // Copyright (c) 2016 Blubyte. All rights reserved. // // // // ——————————————————————————————————————————— v1.0 ——————————————————————————————————————————— // - Initial Release. // // ——————————————————————————————————————————— v1.1 ——————————————————————————————————————————— // - Improved String conversion, now about 45x faster, uses base 10^9 instead // of base 10. // - bytes renamed to limbs. // - Uses typealias for limbs and digits. // // ——————————————————————————————————————————— v1.2 ——————————————————————————————————————————— // - Improved String conversion, now about 10x faster, switched from base 10^9 // to 10^18 (biggest possible decimal base). // - Implemented karatsuba multiplication algorithm, about 5x faster than the // previous algorithm. // - Addition is 1.3x faster. // - Addtiton and subtraction omit trailing zeros, algorithms need less // operations now. // - Implemented exponentiation by squaring. // - New storage (BStorage) for often used results. // - Uses uint_fast64_t instead of UInt64 for Limbs and Digits. // // ——————————————————————————————————————————— v1.3 ——————————————————————————————————————————— // - Huge Perfomance increase by skipping padding zeros and new multiplication // algotithms. // - Printing is now about 10x faster, now on par with GMP. // - Some operations now use multiple cores. // // ——————————————————————————————————————————— v1.4 ——————————————————————————————————————————— // - Reduced copying by using more pointers. // - Multiplication is about 50% faster. // - String to BInt conversion is 2x faster. // - BInt to String also performs 50% better. // // ——————————————————————————————————————————— v1.5 ——————————————————————————————————————————— // - Updated for full Swift 3 compatibility. // - Various optimizations: // - Multiplication is about 2x faster. // - BInt to String conversion is more than 3x faster. // - String to BInt conversion is more than 2x faster. // // ——————————————————————————————————————————— v1.6 ——————————————————————————————————————————— // - Code refactored into modules. // - Renamed the project to SMP (Swift Multiple Precision). // - Added arbitrary base conversion. // // ——————————————————————————————————————————— v2.0 ——————————————————————————————————————————— // - Updated for full Swift 4 compatibility. // - Big refactor, countless optimizations for even better performance. // - BInt conforms to SignedNumeric and BinaryInteger, this makes it very easy to write // generic code. // - BDouble also conforms to SignedNumeric and has new functionalities. // // // // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||||||||||| Evolution |||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // // // // Planned features of BInt v3.0: // - Implement some basic cryptography functions. // - General code cleanup, better documentation. // - More extensive tests. // - Please contact me if you have any suggestions for new features! // // // // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||||||||||| Basic Project syntax conventions |||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // // Indentation: Tabs // // Align: Spaces // // Style: allman // func foo(...) // { // ... // } // // Single line if-statement: // if condition { code } // // Maximum line length: 96 characters // // ———————————————————————————————————————————————————————————————————————————————————————————— // MARK: - Imports // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||| Imports ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— import Foundation // MARK: - Typealiases // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||| Typealiases ||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // Limbs are basically single Digits in base 2^64. Each slot in an Limbs array stores one // Digit of the number. The least significant digit is stored at index 0, the most significant // digit is stored at the last index. public typealias Limbs = [UInt64] public typealias Limb = UInt64 // A digit is a number in base 10^18. This is the biggest possible base that // fits into an unsigned 64 bit number while maintaining the propery that the square root of // the base is a whole number and a power of ten . Digits are required for printing BInt // numbers. Limbs are converted into Digits first, and then printed. public typealias Digits = [UInt64] public typealias Digit = UInt64 // MARK: - Imports // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||| Operators ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— precedencegroup ExponentiationPrecedence { associativity: left higherThan: MultiplicationPrecedence lowerThan: BitwiseShiftPrecedence } // Exponentiation operator infix operator ** : ExponentiationPrecedence // MARK: - BInt // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||| BInt |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— /// BInt is an arbitrary precision integer value type. It stores a number in base 2^64 notation /// as an array. Each element of the array is called a limb, which is of type UInt64, the whole /// array is called limbs and has the type [UInt64]. A boolean sign variable determines if the /// number is positive or negative. If sign == true, then the number is smaller than 0, /// otherwise it is greater or equal to 0. It stores the 64 bit digits in little endian, that /// is, the least significant digit is stored in the array index 0: /// /// limbs == [] := undefined, should throw an error /// limbs == [0], sign == false := 0, defined as positive /// limbs == [0], sign == true := undefined, should throw an error /// limbs == [n] := n if sign == false, otherwise -n, given 0 <= n < 2^64 /// /// limbs == [l0, l1, l2, ..., ln] := /// (l0 * 2^(0*64)) + /// (11 * 2^(1*64)) + /// (12 * 2^(2*64)) + /// ... + /// (ln * 2^(n*64)) public struct BInt: SignedNumeric, // Implies Numeric, Equatable, ExpressibleByIntegerLiteral BinaryInteger, // Implies Hashable, CustomStringConvertible, Strideable, Comparable ExpressibleByFloatLiteral { // // // MARK: - Internal data // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Internal data ||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /// Stores the sign of the number represented by the BInt. "true" means that the number is /// less than zero, "false" means it's more than or equal to zero. internal var sign = false /// Stores the absolute value of the number represented by the BInt. Each element represents /// a "digit" of the number in base 2^64 in an acending order, where the first element is /// the least significant "digit". This representations is the most efficient one for /// computations, however it also means that the number is stored in a non-human-readable /// fashion. To make it readable as a decimal number, BInt offers the required functions. internal var limbs = Limbs() // Required by the protocol "Numeric". public typealias Magnitude = UInt64 // Required by the protocol "Numeric". It's pretty useless because the magnitude of a BInt won't // fit into a UInt64 generally, so we just return the first limb of the BInt. public var magnitude: UInt64 { return self.limbs[0] } // Required by the protocol "BinaryInteger". public typealias Words = [UInt] // Required by the protocol "BinaryInteger". public var words: BInt.Words { return self.limbs.map{ UInt($0) } } /// Returns the size of the BInt in bits. public var size: Int { return 1 + (self.limbs.count * MemoryLayout<Limb>.size * 8) } /// Returns a formated human readable string that says how much space (in bytes, kilobytes, megabytes, or gigabytes) the BInt occupies. public var sizeDescription: String { // One bit for the sign, plus the size of the limbs. let bits = self.size if bits < 8_000 { return String(format: "%.1f b", Double(bits) / 8.0) } if bits < 8_000_000 { return String(format: "%.1f kb", Double(bits) / 8_000.0) } if UInt64(bits) < UInt64(8_000_000_000.0) { return String(format: "%.1f mb", Double(bits) / 8_000_000.0) } return String(format: "%.1f gb", Double(bits) / 8_000_000_000.0) } // // // MARK: - Initializers // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Initializers |||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /// Root initializer for all other initializers. Because no sign is provided, the new /// instance is positive by definition. internal init(limbs: Limbs) { precondition(limbs != [], "BInt can't be initialized with limbs == []") self.limbs = limbs } /// Create an instance initialized with a sign and a limbs array. internal init(sign: Bool, limbs: Limbs) { self.init(limbs: limbs) self.sign = sign } /// Create an instance initialized with the value 0. init() { self.init(limbs: [0]) } /// Create an instance initialized to an integer value. public init(_ z: Int) { // Since abs(Int.min) > Int.max, it is necessary to handle // z == Int.min as a special case. if z == Int.min { self.init(sign: true, limbs: [Limb(Int.max) + 1]) return } else { self.init(sign: z < 0, limbs: [Limb(abs(z))]) } } /// Create an instance initialized to an unsigned integer value. public init(_ n: UInt) { self.init(limbs: [Limb(n)]) } /// Create an instance initialized to a string value. public init?(_ str: String) { var (str, sign, base, limbs) = (str, false, [Limb(1)], [Limb(0)]) limbs.reserveCapacity(Int(Double(str.count) / log10(pow(2.0, 64.0)))) if str.hasPrefix("-") { str.remove(at: str.startIndex) sign = str != "0" } for chunk in String(str.reversed()).split(19).map({ String($0.reversed()) }) { if let num = Limb(String(chunk)) { limbs.addProductOf(multiplier: base, multiplicand: num) base = base.multiplyingBy([10_000_000_000_000_000_000]) } else { return nil } } self.init(sign: sign, limbs: limbs) } /// Create an instance initialized to a string with the value of mathematical numerical /// system of the specified radix (base). So for example, to get the value of hexadecimal /// string radix value must be set to 16. public init?(_ number: String, radix: Int) { if radix == 10 { // Regular string init is faster for decimal numbers. self.init(number) return } let chars: [Character] = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ] var (number, sign, base, limbs) = (number, false, [Limb(1)], [Limb(0)]) if number.hasPrefix("-") { number.remove(at: number.startIndex) sign = number != "0" } for char in number.reversed() { if let digit = chars.index(of: char), digit < radix { limbs.addProductOf(multiplier: base, multiplicand: Limb(digit)) base = base.multiplyingBy([Limb(radix)]) } else { return nil } } self.init(sign: sign, limbs: limbs) } /// Create an instance initialized to a string with the value of mathematical numerical /// system of the specified radix (base). You have to specify the base as a prefix, so for /// example, "0b100101010101110" is a vaild input for a binary number. Currently, /// hexadecimal (0x), octal (0o) and binary (0b) are supported. public init?(prefixedNumber number: String) { if number.hasPrefix("0x") { self.init(String(number.dropFirst(2)), radix: 16) } if number.hasPrefix("0o") { self.init(String(number.dropFirst(2)), radix: 8) } if number.hasPrefix("0b") { self.init(String(number.dropFirst(2)), radix: 2) } else { return nil } } // Requierd by protocol ExpressibleByFloatLiteral. public init(floatLiteral value: Double) { self.init(sign: value < 0.0, limbs: [Limb(value)]) } // Required by protocol ExpressibleByIntegerLiteral. public init(integerLiteral value: Int) { self.init(value) } // Required by protocol Numeric public init?<T>(exactly source: T) where T : BinaryInteger { self.init(Int(source)) } /// Creates an integer from the given floating-point value, rounding toward zero. public init<T>(_ source: T) where T : BinaryFloatingPoint { self.init(Int(source)) } /// Creates a new instance from the given integer. public init<T>(_ source: T) where T : BinaryInteger { self.init(Int(source)) } /// Creates a new instance with the representable value that’s closest to the given integer. public init<T>(clamping source: T) where T : BinaryInteger { self.init(Int(source)) } /// Creates an integer from the given floating-point value, if it can be represented /// exactly. public init?<T>(exactly source: T) where T : BinaryFloatingPoint { self.init(source) } /// Creates a new instance from the bit pattern of the given instance by sign-extending or /// truncating to fit this type. public init<T>(truncatingIfNeeded source: T) where T : BinaryInteger { self.init(source) } // // // MARK: - Struct functions // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Struct functions |||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // // Required by protocol CustomStringConvertible. public var description: String { return (self.sign ? "-" : "").appending(self.limbs.decimalRepresentation) } /// Returns the BInt's value in the given base (radix) as a string. public func asString(radix: Int) -> String { let chars: [Character] = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ] var (limbs, res) = (self.limbs, "") while !limbs.equalTo(0) { let divmod = limbs.divMod([Limb(radix)]) if let r = divmod.remainder.first, r < radix { res.append(chars[Int(r)]) limbs = divmod.quotient } else { fatalError("BInt.asString: Base too big, should be between 2 and 62") } } if res == "" { return "0" } return (self.sign ? "-" : "").appending(String(res.reversed())) } /// Returns BInt's value as an integer. Conversion only works when self has only one limb /// that's within the range of the type "Int". func asInt() -> Int? { if self.limbs.count != 1 { return nil } let number = self.limbs[0] if number <= Limb(Int.max) { return self.sign ? -Int(number) : Int(number) } if number == (Limb(Int.max) + 1) && self.sign { // This is a special case where self == Int.min return Int.min } return nil } var rawValue: (sign: Bool, limbs: [UInt64]) { return (self.sign, self.limbs) } public var hashValue: Int { return "\(self.sign)\(self.limbs)".hashValue } // Required by the protocol "BinaryInteger". A Boolean value indicating whether this type is a // signed integer type. public static var isSigned: Bool { return true } // Required by the protocol "BinaryInteger". The number of bits in the current binary // representation of this value. public var bitWidth: Int { return self.limbs.bitWidth } /// Returns -1 if this value is negative and 1 if it’s positive; otherwise, 0. public func signum() -> BInt { if self.isZero() { return BInt(0) } else if self.isPositive() { return BInt(1) } else { return BInt(-1) } } func isPositive() -> Bool { return !self.sign } func isNegative() -> Bool { return self.sign } func isZero() -> Bool { return self.limbs[0] == 0 && self.limbs.count == 1 } func isNotZero() -> Bool { return self.limbs[0] != 0 || self.limbs.count > 1 } func isOdd() -> Bool { return self.limbs[0] & 1 == 1 } func isEven() -> Bool { return self.limbs[0] & 1 == 0 } /// The number of trailing zeros in this value’s binary representation. public var trailingZeroBitCount: Int { var i = 0 while true { if self.limbs.getBit(at: i) { return i } i += 1 } } // // // MARK: - BInt Shifts // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Shifts ||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public static func <<<T: BinaryInteger>(lhs: BInt, rhs: T) -> BInt { if rhs < 0 { return lhs >> rhs } let limbs = lhs.limbs.shiftingUp(Int(rhs)) let sign = lhs.isNegative() && !limbs.equalTo(0) return BInt(sign: sign, limbs: limbs) } public static func <<=<T: BinaryInteger>(lhs: inout BInt, rhs: T) { lhs.limbs.shiftUp(Int(rhs)) } public static func >><T: BinaryInteger>(lhs: BInt, rhs: T) -> BInt { if rhs < 0 { return lhs << rhs } return BInt(sign: lhs.sign, limbs: lhs.limbs.shiftingDown(Int(rhs))) } public static func >>=<T: BinaryInteger>(lhs: inout BInt, rhs: T) { lhs.limbs.shiftDown(Int(rhs)) } // // // MARK: - BInt Bitwise AND // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt BInt Bitwise AND ||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /// Returns the result of performing a bitwise AND operation on the two given values. public static func &(lhs: BInt, rhs: BInt) -> BInt { var res: Limbs = [0] for i in 0..<(64 * Swift.max(lhs.limbs.count, rhs.limbs.count)) { let newBit = lhs.limbs.getBit(at: i) && rhs.limbs.getBit(at: i) res.setBit(at: i, to: newBit) } return BInt(sign: lhs.sign && rhs.sign, limbs: res) } // static func &(lhs: Int, rhs: BInt) -> BInt // static func &(lhs: BInt, rhs: Int) -> BInt /// Stores the result of performing a bitwise AND operation on the two given values in the /// left-hand-side variable. public static func &=(lhs: inout BInt, rhs: BInt) { let res = lhs & rhs lhs = res } // static func &=(inout lhs: Int, rhs: BInt) // static func &=(inout lhs: BInt, rhs: Int) // // // MARK: - BInt Bitwise OR // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Bitwise OR ||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public static func |(lhs: BInt, rhs: BInt) -> BInt { var res: Limbs = [0] for i in 0..<(64 * Swift.max(lhs.limbs.count, rhs.limbs.count)) { let newBit = lhs.limbs.getBit(at: i) || rhs.limbs.getBit(at: i) res.setBit(at: i, to: newBit) } return BInt(sign: lhs.sign || rhs.sign, limbs: res) } // static func |(lhs: Int, rhs: BInt) -> BInt // static func |(lhs: BInt, rhs: Int) -> BInt // public static func |=(lhs: inout BInt, rhs: BInt) { let res = lhs | rhs lhs = res } // static func |=(inout lhs: Int, rhs: BInt) // static func |=(inout lhs: BInt, rhs: Int) // // // MARK: - BInt Bitwise OR // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Bitwise XOR |||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public static func ^(lhs: BInt, rhs: BInt) -> BInt { var res: Limbs = [0] for i in 0..<(64 * Swift.max(lhs.limbs.count, rhs.limbs.count)) { let newBit = lhs.limbs.getBit(at: i) != rhs.limbs.getBit(at: i) res.setBit(at: i, to: newBit) } return BInt(sign: lhs.sign != rhs.sign, limbs: res) } public static func ^=(lhs: inout BInt, rhs: BInt) { let res = lhs ^ rhs lhs = res } // // // MARK: - BInt Bitwise NOT // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Bitwise NOT |||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public prefix static func ~(x: BInt) -> BInt { var res = x.limbs for i in 0..<(res.bitWidth) { res.setBit(at: i, to: !res.getBit(at: i)) } while res.last! == 0 && res.count > 1 { res.removeLast() } return BInt(sign: !x.sign, limbs: res) } // // // MARK: - BInt Addition // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Addition ||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public prefix static func +(x: BInt) -> BInt { return x } // Required by protocol Numeric public static func +=(lhs: inout BInt, rhs: BInt) { if lhs.sign == rhs.sign { lhs.limbs.addLimbs(rhs.limbs) return } let rhsIsMin = rhs.limbs.lessThan(lhs.limbs) lhs.limbs.difference(rhs.limbs) lhs.sign = (rhs.sign && !rhsIsMin) || (lhs.sign && rhsIsMin) // DNF minimization if lhs.isZero() { lhs.sign = false } } // Required by protocol Numeric public static func +(lhs: BInt, rhs: BInt) -> BInt { var lhs = lhs lhs += rhs return lhs } static func +(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) + rhs } static func +(lhs: BInt, rhs: Int) -> BInt { return lhs + BInt(rhs) } static func +=(lhs: inout Int, rhs: BInt) { lhs += (BInt(lhs) + rhs).asInt()! } static func +=(lhs: inout BInt, rhs: Int) { lhs += BInt(rhs) } // // // MARK: - BInt Negation // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Negation ||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // // Required by protocol SignedNumeric public mutating func negate() { if self.isNotZero() { self.sign = !self.sign } } // Required by protocol SignedNumeric public static prefix func -(n: BInt) -> BInt { var n = n n.negate() return n } // // // MARK: - BInt Subtraction // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Subtraction |||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // // Required by protocol Numeric public static func -(lhs: BInt, rhs: BInt) -> BInt { return lhs + -rhs } static func -(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) - rhs } static func -(lhs: BInt, rhs: Int) -> BInt { return lhs - BInt(rhs) } // Required by protocol Numeric public static func -=(lhs: inout BInt, rhs: BInt) { lhs += -rhs } static func -=(lhs: inout Int, rhs: BInt) { lhs = (BInt(lhs) - rhs).asInt()! } static func -=(lhs: inout BInt, rhs: Int) { lhs -= BInt(rhs) } // // // MARK: - BInt Multiplication // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Multiplication ||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // // Required by protocol Numeric public static func *(lhs: BInt, rhs: BInt) -> BInt { let sign = !(lhs.sign == rhs.sign || lhs.isZero() || rhs.isZero()) return BInt(sign: sign, limbs: lhs.limbs.multiplyingBy(rhs.limbs)) } static func *(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) * rhs } static func *(lhs: BInt, rhs: Int) -> BInt { return lhs * BInt(rhs) } // Required by protocol SignedNumeric public static func *=(lhs: inout BInt, rhs: BInt) { lhs = lhs * rhs } static func *=(lhs: inout Int, rhs: BInt) { lhs = (BInt(lhs) * rhs).asInt()! } static func *=(lhs: inout BInt, rhs: Int) { lhs = lhs * BInt(rhs) } // // // MARK: - BInt Exponentiation // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Exponentiation ||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // static func **(lhs: BInt, rhs: Int) -> BInt { precondition(rhs >= 0, "BInts can't be exponentiated with exponents < 0") return BInt(sign: lhs.sign && (rhs % 2 != 0), limbs: lhs.limbs.exponentiating(rhs)) } func factorial() -> BInt { precondition(!self.sign, "Can't calculate the factorial of an negative number") return BInt(limbs: Limbs.recursiveMul(0, Limb(self.asInt()!))) } // // // MARK: - BInt Division // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Division ||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /// Returns the quotient and remainder of this value divided by the given value. public func quotientAndRemainder(dividingBy rhs: BInt) -> (quotient: BInt, remainder: BInt) { let limbRes = self.limbs.divMod(rhs.limbs) return (BInt(limbs: limbRes.quotient), BInt(limbs: limbRes.remainder)) } public static func /(lhs: BInt, rhs:BInt) -> BInt { let limbs = lhs.limbs.divMod(rhs.limbs).quotient let sign = (lhs.sign != rhs.sign) && !limbs.equalTo(0) return BInt(sign: sign, limbs: limbs) } static func /(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) / rhs } static func /(lhs: BInt, rhs: Int) -> BInt { return lhs / BInt(rhs) } public static func /=(lhs: inout BInt, rhs: BInt) { lhs = lhs / rhs } static func /=(lhs: inout BInt, rhs: Int) { lhs = lhs / BInt(rhs) } // // // MARK: - BInt Modulus // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Modulus |||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public static func %(lhs: BInt, rhs: BInt) -> BInt { let limbs = lhs.limbs.divMod(rhs.limbs).remainder let sign = lhs.sign && !limbs.equalTo(0) return BInt(sign: sign, limbs: limbs) } static func %(lhs: Int, rhs: BInt) -> BInt { return BInt(lhs) % rhs } static func %(lhs: BInt, rhs: Int) -> BInt { return lhs % BInt(rhs) } public static func %=(lhs: inout BInt, rhs: BInt) { lhs = lhs % rhs } static func %=(lhs: inout BInt, rhs: Int) { lhs = lhs % BInt(rhs) } // // // MARK: - BInt Comparing // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BInt Comparing |||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // // Required by protocol Equatable public static func ==(lhs: BInt, rhs: BInt) -> Bool { if lhs.sign != rhs.sign { return false } return lhs.limbs == rhs.limbs } static func ==<T: BinaryInteger>(lhs: BInt, rhs: T) -> Bool { if lhs.limbs.count != 1 { return false } return lhs.limbs[0] == rhs } static func ==<T: BinaryInteger>(lhs: T, rhs: BInt) -> Bool { return rhs == lhs } static func !=(lhs: BInt, rhs: BInt) -> Bool { if lhs.sign != rhs.sign { return true } return lhs.limbs != rhs.limbs } static func !=<T: BinaryInteger>(lhs: BInt, rhs: T) -> Bool { if lhs.limbs.count != 1 { return true } return lhs.limbs[0] != rhs } static func !=<T: BinaryInteger>(lhs: T, rhs: BInt) -> Bool { return rhs != lhs } // Required by protocol Comparable public static func <(lhs: BInt, rhs: BInt) -> Bool { if lhs.sign != rhs.sign { return lhs.sign } if lhs.sign { return rhs.limbs.lessThan(lhs.limbs) } return lhs.limbs.lessThan(rhs.limbs) } static func <<T: BinaryInteger>(lhs: BInt, rhs: T) -> Bool { if lhs.sign != (rhs < 0) { return lhs.sign } if lhs.sign { if lhs.limbs.count != 1 { return true } return rhs < lhs.limbs[0] } else { if lhs.limbs.count != 1 { return false } return lhs.limbs[0] < rhs } } static func <(lhs: Int, rhs: BInt) -> Bool { return BInt(lhs) < rhs } static func <(lhs: BInt, rhs: Int) -> Bool { return lhs < BInt(rhs) } // Required by protocol Comparable public static func >(lhs: BInt, rhs: BInt) -> Bool { return rhs < lhs } static func >(lhs: Int, rhs: BInt) -> Bool { return BInt(lhs) > rhs } static func >(lhs: BInt, rhs: Int) -> Bool { return lhs > BInt(rhs) } // Required by protocol Comparable public static func <=(lhs: BInt, rhs: BInt) -> Bool { return !(rhs < lhs) } static func <=(lhs: Int, rhs: BInt) -> Bool { return !(rhs < BInt(lhs)) } static func <=(lhs: BInt, rhs: Int) -> Bool { return !(BInt(rhs) < lhs) } // Required by protocol Comparable public static func >=(lhs: BInt, rhs: BInt) -> Bool { return !(lhs < rhs) } static func >=(lhs: Int, rhs: BInt) -> Bool { return !(BInt(lhs) < rhs) } static func >=(lhs: BInt, rhs: Int) -> Bool { return !(lhs < BInt(rhs)) } } // // // MARK: - String operations // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||| String operations ||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // // // fileprivate extension String { // Splits the string into equally sized parts (exept for the last one). func split(_ count: Int) -> [String] { return stride(from: 0, to: self.count, by: count).map { i -> String in let start = index(startIndex, offsetBy: i) let end = index(start, offsetBy: count, limitedBy: endIndex) ?? endIndex return String(self[start..<end]) } } } fileprivate let DigitBase: Digit = 1_000_000_000_000_000_000 fileprivate let DigitHalfBase: Digit = 1_000_000_000 fileprivate let DigitZeros = 18 fileprivate extension Array where Element == Limb { var decimalRepresentation: String { // First, convert limbs to digits var digits: Digits = [0] var power: Digits = [1] for limb in self { let digit = (limb >= DigitBase) ? [limb % DigitBase, limb / DigitBase] : [limb] digits.addProductOfDigits(digit, power) var nextPower: Digits = [0] nextPower.addProductOfDigits(power, [446_744_073_709_551_616, 18]) power = nextPower } // Then, convert digits to string var res = String(digits.last!) if digits.count == 1 { return res } for i in (0..<(digits.count - 1)).reversed() { let str = String(digits[i]) let leadingZeros = String(repeating: "0", count: DigitZeros - str.count) res.append(leadingZeros.appending(str)) } return res } } fileprivate extension Digit { mutating func addReportingOverflowDigit(_ addend: Digit) -> Bool { self = self &+ addend if self >= DigitBase { self -= DigitBase; return true } return false } func multipliedFullWidthDigit(by multiplicand: Digit) -> (Digit, Digit) { let (lLo, lHi) = (self % DigitHalfBase, self / DigitHalfBase) let (rLo, rHi) = (multiplicand % DigitHalfBase, multiplicand / DigitHalfBase) let K = (lHi * rLo) + (rHi * lLo) var resLo = (lLo * rLo) + ((K % DigitHalfBase) * DigitHalfBase) var resHi = (lHi * rHi) + (K / DigitHalfBase) if resLo >= DigitBase { resLo -= DigitBase resHi += 1 } return (resLo, resHi) } } fileprivate extension Array where Element == Digit { mutating func addOneDigit( _ addend: Limb, padding paddingZeros: Int ){ let sc = self.count if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) } if paddingZeros >= sc { self.append(addend); return } // Now, i < sc var i = paddingZeros let ovfl = self[i].addReportingOverflowDigit(addend) while ovfl { i += 1 if i == sc { self.append(1); return } self[i] += 1 if self[i] != DigitBase { return } self[i] = 0 } } mutating func addTwoDigit( _ addendLow: Limb, _ addendHigh: Limb, padding paddingZeros: Int) { let sc = self.count if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) } if paddingZeros >= sc { self += [addendLow, addendHigh]; return } // Now, i < sc var i = paddingZeros var newDigit: Digit let ovfl1 = self[i].addReportingOverflowDigit(addendLow) i += 1 if i == sc { newDigit = (addendHigh &+ (ovfl1 ? 1 : 0)) % DigitBase self.append(newDigit) if newDigit == 0 { self.append(1) } return } // Still, i < sc var ovfl2 = self[i].addReportingOverflowDigit(addendHigh) if ovfl1 { self[i] += 1 if self[i] == DigitBase { self[i] = 0; ovfl2 = true } } while ovfl2 { i += 1 if i == sc { self.append(1); return } self[i] += 1 if self[i] != DigitBase { return } self[i] = 0 } } mutating func addProductOfDigits(_ multiplier: Digits, _ multiplicand: Digits) { let (mpc, mcc) = (multiplier.count, multiplicand.count) self.reserveCapacity(mpc &+ mcc) var l, r, resLo, resHi: Digit for i in 0..<mpc { l = multiplier[i] if l == 0 { continue } for j in 0..<mcc { r = multiplicand[j] if r == 0 { continue } (resLo, resHi) = l.multipliedFullWidthDigit(by: r) if resHi == 0 { self.addOneDigit(resLo, padding: i + j) } else { self.addTwoDigit(resLo, resHi, padding: i + j) } } } } } // // // MARK: - Limbs extension // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||| Limbs extension ||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // // // // Extension to Limbs type fileprivate extension Array where Element == Limb { // // // MARK: - Limbs bitlevel // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Limbs bitlevel |||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /// Returns the number of bits that contribute to the represented number, ignoring all /// leading zeros. var bitWidth: Int { var lastBits = 0 var last = self.last! while last != 0 { last >>= 1 lastBits += 1 } return ((self.count - 1) * 64) + lastBits } /// Get bit i of limbs. func getBit(at i: Int) -> Bool { let limbIndex = Int(Limb(i) >> 6) if limbIndex >= self.count { return false } let bitIndex = Limb(i) & 0b111_111 return (self[limbIndex] & (1 << bitIndex)) != 0 } /// Set bit i of limbs to b. b must be 0 for false, and everything else for true. mutating func setBit( at i: Int, to bit: Bool ){ let limbIndex = Int(Limb(i) >> 6) if limbIndex >= self.count && !bit { return } let bitIndex = Limb(i) & 0b111_111 while limbIndex >= self.count { self.append(0) } if bit { self[limbIndex] |= (1 << bitIndex) } else { self[limbIndex] &= ~(1 << bitIndex) } } // // // MARK: - Limbs Shifting // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Limbs Shifting |||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // mutating func shiftUp(_ shift: Int) { // No shifting is required in this case if shift == 0 || self.equalTo(0) { return } let limbShifts = shift >> 6 let bitShifts = Limb(shift) & 0x3f if bitShifts != 0 { var previousCarry = Limb(0) var carry = Limb(0) var ele = Limb(0) // use variable to minimize array accesses for i in 0..<self.count { ele = self[i] carry = ele >> (64 - bitShifts) ele <<= bitShifts ele |= previousCarry // carry from last step previousCarry = carry self[i] = ele } if previousCarry != 0 { self.append(previousCarry) } } if limbShifts != 0 { self.insert(contentsOf: Limbs(repeating: 0, count: limbShifts), at: 0) } } func shiftingUp(_ shift: Int) -> Limbs { var res = self res.shiftUp(shift) return res } mutating func shiftDown(_ shift: Int) { if shift == 0 || self.equalTo(0) { return } let limbShifts = shift >> 6 let bitShifts = Limb(shift) & 0x3f if limbShifts >= self.count { self = [0] return } self.removeSubrange(0..<limbShifts) if bitShifts != 0 { var previousCarry = Limb(0) var carry = Limb(0) var ele = Limb(0) // use variable to minimize array accesses var i = self.count - 1 // use while for high performance while i >= 0 { ele = self[i] carry = ele << (64 - bitShifts) ele >>= bitShifts ele |= previousCarry previousCarry = carry self[i] = ele i -= 1 } } if self.last! == 0 && self.count != 1 { self.removeLast() } } func shiftingDown(_ shift: Int) -> Limbs { var res = self res.shiftDown(shift) return res } // // // MARK: - Limbs Addition // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Limbs Addition |||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // mutating func addLimbs(_ addend: Limbs) { let (sc, ac) = (self.count, addend.count) var (newLimb, ovfl) = (Limb(0), false) let minCount = Swift.min(sc, ac) var i = 0 while i < minCount { if ovfl { (newLimb, ovfl) = self[i].addingReportingOverflow(addend[i]) newLimb = newLimb &+ 1 ovfl = ovfl || newLimb == 0 } else { (newLimb, ovfl) = self[i].addingReportingOverflow(addend[i]) } self[i] = newLimb i += 1 } while ovfl { if i < sc { if i < ac { (newLimb, ovfl) = self[i].addingReportingOverflow(addend[i]) newLimb = newLimb &+ 1 ovfl = ovfl || newLimb == 0 } else { (newLimb, ovfl) = self[i].addingReportingOverflow(1) } self[i] = newLimb } else { if i < ac { (newLimb, ovfl) = addend[i].addingReportingOverflow(1) self.append(newLimb) } else { self.append(1) return } } i += 1 } if self.count < ac { self.append(contentsOf: addend.suffix(from: i)) } } /// Adding Limbs and returning result func adding(_ addend: Limbs) -> Limbs { var res = self res.addLimbs(addend) return res } // CURRENTLY NOT USED: /// Add the addend to Limbs, while using a padding at the lower end. /// Every zero is a Limb, that means one padding zero equals 64 padding bits mutating func addLimbs( _ addend: Limbs, padding paddingZeros: Int ){ let sc = self.count if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) } if paddingZeros >= sc { self += addend; return } // Now, i < sc let ac = addend.count &+ paddingZeros var (newLimb, ovfl) = (Limb(0), false) let minCount = Swift.min(sc, ac) var i = paddingZeros while i < minCount { if ovfl { (newLimb, ovfl) = self[i].addingReportingOverflow(addend[i &- paddingZeros]) newLimb = newLimb &+ 1 self[i] = newLimb ovfl = ovfl || newLimb == 0 } else { (self[i], ovfl) = self[i].addingReportingOverflow(addend[i &- paddingZeros]) } i += 1 } while ovfl { if i < sc { let adding = i < ac ? addend[i &- paddingZeros] &+ 1 : 1 (self[i], ovfl) = self[i].addingReportingOverflow(adding) ovfl = ovfl || adding == 0 } else { if i < ac { (newLimb, ovfl) = addend[i &- paddingZeros].addingReportingOverflow(1) self.append(newLimb) } else { self.append(1) return } } i += 1 } if self.count < ac { self.append(contentsOf: addend.suffix(from: i &- paddingZeros)) } } mutating func addOneLimb( _ addend: Limb, padding paddingZeros: Int ){ let sc = self.count if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) } if paddingZeros >= sc { self.append(addend); return } // Now, i < lhc var i = paddingZeros var ovfl: Bool (self[i], ovfl) = self[i].addingReportingOverflow(addend) while ovfl { i += 1 if i == sc { self.append(1); return } (self[i], ovfl) = self[i].addingReportingOverflow(1) } } /// Basically self.addOneLimb([addendLow, addendHigh], padding: paddingZeros), but faster mutating func addTwoLimb( _ addendLow: Limb, _ addendHigh: Limb, padding paddingZeros: Int) { let sc = self.count if paddingZeros > sc { self += Digits(repeating: 0, count: paddingZeros &- sc) } if paddingZeros >= sc { self += [addendLow, addendHigh]; return } // Now, i < sc var i = paddingZeros var newLimb: Limb var ovfl1: Bool (self[i], ovfl1) = self[i].addingReportingOverflow(addendLow) i += 1 if i == sc { newLimb = addendHigh &+ (ovfl1 ? 1 : 0) self.append(newLimb) if newLimb == 0 { self.append(1) } return } // Still, i < sc var ovfl2: Bool (self[i], ovfl2) = self[i].addingReportingOverflow(addendHigh) if ovfl1 { self[i] = self[i] &+ 1 if self[i] == 0 { ovfl2 = true } } while ovfl2 { i += 1 if i == sc { self.append(1); return } (self[i], ovfl2) = self[i].addingReportingOverflow(1) } } // // // MARK: - Limbs Subtraction // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Limbs Subtraction ||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /// Calculates difference between Limbs in left limb mutating func difference(_ subtrahend: Limbs) { var subtrahend = subtrahend // swap to get difference if self.lessThan(subtrahend) { swap(&self, &subtrahend) } let rhc = subtrahend.count var ovfl = false var i = 0 // skip first zeros while i < rhc && subtrahend[i] == 0 { i += 1 } while i < rhc { if ovfl { (self[i], ovfl) = self[i].subtractingReportingOverflow(subtrahend[i]) self[i] = self[i] &- 1 ovfl = ovfl || self[i] == Limb.max } else { (self[i], ovfl) = self[i].subtractingReportingOverflow(subtrahend[i]) } i += 1 } while ovfl { if i >= self.count { self.append(Limb.max) break } (self[i], ovfl) = self[i].subtractingReportingOverflow(1) i += 1 } if self.count > 1 && self.last! == 0 // cut excess zeros if required { var j = self.count - 2 while j >= 1 && self[j] == 0 { j -= 1 } self.removeSubrange((j + 1)..<self.count) } } func differencing(_ subtrahend: Limbs) -> Limbs { var res = self res.difference(subtrahend) return res } // // // MARK: - Limbs Multiplication // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Limbs Multiplication ||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // mutating func addProductOf( multiplier: Limbs, multiplicand: Limbs ){ let (mpc, mcc) = (multiplier.count, multiplicand.count) self.reserveCapacity(mpc + mcc) // Minimize array subscript calls var l, r, mulHi, mulLo: Limb for i in 0..<mpc { l = multiplier[i] if l == 0 { continue } for j in 0..<mcc { r = multiplicand[j] if r == 0 { continue } (mulHi, mulLo) = l.multipliedFullWidth(by: r) if mulHi != 0 { self.addTwoLimb(mulLo, mulHi, padding: i + j) } else { self.addOneLimb(mulLo, padding: i + j) } } } } // Perform res += (lhs * r) mutating func addProductOf( multiplier: Limbs, multiplicand: Limb ){ if multiplicand < 2 { if multiplicand == 1 { self.addLimbs(multiplier) } // If r == 0 then do nothing with res return } // Minimize array subscript calls var l, mulHi, mulLo: Limb for i in 0..<multiplier.count { l = multiplier[i] if l == 0 { continue } (mulHi, mulLo) = l.multipliedFullWidth(by: multiplicand) if mulHi != 0 { self.addTwoLimb(mulLo, mulHi, padding: i) } else { self.addOneLimb(mulLo, padding: i) } } } func multiplyingBy(_ multiplicand: Limbs) -> Limbs { var res: Limbs = [0] res.addProductOf(multiplier: self, multiplicand: multiplicand) return res } func squared() -> Limbs { var res: Limbs = [0] res.reserveCapacity(2 * self.count) // Minimize array subscript calls var l, r, mulHi, mulLo: Limb for i in 0..<self.count { l = self[i] if l == 0 { continue } for j in 0...i { r = self[j] if r == 0 { continue } (mulHi, mulLo) = l.multipliedFullWidth(by: r) if mulHi != 0 { if i != j { res.addTwoLimb(mulLo, mulHi, padding: i + j) } res.addTwoLimb(mulLo, mulHi, padding: i + j) } else { if i != j { res.addOneLimb(mulLo, padding: i + j) } res.addOneLimb(mulLo, padding: i + j) } } } return res } // // // MARK: - Limbs Exponentiation // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Limbs Exponentiation |||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // // Exponentiation by squaring func exponentiating(_ exponent: Int) -> Limbs { if exponent == 0 { return [1] } if exponent == 1 { return self } var base = self var exponent = exponent var y: Limbs = [1] while exponent > 1 { if exponent & 1 != 0 { y = y.multiplyingBy(base) } base = base.squared() exponent >>= 1 } return base.multiplyingBy(y) } /// Calculate (n + 1) * (n + 2) * ... * (k - 1) * k static func recursiveMul(_ n: Limb, _ k: Limb) -> Limbs { if n >= k - 1 { return [k] } let m = (n + k) >> 1 return recursiveMul(n, m).multiplyingBy(recursiveMul(m, k)) } func factorial(_ base: Int) -> BInt { return BInt(limbs: Limbs.recursiveMul(0, Limb(base))) } // // // MARK: - Limbs Division and Modulo // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Limbs Division and Modulo ||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /// An O(n) division algorithm that returns quotient and remainder. func divMod(_ divisor: Limbs) -> (quotient: Limbs, remainder: Limbs) { precondition(!divisor.equalTo(0), "Division or Modulo by zero not allowed") if self.equalTo(0) { return ([0], [0]) } var (quotient, remainder): (Limbs, Limbs) = ([0], [0]) var (previousCarry, carry, ele): (Limb, Limb, Limb) = (0, 0, 0) // bits of lhs minus one bit var i = (64 * (self.count - 1)) + Int(log2(Double(self.last!))) while i >= 0 { // shift remainder by 1 to the left for r in 0..<remainder.count { ele = remainder[r] carry = ele >> 63 ele <<= 1 ele |= previousCarry // carry from last step previousCarry = carry remainder[r] = ele } if previousCarry != 0 { remainder.append(previousCarry) } remainder.setBit(at: 0, to: self.getBit(at: i)) if !remainder.lessThan(divisor) { remainder.difference(divisor) quotient.setBit(at: i, to: true) } i -= 1 } return (quotient, remainder) } /// Division with limbs, result is floored to nearest whole number. func dividing(_ divisor: Limbs) -> Limbs { return self.divMod(divisor).quotient } /// Modulo with limbs, result is floored to nearest whole number. func modulus(_ divisor: Limbs) -> Limbs { return self.divMod(divisor).remainder } // // // MARK: - Limbs Comparing // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Limbs Comparing ||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // // Note: // a < b iff b > a // a <= b iff b >= a // but: // a < b iff !(a >= b) // a <= b iff !(a > b) func lessThan(_ compare: Limbs) -> Bool { let lhsc = self.count let rhsc = compare.count if lhsc != rhsc { return lhsc < rhsc } var i = lhsc - 1 while i >= 0 { if self[i] != compare[i] { return self[i] < compare[i] } i -= 1 } return false // lhs == rhs } func equalTo(_ compare: Limb) -> Bool { return self[0] == compare && self.count == 1 } } // // // MARK: - Useful BInt math functions // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||| Useful BInt math functions |||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // // // internal class BIntMath { /// Returns true iff (2 ** exp) - 1 is a mersenne prime. static func isMersenne(_ exp: Int) -> Bool { var mersenne = Limbs(repeating: Limb.max, count: exp >> 6) if (exp % 64) > 0 { mersenne.append((Limb(1) << Limb(exp % 64)) - Limb(1)) } var res: Limbs = [4] for _ in 0..<(exp - 2) { res = res.squared().differencing([2]).divMod(mersenne).remainder } return res.equalTo(0) } fileprivate static func euclid(_ a: Limbs, _ b: Limbs) -> Limbs { var (a, b) = (a, b) while !b.equalTo(0) { (a, b) = (b, a.divMod(b).remainder) } return a } fileprivate static func gcdFactors(_ lhs: Limbs, rhs: Limbs) -> (ax: Limbs, bx: Limbs) { let gcd = steinGcd(lhs, rhs) return (lhs.divMod(gcd).quotient, rhs.divMod(gcd).quotient) } static func steinGcd(_ a: Limbs, _ b: Limbs) -> Limbs { if a == [0] { return b } if b == [0] { return a } // Trailing zeros var (za, zb) = (0, 0) while !a.getBit(at: za) { za += 1 } while !b.getBit(at: zb) { zb += 1 } let k = min(za, zb) var (a, b) = (a, b) a.shiftDown(za) b.shiftDown(k) repeat { zb = 0 while !b.getBit(at: zb) { zb += 1 } b.shiftDown(zb) if b.lessThan(a) { (a, b) = (b, a) } // At this point, b >= a b.difference(a) } while b != [0] return a.shiftingUp(k) } static func gcd(_ a: BInt, _ b: BInt) -> BInt { let limbRes = steinGcd(a.limbs, b.limbs) return BInt(sign: a.sign && !limbRes.equalTo(0), limbs: limbRes) } /// Do not use this, extremely slow. Only for testing purposes. static func gcdEuclid(_ a: BInt, _ b: BInt) -> BInt { let limbRes = euclid(a.limbs, b.limbs) return BInt(sign: a.sign && !limbRes.equalTo(0), limbs: limbRes) } fileprivate static func lcmPositive(_ a: Limbs, _ b: Limbs) -> Limbs { return a.divMod(steinGcd(a, b)).quotient.multiplyingBy(b) } static func lcm(_ a:BInt, _ b:BInt) -> BInt { return BInt(limbs: lcmPositive(a.limbs, b.limbs)) } static func fib(_ n:Int) -> BInt { var a: Limbs = [0], b: Limbs = [1], t: Limbs for _ in 2...n { t = b b.addLimbs(a) a = t } return BInt(limbs: b) } /// Order matters, repetition not allowed. static func permutations(_ n: Int, _ k: Int) -> BInt { // n! / (n-k)! return BInt(n).factorial() / BInt(n - k).factorial() } /// Order matters, repetition allowed. static func permutationsWithRepitition(_ n: Int, _ k: Int) -> BInt { // n ** k return BInt(n) ** k } /// Order does not matter, repetition not allowed. static func combinations(_ n: Int, _ k: Int) -> BInt { // (n + k - 1)! / (k! * (n - 1)!) return BInt(n + k - 1).factorial() / (BInt(k).factorial() * BInt(n - 1).factorial()) } /// Order does not matter, repetition allowed. static func combinationsWithRepitition(_ n: Int, _ k: Int) -> BInt { // n! / (k! * (n - k)!) return BInt(n).factorial() / (BInt(k).factorial() * BInt(n - k).factorial()) } static func randomBInt(bits n: Int) -> BInt { let limbs = n >> 6 let singleBits = n % 64 var res = Limbs(repeating: 0, count: Int(limbs)) for i in 0..<Int(limbs) { res[i] = Limb(arc4random_uniform(UInt32.max)) | (Limb(arc4random_uniform(UInt32.max)) << 32) } if singleBits > 0 { var last: Limb if singleBits < 32 { last = Limb(arc4random_uniform(UInt32(2 ** singleBits))) } else if singleBits == 32 { last = Limb(arc4random_uniform(UInt32.max)) } else { last = Limb(arc4random_uniform(UInt32.max)) | (Limb(arc4random_uniform(UInt32(2.0 ** (singleBits - 32)))) << 32) } res.append(last) } return BInt(limbs: res) } let random = randomBInt func isPrime(_ n: BInt) -> Bool { if n <= 3 { return n > 1 } if ((n % 2) == 0) || ((n % 3) == 0) { return false } var i = 5 while (i * i) <= n { if ((n % i) == 0) || ((n % (i + 2)) == 0) { return false } i += 6 } return true } /// Quick exponentiation/modulo algorithm /// FIXME: for security, this should use the constant-time Montgomery algorithm to thwart timing attacks /// /// - Parameters: /// - b: base /// - p: power /// - m: modulus /// - Returns: pow(b, p) % m static func mod_exp(_ b: BInt, _ p: BInt, _ m: BInt) -> BInt { precondition(m != 0, "modulus needs to be non-zero") precondition(p >= 0, "exponent needs to be non-negative") var base = b % m var exponent = p var result = BInt(1) while exponent > 0 { if exponent.limbs[0] % 2 != 0 { result = result * base % m } exponent.limbs.shiftDown(1) base *= base base %= m } return result } /// Non-negative modulo operation /// /// - Parameters: /// - a: left hand side of the module operation /// - m: modulus /// - Returns: r := a % b such that 0 <= r < abs(m) static func nnmod(_ a: BInt, _ m: BInt) -> BInt { let r = a % m guard r.isNegative() else { return r } let p = m.isNegative() ? r - m : r + m return p } /// Convenience function combinding addition and non-negative modulo operations /// /// - Parameters: /// - a: left hand side of the modulo addition /// - b: right hand side of the modulo addition /// - m: modulus /// - Returns: nnmod(a + b, m) static func mod_add(_ a: BInt, _ b: BInt, _ m: BInt) -> BInt { return nnmod(a + b, m) } } // // // MARK: - BDouble // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||| BDouble ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // // // public struct BDouble: ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, CustomStringConvertible, SignedNumeric, Comparable, Hashable { // // // MARK: - Internal data // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Internal data ||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // var sign = Bool() var numerator = Limbs() var denominator = Limbs() public typealias Magnitude = Double public var magnitude: Double = 0.0 // // // MARK: - Initializers // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Initializers |||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public init?<T>(exactly source: T) where T : BinaryInteger { self.init(0.0) } /** Inits a BDouble with two Limbs as numerator and denominator - Parameters: - numerator: The upper part of the fraction as Limbs - denominator: The lower part of the fraction as Limbs Returns: A new BDouble */ public init(sign: Bool, numerator: Limbs, denominator: Limbs) { precondition( !denominator.equalTo(0) && denominator != [] && numerator != [], "Denominator can't be zero and limbs can't be []" ) self.sign = sign self.numerator = numerator self.denominator = denominator self.minimize() } public init(_ numerator: BInt, over denominator: BInt) { self.init( sign: numerator.sign != denominator.sign, numerator: numerator.limbs, denominator: denominator.limbs ) } public init(_ numerator: Int, over denominator: Int) { self.init( sign: (numerator < 0) != (denominator < 0), numerator: [UInt64(abs(numerator))], denominator: [UInt64(abs(denominator))] ) } public init?(_ numerator: String, over denominator: String) { if let n = BInt(numerator) { if let d = BInt(denominator) { self.init(n, over: d) return } } return nil } public init?(_ nStr: String) { if let bi = BInt(nStr) { self.init(bi, over: 1) } else { if let exp = nStr.index(of: "e")?.encodedOffset { let beforeExp = String(Array(nStr)[..<exp].filter{ $0 != "." }) var afterExp = String(Array(nStr)[(exp + 1)...]) var sign = false if let neg = afterExp.index(of: "-")?.encodedOffset { afterExp = String(Array(afterExp)[(neg + 1)...]) sign = true } if sign { if var safeAfterExp = Int(afterExp) { if beforeExp.starts(with: "+") || beforeExp.starts(with: "-") { safeAfterExp = safeAfterExp - beforeExp.count + 2 } else { safeAfterExp = safeAfterExp - beforeExp.count + 1 } let den = ["1"] + [Character](repeating: "0", count: safeAfterExp) self.init(beforeExp, over: String(den)) return } return nil } else { if var safeAfterExp = Int(afterExp) { if beforeExp.starts(with: "+") || beforeExp.starts(with: "-") { safeAfterExp = safeAfterExp - beforeExp.count + 2 } else { safeAfterExp = safeAfterExp - beforeExp.count + 1 } let num = beforeExp + String([Character](repeating: "0", count: safeAfterExp)) self.init(num, over: "1") return } return nil } } if let io = nStr.index(of: ".") { let i = io.encodedOffset let beforePoint = String(Array(nStr)[..<i]) let afterPoint = String(Array(nStr)[(i + 1)...]) if afterPoint == "0" { self.init(beforePoint, over: "1") } else { let den = ["1"] + [Character](repeating: "0", count: afterPoint.count) self.init(beforePoint + afterPoint, over: String(den)) } } else { return nil } } } /// Create an instance initialized to a string with the value of mathematical numerical system of the specified radix (base). /// So for example, to get the value of hexadecimal string radix value must be set to 16. public init?(_ nStr: String, radix: Int) { if radix == 10 { // regular string init is faster // see metrics self.init(nStr) return } var useString = nStr if radix == 16 { if useString.hasPrefix("0x") { useString = String(nStr.dropFirst(2)) } } if radix == 8 { if useString.hasPrefix("0o") { useString = String(nStr.dropFirst(2)) } } if radix == 2 { if useString.hasPrefix("0b") { useString = String(nStr.dropFirst(2)) } } let bint16 = BDouble(radix) var total = BDouble(0) var exp = BDouble(1) for c in useString.reversed() { let int = Int(String(c), radix: radix) if int != nil { let value = BDouble(int!) total = total + (value * exp) exp = exp * bint16 } else { return nil } } self.init(String(describing:total)) } public init(_ z: Int) { self.init(z, over: 1) } public init(_ d: Double) { let nStr = String(d) self.init(nStr)! } public init(integerLiteral value: Int) { self.init(value) } public init(floatLiteral value: Double) { self.init(value) } // // // MARK: - Descriptions // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| Descriptions |||||||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /** * returns the current value in a fraction format */ public var description: String { return self.fractionDescription } /** * returns the current value in a fraction format */ public var fractionDescription : String { var res = (self.sign ? "-" : "") res.append(self.numerator.decimalRepresentation) if self.denominator != [1] { res.append("/".appending(self.denominator.decimalRepresentation)) } return res } static private var _precision = 4 /** * the global percision for all newly created values */ static public var precision : Int { get { return _precision } set { var nv = newValue if nv < 0 { nv = 0 } _precision = nv } } private var _precision : Int = BDouble.precision /** * the precision for the current value */ public var precision : Int { get { return _precision } set { var nv = newValue if nv < 0 { nv = 0 } _precision = nv } } /** * returns the current value in decimal format with the current precision */ public var decimalDescription : String { return self.decimalExpansion(precisionAfterDecimalPoint: self.precision) } /** Returns the current value in decimal format (always with a decimal point). - parameter precision: the precision after the decimal point - parameter rounded: whether or not the return value's last digit will be rounded up */ public func decimalExpansion(precisionAfterDecimalPoint precision: Int, rounded : Bool = true) -> String { var currentPrecision = precision if(rounded && precision > 0) { currentPrecision = currentPrecision + 1 } let multiplier = [10].exponentiating(currentPrecision) let limbs = self.numerator.multiplyingBy(multiplier).divMod(self.denominator).quotient var res = BInt(limbs: limbs).description if currentPrecision <= res.count { res.insert(".", at: String.Index(encodedOffset: res.count - currentPrecision)) if res.hasPrefix(".") { res = "0" + res } else if res.hasSuffix(".") { res += "0" } } else { res = "0." + String(repeating: "0", count: currentPrecision - res.count) + res } var retVal = self.isNegative() && !limbs.equalTo(0) ? "-" + res : res if(rounded && precision > 0) { let lastDigit = Int(retVal.suffix(1))! // this should always be a number let secondDigit = retVal.suffix(2).prefix(1) // this could be a decimal retVal = String(retVal.prefix(retVal.count-2)) if (secondDigit != ".") { if lastDigit >= 5 { retVal = retVal + String(Int(secondDigit)! + 1) } else { retVal = retVal + String(Int(secondDigit)!) } } else { retVal = retVal + "." + String(lastDigit) } } return retVal } public var hashValue: Int { return "\(self.sign)\(self.numerator)\(self.denominator)".hashValue } /** * Returns the size of the BDouble in bits. */ public var size: Int { return 1 + ((self.numerator.count + self.denominator.count) * MemoryLayout<Limb>.size * 8) } /** * Returns a formated human readable string that says how much space * (in bytes, kilobytes, megabytes, or gigabytes) the BDouble occupies */ public var sizeDescription: String { // One bit for the sign, plus the size of the numerator and denominator. let bits = self.size if bits < 8_000 { return String(format: "%.1f b", Double(bits) / 8.0) } if bits < 8_000_000 { return String(format: "%.1f kb", Double(bits) / 8_000.0) } if UInt64(bits) < UInt64(8_000_000_000.0) { return String(format: "%.1f mb", Double(bits) / 8_000_000.0) } return String(format: "%.1f gb", Double(bits) / 8_000_000_000.0) } public func rawData() -> (sign: Bool, numerator: [UInt64], denominator: [UInt64]) { return (self.sign, self.numerator, self.denominator) } public func isPositive() -> Bool { return !self.sign } public func isNegative() -> Bool { return self.sign } public func isZero() -> Bool { return self.numerator.equalTo(0) } public mutating func minimize() { if self.numerator.equalTo(0) { self.denominator = [1] return } let gcd = BIntMath.steinGcd(self.numerator, self.denominator) if gcd[0] > 1 || gcd.count > 1 { self.numerator = self.numerator.divMod(gcd).quotient self.denominator = self.denominator.divMod(gcd).quotient } } /** * If the right side of the decimal is greater than 0.5 then it will round up (ceil), * otherwise round down (floor) to the nearest BInt */ public func rounded() -> BInt { if self.isZero() { return BInt(0) } let digits = 3 let multiplier = [10].exponentiating(digits) let rawRes = abs(self).numerator.multiplyingBy(multiplier).divMod(self.denominator).quotient let res = BInt(limbs: rawRes).description let offset = res.count - digits let rhs = Double("0." + res.suffix(res.count - offset))! let lhs = res.prefix(offset) var retVal = BInt(String(lhs))! if self.isNegative() { retVal = -retVal if rhs > 0.5 { retVal = retVal - BInt(1) } } else { if rhs > 0.5 { retVal = retVal + 1 } } return retVal } // public func sqrt(precision digits: Int) -> BDouble // { // // let self = v // // Find x such that x*x=v <==> x = v/x // // } // // // MARK: - BDouble Addition // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BDouble Addition |||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public static func +(lhs: BDouble, rhs: BDouble) -> BDouble { // a/b + c/d = ad + bc / bd, where lhs = a/b and rhs = c/d. let ad = lhs.numerator.multiplyingBy(rhs.denominator) let bc = rhs.numerator.multiplyingBy(lhs.denominator) let bd = lhs.denominator.multiplyingBy(rhs.denominator) let resNumerator = BInt(sign: lhs.sign, limbs: ad) + BInt(sign: rhs.sign, limbs: bc) return BDouble( sign: resNumerator.sign && !resNumerator.limbs.equalTo(0), numerator: resNumerator.limbs, denominator: bd ) } public static func +(lhs: BDouble, rhs: Double) -> BDouble { return lhs + BDouble(rhs) } public static func +(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) + rhs } public static func +=(lhs: inout BDouble, rhs: BDouble) { let res = lhs + rhs lhs = res } public static func +=(lhs: inout BDouble, rhs: Double) { lhs += BDouble(rhs) } // // // MARK: - BDouble Negation // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BDouble Negation |||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /** * makes the current value negative */ public mutating func negate() { if !self.isZero() { self.sign = !self.sign } } public static prefix func -(n: BDouble) -> BDouble { var n = n n.negate() return n } // // // MARK: - BDouble Subtraction // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BDouble Subtraction ||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public static func -(lhs: BDouble, rhs: BDouble) -> BDouble { return lhs + -rhs } public static func -(lhs: BDouble, rhs: Double) -> BDouble { return lhs - BDouble(rhs) } public static func -(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) - rhs } public static func -=(lhs: inout BDouble, rhs: BDouble) { let res = lhs - rhs lhs = res } public static func -=(lhs: inout BDouble, rhs: Double) { lhs -= BDouble(rhs) } // // // MARK: - BDouble Multiplication // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BDouble Multiplication |||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public static func *(lhs: BDouble, rhs: BDouble) -> BDouble { var res = BDouble( sign: lhs.sign != rhs.sign, numerator: lhs.numerator.multiplyingBy(rhs.numerator), denominator: lhs.denominator.multiplyingBy(rhs.denominator) ) if res.isZero() { res.sign = false } return res } public static func *(lhs: BDouble, rhs: Double) -> BDouble { return lhs * BDouble(rhs) } public static func *(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) * rhs } public static func *=(lhs: inout BDouble, rhs: BDouble) { let res = lhs * rhs lhs = res } public static func *=(lhs: inout BDouble, rhs: Double) { lhs *= BDouble(rhs) } // // // MARK: - BDouble Exponentiation // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BDouble Exponentiation |||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // // TODO: Exponentiation function that supports Double/BDouble in the exponent public static func **(_ base : BDouble, _ exponent : Int) -> BDouble { if exponent == 0 { return BDouble(1) } if exponent == 1 { return base } if exponent < 0 { return BDouble(1) / (base ** -exponent) } return base * (base ** (exponent - 1)) } // // // MARK: - BDouble Division // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BDouble Division |||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // public static func /(lhs: BDouble, rhs: BDouble) -> BDouble { var res = BDouble( sign: lhs.sign != rhs.sign, numerator: lhs.numerator.multiplyingBy(rhs.denominator), denominator: lhs.denominator.multiplyingBy(rhs.numerator) ) if res.isZero() { res.sign = false } return res } public static func /(lhs: BDouble, rhs: Double) -> BDouble { return lhs / BDouble(rhs) } public static func /(lhs: Double, rhs: BDouble) -> BDouble { return BDouble(lhs) / rhs } // // // MARK: - BDouble Comparing // ———————————————————————————————————————————————————————————————————————————————————————— // |||||||| BDouble Comparing ||||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————— // // // /** * An == comparison with an epsilon (fixed then a calculated "ULPs") * Reference: http://floating-point-gui.de/errors/comparison/ * Reference: https://bitbashing.io/comparing-floats.html */ public static func nearlyEqual(_ lhs: BDouble, _ rhs: BDouble, epsilon: Double = 0.00001) -> Bool { let absLhs = abs(lhs) let absRhs = abs(rhs); let diff = abs(lhs - rhs); if (lhs == rhs) { // shortcut, handles infinities return true; } else if diff <= epsilon { return true // shortcut } else if (lhs == 0 || rhs == 0 || diff < Double.leastNormalMagnitude) { // lhs or rhs is zero or both are extremely close to it // relative error is less meaningful here return diff < (epsilon * Double.leastNormalMagnitude); } else { // use relative error return diff / min((absLhs + absRhs), BDouble(Double.greatestFiniteMagnitude)) < epsilon; } } public static func ==(lhs: BDouble, rhs: BDouble) -> Bool { if lhs.sign != rhs.sign { return false } if lhs.numerator != rhs.numerator { return false } if lhs.denominator != rhs.denominator { return false } return true } public static func ==(lhs: BDouble, rhs: Double) -> Bool { return lhs == BDouble(rhs) } public static func ==(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) == rhs } public static func !=(lhs: BDouble, rhs: BDouble) -> Bool { return !(lhs == rhs) } public static func !=(lhs: BDouble, rhs: Double) -> Bool { return lhs != BDouble(rhs) } public static func !=(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) != rhs } public static func <(lhs: BDouble, rhs: BDouble) -> Bool { if lhs.sign != rhs.sign { return lhs.sign } // more efficient than lcm version let ad = lhs.numerator.multiplyingBy(rhs.denominator) let bc = rhs.numerator.multiplyingBy(lhs.denominator) if lhs.sign { return bc.lessThan(ad) } return ad.lessThan(bc) } public static func <(lhs: BDouble, rhs: Double) -> Bool { return lhs < BDouble(rhs) } public static func <(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) < rhs } public static func >(lhs: BDouble, rhs: BDouble) -> Bool { return rhs < lhs } public static func >(lhs: BDouble, rhs: Double) -> Bool { return lhs > BDouble(rhs) } public static func >(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) > rhs } public static func <=(lhs: BDouble, rhs: BDouble) -> Bool { return !(rhs < lhs) } public static func <=(lhs: BDouble, rhs: Double) -> Bool { return lhs <= BDouble(rhs) } public static func <=(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) <= rhs } public static func >=(lhs: BDouble, rhs: BDouble) -> Bool { return !(lhs < rhs) } public static func >=(lhs: BDouble, rhs: Double) -> Bool { return lhs >= BDouble(rhs) } public static func >=(lhs: Double, rhs: BDouble) -> Bool { return BDouble(lhs) >= rhs } } // // // MARK: - BDouble Operators // ———————————————————————————————————————————————————————————————————————————————————————————— // |||||||| BDouble more Operators |||||||||||||||||||||||||||||||||||||||||||||| // ———————————————————————————————————————————————————————————————————————————————————————————— // // // /** * Returns the absolute value of the given number. * - parameter x: a big double */ public func abs(_ x: BDouble) -> BDouble { return BDouble( sign: false, numerator: x.numerator, denominator: x.denominator ) } /** * round to largest BInt value not greater than base */ public func floor(_ base: BDouble) -> BInt { if base.isZero() { return BInt(0) } let digits = 3 let multiplier = [10].exponentiating(digits) let rawRes = abs(base).numerator.multiplyingBy(multiplier).divMod(base.denominator).quotient let res = BInt(limbs: rawRes).description let offset = res.count - digits let lhs = res.prefix(offset).description let rhs = Double("0." + res.suffix(res.count - offset))! var ans = BInt(String(lhs))! if base.isNegative() { ans = -ans if rhs > 0.0 { ans = ans - BInt(1) } } return ans } /** * round to smallest BInt value not less than base */ public func ceil(_ base: BDouble) -> BInt { if base.isZero() { return BInt(0) } let digits = 3 let multiplier = [10].exponentiating(digits) let rawRes = abs(base).numerator.multiplyingBy(multiplier).divMod(base.denominator).quotient let res = BInt(limbs: rawRes).description let offset = res.count - digits let rhs = Double("0." + res.suffix(res.count - offset))! let lhs = res.prefix(offset) var retVal = BInt(String(lhs))! if base.isNegative() { retVal = -retVal } else { if rhs > 0.0 { retVal += 1 } } return retVal } /** * Returns a BDouble number raised to a given power. */ public func pow(_ base : BDouble, _ exp : Int) -> BDouble { return base**exp } /** * Returns the BDouble that is the smallest */ public func min(_ lhs: BDouble, _ rhs: BDouble) -> BDouble { if lhs <= rhs { return lhs } return rhs } /** * Returns the BDouble that is largest */ public func max(_ lhs: BDouble, _ rhs: BDouble) -> BDouble { if lhs >= rhs { return lhs } return rhs }
mit
aba93da75c3a4db33f9bd60bda0cf4fc
25.600595
136
0.500944
3.617901
false
false
false
false
coach-plus/ios
CoachPlus/AppDelegate.swift
1
6545
// // AppDelegate.swift // CoachPlus // // Created by Breit, Maurice on 21.03.17. // Copyright © 2017 Mathandoro GbR. All rights reserved. // import UIKit import UserNotifications import IQKeyboardManagerSwift import Hero import Sentry import YPImagePicker @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { IQKeyboardManager.shared.enable = true self.setupSentry() self.setupStyling() if (Authentication.loggedIn() == false) { FlowManager.setLogin() return true } else { FlowManager.setHome() NotificationManager.shared.registerForNotifications() } DataHandler.def.getUser().done({user in UserManager.storeUser(user: user) UserManager.shared.userWasEdited.onNext(user) }).catch({error in print("could not get user") }) UNUserNotificationCenter.current().delegate = NotificationManager.shared return true } func setupSentry() { // Create a Sentry client and start crash handler do { Client.shared = try Client(dsn: "https://[email protected]/1533813") try Client.shared?.startCrashHandler() } catch let error { print("\(error)") } } 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:. } //Styling func setupStyling() { Hero.shared.containerColor = .clear self.window?.backgroundColor = .coachPlusBlue //let ai = UIActivityIndicatorView.appearance(whenContainedInInstancesOf: [MBProgressHUD.self]) //ai.color = UIColor.coachPlusBlue //UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().backgroundColor = .coachPlusBlue UITableViewCell.appearance().backgroundColor = UIColor.defaultBackground UITableView.appearance().backgroundColor = UIColor.defaultBackground let pickerAppearrance = UINavigationBar.appearance(whenContainedInInstancesOf: [YPImagePicker.self]) pickerAppearrance.tintColor = .coachPlusBlue } // Push Notifications // Called when APNs has assigned the device a unique token func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { if (!Authentication.loggedIn()) { return } let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } let deviceTokenString = tokenParts.joined() print("APNs device token: \(deviceTokenString)") NotificationManager.registerDeviceOnServer(pushId: deviceTokenString) } // Called when APNs failed to register the device for push notifications func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("APNs registration failed: \(error)") } func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) { print("Push notification received: \(data)") } // Universal Link func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { // 1 guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL, let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return false } print(url) return UrlHandler.handleUrlComponents(components: components) } /* func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { // 1 guard userActivity.activityType == NSUserActivityTypeBrowsingWeb, let url = userActivity.webpageURL, let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return false } print(url) return UrlHandler.handleUrlComponents(components: components) } */ func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { print(url) return true } }
mit
d5caa57178760acc1b7e93199d900130
35.971751
285
0.665495
5.879605
false
false
false
false
yume190/JSONDecodeKit
Test/ErrorTests.swift
1
3174
// // ErrorTests.swift // JSONDecodeKit // // Created by Yume on 2018/1/8. // Copyright © 2018年 Yume. All rights reserved. // import XCTest @testable import JSONDecodeKit //{ // "array": { // "primitive":[1,2,3], // "decodeable":[{"res":1},{"res":2},{"res":3},], // }, // "dic": { // "primitive":{ // "a":1, // "b":2, // "c":3, // "d": null, // "f": 5.5, // }, // "decodeable":{ // "a":{"res":1}, // "b":{"res":2}, // "c":{"res":3}, // }, // }, // "dicArray": { // "primitive":{ // "a":[1,2], // "b":[2,3], // "c":[3,4], // }, // "decodeable":{ // "a":[{"res":1},{"res":2},], // "b":[{"res":2},{"res":3},], // "c":[{"res":3},{"res":4},], // }, // } //} class ErrorTests: XCTestCase { func testKeyNotFound() { let json = JSON(data: self.data, isTraceKeypath: true) do { let _: Int = try json["dic"]["primitive"] <| "e" } catch let error as JSONDecodeError { switch error { case .keyNotFound(let base): XCTAssertEqual(base.keyPath, ".dic.primitive") XCTAssertEqual(base.currentKey, "e") NSLog("\(error)") default: fatalError() } return } catch { fatalError() } fatalError() } func testNullValue() { let json = JSON(data: self.data, isTraceKeypath: true) do { let _: Int = try json["dic"]["primitive"] <| "d" } catch let error as JSONDecodeError { switch error { case .nullValue(let base): XCTAssertEqual(base.keyPath, ".dic.primitive") XCTAssertEqual(base.currentKey, "d") NSLog("\(error)") default: fatalError() } return } catch { fatalError() } fatalError() } func testTypeMismatch() { let json = JSON(data: self.data, isTraceKeypath: true) do { let _: Bool = try json["dic"]["primitive"] <| "f" } catch let error as JSONDecodeError { switch error { case .typeMismatch(let base, let extra): XCTAssertEqual(base.keyPath, ".dic.primitive") XCTAssertEqual(base.currentKey, "f") XCTAssertTrue(extra.expectType is Bool.Type) XCTAssertTrue(extra.actualType is NSNumber.Type) XCTAssertEqual((extra.value as! Double), 5.5) NSLog("\(error)") return default: fatalError() } } catch { fatalError() } fatalError() } private lazy var data:Data = { let path = Bundle(for: type(of: self)).url(forResource: "test2", withExtension: "json") let data = try! Data(contentsOf: path!) return data }() }
mit
3b09af9d0d562d5afc147e26f4ec139f
25.425
95
0.431725
4.177866
false
true
false
false
jtbandes/swift
test/SILGen/class_resilience.swift
6
1530
// RUN: rm -rf %t && mkdir %t // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -I %t -emit-silgen -enable-resilience %s | %FileCheck %s import resilient_class // Accessing final property of resilient class from different resilience domain // through accessor // CHECK-LABEL: sil @_T016class_resilience20finalPropertyOfOthery010resilient_A022ResilientOutsideParentCF // CHECK: function_ref @_T015resilient_class22ResilientOutsideParentC13finalPropertySSfg public func finalPropertyOfOther(_ other: ResilientOutsideParent) { _ = other.finalProperty } public class MyResilientClass { public final var finalProperty: String = "MyResilientClass.finalProperty" } // Accessing final property of resilient class from my resilience domain // directly // CHECK-LABEL: sil @_T016class_resilience19finalPropertyOfMineyAA16MyResilientClassCF // CHECK: bb0([[ARG:%.*]] : $MyResilientClass): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: ref_element_addr [[BORROWED_ARG]] : $MyResilientClass, #MyResilientClass.finalProperty // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] public func finalPropertyOfMine(_ other: MyResilientClass) { _ = other.finalProperty }
apache-2.0
0885096a72e635657bdff57c8d976760
44
181
0.765359
3.963731
false
false
false
false
ShengQiangLiu/arcgis-runtime-samples-ios
TableOfContentsSample/swift/TableOfContents/TOC/Cells/LayerInfoCell.swift
4
3070
// // Copyright 2015 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // import UIKit let LEVEL_INDENT:CGFloat = 15 class CheckBox:UIButton { var isChecked:Bool = false { didSet { self.updateCheckBox() } } func changeCheckBox() { self.isChecked = !self.isChecked } func updateCheckBox() { if self.isChecked { self.setImage(UIImage(named: "checkbox_checked.png"), forState:.Normal) } else { self.setImage(UIImage(named: "checkbox_unchecked.png"), forState:.Normal) } } } protocol LayerInfoCellDelegate:class { func layerInfoCell(layerInfoCell:LayerInfoCell, didChangeVisibility visibility:Bool) } class LayerInfoCell: UITableViewCell { @IBOutlet weak var valueLabel:UILabel! @IBOutlet weak var visibilitySwitch:CheckBox! @IBOutlet weak var arrowImage:UIImageView! @IBOutlet weak var arrowImageLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var visibilitySwitchLeadingConstraint: NSLayoutConstraint! var level:Int! var expanded:Bool = false { //update the arrow image based on the state of the expansion didSet { if self.arrowImage != nil { self.arrowImage.image = UIImage(named: self.expanded ? "CircleArrowDown_sml" : "CircleArrowRight_sml") } } } var canChangeVisibility:Bool = false { //show checkbox if the layer can be hidden didSet { canChangeVisibility ? self.showVisibilitySwitch() : hideVisibilitySwitch() } } var visibility:Bool = false { //set the state of the checkbox didSet { self.visibilitySwitch?.isChecked = visibility } } weak var layerInfoCellDelegate:LayerInfoCellDelegate? //called when the user checks or unchecks the visibility switch @IBAction func visibilityChanged() { self.visibilitySwitch.changeCheckBox() self.layerInfoCellDelegate?.layerInfoCell(self, didChangeVisibility: self.visibilitySwitch.isChecked) } override func layoutSubviews() { super.layoutSubviews() //set the indentation based on the level self.arrowImageLeadingConstraint.constant = CGFloat(self.level + 1) * LEVEL_INDENT } //MARK: - hide/show switch func hideVisibilitySwitch() { self.visibilitySwitch.hidden = true self.visibilitySwitchLeadingConstraint.constant = -self.visibilitySwitch.bounds.size.width } func showVisibilitySwitch() { self.visibilitySwitch.hidden = false self.visibilitySwitchLeadingConstraint.constant = 8 } }
apache-2.0
0a7714ee1db748990809b13a5a5f8eeb
29.7
118
0.66873
4.842271
false
false
false
false
fxm90/GradientProgressBar
Example/Pods/SnapshotTesting/Sources/SnapshotTesting/Snapshotting/SceneKit.swift
1
1406
#if os(iOS) || os(macOS) || os(tvOS) import SceneKit #if os(macOS) import Cocoa #elseif os(iOS) || os(tvOS) import UIKit #endif #if os(macOS) extension Snapshotting where Value == SCNScene, Format == NSImage { /// A snapshot strategy for comparing SceneKit scenes based on pixel equality. /// /// - Parameters: /// - precision: The percentage of pixels that must match. /// - size: The size of the scene. public static func image(precision: Float = 1, size: CGSize) -> Snapshotting { return .scnScene(precision: precision, size: size) } } #elseif os(iOS) || os(tvOS) extension Snapshotting where Value == SCNScene, Format == UIImage { /// A snapshot strategy for comparing SceneKit scenes based on pixel equality. /// /// - Parameters: /// - precision: The percentage of pixels that must match. /// - size: The size of the scene. public static func image(precision: Float = 1, size: CGSize) -> Snapshotting { return .scnScene(precision: precision, size: size) } } #endif fileprivate extension Snapshotting where Value == SCNScene, Format == Image { static func scnScene(precision: Float, size: CGSize) -> Snapshotting { return Snapshotting<View, Image>.image(precision: precision).pullback { scene in let view = SCNView(frame: .init(x: 0, y: 0, width: size.width, height: size.height)) view.scene = scene return view } } } #endif
mit
289190366b93ad9442886cb010c2768f
32.47619
90
0.681366
3.905556
false
false
false
false
ECP-CANDLE/Supervisor
archives/workflows/simple_hyperopt_example/ext/EQ-Py/EQPy.swift
1
1391
import location; pragma worktypedef resident_work; @dispatch=resident_work (void v) _void_py(string code, string expr="\"\"") "turbine" "0.1.0" [ "turbine::python 1 1 <<code>> <<expr>> "]; @dispatch=resident_work (string output) _string_py(string code, string expr) "turbine" "0.1.0" [ "set <<output>> [ turbine::python 1 1 <<code>> <<expr>> ]" ]; string init_package_string = "import eqpy\nimport %s\n" + "import threading\n" + "p = threading.Thread(target=%s.run)\np.start()"; (void v) EQPy_init_package(location loc, string packageName){ //printf("EQPy_init_package called"); string code = init_package_string % (packageName,packageName); //printf("Code is: \n%s", code); @location=loc _void_py(code) => v = propagate(); } EQPy_stop(location loc){ // do nothing } string get_string = "result = eqpy.output_q.get()"; (string result) EQPy_get(location loc){ //printf("EQPy_get called"); string code = get_string; //printf("Code is: \n%s", code); result = @location=loc _string_py(code, "result"); } string put_string = """ eqpy.input_q.put("%s")\n"" """; (void v) EQPy_put(location loc, string data){ //printf("EQPy_put called with: \n%s", data); string code = put_string % data; //printf("EQPy_put code: \n%s", code); @location=loc _void_py(code) => v = propagate(); } // Local Variables: // c-basic-offset: 4 // End:
mit
763f08325aa2e82eaacc0bc9ac058b20
26.82
70
0.629763
2.940803
false
false
false
false
MrDML/WavesAnimationSwift
RomWavesCustom/RomWavesCustom/ViewController.swift
1
3211
// // ViewController.swift // RomWavesCustom // // Created by 戴明亮 on 17/3/8. // Copyright © 2017年 戴明亮. All rights reserved. // import UIKit class ViewController: UIViewController { var tableView: UITableView? = { () -> (UITableView) in let tab = UITableView.init(frame: UIScreen.main.bounds, style: .plain) return tab }() override func viewDidLoad() { super.viewDidLoad() tableView?.delegate = self tableView?.dataSource = self guard let tableView = tableView else { return } view.addSubview(tableView) } // override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cellId") if cell == nil { cell = UITableViewCell.init(style: .subtitle, reuseIdentifier: "cellId") } return cell! } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerId") if headerView == nil { headerView = UITableViewHeaderFooterView.init(reuseIdentifier: "headerId") let waves = RomWavesCustom.init(frame: CGRect.init(x: 0, y: 120, width: UIScreen.main.bounds.width, height: 80)) headerView?.addSubview(waves) let imgv = UIImageView.init() imgv.image = UIImage.init(named: "swiftIcon") let size = CGSize.init(width: 50, height: 50) //imgv.image?.size ?? CGSize.init(width: 50, height: 50); imgv.center = CGPoint.init(x: UIScreen.main.bounds.size.width * 0.5, y: 145 - size.height * 0.5) imgv.bounds = CGRect.init(x: 0, y: 0, width: size.width, height: size.height) imgv.layer.cornerRadius = size.width * 0.5 imgv.clipsToBounds = true let originY = imgv.frame.origin.y waves.currentYOffset = { (offset) -> () in var rect = imgv.frame var inset = offset inset -= 25 rect.origin.y = (originY - 25) + inset imgv.frame = rect } headerView?.addSubview(imgv) } headerView?.layer.backgroundColor = UIColor.init(colorLiteralRed: 245/255.0, green: 68/255.0, blue: 4/255.0, alpha: 0.95).cgColor return headerView; } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 200; } }
mit
244b89814433141de4c13ae5514bbe01
29.150943
137
0.580413
4.727811
false
false
false
false
ello/ello-ios
Sources/Model/NotificationAttributedTitle.swift
1
16334
//// /// NotificationAttributedTitle.swift // struct NotificationAttributedTitle { static private func attrs(_ addlAttrs: [NSAttributedString.Key: Any] = [:]) -> [NSAttributedString.Key: Any] { let attrs: [NSAttributedString.Key: Any] = [ .font: UIFont.defaultFont(), .foregroundColor: UIColor.greyA, ] return attrs + addlAttrs } static private func styleText(_ text: String) -> NSAttributedString { return NSAttributedString(string: text, attributes: attrs()) } static private func styleUser(_ user: User?) -> NSAttributedString { if let user = user { return NSAttributedString( string: user.atName, attributes: attrs([ ElloAttributedText.Link: "user", ElloAttributedText.Object: user, .underlineStyle: NSUnderlineStyle.single.rawValue, ]) ) } else { return styleText("Someone") } } static private func stylePost(_ text: String, _ post: Post) -> NSAttributedString { let attrs = self.attrs([ ElloAttributedText.Link: "post", ElloAttributedText.Object: post, .underlineStyle: NSUnderlineStyle.single.rawValue, ]) return NSAttributedString(string: text, attributes: attrs) } static private func styleComment(_ text: String, _ comment: ElloComment) -> NSAttributedString { let attrs = self.attrs([ ElloAttributedText.Link: "comment", ElloAttributedText.Object: comment, .underlineStyle: NSUnderlineStyle.single.rawValue, ]) return NSAttributedString(string: text, attributes: attrs) } static private func styleArtistInvite(_ artistInvite: ArtistInvite) -> NSAttributedString { let attrs = self.attrs([ ElloAttributedText.Link: "artistInvite", ElloAttributedText.Object: artistInvite, .underlineStyle: NSUnderlineStyle.single.rawValue, ]) return NSAttributedString(string: artistInvite.title, attributes: attrs) } static private func styleCategory(_ category: Category) -> NSAttributedString { let attrs = self.attrs([ ElloAttributedText.Link: "category", ElloAttributedText.Object: category, .underlineStyle: NSUnderlineStyle.single.rawValue, ]) return NSAttributedString(string: category.name, attributes: attrs) } static private func styleCategory(partial: CategoryPartial) -> NSAttributedString { let attrs = self.attrs([ ElloAttributedText.Link: "categoryPartial", ElloAttributedText.Object: partial, .underlineStyle: NSUnderlineStyle.single.rawValue, ]) return NSAttributedString(string: partial.name, attributes: attrs) } static func from(notification: Notification) -> NSAttributedString { let kind = notification.activity.kind let author = notification.author let subject = notification.subject switch kind { case .repostNotification: if let post = subject as? Post { return styleUser(author).appending(styleText(" reposted your ")) .appending(stylePost("post", post)) .appending(styleText(".")) } else { return styleUser(author).appending(styleText(" reposted your post.")) } case .newFollowedUserPost: return styleText("You started following ").appending(styleUser(author)) .appending(styleText(".")) case .newFollowerPost: return styleUser(author).appending(styleText(" started following you.")) case .postMentionNotification: if let post = subject as? Post { return styleUser(author).appending(styleText(" mentioned you in a ")) .appending(stylePost("post", post)) .appending(styleText(".")) } else { return styleUser(author) .appending(styleText(" mentioned you in a post.")) } case .commentNotification: if let comment = subject as? ElloComment { return styleUser(author) .appending(styleText(" commented on your ")) .appending(styleComment("post", comment)) .appending(styleText(".")) } else { return styleUser(author) .appending(styleText(" commented on a post.")) } case .commentMentionNotification: if let comment = subject as? ElloComment { return styleUser(author) .appending(styleText(" mentioned you in a ")) .appending(styleComment("comment", comment)) .appending(styleText(".")) } else { return styleUser(author) .appending(styleText(" mentioned you in a comment.")) } case .commentOnOriginalPostNotification: if let comment = subject as? ElloComment, let repost = comment.loadedFromPost, let repostAuthor = repost.author, let source = repost.repostSource { return styleUser(author) .appending(styleText(" commented on ")) .appending(styleUser(repostAuthor)) .appending(styleText("’s ")) .appending(stylePost("repost", repost)) .appending(styleText(" of your ")) .appending(stylePost("post", source)) .appending(styleText(".")) } else { return styleUser(author) .appending(styleText(" commented on your post")) } case .commentOnRepostNotification: if let comment = subject as? ElloComment { return styleUser(author) .appending(styleText(" commented on your ")) .appending(styleComment("repost", comment)) .appending(styleText(".")) } else { return styleUser(author) .appending(styleText(" commented on your repost")) } case .invitationAcceptedPost: return styleUser(author) .appending(styleText(" accepted your invitation.")) case .loveNotification: if let love = subject as? Love, let post = love.post { return styleUser(author) .appending(styleText(" loved your ")) .appending(stylePost("post", post)) .appending(styleText(".")) } else { return styleUser(author).appending(styleText(" loved your post.")) } case .loveOnRepostNotification: if let love = subject as? Love, let post = love.post { return styleUser(author) .appending(styleText(" loved your ")) .appending(stylePost("repost", post)) .appending(styleText(".")) } else { return styleUser(author).appending(styleText(" loved your repost.")) } case .loveOnOriginalPostNotification: if let love = subject as? Love, let repost = love.post, let repostAuthor = repost.author, let source = repost.repostSource { return styleUser(author) .appending(styleText(" loved ")) .appending(styleUser(repostAuthor)) .appending(styleText("’s ")) .appending(stylePost("repost", repost)) .appending(styleText(" of your ")) .appending(stylePost("post", source)) .appending(styleText(".")) } else { return styleUser(author).appending(styleText(" loved a repost of your post.")) } case .watchNotification: if let watch = subject as? Watch, let post = watch.post { return styleUser(author) .appending(styleText(" is watching your ")) .appending(stylePost("post", post)) .appending(styleText(".")) } else { return styleUser(author).appending(styleText(" is watching your post.")) } case .watchCommentNotification: if let comment = subject as? ElloComment, let post = comment.parentPost { return styleUser(author) .appending(styleText(" commented on a ")) .appending(stylePost("post", post)) .appending(styleText(" you’re watching.")) } else { return styleUser(author).appending( styleText(" commented on a post you’re watching.") ) } case .watchOnRepostNotification: if let watch = subject as? Watch, let post = watch.post { return styleUser(author) .appending(styleText(" is watching your ")) .appending(stylePost("repost", post)) .appending(styleText(".")) } else { return styleUser(author).appending(styleText(" is watching your repost.")) } case .watchOnOriginalPostNotification: if let watch = subject as? Watch, let repost = watch.post, let repostAuthor = repost.author, let source = repost.repostSource { return styleUser(author) .appending(styleText(" is watching ")) .appending(styleUser(repostAuthor)) .appending(styleText("’s ")) .appending(stylePost("repost", repost)) .appending(styleText(" of your ")) .appending(stylePost("post", source)) .appending(styleText(".")) } else { return styleUser(author).appending(styleText(" is watching a repost of your post.")) } case .approvedArtistInviteSubmission: if let submission = subject as? ArtistInviteSubmission, let artistInvite = submission.artistInvite { return styleText("Your submission to ") .appending(styleArtistInvite(artistInvite)) .appending(styleText(" has been accepted!")) } else { return styleText("Your submission has been accepted!") } case .approvedArtistInviteSubmissionNotificationForFollowers: if let submission = subject as? ArtistInviteSubmission, let artistInvite = submission.artistInvite, let author = submission.post?.author { return styleUser(author) .appending(styleText("’s submission to ")) .appending(styleArtistInvite(artistInvite)) .appending(styleText(" has been accepted!")) } else { return styleText("A followers submission has been accepted!") } case .categoryPostFeatured: if let submission = subject as? CategoryPost, let featuredBy = submission.featuredBy, let categoryText = submission.category.map(({ styleCategory($0) })) ?? submission.categoryPartial.map({ styleCategory(partial: $0) }), let post = submission.post { return styleUser(featuredBy) .appending(styleText(" featured your ")) .appending(stylePost("post", post)) .appending(styleText(" in ")) .appending(categoryText) .appending(styleText(".")) } else { return styleText("Someone featured your post.") } case .categoryRepostFeatured: if let submission = subject as? CategoryPost, let featuredBy = submission.featuredBy, let categoryText = submission.category.map(({ styleCategory($0) })) ?? submission.categoryPartial.map({ styleCategory(partial: $0) }), let post = submission.post { return styleUser(featuredBy) .appending(styleText(" featured your ")) .appending(stylePost("repost", post)) .appending(styleText(" in ")) .appending(categoryText) .appending(styleText(".")) } else { return styleText("Someone featured your repost.") } case .categoryPostViaRepostFeatured: if let submission = subject as? CategoryPost, let featuredBy = submission.featuredBy, let categoryText = submission.category.map(({ styleCategory($0) })) ?? submission.categoryPartial.map({ styleCategory(partial: $0) }), let repost = submission.post, let source = repost.repostSource { return styleUser(featuredBy) .appending(styleText(" featured a ")) .appending(stylePost("repost", repost)) .appending(styleText(" of your ")) .appending(stylePost("post", source)) .appending(styleText(" in ")) .appending(categoryText) .appending(styleText(".")) } else { return styleText("Someone featured a repost of your post.") } case .userAddedAsFeatured: if let submission = subject as? CategoryUser, let featuredBy = submission.featuredBy, let category = submission.category { return styleUser(featuredBy) .appending(styleText(" has featured you in ")) .appending(styleCategory(category)) .appending(styleText(".")) } else { return styleText("Someone has featured you in a category.") } case .userAddedAsCurator: if let submission = subject as? CategoryUser, let curatorBy = submission.curatorBy, let category = submission.category { return styleUser(curatorBy) .appending(styleText(" has invited you to help curate ")) .appending(styleCategory(category)) .appending(styleText(".")) } else { return styleText("Someone has invited you to help curate a category.") } case .userAddedAsModerator: if let submission = subject as? CategoryUser, let moderatorBy = submission.moderatorBy, let category = submission.category { return styleUser(moderatorBy) .appending(styleText(" has invited you to help moderate ")) .appending(styleCategory(category)) .appending(styleText(".")) } else { return styleText("Someone has invited you to help moderate a category.") } case .welcomeNotification: return styleText("Welcome to Ello!") default: return NSAttributedString(string: "") } } }
mit
4778b8227a176e87f8c264d53f4f2a86
41.06701
100
0.523343
5.989725
false
false
false
false
tanikawa-y/ObjectMapper
ObjectMapperTests/ObjectMapperTests.swift
1
25986
// // ObjectMapperTests.swift // ObjectMapperTests // // Created by Tristan Himmelman on 2014-10-16. // Copyright (c) 2014 hearst. All rights reserved. // import UIKit import XCTest import ObjectMapper class ObjectMapperTests: XCTestCase { let userMapper = Mapper<User>() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testImmutableMappable() { let mapper = Mapper<Immutable>() let JSON = [ "prop1": "Immutable!", "prop2": 255, "prop3": true ] let immutable = mapper.map(JSON) XCTAssertEqual(immutable.prop1, "Immutable!") XCTAssertEqual(immutable.prop2, 255) XCTAssertEqual(immutable.prop3, true) let JSON2 = [ "prop1": "prop1", "prop2": NSNull() ] let immutable2 = mapper.map(JSON2) XCTAssert(immutable2 == nil) let JSONFromObject = mapper.toJSON(immutable) XCTAssert(mapper.map(JSONFromObject) == immutable) } func testBasicParsing() { let username = "John Doe" let identifier = "user8723" let photoCount = 13 let age = 1227 let weight = 123.23 let float: Float = 123.231 let drinker = true let smoker = false let arr = [ "bla", true, 42 ] let birthday = NSDate(timeIntervalSince1970: 1398956159) let y2k = NSDate(timeIntervalSince1970: 946684800) // calculated via http://wolfr.am/2pliY~W9 let directory = [ "key1" : "value1", "key2" : false, "key3" : 142 ] let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17, \"birthdayOpt\" : 1398956159, \"y2kOpt\" : \"2000-01-01T00:00:00Z\", \"username\" : \"sub user\" }" let userJSONString = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"birthday\": 1398956159, \"birthdayOpt\": 1398956159, \"y2k\" : \"2000-01-01T00:00:00Z\", \"y2kOpt\" : \"2000-01-01T00:00:00Z\", \"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" if let user = userMapper.map(string: userJSONString) { XCTAssertEqual(username, user.username, "Username should be the same") XCTAssertEqual(identifier, user.identifier!, "Identifier should be the same") XCTAssertEqual(photoCount, user.photoCount, "PhotoCount should be the same") XCTAssertEqual(age, user.age!, "Age should be the same") XCTAssertEqual(weight, user.weight!, "Weight should be the same") XCTAssertEqual(float, user.float!, "float should be the same") XCTAssertEqual(drinker, user.drinker, "Drinker should be the same") XCTAssertEqual(smoker, user.smoker!, "Smoker should be the same") XCTAssertEqual(birthday, user.birthday, "Birthday should be the same") XCTAssertEqual(birthday, user.birthdayOpt!, "Birthday should be the same") XCTAssertEqual(y2k, user.y2k, "Y2K date should be the same") XCTAssertEqual(y2k, user.y2kOpt!, "Y2K date should be the same") println(Mapper().toJSONString(user, prettyPrint: true)) } else { XCTAssert(false, "Mapping user object failed") } } func testInstanceParsing() { let username = "John Doe" let identifier = "user8723" let photoCount = 13 let age = 1227 let weight = 123.23 let float: Float = 123.231 let drinker = true let smoker = false let arr = [ "bla", true, 42 ] let birthday = NSDate(timeIntervalSince1970: 1398956159) let y2k = NSDate(timeIntervalSince1970: 946684800) let directory = [ "key1" : "value1", "key2" : false, "key3" : 142 ] let subUserJSON = "{\"identifier\" : \"user8723\", \"drinker\" : true, \"age\": 17,\"birthdayOpt\" : 1398956159, \"y2kOpt\" : \"2000-01-01T00:00:00Z\", \"username\" : \"sub user\" }" let userJSONString = "{\"username\":\"\(username)\",\"identifier\":\"\(identifier)\",\"photoCount\":\(photoCount),\"age\":\(age),\"drinker\":\(drinker),\"smoker\":\(smoker), \"arr\":[ \"bla\", true, 42 ], \"dict\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"arrOpt\":[ \"bla\", true, 42 ], \"dictOpt\":{ \"key1\" : \"value1\", \"key2\" : false, \"key3\" : 142 }, \"birthday\": 1398956159, \"birthdayOpt\": 1398956159, \"y2k\" : \"2000-01-01T00:00:00Z\", \"y2kOpt\" : \"2000-01-01T00:00:00Z\", \"weight\": \(weight), \"float\": \(float), \"friend\": \(subUserJSON), \"friendDictionary\":{ \"bestFriend\": \(subUserJSON)}}" let user = Mapper().map(string: userJSONString, toObject: User()) XCTAssertEqual(username, user.username, "Username should be the same") XCTAssertEqual(identifier, user.identifier!, "Identifier should be the same") XCTAssertEqual(photoCount, user.photoCount, "PhotoCount should be the same") XCTAssertEqual(age, user.age!, "Age should be the same") XCTAssertEqual(weight, user.weight!, "Weight should be the same") XCTAssertEqual(float, user.float!, "float should be the same") XCTAssertEqual(drinker, user.drinker, "Drinker should be the same") XCTAssertEqual(smoker, user.smoker!, "Smoker should be the same") XCTAssertEqual(birthday, user.birthday, "Birthday should be the same") XCTAssertEqual(birthday, user.birthdayOpt!, "Birthday should be the same") XCTAssertEqual(y2k, user.y2k, "Y2K date should be the same") XCTAssertEqual(y2k, user.y2kOpt!, "Y2K date should be the same") println(Mapper().toJSONString(user, prettyPrint: true)) } func testDictionaryParsing() { var name: String = "Genghis khan" var UUID: String = "12345" var major: Int = 99 var minor: Int = 1 let json: [String: AnyObject] = ["name": name, "UUID": UUID, "major": major] //test that the sematics of value types works as expected. the resulting maped student //should have the correct minor property set even thoug it's not mapped var s = Student() s.minor = minor let student = Mapper().map(json, toObject: s) XCTAssertEqual(student.name!, name, "Names should be the same") XCTAssertEqual(student.UUID!, UUID, "UUID should be the same") XCTAssertEqual(student.major!, major, "major should be the same") XCTAssertEqual(student.minor!, minor, "minor should be the same") //Test that mapping a reference type works as expected while not relying on the return value var username: String = "Barack Obama" var identifier: String = "Political" var photoCount: Int = 1000000000 let json2: [String: AnyObject] = ["username": username, "identifier": identifier, "photoCount": photoCount] let user = User() Mapper().map(json2, toObject: user) XCTAssertEqual(user.username, username, "Usernames should be the same") XCTAssertEqual(user.identifier!, identifier, "identifiers should be the same") XCTAssertEqual(user.photoCount, photoCount, "photo count should be the same") } func testNestedKeys(){ let heightInCM = 180.0 let userJSONString = "{\"username\":\"bob\", \"height\": {\"value\": \(heightInCM), \"text\": \"6 feet tall\"} }" if let user = userMapper.map(string: userJSONString) { XCTAssertEqual(user.heightInCM!, heightInCM, "Username should be the same") } else { XCTAssert(false, "Nested key failed") } } func testNullObject() { let userJSONString = "{\"username\":\"bob\"}" if let user = userMapper.map(string: userJSONString) { XCTAssert(user.heightInCM == nil, "Username should be the same") } else { XCTAssert(false, "Null Object failed") } } func testToObjectFromString() { let username = "bob" let userJSONString = "{\"username\":\"\(username)\"}" var user = User() user.username = "Tristan" Mapper().map(string: userJSONString, toObject: user) XCTAssert(user.username == username, "Username should be the same") } func testToObjectFromJSON() { let username = "bob" let userJSON = ["username":username] var user = User() user.username = "Tristan" Mapper().map(userJSON, toObject: user) XCTAssert(user.username == username, "Username should be the same") } func testToObjectFromAnyObject() { let username = "bob" let userJSON = ["username":username] var user = User() user.username = "Tristan" Mapper().map(userJSON as AnyObject?, toObject: user) XCTAssert(user.username == username, "Username should be the same") } func testToJSONAndBack(){ var user = User() user.username = "tristan_him" user.identifier = "tristan_him_identifier" user.photoCount = 0 user.age = 28 user.weight = 150 user.drinker = true user.smoker = false user.arr = ["cheese", 11234] user.birthday = NSDate() user.y2k = NSDate(timeIntervalSince1970: 946684800) user.imageURL = NSURL(string: "http://google.com/image/1234") user.intWithString = 12345 let jsonString = Mapper().toJSONString(user, prettyPrint: true) println(jsonString) if let parsedUser = userMapper.map(string: jsonString) { XCTAssertEqual(user.identifier!, parsedUser.identifier!, "Identifier should be the same") XCTAssertEqual(user.photoCount, parsedUser.photoCount, "PhotoCount should be the same") XCTAssertEqual(user.age!, parsedUser.age!, "Age should be the same") XCTAssertEqual(user.weight!, parsedUser.weight!, "Weight should be the same") XCTAssertEqual(user.drinker, parsedUser.drinker, "Drinker should be the same") XCTAssertEqual(user.smoker!, parsedUser.smoker!, "Smoker should be the same") XCTAssertEqual(user.imageURL!, parsedUser.imageURL!, "Image URL should be the same") XCTAssertEqual(user.intWithString, parsedUser.intWithString, "Int value from/to String should be the same") // XCTAssert(user.birthday.compare(parsedUser.birthday) == .OrderedSame, "Birthday should be the same") XCTAssert(user.y2k.compare(parsedUser.y2k) == .OrderedSame, "Y2k should be the same") } else { XCTAssert(false, "to JSON and back failed") } } func testUnknownPropertiesIgnored() { let userJSONString = "{\"username\":\"bob\",\"identifier\":\"bob1987\", \"foo\" : \"bar\", \"fooArr\" : [ 1, 2, 3], \"fooObj\" : { \"baz\" : \"qux\" } }" let user = userMapper.map(string: userJSONString) XCTAssert(user != nil, "User should not be nil") } func testInvalidJsonResultsInNilObject() { let userJSONString = "{\"username\":\"bob\",\"identifier\":\"bob1987\"" // missing ending brace let user = userMapper.map(string: userJSONString) XCTAssert(user == nil, "User should be nil due to invalid JSON") } func testMapArrayJSON(){ let name1 = "Bob" let name2 = "Jane" let arrayJSONString = "[{\"name\": \"\(name1)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC875\", \"major\": 541, \"minor\": 123},{ \"name\": \"\(name2)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC876\", \"major\": 54321,\"minor\": 13 }]" let students = Mapper<Student>().mapArray(string: arrayJSONString) XCTAssert(!students.isEmpty, "Student Array should not be empty") XCTAssert(students.count == 2, "There should be 2 students in array") XCTAssert(students[0].name == name1, "First student's does not match") XCTAssert(students[1].name == name2, "Second student's does not match") } // test mapArray() with JSON string that is not an array form // should return a collection with one item func testMapArrayJSONWithNoArray(){ let name1 = "Bob" let arrayJSONString = "{\"name\": \"\(name1)\", \"UUID\": \"3C074D4B-FC8C-4CA2-82A9-6E9367BBC875\", \"major\": 541, \"minor\": 123}" let students = Mapper<Student>().mapArray(string: arrayJSONString) XCTAssert(!students.isEmpty, "Student Array should not be empty") XCTAssert(students.count == 1, "There should be 1 student in array") XCTAssert(students[0].name == name1, "First student's does not match") } func testArrayOfCustomObjects(){ let percentage1: Double = 0.1 let percentage2: Double = 1792.41 let JSON = "{ \"tasks\": [{\"taskId\":103,\"percentage\":\(percentage1)},{\"taskId\":108,\"percentage\":\(percentage2)}] }" let plan = Mapper<Plan>().map(string: JSON) if let tasks = plan?.tasks { let task1 = tasks[0] XCTAssertEqual(task1.percentage!, percentage1, "Percentage 1 should be the same") let task2 = tasks[1] XCTAssertEqual(task2.percentage!, percentage2, "Percentage 2 should be the same") } else { XCTAssert(false, "Tasks not mapped") } } func testDictionaryOfCustomObjects(){ let percentage1: Double = 0.1 let percentage2: Double = 1792.41 let JSON = "{\"tasks\": { \"task1\": {\"taskId\":103,\"percentage\":\(percentage1)}, \"task2\": {\"taskId\":108,\"percentage\":\(percentage2)}}}" let taskDict = Mapper<TaskDictionary>().map(string: JSON) if let task = taskDict?.tasks?["task1"] { XCTAssertEqual(task.percentage!, percentage1, "Percentage 1 should be the same") } else { XCTAssert(false, "Dictionary not mapped") } } func testDoubleParsing(){ let percentage1: Double = 1792.41 let JSON = "{\"taskId\":103,\"percentage\":\(percentage1)}" let task = Mapper<Task>().map(string: JSON) if let task = task { XCTAssertEqual(task.percentage!, percentage1, "Percentage 1 should be the same") } else { XCTAssert(false, "Task not mapped") } } func testMappingAGenericObject(){ let code: Int = 22 let JSON = "{\"result\":{\"code\":\(code)}}" let response = Mapper<Response<Status>>().map(string: JSON) if let status = response?.result?.status { XCTAssertEqual(status, code, "Code was not mapped correctly") } else { XCTAssert(false, "Generic object FAILED to map") } } func testToJSONArray(){ var task1 = Task() task1.taskId = 1 task1.percentage = 11.1 var task2 = Task() task2.taskId = 2 task2.percentage = 22.2 var task3 = Task() task3.taskId = 3 task3.percentage = 33.3 var taskArray = [task1, task2, task3] let JSONArray = Mapper().toJSONArray(taskArray) println(JSONArray) let taskId1 = JSONArray[0]["taskId"] as Int let percentage1 = JSONArray[0]["percentage"] as Double XCTAssertEqual(taskId1, task1.taskId!, "TaskId1 was not mapped correctly") XCTAssertEqual(percentage1, task1.percentage!, "percentage1 was not mapped correctly") let taskId2 = JSONArray[1]["taskId"] as Int let percentage2 = JSONArray[1]["percentage"] as Double XCTAssertEqual(taskId2, task2.taskId!, "TaskId2 was not mapped correctly") XCTAssertEqual(percentage2, task2.percentage!, "percentage2 was not mapped correctly") let taskId3 = JSONArray[2]["taskId"] as Int let percentage3 = JSONArray[2]["percentage"] as Double XCTAssertEqual(taskId3, task3.taskId!, "TaskId3 was not mapped correctly") XCTAssertEqual(percentage3, task3.percentage!, "percentage3 was not mapped correctly") } func testISO8601DateTransformWithInvalidInput() { var JSON: [String: AnyObject] = ["y2kOpt": ""] let user1 = userMapper.map(JSON) XCTAssert(user1.y2kOpt == nil, "ISO8601DateTransform should return nil for empty string") JSON["y2kOpt"] = "incorrect format" let user2 = userMapper.map(JSON) XCTAssert(user2.y2kOpt == nil, "ISO8601DateTransform should return nil for incorrect format") } func testJsonToObjectModelOptionalDictionnaryOfPrimitives() { var json = ["dictStringString":["string": "string"], "dictStringBool":["string": false], "dictStringInt":["string": 1], "dictStringDouble":["string": 1.1], "dictStringFloat":["string": 1.2]] let mapper = Mapper<TestCollectionOfPrimitives>() let testSet = mapper.map(json) XCTAssertTrue(testSet.dictStringString.count == 1) XCTAssertTrue(testSet.dictStringInt.count == 1) XCTAssertTrue(testSet.dictStringBool.count == 1) XCTAssertTrue(testSet.dictStringDouble.count == 1) XCTAssertTrue(testSet.dictStringFloat.count == 1) } func testObjectToModelDictionnaryOfPrimitives() { var object = TestCollectionOfPrimitives() object.dictStringString = ["string": "string"] object.dictStringBool = ["string": false] object.dictStringInt = ["string": 1] object.dictStringDouble = ["string": 1.2] object.dictStringFloat = ["string": 1.3] let json = Mapper<TestCollectionOfPrimitives>().toJSON(object) XCTAssertTrue((json["dictStringString"] as [String:String]).count == 1) XCTAssertTrue((json["dictStringBool"] as [String:Bool]).count == 1) XCTAssertTrue((json["dictStringInt"] as [String:Int]).count == 1) XCTAssertTrue((json["dictStringDouble"] as [String:Double]).count == 1) XCTAssertTrue((json["dictStringFloat"] as [String:Float]).count == 1) let dict:[String: String] = json["dictStringString"] as [String:String] let value = dict["string"]! as String XCTAssertTrue(value == "string") } func testSubclass() { var object = Subclass() object.base = "base var" object.sub = "sub var" let json = Mapper().toJSON(object) let parsedObject = Mapper<Subclass>().map(json) XCTAssert(object.base! == parsedObject.base!, "base class var was not mapped") XCTAssert(object.sub! == parsedObject.sub!, "sub class var was not mapped") } func testGenericSubclass() { var object = GenericSubclass<String>() object.base = "base var" object.sub = "sub var" let json = Mapper().toJSON(object) let parsedObject = Mapper<GenericSubclass<String>>().map(json) XCTAssert(object.base! == parsedObject.base!, "base class var was not mapped") XCTAssert(object.sub! == parsedObject.sub!, "sub class var was not mapped") } func testSubclassWithGenericArrayInSuperclass() { let parsedObject = Mapper<SubclassWithGenericArrayInSuperclass<AnyObject>>().map(string:"{\"genericItems\":[{\"value\":\"value0\"}, {\"value\":\"value1\"}]}") if let genericItems = parsedObject?.genericItems { XCTAssertEqual(genericItems[0].value!, "value0") XCTAssertEqual(genericItems[1].value!, "value1") } else { XCTFail("genericItems should not be .None") } } } infix operator <^> { associativity left } infix operator <*> { associativity left } public func <^><T, U>(f: T -> U, a: T?) -> U? { return a.map(f) } public func <*><T, U>(f: (T -> U)?, a: T?) -> U? { return a.apply(f) } extension Optional { func apply<U>(f: (T -> U)?) -> U? { switch (self, f) { case let (.Some(x), .Some(fx)): return fx(x) default: return .None } } } struct Immutable: Equatable { let prop1: String let prop2: Int let prop3: Bool } extension Immutable: Mappable { static func create(prop1: String)(prop2: Int)(prop3: Bool) -> Immutable { return Immutable(prop1: prop1, prop2: prop2, prop3: prop3) } init?(_ map: Map) { let x = Immutable.create <^> map["prop1"].value() <*> map["prop2"].value() <*> map["prop3"].value() if let x = x { self = x } else { return nil } } mutating func mapping(map: Map) { switch map.mappingType { case .fromJSON: if let x = Immutable(map) { self = x } case .toJSON: var prop1 = self.prop1 var prop2 = self.prop2 var prop3 = self.prop3 prop1 <- map["prop1"] prop2 <- map["prop2"] prop3 <- map["prop3"] } } } func ==(lhs: Immutable, rhs: Immutable) -> Bool { return lhs.prop1 == rhs.prop1 && lhs.prop2 == rhs.prop2 && lhs.prop3 == rhs.prop3 } class Response<T: Mappable>: Mappable { var result: T? required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { result <- map["result"] } } class Status: Mappable { var status: Int? required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { status <- map["code"] } } class Plan: Mappable { var tasks: [Task]? required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { tasks <- map["tasks"] } } class Task: Mappable { var taskId: Int? var percentage: Double? init() {} required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { taskId <- map["taskId"] percentage <- map["percentage"] } } class TaskDictionary: Mappable { var test: String? var tasks: [String : Task]? required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { test <- map["test"] tasks <- map["tasks"] } } // Confirm that struct can conform to `Mappable` struct Student: Mappable { var name: String? var UUID: String? var major: Int? var minor: Int? init() {} init?(_ map: Map) { mapping(map) } mutating func mapping(map: Map) { name <- map["name"] UUID <- map["UUID"] major <- map["major"] minor <- map["minor"] } } class User: Mappable { var username: String = "" var identifier: String? var photoCount: Int = 0 var age: Int? var weight: Double? var float: Float? var drinker: Bool = false var smoker: Bool? var arr: [AnyObject] = [] var arrOptional: [AnyObject]? var dict: [String : AnyObject] = [:] var dictOptional: [String : AnyObject]? var dictString: [String : String]? var friendDictionary: [String : User]? var friend: User? var friends: [User]? = [] var birthday: NSDate = NSDate() var birthdayOpt: NSDate? var y2k: NSDate = NSDate() var y2kOpt: NSDate? var imageURL: NSURL? var intWithString: Int = 0 var heightInCM: Double? init() {} required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { username <- map["username"] identifier <- map["identifier"] photoCount <- map["photoCount"] age <- map["age"] weight <- map["weight"] float <- map["float"] drinker <- map["drinker"] smoker <- map["smoker"] arr <- map["arr"] arrOptional <- map["arrOpt"] dict <- map["dict"] dictOptional <- map["dictOpt"] friend <- map["friend"] friends <- map["friends"] friendDictionary <- map["friendDictionary"] dictString <- map["dictString"] heightInCM <- map["height.value"] birthday <- (map["birthday"], DateTransform()) birthdayOpt <- (map["birthdayOpt"], DateTransform()) y2k <- (map["y2k"], ISO8601DateTransform()) y2kOpt <- (map["y2kOpt"], ISO8601DateTransform()) imageURL <- (map["imageURL"], URLTransform()) intWithString <- (map["intWithString"], TransformOf<Int, String>(fromJSON: { $0?.toInt() }, toJSON: { $0.map { String($0) } })) } var description : String { return "username: \(username) \nid:\(identifier) \nage: \(age) \nphotoCount: \(photoCount) \ndrinker: \(drinker) \nsmoker: \(smoker) \narr: \(arr) \narrOptional: \(arrOptional) \ndict: \(dict) \ndictOptional: \(dictOptional) \nfriend: \(friend)\nfriends: \(friends) \nbirthday: \(birthday)\nbirthdayOpt: \(birthdayOpt) \ny2k: \(y2k) \ny2kOpt: \(y2k) \nweight: \(weight)" } } class TestCollectionOfPrimitives : Mappable { var dictStringString: [String: String] = [:] var dictStringInt: [String: Int] = [:] var dictStringBool: [String: Bool] = [:] var dictStringDouble: [String: Double] = [:] var dictStringFloat: [String: Float] = [:] var arrayString: [String] = [] var arrayInt: [Int] = [] var arrayBool: [Bool] = [] var arrayDouble: [Double] = [] var arrayFloat: [Float] = [] init() {} required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { dictStringString <- map["dictStringString"] dictStringBool <- map["dictStringBool"] dictStringInt <- map["dictStringInt"] dictStringDouble <- map["dictStringDouble"] dictStringFloat <- map["dictStringFloat"] arrayString <- map["arrayString"] arrayInt <- map["arrayInt"] arrayBool <- map["arrayBool"] arrayDouble <- map["arrayDouble"] arrayFloat <- map["arrayFloat"] } } class Base: Mappable { var base: String? init() {} required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { base <- map["base"] } } class Subclass: Base { var sub: String? override init() { super.init() } required init?(_ map: Map) { super.init(map) mapping(map) } override func mapping(map: Map) { super.mapping(map) sub <- map["sub"] } } class GenericSubclass<T>: Base { var sub: String? override init() { super.init() } required init?(_ map: Map) { super.init(map) mapping(map) } override func mapping(map: Map) { super.mapping(map) sub <- map["sub"] } } class WithGenericArray<T: Mappable>: Mappable { var genericItems: [T]? required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { genericItems <- map["genericItems"] } } class ConcreteItem: Mappable { var value: String? required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { value <- map["value"] } } class SubclassWithGenericArrayInSuperclass<Unused>: WithGenericArray<ConcreteItem> { required init?(_ map: Map) { super.init(map) } }
mit
24b7cde89d5e8ef7c7b78ebd3b44136e
31.4825
648
0.633072
3.729869
false
true
false
false
nfls/nflsers
app/v2/Model/Media/Rank.swift
1
589
// // Rank.swift // NFLSers-iOS // // Created by Qingyang Hu on 2018/8/13. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import ObjectMapper class Rank: Model { required init(map: Map) throws { self.rank = try map.value("rank") self.score = try map.value("score") self.time = ISO8601DateFormatter().date(from: try map.value("time"))! self.user = try map.value("user") self.game = try map.value("game") } let rank: Int let score: Int let time: Date let user: User let game: String }
apache-2.0
d07bbd3f2dabf89e8ce05a412f051efd
21.384615
77
0.606529
3.527273
false
false
false
false
abelsanchezali/ViewBuilder
Source/Document/Deserializer/XMLDataDeserializer.swift
1
5014
// // XMLDataDeserializer.swift // ViewBuilder // // Created by Abel Sanchez on 6/9/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import Foundation class XMLDataDeserializerNSXMLParserDelegate: NSObject, XMLParserDelegate { private struct Constants { static var moduleWithNameExpresion: NSRegularExpression? = { try! NSRegularExpression(pattern: "^withName\\(([\\w\\.]*)\\)\\s*$", options: []) }() } let options: DocumentOptions public init(options: DocumentOptions) { self.options = options } var root: DataNode? = nil var error: NSError? = nil var includeParsingInfo: Bool { get { return options.includeParsingInfo } } private var current: DataNode? = nil private var namespaces = [String:String]() func parserDidStartDocument(_ parser: XMLParser) { } func parserDidEndDocument(_ parser: XMLParser) { } private func domainForNamespace(_ namespace: String?) -> String? { guard let namespace = namespace else { return nil } if namespace.hasPrefix("@") { let key = namespace.substring(from: namespace.index(namespace.startIndex, offsetBy: 1)) // Resolve namespaces with module name if let match = Constants.moduleWithNameExpresion?.firstMatch(in: key, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, key.count)), let nameParameter = key.substring(match.range(at:1)) { return options.resolveNamespaceWithName(nameParameter) } // Fallback to defined namespaces return options.resolveValue(for: key) as? String } return namespace } private static let domainSeparator = CharacterSet(charactersIn: ":") private func getPrefixAndName(_ text: String) -> (String?, String) { guard let range = text.rangeOfCharacter(from: XMLDataDeserializerNSXMLParserDelegate.domainSeparator) else { return (nil, text) } let prefix = text.substring(to: range.lowerBound) let name = text.substring(from: range.upperBound) return (prefix, name) } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { let domain = domainForNamespace(namespaceURI) if root == nil { root = DataNode(name: elementName, domain: domain) current = root } else { let node = DataNode(name: elementName, domain: domain, parent: current) current?.childs.append(node) current = node } for (k, v) in attributeDict { let (prefix, name) = getPrefixAndName(k) let domain = prefix != nil ? namespaces[prefix!] : nil current?.attributes.append(DataAttribute(domain: domain, name: name, text: v)) } if includeParsingInfo { current?.debugInfo = DocumentSourceInfo(columnNumber: parser.columnNumber, lineNumber: parser.lineNumber) } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { current?.prefixes = DomainPrefixTable(table: namespaces) current = current?.parent } func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { namespaces[prefix] = domainForNamespace(namespaceURI) } func parser(_ parser: XMLParser, didEndMappingPrefix prefix: String) { namespaces.removeValue(forKey: prefix) } func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error) { root = nil error = validationError as NSError? Log.shared.write("Validation error ocurred (\(validationError))") } func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { root = nil error = parseError as NSError? Log.shared.write("Parse error ocurred (\(parseError))") } } public class XMLDataDeserializer: DataDeserializerProtocol { public class var identifier: String { return "XML" } public required init() { } open func loadData(from path: String, options: DocumentOptions) -> DataNode? { guard let parser = XMLParser(contentsOf: URL(fileURLWithPath: path)) else { return nil } parser.shouldProcessNamespaces = true parser.shouldReportNamespacePrefixes = true let delegate = XMLDataDeserializerNSXMLParserDelegate(options: options) parser.delegate = delegate parser.parse() return delegate.root } }
mit
c70a0bda1f6994fc68e0aac8c0894abf
34.302817
173
0.619789
5.216441
false
false
false
false
KnuffApp/Knuff-iOS
Knuff/ViewControllers/SuccessViewController.swift
1
2550
// // SuccessViewController.swift // Knuff // // Created by Simon Blommegard on 30/03/15. // Copyright (c) 2015 Bowtie. All rights reserved. // import UIKit class SuccessViewController: UIViewController { var titleLabel: UILabel? var pulseView: DevicePulseView? var checkView: InstructionStepView? var infoLabel: UILabel? override func viewDidLoad() { super.viewDidLoad() titleLabel = UILabel() titleLabel!.text = "Push galore!" titleLabel!.font = UIFont(name: "OpenSans-Bold", size: 18) titleLabel!.textColor = UIColor(hex: 0xF7F9FC) titleLabel!.sizeToFit() view.addSubview(titleLabel!) pulseView = DevicePulseView(state: PulseViewState.success) pulseView!.sizeToFit() view.addSubview(pulseView!) checkView = InstructionStepView(title: "You are broadcasting your device", badgeString: nil) checkView!.badge.imageCircleContent = UIImage(named: "Check") checkView!.sizeToFit() view.addSubview(checkView!) infoLabel = UILabel() let deviceName = UIDevice.current.name infoLabel!.text = "To recieve push notifications from your computer just select \"\(deviceName)\" in the device list and tap the home button." infoLabel!.font = UIFont(name: "OpenSans-Light", size: 12) infoLabel!.textColor = UIColor(white: 1, alpha: 1) infoLabel!.textAlignment = .center infoLabel!.numberOfLines = 0 infoLabel!.bounds.size = infoLabel!.sizeThatFits(CGSize(width: 300, height: CGFloat.greatestFiniteMagnitude)) view.addSubview(infoLabel!) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) pulseView!.pulseView.startAnimations() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() titleLabel!.frame.origin = CGPoint( x: round((view.bounds.width/2) - (titleLabel!.bounds.width/2)), y: topLayoutGuide.length + 50 ) checkView!.frame.origin = CGPoint( x: round((view.bounds.width/2) - (checkView!.bounds.width/2)), y: round((view.bounds.height - checkView!.bounds.height) * 0.6) ) let height = checkView!.frame.minY - titleLabel!.frame.maxY pulseView!.frame.origin = CGPoint( x: round((view.bounds.width/2) - (pulseView!.bounds.width/2)), y: titleLabel!.frame.maxY + round(height/2 - (pulseView!.bounds.height/2)) ) infoLabel!.frame.origin = CGPoint( x: round((view.bounds.width/2) - (infoLabel!.bounds.width/2)), y: checkView!.frame.maxY + 20 ) } }
mit
27ba1d2099738e27e37968f9d65db371
30.481481
146
0.68
4.146341
false
false
false
false
Liuyingao/SwiftRepository
Properties.swift
1
3160
struct FixedLengthRange { var firstValue: Int let length : Int } // var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) // rangeOfThreeItems.firstValue = 6 // rangeOfThreeItems.length = 6 let rangeOfFourItems = FixedLengthRange(firstValue: 1, length: 4) // rangeOfFourItems.firstValue = 6 //延时属性 struct LazeProperty{ lazy var data = FixedLengthRange(firstValue: 1, length: 2) var valueCount : Int init(valueCount: Int){ self.valueCount = valueCount } } var demo = LazeProperty(valueCount : 1) print(demo) print(demo.data) //计算属性 struct Rect{ var width : Double var length : Double var square : Double{ get{ return width * length } set{ width = newValue / length length = newValue / width } } } var newRect = Rect(width: 2.0, length: 4.0) print(newRect.width) print(newRect.length) print(newRect.square) newRect.square = 10 print(newRect.width) print(newRect.length) print(newRect.square) //属性观察器 class ObserverFather{ var property1 = 0{ willSet { print("Father property1's willset: newValue:\(newValue), oldValue: \(property1)") } didSet { print("Father property1's didSet: newValue:\(property1), oldValue: \(oldValue)") } } var property2 : Int{ return property1 * 2 } var property3 : Int{ get { return property1 + property2 } set { property1 = newValue - 1 } } } var obs = ObserverFather() obs.property1 = 3 print(obs.property2) print("----------------------------") //可以为除了延迟存储属性之外的其他存储属性添加属性观察器, //也可以通过重写属性的方式为继承的属性(包括存储属性和计算属性)添加属性观察器。 class ObserverSon: ObserverFather{ override var property1: Int { willSet { print("Son property1's willset: newValue:\(newValue), oldValue: \(property1)") } didSet { print("Son property1's didset: newValue:\(property1), oldValue: \(oldValue)") } } override var property2 : Int{ get { return property1 * 4 } set { property1 = newValue / 4 } } override var property3: Int{ willSet { print("Son property3's willset: newValue:\(newValue), oldValue: \(property3)") } didSet { print("Son property3's didset: newValue:\(property3), oldValue: \(oldValue)") } } } var obs1 = ObserverSon() // obs1.property2 = 8 obs1.property3 = 100 //类属性 //static则可以用在所有地方 //class只能用在类的计算属性上 struct SomeStructure { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 1 } } enum SomeEnumeration { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { return 6 } } class SomeClass { static var storedTypeProperty = "Some value." static var count = 0 class var computedTypeProperty: Int { return count++ } static var overrideableComputedTypeProperty: Int { return 107 } } print(SomeClass.computedTypeProperty) print(SomeClass.computedTypeProperty) print(SomeClass.computedTypeProperty) print(SomeClass.computedTypeProperty) print(SomeClass.count)
gpl-2.0
90ed69905162c378a1cb71f267f86f32
19.232877
84
0.691943
3.334086
false
false
false
false
boyXiong/XWSwiftRefreshT
XWSwiftRefreshT/common/XWConst.swift
2
1700
// // XWConst.swift // XWRefresh // // Created by Xiong Wei on 15/9/8. // Copyright © 2015年 Xiong Wei. All rights reserved. // 新浪微博: @爱吃香干炒肉 import UIKit //文字颜色 let XWRefreshLabelTextColor = xwColor(r: 100, g: 100, b: 100) //字体大小 let XWRefreshLabelFont = UIFont.boldSystemFontOfSize(13) /** 头部高度 */ let XWRefreshHeaderHeight:CGFloat = 64 /** 尾部高度 */ let XWRefreshFooterHeight:CGFloat = 44 /** gifView 偏差 */ let XWRefreshGifViewWidthDeviation:CGFloat = 99 /** footer 菊花 偏差 */ let XWRefreshFooterActivityViewDeviation:CGFloat = 100 /** 开始的动画时间 */ let XWRefreshFastAnimationDuration = 0.25 /** 慢的动画时间 */ let XWRefreshSlowAnimationDuration = 0.4 /** 更新的时间 */ let XWRefreshHeaderLastUpdatedTimeKey = "XWRefreshHeaderLastUpdatedTimeKey" /** 也就是上拉下拉的多少*/ let XWRefreshKeyPathContentOffset = "contentOffset" /** 内容的size */ let XWRefreshKeyPathContentSize = "contentSize" /** 内边距 */ let XWRefreshKeyPathContentInset = "contentInset" /** 手势状态 */ let XWRefreshKeyPathPanKeyPathState = "state" let XWRefreshHeaderStateIdleText = "下拉可以刷新" let XWRefreshHeaderStatePullingText = "松开立即刷新" let XWRefreshHeaderStateRefreshingText = "正在刷新数据中..." let XWRefreshFooterStateIdleText = "点击加载更多" let XWRefreshFooterStateRefreshingText = "正在加载更多的数据..." let XWRefreshFooterStateNoMoreDataText = "已经全部加载完毕" /** 图片路径 */ let XWIconSrcPath:String = "Frameworks/XWSwiftRefresh.framework/xw_icon.bundle/xw_down.png" let XWIconLocalPath:String = "xw_icon.bundle/xw_down.png"
mit
8d4fe12c9be40ad4adcd7e166e98f577
22.629032
91
0.76041
3.53012
false
false
false
false
RailwayStations/Bahnhofsfotos
Modules/Shared/Sources/Constants.swift
1
1653
// // Constants.swift // Bahnhofsfotos // // Created by Miguel Dönicke on 16.12.16. // Copyright © 2016 MrHaitec. All rights reserved. // public class Constants { public final class JsonConstants { //Bahnhofs-Konstanten public static let kId = "id" public static let kCountry = "country" public static let kTitle = "title" public static let kLat = "lat" public static let kLon = "lon" public static let kPhotographer = "photographer" public static let kPhotographerUrl = "photographerUrl" public static let kPhotoUrl = "photoUrl" public static let kLicense = "license" public static let kDS100 = "DS100" //Länderkonstanten public static let kCountryCode = "code" public static let kCountryName = "name" public static let kCountryEmail = "email" public static let kCountryTwitterTags = "twitterTags" public static let kCountryTimetableUrlTemplate = "timetableUrlTemplate" } public static let dbFilename = "db.sqlite3" // Links zusammenschrauben public static let baseUrl = "https://api.railway-stations.org" public struct StoryboardIdentifiers { public static let settingsViewController = "SettingsViewController" public static let listViewController = "ListViewController" public static let mapViewController = "MapViewController" public static let signInViewController = "SignInViewController" public static let chatViewController = "ChatViewController" public static let highScoreViewController = "HighScoreViewController" } }
apache-2.0
fb3a5fbef30bb4ac3cc467f6f7cef2bd
36.5
79
0.689697
4.570637
false
false
false
false
darthpelo/SurviveAmsterdam
mobile/Pods/QuadratTouch/Source/Shared/Endpoints/PageUpdates.swift
4
1842
// // Pageupdates.swift // Quadrat // // Created by Constantine Fry on 06/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation public class PageUpdates: Endpoint { override var endpoint: String { return "pageupdates" } /** https://developer.foursquare.com/docs/pageupdates/pageupdates */ public func get(updateId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { return self.getWithPath(updateId, parameters: parameters, completionHandler: completionHandler) } // MARK: - General /** https://developer.foursquare.com/docs/pageupdates/add */ public func add(pageId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = pageId + "/add" return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/pageupdates/list */ public func list(completionHandler: ResponseClosure? = nil) -> Task { let path = "list" return self.getWithPath(path, parameters: nil, completionHandler: completionHandler) } // MARK: - Actions /** https://developer.foursquare.com/docs/pageupdates/delete */ public func delete(updateId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = updateId + "/delete" return self.postWithPath(path, parameters: nil, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/pageupdates/like */ public func like(updateId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = updateId + "/like" return self.postWithPath(path, parameters: nil, completionHandler: completionHandler) } }
mit
fbacc3eadd4f9317682eae42d2b36820
37.375
115
0.680782
4.710997
false
false
false
false
alexsosn/ConvNetSwift
ConvNetSwift/convnet-swift/Layers/LayersInput/LayersInput.swift
1
1690
import Foundation struct InputLayerOpt: LayerOutOptProtocol { var layerType: LayerType = .Input var outSx: Int var outSy: Int var outDepth: Int init(outSx: Int, outSy: Int, outDepth: Int) { self.outSx = outSx self.outSy = outSy self.outDepth = outDepth } } class InputLayer: InnerLayer { var outDepth: Int var outSx: Int var outSy: Int var layerType: LayerType var inAct: Vol? var outAct: Vol? init(opt: InputLayerOpt) { // required: depth outDepth = opt.outDepth // optional: default these dimensions to 1 outSx = opt.outSx outSy = opt.outSy // computed layerType = .Input } func forward(_ V: inout Vol, isTraining: Bool) -> Vol { inAct = V outAct = V return outAct! // simply identity function for now } func backward() -> () {} func getParamsAndGrads() -> [ParamsAndGrads] { return [] } func assignParamsAndGrads(_ paramsAndGrads: [ParamsAndGrads]) { } func toJSON() -> [String: AnyObject] { var json: [String: AnyObject] = [:] json["outDepth"] = outDepth as AnyObject? json["outSx"] = outSx as AnyObject? json["outSy"] = outSy as AnyObject? json["layerType"] = layerType.rawValue as AnyObject? return json } // func fromJSON(json: [String: AnyObject]) -> () { // outDepth = json["outDepth"] // outSx = json["outSx"] // outSy = json["outSy"] // layerType = json["layerType"]; // } }
mit
b02433f6a610cb65df4035b4d0c9aa1a
22.150685
67
0.537278
4.322251
false
false
false
false
glessard/async-deferred
Tests/deferredTests/DeferredTests.swift
3
7908
// // DeferredTests.swift // deferred-tests // // Created by Guillaume Lessard on 2015-07-10. // Copyright © 2015-2020 Guillaume Lessard. All rights reserved. // import XCTest import Foundation import Dispatch import deferred class DeferredTests: XCTestCase { func testValue() { let value = 1 let d = Deferred<Int, Never>(value: value) XCTAssertEqual(d.value, value) XCTAssertEqual(d.state, .resolved) XCTAssertEqual(d.error, nil) } func testError() { let value = nzRandom() let d = Deferred<Never, TestError>(error: TestError(value)) XCTAssertEqual(d.value, nil) XCTAssertEqual(d.state, .resolved) XCTAssertEqual(d.error, TestError(value)) } func testResult() { let value = nzRandom() let d = Deferred(result: Result(catching: { value })) XCTAssertEqual(d.value, value) XCTAssertEqual(d.state, .resolved) XCTAssertEqual(d.error, nil) } func testBeginExecution() { let q = DispatchQueue(label: #function) let e = expectation(description: #function) let r = nzRandom() var d: Deferred<Int, Never>! = nil q.async { d = Deferred<Int, Never>(queue: q) { resolver in resolver.resolve(value: r) e.fulfill() } XCTAssertEqual(d.state, .waiting) d.beginExecution() XCTAssertEqual(d.state, .executing) } waitForExpectations(timeout: 0.1) XCTAssertEqual(d.value, r) XCTAssertEqual(d.state, .resolved) d.beginExecution() XCTAssertEqual(d.state, .resolved) } func testSynchronousInit() { let d1 = Deferred<Int, Cancellation>(notifyingAt: .current) { _ in } XCTAssertEqual(d1.state, .executing) } func testPeek() { let value = nzRandom() let d1 = Deferred<Int, Error>(value: value) XCTAssertEqual(d1.peek(), value) let d2 = Deferred<Int, Cancellation> { _ in } XCTAssertEqual(d2.peek(), nil) XCTAssertEqual(d2.state, .waiting) d2.cancel() XCTAssertNotNil(d2.peek()) XCTAssertEqual(d2.peek(), .canceled()) XCTAssertEqual(d2.state, .resolved) } func testValueBlocks() { let wait = 0.01 let value = nzRandom() let s = DispatchSemaphore(value: 0) let busy = Deferred<Int, Never> { resolver in s.wait() resolver.resolve(value: value) } let e = expectation(description: "Timing out on Deferred") let fulfillTime = DispatchTime.now() + wait DispatchQueue.global().async { XCTAssertEqual(busy.state, .waiting) let v = busy.value XCTAssertEqual(busy.state, .resolved) XCTAssertEqual(v, value) if .now() < fulfillTime { XCTFail("delayed.value unblocked too soon") } } DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: fulfillTime) { e.fulfill() } waitForExpectations(timeout: 0.1) { _ in s.signal() } } func testValueUnblocks() { let wait = 0.01 let s = DispatchSemaphore(value: 0) let busy = Deferred<DispatchTimeoutResult, Never> { resolver in let timeoutResult = s.wait(timeout: .now() + wait) resolver.resolve(.success(timeoutResult)) } let e = expectation(description: #function) let fulfillTime = DispatchTime.now() + wait DispatchQueue.global().async { XCTAssertEqual(busy.state, .waiting) let v = busy.value XCTAssertEqual(busy.state, .resolved) XCTAssertEqual(v, .timedOut) if .now() < fulfillTime { XCTFail("delayed.value unblocked too soon") } e.fulfill() } waitForExpectations(timeout: 0.1) } func testNotify() { let wait = 0.01 let s = DispatchSemaphore(value: 0) let busy = Deferred<DispatchTimeoutResult, Never>(queue: .global(qos: .utility)) { resolver in let timeoutResult = s.wait(timeout: .now() + wait) resolver.resolve(value: timeoutResult) } let e1 = expectation(description: #function + "-1") busy.notify(queue: .global(qos: .userInteractive)) { result in XCTAssertEqual(result.value, try! result.get()) e1.fulfill() } waitForExpectations(timeout: 0.1) let e2 = expectation(description: #function + "-2") busy.notify { result in e2.fulfill() } waitForExpectations(timeout: 0.1) } func testGet() throws { let d = Double(nzRandom()) let e = TestError(1) let d1 = Deferred<Double, TestError>(value: d) let d2 = Deferred<Double, TestError>(error: e) var double = 0.0 do { double = try d1.get() double = try d2.get() XCTFail() } catch let error as TestError { XCTAssertEqual(error, e) } XCTAssertEqual(double, d) } func testState() { let s = DispatchSemaphore(value: 0) let e = expectation(description: "state") let d = Deferred<DispatchTimeoutResult, Error>(task: { s.wait(timeout: .now() + 1.0) }) d.notify(handler: { r in if case .success = r { e.fulfill() } }) XCTAssertEqual(d.state, .executing) XCTAssertNotEqual(d.state, .resolved) s.signal() waitForExpectations(timeout: 1.0) XCTAssertEqual(d.state, .resolved) } func testNotifyWaiters() throws { let (t, d) = Deferred<Int, Never>.CreatePair() let s = Deferred<Int, Never>(value: 0) let e1 = expectation(description: #function) d.notify(queue: .global(), handler: { _ in e1.fulfill()}) t.retainSource(s) let e2 = expectation(description: #function) d.notify(queue: nil, handler: { _ in e2.fulfill() }) let e3 = expectation(description: #function) d.notify(queue: DispatchQueue(label: #function), handler: { _ in e3.fulfill() }) t.retainSource(s) let r = nzRandom() t.resolve(value: r) waitForExpectations(timeout: 0.1) XCTAssertEqual(d.value, r) } func testCancel() { // Cancel before calculation has run -- cancellation success let d1 = Deferred<Int, Error>(qos: .utility, task: { _ in }) d1.cancel() XCTAssertEqual(d1.value, nil) XCTAssertEqual(d1.error as? Cancellation, .canceled("")) // Set before canceling -- cancellation failure let d2 = Deferred<Int, Cancellation>(value: nzRandom()) d2.cancel("message") XCTAssertEqual(d2.error, nil) } func testErrorTypes() { let customMessage = "Custom Message" let cancellations: [Cancellation] = [ .canceled(""), .canceled(customMessage), .timedOut(""), .timedOut(customMessage), ] let cancellationStrings = cancellations.map(String.init(describing: )) // cancellationStrings.forEach({print($0)}) for (i,e) in cancellations.enumerated() { XCTAssertEqual(String(describing: e), cancellationStrings[i]) } let invalidations: [Invalidation] = [ .invalid(""), .invalid(customMessage), ] let invalidationStrings = invalidations.map(String.init(describing:)) // invalidationStrings.forEach({print($0)}) for (i,e) in invalidations.enumerated() { XCTAssertEqual(String(describing: e), invalidationStrings[i]) } } } extension Result: ResultWrapper { public var result: Result<Success, Failure> { return self } } class ResultWrapperTests: XCTestCase { func testAccessors() { let r = nzRandom() var re = Result<Int, TestError>.success(r) XCTAssertEqual(re.value, r) XCTAssertEqual(re.error, nil) re = .failure(TestError(r)) XCTAssertEqual(re.value, nil) XCTAssertEqual(re.error, TestError(r)) let rn = Result<Int, Never>.success(r) let rr = rn.value XCTAssertEqual(rr, r) XCTAssertEqual(rn.error, nil) } func testGet() throws { let r = nzRandom() let re = Deferred<Never, TestError>(error: TestError(r)) do { let _: Never = try re.get() } catch TestError.value(let e) { XCTAssertEqual(e, r) } let rn = Deferred<Int, Never>(value: r) XCTAssertEqual(rn.get(), r) } }
mit
79a4fcc76ed61b6938b093b19200c1f5
23.404321
91
0.638295
3.827202
false
true
false
false
Ruenzuo/Traveler
Traveler/Traveler/Source/TravelerOAuthViewController.swift
1
6012
// // TravelerOAuthViewController.swift // Traveler // // Created by Renzo Crisostomo on 26/09/15. // Copyright © 2015 Ruenzuo.io. All rights reserved. // import UIKit public protocol TravelerOAuthViewControllerDelegate { func viewControllerDidFinishAuthorization(viewController: TravelerOAuthViewController) func viewController(viewController: TravelerOAuthViewController, didFinishAuthorizationWithError error:NSError) } public class TravelerOAuthViewController: UIViewController, UIWebViewDelegate { let webView: UIWebView; let PSNAuthorize = "https://auth.api.sonyentertainmentnetwork.com/2.0/oauth/authorize?response_type=code&client_id=78420c74-1fdf-4575-b43f-eb94c7d770bf&redirect_uri=https%3a%2f%2fwww.bungie.net%2fen%2fUser%2fSignIn%2fPsnid&scope=psn:s2s&request_locale=en" let PSNLogin = "https://auth.api.sonyentertainmentnetwork.com/login.jsp" public var delegate: TravelerOAuthViewControllerDelegate? // MARK: - Override public required init?(coder aDecoder: NSCoder) { fatalError("Not supported") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { webView = UIWebView() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } convenience init() { self.init(nibName: nil, bundle: nil) } public override func loadView() { self.title = "Login" let backgroundView = UIView() backgroundView.backgroundColor = .whiteColor() webView.translatesAutoresizingMaskIntoConstraints = false backgroundView.addSubview(webView) let topConstraint = NSLayoutConstraint(item: webView, attribute: .Top, relatedBy: .Equal, toItem: backgroundView, attribute: .Top, multiplier: 1, constant: 0) let leftConstraint = NSLayoutConstraint(item: webView, attribute: .Left, relatedBy: .Equal, toItem: backgroundView, attribute: .Left, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: webView, attribute: .Bottom, relatedBy: .Equal, toItem: backgroundView, attribute: .Bottom, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: webView, attribute: .Right, relatedBy: .Equal, toItem: backgroundView, attribute: .Right, multiplier: 1, constant: 0) backgroundView.addConstraints([topConstraint, leftConstraint, bottomConstraint, rightConstraint]) self.view = backgroundView } public override func viewDidLoad() { super.viewDidLoad() webView.delegate = self retrieveCookies() } // MARK: - Private func retrieveCookies() { guard let authorizeURL = NSURL(string: PSNAuthorize) else { notifyWrongURL() return } let authorizeRequest = NSURLRequest(URL: authorizeURL) let session = NSURLSession.sharedSession() UIApplication.sharedApplication().networkActivityIndicatorVisible = true let task = session.dataTaskWithRequest(authorizeRequest) { (data, response, error) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if let _ = error { self.notifyRequestFailed() } else { self.login() } } task.resume() } func login() { guard let loginURL = NSURL(string: PSNLogin) else { notifyWrongURL() return } let loginRequest = NSURLRequest(URL: loginURL) webView.loadRequest(loginRequest) } func notifyWrongURL() { let error = Traveler.wrongURLErrorWithDomain(TravelerConstants.ErrorDomain.Authorization) self.delegate?.viewController(self, didFinishAuthorizationWithError: error) } func notifyCookiesNotFound() { let error = Traveler.cookiesNotFoundErrorWithDomain(TravelerConstants.ErrorDomain.Authorization) self.delegate?.viewController(self, didFinishAuthorizationWithError: error) } func notifyRequestFailed() { let error = Traveler.requestFailedErrorWithDomain(TravelerConstants.ErrorDomain.Authorization) self.delegate?.viewController(self, didFinishAuthorizationWithError: error) } func validateCookies() { guard let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies else { notifyCookiesNotFound() return } var bungledFound = false var bundleatkFound = false for cookie in cookies { switch cookie.name { case "bungled": bungledFound = true case "bungleatk": bundleatkFound = true default: continue } } if (bungledFound && bundleatkFound) { self.delegate?.viewControllerDidFinishAuthorization(self) } else { notifyCookiesNotFound() } } // MARK: - UIWebViewDelegate public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.URL?.host == "auth.api.sonyentertainmentnetwork.com" && request.URL?.path == "/login.do" && navigationType == .FormSubmitted { webView.hidden = true } return true } public func webViewDidStartLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true } public func webViewDidFinishLoad(webView: UIWebView) { UIApplication.sharedApplication().networkActivityIndicatorVisible = false if webView.request?.URL?.host == "www.bungie.net" { validateCookies() } if webView.request?.URL?.query == "authentication_error=true" { webView.hidden = false } } public func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { if error?.code == NSURLErrorCancelled { return } notifyRequestFailed() } }
mit
fd49877d167978b6332ccf74d0f80cdd
36.575
259
0.676427
4.988382
false
false
false
false
maxadamski/swift-corelibs-foundation
Foundation/NSData.swift
2
32274
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif public struct NSDataReadingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let DataReadingMappedIfSafe = NSDataReadingOptions(rawValue: UInt(1 << 0)) public static let DataReadingUncached = NSDataReadingOptions(rawValue: UInt(1 << 1)) public static let DataReadingMappedAlways = NSDataReadingOptions(rawValue: UInt(1 << 2)) } public struct NSDataWritingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let DataWritingAtomic = NSDataWritingOptions(rawValue: UInt(1 << 0)) public static let DataWritingWithoutOverwriting = NSDataWritingOptions(rawValue: UInt(1 << 1)) } public struct NSDataSearchOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let Backwards = NSDataSearchOptions(rawValue: UInt(1 << 0)) public static let Anchored = NSDataSearchOptions(rawValue: UInt(1 << 1)) } public struct NSDataBase64EncodingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let Encoding64CharacterLineLength = NSDataBase64EncodingOptions(rawValue: UInt(1 << 0)) public static let Encoding76CharacterLineLength = NSDataBase64EncodingOptions(rawValue: UInt(1 << 1)) public static let EncodingEndLineWithCarriageReturn = NSDataBase64EncodingOptions(rawValue: UInt(1 << 4)) public static let EncodingEndLineWithLineFeed = NSDataBase64EncodingOptions(rawValue: UInt(1 << 5)) } public struct NSDataBase64DecodingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let IgnoreUnknownCharacters = NSDataBase64DecodingOptions(rawValue: UInt(1 << 0)) public static let Anchored = NSDataSearchOptions(rawValue: UInt(1 << 1)) } private final class _NSDataDeallocator { var handler: (UnsafeMutablePointer<Void>, Int) -> Void = {_,_ in } } private let __kCFMutable: CFOptionFlags = 0x01 private let __kCFGrowable: CFOptionFlags = 0x02 private let __kCFMutableVarietyMask: CFOptionFlags = 0x03 private let __kCFBytesInline: CFOptionFlags = 0x04 private let __kCFUseAllocator: CFOptionFlags = 0x08 private let __kCFDontDeallocate: CFOptionFlags = 0x10 private let __kCFAllocatesCollectable: CFOptionFlags = 0x20 public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { typealias CFType = CFDataRef private var _base = _CFInfo(typeID: CFDataGetTypeID()) private var _length: CFIndex = 0 private var _capacity: CFIndex = 0 private var _deallocator: UnsafeMutablePointer<Void> = nil // for CF only private var _deallocHandler: _NSDataDeallocator? = _NSDataDeallocator() // for Swift private var _bytes: UnsafeMutablePointer<UInt8> = nil internal var _cfObject: CFType { get { if self.dynamicType === NSData.self || self.dynamicType === NSMutableData.self { return unsafeBitCast(self, CFType.self) } else { return CFDataCreate(kCFAllocatorSystemDefault, unsafeBitCast(self.bytes, UnsafePointer<UInt8>.self), self.length) } } } public override required convenience init() { self.init(bytes: nil, length: 0, copy: false, deallocator: nil) } deinit { if _bytes != nil { _deallocHandler?.handler(_bytes, _length) } if self.dynamicType === NSData.self || self.dynamicType === NSMutableData.self { _CFDeinit(self._cfObject) } } internal init(bytes: UnsafeMutablePointer<Void>, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { super.init() let options : CFOptionFlags = (self.dynamicType == NSMutableData.self) ? __kCFMutable | __kCFGrowable : 0x0 if copy { _CFDataInit(unsafeBitCast(self, CFMutableDataRef.self), options, length, UnsafeMutablePointer<UInt8>(bytes), length, false) if let handler = deallocator { handler(bytes, length) } } else { if let handler = deallocator { _deallocHandler!.handler = handler } // The data initialization should flag that CF should not deallocate which leaves the handler a chance to deallocate instead _CFDataInit(unsafeBitCast(self, CFMutableDataRef.self), options | __kCFDontDeallocate, length, UnsafeMutablePointer<UInt8>(bytes), length, true) } } public var length: Int { get { return CFDataGetLength(_cfObject) } } public var bytes: UnsafePointer<Void> { get { return UnsafePointer<Void>(CFDataGetBytePtr(_cfObject)) } } public func copyWithZone(zone: NSZone) -> AnyObject { return self } public func mutableCopyWithZone(zone: NSZone) -> AnyObject { return NSMutableData(bytes: UnsafeMutablePointer<Void>(bytes), length: length, copy: true, deallocator: nil) } public func encodeWithCoder(aCoder: NSCoder) { } public required convenience init?(coder aDecoder: NSCoder) { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } private func byteDescription(limit limit: Int? = nil) -> String { var s = "" let buffer = UnsafePointer<UInt8>(bytes) var i = 0 while i < self.length { if i > 0 && i % 4 == 0 { // if there's a limit, and we're at the barrier where we'd add the ellipses, don't add a space. if let limit = limit where self.length > limit && i == self.length - (limit / 2) { /* do nothing */ } else { s += " " } } let byte = buffer[i] var byteStr = String(byte, radix: 16, uppercase: false) if byte <= 0xf { byteStr = "0\(byteStr)" } s += byteStr // if we've hit the midpoint of the limit, skip to the last (limit / 2) bytes. if let limit = limit where self.length > limit && i == (limit / 2) - 1 { s += " ... " i = self.length - (limit / 2) } else { i += 1 } } return s } override public var debugDescription: String { return "<\(byteDescription(limit: 1024))>" } override public var description: String { return "<\(byteDescription())>" } override internal var _cfTypeID: CFTypeID { return CFDataGetTypeID() } } extension NSData { public convenience init(bytes: UnsafePointer<Void>, length: Int) { self.init(bytes: UnsafeMutablePointer<Void>(bytes), length: length, copy: true, deallocator: nil) } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int) { self.init(bytes: bytes, length: length, copy: false, deallocator: nil) } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, freeWhenDone b: Bool) { self.init(bytes: bytes, length: length, copy: false) { buffer, length in if b { free(buffer) } } } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { self.init(bytes: bytes, length: length, copy: false, deallocator: deallocator) } internal struct NSDataReadResult { var bytes: UnsafeMutablePointer<Void> var length: Int var deallocator: ((buffer: UnsafeMutablePointer<Void>, length: Int) -> Void)? } internal static func readBytesFromFileWithExtendedAttributes(path: String, options: NSDataReadingOptions) throws -> NSDataReadResult { let fd = _CFOpenFile(path, O_RDONLY) if fd < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } defer { close(fd) } var info = stat() let ret = withUnsafeMutablePointer(&info) { infoPointer -> Bool in if fstat(fd, infoPointer) < 0 { return false } return true } if !ret { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } let length = Int(info.st_size) if options.contains(.DataReadingMappedAlways) { let data = mmap(nil, length, PROT_READ, MAP_PRIVATE, fd, 0) // Swift does not currently expose MAP_FAILURE if data != UnsafeMutablePointer<Void>(bitPattern: -1) { return NSDataReadResult(bytes: data, length: length) { buffer, length in munmap(buffer, length) } } } let data = malloc(length) var remaining = Int(info.st_size) var total = 0 while remaining > 0 { let amt = read(fd, data.advancedBy(total), remaining) if amt < 0 { break } remaining -= amt total += amt } if remaining != 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } return NSDataReadResult(bytes: data, length: length) { buffer, length in free(buffer) } } public convenience init(contentsOfFile path: String, options readOptionsMask: NSDataReadingOptions) throws { let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: readOptionsMask) self.init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } public convenience init?(contentsOfFile path: String) { do { let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: []) self.init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } catch { return nil } } public convenience init(data: NSData) { self.init(bytes:data.bytes, length: data.length) } public convenience init(contentsOfURL url: NSURL, options readOptionsMask: NSDataReadingOptions) throws { if url.fileURL { try self.init(contentsOfFile: url.path!, options: readOptionsMask) } else { let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let cond = NSCondition() var resError: NSError? var resData: NSData? let task = session.dataTaskWithURL(url, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in resData = data resError = error cond.broadcast() }) task.resume() cond.wait() if resData == nil { throw resError! } self.init(data: resData!) } } public convenience init?(contentsOfURL url: NSURL) { do { try self.init(contentsOfURL: url, options: []) } catch { return nil } } } extension NSData { public func getBytes(buffer: UnsafeMutablePointer<Void>, length: Int) { CFDataGetBytes(_cfObject, CFRangeMake(0, length), UnsafeMutablePointer<UInt8>(buffer)) } public func getBytes(buffer: UnsafeMutablePointer<Void>, range: NSRange) { CFDataGetBytes(_cfObject, CFRangeMake(range.location, range.length), UnsafeMutablePointer<UInt8>(buffer)) } public func isEqualToData(other: NSData) -> Bool { if self === other { return true } if length != other.length { return false } let bytes1 = bytes let bytes2 = other.bytes if bytes1 == bytes2 { return true } return memcmp(bytes1, bytes2, length) == 0 } public func subdataWithRange(range: NSRange) -> NSData { if range.length == 0 { return NSData() } if range.location == 0 && range.length == self.length { return copyWithZone(nil) as! NSData } return NSData(bytes: bytes.advancedBy(range.location), length: range.length) } internal func makeTemporaryFileInDirectory(dirPath: String) throws -> (Int32, String) { let template = dirPath._nsObject.stringByAppendingPathComponent("tmp.XXXXXX") let maxLength = Int(PATH_MAX) + 1 var buf = [Int8](count: maxLength, repeatedValue: 0) template._nsObject.getFileSystemRepresentation(&buf, maxLength: maxLength) let fd = mkstemp(&buf) if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: dirPath) } let pathResult = NSFileManager.defaultManager().stringWithFileSystemRepresentation(buf, length: Int(strlen(buf))) return (fd, pathResult) } internal class func writeToFileDescriptor(fd: Int32, path: String? = nil, buf: UnsafePointer<Void>, length: Int) throws { var bytesRemaining = length while bytesRemaining > 0 { var bytesWritten : Int repeat { bytesWritten = write(fd, buf.advancedBy(length - bytesRemaining), bytesRemaining) } while (bytesWritten < 0 && errno == EINTR) if bytesWritten <= 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else { bytesRemaining -= bytesWritten } } } public func writeToFile(path: String, options writeOptionsMask: NSDataWritingOptions) throws { var fd : Int32 var mode : mode_t? = nil let useAuxiliaryFile = writeOptionsMask.contains(.DataWritingAtomic) var auxFilePath : String? = nil if useAuxiliaryFile { // Preserve permissions. var info = stat() if lstat(path, &info) == 0 { mode = info.st_mode } else if errno != ENOENT && errno != ENAMETOOLONG { throw _NSErrorWithErrno(errno, reading: false, path: path) } let (newFD, path) = try self.makeTemporaryFileInDirectory(path._nsObject.stringByDeletingLastPathComponent) fd = newFD auxFilePath = path fchmod(fd, 0o666) } else { var flags = O_WRONLY | O_CREAT | O_TRUNC if writeOptionsMask.contains(.DataWritingWithoutOverwriting) { flags |= O_EXCL } fd = _CFOpenFileWithMode(path, flags, 0o666) } if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: path) } defer { close(fd) } try self.enumerateByteRangesUsingBlockRethrows { (buf, range, stop) in if range.length > 0 { do { try NSData.writeToFileDescriptor(fd, path: path, buf: buf, length: range.length) if fsync(fd) < 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } } catch let err { if let auxFilePath = auxFilePath { do { try NSFileManager.defaultManager().removeItemAtPath(auxFilePath) } catch _ {} } throw err } } } if let auxFilePath = auxFilePath { if rename(auxFilePath, path) != 0 { do { try NSFileManager.defaultManager().removeItemAtPath(auxFilePath) } catch _ {} throw _NSErrorWithErrno(errno, reading: false, path: path) } if let mode = mode { chmod(path, mode) } } } public func writeToFile(path: String, atomically useAuxiliaryFile: Bool) -> Bool { do { try writeToFile(path, options: useAuxiliaryFile ? .DataWritingAtomic : []) } catch { return false } return true } public func writeToURL(url: NSURL, atomically: Bool) -> Bool { if url.fileURL { if let path = url.path { return writeToFile(path, atomically: atomically) } } return false } /// Write the contents of the receiver to a location specified by the given file URL. /// /// - parameter url: The location to which the receiver’s contents will be written. /// - parameter writeOptionsMask: An option set specifying file writing options. /// /// - throws: This method returns Void and is marked with the `throws` keyword to indicate that it throws an error in the event of failure. /// /// This method is invoked in a `try` expression and the caller is responsible for handling any errors in the `catch` clauses of a `do` statement, as described in [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42) in [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097) and [Error Handling](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-ID10) in [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216). public func writeToURL(url: NSURL, options writeOptionsMask: NSDataWritingOptions) throws { guard let path = url.path where url.fileURL == true else { let userInfo = [NSLocalizedDescriptionKey : "The folder at “\(url)” does not exist or is not a file URL.", // NSLocalizedString() not yet available NSURLErrorKey : url.absoluteString ?? ""] as Dictionary<String, Any> throw NSError(domain: NSCocoaErrorDomain, code: 4, userInfo: userInfo) } try writeToFile(path, options: writeOptionsMask) } internal func enumerateByteRangesUsingBlockRethrows(block: (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<Bool>) throws -> Void) throws { var err : ErrorType? = nil self.enumerateByteRangesUsingBlock() { (buf, range, stop) -> Void in do { try block(buf, range, stop) } catch let e { err = e } } if let err = err { throw err } } public func enumerateByteRangesUsingBlock(block: (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<Bool>) -> Void) { var stop = false withUnsafeMutablePointer(&stop) { stopPointer in block(bytes, NSMakeRange(0, length), stopPointer) } } } extension NSData : _CFBridgable { } extension CFDataRef : _NSBridgable { typealias NSType = NSData internal var _nsObject: NSType { return unsafeBitCast(self, NSType.self) } } extension NSMutableData { internal var _cfMutableObject: CFMutableDataRef { return unsafeBitCast(self, CFMutableDataRef.self) } } public class NSMutableData : NSData { public required convenience init() { self.init(bytes: nil, length: 0) } public required convenience init?(coder aDecoder: NSCoder) { NSUnimplemented() } internal override init(bytes: UnsafeMutablePointer<Void>, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { super.init(bytes: bytes, length: length, copy: copy, deallocator: deallocator) } public var mutableBytes: UnsafeMutablePointer<Void> { get { return UnsafeMutablePointer(CFDataGetMutableBytePtr(_cfMutableObject)) } } public override var length: Int { get { return CFDataGetLength(_cfObject) } set { CFDataSetLength(_cfMutableObject, newValue) } } public override func copyWithZone(zone: NSZone) -> AnyObject { return NSData(data: self) } } extension NSData { /* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64. */ public convenience init?(base64EncodedString base64String: String, options: NSDataBase64DecodingOptions) { let encodedBytes = Array(base64String.utf8) guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else { return nil } self.init(bytes: decodedBytes, length: decodedBytes.count) } /* Create a Base-64 encoded NSString from the receiver's contents using the given options. */ public func base64EncodedStringWithOptions(options: NSDataBase64EncodingOptions) -> String { var decodedBytes = [UInt8](count: self.length, repeatedValue: 0) getBytes(&decodedBytes, length: decodedBytes.count) let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options) let characters = encodedBytes.map { Character(UnicodeScalar($0)) } return String(characters) } /* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64. */ public convenience init?(base64EncodedData base64Data: NSData, options: NSDataBase64DecodingOptions) { var encodedBytes = [UInt8](count: base64Data.length, repeatedValue: 0) base64Data.getBytes(&encodedBytes, length: encodedBytes.count) guard let decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else { return nil } self.init(bytes: decodedBytes, length: decodedBytes.count) } /* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options. */ public func base64EncodedDataWithOptions(options: NSDataBase64EncodingOptions) -> NSData { var decodedBytes = [UInt8](count: self.length, repeatedValue: 0) getBytes(&decodedBytes, length: decodedBytes.count) let encodedBytes = NSData.base64EncodeBytes(decodedBytes, options: options) return NSData(bytes: encodedBytes, length: encodedBytes.count) } /** The ranges of ASCII characters that are used to encode data in Base64. */ private static var base64ByteMappings: [Range<UInt8>] { return [ 65 ..< 91, // A-Z 97 ..< 123, // a-z 48 ..< 58, // 0-9 43 ..< 44, // + 47 ..< 48, // / 61 ..< 62 // = ] } /** This method takes a byte with a character from Base64-encoded string and gets the binary value that the character corresponds to. If the byte is not a valid character in Base64, this will return nil. - parameter byte: The byte with the Base64 character. - returns: The numeric value that the character corresponds to. */ private static func base64DecodeByte(byte: UInt8) -> UInt8? { var decodedStart: UInt8 = 0 for range in base64ByteMappings { if range.contains(byte) { let result = decodedStart + (byte - range.startIndex) return result == 64 ? 0 : result } decodedStart += range.endIndex - range.startIndex } return nil } /** This method takes six bits of binary data and encodes it as a character in Base64. The value in the byte must be less than 64, because a Base64 character can only represent 6 bits. - parameter byte: The byte to encode - returns: The ASCII value for the encoded character. */ private static func base64EncodeByte(byte: UInt8) -> UInt8 { assert(byte < 64) var decodedStart: UInt8 = 0 for range in base64ByteMappings { let decodedRange = decodedStart ..< decodedStart + (range.endIndex - range.startIndex) if decodedRange.contains(byte) { return range.startIndex + (byte - decodedStart) } decodedStart += range.endIndex - range.startIndex } return 0 } /** This method takes an array of bytes and either adds or removes padding as part of Base64 encoding and decoding. If the fromSize is larger than the toSize, this will inflate the bytes by adding zero between the bits. If the fromSize is smaller than the toSize, this will deflate the bytes by removing the most significant bits and recompacting the bytes. For instance, if you were going from 6 bits to 8 bits, and you had an array of bytes with `[0b00010000, 0b00010101, 0b00001001 0b00001101]`, this would give a result of: `[0b01000001 0b01010010 0b01001101]`. This transition is done when decoding Base64 data. If you were going from 8 bits to 6 bits, and you had an array of bytes with `[0b01000011 0b01101111 0b01101110], this would give a result of: `[0b00010000 0b00110110 0b00111101 0b00101110]. This transition is done when encoding data in Base64. - parameter bytes: The original bytes - parameter fromSize: The number of useful bits in each byte of the input. - parameter toSize: The number of useful bits in each byte of the output. - returns: The resized bytes */ private static func base64ResizeBytes(bytes: [UInt8], fromSize: UInt32, toSize: UInt32) -> [UInt8] { var bitBuffer: UInt32 = 0 var bitCount: UInt32 = 0 var result = [UInt8]() result.reserveCapacity(bytes.count * Int(fromSize) / Int(toSize)) let mask = UInt32(1 << toSize - 1) for byte in bytes { bitBuffer = bitBuffer << fromSize | UInt32(byte) bitCount += fromSize if bitCount % toSize == 0 { while(bitCount > 0) { let byte = UInt8(mask & (bitBuffer >> (bitCount - toSize))) result.append(byte) bitCount -= toSize } } } let paddingBits = toSize - (bitCount % toSize) if paddingBits != toSize { bitBuffer = bitBuffer << paddingBits bitCount += paddingBits } while(bitCount > 0) { let byte = UInt8(mask & (bitBuffer >> (bitCount - toSize))) result.append(byte) bitCount -= toSize } return result } /** This method decodes Base64-encoded data. If the input contains any bytes that are not valid Base64 characters, this will return nil. - parameter bytes: The Base64 bytes - parameter options: Options for handling invalid input - returns: The decoded bytes. */ private static func base64DecodeBytes(bytes: [UInt8], options: NSDataBase64DecodingOptions = []) -> [UInt8]? { var decodedBytes = [UInt8]() decodedBytes.reserveCapacity(bytes.count) for byte in bytes { guard let decoded = base64DecodeByte(byte) else { if options.contains(.IgnoreUnknownCharacters) { continue } else { return nil } } decodedBytes.append(decoded) } return base64ResizeBytes(decodedBytes, fromSize: 6, toSize: 8) } /** This method encodes data in Base64. - parameter bytes: The bytes you want to encode - parameter options: Options for formatting the result - returns: The Base64-encoding for those bytes. */ private static func base64EncodeBytes(bytes: [UInt8], options: NSDataBase64EncodingOptions = []) -> [UInt8] { var encodedBytes = base64ResizeBytes(bytes, fromSize: 8, toSize: 6) encodedBytes = encodedBytes.map(base64EncodeByte) let paddingBytes = (4 - (encodedBytes.count % 4)) % 4 for _ in 0..<paddingBytes { encodedBytes.append(61) } let lineLength: Int if options.contains(.Encoding64CharacterLineLength) { lineLength = 64 } else if options.contains(.Encoding76CharacterLineLength) { lineLength = 76 } else { lineLength = 0 } if lineLength > 0 { var separator = [UInt8]() if options.contains(.EncodingEndLineWithCarriageReturn) { separator.append(13) } if options.contains(.EncodingEndLineWithLineFeed) { separator.append(10) } let lines = encodedBytes.count / lineLength for line in 0..<lines { for (index,character) in separator.enumerate() { encodedBytes.insert(character, atIndex: (lineLength + separator.count) * line + index + lineLength) } } } return encodedBytes } } extension NSMutableData { public func appendBytes(bytes: UnsafePointer<Void>, length: Int) { CFDataAppendBytes(_cfMutableObject, UnsafePointer<UInt8>(bytes), length) } public func appendData(other: NSData) { appendBytes(other.bytes, length: other.length) } public func increaseLengthBy(extraLength: Int) { CFDataSetLength(_cfMutableObject, CFDataGetLength(_cfObject) + extraLength) } public func replaceBytesInRange(range: NSRange, withBytes bytes: UnsafePointer<Void>) { CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer<UInt8>(bytes), length) } public func resetBytesInRange(range: NSRange) { bzero(mutableBytes.advancedBy(range.location), range.length) } public func setData(data: NSData) { length = data.length replaceBytesInRange(NSMakeRange(0, data.length), withBytes: data.bytes) } public func replaceBytesInRange(range: NSRange, withBytes replacementBytes: UnsafePointer<Void>, length replacementLength: Int) { CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer<UInt8>(bytes), replacementLength) } } extension NSMutableData { public convenience init?(capacity: Int) { self.init(bytes: nil, length: 0) } public convenience init?(length: Int) { let memory = malloc(length) self.init(bytes: memory, length: length, copy: false) { buffer, amount in free(buffer) } } }
apache-2.0
36b617d661e346a079fc5a2f6af3d2a6
38.112727
924
0.609551
4.865501
false
false
false
false
firebase/firebase-ios-sdk
Example/FirestoreSample/FirestoreSample/App/FirestoreSampleApp.swift
2
1125
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import SwiftUI import Firebase @main struct FirestoreSampleApp: App { init() { FirebaseApp.configure() let settings = Firestore.firestore().settings settings.host = "localhost:8080" settings.isPersistenceEnabled = false settings.isSSLEnabled = false Firestore.firestore().settings = settings } var body: some Scene { WindowGroup { NavigationView { MenuView() } // see https://stackoverflow.com/q/63740788/ .navigationViewStyle(StackNavigationViewStyle()) } } }
apache-2.0
2820cf72e8ca8a3a9d99fff852953e9c
27.846154
75
0.710222
4.411765
false
false
false
false
tschob/HSAudioPlayer
HSAudioPlayer/Core/Private/HSAudioPlayerLog.swift
1
679
// // HSAudioPlayerLog.swift // HSAudioPlayer // // Created by Hans Seiffert on 02.08.16. // Copyright © 2016 Hans Seiffert. All rights reserved. // import UIKit // MARK: - HSAudioPlayerLog func HSAudioPlayerLog(message: AnyObject = "", file: String = #file, function: String = #function, line: Int = #line) { #if DEBUG if (HSAudioPlayerLogSettings.Verbose == true) { if (HSAudioPlayerLogSettings.DetailedLog == true), let className = NSURL(string: file)?.lastPathComponent?.componentsSeparatedByString(".").first { let log = "\(NSDate()) - [\(className)].\(function)[\(line)]: \(message)" print(log) } else { print(message) } } #endif }
mit
747bd6fb0c5f20236b389252c4da5cf8
26.12
119
0.662242
3.568421
false
false
false
false
austinzheng/swift-worksheets
Session1-Basics.playground/section-1.swift
1
11082
// SWIFT SESSIONS: Basics of Swift // (c) 2014 Austin Zheng // Released under the terms of the MIT License import Cocoa // ------------- WELCOME TO SWIFT ------------- // // Welcome to this set of Swift playgrounds, designed to gently introduce you to key Swift concepts with the aid of // live, functional code examples. // First of all, comments in Swift work a lot like they do in C or C++. Use "//" to start a single-line comment. /* Use "/*" and "*/" to start a multi-line comment. Unlike multi-line comments in C or C++, Swift's multi-line comments can be /* /* nested. */ */ */ // Playgrounds are like a REPL - you can enter code and see immediately what happens. If you're running Xcode 6 DP 4 or // later, you don't need to worry about playgrounds damaging your computer - if something goes wrong, just quit Xcode // and check out a fresh copy of the playground. // Semicolons are optional at the end of lines. But if you have multiple statements on the same line, the statements // must be separated by semicolons. // ------------- DECLARING VARIABLES AND CONSTANTS ------------- // // Let's create a variable. var myFirstVariable = 0 // 'var' is used to declare a variable. A variable can be reassigned. myFirstVariable = 1 myFirstVariable = 2 myFirstVariable = 1000 // Let's create a constant. let myFirstConstant = "hello" // 'let' is used to create a constant. A constant's value can't be changed. // myFirstConstant = "world" // uncommenting this will cause the worksheet to fail... // Swift is statically typed. It figured out what type 'myFirstVariable' and 'myFirstConstant' are by looking at the // values they were assigned. This is an example of TYPE INFERENCE. It shouldn't be confused with dynamic typing, // like in languages such as JavaScript or Python. // Because Swift is statically typed, you can't create a variable holding an integer, and then give it a string or a // boolean: // myFirstVariable = "hello" // INVALID // myFirstVariable = false // INVALID // myFirstVariable = 0.321 // INVALID; there is no implicit conversion between floating-point numbers and integers // You can explicitly state what type a variable or constant should be. // After the name of the variable, add a ':', and then the name of the type. var myString : String = "goodbye" let myFloatConstant : Float = 1.2345678 // ------------- BASIC SWIFT TYPES ------------- // // Swift has a number of basic types. The following is a non-comprehensive list. // // Int represents an integer: let a : Int = -10 // UInt represents a non-negative integer: let b : UInt = 3 // Float represents a floating-point number: let c : Float = 3.14159 // Bool represents 'true' or 'false': let d : Bool = false // String represents a Unicode string of characters: let e : String = "this is a string; 你好,世界!" // Character represents a single character; note the use of double quotes: let f : Character = "\n" // There are also specific-width versions of some of these types: let a1 : Int16 = 4 let b1 : UInt64 = 9 let c1 : Float64 = 1.1111 // What if we want to get the string representation of an integer, or the float representation of an integer? We need to // create new instances using the old values. Here's an example: let someInt : Int = 12345 let myFloat : Float = Float(someInt) let myIntString : String = String(someInt) // (Note that C-style casting does not work in Swift. You cannot coerce an Int to a Float, for example.) // Let's look at strings in a little more depth. You can concatenate strings using "+": let myConcatString = "the quick " + "brown fox " + "jumps over " + "the lazy " + "dog" // If you want to interpose another object in a string, use "\(<some expression>)" syntax, as demonstrated below: let myMathString = "the sum of \(someInt) and \(999) is \(someInt + 999)" // Because strings support Unicode, string length (and the distinction between characters and graphemes) is sort of // complicated. Refer to the Swift documentation for more details. // ------------- PRINTING TO CONSOLE ------------- // // Use the 'println()' function to print to the console. Note that you can't see the console in a playground unless you // mouse over a result in the right sidebar, and then click the circle icon. println("bleh") // ------------- SWIFT CONTAINERS ------------- // // Swift also comes with two types of containers: // // Arrays are an ordered collection of items. Arrays are typed: you can have an Array of Strings or an Array of Ints, // but not a single Array that contains both types of items. // Array literals are defined using square brackets. Each item in the array is separated by a comma. let myFirstArray = [1, 2, 3, 4, 5] // Dictionaries, known as maps in other languages, store key-value pairs. Each key maps to a corresponding value. Like // Arrays, Dictionaries are typed, according to both their keys and their values. A dictionary with String keys and // String values is different from a dictionary with Int keys and String values. // Dictionary literals are defined using square brackets, with ':' separating keys from values, and ',' separating // key-value pairs: let stringToStringDict = ["California" : "CA", "Delaware" : "DE", "Wyoming" : "WY"] let intToBoolDict = [0 : false, 1 : true, 2 : false, 3 : true] // Get the number of items in an array or dictionary using the "count" property: myFirstArray.count // returns 5, since there are 5 items in the array stringToStringDict.count // returns 3, since there are three key-value pairs // Get an item in an array using square brackets and the 0-based index of the item you want. Note that using a negative // index, or an index greater than or equal to the number of items in the array, will cause a crash. let firstItem = myFirstArray[0] // = 1 // Get an item from a dictionary using square brackets and the desired key. Note that we place an '!' after the // expression; this is because a dictionary might not have the desired key, so it might return nil. More on this topic // in a future worksheet. let itemInDictionary = intToBoolDict[0]! // = false // Note that dictionaries and arrays created using 'let' cannot be modified at all! If you want to create a mutable // array or dictionary, use 'var': var myMutableArray = [1, 2, 3] // Change the value of an array item by using square brackets. For example, let's set the first item to 100. myMutableArray[0] // originally 1 myMutableArray[0] = 100 myMutableArray[0] // now 100 // Append an item to an array using 'append': myMutableArray.append(99) myMutableArray // now [100, 2, 3, 99] // Delete an item using 'removeAtIndex' or 'removeAll': myMutableArray.removeAtIndex(1) myMutableArray // now [100, 3, 99], since '2' was removed myMutableArray.removeAll(keepCapacity: true) // For dictionaries, use square brackets to either add a new key-value pair, or replace an existing key's value with a // new value: var myMutableDict = ["California" : "CC", "Delaware" : "DE"] myMutableDict["Alabama"] = "AL" myMutableDict["Calfornia"] = "CA" // Remove an item using 'removeValueForKey': myMutableDict.removeValueForKey("California") myMutableDict // Now, no more entry for "California" // ------------- OPERATORS ------------- // // As you might have surmised, Swift comes with the standard suite of C-style operators. 5 + 4 // 9 2 / 3 // 0 2.0 / 3.0 // 0.66666667 -5 % 2 // -1 var someNumber = 1 someNumber++ // See the Swift documentation for more details. A couple of notes: // - Arithmetic is checked by default. If your arithmetic expression's result would cause an overflow or underflow, a // runtime error is raised. Use the unchecked arithmetic operators, &+, &-, &*, &/, &%, to avoid this behavior. // - The '%' operator calculates the proper remainder for a division operation involving negative operands. // ------------- CONTROL FLOW ------------- // // Swift has the standard control flow structures. In most cases, parentheses around the predicates are optional, as // demonstrated below: var testNumber = 10 var whileCounter = 0 // IF STATEMENTS, including optional 'else if' and 'else' clauses. if testNumber > 5 { "ifTestNumber is 6 or greater" } else if testNumber > 1 { "ifTestNumber is between 2 and 5" } else { "ifTestNumber is at most 1" } // WHILE LOOP while whileCounter < 10 { println("working!") whileCounter++ } // DO-WHILE LOOP whileCounter = 0 do { println("working again!") whileCounter++ } while whileCounter < 10 // TRADITIONAL FOR LOOP // (note the declaration of the loop counter variable using 'var') for var i = 0; i < 10; i++ { println("counting up; i is \(i)") } // FOR-EACH LOOP // (note that type inference allows the compiler to figure out that 'a' must be a String) let animals = ["cat", "dog", "bird", "fish", "honeybee"] for a in animals { println("the current animal is \(a)") } // FOR-EACH LOOP WITH INDICES, by using "enumerate()" for (index, a) in enumerate(animals) { println("animal number \(index + 1) is \(a)") } // SWITCH STATEMENTS exist, but will be covered in more detail in another worksheet. switch testNumber { case 0: println("Test number is 0") case 10: println("Test number is 10") default: println("Test number is something else") } // A couple of notes on switch statements: // - They must be comprehensive. Provide a 'default' clause if the compiler complains. // - Swift switch statements do NOT fall through by default. Only one of the three strings will be printed in the above // example, no matter what the input is. The 'fallthrough' keyword can be used to explicitly force execution to // continue onto the next case's code. // - They can do far more than the traditional C-style switch statement. // ------------- FUNCTIONS ------------- // // Swift has functions, like many other languages. // // Declare a function using the 'func' keyword, followed by its name and parentheses. The function body goes inside // curly braces: func doSomethingNifty() { println("hello") } // Function calls are done using the standard C conventions: doSomethingNifty() // calls the function // What if we want the function to return a value? Add an "-> TypeName" after the parentheses: func returnHelloWorld() -> String { return "hello world" } // Note that if we say our function returns a value, it MUST return a value for all possible code paths. Otherwise, the // compiler will complain. Comment out the "return "hello world"" statement above and see what happens. // What if we want to pass arguments into the function? Add the arguments as demonstrated below: // Function arguments are separated by commas. They take the form 'argumentName : ArgumentType'. func addThreeNumbers(firstNumber: Int, secondNumber: Int, thirdNumber: Int) -> Int { return firstNumber + secondNumber + thirdNumber } // Call this function with the appropriate arguments, just like with C or similar languages: let mySum = addThreeNumbers(1, 2, 3) // mySum = 6
mit
37a6a86ce212673866c0ba3e273beccf
38.827338
120
0.705022
3.968459
false
false
false
false
bootstraponline/FBSimulatorControl
fbsimctl/FBSimulatorControlKit/Sources/Parser.swift
2
11226
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import Foundation import FBSimulatorControl public enum ParseError : Error, CustomStringConvertible { case endOfInput case doesNotMatch(String, String) case couldNotInterpret(String, String) case custom(String) public var description: String { get { switch self { case .endOfInput: return "End of Input" case .doesNotMatch(let expected, let actual): return "'\(actual)' does not match '\(expected)'" case .couldNotInterpret(let typeName, let actual): return "\(actual) could not be interpreted as \(typeName)" case .custom(let message): return message } }} } /** Protocol for parsing a list of tokens. */ public struct Parser<A> : CustomStringConvertible { let matchDescription: ParserDescription let output: ([String]) throws -> ([String], A) init(_ matchDescription: ParserDescription, output: @escaping ([String]) throws -> ([String], A)) { self.matchDescription = matchDescription self.output = output } public func parse(_ tokens: [String]) throws -> ([String], A) { let (nextTokens, value) = try output(tokens) return (nextTokens, value) } public var description: String { return self.matchDescription.normalised.usage } } /** Primitives */ extension Parser { func fmap<B>(_ f: @escaping (A) throws -> B) -> Parser<B> { return Parser<B>(self.matchDescription) { input in let (tokensOut, a) = try self.output(input) let b = try f(a) return (tokensOut, b) } } func bind<B>(_ f: @escaping (A) -> Parser<B>) -> Parser<B> { return Parser<B>(self.matchDescription) { tokens in let (tokensA, valueA) = try self.parse(tokens) let (tokensB, valueB) = try f(valueA).parse(tokensA) return (tokensB, valueB) } } func optional() -> Parser<A?> { return Parser<A?>(OptionalDesc(child: self.matchDescription)) { tokens in do { let (tokens, value) = try self.parse(tokens) return (tokens, Optional.some(value)) } catch { return (tokens, nil) } } } func handle(_ f: @escaping (ParseError) -> A) -> Parser<A> { return Parser<A>(self.matchDescription) { tokens in do { return try self.parse(tokens) } catch let error as ParseError { return (tokens, f(error)) } } } func sequence<B>(_ p: Parser<B>) -> Parser<B> { return self .bind({ _ in p }) .describe(SequenceDesc(children: [ self.matchDescription, p.matchDescription ])) } } /** Derivatives */ extension Parser { func fallback(_ a: A) -> Parser<A> { return self.handle { _ in a } } /** * sectionize * * Wrap the description of this parser in a `SectionDesc`. */ func sectionize(_ tag: String, _ name: String, _ explain: String) -> Parser<A> { let desc = SectionDesc( tag: tag, name: name, desc: explain, child: matchDescription) return Parser(desc, output: output) } /** * topLevel * * Version of this parser where the description has been updated to indicate * that it is used to parse the whole argument list from the CLI. When * printing the usage statement, we will prepend the name of the app to the * front of the description to show this to users. */ var topLevel: Parser<A> { let appPath = CommandLine.arguments.first! let appName = (appPath as NSString).lastPathComponent let desc = SequenceDesc(children: [CmdDesc(cmd: appName), matchDescription]) return Parser(desc, output: output) } /** * withExpandedDesc * * Version of this parser where the description has been expanded to span * multiple lines, if it can. */ var withExpandedDesc: Parser<A> { switch matchDescription { case let choice as ChoiceDesc: return Parser(choice.expanded, output: output) default: return self } } func describe(_ description: ParserDescription) -> Parser<A> { return Parser(description, output: self.output) } static var passthrough: Parser<NSNull> { return Parser<NSNull>(SequenceDesc(children: [])) { tokens in return (tokens, NSNull()) } } static var noRemaining: Parser<NSNull> { get { return Parser<NSNull>(SequenceDesc(children: [])) { tokens in if tokens.count > 0 { throw ParseError.custom("There were remaining tokens \(tokens)") } return ([], NSNull()) } }} static func fail(_ error: ParseError) -> Parser<A> { return Parser<A>(ChoiceDesc(children: [])) { _ in throw error } } static func single(_ description: ParserDescription, f: @escaping (String) throws -> A) -> Parser<A> { return Parser<A>(description) { tokens in guard let actual = tokens.first else { throw ParseError.endOfInput } return try (Array(tokens.dropFirst(1)), f(actual)) } } static func ofString(_ string: String, _ constant: A) -> Parser<A> { return Parser.single(CmdDesc(cmd: string)) { token in if token != string { throw ParseError.doesNotMatch(token, string) } return constant } } static func ofFlag<T>(_ flag: String, _ val: T, _ explanation: String) -> Parser<T> { return Parser<T> .ofString("--" + flag, val) .describe(FlagDesc(name: flag, desc: explanation)) } static func ofFlag(_ flag: String, _ explanation: String) -> Parser<Bool> { return ofFlag(flag, true, explanation).fallback(false) } static func ofFlagWithArg<A>(_ flag: String, _ arg: Parser<A>, _ explanation: String) -> Parser<A> { return Parser<()> .ofFlag(flag, (), explanation) .sequence(arg) } static func ofCommandWithArg(_ cmd: String, _ arg: Parser<A>) -> Parser<A> { return Parser<()> .ofString(cmd, ()) .sequence(arg) } static func ofTwoSequenced<B>(_ a: Parser<A>, _ b: Parser<B>) -> Parser<(A, B)> { return a.bind({ valueA in return b.fmap { valueB in return (valueA, valueB) } }).describe(SequenceDesc(children: [ a.matchDescription, b.matchDescription ])) } static func ofThreeSequenced<B, C>(_ a: Parser<A>, _ b: Parser<B>, _ c: Parser<C>) -> Parser<(A, B, C)> { return a.bind({ valueA in return b.bind { valueB in return c.fmap { valueC in return (valueA, valueB, valueC) } } }).describe(SequenceDesc(children: [ a.matchDescription, b.matchDescription, c.matchDescription ])) } static func ofFourSequenced<B, C, D>(_ a: Parser<A>, _ b: Parser<B>, _ c: Parser<C>, _ d: Parser<D>) -> Parser<(A, B, C, D)> { return a.bind({ valueA in return b.bind { valueB in return c.bind { valueC in return d.fmap { valueD in return (valueA, valueB, valueC, valueD) } } } }).describe(SequenceDesc(children: [ a.matchDescription, b.matchDescription, c.matchDescription, d.matchDescription ])) } static func alternative(_ parsers: [Parser<A>]) -> Parser<A> { let descs = parsers.map { $0.matchDescription } return Parser<A>(ChoiceDesc(children: descs)) { tokens in for parser in parsers { do { return try parser.parse(tokens) } catch {} } throw ParseError.doesNotMatch(parsers.description, tokens.description) } } static func manyCount(_ count: Int, _ parser: Parser<A>) -> Parser<[A]> { return self.manySepCount(count, parser, Parser.passthrough) } static func manySepCount<B>(_ count: Int, _ parser: Parser<A>, _ separator: Parser<B>) -> Parser<[A]> { assert(count >= 0, "Count should be >= 0") let desc = AtleastDesc(lowerBound: count, child: parser.matchDescription, sep: separator.matchDescription) return Parser<[A]>(desc) { tokens in var values: [A] = [] var runningArgs = tokens var parseCount = 0 do { while (runningArgs.count > 0) { // Extract the main parsed value let (remainder, value) = try parser.parse(runningArgs) parseCount += 1 runningArgs = remainder values.append(value) // Add the separator, will break out if separator parse fails let (nextRemainder, _) = try separator.parse(runningArgs) runningArgs = nextRemainder } } catch { } if (parseCount < count) { throw ParseError.custom("Only \(parseCount) of \(parser)") } return (runningArgs, values) } } static func manyTill<B>(_ terminatingParser: Parser<B>, _ parser: Parser<A>) -> Parser<[A]> { let desc = SequenceDesc(children: [ AtleastDesc(lowerBound: 0, child: parser.matchDescription), OptionalDesc(child: terminatingParser.matchDescription) ]) return Parser<[A]>(desc) { tokens in var values: [A] = [] var runningArgs = tokens while (runningArgs.count > 0) { do { let _ = try terminatingParser.parse(runningArgs) break } catch { let output = try parser.parse(runningArgs) runningArgs = output.0 values.append(output.1) } } return (runningArgs, values) } } static func many(_ parser: Parser<A>) -> Parser<[A]> { return self.manyCount(0, parser) } static func alternativeMany(_ parsers: [Parser<A>]) -> Parser<[A]> { return Parser.many(Parser.alternative(parsers)) } static func alternativeMany(_ count: Int, _ parsers: [Parser<A>]) -> Parser<[A]> { return Parser.manyCount(count, Parser.alternative(parsers)) } static func union<B : SetAlgebra>(_ parsers: [Parser<B>]) -> Parser<B> { return Parser.union(0, parsers) } static func union<B : SetAlgebra>(_ count: Int, _ parsers: [Parser<B>]) -> Parser<B> { return Parser<B> .alternativeMany(count, parsers) .fmap { sets in var result = B() for set in sets { result.formUnion(set) } return result } } static func accumulate<B : Accumulator>(_ count: Int, _ parsers: [Parser<B>]) -> Parser<B> { return Parser<B> .alternativeMany(count, parsers) .fmap { values in var accumulator = B() for value in values { accumulator = accumulator.append(value) } return accumulator } } static func exhaustive(_ parser: Parser<A>) -> Parser<A> { return Parser .ofTwoSequenced(parser, Parser.noRemaining) .fmap { (original, _) in return original } } } public protocol Parsable { static var parser: Parser<Self> { get } }
bsd-3-clause
cd7584d6a4a7425ab18cbac9237becec
27.135338
128
0.599145
4.055636
false
false
false
false
khizkhiz/swift
test/Serialization/autolinking.swift
8
2940
// RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift // RUN: %target-swift-frontend -emit-ir -lmagic %s -I %t > %t/out.txt // RUN: FileCheck %s < %t/out.txt // RUN: FileCheck -check-prefix=NO-FORCE-LOAD %s < %t/out.txt // RUN: mkdir -p %t/someModule.framework/Modules/someModule.swiftmodule/ // RUN: mv %t/someModule.swiftmodule %t/someModule.framework/Modules/someModule.swiftmodule/%target-swiftmodule-name // RUN: %target-swift-frontend -emit-ir -lmagic %s -F %t > %t/framework.txt // RUN: FileCheck -check-prefix=FRAMEWORK %s < %t/framework.txt // RUN: FileCheck -check-prefix=NO-FORCE-LOAD %s < %t/framework.txt // RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift -autolink-force-load // RUN: %target-swift-frontend -emit-ir -lmagic %s -I %t > %t/force-load.txt // RUN: FileCheck %s < %t/force-load.txt // RUN: FileCheck -check-prefix=FORCE-LOAD-CLIENT %s < %t/force-load.txt // RUN: %target-swift-frontend -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift | FileCheck --check-prefix=NO-FORCE-LOAD %s // RUN: %target-swift-frontend -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift -autolink-force-load | FileCheck --check-prefix=FORCE-LOAD %s // RUN: %target-swift-frontend -emit-ir -parse-stdlib -module-name someModule -module-link-name 0module %S/../Inputs/empty.swift -autolink-force-load | FileCheck --check-prefix=FORCE-LOAD-HEX %s // Linux uses a different autolinking mechanism, based on // swift-autolink-extract. This file tests the Darwin mechanism. // UNSUPPORTED: OS=linux-gnu // UNSUPPORTED: OS=linux-gnueabihf // UNSUPPORTED: OS=freebsd import someModule // CHECK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[LINK_LIST:[0-9]+]]} // CHECK: ![[LINK_LIST]] = !{ // CHECK-DAG: !{{[0-9]+}} = !{!"-lmagic"} // CHECK-DAG: !{{[0-9]+}} = !{!"-lmodule"} // FRAMEWORK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[LINK_LIST:[0-9]+]]} // FRAMEWORK: ![[LINK_LIST]] = !{ // FRAMEWORK-DAG: !{{[0-9]+}} = !{!"-lmagic"} // FRAMEWORK-DAG: !{{[0-9]+}} = !{!"-lmodule"} // FRAMEWORK-DAG: !{{[0-9]+}} = !{!"-framework", !"someModule"} // NO-FORCE-LOAD-NOT: FORCE_LOAD // FORCE-LOAD: @"_swift_FORCE_LOAD_$_module" = common global i1 false // FORCE-LOAD-HEX: @"_swift_FORCE_LOAD_$306d6f64756c65" = common global i1 false // FORCE-LOAD-CLIENT: @"_swift_FORCE_LOAD_$_module" = external global i1 // FORCE-LOAD-CLIENT: @"_swift_FORCE_LOAD_$_module_$_autolinking" = weak hidden constant i1* @"_swift_FORCE_LOAD_$_module" // FORCE-LOAD-CLIENT: @llvm.used = appending global [{{[0-9]+}} x i8*] [ // FORCE-LOAD-CLIENT: i8* bitcast (i1** @"_swift_FORCE_LOAD_$_module_$_autolinking" to i8*) // FORCE-LOAD-CLIENT: ], section "llvm.metadata"
apache-2.0
436331339518f1d2a250e436db96f0d9
56.647059
194
0.67415
3.104541
false
false
false
false
achimk/Swift-UIKit-Extensions
Controllers/UISplitViewController+Extensions.swift
1
2472
// // UISplitViewController+Extensions.swift // // Created by Joachim Kret on 06/10/15. // Copyright © 2015 Joachim Kret. All rights reserved. // import UIKit extension UISplitViewController: Autorotatable { private struct Static { static var token: dispatch_once_t = 0 static var AutorotationMode = "AutorotationMode" } // MARK: Swizzle public override class func initialize() { // make sure this isn't a subclass if self !== UISplitViewController.self { return } dispatch_once(&Static.token) { swizzleInstanceMethod(self, sel1: "shouldAutorotate", sel2: "swizzled_shouldAutorotate") swizzleInstanceMethod(self, sel1: "supportedInterfaceOrientations", sel2: "swizzled_supportedInterfaceOrientations") } } // MARK: Accessors var autorotation: Autorotation { get { if let autorotationMode = objc_getAssociatedObject(self, &Static.AutorotationMode) as? Int { return Autorotation(rawValue: autorotationMode)! } else { return Autorotation.Container } } set { objc_setAssociatedObject(self, &Static.AutorotationMode, newValue.rawValue as Int?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: Swizzled Rotation Methods func swizzled_shouldAutorotate() -> Bool { switch autorotation { case .Container: return self.swizzled_shouldAutorotate() case .ContainerAndTopChildren, .ContainerAndAllChildren: for viewController in viewControllers { if !viewController.shouldAutorotate() { return false } } return true } } func swizzled_supportedInterfaceOrientations() -> UIInterfaceOrientationMask { var mask = UIInterfaceOrientationMask.All.rawValue switch autorotation { case .Container: mask = self.swizzled_supportedInterfaceOrientations().rawValue case .ContainerAndTopChildren, .ContainerAndAllChildren: for viewController in viewControllers.reverse() { mask &= viewController.supportedInterfaceOrientations().rawValue } } return UIInterfaceOrientationMask(rawValue: mask) } }
mit
c31f1e8df5b5c1e52ba0e880a4e87d4d
30.278481
131
0.604209
5.800469
false
false
false
false
cuappdev/podcast-ios
old/Podcast/LoginBackgroundGradientView.swift
1
958
// // LoginBackgroundGradientView.swift // Podcast // // Created by Natasha Armbrust on 4/26/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit class LoginBackgroundGradientView: UIView { var gradient: CAGradientLayer! override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .sea gradient = CAGradientLayer() gradient.colors = [UIColor.aquamarine.cgColor,UIColor.turquoiseBlue.cgColor,UIColor.tealBlue.cgColor,UIColor.bluish.cgColor,UIColor.duskyBlue.cgColor] gradient.locations = [0.25,0.45,0.65,0.85] // kinda arbitrary gradient.startPoint = CGPoint(x: 0.60,y: 0) gradient.endPoint = CGPoint(x: 0.40,y: 1) gradient.frame = frame layer.insertSublayer(gradient, at: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
a639c12c1e9355f00d440278ef7c3888
28.90625
158
0.660397
3.922131
false
false
false
false
kstaring/swift
stdlib/public/core/Policy.swift
1
26227
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Swift Standard Prolog Library. //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Standardized uninhabited type //===----------------------------------------------------------------------===// /// The return type of functions that do not return normally; a type with no /// values. /// /// Use `Never` as the return type when declaring a closure, function, or /// method that unconditionally throws an error, traps, or otherwise does /// not terminate. /// /// func crashAndBurn() -> Never { /// fatalError("Something very, very bad happened") /// } @_fixed_layout public enum Never {} //===----------------------------------------------------------------------===// // Standardized aliases //===----------------------------------------------------------------------===// /// The return type of functions that don't explicitly specify a return type; /// an empty tuple (i.e., `()`). /// /// When declaring a function or method, you don't need to specify a return /// type if no value will be returned. However, the type of a function, /// method, or closure always includes a return type, which is `Void` if /// otherwise unspecified. /// /// Use `Void` or an empty tuple as the return type when declaring a /// closure, function, or method that doesn't return a value. /// /// // No return type declared: /// func logMessage(_ s: String) { /// print("Message: \(s)") /// } /// /// let logger: (String) -> Void = logMessage /// logger("This is a void function") /// // Prints "Message: This is a void function" public typealias Void = () //===----------------------------------------------------------------------===// // Aliases for floating point types //===----------------------------------------------------------------------===// // FIXME: it should be the other way round, Float = Float32, Double = Float64, // but the type checker loses sugar currently, and ends up displaying 'FloatXX' // in diagnostics. /// A 32-bit floating point type. public typealias Float32 = Float /// A 64-bit floating point type. public typealias Float64 = Double //===----------------------------------------------------------------------===// // Default types for unconstrained literals //===----------------------------------------------------------------------===// /// The default type for an otherwise-unconstrained integer literal. public typealias IntegerLiteralType = Int /// The default type for an otherwise-unconstrained floating point literal. public typealias FloatLiteralType = Double /// The default type for an otherwise-unconstrained Boolean literal. /// /// When you create a constant or variable using one of the Boolean literals /// `true` or `false`, the resulting type is determined by the /// `BooleanLiteralType` alias. For example: /// /// let isBool = true /// print("isBool is a '\(type(of: isBool))'") /// // Prints "isBool is a 'Bool'" /// /// The type aliased by `BooleanLiteralType` must conform to the /// `ExpressibleByBooleanLiteral` protocol. public typealias BooleanLiteralType = Bool /// The default type for an otherwise-unconstrained unicode scalar literal. public typealias UnicodeScalarType = String /// The default type for an otherwise-unconstrained Unicode extended /// grapheme cluster literal. public typealias ExtendedGraphemeClusterType = String /// The default type for an otherwise-unconstrained string literal. public typealias StringLiteralType = String //===----------------------------------------------------------------------===// // Default types for unconstrained number literals //===----------------------------------------------------------------------===// // Integer literals are limited to 2048 bits. // The intent is to have arbitrary-precision literals, but implementing that // requires more work. // // Rationale: 1024 bits are enough to represent the absolute value of min/max // IEEE Binary64, and we need 1 bit to represent the sign. Instead of using // 1025, we use the next round number -- 2048. public typealias _MaxBuiltinIntegerType = Builtin.Int2048 #if !os(Windows) && (arch(i386) || arch(x86_64)) public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80 #else public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64 #endif //===----------------------------------------------------------------------===// // Standard protocols //===----------------------------------------------------------------------===// #if _runtime(_ObjC) /// The protocol to which all classes implicitly conform. /// /// You use `AnyObject` when you need the flexibility of an untyped object or /// when you use bridged Objective-C methods and properties that return an /// untyped result. `AnyObject` can be used as the concrete type for an /// instance of any class, class type, or class-only protocol. For example: /// /// class FloatRef { /// let value: Float /// init(_ value: Float) { /// self.value = value /// } /// } /// /// let x = FloatRef(2.3) /// let y: AnyObject = x /// let z: AnyObject = FloatRef.self /// /// `AnyObject` can also be used as the concrete type for an instance of a type /// that bridges to an Objective-C class. Many value types in Swift bridge to /// Objective-C counterparts, like `String` and `Int`. /// /// let s: AnyObject = "This is a bridged string." as NSString /// print(s is NSString) /// // Prints "true" /// /// let v: AnyObject = 100 as NSNumber /// print(type(of: v)) /// // Prints "__NSCFNumber" /// /// The flexible behavior of the `AnyObject` protocol is similar to /// Objective-C's `id` type. For this reason, imported Objective-C types /// frequently use `AnyObject` as the type for properties, method parameters, /// and return values. /// /// Casting AnyObject Instances to a Known Type /// =========================================== /// /// Objects with a concrete type of `AnyObject` maintain a specific dynamic /// type and can be cast to that type using one of the type-cast operators /// (`as`, `as?`, or `as!`). /// /// This example uses the conditional downcast operator (`as?`) to /// conditionally cast the `s` constant declared above to an instance of /// Swift's `String` type. /// /// if let message = s as? String { /// print("Successful cast to String: \(message)") /// } /// // Prints "Successful cast to String: This is a bridged string." /// /// If you have prior knowledge that an `AnyObject` instance has a particular /// type, you can use the unconditional downcast operator (`as!`). Performing /// an invalid cast triggers a runtime error. /// /// let message = s as! String /// print("Successful cast to String: \(message)") /// // Prints "Successful cast to String: This is a bridged string." /// /// let badCase = v as! String /// // Runtime error /// /// Casting is always safe in the context of a `switch` statement. /// /// let mixedArray: [AnyObject] = [s, v] /// for object in mixedArray { /// switch object { /// case let x as String: /// print("'\(x)' is a String") /// default: /// print("'\(object)' is not a String") /// } /// } /// // Prints "'This is a bridged string.' is a String" /// // Prints "'100' is not a String" /// /// Accessing Objective-C Methods and Properties /// ============================================ /// /// When you use `AnyObject` as a concrete type, you have at your disposal /// every `@objc` method and property---that is, methods and properties /// imported from Objective-C or marked with the `@objc` attribute. Because /// Swift can't guarantee at compile time that these methods and properties /// are actually available on an `AnyObject` instance's underlying type, these /// `@objc` symbols are available as implicitly unwrapped optional methods and /// properties, respectively. /// /// This example defines an `IntegerRef` type with an `@objc` method named /// `getIntegerValue()`. /// /// class IntegerRef { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// /// @objc func getIntegerValue() -> Int { /// return value /// } /// } /// /// func getObject() -> AnyObject { /// return IntegerRef(100) /// } /// /// let obj: AnyObject = getObject() /// /// In the example, `obj` has a static type of `AnyObject` and a dynamic type /// of `IntegerRef`. You can use optional chaining to call the `@objc` method /// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of /// `obj`, you can call `getIntegerValue()` directly. /// /// let possibleValue = obj.getIntegerValue?() /// print(possibleValue) /// // Prints "Optional(100)" /// /// let certainValue = obj.getIntegerValue() /// print(certainValue) /// // Prints "100" /// /// If the dynamic type of `obj` doesn't implement a `getIntegerValue()` /// method, the system returns a runtime error when you initialize /// `certainValue`. /// /// Alternatively, if you need to test whether `obj.getIntegerValue()` exists, /// use optional binding before calling the method. /// /// if let f = obj.getIntegerValue { /// print("The value of 'obj' is \(f())") /// } else { /// print("'obj' does not have a 'getIntegerValue()' method") /// } /// // Prints "The value of 'obj' is 100" /// /// - SeeAlso: `AnyClass` @objc public protocol AnyObject : class {} #else /// The protocol to which all classes implicitly conform. /// /// - SeeAlso: `AnyClass` public protocol AnyObject : class {} #endif // Implementation note: the `AnyObject` protocol *must* not have any method or // property requirements. // FIXME: AnyObject should have an alternate version for non-objc without // the @objc attribute, but AnyObject needs to be not be an address-only // type to be able to be the target of castToNativeObject and an empty // non-objc protocol appears not to be. There needs to be another way to make // this the right kind of object. /// The protocol to which all class types implicitly conform. /// /// You can use the `AnyClass` protocol as the concrete type for an instance of /// any class. When you do, all known `@objc` class methods and properties are /// available as implicitly unwrapped optional methods and properties, /// respectively. For example: /// /// class IntegerRef { /// @objc class func getDefaultValue() -> Int { /// return 42 /// } /// } /// /// func getDefaultValue(_ c: AnyClass) -> Int? { /// return c.getDefaultValue?() /// } /// /// The `getDefaultValue(_:)` function uses optional chaining to safely call /// the implicitly unwrapped class method on `c`. Calling the function with /// different class types shows how the `getDefaultValue()` class method is /// only conditionally available. /// /// print(getDefaultValue(IntegerRef.self)) /// // Prints "Optional(42)" /// /// print(getDefaultValue(NSString.self)) /// // Prints "nil" /// /// - SeeAlso: `AnyObject` public typealias AnyClass = AnyObject.Type /// A type that supports standard bitwise arithmetic operators. /// /// Types that conform to the `BitwiseOperations` protocol implement operators /// for bitwise arithmetic. The integer types in the standard library all /// conform to `BitwiseOperations` by default. When you use bitwise operators /// with an integer, you perform operations on the raw data bits that store /// the integer's value. /// /// In the following examples, the binary representation of any values are /// shown in a comment to the right, like this: /// /// let x: UInt8 = 5 // 0b00000101 /// /// Here are the required operators for the `BitwiseOperations` protocol: /// /// - The bitwise OR operator (`|`) returns a value that has each bit set to /// `1` where *one or both* of its arguments had that bit set to `1`. This /// is equivalent to the union of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x | y // 0b00001111 /// /// Performing a bitwise OR operation with a value and `allZeros` always /// returns the same value. /// /// print(x | .allZeros) // 0b00000101 /// // Prints "5" /// /// - The bitwise AND operator (`&`) returns a value that has each bit set to /// `1` where *both* of its arguments had that bit set to `1`. This is /// equivalent to the intersection of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x & y // 0b00000100 /// /// Performing a bitwise AND operation with a value and `allZeros` always /// returns `allZeros`. /// /// print(x & .allZeros) // 0b00000000 /// // Prints "0" /// /// - The bitwise XOR operator (`^`), or exclusive OR operator, returns a value /// that has each bit set to `1` where *one or the other but not both* of /// its operators has that bit set to `1`. This is equivalent to the /// symmetric difference of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x ^ y // 0b00001011 /// /// Performing a bitwise XOR operation with a value and `allZeros` always /// returns the same value. /// /// print(x ^ .allZeros) // 0b00000101 /// // Prints "5" /// /// - The bitwise NOT operator (`~`) is a prefix operator that returns a value /// where all the bits of its argument are flipped: Bits that are `1` in the /// argument are `0` in the result, and bits that are `0` in the argument /// are `1` in the result. This is equivalent to the inverse of a set. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let notX = ~x // 0b11111010 /// /// Performing a bitwise NOT operation on `allZeros` returns a value with /// every bit set to `1`. /// /// let allOnes = ~UInt8.allZeros // 0b11111111 /// /// The `OptionSet` protocol uses a raw value that conforms to /// `BitwiseOperations` to provide mathematical set operations like /// `union(_:)`, `intersection(_:)` and `contains(_:)` with O(1) performance. /// /// Conforming to the BitwiseOperations Protocol /// ============================================ /// /// To make your custom type conform to `BitwiseOperations`, add a static /// `allZeros` property and declare the four required operator functions. Any /// type that conforms to `BitwiseOperations`, where `x` is an instance of the /// conforming type, must satisfy the following conditions: /// /// - `x | Self.allZeros == x` /// - `x ^ Self.allZeros == x` /// - `x & Self.allZeros == .allZeros` /// - `x & ~Self.allZeros == x` /// - `~x == x ^ ~Self.allZeros` /// /// - SeeAlso: `OptionSet` public protocol BitwiseOperations { /// Returns the intersection of bits set in the two arguments. /// /// The bitwise AND operator (`&`) returns a value that has each bit set to /// `1` where *both* of its arguments had that bit set to `1`. This is /// equivalent to the intersection of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x & y // 0b00000100 /// /// Performing a bitwise AND operation with a value and `allZeros` always /// returns `allZeros`. /// /// print(x & .allZeros) // 0b00000000 /// // Prints "0" /// /// - Complexity: O(1). static func & (lhs: Self, rhs: Self) -> Self /// Returns the union of bits set in the two arguments. /// /// The bitwise OR operator (`|`) returns a value that has each bit set to /// `1` where *one or both* of its arguments had that bit set to `1`. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x | y // 0b00001111 /// /// Performing a bitwise OR operation with a value and `allZeros` always /// returns the same value. /// /// print(x | .allZeros) // 0b00000101 /// // Prints "5" /// /// - Complexity: O(1). static func | (lhs: Self, rhs: Self) -> Self /// Returns the bits that are set in exactly one of the two arguments. /// /// The bitwise XOR operator (`^`), or exclusive OR operator, returns a value /// that has each bit set to `1` where *one or the other but not both* of /// its operators has that bit set to `1`. This is equivalent to the /// symmetric difference of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x ^ y // 0b00001011 /// /// Performing a bitwise XOR with a value and `allZeros` always returns the /// same value: /// /// print(x ^ .allZeros) // 0b00000101 /// // Prints "5" /// /// - Complexity: O(1). static func ^ (lhs: Self, rhs: Self) -> Self /// Returns the inverse of the bits set in the argument. /// /// The bitwise NOT operator (`~`) is a prefix operator that returns a value /// in which all the bits of its argument are flipped: Bits that are `1` in the /// argument are `0` in the result, and bits that are `0` in the argument /// are `1` in the result. This is equivalent to the inverse of a set. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let notX = ~x // 0b11111010 /// /// Performing a bitwise NOT operation on `allZeros` returns a value with /// every bit set to `1`. /// /// let allOnes = ~UInt8.allZeros // 0b11111111 /// /// - Complexity: O(1). static prefix func ~ (x: Self) -> Self /// The empty bitset. /// /// The `allZeros` static property is the [identity element][] for bitwise OR /// and XOR operations and the [fixed point][] for bitwise AND operations. /// For example: /// /// let x: UInt8 = 5 // 0b00000101 /// /// // Identity /// x | .allZeros // 0b00000101 /// x ^ .allZeros // 0b00000101 /// /// // Fixed point /// x & .allZeros // 0b00000000 /// /// [identity element]:http://en.wikipedia.org/wiki/Identity_element /// [fixed point]:http://en.wikipedia.org/wiki/Fixed_point_(mathematics) static var allZeros: Self { get } } /// Calculates the union of bits sets in the two arguments and stores the result /// in the first argument. /// /// - Parameters: /// - lhs: A value to update with the union of bits set in the two arguments. /// - rhs: Another value. public func |= <T : BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs | rhs } /// Calculates the intersections of bits sets in the two arguments and stores /// the result in the first argument. /// /// - Parameters: /// - lhs: A value to update with the intersections of bits set in the two /// arguments. /// - rhs: Another value. public func &= <T : BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs & rhs } /// Calculates the bits that are set in exactly one of the two arguments and /// stores the result in the first argument. /// /// - Parameters: /// - lhs: A value to update with the bits that are set in exactly one of the /// two arguments. /// - rhs: Another value. public func ^= <T : BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs ^ rhs } //===----------------------------------------------------------------------===// // Standard pattern matching forms //===----------------------------------------------------------------------===// /// Returns a Boolean value indicating whether two arguments match by value /// equality. /// /// The pattern-matching operator (`~=`) is used internally in `case` /// statements for pattern matching. When you match against an `Equatable` /// value in a `case` statement, this operator is called behind the scenes. /// /// let weekday = 3 /// let lunch: String /// switch weekday { /// case 3: /// lunch = "Taco Tuesday!" /// default: /// lunch = "Pizza again." /// } /// // lunch == "Taco Tuesday!" /// /// In this example, the `case 3` expression uses this pattern-matching /// operator to test whether `weekday` is equal to the value `3`. /// /// - Note: In most cases, you should use the equal-to operator (`==`) to test /// whether two instances are equal. The pattern-matching operator is /// primarily intended to enable `case` statement pattern matching. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @_transparent public func ~= <T : Equatable>(a: T, b: T) -> Bool { return a == b } //===----------------------------------------------------------------------===// // Standard precedence groups //===----------------------------------------------------------------------===// precedencegroup FunctionArrowPrecedence { associativity: right } precedencegroup AssignmentPrecedence { assignment: true associativity: right higherThan: FunctionArrowPrecedence } precedencegroup TernaryPrecedence { associativity: right higherThan: AssignmentPrecedence } precedencegroup DefaultPrecedence { higherThan: TernaryPrecedence } precedencegroup LogicalDisjunctionPrecedence { associativity: left higherThan: TernaryPrecedence } precedencegroup LogicalConjunctionPrecedence { associativity: left higherThan: LogicalDisjunctionPrecedence } precedencegroup ComparisonPrecedence { higherThan: LogicalConjunctionPrecedence } precedencegroup NilCoalescingPrecedence { associativity: right higherThan: ComparisonPrecedence } precedencegroup CastingPrecedence { higherThan: NilCoalescingPrecedence } precedencegroup RangeFormationPrecedence { higherThan: CastingPrecedence } precedencegroup AdditionPrecedence { associativity: left higherThan: RangeFormationPrecedence } precedencegroup MultiplicationPrecedence { associativity: left higherThan: AdditionPrecedence } precedencegroup BitwiseShiftPrecedence { higherThan: MultiplicationPrecedence } //===----------------------------------------------------------------------===// // Standard operators //===----------------------------------------------------------------------===// // Standard postfix operators. postfix operator ++ postfix operator -- // Optional<T> unwrapping operator is built into the compiler as a part of // postfix expression grammar. // // postfix operator ! // Standard prefix operators. prefix operator ++ prefix operator -- prefix operator ! prefix operator ~ prefix operator + prefix operator - // Standard infix operators. // "Exponentiative" infix operator << : BitwiseShiftPrecedence infix operator >> : BitwiseShiftPrecedence // "Multiplicative" infix operator * : MultiplicationPrecedence infix operator &* : MultiplicationPrecedence infix operator / : MultiplicationPrecedence infix operator % : MultiplicationPrecedence infix operator & : MultiplicationPrecedence // "Additive" infix operator + : AdditionPrecedence infix operator &+ : AdditionPrecedence infix operator - : AdditionPrecedence infix operator &- : AdditionPrecedence infix operator | : AdditionPrecedence infix operator ^ : AdditionPrecedence // FIXME: is this the right precedence level for "..." ? infix operator ... : RangeFormationPrecedence infix operator ..< : RangeFormationPrecedence // The cast operators 'as' and 'is' are hardcoded as if they had the // following attributes: // infix operator as : CastingPrecedence // "Coalescing" infix operator ?? : NilCoalescingPrecedence // "Comparative" infix operator < : ComparisonPrecedence infix operator <= : ComparisonPrecedence infix operator > : ComparisonPrecedence infix operator >= : ComparisonPrecedence infix operator == : ComparisonPrecedence infix operator != : ComparisonPrecedence infix operator === : ComparisonPrecedence infix operator !== : ComparisonPrecedence // FIXME: ~= will be built into the compiler. infix operator ~= : ComparisonPrecedence // "Conjunctive" infix operator && : LogicalConjunctionPrecedence // "Disjunctive" infix operator || : LogicalDisjunctionPrecedence // User-defined ternary operators are not supported. The ? : operator is // hardcoded as if it had the following attributes: // operator ternary ? : : TernaryPrecedence // User-defined assignment operators are not supported. The = operator is // hardcoded as if it had the following attributes: // infix operator = : AssignmentPrecedence // Compound infix operator *= : AssignmentPrecedence infix operator /= : AssignmentPrecedence infix operator %= : AssignmentPrecedence infix operator += : AssignmentPrecedence infix operator -= : AssignmentPrecedence infix operator <<= : AssignmentPrecedence infix operator >>= : AssignmentPrecedence infix operator &= : AssignmentPrecedence infix operator ^= : AssignmentPrecedence infix operator |= : AssignmentPrecedence // Workaround for <rdar://problem/14011860> SubTLF: Default // implementations in protocols. Library authors should ensure // that this operator never needs to be seen by end-users. See // test/Prototypes/GenericDispatch.swift for a fully documented // example of how this operator is used, and how its use can be hidden // from users. infix operator ~> @available(*, unavailable, renamed: "BitwiseOperations") public typealias BitwiseOperationsType = BitwiseOperations
apache-2.0
bf74f8d2798c2b1d7d29ec0e14d97604
35.426389
81
0.61715
4.517224
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/InstantPageStoredState.swift
1
3486
// // InstantPageStoredState.swift // Telegram // // Created by Mikhail Filimonov on 27/12/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa import InAppSettings import Foundation import SwiftSignalKit import Postbox import TelegramCore public final class InstantPageStoredDetailsState: Codable { public let index: Int32 public let expanded: Bool public let details: [InstantPageStoredDetailsState] public init(index: Int32, expanded: Bool, details: [InstantPageStoredDetailsState]) { self.index = index self.expanded = expanded self.details = details } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) self.index = try container.decode(Int32.self, forKey: "index") self.expanded = try container.decode(Bool.self, forKey: "expanded") self.details = try container.decode([InstantPageStoredDetailsState].self, forKey: "details") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(self.index, forKey: "index") try container.encode(self.expanded, forKey: "expanded") try container.encode(self.details, forKey: "details") } } public final class InstantPageStoredState: Codable { public let contentOffset: Double public let details: [InstantPageStoredDetailsState] public init(contentOffset: Double, details: [InstantPageStoredDetailsState]) { self.contentOffset = contentOffset self.details = details } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) self.contentOffset = try container.decode(Double.self, forKey: "offset") self.details = try container.decode([InstantPageStoredDetailsState].self, forKey: "details") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(self.contentOffset, forKey: "offset") try container.encode(self.details, forKey: "details") } } public func instantPageStoredState(postbox: Postbox, webPage: TelegramMediaWebpage) -> Signal<InstantPageStoredState?, NoError> { return postbox.transaction { transaction -> InstantPageStoredState? in let key = ValueBoxKey(length: 8) key.setInt64(0, value: webPage.webpageId.id) if let entry = transaction.retrieveItemCacheEntry(id: ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.instantPageStoredState, key: key))?.get(InstantPageStoredState.self) { return entry } else { return nil } } } public func updateInstantPageStoredStateInteractively(postbox: Postbox, webPage: TelegramMediaWebpage, state: InstantPageStoredState?) -> Signal<Void, NoError> { return postbox.transaction { transaction -> Void in let key = ValueBoxKey(length: 8) key.setInt64(0, value: webPage.webpageId.id) let id = ItemCacheEntryId(collectionId: ApplicationSpecificItemCacheCollectionId.instantPageStoredState, key: key) if let state = state, let entry = CodableEntry(state) { transaction.putItemCacheEntry(id: id, entry: entry) } else { transaction.removeItemCacheEntry(id: id) } } }
gpl-2.0
b7c95db7bc162d51199fe3bff88d5a8e
36.880435
204
0.704735
4.715832
false
false
false
false
StanZabroda/Hydra
Pods/HanekeSwift/Haneke/Fetch.swift
4
2114
// // Fetch.swift // Haneke // // Created by Hermes Pique on 9/28/14. // Copyright (c) 2014 Haneke. All rights reserved. // import Foundation enum FetchState<T> { case Pending // Using Wrapper as a workaround for error 'unimplemented IR generation feature non-fixed multi-payload enum layout' // See: http://swiftradar.tumblr.com/post/88314603360/swift-fails-to-compile-enum-with-two-data-cases // See: http://owensd.io/2014/08/06/fixed-enum-layout.html case Success(Wrapper<T>) case Failure(NSError?) } public class Fetch<T> { public typealias Succeeder = (T) -> () public typealias Failer = (NSError?) -> () private var onSuccess : Succeeder? private var onFailure : Failer? private var state : FetchState<T> = FetchState.Pending public init() {} public func onSuccess(onSuccess : Succeeder) -> Self { self.onSuccess = onSuccess switch self.state { case FetchState.Success(let wrapper): onSuccess(wrapper.value) default: break } return self } public func onFailure(onFailure : Failer) -> Self { self.onFailure = onFailure switch self.state { case FetchState.Failure(let error): onFailure(error) default: break } return self } func succeed(value : T) { self.state = FetchState.Success(Wrapper(value)) self.onSuccess?(value) } func fail(error : NSError? = nil) { self.state = FetchState.Failure(error) self.onFailure?(error) } var hasFailed : Bool { switch self.state { case FetchState.Failure(_): return true default: return false } } var hasSucceeded : Bool { switch self.state { case FetchState.Success(_): return true default: return false } } } public class Wrapper<T> { public let value: T public init(_ value: T) { self.value = value } }
mit
7d26a1dde897fbdc183957e82a17b33a
22.752809
120
0.575213
4.323108
false
false
false
false
SteveKueng/SplashBuddy
SplashBuddy/Software.swift
1
3579
// // Software.swift // SplashBuddy // // Created by ftiff on 02/08/16. // Copyright © 2016 François Levaux-Tiffreau. All rights reserved. // import Cocoa /** Object that will hold the definition of a software. The goal here is to: 1. Create a Software object from the plist (MacAdmin supplied Software) 2. Parse the log and either: - Modify the Software object (if it already exists) - Create a new Software object. */ class Software: NSObject { /** Status of the software. Default is .pending, other cases will be set while parsing the log */ @objc enum SoftwareStatus: Int { case installing = 0 case success = 1 case failed = 2 case pending = 3 } @objc dynamic var packageName: String @objc dynamic var packageVersion: String? @objc dynamic var status: SoftwareStatus @objc dynamic var icon: NSImage? @objc dynamic var displayName: String? @objc dynamic var desc: String? @objc dynamic var canContinue: Bool @objc dynamic var displayToUser: Bool /** Initializes a Software Object - note: Only packageName is required to parse, displayName, description and displayToUser will have to be set later to properly show it on the GUI. - parameter packageName: *packageName*-packageVersion.pkg - parameter version: Optional - parameter iconPath: Optional - parameter displayName: Name displayed to user - parameter description: Second line underneath name - parameter canContinue: if set to false, the Software will block the "Continue" button until installed - parameter displayToUser: set to True to display in GUI */ init(packageName: String, version: String? = nil, status: SoftwareStatus = .pending, iconPath: String? = nil, displayName: String? = nil, description: String? = nil, canContinue: Bool = true, displayToUser: Bool = false) { self.packageName = packageName self.packageVersion = version self.status = status self.canContinue = canContinue self.displayToUser = displayToUser self.displayName = displayName self.desc = description if let iconPath = iconPath { self.icon = NSImage(contentsOfFile: iconPath) } else { self.icon = NSImage(named: NSImage.Name.folder) } } convenience init?(from line: String) { var name: String? var version: String? var status: SoftwareStatus? for (regexStatus, regex) in initRegex() { status = regexStatus let matches = regex!.matches(in: line, options: [], range: NSMakeRange(0, line.characters.count)) if !matches.isEmpty { name = (line as NSString).substring(with: matches[0].range(at: 1)) version = (line as NSString).substring(with: matches[0].range(at: 2)) break } } if let packageName = name, let packageVersion = version, let packageStatus = status { self.init(packageName: packageName, version: packageVersion, status: packageStatus) } else { return nil } } } func == (lhs: Software, rhs: Software) -> Bool { return lhs.packageName == rhs.packageName && lhs.packageVersion == rhs.packageVersion && lhs.status == rhs.status }
apache-2.0
deab7d9ab2e8ed8dad97a7dfb578a2d1
27.616
152
0.60917
4.814266
false
false
false
false
ericwastaken/Xcode_Playgrounds
Playgrounds/Insertion Sort.playground/Contents.swift
1
2338
// Insrtion Sort Example // Given insertSort([3,2,7,4,5]) // Returns [2,3,4,5,7] // How: // Two piles - one sorted, one unsorted. Grab from unsorted and place in sorted in the right place by swapping as needed. import Foundation /** Swap to entries in the array! */ public func swapEntries(_ arrayToSwapWith: [Int], swap: Int, with: Int) -> [Int] { // TODO: Add some boundary protections (ensure array indexes within range) var mutableArray = arrayToSwapWith mutableArray[swap] = arrayToSwapWith[with] mutableArray[with] = arrayToSwapWith[swap] return mutableArray } public func insertSort(_ unsortedArray:[Int]) -> [Int] { // First, check if we have work to do if unsortedArray.count <= 1 { // not much to do, so just return it return unsortedArray } // ASSERT: We have 2 or more entries in unsortedArray! // Make a copy so we can modify it (we're going to popLast) var unsortedMutable = unsortedArray // Make an array to hold our sort - and we might as well start it with the "top" item in unsorted var sortedArray = [unsortedMutable.popLast()!] // ASSERT: sortedArray has 1 item and that same item is no longer in unsortedMutable // Now, let's begin our magic. For each item left in unsorted, let's do work while unsortedMutable.count > 0 { // Fetch the top item from unsorted (and also removes it) let sortCandidate = unsortedMutable.popLast()! // Add it to the top of the sorted sortedArray.append(sortCandidate) // Now, check our order in sorted and decide if we need to swap (why count-2 : because count-1 is the item we just added. No need to check it against what? for idx in (0...sortedArray.count-2).reversed() { // check to see if the current item is less than the one just after it if sortedArray[idx] > sortedArray[idx+1] { // yep, we need to swap sortedArray = swapEntries(sortedArray, swap: idx, with: idx+1) } else { // nope... so we don't need to keep going with the FOR LOOP break } } } return sortedArray } let unsorted = [3,2,7,4,5,5] let testSwap = swapEntries(unsorted, swap:0, with: 1) let sorted = insertSort(unsorted)
unlicense
a5be93629c1d7f960aadd68a339e7d3d
36.111111
163
0.641574
4.059028
false
false
false
false
steelwheels/KiwiScript
KiwiLibrary/Source/Terminal/KLCurses.swift
1
4309
/** * @file KLCurses.swift * @brief Define KLCurses class * @par Copyright * Copyright (C) 2020 Steel Wheels Project */ import KiwiEngine import CoconutData import JavaScriptCore import Foundation @objc public protocol KLCursesProtocol: JSExport { var minColor: JSValue { get } var maxColor: JSValue { get } var black: JSValue { get } var red: JSValue { get } var green: JSValue { get } var yellow: JSValue { get } var blue: JSValue { get } var magenta: JSValue { get } var cyan: JSValue { get } var white: JSValue { get } func begin() func end() var width: JSValue { get } var height: JSValue { get } var foregroundColor: JSValue { get set } var backgroundColor: JSValue { get set } func moveTo(_ x: JSValue, _ y: JSValue) -> JSValue func inkey() -> JSValue func put(_ str: JSValue) func fill(_ x: JSValue, _ y: JSValue, _ width: JSValue, _ height: JSValue, _ c: JSValue) } @objc public class KLCurses: NSObject, KLCursesProtocol { private var mCurses: CNCurses private var mContext: KEContext public init(console cons: CNFileConsole, terminalInfo terminfo: CNTerminalInfo, context ctxt: KEContext){ mCurses = CNCurses(console: cons, terminalInfo: terminfo) mContext = ctxt } public var minColor: JSValue { get { return JSValue(int32: CNCurses.Color.black.rawValue, in: mContext) }} public var maxColor: JSValue { get { return JSValue(int32: CNCurses.Color.white.rawValue, in: mContext) }} public var black: JSValue { get { return JSValue(int32: CNCurses.Color.black.rawValue, in: mContext)} } public var red: JSValue { get { return JSValue(int32: CNCurses.Color.red.rawValue, in: mContext)}} public var green: JSValue { get { return JSValue(int32: CNCurses.Color.green.rawValue, in: mContext)}} public var yellow: JSValue { get { return JSValue(int32: CNCurses.Color.yellow.rawValue, in: mContext)}} public var blue: JSValue { get { return JSValue(int32: CNCurses.Color.blue.rawValue, in: mContext)}} public var magenta: JSValue { get { return JSValue(int32: CNCurses.Color.magenta.rawValue, in: mContext)}} public var cyan: JSValue { get { return JSValue(int32: CNCurses.Color.cyan.rawValue, in: mContext)}} public var white: JSValue { get { return JSValue(int32: CNCurses.Color.white.rawValue, in: mContext)}} public func begin() { mCurses.begin() } public func end() { mCurses.end() } public var width: JSValue { get { return JSValue(int32: Int32(mCurses.width), in: mContext) } } public var height: JSValue { get { return JSValue(int32: Int32(mCurses.height), in: mContext) } } public var foregroundColor: JSValue { get { let colid = mCurses.foregroundColor.escapeCode() return JSValue(int32: colid, in: mContext) } set(newcol) { if newcol.isNumber { if let col = CNColor.color(withEscapeCode: newcol.toInt32()) { mCurses.foregroundColor = col } } } } public var backgroundColor: JSValue { get { let colid = mCurses.backgroundColor.escapeCode() return JSValue(int32: colid, in: mContext) } set(newcol) { if newcol.isNumber { if let col = CNColor.color(withEscapeCode: newcol.toInt32()) { mCurses.backgroundColor = col } } } } public func moveTo(_ x: JSValue, _ y: JSValue) -> JSValue { let result: Bool if x.isNumber && y.isNumber { mCurses.moveTo(x: Int(x.toInt32()), y: Int(y.toInt32())) result = true } else { result = false } return JSValue(bool: result, in: mContext) } public func inkey() -> JSValue { if let c = mCurses.inkey() { return JSValue(object: String(c), in: mContext) } else { return JSValue(nullIn: mContext) } } public func put(_ str: JSValue) { if let s = str.toString() { mCurses.put(string: s) } else { CNLog(logLevel: .error, message: "Failed to put string: \(str)", atFunction: #function, inFile: #file) } } public func fill(_ x: JSValue, _ y: JSValue, _ width: JSValue, _ height: JSValue, _ c: JSValue) { if x.isNumber && y.isNumber && width.isNumber && height.isNumber && c.isString { if let str = c.toString() { if let cv = str.first { let xv = Int(x.toInt32()) let yv = Int(y.toInt32()) let wv = Int(width.toInt32()) let hv = Int(height.toInt32()) mCurses.fill(x: xv, y: yv, width: wv, height: hv, char: cv) } } } } }
lgpl-2.1
d10eb1ffc6b12dbaef83b08709ffeda4
27.726667
107
0.676723
3.194218
false
false
false
false
eytanbiala/MyMovies
MyMovies/ImageLoader.swift
1
3175
// // ImageLoader.swift // MyMovies // // Created by Eytan Biala on 7/10/16. // Copyright © 2016 Udacity. All rights reserved. // import Foundation typealias ImageLoadCompletion = (operation: ImageLoadOperation, imageData: NSData?, error: NSError?) -> (Void) public class ImageLoadOperation : NSOperation { public var identifier: String! public var imageURL : NSURL! var imageLoadCompletion: ImageLoadCompletion! { didSet { if self.imageLoadCompletion == nil { finished = true executing = false } } } init(id: String, url: NSURL, completion: ImageLoadCompletion) { super.init() self.name = url.absoluteString identifier = id imageURL = url imageLoadCompletion = completion } override public var asynchronous: Bool { return true } private var _executing: Bool = false override public var executing: Bool { get { return _executing } set { if _executing != newValue { willChangeValueForKey("isExecuting") _executing = newValue didChangeValueForKey("isExecuting") } } } private var _finished: Bool = false; override public var finished: Bool { get { return _finished } set { if _finished != newValue { willChangeValueForKey("isFinished") _finished = newValue didChangeValueForKey("isFinished") } } } override public func main() { let request = NSURLRequest(URL: imageURL) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in guard error == nil && data != nil else { print("Error: \(error)") dispatch_async(dispatch_get_main_queue(), { self.imageLoadCompletion?(operation: self, imageData: nil, error: error) self.imageLoadCompletion = nil }) return } dispatch_async(dispatch_get_main_queue(), { self.imageLoadCompletion?(operation: self, imageData: data, error: nil) self.imageLoadCompletion = nil }) } if cancelled { self.imageLoadCompletion = nil return } task.resume() } } class ImageLoader { private lazy var queue: NSOperationQueue = { let queue = NSOperationQueue() queue.maxConcurrentOperationCount = 10 queue.name = "ImageLoader" queue.qualityOfService = .Utility return queue }() static let sharedInstance = ImageLoader() func loadImage(objectId: String, imageURL: String, completion: ImageLoadCompletion) { if let url = NSURL(string: imageURL) { let operation = ImageLoadOperation(id: objectId, url: url, completion: completion) queue.addOperation(operation) } else { abort() } } }
mit
d477b013ac5473558340b55e09a4b320
26.608696
110
0.562067
5.361486
false
false
false
false
elberdev/unit-4-assignments
HWFrom1-24(Recursion).playground/Contents.swift
1
789
/* Homework link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit#heading=h.za36ai6n5fth */ import Foundation //Question 1 func fib(n: Int) -> Int { var a = 1 var b = 1 for _ in 0..<n { let t = a a = b b = t + b } return b } //Question 2 var stepNum = 0 func tryStep() -> Int { let stepCount = Int(arc4random_uniform(3)) - 1 stepNum += stepCount; switch(stepCount) { case -1: print("Ouch \(stepNum)") case 1: print("Yay \(stepNum)") default: print("Beep \(stepNum)") } return stepCount } func stepUp() { switch tryStep() { case 1: return case -1: stepUp() stepUp() default: stepUp() } } //Question 3
mit
5f58b28e5e62c6415f2a23b89d143ddf
14.78
122
0.544994
3.022989
false
false
false
false
JasonChen2015/Paradise-Lost
Paradise Lost/Classes/DataStructures/File.swift
3
2488
// // File.swift // Paradise Lost // // Created by jason on 30/6/2016. // Copyright © 2016 Jason Chen. All rights reserved. // import Foundation /** e.g. "/var/mobile/Containers/Data/Application/DB4F8A38-59DA-4675-B37B-4AC98E0512E2/Documents/editor/untitled.txt" name = "untitled.txt" path = "/var/mobile/Containers/Data/Application/DB4F8A38-59DA-4675-B37B-4AC98E0512E2/Documents/editor" extensions = "txt" */ struct File { var name: String = "" { didSet { getExtensionsFromName() } } var path: String = "" var extensions: String = "" var size: Int = 0 var createDate: Date = Date(timeIntervalSince1970: 0) var modifyDate: Date = Date(timeIntervalSince1970: 0) // suitable for nil init() { } init(path: String, name: String) { self.path = path self.name = name } init(absolutePathUrl: URL) { self.name = absolutePathUrl.lastPathComponent let path = absolutePathUrl.deletingLastPathComponent().absoluteString let range = path.index(path.startIndex, offsetBy: 7)... // file:// self.path = "\(path[range])" } init(absolutePath: String) { let url = URL(fileURLWithPath: absolutePath) self.name = url.lastPathComponent let n = absolutePath.count - name.count - 1 // '/' self.path = absolutePath.substring(to: absolutePath.index(absolutePath.startIndex, offsetBy: n)) } mutating func getExtensionsFromName() { if name.first != "." { // handle invisible file under unix let temp = name.components(separatedBy: ".") self.extensions = (temp.count == 2) ? temp[1] : "" } } mutating func changeName(_ newName: String) { self.name = newName } mutating func setAttributes() { if let attr = FileExplorerManager().getAttributesOfFileOrFolder(getFullPath()) { if let tsize = attr[FileAttributeKey.size] { size = tsize as! Int } if let tcreateDate = attr[FileAttributeKey.creationDate] { createDate = tcreateDate as! Date } if let tmodifyDate = attr[FileAttributeKey.modificationDate] { modifyDate = tmodifyDate as! Date } } } func getFullPath() -> String { if name == "" { return "" } return path + "/" + name } }
mit
6c6ec2c8e8117a598630e745dd5c5b2f
28.607143
117
0.58464
4.131229
false
false
false
false
box/box-ios-sdk
Sources/Core/AnyCodable.swift
1
3658
// // AnyCodable.swift // BoxSDK // // Created by Daniel Cech on 18/06/2019. // Copyright © 2019 Box. All rights reserved. // // Based on: https://stackoverflow.com/questions/48297263/how-to-use-any-in-codable-type import Foundation struct AnyCodable: Decodable { var value: Any struct CodingKeys: CodingKey { var stringValue: String var intValue: Int? init?(intValue: Int) { stringValue = "\(intValue)" self.intValue = intValue } init?(stringValue: String) { self.stringValue = stringValue } } init(value: Any) { self.value = value } init(from decoder: Decoder) throws { if let container = try? decoder.container(keyedBy: CodingKeys.self) { var result = [String: Any]() try container.allKeys.forEach { key throws in result[key.stringValue] = try container.decode(AnyCodable.self, forKey: key).value } value = result } else if var container = try? decoder.unkeyedContainer() { var result = [Any]() while !container.isAtEnd { result.append(try container.decode(AnyCodable.self).value) } value = result } else if let container = try? decoder.singleValueContainer() { if let intVal = try? container.decode(Int.self) { value = intVal } else if let doubleVal = try? container.decode(Double.self) { value = doubleVal } else if let boolVal = try? container.decode(Bool.self) { value = boolVal } else if let stringVal = try? container.decode(String.self) { value = stringVal } else { throw DecodingError.dataCorruptedError(in: container, debugDescription: "the container contains nothing serialisable") } } else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not serialise")) } } } extension AnyCodable: Encodable { func encode(to encoder: Encoder) throws { if let array = value as? [Any] { var container = encoder.unkeyedContainer() for value in array { let decodable = AnyCodable(value: value) try container.encode(decodable) } } else if let dictionary = value as? [String: Any] { var container = encoder.container(keyedBy: CodingKeys.self) for (key, value) in dictionary { // swiftlint:disable:next force_unwrapping let codingKey = CodingKeys(stringValue: key)! let decodable = AnyCodable(value: value) try container.encode(decodable, forKey: codingKey) } } else { var container = encoder.singleValueContainer() if let intVal = value as? Int { try container.encode(intVal) } else if let doubleVal = value as? Double { try container.encode(doubleVal) } else if let boolVal = value as? Bool { try container.encode(boolVal) } else if let stringVal = value as? String { try container.encode(stringVal) } else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [], debugDescription: "The value is not encodable")) } } } }
apache-2.0
970e6fc21e072b919f9751cb5bbdb82e
33.5
142
0.556467
4.928571
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Test/TestRouterEnvironment.swift
2
2694
// // TestRouterEnvironment.swift // edX // // Created by Akiva Leffert on 12/1/15. // Copyright © 2015 edX. All rights reserved. // import Foundation @testable import edX class TestRouterEnvironment : RouterEnvironment { let mockNetworkManager : MockNetworkManager let mockStorage : OEXMockCredentialStorage let eventTracker : MockAnalyticsTracker let mockCourseDataManager: MockCourseDataManager let mockReachability : MockReachability let mockEnrollmentManager: MockEnrollmentManager init( config : OEXConfig = OEXConfig(dictionary: [:]), interface: OEXInterface? = nil) { mockStorage = OEXMockCredentialStorage() let session = OEXSession(credentialStore: mockStorage) let mockNetworkManager = MockNetworkManager(authorizationHeaderProvider: session, baseURL: NSURL(string:"http://example.com")!) self.mockNetworkManager = mockNetworkManager eventTracker = MockAnalyticsTracker() mockReachability = MockReachability() let analytics = OEXAnalytics() let mockEnrollmentManager = MockEnrollmentManager(interface: interface, networkManager: mockNetworkManager, config: config) self.mockEnrollmentManager = mockEnrollmentManager let mockCourseDataManager = MockCourseDataManager( analytics: analytics, enrollmentManager: mockEnrollmentManager, interface: interface, networkManager: mockNetworkManager, session: session ) self.mockCourseDataManager = mockCourseDataManager let dataManager = DataManager( courseDataManager: mockCourseDataManager, enrollmentManager: mockEnrollmentManager, interface: interface, pushSettings: OEXPushSettingsManager(), userProfileManager:UserProfileManager(networkManager: mockNetworkManager, session: session), userPreferenceManager: UserPreferenceManager(networkManager: mockNetworkManager) ) super.init(analytics: analytics, config: config, dataManager: dataManager, interface: interface, networkManager: mockNetworkManager, reachability: mockReachability, session: session, styles: OEXStyles()) self.analytics.addTracker(eventTracker) } func logInTestUser() -> TestRouterEnvironment { mockStorage.storedAccessToken = OEXAccessToken.fakeToken() mockStorage.storedUserDetails = OEXUserDetails.freshUser() self.session.loadTokenFromStore() return self } }
apache-2.0
fe85ccc927ac9e85bad7d14c6f1c913b
34.92
135
0.681025
6.306792
false
true
false
false
MitchellPhillips22/TIY-Assignments
Day 8/Calculator/Calculator/Button.swift
1
678
// // Button.swift // Calculator // // Created by Mitchell Phillips on 2/10/16. // Copyright © 2016 Mitchell Phillips. All rights reserved. // import UIKit import QuartzCore @IBDesignable class BorderButton: UIButton { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.CGColor } } }
cc0-1.0
cdd0b4eb67bae08ce6ac0eaac7e12bdc
20.1875
60
0.601182
4.835714
false
false
false
false